Mercurial > repos > fubar > jbrowse2
comparison x/static/js/5099.14f82444.chunk.js.map @ 125:49f3d3878413 draft
planemo upload for repository https://github.com/galaxyproject/tools-iuc/tree/master/tools/jbrowse2 commit 5ea1f9c1eef1de76232e69aa6d34cda77d90d566
author | fubar |
---|---|
date | Sat, 05 Oct 2024 23:58:05 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
124:137e08517410 | 125:49f3d3878413 |
---|---|
1 {"version":3,"file":"static/js/5099.14f82444.chunk.js","mappings":";sJAAA,MAsDA,EArDkC,EAqDlC,EApDsB,EAoDtB,EAnD6B,EAmD7B,EAlDoB,EAkDpB,EAzCe,EAyCf,EAvCoB,EAuCpB,EArCc,EAqCd,EAnCe,EAmCf,EAjCgB,GAiChB,EA/BiB,GA+BjB,EA7Bc,GA6Bd,EA3Bc,IA2Bd,EAzBkB,IAyBlB,EAvBe,IAuBf,EArBY,KAqBZ,EAnBsB,KC4EhBA,EAAc,CAClBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAiFL,SAASC,EACPC,GAEA,MAAMC,EAAS,CAAC,EAChB,IAAK,MAAOC,EAAMC,KAASH,EACzBC,EAAE,KAAKE,KAAWC,MAAqBA,EAAQF,GAC/CD,EAAE,MAAME,KAAWC,GAAkBA,EAAQF,EAG/C,OAAOD,CACT,CAEO,MAAMI,EAAkBN,EA1DP,CACtB,CAAC,EAAK,UACN,CAAC,EAAK,kBACN,CAAC,EAAK,mBACN,CAAC,EAAK,gBACN,CAAC,GAAM,uBAEP,CAAC,GAAM,2BAEP,CAAC,GAAM,SAEP,CAAC,IAAM,SAEP,CAAC,IAAO,aAER,CAAC,IAAO,YAER,CAAC,KAAO,aAER,CAAC,KAAO,mBAwCGO,EAAmBP,EArCP,CACvB,CAAC,EAAK,2BACN,CAAC,EAAK,YACN,CAAC,EAAK,sBACN,CAAC,EAA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AAY,WAAY,WACpF,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UAAY,WACpF,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UAAY,WACpF,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UAAY,WACpF,WAAY,WAAY,WAAY,SAAY,WAAY,WAAY,WAAY,SACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,WACpF,WAAY,WAAY,WAAY,SAAY,WAAY,WAAY,WAAY,UACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,UACpF,WAAY,WAAY,WAAY,UAAY,WAAY,WAAY,WAAY,WAE9D,oBAAfh1B,aACPg1B,EAAQ,IAAIh1B,WAAWg1B,mBCjC3B,MACA,EADqB,CAAC78B,EAAO83B,IAAa,KAAOh8B,KAAKkE,EAAO83B,GCD7D,ECDe,SAAmBpP,EAAOoU,GACrC,MAAMv/B,EAAS,CAACyC,EAAOw1B,IAAasH,EAAW,EAAa98B,GAAQw1B,KAAc,EAIlF,OAHAj4B,EAAOw/B,OAAS,CAAC/8B,EAAOw1B,IAAasH,EAAW,EAAa98B,GAAQw1B,GACrEj4B,EAAOwc,SAAWxc,EAClBA,EAAOmrB,MDHc,SCIdnrB,CACX,CDLA,CAAyB,GFoCX,CAACikB,EAASgU,KAEpB,IAAI/X,EAAmB,IAAb+X,EAAiB,GAAMA,EACjC,IAAK,IAAIriB,EAAQ,EAAGA,EAAQqO,EAAQtoB,OAAQia,IACxCsK,EAAMof,EAA+B,KAAxBpf,EAAM+D,EAAQrO,KAAmBsK,IAAQ,EAE1D,OAAOA,CAAQ","sources":["../../../node_modules/@gmod/cram/src/cramFile/constants.ts","../../../node_modules/@gmod/cram/src/cramFile/record.ts","../../../node_modules/@gmod/cram/src/errors.ts","../../../node_modules/@gmod/cram/src/unzip-pako.ts","../../../node_modules/@gmod/cram/src/rans/constants.ts","../../../node_modules/@gmod/cram/src/rans/decoding.ts","../../../node_modules/@gmod/cram/src/rans/frequencies.ts","../../../node_modules/@gmod/cram/src/rans/index.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/getBits.ts","../../../node_modules/@gmod/cram/src/cramFile/util.ts","../../../node_modules/@gmod/cram/src/cramFile/sectionParsers.ts","../../../node_modules/@gmod/cram/src/cramFile/slice/decodeRecord.ts","../../../node_modules/@gmod/cram/src/cramFile/slice/index.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/_base.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/byteArrayLength.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/index.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/external.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/huffman.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/byteArrayStop.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/beta.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/subexp.ts","../../../node_modules/@gmod/cram/src/cramFile/codecs/gamma.ts","../../../node_modules/@gmod/cram/src/cramFile/container/compressionScheme.ts","../../../node_modules/@gmod/cram/src/cramFile/container/index.ts","../../../node_modules/@gmod/cram/src/io/index.ts","../../../node_modules/@gmod/cram/src/sam.ts","../../../node_modules/@gmod/cram/src/cramFile/file.ts","../../../node_modules/@gmod/cram/src/rans/d04.ts","../../../node_modules/@gmod/cram/src/rans/d14.ts","../../../node_modules/@gmod/cram/src/craiIndex.ts","../../../node_modules/@gmod/cram/src/indexedCramFile.ts","../../../node_modules/@jkbonfield/htscodecs/arith_gen.js","../../../node_modules/@jkbonfield/htscodecs/arith_sh.js","../../../node_modules/@jkbonfield/htscodecs/byte_model.js","../../../node_modules/@jkbonfield/htscodecs/fqzcomp.js","../../../node_modules/@jkbonfield/htscodecs/index.js","../../../node_modules/@jkbonfield/htscodecs/iostream.js","../../../node_modules/@jkbonfield/htscodecs/rans.js","../../../node_modules/@jkbonfield/htscodecs/rans4x16.js","../../../node_modules/@jkbonfield/htscodecs/tok3.js","../../../node_modules/bzip2/bzip2.js","../../../node_modules/charenc/charenc.js","../../../node_modules/crypt/crypt.js","../../../node_modules/is-buffer/index.js","../../../node_modules/md5/md5.js","../../../node_modules/xz-decompress/dist/package/xz-decompress.js","../../../node_modules/crc/mjs/calculators/crc32.js","../../../node_modules/crc/mjs/create_buffer.js","../../../node_modules/crc/mjs/crc32.js","../../../node_modules/crc/mjs/define_crc.js"],"sourcesContent":["const Constants = {\n CRAM_FLAG_PRESERVE_QUAL_SCORES: 1 << 0,\n CRAM_FLAG_DETACHED: 1 << 1,\n CRAM_FLAG_MATE_DOWNSTREAM: 1 << 2,\n CRAM_FLAG_NO_SEQ: 1 << 3,\n CRAM_FLAG_MASK: (1 << 4) - 1,\n\n // mate read is reversed\n CRAM_M_REVERSE: 1,\n // mated read is unmapped\n CRAM_M_UNMAP: 2,\n\n // the read is paired in sequencing, no matter whether it is mapped in a pair\n BAM_FPAIRED: 1,\n // the read is mapped in a proper pair\n BAM_FPROPER_PAIR: 2,\n // the read itself is unmapped; conflictive with BAM_FPROPER_PAIR\n BAM_FUNMAP: 4,\n // the mate is unmapped\n BAM_FMUNMAP: 8,\n // the read is mapped to the reverse strand\n BAM_FREVERSE: 16,\n // the mate is mapped to the reverse strand\n BAM_FMREVERSE: 32,\n // this is read1\n BAM_FREAD1: 64,\n // this is read2\n BAM_FREAD2: 128,\n // not primary alignment\n BAM_FSECONDARY: 256,\n // QC failure\n BAM_FQCFAIL: 512,\n // optical or PCR duplicate\n BAM_FDUP: 1024,\n // supplementary alignment\n BAM_FSUPPLEMENTARY: 2048,\n\n BAM_CMATCH: 0,\n BAM_CINS: 1,\n BAM_CDEL: 2,\n BAM_CREF_SKIP: 3,\n BAM_CSOFT_CLIP: 4,\n BAM_CHARD_CLIP: 5,\n BAM_CPAD: 6,\n BAM_CEQUAL: 7,\n BAM_CDIFF: 8,\n BAM_CBACK: 9,\n\n BAM_CIGAR_STR: 'MIDNSHP:XB',\n BAM_CIGAR_SHIFT: 4,\n BAM_CIGAR_MASK: 0xf,\n BAM_CIGAR_TYPE: 0x3c1a7,\n}\n\nexport default Constants\n","import Constants from './constants'\nimport CramContainerCompressionScheme from './container/compressionScheme'\nimport type decodeRecord from './slice/decodeRecord'\n\nexport interface RefRegion {\n start: number\n end: number\n seq: string\n}\n\nexport interface ReadFeature {\n code: string\n pos: number\n refPos: number\n data: any\n\n ref?: string\n sub?: string\n}\n\nfunction decodeReadSequence(cramRecord: CramRecord, refRegion: RefRegion) {\n // if it has no length, it has no sequence\n if (!cramRecord.lengthOnRef && !cramRecord.readLength) {\n return null\n }\n\n if (cramRecord.isUnknownBases()) {\n return null\n }\n\n // remember: all coordinates are 1-based closed\n const regionSeqOffset = cramRecord.alignmentStart - refRegion.start\n\n if (!cramRecord.readFeatures) {\n return refRegion.seq\n .slice(regionSeqOffset, regionSeqOffset + (cramRecord.lengthOnRef || 0))\n .toUpperCase()\n }\n\n let bases = ''\n let regionPos = regionSeqOffset\n let currentReadFeature = 0\n while (bases.length < cramRecord.readLength) {\n if (currentReadFeature < cramRecord.readFeatures.length) {\n const feature = cramRecord.readFeatures[currentReadFeature]!\n if (feature.code === 'Q' || feature.code === 'q') {\n currentReadFeature += 1\n } else if (feature.pos === bases.length + 1) {\n // process the read feature\n currentReadFeature += 1\n\n if (feature.code === 'b') {\n // specify a base pair for some reason\n const added = feature.data\n bases += added\n regionPos += added.length\n } else if (feature.code === 'B') {\n // base pair and associated quality\n // TODO: do we need to set the quality in the qual scores?\n bases += feature.data[0]\n regionPos += 1\n } else if (feature.code === 'X') {\n // base substitution\n bases += feature.sub\n regionPos += 1\n } else if (feature.code === 'I') {\n // insertion\n bases += feature.data\n } else if (feature.code === 'D') {\n // deletion\n regionPos += feature.data\n } else if (feature.code === 'i') {\n // insert single base\n bases += feature.data\n } else if (feature.code === 'N') {\n // reference skip. delete some bases\n // do nothing\n // seqBases.splice(feature.pos - 1, feature.data)\n regionPos += feature.data\n } else if (feature.code === 'S') {\n // soft clipped bases that should be present in the read seq\n // seqBases.splice(feature.pos - 1, 0, ...feature.data.split(''))\n bases += feature.data\n } else if (feature.code === 'P') {\n // padding, do nothing\n } else if (feature.code === 'H') {\n // hard clip, do nothing\n }\n } else if (currentReadFeature < cramRecord.readFeatures.length) {\n // put down a chunk of sequence up to the next read feature\n const chunk = refRegion.seq.slice(\n regionPos,\n regionPos + feature.pos - bases.length - 1,\n )\n bases += chunk\n regionPos += chunk.length\n }\n } else {\n // put down a chunk of reference up to the full read length\n const chunk = refRegion.seq.slice(\n regionPos,\n regionPos + cramRecord.readLength - bases.length,\n )\n bases += chunk\n regionPos += chunk.length\n }\n }\n\n return bases.toUpperCase()\n}\n\nconst baseNumbers = {\n a: 0,\n A: 0,\n c: 1,\n C: 1,\n g: 2,\n G: 2,\n t: 3,\n T: 3,\n n: 4,\n N: 4,\n}\n\nfunction decodeBaseSubstitution(\n cramRecord: CramRecord,\n refRegion: RefRegion,\n compressionScheme: CramContainerCompressionScheme,\n readFeature: ReadFeature,\n) {\n // decode base substitution code using the substitution matrix\n const refCoord = readFeature.refPos - refRegion.start\n const refBase = refRegion.seq.charAt(refCoord)\n if (refBase) {\n readFeature.ref = refBase\n }\n let baseNumber = (baseNumbers as any)[refBase]\n if (baseNumber === undefined) {\n baseNumber = 4\n }\n const substitutionScheme = compressionScheme.substitutionMatrix[baseNumber]!\n const base = substitutionScheme[readFeature.data]\n if (base) {\n readFeature.sub = base\n }\n}\n\nexport interface MateRecord {\n readName?: string\n sequenceId: number\n alignmentStart: number\n flags?: number\n\n uniqueId?: number\n}\n\nexport const BamFlags = [\n [0x1, 'Paired'],\n [0x2, 'ProperlyPaired'],\n [0x4, 'SegmentUnmapped'],\n [0x8, 'MateUnmapped'],\n [0x10, 'ReverseComplemented'],\n // the mate is mapped to the reverse strand\n [0x20, 'MateReverseComplemented'],\n // this is read1\n [0x40, 'Read1'],\n // this is read2\n [0x80, 'Read2'],\n // not primary alignment\n [0x100, 'Secondary'],\n // QC failure\n [0x200, 'FailedQc'],\n // optical or PCR duplicate\n [0x400, 'Duplicate'],\n // supplementary alignment\n [0x800, 'Supplementary'],\n] as const\n\nexport const CramFlags = [\n [0x1, 'PreservingQualityScores'],\n [0x2, 'Detached'],\n [0x4, 'WithMateDownstream'],\n [0x8, 'DecodeSequenceAsStar'],\n] as const\n\nexport const MateFlags = [\n [0x1, 'OnNegativeStrand'],\n [0x2, 'Unmapped'],\n] as const\n\ntype FlagsDecoder<Type> = {\n [Property in Type as `is${Capitalize<string & Property>}`]: (\n flags: number,\n ) => boolean\n}\n\ntype FlagsEncoder<Type> = {\n [Property in Type as `set${Capitalize<string & Property>}`]: (\n flags: number,\n ) => number\n}\n\nfunction makeFlagsHelper<T>(\n x: readonly (readonly [number, T])[],\n): FlagsDecoder<T> & FlagsEncoder<T> {\n const r: any = {}\n for (const [code, name] of x) {\n r[`is${name}`] = (flags: number) => !!(flags & code)\n r[`set${name}`] = (flags: number) => flags | code\n }\n\n return r\n}\n\nexport const BamFlagsDecoder = makeFlagsHelper(BamFlags)\nexport const CramFlagsDecoder = makeFlagsHelper(CramFlags)\nexport const MateFlagsDecoder = makeFlagsHelper(MateFlags)\n\n/**\n * Class of each CRAM record returned by this API.\n */\nexport default class CramRecord {\n public tags: Record<string, string>\n public flags: number\n public cramFlags: number\n public readBases?: string | null\n public _refRegion?: RefRegion\n public readFeatures?: ReadFeature[]\n public alignmentStart: number\n public lengthOnRef: number | undefined\n public readLength: number\n public templateLength?: number\n public templateSize?: number\n public readName?: string\n public mateRecordNumber?: number\n public mate?: MateRecord\n public uniqueId: number\n public sequenceId: number\n public readGroupId: number\n public mappingQuality: number | undefined\n public qualityScores: number[] | null | undefined\n\n constructor({\n flags,\n cramFlags,\n readLength,\n mappingQuality,\n lengthOnRef,\n qualityScores,\n mateRecordNumber,\n readBases,\n readFeatures,\n mateToUse,\n readGroupId,\n readName,\n sequenceId,\n uniqueId,\n templateSize,\n alignmentStart,\n tags,\n }: ReturnType<typeof decodeRecord> & { uniqueId: number }) {\n this.flags = flags\n this.cramFlags = cramFlags\n this.readLength = readLength\n this.mappingQuality = mappingQuality\n this.lengthOnRef = lengthOnRef\n this.qualityScores = qualityScores\n if (readBases) {\n this.readBases = readBases\n }\n\n this.readGroupId = readGroupId\n this.readName = readName\n this.sequenceId = sequenceId\n this.uniqueId = uniqueId\n this.templateSize = templateSize\n this.alignmentStart = alignmentStart\n this.tags = tags\n\n // backwards compatibility\n if (readFeatures) {\n this.readFeatures = readFeatures\n }\n if (mateToUse) {\n this.mate = {\n flags: mateToUse.mateFlags,\n readName: mateToUse.mateReadName,\n sequenceId: mateToUse.mateSequenceId,\n alignmentStart: mateToUse.mateAlignmentStart,\n }\n }\n if (mateRecordNumber) {\n this.mateRecordNumber = mateRecordNumber\n }\n }\n\n /**\n * @returns {boolean} true if the read is paired, regardless of whether both segments are mapped\n */\n isPaired() {\n return !!(this.flags & Constants.BAM_FPAIRED)\n }\n\n /** @returns {boolean} true if the read is paired, and both segments are mapped */\n isProperlyPaired() {\n return !!(this.flags & Constants.BAM_FPROPER_PAIR)\n }\n\n /** @returns {boolean} true if the read itself is unmapped; conflictive with isProperlyPaired */\n isSegmentUnmapped() {\n return !!(this.flags & Constants.BAM_FUNMAP)\n }\n\n /** @returns {boolean} true if the read itself is unmapped; conflictive with isProperlyPaired */\n isMateUnmapped() {\n return !!(this.flags & Constants.BAM_FMUNMAP)\n }\n\n /** @returns {boolean} true if the read is mapped to the reverse strand */\n isReverseComplemented() {\n return !!(this.flags & Constants.BAM_FREVERSE)\n }\n\n /** @returns {boolean} true if the mate is mapped to the reverse strand */\n isMateReverseComplemented() {\n return !!(this.flags & Constants.BAM_FMREVERSE)\n }\n\n /** @returns {boolean} true if this is read number 1 in a pair */\n isRead1() {\n return !!(this.flags & Constants.BAM_FREAD1)\n }\n\n /** @returns {boolean} true if this is read number 2 in a pair */\n isRead2() {\n return !!(this.flags & Constants.BAM_FREAD2)\n }\n\n /** @returns {boolean} true if this is a secondary alignment */\n isSecondary() {\n return !!(this.flags & Constants.BAM_FSECONDARY)\n }\n\n /** @returns {boolean} true if this read has failed QC checks */\n isFailedQc() {\n return !!(this.flags & Constants.BAM_FQCFAIL)\n }\n\n /** @returns {boolean} true if the read is an optical or PCR duplicate */\n isDuplicate() {\n return !!(this.flags & Constants.BAM_FDUP)\n }\n\n /** @returns {boolean} true if this is a supplementary alignment */\n isSupplementary() {\n return !!(this.flags & Constants.BAM_FSUPPLEMENTARY)\n }\n\n /**\n * @returns {boolean} true if the read is detached\n */\n isDetached() {\n return !!(this.cramFlags & Constants.CRAM_FLAG_DETACHED)\n }\n\n /** @returns {boolean} true if the read has a mate in this same CRAM segment */\n hasMateDownStream() {\n return !!(this.cramFlags & Constants.CRAM_FLAG_MATE_DOWNSTREAM)\n }\n\n /** @returns {boolean} true if the read contains qual scores */\n isPreservingQualityScores() {\n return !!(this.cramFlags & Constants.CRAM_FLAG_PRESERVE_QUAL_SCORES)\n }\n\n /** @returns {boolean} true if the read has no sequence bases */\n isUnknownBases() {\n return !!(this.cramFlags & Constants.CRAM_FLAG_NO_SEQ)\n }\n\n /**\n * Get the original sequence of this read.\n * @returns {String} sequence basepairs\n */\n getReadBases() {\n if (!this.readBases && this._refRegion) {\n const decoded = decodeReadSequence(this, this._refRegion)\n if (decoded) {\n this.readBases = decoded\n }\n }\n return this.readBases\n }\n\n /**\n * Get the pair orientation of a paired read. Adapted from igv.js\n * @returns {String} of paired orientatin\n */\n getPairOrientation() {\n if (\n !this.isSegmentUnmapped() &&\n this.isPaired() &&\n !this.isMateUnmapped() &&\n this.mate &&\n this.sequenceId === this.mate.sequenceId\n ) {\n const s1 = this.isReverseComplemented() ? 'R' : 'F'\n const s2 = this.isMateReverseComplemented() ? 'R' : 'F'\n let o1 = ' '\n let o2 = ' '\n if (this.isRead1()) {\n o1 = '1'\n o2 = '2'\n } else if (this.isRead2()) {\n o1 = '2'\n o2 = '1'\n }\n\n const tmp = []\n let isize = this.templateLength || this.templateSize\n if (isize === undefined) {\n throw new Error('One of templateSize and templateLength must be set')\n }\n if (this.alignmentStart > this.mate.alignmentStart && isize > 0) {\n isize = -isize\n }\n if (isize > 0) {\n tmp[0] = s1\n tmp[1] = o1\n tmp[2] = s2\n tmp[3] = o2\n } else {\n tmp[2] = s1\n tmp[3] = o1\n tmp[0] = s2\n tmp[1] = o2\n }\n return tmp.join('')\n }\n return null\n }\n\n /**\n * Annotates this feature with the given reference sequence basepair\n * information. This will add a `sub` and a `ref` item to base\n * substitution read features given the actual substituted and reference\n * base pairs, and will make the `getReadSequence()` method work.\n *\n * @param {object} refRegion\n * @param {number} refRegion.start\n * @param {number} refRegion.end\n * @param {string} refRegion.seq\n * @param {CramContainerCompressionScheme} compressionScheme\n * @returns {undefined} nothing\n */\n addReferenceSequence(\n refRegion: RefRegion,\n compressionScheme: CramContainerCompressionScheme,\n ) {\n if (this.readFeatures) {\n // use the reference bases to decode the bases\n // substituted in each base substitution\n this.readFeatures.forEach(readFeature => {\n if (readFeature.code === 'X') {\n decodeBaseSubstitution(\n this,\n refRegion,\n compressionScheme,\n readFeature,\n )\n }\n })\n }\n\n // if this region completely covers this read,\n // keep a reference to it\n if (\n !this.readBases &&\n refRegion.start <= this.alignmentStart &&\n refRegion.end >=\n this.alignmentStart + (this.lengthOnRef || this.readLength) - 1\n ) {\n this._refRegion = refRegion\n }\n }\n\n toJSON() {\n const data: any = {}\n Object.keys(this).forEach(k => {\n if (k.startsWith('_')) {\n return\n }\n data[k] = (this as any)[k]\n })\n\n data.readBases = this.getReadBases()\n\n return data\n }\n}\n","export class CramError extends Error {}\n\n/** Error caused by encountering a part of the CRAM spec that has not yet been implemented */\nexport class CramUnimplementedError extends Error {}\n\n/** An error caused by malformed data. */\nexport class CramMalformedError extends CramError {}\n\n/**\n * An error caused by data being too big, exceeding a size limit.\n */\nexport class CramSizeLimitError extends CramError {}\n\n/**\n * An invalid argument was supplied to a cram-js method or object.\n */\nexport class CramArgumentError extends CramError {}\n","import { inflate } from 'pako'\nimport { Buffer } from 'buffer'\n\nexport function unzip(input: Buffer) {\n return Buffer.from(inflate(input))\n}\n","const TF_SHIFT = 12\nconst TOTFREQ = 1 << TF_SHIFT\nconst RANS_BYTE_L = 1 << 23\n\nexport { TF_SHIFT, TOTFREQ, RANS_BYTE_L }\n","// @ts-nocheck\nimport { CramMalformedError } from '../errors'\n\nimport { RANS_BYTE_L } from './constants'\n\nclass FC {\n // int F, C;\n constructor() {\n this.F = undefined\n this.C = undefined\n }\n}\n\nclass AriDecoder {\n // final FC[] fc = new FC[256];\n // byte[] R;\n\n constructor() {\n this.fc = new Array(256)\n for (let i = 0; i < this.fc.length; i += 1) {\n this.fc[i] = new FC()\n }\n this.R = null\n }\n}\n\nclass DecodingSymbol {\n // int start; // Start of range.\n // int freq; // Symbol frequency.\n constructor() {\n this.start = undefined\n this.freq = undefined\n }\n}\n\n// Initialize a decoder symbol to start \"start\" and frequency \"freq\"\nfunction symbolInit(sym, start, freq) {\n if (!(start <= 1 << 16)) {\n throw new CramMalformedError('assertion failed: start <= 1<<16')\n }\n if (!(freq <= (1 << 16) - start)) {\n throw new CramMalformedError('assertion failed: freq <= 1<<16')\n }\n sym.start = start\n sym.freq = freq\n}\n\n// Advances in the bit stream by \"popping\" a single symbol with range start\n// \"start\" and frequency \"freq\". All frequencies are assumed to sum to\n// \"1 << scaleBits\".\n// No renormalization or output happens.\n/* private static int */ function advanceStep(\n /* final int */ r,\n /* final int */ start,\n /* final int */ freq,\n /* final int */ scaleBits,\n) {\n /* final int */ const mask = (1 << scaleBits) - 1\n\n // s, x = D(x)\n return freq * (r >> scaleBits) + (r & mask) - start\n}\n\n// Equivalent to RansDecAdvanceStep that takes a symbol.\n/* static int */ function advanceSymbolStep(\n /* final int */ r,\n /* final RansDecSymbol */ sym,\n /* final int */ scaleBits,\n) {\n return advanceStep(r, sym.start, sym.freq, scaleBits)\n}\n\n// Returns the current cumulative frequency (map it to a symbol yourself!)\n/* static int */ function get(/* final int */ r, /* final int */ scaleBits) {\n return r & ((1 << scaleBits) - 1)\n}\n\n// Advances in the bit stream by \"popping\" a single symbol with range start\n// \"start\" and frequency \"freq\". All frequencies are assumed to sum to\n// \"1 << scaleBits\",\n// and the resulting bytes get written to ptr (which is updated).\n/* private static int */ function advance(\n /* int */ r,\n /* final ByteBuffer */ pptr,\n /* final int */ start,\n /* final int */ freq,\n /* final int */ scaleBits,\n) {\n /* final int */ const mask = (1 << scaleBits) - 1\n\n // s, x = D(x)\n r = freq * (r >> scaleBits) + (r & mask) - start\n\n // re-normalize\n if (r < RANS_BYTE_L) {\n do {\n /* final int */ const b = 0xff & pptr.get()\n r = (r << 8) | b\n } while (r < RANS_BYTE_L)\n }\n\n return r\n}\n\n// Equivalent to RansDecAdvance that takes a symbol.\n/* static int */ function advanceSymbol(\n /* final int */ r,\n /* final ByteBuffer */ pptr,\n /* final RansDecSymbol */ sym,\n /* final int */ scaleBits,\n) {\n return advance(r, pptr, sym.start, sym.freq, scaleBits)\n}\n\n// Re-normalize.\n/* static int */ function renormalize(\n /* int */ r,\n /* final ByteBuffer */ pptr,\n) {\n // re-normalize\n if (r < RANS_BYTE_L) {\n do {\n r = (r << 8) | (0xff & pptr.get())\n } while (r < RANS_BYTE_L)\n }\n\n return r\n}\n\nexport default {\n FC,\n AriDecoder,\n DecodingSymbol,\n symbolInit,\n advanceStep,\n advanceSymbolStep,\n get,\n advanceSymbol,\n renormalize,\n}\n","// @ts-nocheck\nimport { CramMalformedError } from '../errors'\n\nimport { TOTFREQ } from './constants'\nimport Decoding from './decoding'\n\nfunction assert(result) {\n if (!result) {\n throw new CramMalformedError('assertion failed')\n }\n}\n\nexport function readStatsO0(\n /* ByteBuffer */ cp,\n /* Decoding.AriDecoder */ decoder,\n /* Decoding.RansDecSymbol[] */ syms,\n) {\n // Pre-compute reverse lookup of frequency.\n let rle = 0\n let x = 0\n let j = cp.get() & 0xff\n do {\n if (decoder.fc[j] == null) {\n decoder.fc[j] = new Decoding.FC()\n }\n decoder.fc[j].F = cp.get() & 0xff\n if (decoder.fc[j].F >= 128) {\n decoder.fc[j].F &= ~128\n decoder.fc[j].F = ((decoder.fc[j].F & 127) << 8) | (cp.get() & 0xff)\n }\n decoder.fc[j].C = x\n\n Decoding.symbolInit(syms[j], decoder.fc[j].C, decoder.fc[j].F)\n\n /* Build reverse lookup table */\n if (!decoder.R) {\n decoder.R = new Array(TOTFREQ)\n }\n decoder.R.fill(j, x, x + decoder.fc[j].F)\n\n x += decoder.fc[j].F\n\n if (rle === 0 && j + 1 === (0xff & cp.getByteAt(cp.position()))) {\n j = cp.get() & 0xff\n rle = cp.get() & 0xff\n } else if (rle !== 0) {\n rle -= 1\n j += 1\n } else {\n j = cp.get() & 0xff\n }\n } while (j !== 0)\n\n assert(x < TOTFREQ)\n}\n\nexport function readStatsO1(\n /* ByteBuffer */ cp,\n /* Decoding.AriDecoder[] */ D,\n /* Decoding.RansDecSymbol[][] */ syms,\n) {\n let rlei = 0\n let i = 0xff & cp.get()\n do {\n let rlej = 0\n let x = 0\n let j = 0xff & cp.get()\n if (D[i] == null) {\n D[i] = new Decoding.AriDecoder()\n }\n do {\n if (D[i].fc[j] == null) {\n D[i].fc[j] = new Decoding.FC()\n }\n D[i].fc[j].F = 0xff & cp.get()\n if (D[i].fc[j].F >= 128) {\n D[i].fc[j].F &= ~128\n D[i].fc[j].F = ((D[i].fc[j].F & 127) << 8) | (0xff & cp.get())\n }\n D[i].fc[j].C = x\n\n if (D[i].fc[j].F === 0) {\n D[i].fc[j].F = TOTFREQ\n }\n\n if (syms[i][j] == null) {\n syms[i][j] = new Decoding.RansDecSymbol()\n }\n\n Decoding.symbolInit(syms[i][j], D[i].fc[j].C, D[i].fc[j].F)\n\n /* Build reverse lookup table */\n if (D[i].R == null) {\n D[i].R = new Array(TOTFREQ)\n }\n D[i].R.fill(j, x, x + D[i].fc[j].F)\n\n x += D[i].fc[j].F\n assert(x <= TOTFREQ)\n\n if (rlej === 0 && j + 1 === (0xff & cp.getByteAt(cp.position()))) {\n j = 0xff & cp.get()\n rlej = 0xff & cp.get()\n } else if (rlej !== 0) {\n rlej -= 1\n j += 1\n } else {\n j = 0xff & cp.get()\n }\n } while (j !== 0)\n\n if (rlei === 0 && i + 1 === (0xff & cp.getByteAt(cp.position()))) {\n i = 0xff & cp.get()\n rlei = 0xff & cp.get()\n } else if (rlei !== 0) {\n rlei -= 1\n i += 1\n } else {\n i = 0xff & cp.get()\n }\n } while (i !== 0)\n}\n","// @ts-nocheck\nimport { Buffer } from 'buffer'\nimport { CramMalformedError } from '../errors'\n\nimport Decoding from './decoding'\nimport { readStatsO0, readStatsO1 } from './frequencies'\n\nimport D04 from './d04'\nimport D14 from './d14'\n\n// const /* int */ ORDER_BYTE_LENGTH = 1\n// const /* int */ COMPRESSED_BYTE_LENGTH = 4\nconst /* int */ RAW_BYTE_LENGTH = 4\n// const /* int */ PREFIX_BYTE_LENGTH =\n// ORDER_BYTE_LENGTH + COMPRESSED_BYTE_LENGTH + RAW_BYTE_LENGTH\n\n// enum ORDER {\n// ZERO, ONE;\n\n// static ORDER fromInt(const /* int */ value) {\n// try {\n// return ORDER.values()[value];\n// } catch (const ArrayIndexOutOfBoundsException e) {\n// throw new RuntimeException(\"Unknown rANS order: \" + value);\n// }\n// }\n// }\n\n// static ByteBuffer compress(const ByteBuffer input, const ORDER order, const ByteBuffer out) {\n// if (input.remaining() == 0)\n// return EMPTY_BUFFER;\n\n// if (input.remaining() < 4)\n// return encode_order0_way4(input, out);\n\n// switch (order) {\n// case ZERO:\n// return encode_order0_way4(input, out);\n// case ONE:\n// return encode_order1_way4(input, out);\n\n// default:\n// throw new RuntimeException(\"Unknown rANS order: \" + order);\n// }\n// }\n\n// static /* ByteBuffer */ allocateIfNeeded(/* const int */ in_size,\n// /* const ByteBuffer */ out_buf) {\n// const /* int */ compressedSize = (/* int */) (1.05 * in_size + 257 * 257 * 3 + 4);\n// if (out_buf == null)\n// return ByteBuffer.allocate(compressedSize);\n// if (out_buf.remaining() < compressedSize)\n// throw new RuntimeException(\"Insufficient buffer size.\");\n// out_buf.order(ByteOrder.LITTLE_ENDIAN);\n// return out_buf;\n// }\n\n// static ByteBuffer encode_order0_way4(const ByteBuffer input,\n// ByteBuffer out_buf) {\n// const /* int */ in_size = input.remaining();\n// out_buf = allocateIfNeeded(in_size, out_buf);\n// const /* int */ freqTableStart = PREFIX_BYTE_LENGTH;\n// out_buf.position(freqTableStart);\n\n// const /* int */[] F = Frequencies.calcFrequencies_o0(in);\n// const RansEncSymbol[] syms = Frequencies.buildSyms_o0(F);\n\n// const ByteBuffer cp = out_buf.slice();\n// const /* int */ frequencyTable_size = Frequencies.writeFrequencies_o0(cp, F);\n\n// input.rewind();\n// const /* int */ compressedBlob_size = E04.compress(input, syms, cp);\n\n// finalizeCompressed(0, out_buf, in_size, frequencyTable_size,\n// compressedBlob_size);\n// return out_buf;\n// }\n\n// static ByteBuffer encode_order1_way4(const ByteBuffer input,\n// ByteBuffer out_buf) {\n// const /* int */ in_size = input.remaining();\n// out_buf = allocateIfNeeded(in_size, out_buf);\n// const /* int */ freqTableStart = PREFIX_BYTE_LENGTH;\n// out_buf.position(freqTableStart);\n\n// const /* int */[][] F = Frequencies.calcFrequencies_o1(in);\n// const RansEncSymbol[][] syms = Frequencies.buildSyms_o1(F);\n\n// const ByteBuffer cp = out_buf.slice();\n// const /* int */ frequencyTable_size = Frequencies.writeFrequencies_o1(cp, F);\n\n// input.rewind();\n// const /* int */ compressedBlob_size = E14.compress(input, syms, cp);\n\n// finalizeCompressed(1, out_buf, in_size, frequencyTable_size,\n// compressedBlob_size);\n// return out_buf;\n// }\n\n// static void finalizeCompressed(const /* int */ order, const ByteBuffer out_buf,\n// const /* int */ in_size, const /* int */ frequencyTable_size, const /* int */ compressedBlob_size) {\n// out_buf.limit(PREFIX_BYTE_LENGTH + frequencyTable_size\n// + compressedBlob_size);\n// out_buf.put(0, (byte) order);\n// out_buf.order(ByteOrder.LITTLE_ENDIAN);\n// const /* int */ compressedSizeOffset = ORDER_BYTE_LENGTH;\n// out_buf.putInt(compressedSizeOffset, frequencyTable_size\n// + compressedBlob_size);\n// const /* int */ rawSizeOffset = ORDER_BYTE_LENGTH + COMPRESSED_BYTE_LENGTH;\n// out_buf.putInt(rawSizeOffset, in_size);\n// out_buf.rewind();\n// }\n\nfunction /* static ByteBuffer */ uncompressOrder0Way4(\n /* const ByteBuffer */ input,\n /* const ByteBuffer */ out,\n) {\n // input.order(ByteOrder.LITTLE_ENDIAN);\n const D = new Decoding.AriDecoder()\n const syms = new Array(256)\n for (let i = 0; i < syms.length; i += 1) {\n syms[i] = new Decoding.DecodingSymbol()\n }\n\n readStatsO0(input, D, syms)\n\n D04(input, D, syms, out)\n\n return out\n}\n\nfunction /* static ByteBuffer */ uncompressOrder1Way4(\n /* const ByteBuffer */ input,\n /* const ByteBuffer */ output,\n) {\n const D = new Array(256)\n for (let i = 0; i < D.length; i += 1) {\n D[i] = new Decoding.AriDecoder()\n }\n const /* Decoding.RansDecSymbol[][] */ syms = new Array(256)\n for (let i = 0; i < syms.length; i += 1) {\n syms[i] = new Array(256)\n for (let j = 0; j < syms[i].length; j += 1) {\n syms[i][j] = new Decoding.DecodingSymbol()\n }\n }\n readStatsO1(input, D, syms)\n\n D14(input, output, D, syms)\n\n return output\n}\n\n/* compat layer to make a node buffer act like a java ByteBuffer */\nclass ByteBuffer {\n constructor(nodeBuffer, initialInputPosition = 0) {\n this._buffer = nodeBuffer\n this._position = initialInputPosition\n this.length = nodeBuffer.length\n }\n\n get() {\n const b = this._buffer[this._position]\n this._position += 1\n return b\n }\n\n getByte() {\n return this.get()\n }\n\n getByteAt(position) {\n return this._buffer[position]\n }\n\n position() {\n return this._position\n }\n\n put(val) {\n this._buffer[this._position] = val\n this._position += 1\n return val\n }\n\n putAt(position, val) {\n this._buffer[position] = val\n return val\n }\n\n setPosition(pos) {\n this._position = pos\n return pos\n }\n\n getInt() {\n const i = this._buffer.readInt32LE(this._position)\n this._position += 4\n return i\n }\n\n remaining() {\n return this._buffer.length - this._position\n }\n}\n\n// static /* const */ ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);\nexport default function uncompress(\n inputBuffer,\n outputBuffer,\n initialInputPosition = 0,\n) {\n if (inputBuffer.length === 0) {\n outputBuffer.fill(0)\n return outputBuffer\n }\n\n const input = new ByteBuffer(inputBuffer, initialInputPosition)\n // input.order(ByteOrder.LITTLE_ENDIAN);\n\n const order = input.get()\n if (order !== 0 && order !== 1) {\n throw new CramMalformedError(`Invalid rANS order ${order}`)\n }\n\n const /* int */ inputSize = input.getInt()\n if (inputSize !== input.remaining() - RAW_BYTE_LENGTH) {\n throw new CramMalformedError('Incorrect input length.')\n }\n\n const /* int */ outputSize = input.getInt()\n const output = new ByteBuffer(outputBuffer || Buffer.allocUnsafe(outputSize))\n // TODO output.limit(outputSize)\n\n if (output.length < outputSize) {\n throw new CramMalformedError(\n `Output buffer too small to fit ${outputSize} bytes.`,\n )\n }\n\n switch (order) {\n case 0:\n return uncompressOrder0Way4(input, output)\n\n case 1:\n return uncompressOrder1Way4(input, output)\n\n default:\n throw new CramMalformedError(`Invalid rANS order: ${order}`)\n }\n}\n","export class CramBufferOverrunError extends Error {}\n\nexport function getBits(\n data: Buffer,\n cursor: { bytePosition: number; bitPosition: number },\n numBits: number,\n) {\n let val = 0\n if (\n cursor.bytePosition + (7 - cursor.bitPosition + numBits) / 8 >\n data.length\n ) {\n throw new CramBufferOverrunError(\n 'read error during decoding. the file seems to be truncated.',\n )\n }\n for (let dlen = numBits; dlen; dlen--) {\n // get the next `dlen` bits in the input, put them in val\n val <<= 1\n val |= (data[cursor.bytePosition]! >> cursor.bitPosition) & 1\n cursor.bitPosition -= 1\n if (cursor.bitPosition < 0) {\n cursor.bytePosition += 1\n }\n cursor.bitPosition &= 7\n }\n return val\n}\n","import md5 from 'md5'\nimport Long from 'long'\nimport { CramBufferOverrunError } from './codecs/getBits'\n\nexport function itf8Size(v: number) {\n if (!(v & ~0x7f)) {\n return 1\n }\n if (!(v & ~0x3fff)) {\n return 2\n }\n if (!(v & ~0x1fffff)) {\n return 3\n }\n if (!(v & ~0xfffffff)) {\n return 4\n }\n return 5\n}\n\nexport function parseItf8(buffer: Uint8Array, initialOffset: number) {\n let offset = initialOffset\n const countFlags = buffer[offset]!\n let result: number\n if (countFlags < 0x80) {\n result = countFlags\n offset = offset + 1\n } else if (countFlags < 0xc0) {\n result = ((countFlags << 8) | buffer[offset + 1]!) & 0x3fff\n offset = offset + 2\n } else if (countFlags < 0xe0) {\n result =\n ((countFlags << 16) | (buffer[offset + 1]! << 8) | buffer[offset + 2]!) &\n 0x1fffff\n offset = offset + 3\n } else if (countFlags < 0xf0) {\n result =\n ((countFlags << 24) |\n (buffer[offset + 1]! << 16) |\n (buffer[offset + 2]! << 8) |\n buffer[offset + 3]!) &\n 0x0fffffff\n offset = offset + 4\n } else {\n result =\n ((countFlags & 0x0f) << 28) |\n (buffer[offset + 1]! << 20) |\n (buffer[offset + 2]! << 12) |\n (buffer[offset + 3]! << 4) |\n (buffer[offset + 4]! & 0x0f)\n // x=((0xff & 0x0f)<<28) | (0xff<<20) | (0xff<<12) | (0xff<<4) | (0x0f & 0x0f);\n // TODO *val_p = uv < 0x80000000UL ? uv : -((int32_t) (0xffffffffUL - uv)) - 1;\n offset = offset + 5\n }\n if (offset > buffer.length) {\n throw new CramBufferOverrunError(\n 'Attempted to read beyond end of buffer; this file seems truncated.',\n )\n }\n return [result, offset - initialOffset] as const\n}\n\nexport function parseLtf8(buffer: Buffer, initialOffset: number) {\n let offset = initialOffset\n const countFlags = buffer[offset]!\n let n: number | Long\n if (countFlags < 0x80) {\n n = countFlags\n offset += 1\n } else if (countFlags < 0xc0) {\n n = ((buffer[offset]! << 8) | buffer[offset + 1]!) & 0x3fff\n offset += 2\n } else if (countFlags < 0xe0) {\n n =\n ((buffer[offset]! << 16) |\n (buffer[offset + 1]! << 8) |\n buffer[offset + 2]!) &\n 0x1fffff\n n = ((countFlags & 63) << 16) | buffer.readUInt16LE(offset + 1)\n offset += 3\n } else if (countFlags < 0xf0) {\n n =\n ((buffer[offset]! << 24) |\n (buffer[offset + 1]! << 16) |\n (buffer[offset + 2]! << 8) |\n buffer[offset + 3]!) &\n 0x0fffffff\n offset += 4\n } else if (countFlags < 0xf8) {\n n =\n ((buffer[offset]! & 15) * 2 ** 32 + (buffer[offset + 1]! << 24)) |\n ((buffer[offset + 2]! << 16) |\n (buffer[offset + 3]! << 8) |\n buffer[offset + 4]!)\n // TODO *val_p = uv < 0x80000000UL ? uv : -((int32_t) (0xffffffffUL - uv)) - 1;\n offset += 5\n } else if (countFlags < 0xfc) {\n n =\n ((((buffer[offset]! & 7) << 8) | buffer[offset + 1]!) * 2 ** 32 +\n (buffer[offset + 2]! << 24)) |\n ((buffer[offset + 3]! << 16) |\n (buffer[offset + 4]! << 8) |\n buffer[offset + 5]!)\n offset += 6\n } else if (countFlags < 0xfe) {\n n =\n ((((buffer[offset]! & 3) << 16) |\n (buffer[offset + 1]! << 8) |\n buffer[offset + 2]!) *\n 2 ** 32 +\n (buffer[offset + 3]! << 24)) |\n ((buffer[offset + 4]! << 16) |\n (buffer[offset + 5]! << 8) |\n buffer[offset + 6]!)\n offset += 7\n } else if (countFlags < 0xff) {\n n = Long.fromBytesBE(\n buffer.slice(offset + 1, offset + 8) as unknown as number[],\n )\n if (\n n.greaterThan(Number.MAX_SAFE_INTEGER) ||\n n.lessThan(Number.MIN_SAFE_INTEGER)\n ) {\n throw new Error('integer overflow')\n }\n n = n.toNumber()\n offset += 8\n } else {\n n = Long.fromBytesBE(\n buffer.slice(offset + 1, offset + 9) as unknown as number[],\n )\n if (\n n.greaterThan(Number.MAX_SAFE_INTEGER) ||\n n.lessThan(Number.MIN_SAFE_INTEGER)\n ) {\n throw new Error('integer overflow')\n }\n n = n.toNumber()\n offset += 9\n }\n return [n, offset - initialOffset] as const\n}\n\nexport function parseItem<T>(\n buffer: Buffer,\n parser: (buffer: Buffer, offset: number) => { offset: number; value: T },\n startBufferPosition = 0,\n startFilePosition = 0,\n) {\n const { offset, value } = parser(buffer, startBufferPosition)\n return {\n ...value,\n _endPosition: offset + startFilePosition,\n _size: offset - startBufferPosition,\n }\n}\n\n// this would be nice as a decorator, but i'm a little worried about babel\n// support for it going away or changing. memoizes a method in the stupidest\n// possible way, with no regard for the arguments. actually, this only works\n// on methods that take no arguments\nexport function tinyMemoize(_class: any, methodName: any) {\n const method = _class.prototype[methodName]\n const memoAttrName = `_memo_${methodName}`\n _class.prototype[methodName] = function _tinyMemoized() {\n if (!(memoAttrName in this)) {\n const res = method.call(this)\n this[memoAttrName] = res\n Promise.resolve(res).catch(() => {\n \n delete this[memoAttrName]\n })\n }\n return this[memoAttrName]\n }\n}\n\nexport function sequenceMD5(seq: string) {\n return md5(seq.toUpperCase().replaceAll(/[^\\u0021-\\u007e]/g, ''))\n}\n","import { TupleOf } from '../typescript'\nimport { parseItf8, parseLtf8 } from './util'\nimport { DataSeriesEncodingMap } from './codecs/dataSeriesTypes'\nimport { CramEncoding } from './encoding'\n\nexport function cramFileDefinition() {\n return {\n parser: (buffer: Buffer, _startOffset = 0) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n let offset = 0\n const magic = buffer.subarray(offset, offset + 4).toString()\n offset += 4\n const majorVersion = dataView.getUint8(offset)\n offset += 1\n const minorVersion = dataView.getUint8(offset)\n offset += 1\n const fileId = b\n .subarray(offset, offset + 20)\n .toString()\n .replaceAll('\\0', '')\n offset += 20\n return {\n value: {\n magic,\n majorVersion,\n minorVersion,\n fileId,\n },\n offset,\n }\n },\n maxLength: 26,\n }\n}\nexport function cramBlockHeader() {\n const parser = (buffer: Buffer, _startOffset = 0) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n let offset = 0\n const d = dataView.getUint8(offset)\n const compressionMethod = [\n 'raw',\n 'gzip',\n 'bzip2',\n 'lzma',\n 'rans',\n 'rans4x16',\n 'arith',\n 'fqzcomp',\n 'tok3',\n ][d]\n if (!compressionMethod) {\n throw new Error(`compression method number ${d} not implemented`)\n }\n offset += 1\n\n const c = dataView.getUint8(offset)\n const contentType = [\n 'FILE_HEADER',\n 'COMPRESSION_HEADER',\n 'MAPPED_SLICE_HEADER',\n 'UNMAPPED_SLICE_HEADER', // < only used in cram v1\n 'EXTERNAL_DATA',\n 'CORE_DATA',\n ][c]\n if (!contentType) {\n throw new Error(`invalid block content type id ${c}`)\n }\n offset += 1\n\n const [contentId, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [compressedSize, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const [uncompressedSize, newOffset3] = parseItf8(buffer, offset)\n offset += newOffset3\n return {\n offset,\n value: {\n uncompressedSize,\n compressedSize,\n contentId,\n contentType: contentType as\n | 'FILE_HEADER'\n | 'COMPRESSION_HEADER'\n | 'MAPPED_SLICE_HEADER'\n | 'UNMAPPED_SLICE_HEADER' // < only used in cram v1\n | 'EXTERNAL_DATA'\n | 'CORE_DATA',\n compressionMethod: compressionMethod as CompressionMethod,\n },\n }\n }\n return { parser, maxLength: 17 }\n}\n\nexport function cramBlockCrc32() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n const crc32 = dataView.getUint32(offset, true)\n offset += 4\n return {\n offset,\n value: {\n crc32,\n },\n }\n },\n maxLength: 4,\n }\n}\n\nexport type CramTagDictionary = string[][]\n\nfunction makeTagSet(buffer: Buffer, stringStart: number, stringEnd: number) {\n const str = buffer.toString('utf8', stringStart, stringEnd)\n const tags = []\n for (let i = 0; i < str.length; i += 3) {\n tags.push(str.slice(i, i + 3))\n }\n return tags\n}\n\nexport function cramTagDictionary() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const [size, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const subbuf = buffer.subarray(offset, offset + size)\n offset += size\n\n const tagSets = []\n let stringStart = 0\n let i = 0\n for (; i < subbuf.length; i++) {\n if (!subbuf[i]) {\n tagSets.push(makeTagSet(subbuf, stringStart, i))\n stringStart = i + 1\n }\n }\n if (i > stringStart) {\n tagSets.push(makeTagSet(subbuf, stringStart, i))\n }\n\n return {\n value: {\n size,\n ents: tagSets,\n },\n offset,\n }\n },\n }\n}\n\nexport interface CramPreservationMap {\n MI: boolean\n UI: boolean\n PI: boolean\n RN: boolean\n AP: boolean\n RR: boolean\n SM: [number, number, number, number, number]\n TD: CramTagDictionary\n}\n\nexport function cramPreservationMap() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n const [mapSize, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [mapCount, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const ents = []\n for (let i = 0; i < mapCount; i++) {\n const key =\n String.fromCharCode(buffer[offset]!) +\n String.fromCharCode(buffer[offset + 1]!)\n offset += 2\n\n if (\n key === 'MI' ||\n key === 'UI' ||\n key === 'PI' ||\n key === 'RN' ||\n key === 'AP' ||\n key === 'RR'\n ) {\n ents.push({\n key,\n value: !!dataView.getUint8(offset),\n })\n offset += 1\n } else if (key === 'SM') {\n ents.push({\n key,\n value: [\n dataView.getUint8(offset),\n dataView.getUint8(offset + 1),\n dataView.getUint8(offset + 2),\n dataView.getUint8(offset + 3),\n dataView.getUint8(offset + 4),\n ],\n })\n offset += 5\n } else if (key === 'TD') {\n const { offset: offsetRet, value } = cramTagDictionary().parser(\n buffer,\n offset,\n )\n ents.push({ key, value: value.ents })\n offset = offsetRet\n } else {\n throw new Error(`unknown key ${key}`)\n }\n }\n return {\n value: {\n mapSize,\n mapCount,\n ents,\n },\n offset,\n }\n },\n }\n}\n\nfunction formatMap(data: { ents: { key: string; value: unknown }[] }) {\n const map: Record<string, unknown> = {}\n for (const { key, value } of data.ents) {\n if (map[key]) {\n console.warn(`duplicate key ${key} in map`)\n }\n map[key] = value\n }\n return map\n}\n\nexport interface MappedSliceHeader {\n refSeqId: number\n refSeqStart: number\n refSeqSpan: number\n numRecords: number\n recordCounter: number\n numBlocks: number\n numContentIds: number\n contentIds: number[]\n refBaseBlockId: number\n md5?: TupleOf<number, 16>\n}\n\nexport interface UnmappedSliceHeader {\n numRecords: number\n recordCounter: number\n numBlocks: number\n numContentIds: number\n contentIds: number[]\n md5?: TupleOf<number, 16>\n}\n\nexport function isMappedSliceHeader(\n header: unknown,\n): header is MappedSliceHeader {\n return typeof (header as any).refSeqId === 'number'\n}\n\ninterface Value {\n codecId: number\n parametersBytes: number\n parameters: Record<string, unknown>\n}\n// assemble a section parser for the unmapped slice header, with slight\n// variations depending on the major version of the cram file\nfunction cramUnmappedSliceHeader(majorVersion: number) {\n let maxLength = 0\n maxLength += 5\n maxLength += 9\n maxLength += 5 * 2\n maxLength += 16\n\n const parser = (buffer: Buffer, offset: number) => {\n const [numRecords, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n let recordCounter = 0\n\n // recordCounter is itf8 in a CRAM v2 file, absent in CRAM v1\n if (majorVersion >= 3) {\n const [rc, newOffset2] = parseLtf8(buffer, offset)\n offset += newOffset2\n recordCounter = rc\n } else if (majorVersion === 2) {\n const [rc, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n recordCounter = rc\n } else {\n console.warn('recordCounter=0')\n }\n\n const [numBlocks, newOffset3] = parseItf8(buffer, offset)\n offset += newOffset3\n const [numContentIds, newOffset4] = parseItf8(buffer, offset)\n offset += newOffset4\n const contentIds = []\n for (let i = 0; i < numContentIds; i++) {\n const [id, newOffset5] = parseItf8(buffer, offset)\n offset += newOffset5\n contentIds.push(id)\n }\n\n // the md5 sum is missing in cram v1\n let md5: TupleOf<number, 16> | undefined\n if (majorVersion >= 2) {\n md5 = [...buffer.subarray(offset, offset + 16)] as TupleOf<number, 16>\n offset += 16\n }\n\n return {\n value: {\n recordCounter,\n md5,\n contentIds,\n numContentIds,\n numBlocks,\n numRecords,\n },\n offset,\n }\n }\n return {\n parser,\n maxLength: (numContentIds: number) => maxLength + numContentIds * 5,\n }\n}\n\n// assembles a section parser for the unmapped slice header, with slight\n// variations depending on the major version of the cram file\nfunction cramMappedSliceHeader(majorVersion: number) {\n let maxLength = 0\n maxLength += 5 * 4 // EL0\n maxLength += 9 // EL1\n maxLength += 5 * 3 // EL2 ITF8s\n maxLength += 16 // MD5\n\n return {\n parser: (buffer: Buffer, offset: number) => {\n // L0\n const [refSeqId, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [refSeqStart, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const [refSeqSpan, newOffset3] = parseItf8(buffer, offset)\n offset += newOffset3\n const [numRecords, newOffset4] = parseItf8(buffer, offset)\n offset += newOffset4\n // EL0\n\n // L1\n let recordCounter = 0\n if (majorVersion >= 3) {\n const [rc, newOffset5] = parseLtf8(buffer, offset)\n offset += newOffset5\n recordCounter = rc\n } else if (majorVersion === 2) {\n const [rc, newOffset5] = parseItf8(buffer, offset)\n offset += newOffset5\n recordCounter = rc\n } else {\n console.warn('majorVersion is <2, recordCounter set to 0')\n }\n // EL1\n\n // L2\n const [numBlocks, newOffset6] = parseItf8(buffer, offset)\n offset += newOffset6\n const [numContentIds, newOffset7] = parseItf8(buffer, offset)\n offset += newOffset7\n const contentIds = []\n for (let i = 0; i < numContentIds; i++) {\n const [id, newOffset5] = parseItf8(buffer, offset)\n offset += newOffset5\n contentIds.push(id)\n }\n const [refBaseBlockId, newOffset8] = parseItf8(buffer, offset)\n offset += newOffset8\n // EL2\n\n // the md5 sum is missing in cram v1\n let md5: TupleOf<number, 16> | undefined\n if (majorVersion >= 2) {\n md5 = [...buffer.subarray(offset, offset + 16)] as TupleOf<number, 16>\n offset += 16\n }\n\n return {\n value: {\n md5,\n numBlocks,\n numRecords,\n numContentIds,\n refSeqSpan,\n refSeqId,\n refSeqStart,\n recordCounter,\n refBaseBlockId,\n contentIds,\n },\n offset,\n }\n },\n maxLength: (numContentIds: number) => maxLength + numContentIds * 5,\n }\n}\n\nfunction cramEncoding() {\n return {\n parser: (buffer: Buffer, offset: number) => cramEncodingSub(buffer, offset),\n }\n}\n\nfunction cramEncodingSub(\n buffer: Buffer,\n offset: number,\n): { value: Value; offset: number } {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n const [codecId, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [parametersBytes, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n\n const parameters = {} as Record<string, unknown>\n\n if (codecId === 0) {\n // NULL\n } else if (codecId === 1) {\n // EXTERNAL\n const [bc, newOffset3] = parseItf8(buffer, offset)\n parameters.blockContentId = bc\n offset += newOffset3\n } else if (codecId === 2) {\n // GOLUMB\n const [off, newOffset3] = parseItf8(buffer, offset)\n parameters.offset = off\n offset += newOffset3\n const [M2, newOffset4] = parseItf8(buffer, offset)\n parameters.M = M2\n offset += newOffset4\n } else if (codecId === 3) {\n // HUFFMAN_INT\n const val = parseItf8(buffer, offset)\n const numCodes = val[0]\n offset += val[1]\n const symbols = [] as number[]\n for (let i = 0; i < numCodes; i++) {\n const code = parseItf8(buffer, offset)\n symbols.push(code[0])\n offset += code[1]\n }\n parameters.symbols = symbols\n const val2 = parseItf8(buffer, offset)\n const numLengths = val[0]\n parameters.numLengths = numLengths\n parameters.numCodes = numCodes\n parameters.numLengths = numLengths\n offset += val2[1]\n const bitLengths = [] as number[]\n for (let i = 0; i < numLengths; i++) {\n const len = parseItf8(buffer, offset)\n offset += len[1]\n bitLengths.push(len[0])\n }\n parameters.bitLengths = bitLengths\n } else if (codecId === 4) {\n // BYTE_ARRAY_LEN\n const { value: lengthsEncoding, offset: newOffset1 } = cramEncodingSub(\n buffer,\n offset,\n )\n parameters.lengthsEncoding = lengthsEncoding\n offset = newOffset1\n const { value: valuesEncoding, offset: newOffset2 } = cramEncodingSub(\n buffer,\n offset,\n )\n parameters.valuesEncoding = valuesEncoding\n offset = newOffset2\n } else if (codecId === 5) {\n // BYTE_ARRAY_STOP\n parameters.stopByte = dataView.getUint8(offset)\n offset += 1\n const [blockContentId, newOffset1] = parseItf8(buffer, offset)\n parameters.blockContentId = blockContentId\n offset += newOffset1\n } else if (codecId === 6) {\n // BETA\n const [off, newOffset1] = parseItf8(buffer, offset)\n parameters.offset = off\n offset += newOffset1\n const [len, newOffset2] = parseItf8(buffer, offset)\n parameters.length = len\n offset += newOffset2\n } else if (codecId === 7) {\n // SUBEXP\n const [off, newOffset1] = parseItf8(buffer, offset)\n parameters.offset = off\n offset += newOffset1\n const [K, newOffset2] = parseItf8(buffer, offset)\n parameters.K = K\n offset += newOffset2\n } else if (codecId === 8) {\n // GOLOMB_RICE\n const [off, newOffset1] = parseItf8(buffer, offset)\n parameters.offset = off\n offset += newOffset1\n const [l2m, newOffset2] = parseItf8(buffer, offset)\n parameters.log2m = l2m\n offset += newOffset2\n } else if (codecId === 9) {\n // GAMMA\n const [off, newOffset1] = parseItf8(buffer, offset)\n parameters.offset = off\n offset += newOffset1\n } else {\n throw new Error(`unknown codecId ${codecId}`)\n }\n\n return {\n value: {\n codecId,\n parametersBytes,\n parameters,\n },\n offset,\n }\n}\n\nfunction cramDataSeriesEncodingMap() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const [mapSize, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [mapCount, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const ents = []\n for (let i = 0; i < mapCount; i++) {\n const key =\n String.fromCharCode(buffer[offset]!) +\n String.fromCharCode(buffer[offset + 1]!)\n offset += 2\n\n const { value, offset: newOffset4 } = cramEncodingSub(buffer, offset)\n offset = newOffset4\n ents.push({ key, value })\n }\n return {\n value: {\n mapSize,\n ents,\n mapCount,\n },\n offset,\n }\n },\n }\n}\n\nfunction cramTagEncodingMap() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const [mapSize, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [mapCount, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const ents = []\n for (let i = 0; i < mapCount; i++) {\n const [k0, newOffset3] = parseItf8(buffer, offset)\n offset += newOffset3\n const key =\n String.fromCharCode((k0 >> 16) & 0xff) +\n String.fromCharCode((k0 >> 8) & 0xff) +\n String.fromCharCode(k0 & 0xff)\n\n const { value, offset: newOffset4 } = cramEncodingSub(buffer, offset)\n offset = newOffset4\n ents.push({ key, value })\n }\n return {\n value: {\n mapSize,\n ents,\n mapCount,\n },\n offset,\n }\n },\n }\n}\n\nfunction cramCompressionHeader() {\n return {\n parser: (buffer: Buffer, offset: number) => {\n // TODO: if we want to support CRAM v1, we will need to refactor\n // compression header into 2 parts to parse the landmarks, like the\n // container header\n const { value: preservation, offset: newOffset1 } =\n cramPreservationMap().parser(buffer, offset)\n offset = newOffset1\n\n const { value: dataSeriesEncoding, offset: newOffset2 } =\n cramDataSeriesEncodingMap().parser(buffer, offset)\n offset = newOffset2\n\n const { value: tagEncoding, offset: newOffset3 } =\n cramTagEncodingMap().parser(buffer, offset)\n offset = newOffset3\n\n return {\n value: {\n dataSeriesEncoding: formatMap(\n dataSeriesEncoding,\n ) as DataSeriesEncodingMap,\n preservation: formatMap(\n preservation,\n ) as unknown as CramPreservationMap,\n tagEncoding: formatMap(tagEncoding) as Record<string, CramEncoding>,\n },\n offset,\n }\n },\n }\n}\n\nfunction cramContainerHeader1(majorVersion: number) {\n let maxLength = 4\n maxLength += 5 * 4\n maxLength += 9\n maxLength += 9\n maxLength += 5 + 5\n return {\n maxLength,\n parser: (buffer: Buffer, offset: number) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n // byte size of the container data (blocks)\n const length = dataView.getInt32(offset, true)\n offset += 4\n // reference sequence identifier, -1 for unmapped reads, -2 for multiple\n // reference sequences\n const [refSeqId, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const [refSeqStart, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n const [alignmentSpan, newOffset3] = parseItf8(buffer, offset)\n offset += newOffset3\n const [numRecords, newOffset4] = parseItf8(buffer, offset)\n offset += newOffset4\n\n let recordCounter = 0\n if (majorVersion >= 3) {\n const [rc, newOffset5] = parseLtf8(buffer, offset)\n recordCounter = rc\n offset += newOffset5\n } else if (majorVersion === 2) {\n const [rc, newOffset5] = parseItf8(buffer, offset)\n recordCounter = rc\n offset += newOffset5\n } else {\n console.warn('setting recordCounter=0')\n }\n\n let numBases: number | undefined\n if (majorVersion > 1) {\n const [n, newOffset5] = parseLtf8(buffer, offset)\n numBases = n\n offset += newOffset5\n }\n const [numBlocks, newOffset6] = parseItf8(buffer, offset)\n offset += newOffset6\n const [numLandmarks, newOffset7] = parseItf8(buffer, offset)\n offset += newOffset7\n return {\n value: {\n length,\n refSeqId,\n refSeqStart,\n alignmentSpan,\n numBlocks,\n numLandmarks,\n numBases,\n recordCounter,\n numRecords,\n },\n offset,\n }\n },\n }\n}\n\nfunction cramContainerHeader2(majorVersion: number) {\n return {\n parser: (buffer: Buffer, offset: number) => {\n const b = buffer\n const dataView = new DataView(b.buffer, b.byteOffset, b.length)\n const [numLandmarks, newOffset1] = parseItf8(buffer, offset)\n offset += newOffset1\n const landmarks = []\n for (let i = 0; i < numLandmarks; i++) {\n const [landmark, newOffset2] = parseItf8(buffer, offset)\n offset += newOffset2\n landmarks.push(landmark)\n }\n\n let crc32: number | undefined\n if (majorVersion >= 3) {\n crc32 = dataView.getUint32(offset, true)\n offset += 4\n }\n return {\n value: {\n ...(crc32 === undefined ? {} : { crc32 }),\n numLandmarks,\n landmarks,\n },\n offset,\n }\n },\n maxLength: (numLandmarks: number) => 5 + 5 * numLandmarks + 4,\n }\n}\n\nexport type CompressionMethod =\n | 'raw'\n | 'gzip'\n | 'bzip2'\n | 'lzma'\n | 'rans'\n | 'rans4x16'\n | 'arith'\n | 'fqzcomp'\n | 'tok3'\n\nexport interface BlockHeader {\n compressionMethod: CompressionMethod\n contentType:\n | 'FILE_HEADER'\n | 'COMPRESSION_HEADER'\n | 'MAPPED_SLICE_HEADER'\n | 'UNMAPPED_SLICE_HEADER' // < only used in cram v1\n | 'EXTERNAL_DATA'\n | 'CORE_DATA'\n contentId: number\n compressedSize: number\n uncompressedSize: number\n}\n\nexport interface CramCompressionHeader {\n preservation: CramPreservationMap\n dataSeriesEncoding: DataSeriesEncodingMap\n tagEncoding: Record<string, CramEncoding>\n _size: number\n _endPosition: number\n}\n\nexport function getSectionParsers(majorVersion: number) {\n return {\n cramFileDefinition: cramFileDefinition(),\n cramBlockHeader: cramBlockHeader(),\n cramBlockCrc32: cramBlockCrc32(),\n cramDataSeriesEncodingMap: cramDataSeriesEncodingMap(),\n cramTagEncodingMap: cramTagEncodingMap(),\n cramCompressionHeader: cramCompressionHeader(),\n cramEncoding: cramEncoding(),\n cramUnmappedSliceHeader: cramUnmappedSliceHeader(majorVersion),\n cramMappedSliceHeader: cramMappedSliceHeader(majorVersion),\n cramContainerHeader1: cramContainerHeader1(majorVersion),\n cramContainerHeader2: cramContainerHeader2(majorVersion),\n }\n}\n","import { CramMalformedError } from '../../errors'\nimport {\n BamFlagsDecoder,\n CramFlagsDecoder,\n MateFlagsDecoder,\n ReadFeature,\n} from '../record'\nimport CramSlice, { SliceHeader } from './index'\nimport { isMappedSliceHeader } from '../sectionParsers'\nimport CramContainerCompressionScheme, {\n DataSeriesTypes,\n} from '../container/compressionScheme'\nimport { CramFileBlock } from '../file'\nimport { Cursors, DataTypeMapping } from '../codecs/_base'\nimport { DataSeriesEncodingKey } from '../codecs/dataSeriesTypes'\n\n/**\n * given a Buffer, read a string up to the first null character\n * @private\n */\nfunction readNullTerminatedString(buffer: Uint8Array) {\n let r = ''\n for (let i = 0; i < buffer.length && buffer[i] !== 0; i++) {\n r += String.fromCharCode(buffer[i]!)\n }\n return r\n}\n\n/**\n * parse a BAM tag's array value from a binary buffer\n * @private\n */\nfunction parseTagValueArray(buffer: Uint8Array) {\n const arrayType = String.fromCharCode(buffer[0]!)\n const length = Int32Array.from(buffer.slice(1))[0]!\n\n const array: number[] = new Array(length)\n buffer = buffer.slice(5)\n\n if (arrayType === 'c') {\n const arr = new Int8Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 'C') {\n const arr = new Uint8Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 's') {\n const arr = new Int16Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 'S') {\n const arr = new Uint16Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 'i') {\n const arr = new Int32Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 'I') {\n const arr = new Uint32Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else if (arrayType === 'f') {\n const arr = new Float32Array(buffer.buffer)\n for (let i = 0; i < length; i += 1) {\n array[i] = arr[i]!\n }\n } else {\n throw new Error(`unknown type: ${arrayType}`)\n }\n\n return array\n}\n\nfunction parseTagData(tagType: string, buffer: Uint8Array) {\n if (tagType === 'Z') {\n return readNullTerminatedString(buffer)\n }\n if (tagType === 'A') {\n return String.fromCharCode(buffer[0]!)\n }\n if (tagType === 'I') {\n return new Uint32Array(buffer.buffer)[0]\n }\n if (tagType === 'i') {\n return new Int32Array(buffer.buffer)[0]\n }\n if (tagType === 's') {\n return new Int16Array(buffer.buffer)[0]\n }\n if (tagType === 'S') {\n return new Uint16Array(buffer.buffer)[0]\n }\n if (tagType === 'c') {\n return new Int8Array(buffer.buffer)[0]\n }\n if (tagType === 'C') {\n return buffer[0]!\n }\n if (tagType === 'f') {\n return new Float32Array(buffer.buffer)[0]\n }\n if (tagType === 'H') {\n return Number.parseInt(\n readNullTerminatedString(buffer).replace(/^0x/, ''),\n 16,\n )\n }\n if (tagType === 'B') {\n return parseTagValueArray(buffer)\n }\n\n throw new CramMalformedError(`Unrecognized tag type ${tagType}`)\n}\n\nfunction decodeReadFeatures(\n alignmentStart: number,\n readFeatureCount: number,\n decodeDataSeries: any,\n compressionScheme: CramContainerCompressionScheme,\n majorVersion: number,\n) {\n let currentReadPos = 0\n let currentRefPos = alignmentStart - 1\n const readFeatures: ReadFeature[] = new Array(readFeatureCount)\n\n function decodeRFData([type, dataSeriesName]: readonly [\n type: string,\n dataSeriesName: string,\n ]) {\n const data = decodeDataSeries(dataSeriesName)\n if (type === 'character') {\n return String.fromCharCode(data)\n }\n if (type === 'string') {\n let r = ''\n for (let i = 0; i < data.byteLength; i++) {\n r += String.fromCharCode(data[i])\n }\n return r\n }\n if (type === 'numArray') {\n return data.toArray()\n }\n // else if (type === 'number') {\n // return data[0]\n // }\n return data\n }\n\n for (let i = 0; i < readFeatureCount; i += 1) {\n const code = String.fromCharCode(decodeDataSeries('FC'))\n\n const readPosDelta = decodeDataSeries('FP')\n\n // map of operator name -> data series name\n const data1Schema = {\n B: ['character', 'BA'] as const,\n S: ['string', majorVersion > 1 ? 'SC' : 'IN'] as const, // IN if cram v1, SC otherwise\n X: ['number', 'BS'] as const,\n D: ['number', 'DL'] as const,\n I: ['string', 'IN'] as const,\n i: ['character', 'BA'] as const,\n b: ['string', 'BB'] as const,\n q: ['numArray', 'QQ'] as const,\n Q: ['number', 'QS'] as const,\n H: ['number', 'HC'] as const,\n P: ['number', 'PD'] as const,\n N: ['number', 'RS'] as const,\n }[code]\n\n if (!data1Schema) {\n throw new CramMalformedError(`invalid read feature code \"${code}\"`)\n }\n\n let data = decodeRFData(data1Schema)\n\n // if this is a tag with two data items, make the data an array and add the second item\n const data2Schema = { B: ['number', 'QS'] as const }[code]\n if (data2Schema) {\n data = [data, decodeRFData(data2Schema)]\n }\n\n currentReadPos += readPosDelta\n const pos = currentReadPos\n\n currentRefPos += readPosDelta\n const refPos = currentRefPos\n\n // for gapping features, adjust the reference position for read features that follow\n if (code === 'D' || code === 'N') {\n currentRefPos += data\n } else if (code === 'I' || code === 'S') {\n currentRefPos -= data.length\n } else if (code === 'i') {\n currentRefPos -= 1\n }\n\n readFeatures[i] = { code, pos, refPos, data }\n }\n return readFeatures\n}\n\nexport type DataSeriesDecoder = <T extends DataSeriesEncodingKey>(\n dataSeriesName: T,\n) => DataTypeMapping[DataSeriesTypes[T]]\n\nexport default function decodeRecord(\n slice: CramSlice,\n decodeDataSeries: DataSeriesDecoder,\n compressionScheme: CramContainerCompressionScheme,\n sliceHeader: SliceHeader,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n majorVersion: number,\n recordNumber: number,\n) {\n let flags = decodeDataSeries('BF')\n\n // note: the C data type of compressionFlags is byte in cram v1\n // and int32 in cram v2+, but that does not matter for us here\n // in javascript land.\n const cramFlags = decodeDataSeries('CF')\n\n if (!isMappedSliceHeader(sliceHeader.parsedContent)) {\n throw new Error('slice header not mapped')\n }\n\n const sequenceId =\n majorVersion > 1 && sliceHeader.parsedContent.refSeqId === -2\n ? decodeDataSeries('RI')\n : sliceHeader.parsedContent.refSeqId\n\n const readLength = decodeDataSeries('RL')\n // if APDelta, will calculate the true start in a second pass\n let alignmentStart = decodeDataSeries('AP')\n if (compressionScheme.APdelta) {\n alignmentStart = alignmentStart + cursors.lastAlignmentStart\n }\n cursors.lastAlignmentStart = alignmentStart\n const readGroupId = decodeDataSeries('RG')\n\n let readName: string | undefined\n if (compressionScheme.readNamesIncluded) {\n readName = readNullTerminatedString(decodeDataSeries('RN'))\n }\n\n let mateToUse:\n | {\n mateFlags: number\n mateSequenceId: number\n mateAlignmentStart: number\n mateReadName: string | undefined\n }\n | undefined\n let templateSize: number | undefined\n let mateRecordNumber: number | undefined\n // mate record\n if (CramFlagsDecoder.isDetached(cramFlags)) {\n // note: the MF is a byte in 1.0, int32 in 2+, but once again this doesn't\n // matter for javascript\n const mateFlags = decodeDataSeries('MF')\n let mateReadName: string | undefined\n if (!compressionScheme.readNamesIncluded) {\n mateReadName = readNullTerminatedString(decodeDataSeries('RN'))\n readName = mateReadName\n }\n const mateSequenceId = decodeDataSeries('NS')\n const mateAlignmentStart = decodeDataSeries('NP')\n if (mateFlags || mateSequenceId > -1) {\n mateToUse = {\n mateFlags,\n mateSequenceId,\n mateAlignmentStart,\n mateReadName,\n }\n }\n\n templateSize = decodeDataSeries('TS')\n\n // set mate unmapped if needed\n if (MateFlagsDecoder.isUnmapped(mateFlags)) {\n flags = BamFlagsDecoder.setMateUnmapped(flags)\n }\n // set mate reversed if needed\n if (MateFlagsDecoder.isOnNegativeStrand(mateFlags)) {\n flags = BamFlagsDecoder.setMateReverseComplemented(flags)\n }\n\n // detachedCount++\n } else if (CramFlagsDecoder.isWithMateDownstream(cramFlags)) {\n mateRecordNumber = decodeDataSeries('NF') + recordNumber + 1\n }\n\n // TODO: the aux tag parsing will have to be refactored if we want to support\n // cram v1\n const TLindex = decodeDataSeries('TL')\n if (TLindex < 0) {\n /* TODO: check nTL: TLindex >= compressionHeader.tagEncoding.size */\n throw new CramMalformedError('invalid TL index')\n }\n\n const tags: Record<string, any> = {}\n // TN = tag names\n const TN = compressionScheme.getTagNames(TLindex)!\n const ntags = TN.length\n for (let i = 0; i < ntags; i += 1) {\n const tagId = TN[i]!\n const tagName = tagId.slice(0, 2)\n const tagType = tagId.slice(2, 3)\n\n const tagData = compressionScheme\n .getCodecForTag(tagId)\n .decode(slice, coreDataBlock, blocksByContentId, cursors)\n tags[tagName] =\n typeof tagData === 'number' ? tagData : parseTagData(tagType, tagData)\n }\n\n let readFeatures: ReadFeature[] | undefined\n let lengthOnRef: number | undefined\n let mappingQuality: number | undefined\n let qualityScores: number[] | undefined | null\n let readBases = undefined\n if (!BamFlagsDecoder.isSegmentUnmapped(flags)) {\n // reading read features\n const readFeatureCount = decodeDataSeries('FN')\n if (readFeatureCount) {\n readFeatures = decodeReadFeatures(\n alignmentStart,\n readFeatureCount,\n decodeDataSeries,\n compressionScheme,\n majorVersion,\n )\n }\n\n // compute the read's true span on the reference sequence, and the end\n // coordinate of the alignment on the reference\n lengthOnRef = readLength\n if (readFeatures) {\n for (const { code, data } of readFeatures) {\n if (code === 'D' || code === 'N') {\n lengthOnRef += data\n } else if (code === 'I' || code === 'S') {\n lengthOnRef = lengthOnRef - data.length\n } else if (code === 'i') {\n lengthOnRef = lengthOnRef - 1\n }\n }\n }\n if (Number.isNaN(lengthOnRef)) {\n console.warn(\n `${\n readName || `${sequenceId}:${alignmentStart}`\n } record has invalid read features`,\n )\n lengthOnRef = readLength\n }\n\n // mapping quality\n mappingQuality = decodeDataSeries('MQ')\n if (CramFlagsDecoder.isPreservingQualityScores(cramFlags)) {\n qualityScores = new Array(readLength)\n for (let i = 0; i < qualityScores.length; i++) {\n qualityScores[i] = decodeDataSeries('QS')\n }\n }\n } else if (CramFlagsDecoder.isDecodeSequenceAsStar(cramFlags)) {\n readBases = null\n qualityScores = null\n } else {\n const bases = new Array(readLength) as number[]\n for (let i = 0; i < bases.length; i += 1) {\n bases[i] = decodeDataSeries('BA')\n }\n readBases = String.fromCharCode(...bases)\n\n if (CramFlagsDecoder.isPreservingQualityScores(cramFlags)) {\n qualityScores = new Array(readLength)\n for (let i = 0; i < bases.length; i += 1) {\n qualityScores[i] = decodeDataSeries('QS')\n }\n }\n }\n\n return {\n readLength,\n sequenceId,\n cramFlags,\n flags,\n alignmentStart,\n readGroupId,\n readName,\n mateToUse,\n templateSize,\n mateRecordNumber,\n readFeatures,\n lengthOnRef,\n mappingQuality,\n qualityScores,\n readBases,\n tags,\n }\n}\n","import { CramArgumentError, CramMalformedError } from '../../errors'\nimport { parseItem, sequenceMD5, tinyMemoize } from '../util'\n\nimport Constants from '../constants'\nimport decodeRecord, { DataSeriesDecoder } from './decodeRecord'\nimport CramRecord from '../record'\nimport CramContainer from '../container'\nimport CramFile, { CramFileBlock } from '../file'\nimport {\n getSectionParsers,\n isMappedSliceHeader,\n MappedSliceHeader,\n UnmappedSliceHeader,\n} from '../sectionParsers'\nimport { CramBufferOverrunError } from '../codecs/getBits'\nimport { Cursors, DataTypeMapping } from '../codecs/_base'\nimport { DataSeriesEncodingKey } from '../codecs/dataSeriesTypes'\nimport { DataSeriesTypes } from '../container/compressionScheme'\n\nexport type SliceHeader = CramFileBlock & {\n parsedContent: MappedSliceHeader | UnmappedSliceHeader\n}\n\n/**\n * @private\n * Try to estimate the template length from a bunch of interrelated multi-segment reads.\n * @param {Array[CramRecord]} allRecords\n * @param {number} currentRecordNumber\n * @param {CramRecord} thisRecord\n */\nfunction calculateMultiSegmentMatedTemplateLength(\n allRecords: CramRecord[],\n currentRecordNumber: number,\n thisRecord: CramRecord,\n) {\n function getAllMatedRecords(startRecord: CramRecord) {\n const records = [startRecord]\n if (\n startRecord.mateRecordNumber !== undefined &&\n startRecord.mateRecordNumber >= 0\n ) {\n const mateRecord = allRecords[startRecord.mateRecordNumber]\n if (!mateRecord) {\n throw new CramMalformedError(\n 'intra-slice mate record not found, this file seems malformed',\n )\n }\n records.push(...getAllMatedRecords(mateRecord))\n }\n return records\n }\n\n const matedRecords = getAllMatedRecords(thisRecord)\n const starts = matedRecords.map(r => r.alignmentStart)\n const ends = matedRecords.map(r => r.alignmentStart + r.readLength - 1)\n const estimatedTemplateLength = Math.max(...ends) - Math.min(...starts) + 1\n if (estimatedTemplateLength >= 0) {\n matedRecords.forEach(r => {\n if (r.templateLength !== undefined) {\n throw new CramMalformedError(\n 'mate pair group has some members that have template lengths already, this file seems malformed',\n )\n }\n r.templateLength = estimatedTemplateLength\n })\n }\n}\n\n/**\n * @private\n * Attempt to calculate the `templateLength` for a pair of intra-slice paired reads.\n * Ported from htslib. Algorithm is imperfect.\n * @param {CramRecord} thisRecord\n * @param {CramRecord} mateRecord\n */\nfunction calculateIntraSliceMatePairTemplateLength(\n thisRecord: CramRecord,\n mateRecord: CramRecord,\n) {\n // this just estimates the template length by using the simple (non-gapped) end coordinate of each\n // read, because gapping in the alignment doesn't mean the template is longer or shorter\n const start = Math.min(thisRecord.alignmentStart, mateRecord.alignmentStart)\n const end = Math.max(\n thisRecord.alignmentStart + thisRecord.readLength - 1,\n mateRecord.alignmentStart + mateRecord.readLength - 1,\n )\n const lengthEstimate = end - start + 1\n thisRecord.templateLength = lengthEstimate\n mateRecord.templateLength = lengthEstimate\n}\n\n/**\n * @private establishes a mate-pair relationship between two records in the\n * same slice. CRAM compresses mate-pair relationships between records in the\n * same slice down into just one record having the index in the slice of its\n * mate\n */\nfunction associateIntraSliceMate(\n allRecords: CramRecord[],\n currentRecordNumber: number,\n thisRecord: CramRecord,\n mateRecord: CramRecord,\n) {\n const complicatedMultiSegment = !!(\n mateRecord.mate ||\n (mateRecord.mateRecordNumber !== undefined &&\n mateRecord.mateRecordNumber !== currentRecordNumber)\n )\n\n // Deal with lossy read names\n if (!thisRecord.readName) {\n thisRecord.readName = String(thisRecord.uniqueId)\n mateRecord.readName = thisRecord.readName\n }\n\n thisRecord.mate = {\n sequenceId: mateRecord.sequenceId,\n alignmentStart: mateRecord.alignmentStart,\n uniqueId: mateRecord.uniqueId,\n }\n if (mateRecord.readName) {\n thisRecord.mate.readName = mateRecord.readName\n }\n\n // the mate record might have its own mate pointer, if this is some kind of\n // multi-segment (more than paired) scheme, so only relate that one back to this one\n // if it does not have any other relationship\n if (!mateRecord.mate && mateRecord.mateRecordNumber === undefined) {\n mateRecord.mate = {\n sequenceId: thisRecord.sequenceId,\n alignmentStart: thisRecord.alignmentStart,\n uniqueId: thisRecord.uniqueId,\n }\n if (thisRecord.readName) {\n mateRecord.mate.readName = thisRecord.readName\n }\n }\n\n // make sure the proper flags and cramFlags are set on both records\n // paired\n thisRecord.flags |= Constants.BAM_FPAIRED\n\n // set mate unmapped if needed\n if (mateRecord.flags & Constants.BAM_FUNMAP) {\n thisRecord.flags |= Constants.BAM_FMUNMAP\n // thisRecord.templateLength = 0\n }\n if (thisRecord.flags & Constants.BAM_FUNMAP) {\n // thisRecord.templateLength = 0\n mateRecord.flags |= Constants.BAM_FMUNMAP\n }\n\n // set mate reversed if needed\n if (mateRecord.flags & Constants.BAM_FREVERSE) {\n thisRecord.flags |= Constants.BAM_FMREVERSE\n }\n if (thisRecord.flags & Constants.BAM_FREVERSE) {\n mateRecord.flags |= Constants.BAM_FMREVERSE\n }\n\n if (thisRecord.templateLength === undefined) {\n if (complicatedMultiSegment) {\n calculateMultiSegmentMatedTemplateLength(\n allRecords,\n currentRecordNumber,\n thisRecord,\n )\n } else {\n calculateIntraSliceMatePairTemplateLength(thisRecord, mateRecord)\n }\n }\n\n // delete this last because it's used by the\n // complicated template length estimation\n thisRecord.mateRecordNumber = undefined\n}\n\nexport default class CramSlice {\n private file: CramFile\n\n constructor(\n public container: CramContainer,\n public containerPosition: number,\n public sliceSize: number,\n ) {\n this.file = container.file\n }\n\n // memoize\n async getHeader() {\n // fetch and parse the slice header\n const { majorVersion } = await this.file.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n const containerHeader = await this.container.getHeader()\n if (!containerHeader) {\n throw new Error('no container header detected')\n }\n\n const header = await this.file.readBlock(\n containerHeader._endPosition + this.containerPosition,\n )\n if (header === undefined) {\n throw new Error('block header undefined')\n }\n if (header.contentType === 'MAPPED_SLICE_HEADER') {\n const content = parseItem(\n header.content,\n sectionParsers.cramMappedSliceHeader.parser,\n 0,\n containerHeader._endPosition,\n )\n return { ...header, parsedContent: content }\n } else if (header.contentType === 'UNMAPPED_SLICE_HEADER') {\n const content = parseItem(\n header.content,\n sectionParsers.cramUnmappedSliceHeader.parser,\n 0,\n containerHeader._endPosition,\n )\n return { ...header, parsedContent: content }\n } else {\n throw new CramMalformedError(\n `error reading slice header block, invalid content type ${header.contentType}`,\n )\n }\n }\n\n // memoize\n async getBlocks() {\n const header = await this.getHeader()\n // read all the blocks into memory and store them\n let blockPosition = header._endPosition\n const blocks: CramFileBlock[] = new Array(header.parsedContent.numBlocks)\n for (let i = 0; i < blocks.length; i++) {\n const block = await this.file.readBlock(blockPosition)\n if (block === undefined) {\n throw new Error('block undefined')\n }\n blocks[i] = block\n blockPosition = blocks[i]!._endPosition\n }\n\n return blocks\n }\n\n // no memoize\n async getCoreDataBlock() {\n const blocks = await this.getBlocks()\n return blocks[0]!\n }\n\n // memoize\n async _getBlocksContentIdIndex(): Promise<Record<number, CramFileBlock>> {\n const blocks = await this.getBlocks()\n const blocksByContentId: Record<number, CramFileBlock> = {}\n blocks.forEach(block => {\n if (block.contentType === 'EXTERNAL_DATA') {\n blocksByContentId[block.contentId] = block\n }\n })\n return blocksByContentId\n }\n\n async getBlockByContentId(id: number) {\n const blocksByContentId = await this._getBlocksContentIdIndex()\n return blocksByContentId[id]\n }\n\n async getReferenceRegion() {\n // read the slice header\n const sliceHeader = (await this.getHeader()).parsedContent\n if (!isMappedSliceHeader(sliceHeader)) {\n throw new Error('slice header not mapped')\n }\n\n if (sliceHeader.refSeqId < 0) {\n return undefined\n }\n\n const compressionScheme = await this.container.getCompressionScheme()\n if (compressionScheme === undefined) {\n throw new Error('compression scheme undefined')\n }\n\n if (sliceHeader.refBaseBlockId >= 0) {\n const refBlock = await this.getBlockByContentId(\n sliceHeader.refBaseBlockId,\n )\n if (!refBlock) {\n throw new CramMalformedError(\n 'embedded reference specified, but reference block does not exist',\n )\n }\n\n // TODO: we do not read anything named 'span'\n // if (sliceHeader.span > refBlock.uncompressedSize) {\n // throw new CramMalformedError('Embedded reference is too small')\n // }\n\n // TODO verify\n return {\n seq: (refBlock as any).data.toString('utf8'),\n start: sliceHeader.refSeqStart,\n end: sliceHeader.refSeqStart + sliceHeader.refSeqSpan - 1,\n span: sliceHeader.refSeqSpan,\n }\n }\n if (\n compressionScheme.referenceRequired ||\n this.file.fetchReferenceSequenceCallback\n ) {\n if (!this.file.fetchReferenceSequenceCallback) {\n throw new Error(\n 'reference sequence not embedded, and seqFetch callback not provided, cannot fetch reference sequence',\n )\n }\n\n const seq = await this.file.fetchReferenceSequenceCallback(\n sliceHeader.refSeqId,\n sliceHeader.refSeqStart,\n sliceHeader.refSeqStart + sliceHeader.refSeqSpan - 1,\n )\n\n if (seq.length !== sliceHeader.refSeqSpan) {\n throw new CramArgumentError(\n 'seqFetch callback returned a reference sequence of the wrong length',\n )\n }\n\n return {\n seq,\n start: sliceHeader.refSeqStart,\n end: sliceHeader.refSeqStart + sliceHeader.refSeqSpan - 1,\n span: sliceHeader.refSeqSpan,\n }\n }\n\n return undefined\n }\n\n getAllRecords() {\n return this.getRecords(() => true)\n }\n\n async _fetchRecords() {\n const { majorVersion } = await this.file.getDefinition()\n\n const compressionScheme = await this.container.getCompressionScheme()\n if (compressionScheme === undefined) {\n throw new Error('compression scheme undefined')\n }\n\n const sliceHeader = await this.getHeader()\n const blocksByContentId = await this._getBlocksContentIdIndex()\n\n // check MD5 of reference if available\n if (\n majorVersion > 1 &&\n this.file.options.checkSequenceMD5 &&\n isMappedSliceHeader(sliceHeader.parsedContent) &&\n sliceHeader.parsedContent.refSeqId >= 0 &&\n sliceHeader.parsedContent.md5?.join('') !== '0000000000000000'\n ) {\n const refRegion = await this.getReferenceRegion()\n if (refRegion) {\n const { seq, start, end } = refRegion\n const seqMd5 = sequenceMD5(seq)\n const storedMd5 = sliceHeader.parsedContent.md5\n ?.map(byte => (byte < 16 ? '0' : '') + byte.toString(16))\n .join('')\n if (seqMd5 !== storedMd5) {\n throw new CramMalformedError(\n `MD5 checksum reference mismatch for ref ${sliceHeader.parsedContent.refSeqId} pos ${start}..${end}. recorded MD5: ${storedMd5}, calculated MD5: ${seqMd5}`,\n )\n }\n }\n }\n\n // tracks the read position within the block. codec.decode() methods\n // advance the byte and bit positions in the cursor as they decode\n // data note that we are only decoding a single block here, the core\n // data block\n const coreDataBlock = await this.getCoreDataBlock()\n const cursors: Cursors = {\n lastAlignmentStart: isMappedSliceHeader(sliceHeader.parsedContent)\n ? sliceHeader.parsedContent.refSeqStart\n : 0,\n coreBlock: { bitPosition: 7, bytePosition: 0 },\n externalBlocks: {\n map: new Map(),\n getCursor(contentId: number) {\n let r = this.map.get(contentId)\n if (r === undefined) {\n r = { bitPosition: 7, bytePosition: 0 }\n this.map.set(contentId, r)\n }\n return r\n },\n },\n }\n\n const decodeDataSeries: DataSeriesDecoder = <\n T extends DataSeriesEncodingKey,\n >(\n dataSeriesName: T,\n ): DataTypeMapping[DataSeriesTypes[T]] => {\n const codec = compressionScheme.getCodecForDataSeries(dataSeriesName)\n if (!codec) {\n throw new CramMalformedError(\n `no codec defined for ${dataSeriesName} data series`,\n )\n }\n // console.log(dataSeriesName, Object.getPrototypeOf(codec))\n const decoded = codec.decode(\n this,\n coreDataBlock,\n blocksByContentId,\n cursors,\n )\n return decoded\n }\n const records: CramRecord[] = new Array(\n sliceHeader.parsedContent.numRecords,\n )\n for (let i = 0; i < records.length; i += 1) {\n try {\n const init = decodeRecord(\n this,\n decodeDataSeries,\n compressionScheme,\n sliceHeader,\n coreDataBlock,\n blocksByContentId,\n cursors,\n majorVersion,\n i,\n )\n records[i] = new CramRecord({\n ...init,\n uniqueId:\n sliceHeader.contentPosition +\n sliceHeader.parsedContent.recordCounter +\n i +\n 1,\n })\n } catch (e) {\n if (e instanceof CramBufferOverrunError) {\n console.warn(\n 'read attempted beyond end of buffer, file seems truncated.',\n )\n break\n } else {\n throw e\n }\n }\n }\n\n // interpret `recordsToNextFragment` attributes to make standard `mate`\n // objects Resolve mate pair cross-references between records in this slice\n for (let i = 0; i < records.length; i += 1) {\n const { mateRecordNumber } = records[i]!\n if (mateRecordNumber !== undefined && mateRecordNumber >= 0) {\n associateIntraSliceMate(\n records,\n i,\n records[i]!,\n records[mateRecordNumber]!,\n )\n }\n }\n\n return records\n }\n\n async getRecords(filterFunction: (r: CramRecord) => boolean) {\n // fetch the features if necessary, using the file-level feature cache\n const cacheKey = this.container.filePosition + this.containerPosition\n let recordsPromise = this.file.featureCache.get(cacheKey.toString())\n if (!recordsPromise) {\n recordsPromise = this._fetchRecords()\n this.file.featureCache.set(cacheKey.toString(), recordsPromise)\n }\n\n const unfiltered = await recordsPromise\n const records = unfiltered.filter(filterFunction)\n\n // if we can fetch reference sequence, add the reference sequence to the records\n if (records.length && this.file.fetchReferenceSequenceCallback) {\n const sliceHeader = await this.getHeader()\n if (\n isMappedSliceHeader(sliceHeader.parsedContent) &&\n (sliceHeader.parsedContent.refSeqId >= 0 || // single-ref slice\n sliceHeader.parsedContent.refSeqId === -2) // multi-ref slice\n ) {\n const singleRefId =\n sliceHeader.parsedContent.refSeqId >= 0\n ? sliceHeader.parsedContent.refSeqId\n : undefined\n const compressionScheme = await this.container.getCompressionScheme()\n if (compressionScheme === undefined) {\n throw new Error('compression scheme undefined')\n }\n const refRegions: Record<\n string,\n { id: number; start: number; end: number; seq: string | null }\n > = {}\n\n // iterate over the records to find the spans of the reference\n // sequences we need to fetch\n for (const record of records) {\n const seqId =\n singleRefId !== undefined ? singleRefId : record.sequenceId\n let refRegion = refRegions[seqId]\n if (!refRegion) {\n refRegion = {\n id: seqId,\n start: record.alignmentStart,\n end: Number.NEGATIVE_INFINITY,\n seq: null,\n }\n refRegions[seqId] = refRegion\n }\n\n const end =\n record.alignmentStart +\n (record.lengthOnRef || record.readLength) -\n 1\n if (end > refRegion.end) {\n refRegion.end = end\n }\n if (record.alignmentStart < refRegion.start) {\n refRegion.start = record.alignmentStart\n }\n }\n\n // fetch the `seq` for all of the ref regions\n await Promise.all(\n Object.values(refRegions).map(async refRegion => {\n if (\n refRegion.id !== -1 &&\n refRegion.start <= refRegion.end &&\n this.file.fetchReferenceSequenceCallback\n ) {\n refRegion.seq = await this.file.fetchReferenceSequenceCallback(\n refRegion.id,\n refRegion.start,\n refRegion.end,\n )\n }\n }),\n )\n\n // now decorate all the records with them\n for (const record of records) {\n const seqId =\n singleRefId !== undefined ? singleRefId : record.sequenceId\n const refRegion = refRegions[seqId]\n if (refRegion?.seq) {\n const seq = refRegion.seq\n record.addReferenceSequence(\n { ...refRegion, seq },\n compressionScheme,\n )\n }\n }\n }\n }\n\n return records\n }\n}\n\n// memoize several methods in the class for performance\n'getHeader getBlocks _getBlocksContentIdIndex'.split(' ').forEach(method => {\n tinyMemoize(CramSlice, method)\n})\n","import CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { DataType } from './dataSeriesTypes'\n\nexport interface DataTypeMapping {\n byte: number\n int: number\n long: number\n byteArray: Uint8Array\n}\n\nexport interface Cursor {\n bitPosition: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7\n bytePosition: number\n}\n\nexport interface Cursors {\n lastAlignmentStart: number\n coreBlock: Cursor\n externalBlocks: {\n map: Map<any, any>\n getCursor: (contentId: number) => Cursor\n }\n}\n\n// codec base class\nexport default abstract class CramCodec<\n TResult extends DataType = DataType,\n TParameters = unknown,\n> {\n public parameters: TParameters\n public dataType: DataType\n\n constructor(parameters: TParameters, dataType: TResult) {\n this.parameters = parameters\n this.dataType = dataType\n }\n\n abstract decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ): DataTypeMapping[TResult]\n}\n","import CramCodec, { Cursors } from './_base'\nimport { ByteArrayLengthEncoding, CramEncoding } from '../encoding'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { DataType } from './dataSeriesTypes'\nimport { tinyMemoize } from '../util'\n\ntype CramCodecFactory = <TData extends DataType = DataType>(\n encodingData: CramEncoding,\n dataType: TData | 'ignore',\n) => CramCodec<TData>\n\nexport default class ByteArrayStopCodec extends CramCodec<\n 'byteArray',\n ByteArrayLengthEncoding['parameters']\n> {\n private instantiateCodec: CramCodecFactory\n\n constructor(\n parameters: ByteArrayLengthEncoding['parameters'],\n dataType: 'byteArray',\n instantiateCodec: CramCodecFactory,\n ) {\n super(parameters, dataType)\n this.instantiateCodec = instantiateCodec\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n const lengthCodec = this._getLengthCodec()\n const arrayLength = lengthCodec.decode(\n slice,\n coreDataBlock,\n blocksByContentId,\n cursors,\n )\n\n const dataCodec = this._getDataCodec()\n const data = new Uint8Array(arrayLength)\n for (let i = 0; i < arrayLength; i += 1) {\n data[i] = dataCodec.decode(\n slice,\n coreDataBlock,\n blocksByContentId,\n cursors,\n )\n }\n\n return data\n }\n\n // memoize\n _getLengthCodec() {\n const encodingParams = this.parameters.lengthsEncoding\n return this.instantiateCodec(encodingParams, 'int')\n }\n\n // memoize\n _getDataCodec() {\n const encodingParams = this.parameters.valuesEncoding\n return this.instantiateCodec(encodingParams, 'byte')\n }\n}\n\n'_getLengthCodec _getDataCodec'.split(' ').forEach(method => {\n tinyMemoize(ByteArrayStopCodec, method)\n})\n","import { CramUnimplementedError } from '../../errors'\n\nimport HuffmanIntCodec from './huffman'\nimport ExternalCodec from './external'\nimport ByteArrayStopCodec from './byteArrayStop'\nimport ByteArrayLengthCodec from './byteArrayLength'\nimport BetaCodec from './beta'\nimport GammaCodec from './gamma'\nimport SubexpCodec from './subexp'\nimport CramCodec from './_base'\nimport { CramEncoding } from '../encoding'\nimport { DataType } from './dataSeriesTypes'\n\nconst codecClasses = {\n 1: ExternalCodec,\n // 2: GolombCodec,\n 3: HuffmanIntCodec,\n 4: ByteArrayLengthCodec,\n 5: ByteArrayStopCodec,\n 6: BetaCodec,\n 7: SubexpCodec,\n // 8: GolombRiceCodec,\n 9: GammaCodec,\n}\n\nfunction getCodecClassWithId(id: number) {\n return (codecClasses as any)[id]\n}\n\nexport function instantiateCodec<TResult extends DataType = DataType>(\n encodingData: CramEncoding,\n dataType: DataType | 'ignore',\n): CramCodec<TResult> {\n const CodecClass = getCodecClassWithId(\n dataType === 'ignore' ? 0 : encodingData.codecId,\n )\n if (!CodecClass) {\n throw new CramUnimplementedError(\n `no codec implemented for codec ID ${encodingData.codecId}`,\n )\n }\n\n return new CodecClass(encodingData.parameters, dataType, instantiateCodec)\n}\n","import { CramMalformedError, CramUnimplementedError } from '../../errors'\nimport CramCodec, { Cursor, Cursors } from './_base'\nimport { parseItf8 } from '../util'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { CramBufferOverrunError } from './getBits'\nimport { ExternalCramEncoding } from '../encoding'\n\nexport default class ExternalCodec extends CramCodec<\n 'int' | 'byte',\n ExternalCramEncoding['parameters']\n> {\n private readonly _decodeData: (\n contentBlock: CramFileBlock,\n cursor: Cursor,\n ) => number\n\n constructor(\n parameters: ExternalCramEncoding['parameters'],\n dataType: 'int' | 'byte',\n ) {\n super(parameters, dataType)\n if (this.dataType === 'int') {\n this._decodeData = this._decodeInt\n } else if (this.dataType === 'byte') {\n this._decodeData = this._decodeByte\n } else {\n throw new CramUnimplementedError(\n `${this.dataType} decoding not yet implemented by EXTERNAL codec`,\n )\n }\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n const { blockContentId } = this.parameters\n const contentBlock = blocksByContentId[blockContentId]\n if (!contentBlock) {\n throw new CramMalformedError(\n `no block found with content ID ${blockContentId}}`,\n )\n }\n const cursor = cursors.externalBlocks.getCursor(blockContentId)\n return this._decodeData(contentBlock, cursor)\n }\n\n _decodeInt(contentBlock: CramFileBlock, cursor: Cursor) {\n const [result, bytesRead] = parseItf8(\n contentBlock.content,\n cursor.bytePosition,\n )\n cursor.bytePosition = cursor.bytePosition + bytesRead\n return result\n }\n\n _decodeByte(contentBlock: CramFileBlock, cursor: Cursor) {\n if (cursor.bytePosition >= contentBlock.content.length) {\n throw new CramBufferOverrunError(\n 'attempted to read beyond end of block. this file seems truncated.',\n )\n }\n return contentBlock.content[cursor.bytePosition++]!\n }\n}\n","import { CramMalformedError } from '../../errors'\nimport CramCodec, { Cursor, Cursors } from './_base'\nimport { getBits } from './getBits'\nimport { HuffmanEncoding } from '../encoding'\n\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\n\nfunction numberOfSetBits(ii: number) {\n let i = (ii - (ii >> 1)) & 0x55555555\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333)\n return (((i + (i >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24\n}\n\ninterface Code {\n bitLength: number\n value: number\n bitCode: number\n}\n\nexport default class HuffmanIntCodec extends CramCodec<\n 'byte' | 'int',\n HuffmanEncoding['parameters']\n> {\n private codes: Record<number, Code> = {}\n private codeBook: Record<number, number[]> = {}\n private sortedCodes: Code[] = []\n private sortedValuesByBitCode: number[] = []\n private sortedBitCodes: number[] = []\n private sortedBitLengthsByBitCode: number[] = []\n private bitCodeToValue: number[] = []\n\n constructor(\n parameters: HuffmanEncoding['parameters'],\n dataType: 'byte' | 'int',\n ) {\n super(parameters, dataType)\n if (!['byte', 'int'].includes(this.dataType)) {\n throw new TypeError(\n `${this.dataType} decoding not yet implemented by HUFFMAN_INT codec`,\n )\n }\n\n this.buildCodeBook()\n this.buildCodes()\n this.buildCaches()\n\n // if this is a degenerate zero-length huffman code, special-case the\n // decoding\n if (this.sortedCodes[0]!.bitLength === 0) {\n this._decode = this._decodeZeroLengthCode\n }\n }\n\n buildCodeBook() {\n // parse the parameters together into a `codes` data structure\n let codes = new Array<{ symbol: number; bitLength: number }>(\n this.parameters.numCodes,\n )\n for (let i = 0; i < this.parameters.numCodes; i++) {\n codes[i] = {\n symbol: this.parameters.symbols[i]!,\n bitLength: this.parameters.bitLengths[i]!,\n }\n }\n // sort the codes by bit length and symbol value\n codes = codes.sort(\n (a, b) => a.bitLength - b.bitLength || a.symbol - b.symbol,\n )\n\n this.codeBook = {}\n codes.forEach(code => {\n if (!this.codeBook[code.bitLength]) {\n this.codeBook[code.bitLength] = []\n }\n this.codeBook[code.bitLength]!.push(code.symbol)\n })\n }\n\n buildCodes() {\n this.codes = {} /* new TreeMap<Integer, HuffmanBitCode>(); */\n let codeLength = 0\n let codeValue = -1\n Object.entries(this.codeBook).forEach(([bitLength, symbols]) => {\n const bitLengthInt = Number.parseInt(bitLength, 10)\n symbols.forEach(symbol => {\n const code = {\n bitLength: bitLengthInt,\n value: symbol,\n bitCode: 0,\n }\n codeValue = codeValue + 1\n const delta = bitLengthInt - codeLength // new length?\n codeValue = codeValue << delta // pad with 0's\n code.bitCode = codeValue // calculated: huffman code\n codeLength = codeLength + delta // adjust current code length\n\n if (numberOfSetBits(codeValue) > bitLengthInt) {\n throw new CramMalformedError('Symbol out of range')\n }\n\n this.codes[symbol] = code\n })\n })\n }\n\n buildCaches() {\n this.sortedCodes = Object.values(this.codes).sort(\n (a, b) => a.bitLength - b.bitLength || a.bitCode - b.bitCode,\n )\n\n this.sortedValuesByBitCode = this.sortedCodes.map(c => c.value)\n this.sortedBitCodes = this.sortedCodes.map(c => c.bitCode)\n this.sortedBitLengthsByBitCode = this.sortedCodes.map(c => c.bitLength)\n const maxBitCode = Math.max(...this.sortedBitCodes)\n\n this.bitCodeToValue = new Array(maxBitCode + 1).fill(-1)\n for (let i = 0; i < this.sortedBitCodes.length; i += 1) {\n this.bitCodeToValue[this.sortedCodes[i]!.bitCode] = i\n }\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n return this._decode(slice, coreDataBlock, cursors.coreBlock)\n }\n\n // _decodeNull() {\n // return -1\n // }\n\n // the special case for zero-length codes\n _decodeZeroLengthCode() {\n return this.sortedCodes[0]!.value\n }\n\n _decode(slice: CramSlice, coreDataBlock: CramFileBlock, coreCursor: Cursor) {\n const input = coreDataBlock.content\n\n let prevLen = 0\n let bits = 0\n for (let i = 0; i < this.sortedCodes.length; i += 1) {\n const length = this.sortedCodes[i]!.bitLength\n bits <<= length - prevLen\n bits |= getBits(input, coreCursor, length - prevLen)\n prevLen = length\n {\n const index = this.bitCodeToValue[bits]!\n if (index > -1 && this.sortedBitLengthsByBitCode[index] === length) {\n return this.sortedValuesByBitCode[index]!\n }\n\n for (\n let j = i;\n this.sortedCodes[j + 1]!.bitLength === length &&\n j < this.sortedCodes.length;\n j += 1\n ) {\n i += 1\n }\n }\n }\n throw new CramMalformedError('Huffman symbol not found.')\n }\n}\n","import { CramMalformedError } from '../../errors'\n\nimport CramCodec, { Cursor, Cursors } from './_base'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { ByteArrayStopCramEncoding } from '../encoding'\nimport { CramBufferOverrunError } from './getBits'\n\nexport default class ByteArrayStopCodec extends CramCodec<\n 'byteArray',\n ByteArrayStopCramEncoding['parameters']\n> {\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n const { blockContentId } = this.parameters\n const contentBlock = blocksByContentId[blockContentId]\n if (!contentBlock) {\n throw new CramMalformedError(\n `no block found with content ID ${blockContentId}`,\n )\n }\n const cursor = cursors.externalBlocks.getCursor(blockContentId)\n return this._decodeByteArray(contentBlock, cursor)\n }\n\n _decodeByteArray(contentBlock: CramFileBlock, cursor: Cursor) {\n const dataBuffer = contentBlock.content\n const { stopByte } = this.parameters\n // scan to the next stop byte\n const startPosition = cursor.bytePosition\n let stopPosition = cursor.bytePosition\n while (\n dataBuffer[stopPosition] !== stopByte &&\n stopPosition < dataBuffer.length\n ) {\n if (stopPosition === dataBuffer.length) {\n throw new CramBufferOverrunError(\n 'byteArrayStop reading beyond length of data buffer?',\n )\n }\n stopPosition = stopPosition + 1\n }\n cursor.bytePosition = stopPosition + 1\n return dataBuffer.subarray(startPosition, stopPosition)\n }\n}\n","import { CramUnimplementedError } from '../../errors'\nimport CramCodec, { Cursors } from './_base'\nimport { getBits } from './getBits'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { BetaEncoding } from '../encoding'\n\nexport default class BetaCodec extends CramCodec<\n 'int',\n BetaEncoding['parameters']\n> {\n constructor(parameters: BetaEncoding['parameters'], dataType: 'int') {\n super(parameters, dataType)\n if (this.dataType !== 'int') {\n throw new CramUnimplementedError(\n `${this.dataType} decoding not yet implemented by BETA codec`,\n )\n }\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n const fromBits = getBits(\n coreDataBlock.content,\n cursors.coreBlock,\n this.parameters.length,\n )\n return fromBits - this.parameters.offset\n }\n}\n","import { CramUnimplementedError } from '../../errors'\nimport CramCodec, { Cursors } from './_base'\nimport { getBits } from './getBits'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\nimport { SubexpEncoding } from '../encoding'\n\nexport default class SubexpCodec extends CramCodec<\n 'int',\n SubexpEncoding['parameters']\n> {\n constructor(parameters: SubexpEncoding['parameters'], dataType: 'int') {\n super(parameters, dataType)\n if (this.dataType !== 'int') {\n throw new CramUnimplementedError(\n `${this.dataType} decoding not yet implemented by SUBEXP codec`,\n )\n }\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n let numLeadingOnes = 0\n while (getBits(coreDataBlock.content, cursors.coreBlock, 1)) {\n numLeadingOnes = numLeadingOnes + 1\n }\n\n let b: number\n let n: number\n if (numLeadingOnes === 0) {\n b = this.parameters.K\n n = getBits(coreDataBlock.content, cursors.coreBlock, b)\n } else {\n b = numLeadingOnes + this.parameters.K - 1\n const bits = getBits(coreDataBlock.content, cursors.coreBlock, b)\n n = (1 << b) | bits\n }\n\n return n - this.parameters.offset\n }\n}\n","import { CramUnimplementedError } from '../../errors'\nimport CramCodec, { Cursors } from './_base'\nimport { getBits } from './getBits'\nimport { GammaEncoding } from '../encoding'\nimport CramSlice from '../slice'\nimport { CramFileBlock } from '../file'\n\nexport default class GammaCodec extends CramCodec<\n 'int',\n GammaEncoding['parameters']\n> {\n constructor(parameters: GammaEncoding['parameters'], dataType: 'int') {\n super(parameters, dataType)\n if (this.dataType !== 'int') {\n throw new CramUnimplementedError(\n `${this.dataType} decoding not yet implemented by GAMMA codec`,\n )\n }\n }\n\n decode(\n slice: CramSlice,\n coreDataBlock: CramFileBlock,\n blocksByContentId: Record<number, CramFileBlock>,\n cursors: Cursors,\n ) {\n let length = 1\n\n while (getBits(coreDataBlock.content, cursors.coreBlock, 1) === 0) {\n length = length + 1\n }\n\n const readBits = getBits(\n coreDataBlock.content,\n cursors.coreBlock,\n length - 1,\n )\n\n const value = readBits | (1 << (length - 1))\n return value - this.parameters.offset\n }\n}\n","import { instantiateCodec } from '../codecs'\nimport CramCodec from '../codecs/_base'\nimport { CramCompressionHeader } from '../sectionParsers'\nimport { CramEncoding } from '../encoding'\nimport { CramMalformedError } from '../../errors'\nimport {\n DataSeriesEncodingKey,\n DataSeriesEncodingMap,\n} from '../codecs/dataSeriesTypes'\n\n// the hardcoded data type to be decoded for each core\n// data field\nconst dataSeriesTypes = {\n BF: 'int',\n CF: 'int',\n RI: 'int',\n RL: 'int',\n AP: 'int',\n RG: 'int',\n MF: 'int',\n NS: 'int',\n NP: 'int',\n TS: 'int',\n NF: 'int',\n TC: 'byte',\n TN: 'int',\n FN: 'int',\n FC: 'byte',\n FP: 'int',\n BS: 'byte',\n IN: 'byteArray',\n SC: 'byteArray',\n DL: 'int',\n BA: 'byte',\n BB: 'byteArray',\n RS: 'int',\n PD: 'int',\n HC: 'int',\n MQ: 'int',\n RN: 'byteArray',\n QS: 'byte',\n QQ: 'byteArray',\n TL: 'int',\n // TM: 'ignore',\n // TV: 'ignore',\n} as const\n\nexport type DataSeriesTypes = typeof dataSeriesTypes\n\nfunction parseSubstitutionMatrix(byteArray: number[]) {\n const matrix: string[][] = new Array(5)\n for (let i = 0; i < 5; i += 1) {\n matrix[i] = new Array(4)\n }\n\n matrix[0]![(byteArray[0]! >> 6) & 3] = 'C'\n matrix[0]![(byteArray[0]! >> 4) & 3] = 'G'\n matrix[0]![(byteArray[0]! >> 2) & 3] = 'T'\n matrix[0]![(byteArray[0]! >> 0) & 3] = 'N'\n\n matrix[1]![(byteArray[1]! >> 6) & 3] = 'A'\n matrix[1]![(byteArray[1]! >> 4) & 3] = 'G'\n matrix[1]![(byteArray[1]! >> 2) & 3] = 'T'\n matrix[1]![(byteArray[1]! >> 0) & 3] = 'N'\n\n matrix[2]![(byteArray[2]! >> 6) & 3] = 'A'\n matrix[2]![(byteArray[2]! >> 4) & 3] = 'C'\n matrix[2]![(byteArray[2]! >> 2) & 3] = 'T'\n matrix[2]![(byteArray[2]! >> 0) & 3] = 'N'\n\n matrix[3]![(byteArray[3]! >> 6) & 3] = 'A'\n matrix[3]![(byteArray[3]! >> 4) & 3] = 'C'\n matrix[3]![(byteArray[3]! >> 2) & 3] = 'G'\n matrix[3]![(byteArray[3]! >> 0) & 3] = 'N'\n\n matrix[4]![(byteArray[4]! >> 6) & 3] = 'A'\n matrix[4]![(byteArray[4]! >> 4) & 3] = 'C'\n matrix[4]![(byteArray[4]! >> 2) & 3] = 'G'\n matrix[4]![(byteArray[4]! >> 0) & 3] = 'T'\n\n return matrix\n}\n\ntype DataSeriesCache = {\n [K in DataSeriesEncodingKey]?: CramCodec<DataSeriesTypes[K]>\n}\n\nexport default class CramContainerCompressionScheme {\n public readNamesIncluded: boolean\n public APdelta: boolean\n public referenceRequired: boolean\n public tagIdsDictionary: Record<number, string[]>\n public substitutionMatrix: string[][]\n public dataSeriesCodecCache: DataSeriesCache = {}\n public tagCodecCache: Record<string, CramCodec> = {}\n public tagEncoding: Record<string, CramEncoding> = {}\n public dataSeriesEncoding: DataSeriesEncodingMap\n\n constructor(content: CramCompressionHeader) {\n // interpret some of the preservation map tags for convenient use\n this.readNamesIncluded = content.preservation.RN\n this.APdelta = content.preservation.AP\n this.referenceRequired = !!content.preservation.RR\n this.tagIdsDictionary = content.preservation.TD\n this.substitutionMatrix = parseSubstitutionMatrix(content.preservation.SM)\n this.dataSeriesEncoding = content.dataSeriesEncoding\n this.tagEncoding = content.tagEncoding\n }\n\n /**\n * @param {string} tagName three-character tag name\n * @private\n */\n getCodecForTag(tagName: string): CramCodec {\n const test = this.tagCodecCache[tagName]\n if (!test) {\n const encodingData = this.tagEncoding[tagName]\n if (!encodingData) {\n throw new Error('Error, no tag encoding')\n }\n const ret = instantiateCodec(\n encodingData,\n 'byteArray', // all tags are byte array data\n )\n this.tagCodecCache[tagName] = ret\n return ret\n } else {\n return test\n }\n }\n\n /**\n *\n * @param {number} tagListId ID of the tag list to fetch from the tag dictionary\n * @private\n */\n getTagNames(tagListId: number) {\n return this.tagIdsDictionary[tagListId]\n }\n\n getCodecForDataSeries<TDataSeries extends DataSeriesEncodingKey>(\n dataSeriesName: TDataSeries,\n ): CramCodec<DataSeriesTypes[TDataSeries]> | undefined {\n let r: CramCodec<DataSeriesTypes[TDataSeries]> | undefined =\n this.dataSeriesCodecCache[dataSeriesName]\n if (r === undefined) {\n const encodingData = this.dataSeriesEncoding[dataSeriesName]\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (encodingData) {\n const dataType = dataSeriesTypes[dataSeriesName]\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!dataType) {\n throw new CramMalformedError(\n `data series name ${dataSeriesName} not defined in file compression header`,\n )\n }\n r = instantiateCodec(encodingData, dataType)\n // didn't find a way to make TS understand this\n this.dataSeriesCodecCache[dataSeriesName] = r as CramCodec<any>\n }\n }\n return r\n }\n\n toJSON() {\n const data: any = {}\n Object.keys(this).forEach(k => {\n if (k.endsWith('Cache')) {\n return\n }\n data[k] = (this as any)[k]\n })\n return data\n }\n}\n","import { Buffer } from 'buffer'\nimport { CramMalformedError } from '../../errors'\n// locals\nimport { itf8Size, parseItem, tinyMemoize } from '../util'\nimport CramSlice from '../slice'\nimport CramContainerCompressionScheme from './compressionScheme'\nimport CramFile from '../file'\nimport { getSectionParsers } from '../sectionParsers'\n\nexport default class CramContainer {\n constructor(\n public file: CramFile,\n public filePosition: number,\n ) {}\n\n getHeader() {\n return this._readContainerHeader(this.filePosition)\n }\n\n async getCompressionHeaderBlock() {\n const containerHeader = await this.getHeader()\n\n // if there are no records in the container, there will be no compression\n // header\n if (!containerHeader?.numRecords) {\n return null\n }\n const { majorVersion } = await this.file.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n\n const block = await this.getFirstBlock()\n if (block === undefined) {\n return undefined\n }\n if (block.contentType !== 'COMPRESSION_HEADER') {\n throw new CramMalformedError(\n `invalid content type ${block.contentType} in compression header block`,\n )\n }\n\n const content = parseItem(\n block.content,\n sectionParsers.cramCompressionHeader.parser,\n 0,\n block.contentPosition,\n )\n return {\n ...block,\n parsedContent: content,\n }\n }\n\n async getFirstBlock() {\n const containerHeader = await this.getHeader()\n if (!containerHeader) {\n return undefined\n }\n return this.file.readBlock(containerHeader._endPosition)\n }\n\n // parses the compression header data into a CramContainerCompressionScheme\n // object\n async getCompressionScheme() {\n const header = await this.getCompressionHeaderBlock()\n if (!header) {\n return undefined\n }\n\n return new CramContainerCompressionScheme(header.parsedContent)\n }\n\n getSlice(slicePosition: number, sliceSize: number) {\n // note: slicePosition is relative to the end of the container header\n // TODO: perhaps we should cache slices?\n return new CramSlice(this, slicePosition, sliceSize)\n }\n\n async _readContainerHeader(position: number) {\n const { majorVersion } = await this.file.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n const { cramContainerHeader1, cramContainerHeader2 } = sectionParsers\n const { size: fileSize } = await this.file.stat()\n\n if (position >= fileSize) {\n console.warn(`pos:${position}>=fileSize:${fileSize} in cram container`)\n return undefined\n }\n\n // parse the container header. do it in 2 pieces because you cannot tell\n // how much to buffer until you read numLandmarks\n const bytes1 = Buffer.allocUnsafe(cramContainerHeader1.maxLength)\n await this.file.read(bytes1, 0, cramContainerHeader1.maxLength, position)\n const header1 = parseItem(bytes1, cramContainerHeader1.parser)\n const numLandmarksSize = itf8Size(header1.numLandmarks)\n if (position + header1.length >= fileSize) {\n // header indicates container goes beyond fileSize\n console.warn(\n `container at ${position} is beyond fileSize:${fileSize}, skipping`,\n )\n return undefined\n }\n const bytes2 = Buffer.allocUnsafe(\n cramContainerHeader2.maxLength(header1.numLandmarks),\n )\n await this.file.read(\n bytes2,\n 0,\n cramContainerHeader2.maxLength(header1.numLandmarks),\n position + header1._size - numLandmarksSize,\n )\n const header2 = parseItem(bytes2, cramContainerHeader2.parser)\n\n if (this.file.validateChecksums && header2.crc32 !== undefined) {\n await this.file.checkCrc32(\n position,\n header1._size + header2._size - numLandmarksSize - 4,\n header2.crc32,\n `container header beginning at position ${position}`,\n )\n }\n\n const completeHeader = Object.assign(header1, header2, {\n _size: header1._size + header2._size - numLandmarksSize,\n _endPosition: header1._size + header2._size - numLandmarksSize + position,\n })\n\n return completeHeader\n }\n}\n\n'getHeader getCompressionHeaderBlock getCompressionScheme'\n .split(' ')\n .forEach(method => {\n tinyMemoize(CramContainer, method)\n })\n","import { Filehandle } from '../cramFile/filehandle'\nimport { LocalFile, RemoteFile } from 'generic-filehandle'\n\nfunction open(\n maybeUrl?: string,\n maybePath?: string,\n maybeFilehandle?: Filehandle,\n): Filehandle {\n if (maybeFilehandle) {\n return maybeFilehandle\n }\n if (maybeUrl) {\n return new RemoteFile(maybeUrl)\n }\n if (maybePath) {\n return new LocalFile(maybePath)\n }\n throw new Error('no url, path, or filehandle provided, cannot open')\n}\n\nexport { open }\n\nexport { LocalFile, RemoteFile } from 'generic-filehandle'\n","export function parseHeaderText(text: string) {\n const lines = text.split(/\\r?\\n/)\n const data: {\n tag: string\n data: {\n tag: string\n value: string\n }[]\n }[] = []\n for (const line of lines) {\n const [tag, ...fields] = line.split(/\\t/)\n if (tag) {\n data.push({\n tag: tag.slice(1),\n data: fields.map(f => {\n const r = f.indexOf(':')\n return r !== -1\n ? {\n tag: f.slice(0, r),\n value: f.slice(r + 1),\n }\n : // @CO lines are not comma separated.\n // See \"samtools view -H c2\\#pad.3.0.cram\"\n // so, just store value tag and value itself\n {\n tag: f,\n value: '',\n }\n }),\n })\n }\n }\n return data\n}\n","import { Buffer } from 'buffer'\nimport crc32 from 'crc/crc32'\nimport QuickLRU from 'quick-lru'\nimport htscodecs from '@jkbonfield/htscodecs'\nimport bzip2 from 'bzip2'\nimport { XzReadableStream } from 'xz-decompress'\nimport { CramMalformedError, CramUnimplementedError } from '../errors'\n// locals\nimport { unzip } from '../unzip'\nimport ransuncompress from '../rans'\nimport {\n BlockHeader,\n CompressionMethod,\n cramFileDefinition,\n getSectionParsers,\n} from './sectionParsers'\nimport CramContainer from './container'\nimport CramRecord from './record'\nimport { open } from '../io'\nimport { parseItem, tinyMemoize } from './util'\nimport { parseHeaderText } from '../sam'\nimport { Filehandle } from './filehandle'\n\nfunction bufferToStream(buf: Buffer) {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(buf)\n controller.close()\n },\n })\n}\n\n// source: https://abdulapopoola.com/2019/01/20/check-endianness-with-javascript/\nfunction getEndianness() {\n const uInt32 = new Uint32Array([0x11223344])\n const uInt8 = new Uint8Array(uInt32.buffer)\n\n if (uInt8[0] === 0x44) {\n return 0 // little-endian\n } else if (uInt8[0] === 0x11) {\n return 1 // big-endian\n } else {\n return 2 // mixed-endian?\n }\n}\n\nexport interface CramFileSource {\n filehandle?: Filehandle\n url?: string\n path?: string\n}\n\nexport type SeqFetch = (\n seqId: number,\n start: number,\n end: number,\n) => Promise<string>\n\nexport type CramFileArgs = CramFileSource & {\n checkSequenceMD5?: boolean\n cacheSize?: number\n seqFetch?: SeqFetch\n}\n\nexport type CramFileBlock = BlockHeader & {\n _endPosition: number\n contentPosition: number\n _size: number\n content: Buffer\n crc32?: number\n}\n\nexport default class CramFile {\n private file: Filehandle\n public validateChecksums: boolean\n public fetchReferenceSequenceCallback?: SeqFetch\n public options: {\n checkSequenceMD5?: boolean\n cacheSize: number\n }\n public featureCache: QuickLRU<string, Promise<CramRecord[]>>\n private header: string | undefined\n\n constructor(args: CramFileArgs) {\n this.file = open(args.url, args.path, args.filehandle)\n this.validateChecksums = true\n this.fetchReferenceSequenceCallback = args.seqFetch\n this.options = {\n checkSequenceMD5: args.checkSequenceMD5,\n cacheSize: args.cacheSize ?? 20000,\n }\n\n // cache of features in a slice, keyed by the slice offset. caches all of\n // the features in a slice, or none. the cache is actually used by the\n // slice object, it's just kept here at the level of the file\n this.featureCache = new QuickLRU({\n maxSize: this.options.cacheSize,\n })\n if (getEndianness() > 0) {\n throw new Error('Detected big-endian machine, may be unable to run')\n }\n }\n\n // can just read this object like a filehandle\n read(buffer: Buffer, offset: number, length: number, position: number) {\n return this.file.read(buffer, offset, length, position)\n }\n\n // can just stat this object like a filehandle\n stat() {\n return this.file.stat()\n }\n\n // memoized\n async getDefinition() {\n const { maxLength, parser } = cramFileDefinition()\n const headbytes = Buffer.allocUnsafe(maxLength)\n await this.file.read(headbytes, 0, maxLength, 0)\n const definition = parser(headbytes).value\n if (definition.majorVersion !== 2 && definition.majorVersion !== 3) {\n throw new CramUnimplementedError(\n `CRAM version ${definition.majorVersion} not supported`,\n )\n }\n return definition\n }\n\n // memoize\n async getSamHeader() {\n const firstContainer = await this.getContainerById(0)\n if (!firstContainer) {\n throw new CramMalformedError('file contains no containers')\n }\n\n const firstBlock = await firstContainer.getFirstBlock()\n if (firstBlock === undefined) {\n return parseHeaderText('')\n }\n const content = firstBlock.content\n // find the end of the trailing zeros in the header text\n const headerLength = content.readInt32LE(0)\n const textStart = 4\n // let textEnd = content.length - 1\n // while (textEnd >= textStart && !content[textEnd]) textEnd -= 1\n // trim off the trailing zeros\n const text = content.toString('utf8', textStart, textStart + headerLength)\n this.header = text\n return parseHeaderText(text)\n }\n\n async getHeaderText() {\n await this.getSamHeader()\n return this.header\n }\n\n async getContainerById(containerNumber: number) {\n const { majorVersion } = await this.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n let position = sectionParsers.cramFileDefinition.maxLength\n const { size: fileSize } = await this.file.stat()\n const { cramContainerHeader1 } = sectionParsers\n\n // skip with a series of reads to the proper container\n let currentContainer: CramContainer | undefined\n for (let i = 0; i <= containerNumber; i++) {\n // if we are about to go off the end of the file\n // and have not found that container, it does not exist\n if (position + cramContainerHeader1.maxLength + 8 >= fileSize) {\n return undefined\n }\n\n currentContainer = this.getContainerAtPosition(position)\n const currentHeader = await currentContainer.getHeader()\n if (!currentHeader) {\n throw new CramMalformedError(\n `container ${containerNumber} not found in file`,\n )\n }\n // if this is the first container, read all the blocks in the container\n // to determine its length, because we cannot trust the container\n // header's given length due to a bug somewhere in htslib\n if (i === 0) {\n position = currentHeader._endPosition\n for (let j = 0; j < currentHeader.numBlocks; j++) {\n const block = await this.readBlock(position)\n if (block === undefined) {\n return undefined\n }\n position = block._endPosition\n }\n } else {\n // otherwise, just traverse to the next container using the container's length\n position += currentHeader._size + currentHeader.length\n }\n }\n\n return currentContainer\n }\n\n async checkCrc32(\n position: number,\n length: number,\n recordedCrc32: number,\n description: string,\n ) {\n const b = Buffer.allocUnsafe(length)\n await this.file.read(b, 0, length, position)\n const calculatedCrc32 = crc32.unsigned(b)\n if (calculatedCrc32 !== recordedCrc32) {\n throw new CramMalformedError(\n `crc mismatch in ${description}: recorded CRC32 = ${recordedCrc32}, but calculated CRC32 = ${calculatedCrc32}`,\n )\n }\n }\n\n /**\n * @returns {Promise[number]} the number of containers in the file\n */\n async containerCount(): Promise<number | undefined> {\n const { majorVersion } = await this.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n const { size: fileSize } = await this.file.stat()\n const { cramContainerHeader1 } = sectionParsers\n\n let containerCount = 0\n let position = sectionParsers.cramFileDefinition.maxLength\n while (position + cramContainerHeader1.maxLength + 8 < fileSize) {\n const currentHeader =\n await this.getContainerAtPosition(position).getHeader()\n if (!currentHeader) {\n break\n }\n // if this is the first container, read all the blocks in the\n // container, because we cannot trust the container\n // header's given length due to a bug somewhere in htslib\n if (containerCount === 0) {\n position = currentHeader._endPosition\n for (let j = 0; j < currentHeader.numBlocks; j++) {\n const block = await this.readBlock(position)\n if (block === undefined) {\n return undefined\n }\n position = block._endPosition\n }\n } else {\n // otherwise, just traverse to the next container using the container's length\n position += currentHeader._size + currentHeader.length\n }\n containerCount += 1\n }\n\n return containerCount\n }\n\n getContainerAtPosition(position: number) {\n return new CramContainer(this, position)\n }\n\n async readBlockHeader(position: number) {\n const { majorVersion } = await this.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n const { cramBlockHeader } = sectionParsers\n const { size: fileSize } = await this.file.stat()\n\n if (position + cramBlockHeader.maxLength >= fileSize) {\n return undefined\n }\n\n const buffer = Buffer.allocUnsafe(cramBlockHeader.maxLength)\n await this.file.read(buffer, 0, cramBlockHeader.maxLength, position)\n return parseItem(buffer, cramBlockHeader.parser, 0, position)\n }\n\n async _parseSection<T>(\n section: {\n maxLength: number\n parser: (buffer: Buffer, offset: number) => { offset: number; value: T }\n },\n position: number,\n size = section.maxLength,\n preReadBuffer?: Buffer,\n ) {\n let buffer: Buffer\n if (preReadBuffer) {\n buffer = preReadBuffer\n } else {\n const { size: fileSize } = await this.file.stat()\n if (position + size >= fileSize) {\n return undefined\n }\n buffer = Buffer.allocUnsafe(size)\n await this.file.read(buffer, 0, size, position)\n }\n const data = parseItem(buffer, section.parser, 0, position)\n if (data._size !== size) {\n throw new CramMalformedError(\n `section read error: requested size ${size} does not equal parsed size ${data._size}`,\n )\n }\n return data\n }\n\n async _uncompress(\n compressionMethod: CompressionMethod,\n inputBuffer: Buffer,\n outputBuffer: Buffer,\n ) {\n if (compressionMethod === 'gzip') {\n const result = unzip(inputBuffer)\n result.copy(outputBuffer)\n } else if (compressionMethod === 'bzip2') {\n const bits = bzip2.array(inputBuffer)\n let size = bzip2.header(bits)\n let j = 0\n let chunk: Uint8Array | -1\n do {\n chunk = bzip2.decompress(bits, size)\n if (chunk !== -1) {\n Buffer.from(chunk).copy(outputBuffer, j)\n j += chunk.length\n size -= chunk.length\n }\n } while (chunk !== -1)\n } else if (compressionMethod === 'lzma') {\n const decompressedResponse = new Response(\n new XzReadableStream(bufferToStream(inputBuffer)),\n )\n const ret = Buffer.from(await decompressedResponse.arrayBuffer())\n ret.copy(outputBuffer)\n } else if (compressionMethod === 'rans') {\n ransuncompress(inputBuffer, outputBuffer)\n // htscodecs r4x8 is slower, but compatible.\n // htscodecs.r4x8_uncompress(inputBuffer, outputBuffer);\n } else if (compressionMethod === 'rans4x16') {\n htscodecs.r4x16_uncompress(inputBuffer, outputBuffer)\n } else if (compressionMethod === 'arith') {\n htscodecs.arith_uncompress(inputBuffer, outputBuffer)\n } else if (compressionMethod === 'fqzcomp') {\n htscodecs.fqzcomp_uncompress(inputBuffer, outputBuffer)\n } else if (compressionMethod === 'tok3') {\n htscodecs.tok3_uncompress(inputBuffer, outputBuffer)\n } else {\n throw new CramUnimplementedError(\n `${compressionMethod} decompression not yet implemented`,\n )\n }\n }\n\n async readBlock(position: number) {\n const { majorVersion } = await this.getDefinition()\n const sectionParsers = getSectionParsers(majorVersion)\n const blockHeader = await this.readBlockHeader(position)\n if (blockHeader === undefined) {\n return undefined\n }\n const blockContentPosition = blockHeader._endPosition\n\n const uncompressedData = Buffer.allocUnsafe(blockHeader.uncompressedSize)\n\n const block: CramFileBlock = {\n ...blockHeader,\n _endPosition: blockContentPosition,\n contentPosition: blockContentPosition,\n content: uncompressedData,\n }\n\n if (blockHeader.compressionMethod !== 'raw') {\n const compressedData = Buffer.allocUnsafe(blockHeader.compressedSize)\n await this.read(\n compressedData,\n 0,\n blockHeader.compressedSize,\n blockContentPosition,\n )\n\n await this._uncompress(\n blockHeader.compressionMethod,\n compressedData,\n uncompressedData,\n )\n } else {\n await this.read(\n uncompressedData,\n 0,\n blockHeader.uncompressedSize,\n blockContentPosition,\n )\n }\n\n if (majorVersion >= 3) {\n // parse the crc32\n const crc = await this._parseSection(\n sectionParsers.cramBlockCrc32,\n blockContentPosition + blockHeader.compressedSize,\n )\n if (crc === undefined) {\n return undefined\n }\n block.crc32 = crc.crc32\n\n // check the block data crc32\n if (this.validateChecksums) {\n await this.checkCrc32(\n position,\n blockHeader._size + blockHeader.compressedSize,\n crc.crc32,\n 'block data',\n )\n }\n\n // make the endposition and size reflect the whole block\n block._endPosition = crc._endPosition\n block._size =\n block.compressedSize + sectionParsers.cramBlockCrc32.maxLength\n } else {\n block._endPosition = blockContentPosition + block.compressedSize\n block._size = block.compressedSize\n }\n\n return block\n }\n}\n\n'getDefinition getSectionParsers getSamHeader'.split(' ').forEach(method => {\n tinyMemoize(CramFile, method)\n})\n","// @ts-nocheck\nimport { CramMalformedError } from '../errors'\n\nimport { TF_SHIFT } from './constants'\nimport Decoding from './decoding'\n\nexport default function uncompress(\n /* ByteBuffer */ input,\n /* Decoding.AriDecoder */ D,\n /* Decoding.Symbol[] */ syms,\n /* ByteBuffer */ out,\n) {\n let rans0 = input.getInt()\n let rans1 = input.getInt()\n let rans2 = input.getInt()\n let rans3 = input.getInt()\n\n const /* int */ outputSize = out.remaining()\n const /* int */ outputEnd = outputSize & ~3\n for (let i = 0; i < outputEnd; i += 4) {\n const /* byte */ c0 = D.R[Decoding.get(rans0, TF_SHIFT)]\n const /* byte */ c1 = D.R[Decoding.get(rans1, TF_SHIFT)]\n const /* byte */ c2 = D.R[Decoding.get(rans2, TF_SHIFT)]\n const /* byte */ c3 = D.R[Decoding.get(rans3, TF_SHIFT)]\n\n out.putAt(i, c0)\n out.putAt(i + 1, c1)\n out.putAt(i + 2, c2)\n out.putAt(i + 3, c3)\n\n rans0 = Decoding.advanceSymbolStep(rans0, syms[0xff & c0], TF_SHIFT)\n rans1 = Decoding.advanceSymbolStep(rans1, syms[0xff & c1], TF_SHIFT)\n rans2 = Decoding.advanceSymbolStep(rans2, syms[0xff & c2], TF_SHIFT)\n rans3 = Decoding.advanceSymbolStep(rans3, syms[0xff & c3], TF_SHIFT)\n\n rans0 = Decoding.renormalize(rans0, input)\n rans1 = Decoding.renormalize(rans1, input)\n rans2 = Decoding.renormalize(rans2, input)\n rans3 = Decoding.renormalize(rans3, input)\n }\n\n out.setPosition(outputEnd)\n let /* byte */ c: number\n switch (outputSize & 3) {\n case 0:\n break\n case 1:\n c = D.R[Decoding.get(rans0, TF_SHIFT)]\n Decoding.advanceSymbol(rans0, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n break\n\n case 2:\n c = D.R[Decoding.get(rans0, TF_SHIFT)]\n Decoding.advanceSymbol(rans0, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n\n c = D.R[Decoding.get(rans1, TF_SHIFT)]\n Decoding.advanceSymbol(rans1, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n break\n\n case 3:\n c = D.R[Decoding.get(rans0, TF_SHIFT)]\n Decoding.advanceSymbol(rans0, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n\n c = D.R[Decoding.get(rans1, TF_SHIFT)]\n Decoding.advanceSymbol(rans1, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n\n c = D.R[Decoding.get(rans2, TF_SHIFT)]\n Decoding.advanceSymbol(rans2, input, syms[0xff & c], TF_SHIFT)\n out.put(c)\n break\n\n default:\n throw new CramMalformedError(\n 'invalid output size encountered during rANS decoding',\n )\n }\n\n out.setPosition(0)\n}\n","// @ts-nocheck\nimport { TF_SHIFT } from './constants'\nimport Decoding from './decoding'\n\nexport default function uncompress(\n /* ByteBuffer */ input,\n /* ByteBuffer */ output,\n /* Decoding.AriDecoder[] */ D,\n /* Decoding.Symbol[][] */ syms,\n) {\n const /* int */ outputSize = output.remaining()\n let rans0 = input.getInt()\n let rans1 = input.getInt()\n let rans2 = input.getInt()\n let rans7 = input.getInt()\n\n const /* int */ isz4 = outputSize >> 2\n let /* int */ i0 = 0\n let /* int */ i1 = isz4\n let /* int */ i2 = 2 * isz4\n let /* int */ i7 = 3 * isz4\n let /* int */ l0 = 0\n let /* int */ l1 = 0\n let /* int */ l2 = 0\n let /* int */ l7 = 0\n for (; i0 < isz4; i0 += 1, i1 += 1, i2 += 1, i7 += 1) {\n const /* int */ c0 = 0xff & D[l0].R[Decoding.get(rans0, TF_SHIFT)]\n const /* int */ c1 = 0xff & D[l1].R[Decoding.get(rans1, TF_SHIFT)]\n const /* int */ c2 = 0xff & D[l2].R[Decoding.get(rans2, TF_SHIFT)]\n const /* int */ c7 = 0xff & D[l7].R[Decoding.get(rans7, TF_SHIFT)]\n\n output.putAt(i0, c0)\n output.putAt(i1, c1)\n output.putAt(i2, c2)\n output.putAt(i7, c7)\n\n rans0 = Decoding.advanceSymbolStep(rans0, syms[l0][c0], TF_SHIFT)\n rans1 = Decoding.advanceSymbolStep(rans1, syms[l1][c1], TF_SHIFT)\n rans2 = Decoding.advanceSymbolStep(rans2, syms[l2][c2], TF_SHIFT)\n rans7 = Decoding.advanceSymbolStep(rans7, syms[l7][c7], TF_SHIFT)\n\n rans0 = Decoding.renormalize(rans0, input)\n rans1 = Decoding.renormalize(rans1, input)\n rans2 = Decoding.renormalize(rans2, input)\n rans7 = Decoding.renormalize(rans7, input)\n\n l0 = c0\n l1 = c1\n l2 = c2\n l7 = c7\n }\n\n // Remainder\n for (; i7 < outputSize; i7 += 1) {\n const /* int */ c7 = 0xff & D[l7].R[Decoding.get(rans7, TF_SHIFT)]\n output.putAt(i7, c7)\n rans7 = Decoding.advanceSymbol(rans7, input, syms[l7][c7], TF_SHIFT)\n l7 = c7\n }\n}\n","import { unzip } from './unzip'\nimport { open } from './io'\nimport { CramMalformedError } from './errors'\nimport { CramFileSource } from './cramFile/file'\nimport { Filehandle } from './cramFile/filehandle'\n\nconst BAI_MAGIC = 21_578_050 // BAI\\1\n\nexport interface Slice {\n start: number\n span: number\n containerStart: number\n sliceStart: number\n sliceBytes: number\n}\n\ntype ParsedIndex = Record<string, Slice[] | undefined>\n\nfunction addRecordToIndex(index: ParsedIndex, record: number[]) {\n const [seqId, start, span, containerStart, sliceStart, sliceBytes] = record\n\n const s = seqId!\n if (!index[s]) {\n index[s] = []\n }\n\n index[s].push({\n start: start!,\n span: span!,\n containerStart: containerStart!,\n sliceStart: sliceStart!,\n sliceBytes: sliceBytes!,\n })\n}\n\nfunction maybeUnzip(data: Buffer) {\n if (data[0] === 31 && data[1] === 139) {\n return unzip(data)\n }\n return data\n}\n\nexport default class CraiIndex {\n // A CRAM index (.crai) is a gzipped tab delimited file containing the\n // following columns:\n //\n // 1. Sequence id\n // 2. Alignment start\n // 3. Alignment span\n // 4. Container start byte position in the file\n // 5. Slice start byte position in the container data (‘blocks’)\n // 6. Slice size in bytes\n // Each line represents a slice in the CRAM file. Please note that all slices must be listed in index file.\n private parseIndexP?: Promise<ParsedIndex>\n\n private filehandle: Filehandle\n\n /**\n *\n * @param {object} args\n * @param {string} [args.path]\n * @param {string} [args.url]\n * @param {FileHandle} [args.filehandle]\n */\n constructor(args: CramFileSource) {\n this.filehandle = open(args.url, args.path, args.filehandle)\n }\n\n async parseIndex() {\n const index: ParsedIndex = {}\n const uncompressedBuffer = maybeUnzip(await this.filehandle.readFile())\n if (\n uncompressedBuffer.length > 4 &&\n uncompressedBuffer.readUInt32LE(0) === BAI_MAGIC\n ) {\n throw new CramMalformedError(\n 'invalid .crai index file. note: file appears to be a .bai index. this is technically legal but please open a github issue if you need support',\n )\n }\n // interpret the text as regular ascii, since it is\n // supposed to be only digits and whitespace characters\n // this is written in a deliberately low-level fashion for performance,\n // because some .crai files can be pretty large.\n let currentRecord: number[] = []\n let currentString = ''\n for (const charCode of uncompressedBuffer) {\n if (\n (charCode >= 48 && charCode <= 57) /* 0-9 */ ||\n (!currentString && charCode === 45) /* leading - */\n ) {\n currentString += String.fromCharCode(charCode)\n } else if (charCode === 9 /* \\t */) {\n currentRecord.push(Number.parseInt(currentString, 10))\n currentString = ''\n } else if (charCode === 10 /* \\n */) {\n currentRecord.push(Number.parseInt(currentString, 10))\n currentString = ''\n addRecordToIndex(index, currentRecord)\n currentRecord = []\n } else if (charCode !== 13 /* \\r */ && charCode !== 32 /* space */) {\n // if there are other characters in the file besides\n // space and \\r, something is wrong.\n throw new CramMalformedError('invalid .crai index file')\n }\n }\n\n // if the file ends without a \\n, we need to flush our buffers\n if (currentString) {\n currentRecord.push(Number.parseInt(currentString, 10))\n }\n if (currentRecord.length === 6) {\n addRecordToIndex(index, currentRecord)\n }\n\n // sort each of them by start\n Object.entries(index).forEach(([seqId, ent]) => {\n const e2 = ent!\n index[seqId] = e2.sort((a, b) => a.start - b.start || a.span - b.span)\n })\n return index\n }\n\n getIndex() {\n if (!this.parseIndexP) {\n this.parseIndexP = this.parseIndex().catch((e: unknown) => {\n this.parseIndexP = undefined\n throw e\n })\n }\n return this.parseIndexP\n }\n\n /**\n * @param {number} seqId\n * @returns {Promise} true if the index contains entries for\n * the given reference sequence ID, false otherwise\n */\n async hasDataForReferenceSequence(seqId: number) {\n return !!(await this.getIndex())[seqId]\n }\n\n /**\n * fetch index entries for the given range\n *\n * @param {number} seqId\n * @param {number} queryStart\n * @param {number} queryEnd\n *\n * @returns {Promise} promise for\n * an array of objects of the form\n * `{start, span, containerStart, sliceStart, sliceBytes }`\n */\n async getEntriesForRange(\n seqId: number,\n queryStart: number,\n queryEnd: number,\n ): Promise<Slice[]> {\n const seqEntries = (await this.getIndex())[seqId]\n if (!seqEntries) {\n return []\n }\n\n const compare = (entry: Slice) => {\n const entryStart = entry.start\n const entryEnd = entry.start + entry.span\n if (entryStart > queryEnd) {\n return -1\n } // entry is ahead of query\n if (entryEnd <= queryStart) {\n return 1\n } // entry is behind query\n return 0 // entry overlaps query\n }\n const bins = [] as Slice[]\n for (const entry of seqEntries) {\n if (compare(entry) === 0) {\n bins.push(entry)\n }\n }\n return bins\n }\n}\n","import { CramUnimplementedError } from './errors'\nimport CramFile from './cramFile'\nimport CramRecord from './cramFile/record'\nimport { SeqFetch } from './cramFile/file'\nimport { Filehandle } from './cramFile/filehandle'\nimport { Slice } from './craiIndex'\n\nexport interface CramFileSource {\n cramFilehandle?: Filehandle\n cramUrl?: string\n cramPath?: string\n}\n\nexport interface CramIndexLike {\n getEntriesForRange: (\n seqId: number,\n start: number,\n end: number,\n ) => Promise<Slice[]>\n hasDataForReferenceSequence: (seqId: number) => Promise<boolean>\n}\n\nexport default class IndexedCramFile {\n public cram: CramFile\n public index: CramIndexLike\n\n /**\n *\n * @param {object} args\n * @param {CramFile} args.cram\n * @param {Index-like} args.index object that supports getEntriesForRange(seqId,start,end) -> Promise[Array[index entries]]\n * @param {number} [args.cacheSize] optional maximum number of CRAM records to cache. default 20,000\n * @param {boolean} [args.checkSequenceMD5] - default true. if false, disables verifying the MD5\n * checksum of the reference sequence underlying a slice. In some applications, this check can cause an inconvenient amount (many megabases) of sequences to be fetched.\n */\n constructor(\n args: {\n index: CramIndexLike\n } & (\n | { cram: CramFile }\n | ({\n cram?: undefined\n seqFetch?: SeqFetch\n checkSequenceMD5?: boolean\n cacheSize?: number\n } & CramFileSource)\n ),\n ) {\n // { cram, index, seqFetch /* fasta, fastaIndex */ }) {\n this.cram =\n args.cram ??\n new CramFile({\n url: args.cramUrl,\n path: args.cramPath,\n filehandle: args.cramFilehandle,\n seqFetch: args.seqFetch,\n checkSequenceMD5: args.checkSequenceMD5,\n cacheSize: args.cacheSize,\n })\n\n if (!(this.cram instanceof CramFile)) {\n throw new Error('invalid arguments: no cramfile')\n }\n\n this.index = args.index\n }\n\n /**\n *\n * @param {number} seq numeric ID of the reference sequence\n * @param {number} start start of the range of interest. 1-based closed coordinates.\n * @param {number} end end of the range of interest. 1-based closed coordinates.\n * @returns {Promise[Array[CramRecord]]}\n */\n async getRecordsForRange(\n seq: number,\n start: number,\n end: number,\n opts: {\n viewAsPairs?: boolean\n pairAcrossChr?: boolean\n maxInsertSize?: number\n } = {},\n ) {\n opts.viewAsPairs = opts.viewAsPairs || false\n opts.pairAcrossChr = opts.pairAcrossChr || false\n opts.maxInsertSize = opts.maxInsertSize || 200000\n\n if (typeof seq === 'string') {\n // TODO: support string reference sequence names somehow\n throw new CramUnimplementedError(\n 'string sequence names not yet supported',\n )\n }\n const seqId = seq\n const slices = await this.index.getEntriesForRange(seqId, start, end)\n\n // TODO: do we need to merge or de-duplicate the blocks?\n\n // fetch all the slices and parse the feature data\n const filter = (feature: CramRecord) =>\n feature.sequenceId === seq &&\n feature.alignmentStart <= end &&\n feature.lengthOnRef !== undefined &&\n feature.alignmentStart + feature.lengthOnRef - 1 >= start\n const sliceResults = await Promise.all(\n slices.map(slice => this.getRecordsInSlice(slice, filter)),\n )\n\n let ret: CramRecord[] = Array.prototype.concat(...sliceResults)\n if (opts.viewAsPairs) {\n const readNames: Record<string, number> = {}\n const readIds: Record<string, number> = {}\n for (const read of ret) {\n const name = read.readName\n if (name === undefined) {\n throw new Error('readName undefined')\n }\n const id = read.uniqueId\n if (!readNames[name]) {\n readNames[name] = 0\n }\n readNames[name] += 1\n readIds[id] = 1\n }\n const unmatedPairs: Record<string, boolean> = {}\n Object.entries(readNames).forEach(([k, v]) => {\n if (v === 1) {\n unmatedPairs[k] = true\n }\n })\n const matePromises = []\n for (const cramRecord of ret) {\n const name = cramRecord.readName\n if (name === undefined) {\n throw new Error('readName undefined')\n }\n if (\n unmatedPairs[name] &&\n cramRecord.mate &&\n (cramRecord.mate.sequenceId === seqId || opts.pairAcrossChr) &&\n Math.abs(cramRecord.alignmentStart - cramRecord.mate.alignmentStart) <\n opts.maxInsertSize\n ) {\n const mateSlices = this.index.getEntriesForRange(\n cramRecord.mate.sequenceId,\n cramRecord.mate.alignmentStart,\n cramRecord.mate.alignmentStart + 1,\n )\n matePromises.push(mateSlices)\n }\n }\n const mateBlocks = await Promise.all(matePromises)\n let mateChunks = [] as Slice[]\n for (const block of mateBlocks) {\n mateChunks.push(...block)\n }\n // filter out duplicates\n mateChunks = mateChunks\n .sort((a, b) => a.toString().localeCompare(b.toString()))\n .filter(\n (item, pos, ary) =>\n !pos || item.toString() !== ary[pos - 1]!.toString(),\n )\n\n const mateRecordPromises = []\n const mateFeatPromises: Promise<CramRecord[]>[] = []\n for (const c of mateChunks) {\n let recordPromise = this.cram.featureCache.get(c.toString())\n if (!recordPromise) {\n recordPromise = this.getRecordsInSlice(c, () => true)\n this.cram.featureCache.set(c.toString(), recordPromise)\n }\n mateRecordPromises.push(recordPromise)\n const featPromise = recordPromise.then(feats => {\n const mateRecs = []\n for (const feature of feats) {\n if (feature.readName === undefined) {\n throw new Error('readName undefined')\n }\n if (unmatedPairs[feature.readName] && !readIds[feature.uniqueId]) {\n mateRecs.push(feature)\n }\n }\n return mateRecs\n })\n mateFeatPromises.push(featPromise)\n }\n const newMateFeats = await Promise.all(mateFeatPromises)\n if (newMateFeats.length) {\n const newMates = newMateFeats.reduce((result, current) =>\n result.concat(current),\n )\n ret = ret.concat(newMates)\n }\n }\n return ret\n }\n\n getRecordsInSlice(\n {\n containerStart,\n sliceStart,\n sliceBytes,\n }: { containerStart: number; sliceStart: number; sliceBytes: number },\n filterFunction: (r: CramRecord) => boolean,\n ) {\n const container = this.cram.getContainerAtPosition(containerStart)\n const slice = container.getSlice(sliceStart, sliceBytes)\n return slice.getRecords(filterFunction)\n }\n\n /**\n *\n * @param {number} seqId\n * @returns {Promise} true if the CRAM file contains data for the given\n * reference sequence numerical ID\n */\n hasDataForReferenceSequence(seqId: number) {\n return this.index.hasDataForReferenceSequence(seqId)\n }\n}\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nconst RangeCoder = require(\"./arith_sh\");\nconst IOStream = require(\"./iostream\");\nconst ByteModel = require(\"./byte_model\");\nconst bzip2 = require(\"bzip2\");\n\nconst ARITH_ORDER = 1\nconst ARITH_EXT = 4\nconst ARITH_STRIPE = 8\nconst ARITH_NOSIZE = 16\nconst ARITH_CAT = 32\nconst ARITH_RLE = 64\nconst ARITH_PACK = 128\n\nmodule.exports = class RangeCoderGen {\n decode(src) {\n\tthis.stream = new IOStream(src);\n\treturn this.decodeStream(this.stream)\n }\n\n decodeStream(stream, n_out=0) {\n\tvar flags = this.stream.ReadByte();\n\tif (!(flags & ARITH_NOSIZE))\n\t n_out = this.stream.ReadUint7();\n\tvar e_len = n_out;\n\n\tvar order = flags & ARITH_ORDER;\n\n\t// 4-way recursion\n\tif (flags & ARITH_STRIPE)\n\t return this.decodeStripe(this.stream, n_out)\n\n\t// Meta data\n\tif (flags & ARITH_PACK) {\n\t var P\n\t [P, e_len] = this.decodePackMeta(this.stream)\n\t}\n\n\t// NOP, useful for tiny blocks\n\tif (flags & ARITH_CAT)\n\t var data = this.decodeCat(this.stream, e_len)\n\n\t// Entropy decode\n\telse if (flags & ARITH_EXT) {\n\t var data = this.decodeExt(this.stream, e_len)\n\t} else if (flags & ARITH_RLE) {\n\t var data = order\n\t\t? this.decodeRLE1(this.stream, e_len)\n\t\t: this.decodeRLE0(this.stream, e_len)\n\t} else {\n\t var data = order\n\t\t? this.decode1(this.stream, e_len)\n\t\t: this.decode0(this.stream, e_len)\n\t}\n\n\t// Transforms\n\tif (flags & ARITH_PACK)\n\t data = this.decodePack(data, P, n_out)\n\n\treturn data\n }\n\n encode(src, flags) {\n\tthis.stream = new IOStream(\"\", 0, src.length*1.1 + 100); // guestimate worst case!\n\n\tthis.stream.WriteByte(flags);\n\tif (!(flags & ARITH_NOSIZE))\n\t this.stream.WriteUint7(src.length);\n\n\tif (flags & ARITH_STRIPE)\n\t return Buffer.concat([this.stream.buf.slice(0, this.stream.pos),\n\t\t\t\t this.encodeStripe(this.stream, src, flags>>8)])\n\n\tvar order = flags & ARITH_ORDER;\n\tvar e_len = src.length;\n\n\t// step 1: Encode meta-data\n\tvar pack_meta\n\tif (flags & ARITH_PACK)\n\t [pack_meta, src, e_len] = this.encodePack(src)\n\n\t// step 2: Write any meta data\n\tif (flags & ARITH_PACK)\n\t this.stream.WriteStream(pack_meta)\n\n\t// step 3: arith encoding below\n\tif (flags & ARITH_RLE) {\n\t return order\n\t\t? this.encodeRLE1(src, e_len, this.stream)\n\t\t: this.encodeRLE0(src, e_len, this.stream);\n\t} else {\n\t return order\n\t\t? this.encode1(src, e_len, this.stream)\n\t\t: this.encode0(src, e_len, this.stream);\n\t}\n }\n\n //----------------------------------------------------------------------\n // Order-0 codec\n decode0(stream, n_out) {\n\tvar output = new Buffer.allocUnsafe(n_out);\n\n\tvar max_sym = stream.ReadByte()\n\tif (max_sym == 0)\n\t max_sym = 256\n\n\tvar byte_model = new ByteModel(max_sym);\n\n\tvar rc = new RangeCoder(stream);\n\trc.RangeStartDecode(stream);\n\n\tfor (var i = 0; i < n_out; i++)\n\t output[i] = byte_model.ModelDecode(stream, rc);\n\n\treturn output;\n }\n\n encode0(src, n_in, out) {\n\t// Count the maximum symbol present\n\tvar max_sym = 0;\n\tfor (var i = 0; i < n_in; i++)\n\t if (max_sym < src[i])\n\t\tmax_sym = src[i]\n\tmax_sym++; // FIXME not what spec states!?\n\n\tvar byte_model = new ByteModel(max_sym);\n\tout.WriteByte(max_sym);\n\tvar rc = new RangeCoder(out);\n\n\tfor (var i = 0; i < n_in; i++)\n\t byte_model.ModelEncode(out, rc, src[i])\n\trc.RangeFinishEncode(out)\n\n\treturn out.buf.slice(0, out.pos);\n }\n\n //----------------------------------------------------------------------\n // Order-1 codec\n\n decode1(stream, n_out) {\n\tvar output = new Buffer.allocUnsafe(n_out);\n\n\tvar max_sym = stream.ReadByte()\n\tif (max_sym == 0)\n\t max_sym = 256\n\n\tvar byte_model = new Array(max_sym);\n\tfor (var i = 0; i < max_sym; i++)\n\t byte_model[i] = new ByteModel(max_sym);\n\n\tvar rc = new RangeCoder(stream);\n\trc.RangeStartDecode(stream);\n\n\tvar last = 0;\n\tfor (var i = 0; i < n_out; i++) {\n\t output[i] = byte_model[last].ModelDecode(stream, rc);\n\t last = output[i];\n\t}\n\n\treturn output;\n }\n\n encode1(src, n_in, out) {\n\t// Count the maximum symbol present\n\tvar max_sym = 0;\n\tfor (var i = 0; i < n_in; i++)\n\t if (max_sym < src[i])\n\t\tmax_sym = src[i]\n\tmax_sym++; // FIXME not what spec states!\n\n\tvar byte_model = new Array(max_sym);\n\tfor (var i = 0; i < max_sym; i++)\n\t byte_model[i] = new ByteModel(max_sym);\n\tout.WriteByte(max_sym);\n\tvar rc = new RangeCoder(out);\n\n\tvar last = 0;\n\tfor (var i = 0; i < n_in; i++) {\n\t byte_model[last].ModelEncode(out, rc, src[i])\n\t last = src[i]\n\t}\n\trc.RangeFinishEncode(out)\n\n\treturn out.buf.slice(0, out.pos);\n }\n\n //----------------------------------------------------------------------\n // External codec\n decodeExt(stream, n_out) {\n\t// Bzip2 only for now\n\tvar output = new Buffer.allocUnsafe(n_out)\n\tvar bits = bzip2.array(stream.buf.slice(stream.pos))\n\tvar size = bzip2.header(bits)\n\tvar j = 0\n\tdo {\n\t var chunk = bzip2.decompress(bits, size);\n\t if (chunk != -1) {\n\t Buffer.from(chunk).copy(output, j)\n\t j += chunk.length\n\t\tsize -= chunk.length\n\t }\n\t} while(chunk != -1);\n\n\treturn output\n }\n\n encodeExt(stream, n_out) {\n\t// We cannot compress using Bzip2 now as it's\n\t// absent from bzip2.js, but consider using\n\t// https://github.com/cscott/compressjs\n }\n\n //----------------------------------------------------------------------\n // Order-0 RLE codec\n decodeRLE0(stream, n_out) {\n\tvar output = new Buffer.allocUnsafe(n_out);\n\n\tvar max_sym = stream.ReadByte()\n\tif (max_sym == 0)\n\t max_sym = 256\n\n\tvar model_lit = new ByteModel(max_sym);\n\tvar model_run = new Array(258);\n\tfor (var i = 0; i <= 257; i++)\n\t model_run[i] = new ByteModel(4)\n\n\tvar rc = new RangeCoder(stream);\n\trc.RangeStartDecode(stream);\n\n\tvar i = 0;\n\twhile (i < n_out) {\n\t output[i] = model_lit.ModelDecode(stream, rc)\n\t var part = model_run[output[i]].ModelDecode(stream, rc)\n\t var run = part\n\t var rctx = 256\n\t while (part == 3) {\n\t\tpart = model_run[rctx].ModelDecode(stream, rc)\n\t\trctx = 257\n\t\trun += part\n\t }\n\t for (var j = 1; j <= run; j++)\n\t\toutput[i+j] = output[i]\n\t i += run+1\n\t}\n\n\treturn output;\n }\n\n encodeRLE0(src, n_in, out) {\n\t// Count the maximum symbol present\n\tvar max_sym = 0;\n\tfor (var i = 0; i < n_in; i++)\n\t if (max_sym < src[i])\n\t\tmax_sym = src[i]\n\tmax_sym++; // FIXME not what spec states!\n\n\tvar model_lit = new ByteModel(max_sym);\n\tvar model_run = new Array(258);\n\tfor (var i = 0; i <= 257; i++)\n\t model_run[i] = new ByteModel(4)\n\n\tout.WriteByte(max_sym);\n\tvar rc = new RangeCoder(out);\n\n\tvar i = 0\n\twhile (i < n_in) {\n\t model_lit.ModelEncode(out, rc, src[i])\n\t var run = 1\n\t while (i+run < n_in && src[i+run] == src[i])\n\t\trun++\n\t run--\n\n\t var rctx = src[i]\n\t var last = src[i]\n\t i += run+1\n\n\t var part = run >= 3 ? 3 : run\n\t model_run[rctx].ModelEncode(out, rc, part)\n\t run -= part\n\t rctx = 256\n\t while (part == 3) {\n\t\tpart = run >= 3 ? 3 : run\n\t\tmodel_run[rctx].ModelEncode(out, rc, part)\n\t\trctx = 257\n\t\trun -= part\n\t }\n\t}\n\trc.RangeFinishEncode(out)\n\n\treturn out.buf.slice(0, out.pos);\n }\n\n //----------------------------------------------------------------------\n // Order-1 RLE codec\n\n decodeRLE1(stream, n_out) {\n\tvar output = new Buffer.allocUnsafe(n_out);\n\n\tvar max_sym = stream.ReadByte()\n\tif (max_sym == 0)\n\t max_sym = 256\n\n\tvar model_lit = new Array(max_sym);\n\tfor (var i = 0; i < max_sym; i++)\n\t model_lit[i] = new ByteModel(max_sym);\n\n\tvar model_run = new Array(258);\n\tfor (var i = 0; i <= 257; i++)\n\t model_run[i] = new ByteModel(4)\n\n\tvar rc = new RangeCoder(stream);\n\trc.RangeStartDecode(stream);\n\n\tvar last = 0;\n\tvar i = 0;\n\twhile (i < n_out) {\n\t output[i] = model_lit[last].ModelDecode(stream, rc)\n\t last = output[i]\n\t var part = model_run[output[i]].ModelDecode(stream, rc)\n\t var run = part\n\t var rctx = 256\n\t while (part == 3) {\n\t\tpart = model_run[rctx].ModelDecode(stream, rc)\n\t\trctx = 257\n\t\trun += part\n\t }\n\t for (var j = 1; j <= run; j++)\n\t\toutput[i+j] = output[i]\n\t i += run+1\n\t}\n\n\treturn output;\n }\n\n encodeRLE1(src, n_in, out) {\n\t// Count the maximum symbol present\n\tvar max_sym = 0;\n\tfor (var i = 0; i < n_in; i++)\n\t if (max_sym < src[i])\n\t\tmax_sym = src[i]\n\tmax_sym++; // FIXME not what spec states!\n\n\tvar model_lit = new Array(max_sym)\n\tfor (var i = 0; i < max_sym; i++)\n\t model_lit[i] = new ByteModel(max_sym);\n\tvar model_run = new Array(258);\n\tfor (var i = 0; i <= 257; i++)\n\t model_run[i] = new ByteModel(4)\n\n\tout.WriteByte(max_sym);\n\tvar rc = new RangeCoder(out);\n\n\tvar i = 0\n\tvar last = 0\n\twhile (i < n_in) {\n\t model_lit[last].ModelEncode(out, rc, src[i])\n\t var run = 1\n\t while (i+run < n_in && src[i+run] == src[i])\n\t\trun++\n\t run--\n\n\t var rctx = src[i]\n\t last = src[i]\n\t i += run+1\n\n\t var part = run >= 3 ? 3 : run\n\t model_run[rctx].ModelEncode(out, rc, part)\n\t run -= part\n\t rctx = 256\n\t while (part == 3) {\n\t\tpart = run >= 3 ? 3 : run\n\t\tmodel_run[rctx].ModelEncode(out, rc, part)\n\t\trctx = 257\n\t\trun -= part\n\t }\n\t}\n\trc.RangeFinishEncode(out)\n\n\treturn out.buf.slice(0, out.pos);\n }\n\n //----------------------------------------------------------------------\n // Pack method\n decodePackMeta(stream) {\n\tthis.nsym = stream.ReadByte()\n\n\tvar M = new Array(this.nsym);\n\tfor (var i = 0; i < this.nsym; i++)\n\t M[i] = stream.ReadByte()\n\n\tvar e_len = stream.ReadUint7(); // Could be derived data from nsym and n_out\n\n\treturn [M, e_len]\n }\n\n decodePack(data, M, len) {\n\tvar out = new Buffer.allocUnsafe(len);\n\n\tif (this.nsym <= 1) {\n\t // Constant value\n\t for (var i = 0; i < len; i++)\n\t\tout[i] = M[0]\n\n\t} else if (this.nsym <= 2) {\n\t // 1 bit per value\n\t for (var i = 0, j = 0; i < len; i++) {\n\t\tif (i % 8 == 0)\n\t\t var v = data[j++]\n\t\tout[i] = M[v & 1]\n\t\tv >>= 1\n\t }\n\n\t} else if (this.nsym <= 4) {\n\t // 2 bits per value\n\t for (var i = 0, j = 0; i < len; i++) {\n\t\tif (i % 4 == 0)\n\t\t var v = data[j++]\n\t\tout[i] = M[v & 3]\n\t\tv >>= 2\n\t }\n\n\t} else if (this.nsym <= 16) {\n\t // 4 bits per value\n\t for (var i = 0, j = 0; i < len; i++) {\n\t\tif (i % 2 == 0)\n\t\t var v = data[j++]\n\t\tout[i] = M[v & 15]\n\t\tv >>= 4\n\t }\n\n\t} else {\n\t // 8 bits per value: NOP\n\t return data\n\t}\n\n\treturn out\n }\n\n // Compute M array and return meta-data stream\n packMeta(src) {\n\tvar stream = new IOStream(\"\", 0, 1024)\n\n\t// Count symbols\n\tvar M = new Array(256)\n\tfor (var i = 0; i < src.length; i++)\n\t M[src[i]] = 1\n\n\t// Write Map\n\tfor (var nsym = 0, i = 0; i < 256; i++)\n\t if (M[i])\n\t\tM[i] = ++nsym; // map to 1..N\n\tstream.WriteByte(nsym);\n\n\t// FIXME: add check for nsym > 16?\n\t// Or just accept it as an inefficient waste of time.\n\tfor (var i = 0; i < 256; i++) {\n\t if (M[i]) {\n\t\tstream.WriteByte(i) // adjust to 0..N-1\n\t\tM[i]--;\n\t }\n\t}\n\n\treturn [stream, M, nsym]\n }\n\n encodePack(data) {\n\tvar meta, M, nsym\n\t[meta, M, nsym] = this.packMeta(data)\n\n\tvar len = data.length\n\tvar i = 0;\n\tif (nsym <= 1) {\n\t // Constant values\n\t meta.WriteUint7(0)\n\t return [meta, new Buffer.allocUnsafe(0), 0];\n\t}\n\n\tif (nsym <= 2) {\n\t // 1 bit per value\n\t var out = new Buffer.allocUnsafe(Math.floor((len+7)/8));\n\t for (var i = 0, j = 0; i < (len & ~7); i+=8, j++)\n\t\tout[j] = (M[data[i+0]]<<0)\n\t\t + (M[data[i+1]]<<1)\n\t\t + (M[data[i+2]]<<2)\n\t\t + (M[data[i+3]]<<3)\n\t\t + (M[data[i+4]]<<4)\n\t\t + (M[data[i+5]]<<5)\n\t\t + (M[data[i+6]]<<6)\n\t\t + (M[data[i+7]]<<7)\n\t if (i < len) {\n\t\tout[j] = 0;\n\t\tvar v = 0;\n\t\twhile (i < len) {\n\t\t out[j] |= M[data[i++]]<<v;\n\t\t v++;\n\t\t}\n\t\tj++;\n\t }\n\n\t meta.WriteUint7(j)\n\t return [meta, out, out.length]\n\t}\n\n\tif (nsym <= 4) {\n\t // 2 bits per value\n\t var out = new Buffer.allocUnsafe(Math.floor((len+3)/4));\n\t for (var i = 0, j = 0; i < (len & ~3); i+=4, j++)\n\t\tout[j] = (M[data[i+0]]<<0)\n\t\t + (M[data[i+1]]<<2)\n\t\t + (M[data[i+2]]<<4)\n\t\t + (M[data[i+3]]<<6)\n\n\t if (i < len) {\n\t\tout[j] = 0;\n\t\tvar v = 0;\n\t\twhile (i < len) {\n\t\t out[j] |= M[data[i++]]<<v;\n\t\t v+=2;\n\t\t}\n\t\tj++;\n\t }\n\n\t meta.WriteUint7(j)\n\t return [meta, out, out.length]\n\t}\n\n\tif (nsym <= 16) {\n\t // 4 bits per value\n\t var out = new Buffer.allocUnsafe(Math.floor((len+1)/2));\n\t for (var i = 0, j = 0; i < (len & ~1); i+=2, j++)\n\t\tout[j] = (M[data[i+0]]<<0)\n\t\t + (M[data[i+1]]<<4)\n\t if (i < len)\n\t\tout[j++] = M[data[i++]];\n\n\t meta.WriteUint7(j)\n\t return [meta, out, out.length]\n\t}\n\n\t// Otherwise an expensive NOP\n\tmeta.WriteUint7(data.length)\n\treturn [meta, data, data.length]\n }\n\n //----------------------------------------------------------------------\n // STRIPE method\n encodeStripe(hdr, src, N) {\n if (N == 0)\n\tN = 4; // old default\n\n\t// Split into multiple streams\n\tvar part = new Array(N)\n\tvar ulen = new Array(N)\n\tfor (var s = 0; s < N; s++) {\n\t ulen[s] = Math.floor(src.length / N) + ((src.length % N) > s);\n\t part[s] = new Array(ulen[s])\n\t}\n\n\tfor (var x = 0, i = 0; i < src.length; i+=N, x++) {\n\t for (var j = 0; j < N; j++)\n\t\tif (x < part[j].length)\n\t\t part[j][x] = src[i+j]\n\t}\n\n\t// Compress each part\n\tvar comp = new Array(N)\n\tvar total = 0\n\tfor (var s = 0; s < N; s++) {\n\t // Example: try O0 and O1 and choose best\n\t var comp0 = this.encode(part[s], 0)\n\t var comp1 = this.encode(part[s], 1)\n\t comp[s] = (comp1.length < comp0.length) ? comp1 : comp0\n\t total += comp[s].length\n\t}\n\n\t// Serialise\n\tvar out = new IOStream(\"\", 0, total+5*N + 1)\n\tout.WriteByte(N)\n\tfor (var s = 0; s < N; s++)\n\t out.WriteUint7(comp[s].length)\n\n\tfor (var s = 0; s < N; s++)\n\t out.WriteData(comp[s], comp[s].length)\n\n\treturn out.buf.slice(0, out.buf.pos)\n }\n\n decodeStripe(stream, len) {\n\tvar N = stream.ReadByte()\n\t\n\t// Retrieve lengths\n\tvar clen = new Array(N)\n\tvar ulen = new Array(N)\n\tfor (var j = 0; j < N; j++)\n\t clen[j] = stream.ReadUint7()\n\n\t// Decode streams\n\tvar T = new Array(N);\n\tfor (var j = 0; j < N; j++) {\n\t ulen[j] = Math.floor(len / N) + ((len % N) > j)\n\t T[j] = this.decodeStream(stream, ulen[j])\n\t}\n\n\t// Transpose\n\tvar out = new Buffer.allocUnsafe(len)\n\tfor (var j = 0; j < N; j++) {\n\t for (var i = 0; i < ulen[j]; i++) {\n\t\tout[i*N + j] = T[j][i];\n\t }\n\t}\n\n\treturn out\n }\n\n //----------------------------------------------------------------------\n // Cat method\n decodeCat(stream, len) {\n\tvar out = new Buffer.allocUnsafe(len);\n\tfor (var i = 0; i < len; i++)\n\t out[i] = stream.ReadByte()\n\n\treturn out\n }\n}\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// An arithmetic coder, based on Eugene Shelwien's reimplementation of\n// Michael Schindler range coder.\n//\n// Order-0 byte stream of ~/scratch/data/q40b\n// C: 3.1s decode (approx same vs 32-bit and 64-bit)\n// Arith_sh.js 6.7s decode (32-bit with carries)\n// Arith.js 317.0s decode (64-bit no carries); int64 crippling it.\n\n//----------------------------------------------------------------------\n// Arithmetic (range) coder\nmodule.exports = class RangeCoder {\n constructor(src) {\n\tthis.low = 0;\n\tthis.range = 0xffffffff;\n\tthis.code = 0;\n\tthis.FFnum = 0;\n\tthis.carry = 0;\n\tthis.cache = 0;\n }\n\n RangeStartDecode(src) {\n\tfor (var i = 0; i < 5; i++)\n\t this.code = (this.code << 8) + src.ReadByte();\n\tthis.code &= 0xffffffff;\n\tthis.code >>>= 0; // force to be +ve int\n }\n\n RangeGetFrequency(tot_freq) {\n\tthis.range = Math.floor(this.range / tot_freq);\n\t//return this.code / this.range;\n\treturn Math.floor(this.code / this.range);\n\n\t// Conceptual scenario; return freq only and don't modify range yet\n\t//return Math.floor(this.code / (Math.floor(this.range / tot_freq)));\n }\n\n RangeDecode(src, sym_low, sym_freq, tot_freq) {\n\t// Conceptually we divide range here, but in practice we cached it earlier\n\t//this.range = Math.floor(this.range / tot_freq);\n\n\tthis.code -= sym_low * this.range;\n\tthis.range *= sym_freq;\n\n\twhile (this.range < (1<<24)) {\n\t this.range *= 256;\n\t this.code = (this.code*256 + src.ReadByte());\n\t}\n }\n\n RangeShiftLow(dst) {\n\t// We know range is < (1<<24) as we got here. We already have a\n\t// cached copy of 8 bits from low. Is this correct, or does it need\n\t// fixing? Possible scenarios.\n\t// 1. Low < 0xff000000 thus low+range < 0xffffffff and cache\n\t// cannot possibly change. Output cache and as many ffs as needed.\n\t// 2. We already detected an overflow in RangeEncode, setting carry.\n\t// In this case output cached byte + 1 and any 00s needed.\n\t// 3. Neither case - range is low but we haven't yet detected if we're\n\t// XXffffff or XY000000 scenario. Increase counter for ff/00s.\n\n\tif (this.low < 0xff000000 | this.carry) {\n\t // cached byte if no overflow, byte+1 otherwise\n\t dst.WriteByte(this.cache + this.carry);\n\n\t // Flush any tracked FFs (no carry) or 00s (carry).\n\t while (this.FFnum) {\n\t\tdst.WriteByte(this.carry-1);\n\t\tthis.FFnum--;\n\t }\n\n\t // Take a copy of top byte ready for next flush\n\t this.cache = this.low >>> 24;\n\t this.carry = 0;\n\t} else {\n\t this.FFnum++; // keep track of number of trailing ff/00 bytes to write\n\t}\n\tthis.low <<= 8;\n\tthis.low >>>= 0; // force to be +ve int\n }\n\n RangeEncode(dst, sym_low, sym_freq, tot_freq) {\n\tvar old_low = this.low\n\tthis.range = Math.floor(this.range / tot_freq)\n\tthis.low += sym_low * this.range;\n\tthis.low >>>= 0; // Truncate to +ve int so we can spot overflow\n\tthis.range *= sym_freq;\n\n\t// \"low + sym*range < old_low\" means we overflow; set carry.\n\t// NB: can this.low < old_low occur twice before range < (1<<24)?\n\t// We claim not, but prove it!\n\tif (this.low < old_low) {\n\t if (this.carry != 0) console.log(\"ERROR: Multiple carry\")\n\t this.carry = 1\n\t}\n\n\t// Renormalise if range gets too small\n\twhile (this.range < (1<<24)) {\n\t this.range *= 256;\n\t this.RangeShiftLow(dst);\n\t}\n }\n\n RangeFinishEncode(dst) {\n\tfor (var i = 0; i < 5; i++)\n\t this.RangeShiftLow(dst)\n }\n};\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// An adaptive probability model for encoding and decoding of symbols\n// within a given alphabet, using the range coder to get/put the\n// compressed data.\n\nconst MAX_FREQ = ((1<<16)-17)\nconst STEP = 16\n\nmodule.exports = class ByteModel {\n constructor(max_sym = 256) {\n\tthis.total_freq = max_sym;\n\tthis.max_sym = max_sym-1;\n\tthis.S = new Array\n\tthis.F = new Array\n\n\tfor (var i = 0; i <= this.max_sym; i++) {\n\t this.S[i] = i;\n\t this.F[i] = 1;\n\t}\n }\n\n ModelDecode(src, rc) {\n\t// Find symbol\n\tvar freq = rc.RangeGetFrequency(this.total_freq);\n\n\t// Linear scan to find cumulative frequency 'freq'\n\tvar acc = 0;\n\tvar x = 0;\n\twhile (acc + this.F[x] <= freq)\n\t acc += this.F[x++];\n\n//\tfor (var acc = 0; (acc += this.F[x]) <= freq; x++)\n//\t ;\n//\tacc -= this.F[x];\n\n\t// Update range coder\n\trc.RangeDecode(src, acc, this.F[x], this.total_freq);\n\n\t// Update model\n\tthis.F[x] += STEP;\n\tthis.total_freq += STEP;\n\tif (this.total_freq > MAX_FREQ)\n\t this.ModelRenormalise();\n\t\n\n\t// Keep symbols approximately frequency sorted\n\tvar sym = this.S[x];\n\tif (x > 0 && this.F[x] > this.F[x-1]) {\n\t var tmp = this.F[x];\n\t this.F[x] = this.F[x-1];\n\t this.F[x-1] = tmp;\n\n\t tmp = this.S[x];\n\t this.S[x] = this.S[x-1];\n\t this.S[x-1] = tmp;\n\t}\n\n\treturn sym;\n }\n\n ModelRenormalise() {\n\t// Halve all the frequencies, being careful not to hit zero\n\tthis.total_freq = 0;\n\tfor (var i = 0; i <= this.max_sym; i++) {\n\t this.F[i] -= Math.floor(this.F[i] / 2);\n\t this.total_freq += this.F[i];\n\t}\n }\n\n ModelEncode(dst, rc, sym) {\n\t// Find cumulative frequency\n\tvar acc = 0;\n\tfor (var x = 0; this.S[x] != sym; x++)\n\t acc += this.F[x];\n\n\t// Encode\n\trc.RangeEncode(dst, acc, this.F[x], this.total_freq);\n\n\t// Update model\n\tthis.F[x] += STEP;\n\tthis.total_freq += STEP;\n\tif (this.total_freq > MAX_FREQ) // FIXME x2\n\t this.ModelRenormalise();\n\n\t// Keep symbols approximately frequency sorted\n\tvar sym = this.S[x];\n\tif (x > 0 && this.F[x] > this.F[x-1]) {\n\t var tmp = this.F[x];\n\t this.F[x] = this.F[x-1];\n\t this.F[x-1] = tmp;\n\n\t tmp = this.S[x];\n\t this.S[x] = this.S[x-1];\n\t this.S[x-1] = tmp;\n\t}\n }\n};\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nconst IOStream = require(\"./iostream\");\nconst ByteModel = require(\"./byte_model\");\nconst RangeCoder = require(\"./arith_sh\");\n\n\n//----------------------------------------------------------------------\n// Main arithmetic entry function: decodes a compressed src and\n// returns the uncompressed buffer.\n\nfunction read_array(src, tab, size) {\n var j = 0; // array value\n var z = 0; // array index: tab[j]\n var last = -1;\n\n // Remove first level of run-length encoding\n var R = new Array(1024) // runs\n while (z < size) {\n\tvar run = src.ReadByte()\n\tR[j++] = run\n\tz += run\n\n\tif (run == last) {\n\t var copy = src.ReadByte()\n\t z += run * copy\n\t while (copy--)\n\t\tR[j++] = run\n\t}\n\tlast = run\n }\n\n // Now expand runs in R to tab, noting 255 is max run\n var i = 0\n j = 0\n z = 0\n while (z < size) {\n\tvar run_len = 0\n\tdo {\n\t var part = R[j++]\n\t run_len += part\n\t} while (part == 255)\n\t\n\twhile (run_len--)\n\t tab[z++] = i;\n\ti++\n }\n}\n\nconst QMAX = 256\n\nconst FLAG_DEDUP = 2\nconst FLAG_FLEN = 4\nconst FLAG_SEL = 8 // whether selector is used in context\nconst FLAG_QMAP = 16\nconst FLAG_PTAB = 32\nconst FLAG_DTAB = 64\nconst FLAG_QTAB = 128\n\nconst GFLAG_MULTI_PARAM = 1\nconst GFLAG_HAVE_STAB = 2\nconst GFLAG_DO_REV = 4\n\n// Compute a new context from our current state and qual q\nfunction fqz_update_ctx(params, state, q) {\n var last = params.context\n state.qctx = ((state.qctx << params.qshift) + params.qtab[q]); // >>> 0\n last += ((state.qctx & ((1<<params.qbits)-1)) << params.qloc); // >>> 0\n\n if (params.do_pos)\n\tlast += params.ptab[Math.min(state.p, 1023)] << params.ploc\n\n if (params.do_delta) {\n\tlast += params.dtab[Math.min(state.delta, 255)] << params.dloc\n\t// Is it better to use q here or qtab[q]?\n\t// If qtab[q] we can map eg [a-z0-9A-Z]->0 ,->1 and have\n\t// delta being a token number count into comma separated lists?\n\tstate.delta += (state.prevq != q) ? 1 : 0\n\tstate.prevq = q\n }\n\n if (params.do_sel)\n\tlast += state.s << params.sloc\n\n state.p--\n\n return last & 0xffff\n}\n\nfunction decode_fqz_single_param(src) {\n var p = {} // params\n \n // Load FQZ parameters\n p.context = src.ReadUint16()\n p.pflags = src.ReadByte()\n\n p.do_dedup = p.pflags & FLAG_DEDUP\n p.fixed_len = p.pflags & FLAG_FLEN\n p.do_sel = p.pflags & FLAG_SEL\n p.do_qmap = p.pflags & FLAG_QMAP\n p.do_pos = p.pflags & FLAG_PTAB\n p.do_delta = p.pflags & FLAG_DTAB\n p.do_qtab = p.pflags & FLAG_QTAB\n\n p.max_sym = src.ReadByte()\n\n var x = src.ReadByte()\n p.qbits = x>>4\n p.qshift = x&15\n x = src.ReadByte()\n p.qloc = x>>4\n p.sloc = x&15\n x = src.ReadByte()\n p.ploc = x>>4\n p.dloc = x&15\n\n // Qual map, eg to \"unbin\" Illumina qualities\n p.qmap = new Array(256);\n if (p.pflags & FLAG_QMAP) {\n\tfor (var i = 0; i < p.max_sym; i++)\n\t p.qmap[i] = src.ReadByte()\n } else {\n\t// Useful optimisation to speed up main loop\n\tfor (var i = 0; i < 256; i++)\n\t p.qmap[i] = i; // NOP\n }\n\n // Read tables\n p.qtab = new Array(1024);\n if (p.qbits > 0 && (p.pflags & FLAG_QTAB)) {\n\tread_array(src, p.qtab, 256)\n } else {\n\t// Useful optimisation to speed up main loop\n\tfor (var i = 0; i < 256; i++)\n\t p.qtab[i] = i; // NOP\n }\n\n p.ptab = new Array(1024);\n if (p.pflags & FLAG_PTAB)\n\tread_array(src, p.ptab, 1024);\n\n p.dtab = new Array(256);\n if (p.pflags & FLAG_DTAB)\n\tread_array(src, p.dtab, 256);\n\n return p\n}\n\nfunction decode_fqz_params(src) {\n var gparams = {\n\tmax_sym: 0\n }\n\n // Check fqz format version\n var vers = src.ReadByte()\n if (vers != 5) {\n\tconsole.error(\"Invalid FQZComp version number\");\n\treturn;\n }\n\n var gflags = src.ReadByte()\n var nparam = (gflags & GFLAG_MULTI_PARAM) ? src.ReadByte() : 1\n var max_sel = gflags.nparam > 1 ? gflags.nparam-1 : 0 // Note max_sel, not num_sel\n\n var stab = new Array(256);\n if (gflags & GFLAG_HAVE_STAB) {\n\tmax_sel = src.ReadByte()\n\tread_array(src, stab, 256);\n } else {\n\tfor (var i = 0; i < nparam; i++)\n\t stab[i] = i;\n\tfor (; i < 256; i++)\n\t stab[i] = nparam-1;\n }\n gparams.do_rev = (gflags & GFLAG_DO_REV)\n gparams.stab = stab\n gparams.max_sel = max_sel\n\n gparams.params = new Array(gparams.nparam)\n for (var p = 0; p < nparam; p++) {\n\tgparams.params[p] = decode_fqz_single_param(src)\n\tif (gparams.max_sym < gparams.params[p].max_sym)\n\t gparams.max_sym = gparams.params[p].max_sym\n }\n\n return gparams\n}\n\nfunction fqz_create_models(gparams) {\n var model = {}\n\n model.qual = new Array(1<<16)\n for (var i = 0; i < (1<<16); i++)\n\tmodel.qual[i] = new ByteModel(gparams.max_sym+1) // +1 as max value not num. values\n\n model.len = new Array(4)\n for (var i = 0; i < 4; i++)\n\tmodel.len[i] = new ByteModel(256)\n\n model.rev = new ByteModel(2)\n model.dup = new ByteModel(2)\n\n if (gparams.max_sel > 0)\n\tmodel.sel = new ByteModel(gparams.max_sel+1) // +1 as max value not num. values\n\n return model\n}\n\n// Initialise a new record, updating state.\n// Returns 1 if dup, otherwise 0\nfunction decode_fqz_new_record(src, rc, gparams, model, state, rev) {\n // Parameter selector\n if (gparams.max_sel > 0) {\n\tstate.s = model.sel.ModelDecode(src, rc)\n } else {\n\tstate.s = 0;\n }\n state.x = gparams.stab[state.s]\n\n var params = gparams.params[state.x]\n\n // Reset contexts at the start of each new record\n if (params.fixed_len >= 0) {\n\t// Not fixed or fixed but first record\n\tvar len = model.len[0].ModelDecode(src, rc)\n\tlen |= model.len[1].ModelDecode(src, rc) << 8\n\tlen |= model.len[2].ModelDecode(src, rc) << 16\n\tlen |= model.len[3].ModelDecode(src, rc) << 24\n\tif (params.fixed_len > 0)\n\t params.fixed_len = -len\n } else {\n\tlen = -params.fixed_len\n }\n state.len = len\n\n if (gparams.do_rev)\n\trev[state.rec] = model.rev.ModelDecode(src, rc)\n\n state.is_dup = 0\n if (params.pflags & FLAG_DEDUP) {\n\tif (model.dup.ModelDecode(src, rc))\n\t state.is_dup = 1\n }\n\n state.p = len; // number of remaining bytes in this record\n state.delta = 0\n state.qctx = 0\n state.prevq = 0\n state.rec++\n}\n\nfunction decode_fqz(src, q_lens) {\n // Decode parameter block\n var n_out = src.ReadUint7()\n var gparams = decode_fqz_params(src)\n if (!gparams) return\n var params = gparams.params\n var rev = new Array(q_lens.length)\n\n // Create initial models\n var model = fqz_create_models(gparams)\n\n // Create our entropy encoder and output buffers\n var rc = new RangeCoder(src)\n rc.RangeStartDecode(src)\n var output = new Buffer.allocUnsafe(n_out)\n\n // Internal FQZ state\n var state = {\n\tqctx:0, // Qual-only sub-context\n\tprevq:0, // Previous quality value\n\tdelta:0, // Running delta (q vs prevq)\n\tp:0, // Number of bases left in current record\n\ts:0, // Current parameter selector value (0 if unused)\n\tx:0, // \"stab\" tabulated copy of s\n\tlen:0, // Length of current string\n\tis_dup:0, // This string is a duplicate of last\n\trec:0 // Record number\n }\n\n // The main decode loop itself\n var i = 0 // position in output buffer\n while (i < n_out) {\n\tif (state.p == 0) {\n\t decode_fqz_new_record(src, rc, gparams, model, state, rev)\n\t if (state.is_dup > 0) {\n\t\tif (model.dup.ModelDecode(src, rc)) {\n\t\t // Duplicate of last line\n\t\t for (var x = 0; x < len; x++)\n\t\t\toutput[i+x] = output[i+x-state.len]\n\t\t i += state.len\n\t\t state.p = 0\n\t\t continue\n\t\t}\n\t }\n\t q_lens.push(state.len)\n\n\t var params = gparams.params[state.x]\n\t var last = params.context\n\t}\n\n\t// Decode the current quality (possibly mapped via qmap)\n\tvar Q = model.qual[last].ModelDecode(src, rc)\n\n\t//if (params.do_qmap)\n\t// output[i++] = params.qmap[Q];\n\t//else\n\t// output[i++] = Q\n\toutput[i++] = params.qmap[Q]; // optimised version of above\n\tlast = fqz_update_ctx(params, state, Q)\n }\n\n if (gparams.do_rev)\n\treverse_qualities(output, n_out, rev, q_lens)\n\n return output;\n}\n\nfunction reverse_qualities(qual, qual_len, rev, len) {\n var rec = 0\n var i = 0\n while (i < qual_len) {\n\tif (rev[rec]) {\n\t var j = 0\n\t var k = len[rec]-1\n\t while (j < k) {\n\t\tvar tmp = qual[i+j]\n\t\tqual[i+j] = qual[i+k]\n\t\tqual[i+k] = tmp\n\t\tj++\n\t\tk--\n\t }\n\t}\n\n\ti += len[rec++];\n }\n}\n\nfunction decode(src, q_lens) {\n var stream = new IOStream(src);\n\n //var n_out = stream.ReadUint32(); stream.ReadUint32(); // move to main\n\n return decode_fqz(stream, q_lens);\n}\n \n//----------------------------------------------------------------------\n// FQZComp encoder.\n\nfunction pick_fqz_params(src, q_lens, q_dirs, qhist) {\n // Find cardinality of q_dirs\n var qd_last = q_dirs[0];\n for (var i = 0; i < q_dirs.length; i++)\n\tif (q_dirs[i] != qd_last)\n\t break;\n var qd_fixed = (i == q_dirs.length) ? 1 : 0\n\n // Scan input to find number of symbols and max symbol\n var nsym = 0\n var max_sym = 0\n\n // selector == 0: Assume one single input dataset\n for (var i = 0; i < 256; i++)\n\tqhist[0][i] = 0;\n\n var rec = 0;\n var len = 0\n for (var i = 0; i < src.length; i++) {\n\tif (len == 0) {\n\t len = q_lens[rec < q_lens.length-1 ? rec++ : rec]\n\t}\n\tqhist[0][src[i]]++;\n\tlen--;\n }\n for (var i = 0; i < 256; i++) {\n\tif (!qhist[0][i])\n\t continue;\n\tif (max_sym < i)\n\t max_sym = i;\n\tnsym++;\n }\n\n var qshift = 5\n var do_qmap = 0\n // Reduced symbol frequencies implies lower qshift and\n // a lookup table to go from qual to Q\n if (nsym <= 16) {\n\tdo_qmap = 1 // based on qhist\n\tif (nsym <= 2)\n\t qshift = 1\n\telse if (nsym <= 4)\n\t qshift = 2\n\telse if (nsym <= 8)\n\t qshift = 3\n\telse\n\t qshift = 4\n }\n\n// // Two params and a 1-bit selector.\n// // This is 1% overhead vs two data sets compressed independently.\n// // It's 6.9% smaller than compressing both together with 1 param.\n// if (0) return [{\n//\t// q4\n//\tqbits: 8,\n//\tqshift: 2,\n//\tqloc: 7,\n//\n//\tpbits: 7,\n//\tpshift: 1,\n//\tploc: 0,\n//\n//\tdbits: 0,\n//\tdshift: 0,\n//\tdloc: 0,\n//\n// sbits: 0,\n// sloc: 0,\n//\n//\t//sbits: 2,\n//\t//do_stab: 1,\n//\tsbits: 1,\n//\tdo_stab: 0,\n//\tcontext: (0<<15),\n//\n//\tmax_sym: 36,\n//\tnsym: 4,\n//\n//\tdo_qmap: 1,\n//\tdo_dedup: 0,\n//\tfixed_len: 1,\n//\tdo_sel: 0,\n//\tdo_rev: 0,\n//\tdo_pos: 1,\n//\tdo_delta: 0,\n//\tdo_qtab: 0\n// }, {\n//\t//q40\n//\tqbits: 9,\n//\tqshift: 5,\n//\tqloc: 7,\n//\n//\tpbits: 7,\n//\tpshift: 0,\n//\tploc: 0,\n//\n//\tdbits: 0,\n//\tdshift: 0,\n//\tdloc: 0,\n//\n// sbits: 0,\n// sloc: 0,\n//\n//\t//sbits: 2,\n//\t//do_stab: 1,\n//\tsbits: 1,\n//\tdo_stab: 0,\n//\tcontext: (1<<15),\n//\n//\tmax_sym: 44,\n//\tnsym: 45,\n//\n//\tdo_qmap: 0,\n//\tdo_dedup: 0,\n//\tfixed_len: 1,\n//\tdo_sel: 0,\n//\tdo_rev: 0,\n//\tdo_pos: 1,\n//\tdo_delta: 0,\n//\tdo_qtab: 0\n// }]\n\n return [{qbits: 8+(qshift>4),\n\t qshift: qshift,\n\t qloc: 7,\n\n\t pbits: 7,\n\t pshift: q_lens[0] > 128 ? 1 : 0,\n\t ploc: 0,\n\n\t dbits: qshift>4 ? 0 : 1,\n\t dshift: 3,\n\t dloc: 15,\n\n\n\t // NB: Also useful as a way of embedding sel and doing sel\n\t // specific contexts. Identical bar context. Eg 0<<15 or 1<<15.\n\t sbits: 0,\n\t sloc: 15,\n\t do_stab: 0,\n\t context: (0<<15),\n\n\t max_sym: max_sym,\n\t nsym: nsym,\n\n\t do_qmap: do_qmap,\n\t do_dedup: 0,\n\t fixed_len: (q_lens.length == 1) ? 1 : 0,\n\t do_sel: 0,\n\t do_rev: 0,\n\t do_pos: 1,\n\t do_delta: (qshift <= 4) ? 1 : 0,\n\t do_qtab: 0,\n\n\t // Override above with some attempt at using selectors\n\t // when the q_dirs are specific and non-fixed.\n\t qbits: 8+(qshift>4)-(qd_fixed==0),\n\t sbits: 1,\n\t sloc: 15-(qshift<=4), // read1 vs read2\n\t do_stab: 1,\n\t do_sel: 1,\n\t \n//\t // q4+dir: 7245769 with, 7353962 without. 1.5% saving\n//\t qbits: 6,\n//\t dbits: 2,\n//\t dshift: 2,\n//\t dloc: 13,\n//\t sbits: 1,\n//\t sloc: 15,\n//\t do_stab: 1,\n//\t do_sel: 1,\n\n\t // with 20 bits of context, q40 = 31741545\n\t // qbits 10, dbits 2, pbits 7, sbits 1\n\t }]\n}\n\nfunction store_array(out, tab, size) {\n var i = 0; // index into tab\n var j = 0; // current value in tab[i]\n\n var tmp1 = new Array(size*2);\n var sz1 = 0;\n\n // First level of RLE. Replace all runs of 'j' values\n // with run-lengths, including zeros for missing values.\n // Eg 0 1 2 2 2 3 3 3 4 4 4 5 5 5 5 7 7\n // to 1 1 3 3 3 4 0 2\n while (i < size) {\n\t// Length of j^{th} element\n\tvar i_start = i\n\twhile (i < size && tab[i] == j)\n\t i++;\n\tvar run_len = i - i_start\n\n\t// Encode run length to tmp array\n\tdo {\n\t var r = Math.min(255, run_len)\n\t tmp1[sz1++] = r\n\t run_len -= r\n\t} while (r == 255)\n\tj++;\n }\n\n // Second round of RLE on our tmp array, using a different\n // RLE algorithm.\n // Eg 1 1 3 3 3 4 0 2\n // to 1 1 +0 3 3 +1 4 0 2\n var last = -1\n var tmp2 = new Array(size*2)\n var sz2 = 0\n i = 0 // index into tmp1]\n // k is used size of tmp1[]\n while (i < sz1) {\n\tvar curr = tmp1[i++];\n\ttmp2[sz2++] = curr\n\tif (curr == last) {\n\t var i_start = i;\n\t while (i < sz1 && tmp1[i] == last && i - i_start < 255)\n\t\ti++;\n\t tmp2[sz2++] = i - i_start;\n\t} else {\n\t last = curr\n\t}\n }\n\n // Append 2nd RLE, tmp2, to out.\n out.WriteData(tmp2, sz2)\n}\n\n\t\t\t\t \n\n// q_lens is an array of quality lengths per record.\n// (If they're all the same, just set one value.)\nfunction encode_fqz_params(out, params, qhist, qtab, ptab, dtab, stab) {\n var dsqr = [\n 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3,\n 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7\n ]\n\n for (var i = 0; i < params.length; i++)\n\tstab[i] = i; // 1 parameter set per selector value\n for (; i < 256; i++)\n\tstab[i] = params.length-1;\n\n // Store global meta-data\n out.WriteByte(5); // FQZ format number\n var gflags = ((params.length > 1) ? GFLAG_MULTI_PARAM : 0)\n\t | ((params[0].do_stab) ? GFLAG_HAVE_STAB : 0)\n out.WriteByte(gflags)\n\n if (gflags & GFLAG_MULTI_PARAM)\n\tout.WriteByte(params.length) // Number of parameter blocks.\n\n if (gflags & GFLAG_HAVE_STAB) {\n\tvar max_sel = 1<<params[0].sbits;\n\tif (max_sel > 0) max_sel--;\n\tout.WriteByte(max_sel)\n\tstore_array(out, stab, 256)\n }\n\n // Store per-param meta-data\n for (var p = 0; p < params.length; p++) {\n\tout.WriteUint16(params[p].context)\n\tout.WriteByte((params[p].do_qtab ? FLAG_QTAB : 0) | // FLAG\n\t\t (params[p].do_delta ? FLAG_DTAB : 0) |\n\t\t (params[p].do_pos ? FLAG_PTAB : 0) |\n\t\t (params[p].do_qmap ? FLAG_QMAP : 0) |\n\t\t (params[p].do_sel ? FLAG_SEL : 0) |\n\t\t (params[p].fixed_len? FLAG_FLEN : 0) |\n\t\t (params[p].do_dedup ? FLAG_DEDUP : 0))\n\tif (params[p].do_qmap)\n\t out.WriteByte(params[p].nsym)\n\telse\n\t out.WriteByte(params[p].max_sym)\n\tout.WriteByte((params[p].qbits << 4) | (params[p].qshift))\n\tout.WriteByte((params[p].qloc << 4) | (params[p].sloc))\n\tout.WriteByte((params[p].ploc << 4) | (params[p].dloc))\n\n\tif (params[p].do_qmap) {\n\t params[p].max_sym = params[p].nsym\n\t var n = 0;\n\t for (var i = 0; i < 256; i++) {\n\t\tif (qhist[p][i]) {\n\t\t out.WriteByte(i)\n\t\t qhist[p][i] = n++;\n\t\t}\n\t }\n\t // Ensure we have all matched input params\n\t for (; n < params[p].nsym; n++)\n\t\tout.WriteByte(0)\n\t} else {\n\t //params[p].nsym = 255;\n\t for (var i = 0; i < 256; i++)\n\t\tqhist[p][i] = i; // NOP\n\t}\n\n\tif (params[p].qbits > 0) {\n\t //\t// Eg map 0-44 to a smaller range, to improve context usage.\n\t //\t// Makes q40 test set go from 33596471 to 33450075 (-0.4%)\n\t //\tparams[p].do_qtab = 1;\n\t //\tfor (var j = i = 0; i < params[p].max_sym; i++) {\n\t //\t qtab[i]=j;\n\t //\t if ((i%3)!=0 | i >= 28) j++\n\t //\t console.log(\"qtab[\",i,\"]=\",qtab[i]);\n\t //\t}\n\t //\tfor (; i < 256; i++)\n\t //\t qtab[i] = qtab[params[p].max_sym-1]\n\n\t for (var i = 0; i < 256; i++)\n\t\tqtab[p][i] = i; // NOP for now\n\n\t if (params[p].do_qtab)\n\t\tstore_array(out, qtab[p], 256)\n\t}\n\n\tif (params[p].pbits > 0) {\n\t for (var i = 0; i < 1024; i++)\n\t\tptab[p][i] = Math.min((1<<params[p].pbits)-1, i >> params[p].pshift)\n\n\t store_array(out, ptab[p], 1024)\n\t}\n\n\tif (params[p].dbits > 0) {\n\t for (var i = 0; i < 256; i++)\n\t\tif (dsqr[i] > (1<<params[p].dbits) - 1)\n\t\t dsqr[i] = (1<<params[p].dbits) - 1\n\t for (var i = 0; i < 256; i++)\n\t\tdtab[p][i] = dsqr[Math.min(dsqr.length-1, i >> params[p].dshift)]\n\n\t store_array(out, dtab[p], 256)\n\t}\n }\n\n return out\n}\n\nfunction encode_fqz(out, src, q_lens, q_dirs, params, qhist, qtab, ptab, dtab, stab) {\n //console.error(\"0:\",params[0])\n //console.error(\"1:\",params[1])\n\n var max_sel = 1<<params[0].sbits\n if (max_sel > 0) max_sel--\n var n_in = src.length\n\n // Create the models\n var max_sym = 0;\n for (var p = 0; p < params.length; p++)\n\tif (max_sym < params[p].max_sym)\n\t max_sym = params[p].max_sym;\n\n var model_qual = new Array(1<<16)\n for (var i = 0; i < (1<<16); i++)\n\tmodel_qual[i] = new ByteModel(max_sym+1)\n\n var model_len = new Array(4)\n for (var i = 0; i < 4; i++)\n\tmodel_len[i] = new ByteModel(256)\n\n var model_rev = new ByteModel(2)\n var model_dup = new ByteModel(2)\n var model_sel = new ByteModel(max_sel+1)\n\n // Note: our JavaScript encoder doesn't have a way for reversing\n // some quality strings, so we ignore do_rev for now.\n var rc = new RangeCoder(src)\n\n // The main encoding loop\n var p = 0; // remaining position along current record\n var i = 0; // index in src data\n var rec = 0;\n\n while (i < n_in) {\n\tif (p == 0) {\n\t //var s = 0 // single non-mixed sample\n\t var s = q_dirs[rec]\n\t if (params[0].sbits > 0) {// FIXME: check All params[].do_stab / sbits must be identical\n\t\t//console.log(\"Ssel\", s)\n\t model_sel.ModelEncode(out, rc, s)\n\t }\n\t var x = stab[s]\n\n\t // Reset contexts at the statr of each new record\n\t var len = q_lens[Math.min(q_lens.length-1, rec++)]\n\t if (params[x].fixed_len) {\n\t\tif (params[x].fixed_len > 0) { // First length\n\t\t //console.log(\"Len\", len)\n\t\t model_len[0].ModelEncode(out, rc, len & 0xff)\n\t\t model_len[1].ModelEncode(out, rc, (len>>8) & 0xff)\n\t\t model_len[2].ModelEncode(out, rc, (len>>16) & 0xff)\n\t\t model_len[3].ModelEncode(out, rc, (len>>24) & 0xff)\n\t\t params[x].fixed_len = -1; // indicate we've stored it once\n\t\t}\n\t } else {\n\t\t//console.log(\"len\", len)\n\t\tmodel_len[0].ModelEncode(out, rc, len & 0xff)\n\t\tmodel_len[1].ModelEncode(out, rc, (len>>8) & 0xff)\n\t\tmodel_len[2].ModelEncode(out, rc, (len>>16) & 0xff)\n\t\tmodel_len[3].ModelEncode(out, rc, (len>>24) & 0xff)\n\t }\n\n\t if (params[x].do_dedup)\n\t\tprocess.exit(1) // FIXME\n\n\t p = len\n\t var delta = 0\n\t //var last = 0\n\t var last = params[x].context\n\t var qlast = 0\n\t var q1 = 0\n\t}\n\n\t// Encode current quality\n\tvar q = src[i++]\n\tvar Q = qhist[x][q]\n\tmodel_qual[last].ModelEncode(out, rc, Q)\n\t//console.log(\"Ctx\",last,qhist[x][q])\n\n\t// Update contexts for next quality\n\tqlast = (qlast << params[x].qshift) + qtab[x][Q]\n\tlast = params[x].context\n\tlast += (qlast & ((1<<params[x].qbits)-1)) << params[x].qloc\n\n\t// 46.6-48.6 billion cycles with ifs + \"<< params[x].?loc\" shifts\n\t// 47.3-47.3 billion cycles with ifs\n\t// 47.1-47.9 billion cycles without ifs\n\tif (params[x].pbits > 0)\n\t last += ptab[x][Math.min(p, 1023)] << params[x].ploc\n\n\tif (params[x].dbits > 0) {\n\t last += dtab[x][Math.min(delta, 255)] << params[x].dloc\n\t delta += (q1 != Q) ? 1 : 0\n\t q1 = Q\n\t}\n\n\tif (params[x].do_sel)\n\t last += s << params[x].sloc\n\n\tlast = (last & 0xffff)\n\tp--\n }\n\n rc.RangeFinishEncode(out)\n return out.buf.slice(0, out.pos)\n}\n\nfunction encode(src, q_lens, q_dirs) {\n var qhist = new Array(2)\n var qtab = new Array(2)\n var ptab = new Array(2)\n var dtab = new Array(2)\n var stab = new Array(256)\n\n for (var s = 0; s < 2; s++) {\n qhist[s] = new Array(256)\n qtab[s] = new Array(256)\n ptab[s] = new Array(1024) \n dtab[s] = new Array(256)\n }\n\n var out = new IOStream(\"\", 0, src.length*1.1 + 100); // FIXME: guestimate worst case\n\n out.WriteUint7(src.length);\n var params = pick_fqz_params(src, q_lens, q_dirs, qhist)\n var out = encode_fqz_params(out, params, qhist, qtab, ptab, dtab, stab)\n return encode_fqz(out, src, q_lens, q_dirs, params, qhist, qtab, ptab, dtab, stab)\n}\n\nmodule.exports = { decode, encode }\n","/*\n * Copyright (c) 2020 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// This is an interface to the htscodecs reference implementation of\n// the CRAM 3.1 codecs.\n\n// This JavaScript file is not part of the reference implementation\n// and is simply and interface to get a consistent interface for cram-js.\n\n\"use strict\";\n\nvar r4x8 = require('./rans');\nvar r4x16 = require('./rans4x16');\nvar arith = require('./arith_gen');\nvar fqzcomp = require('./fqzcomp');\nvar tok3 = require('./tok3');\n\nfunction r4x8_uncompress(inputBuffer, outputBuffer) {\n r4x8.decode(inputBuffer).copy(outputBuffer, 0, 0);\n}\n\nfunction r4x16_uncompress(inputBuffer, outputBuffer) {\n r4x16.decode(inputBuffer).copy(outputBuffer, 0, 0);\n}\n\nfunction arith_uncompress(inputBuffer, outputBuffer) {\n arith.decode(inputBuffer).copy(outputBuffer, 0, 0);\n}\n\nfunction fqzcomp_uncompress(inputBuffer, outputBuffer) {\n var q_lens = new Array\n fqzcomp.decode(inputBuffer, q_lens).copy(outputBuffer, 0, 0);\n}\n\nfunction tok3_uncompress(inputBuffer, outputBuffer) {\n // Returns in string form instead of buffer\n var out = tok3.decode(inputBuffer, 0, '\\0');\n Buffer.from(out, 'binary').copy(outputBuffer, 0, 0);\n}\n\nmodule.exports = {\n r4x8_uncompress: r4x8_uncompress,\n r4x16_uncompress: r4x16_uncompress,\n arith_uncompress: arith_uncompress,\n fqzcomp_uncompress: fqzcomp_uncompress,\n tok3_uncompress: tok3_uncompress,\n};\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// Turn a buffer into a fake stream with get / put commands.\n// This enables up to closely match the published pseudocode.\nmodule.exports = class IOStream {\n constructor(buf, start_pos = 0, size = 0) {\n\tif (size != 0) {\n\t this.buf = Buffer.allocUnsafe(size)\n\t this.length = size\n\t} else {\n\t this.buf = buf\n\t this.length = buf.length\n\t}\n\tthis.pos = start_pos\n }\n\n // ----------\n // Reading\n EOF() {\n\treturn this.pos >= this.length\n }\n\n ReadData(len) {\n\tvar A = this.buf.slice(this.pos, this.pos+len)\n\tthis.pos += len;\n\treturn A\n }\n\n ReadByte() {\n\tconst b = this.buf[this.pos]\n\tthis.pos++\n\treturn b\n }\n\n ReadChar() {\n\tconst b = this.buf[this.pos]\n\tthis.pos++\n\treturn String.fromCharCode(b)\n }\n\n ReadUint16() {\n\tvar i = this.ReadByte()\n\ti |= this.ReadByte()<<8\n\treturn i\n }\n\n ReadUint32() {\n\tconst i = this.buf.readInt32LE(this.pos)\n\tthis.pos += 4\n\treturn i\n }\n\n // nul terminated string\n ReadString() {\n\tvar s = \"\"\n\tdo {\n\t var b = this.buf[this.pos++]\n\t if (b)\n\t\ts += String.fromCharCode(b)\n\t} while (b)\n\treturn s\n }\n\n// ReadUint7() {\n//\t// Variable sized unsigned integers\n//\tvar i = 0;\n//\tvar s = 0;\n//\tdo {\n//\t var c = this.ReadByte();\n//\t i = i | ((c & 0x7f)<<s);\n//\t s += 7;\n//\t} while ((c & 0x80))\n//\n//\treturn i;\n// }\n\n ReadUint7() {\n\t// Variable sized unsigned integers\n\tvar i = 0;\n\tdo {\n\t var c = this.ReadByte();\n\t i = (i<<7) | (c & 0x7f)\n\t} while ((c & 0x80))\n\n\treturn i;\n }\n\n ReadITF8() {\n\tvar i = this.buf[this.pos];\n\tthis.pos++;\n\n\t//process.stderr.write(\"i=\"+i+\"\\n\");\n\n\tif (i >= 0xf0) {\n\t // 1111xxxx => +4 bytes\n\t i = (i & 0x0f) << 28;\n\t i += (this.buf[this.pos+0] << 20)\n\t + (this.buf[this.pos+1] << 12)\n\t + (this.buf[this.pos+2] << 4)\n\t + (this.buf[this.pos+3] >> 4);\n\t this.pos += 4;\n\t //process.stderr.write(\" 4i=\"+i+\"\\n\");\n\t} else if (i >= 0xe0) {\n\t // 1110xxxx => +3 bytes\n\t i = (i & 0x0f) << 24;\n\t i += (this.buf[this.pos+0] << 16)\n\t + (this.buf[this.pos+1] << 8)\n\t + (this.buf[this.pos+2] << 0);\n\t this.pos += 3;\n\t //process.stderr.write(\" 3i=\"+i+\"\\n\");\n\t} else if (i >= 0xc0) {\n\t // 110xxxxx => +2 bytes\n\t i = (i & 0x1f) << 16;\n\t i += (this.buf[this.pos+0] << 8)\n\t + (this.buf[this.pos+1] << 0);\n\t this.pos += 2;\n\t //process.stderr.write(\" 2i=\"+i+\"\\n\");\n\t} else if (i >= 0x80) {\n\t // 10xxxxxx => +1 bytes\n\t i = (i & 0x3f) << 8;\n\t i += this.buf[this.pos];\n\t this.pos++;;\n\t //process.stderr.write(\" 1i=\"+i+\"\\n\");\n\t} else {\n\t // 0xxxxxxx => +0 bytes\n\t}\n\n\treturn i;\n }\n\n // ----------\n // Writing\n WriteByte(b) {\n\tthis.buf[this.pos++] = b\n }\n\n WriteChar(b) {\n\tthis.buf[this.pos++] = b.charCodeAt(0)\n }\n\n WriteString(str) {\n\tfor (var i = 0; i < str.length; i++)\n\t this.buf[this.pos++] = str.charCodeAt(i)\n\tthis.buf[this.pos++] = 0\n }\n\n WriteData(buf, len) {\n\tfor (var i = 0; i < len; i++)\n\t this.buf[this.pos++] = buf[i]\n }\n\n WriteStream(stream) {\n\tthis.WriteData(stream.buf, stream.pos)\n }\n\n WriteUint16(u) {\n\t//this.buf.writeInt16LE(u, this.pos);\n\tthis.WriteByte(u&0xff)\n\tthis.WriteByte((u>>8)&0xff)\n }\n\n WriteUint32(u) {\n\tthis.buf.writeInt32LE(u, this.pos);\n\tthis.pos += 4;\n }\n\n// WriteUint7(i) {\n//\tdo {\n//\t this.WriteByte((i & 0x7f) | ((i > 0x80) << 7));\n//\t i >>= 7;\n//\t} while (i > 0);\n// }\n\n WriteUint7(i) {\n\tvar s = 0;\n\tvar X = i;\n\tdo {\n\t s += 7;\n\t X >>= 7;\n\t} while (X > 0);\n\n\tdo {\n\t s -= 7;\n\t this.WriteByte(((i >> s) & 0x7f) + ((s > 0) << 7))\n\t} while (s > 0);\n }\n\n WriteITF8(i) {\n\t// Horrid, ITF8 is unsigned, but we still write signed into it\n\tif (i < 0)\n\t i = (1<<32) + i\n\n\tif (i <= 0x0000007f) {\n\t // 1 byte\n\t this.buf[this.pos++] = i\n\t} else if (i <= 0x00003fff) {\n\t // 2 bytes\n\t this.buf[this.pos++] = 0x80 | Math.floor(i / 256)\n\t this.buf[this.pos++] = i & 0xff;\n\t} else if (i < 0x0001ffff) {\n\t // 3 bytes\n\t this.buf[this.pos++] = 0xc0 | Math.floor(i / 65536)\n\t this.buf[this.pos++] = Math.floor(i / 256) & 0xff\n\t this.buf[this.pos++] = i & 0xff;\n\t} else if (i < 0x0fffffff) {\n\t // 4 bytes\n\t this.buf[this.pos++] = 0xe0 | Math.floor(i / 16777216)\n\t this.buf[this.pos++] = Math.floor(i / 65536) & 0xff\n\t this.buf[this.pos++] = Math.floor(i / 256) & 0xff\n\t this.buf[this.pos++] = i & 0xff;\n\t} else {\n\t // 5 bytes; oddly using 4.5 bytes\n\t this.buf[this.pos++] = 0xf0 | Math.floor(i / 268435456)\n\t this.buf[this.pos++] = Math.floor(i / 1048576) & 0xff\n\t this.buf[this.pos++] = Math.floor(i / 4096) & 0xff\n\t this.buf[this.pos++] = Math.floor(i / 4) & 0xff\n\t this.buf[this.pos++] = i & 0x0f;\n\t}\n }\n\n // ----------\n // Writing from end of buffer going backwards.\n // Needed by rANS codec.\n WriteByteNeg(b) {\n\tthis.buf[--this.pos] = b;\n }\n};\n","/*\n * Copyright (c) 2019-2020 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nconst IOStream = require(\"./iostream\");\n\n//----------------------------------------------------------------------\n// rANS primitives itself\n//\n// RansGet* is decoder side\n\nfunction RansGetCumulativeFreq(R) {\n return R & 0xfff;\n}\n\nfunction RansGetSymbolFromFreq(C, f) {\n // NOTE: Inefficient.\n // In practice we would implement this via a precomputed\n // lookup table C2S[f]; see RansBuildC2S below.\n var s = 0;\n while (f >= C[s+1])\n\ts++;\n\n return s;\n}\n\nfunction RansBuildC2S(C) {\n var C2S = new Array(0x1000);\n var s = 0;\n for (var f = 0; f < 0x1000; f++) {\n\twhile (f >= C[s+1])\n\t s++;\n\tC2S[f] = s;\n }\n return C2S;\n}\n\nfunction RansAdvanceStep(R, c, f) {\n return f * (R >> 12) + (R & 0xfff) - c;\n}\n\nfunction RansRenorm(src, R) {\n while (R < (1<<23))\n\tR = (R << 8) + src.ReadByte();\n\n return R;\n}\n\n\n// RanEnc* is for encoder\nfunction RansEncInit() {\n return 1<<23;\n}\n\nfunction RansEncFlush(R, dst) {\n dst.WriteByteNeg((R >> 24) & 0xff);\n dst.WriteByteNeg((R >> 16) & 0xff);\n dst.WriteByteNeg((R >> 8) & 0xff);\n dst.WriteByteNeg((R >> 0) & 0xff);\n}\n\nfunction RansEncRenorm(R, dst, freq, scale_bits) {\n var R_max = (((1 << 23) >> scale_bits) << 8) * freq;\n\n while (R >= R_max) {\n\tdst.WriteByteNeg(R & 0xff);\n\tR >>= 8;\n }\n return R;\n}\n\n// Puts a symbol with frequency freq, cumulative freq start\n// and total freq 1<<scale_bits.\n//\n// Note with static probabilities, /freq and %freq could be\n// precomputed via multiplies and shifts.\nfunction RansEncPut(R, dst, start, freq, scale_bits) {\n var scale = 1<<scale_bits;\n R = RansEncRenorm(R, dst, freq, scale_bits);\n R = (Math.floor(R / freq) << scale_bits) + (R % freq) + start;\n return R;\n}\n\n//----------------------------------------------------------------------\n// Main rANS entry function: decodes a compressed src and\n// returns the uncompressed buffer.\nfunction decode(src) {\n var stream = new IOStream(src);\n var order = stream.ReadByte();\n var n_in = stream.ReadUint32();\n var n_out = stream.ReadUint32();\n\n if (order == 0) {\n\treturn RansDecode0(stream, n_out)\n } else {\n\treturn RansDecode1(stream, n_out)\n }\n}\n\nfunction encode(src, order) {\n //var stream = new IOStream(src);\n //var n_in = stream.ReadUint32();\n //var n_out = stream.ReadUint32();\n\n if (order == 0) {\n\treturn RansEncode0(src)\n } else {\n\treturn RansEncode1(src)\n }\n}\n\n//----------------------------------------------------------------------\n// Order-0 decoder\n\n// Decode a single table of order-0 frequences,\n// filling out the F and C arrays.\nfunction ReadFrequencies0(src, F, C) {\n // Initialise; not in the specification - implicit?\n for (var i = 0; i < 256; i++)\n\tF[i] = 0;\n\n var sym = src.ReadByte();\n var last_sym = sym;\n var rle = 0;\n\n // Read F[]\n do {\n\tvar f = src.ReadITF8();\n\tF[sym] = f;\n\tif (rle > 0) {\n\t rle--;\n\t sym++;\n\t} else {\n\t sym = src.ReadByte();\n\t if (sym == last_sym+1)\n\t\trle = src.ReadByte();\n\t}\n\tlast_sym = sym;\n } while (sym != 0);\n\n // Compute C[] from F[]\n C[0] = 0;\n for (var i = 0; i <= 255; i++)\n\tC[i+1] = C[i] + F[i];\n}\n\nfunction RansDecode0(src, nbytes) {\n // Decode frequencies\n var F = new Array(256);\n var C = new Array(256);\n ReadFrequencies0(src, F, C);\n\n // Fast lookup to avoid slow RansGetSymbolFromFreq\n var C2S = RansBuildC2S(C);\n\n // Initialise rANS state\n var R = new Array(4);\n for (var i = 0; i < 4; i++)\n\tR[i] = src.ReadUint32();\n\n // Main decode loop\n var output = new Buffer.allocUnsafe(nbytes);\n for (var i = 0; i < nbytes; i++) {\n\tvar i4 = i%4;\n\tvar f = RansGetCumulativeFreq(R[i4]);\n\tvar s = C2S[f]; // Equiv to RansGetSymbolFromFreq(C, f);\n\n\toutput[i] = s;\n\tR[i4] = RansAdvanceStep(R[i4], C[s], F[s]);\n\tR[i4] = RansRenorm(src, R[i4]);\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------\n// Order-0 encoder\n\nfunction BuildFrequencies0(src, F) {\n for (var i = 0; i < 256; i++)\n\tF[i] = 0;\n\n for (var i = 0; i < src.length; i++)\n\tF[src[i]]++;\n}\n\nfunction NormaliseFrequencies0(F) {\n // Compute total\n var tot = 0;\n for (var i = 0; i < 256; i++)\n\ttot += F[i];\n\n // Scale total of frequencies to max\n const max = (1<<12);\n var scale = max / tot;\n do {\n\tvar max_val = 0;\n\tvar max_idx = 0;\n\tvar renorm = 0;\n\ttot = 0;\n\tfor (var i = 0; i < 256; i++) {\n\t if (F[i] == 0)\n\t\tcontinue\n\n\t if (max_val < F[i]) {\n\t\tmax_val = F[i]\n\t\tmax_idx = i\n\t }\n\n\t F[i] = Math.floor(F[i] * scale);\n\t if (F[i] == 0)\n\t\tF[i] = 1;\n\n\t tot += F[i];\n\t}\n\n\t// Adjust new tot to ensure it matches.\n\tif (tot < max) {\n\t // Too low, boost the most common symbol\n\t F[max_idx] += max-tot;\n\t} else if (tot-max < F[max_idx]/2 && F[max_idx] > 2) {\n\t // Too high, reduce the common symbol\n\t F[max_idx] -= tot-max;\n\t} else if (tot != max) {\n\t // Much too high, fudge scale and try again.\n\t scale = scale * 0.99\n\t renorm = 1;\n\t}\n } while (renorm)\n}\n\nfunction WriteFrequencies0(out, F) {\n var rle = 0;\n for (var i = 0; i < 256; i++) {\n\tif (!F[i])\n\t continue\n\n\t// Output Symbol if needed and Frequency\n\tif (rle > 0)\n\t rle--\n\telse {\n\t out.WriteByte(i)\n\n\t if (i > 0 && F[i-1] > 0) {\n\t\t// We've encoded two symbol frequencies in a row.\n\t\t// How many more are there? Store that count so\n\t\t// we can avoid writing consecutive symbols.\n\t\tfor (rle = i+1; rle<256 && F[rle]; rle++)\n\t\t ;\n\t\trle -= i+1;\n\n\t\tout.WriteByte(rle);\n\t }\n\t}\n\n\tout.WriteITF8(F[i])\n }\n out.WriteByte(0);\n}\n\nfunction RansEncode0(src) {\n const nbytes = src.length\n var output = new IOStream(\"\", 0, 257*3+9);\n\n output.WriteByte(0); // Order 0\n output.WriteUint32(0); // compressed size: correct later\n output.WriteUint32(0); // uncompressed size: correct later\n\n // Compute frequencies\n var F = new Array(256)\n BuildFrequencies0(src, F)\n NormaliseFrequencies0(F);\n WriteFrequencies0(output, F);\n\n // Compute cumulative frequencies\n var C = new Array(256)\n C[0] = 0;\n for (var i = 1; i < 256; i++)\n\tC[i] = C[i-1] + F[i-1];\n\n // Initialise rANS state\n var R = new Array(4);\n for (var i = 0; i < 4; i++)\n\tR[i] = RansEncInit();\n\n var alloc = Math.floor(nbytes*1.05+100)\n var rans_out = new IOStream(\"\", alloc, alloc)\n\n // Main encode loop\n for (var i = nbytes-1; i >= 0; i--)\n\tR[i%4] = RansEncPut(R[i%4], rans_out, C[src[i]], F[src[i]], 12);\n\n for (var i = 3; i >= 0; i--)\n\tRansEncFlush(R[i], rans_out);\n\n // Stitch blocks together into final output buffer\n var freq_tab = output.pos\n output.buf.writeInt32LE(freq_tab-9 + (rans_out.length - rans_out.pos), 1);\n output.buf.writeInt32LE(nbytes, 5);\n\n return Buffer.concat([output.buf.slice(0, output.pos),\n\t\t\t rans_out.buf.slice(rans_out.pos, rans_out.length)],\n\t\t\t output.pos + rans_out.length - rans_out.pos);\n}\n\n//----------------------------------------------------------------------\n// Order-1 decoder\n\n// Decode a table of order-1 frequences,\n// filling out the F and C arrays.\nfunction ReadFrequencies1(src, F, C) {\n // Initialise; not in the specification - implicit?\n for (var i = 0; i < 256; i++) {\n\tF[i] = new Array(256);\n\tC[i] = new Array(256);\n\tfor (var j = 0; j < 256; j++)\n\t F[i][j] = 0;\n }\n\n var sym = src.ReadByte();\n var last_sym = sym;\n var rle = 0;\n\n // Read F[]\n do {\n\tReadFrequencies0(src, F[sym], C[sym]);\n\n\tif (rle > 0) {\n\t rle--;\n\t sym++;\n\t} else {\n\t sym = src.ReadByte();\n\t if (sym == last_sym+1)\n\t\trle = src.ReadByte();\n\t}\n\tlast_sym = sym;\n } while (sym != 0);\n}\n\nfunction RansDecode1(src, nbytes) {\n // Decode frequencies\n var F = new Array(256);\n var C = new Array(256);\n ReadFrequencies1(src, F, C);\n\n // Fast lookup to avoid slow RansGetSymbolFromFreq\n var C2S = new Array(256);\n for (var i = 0; i < 256; i++)\n\tC2S[i] = RansBuildC2S(C[i]);\n\n // Initialise rANS state\n var R = new Array(4);\n var L = new Array(4);\n for (var j = 0; j < 4; j++) {\n\tR[j] = src.ReadUint32();\n\tL[j] = 0;\n }\n\n // Main decode loop\n var output = new Buffer.allocUnsafe(nbytes);\n var nbytes4 = Math.floor(nbytes/4);\n for (var i = 0; i < nbytes4; i++) {\n\tfor (var j = 0; j < 4; j++) {\n\t var f = RansGetCumulativeFreq(R[j]);\n\n\t //var s = RansGetSymbolFromFreq(C[L[j]], f);\n\t var s = C2S[L[j]][f]; // Precomputed version of above\n\n\t output[i+j*nbytes4] = s;\n\t R[j] = RansAdvanceStep(R[j], C[L[j]][s], F[L[j]][s]);\n\t R[j] = RansRenorm(src, R[j]);\n\t L[j] = s;\n\t}\n }\n\n // Now deal with the remainder if buffer size is not a multiple of 4,\n // using rANS state 3 exclusively. (It'd have been nice to have\n // designed this to just act as if we kept going with a bail out.)\n i = 4*i;\n while (i < nbytes) {\n\tvar f = RansGetCumulativeFreq(R[3]);\n\tvar s = RansGetSymbolFromFreq(C[L[3]], f);\n\toutput[i++] = s;\n\tR[3] = RansAdvanceStep(R[3], C[L[3]][s], F[L[3]][s]);\n\tR[3] = RansRenorm(src, R[3]);\n\tL[3] = s;\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------\n// Order-1 encoder\n\nfunction BuildFrequencies1(src, F, F0) {\n for (var i = 0; i < 256; i++) {\n\tF0[i] = 0;\n\tfor (var j = 0; j < 256; j++)\n\t F[i][j] = 0;\n }\n\n var last = 0;\n for (var i = 0; i < src.length; i++) {\n\tF0[src[i]]++;\n\tF[last][src[i]]++;\n\t//F[last][src[i]]++;\n\tlast = src[i];\n }\n\n // Also accept we'll be starting at 4 points, not just byte 0\n F[0][src[1*(src.length >> 2)]]++;\n F[0][src[2*(src.length >> 2)]]++;\n F[0][src[3*(src.length >> 2)]]++;\n F0[0] += 3;\n}\n\nfunction NormaliseFrequencies1(F, F0) {\n for (var i = 0; i < 256; i++)\n\tif (F0[i])\n\t NormaliseFrequencies0(F[i])\n}\n\nfunction WriteFrequencies1(out, F, F0) {\n var rle = 0;\n var last_sym = 0;\n\n for (var i = 0; i < 256; i++) {\n\tif (!F0[i])\n\t continue\n\n\t// Output Symbol if needed and Frequency\n\tif (rle > 0)\n\t rle--\n\telse {\n\t out.WriteByte(i)\n\n\t if (i > 0 && F0[i-1] > 0) {\n\t\tfor (rle = i+1; rle<256 && F0[rle]; rle++)\n\t\t ;\n\t\trle -= i+1;\n\t\tout.WriteByte(rle);\n\t }\n\t}\n\n\tWriteFrequencies0(out, F[i]);\n }\n out.WriteByte(0);\n}\n\nfunction RansEncode1(src) {\n const nbytes = src.length;\n var output = new IOStream(\"\", 0, 257*257*3+9);\n\n output.WriteByte(1); // Order 0\n output.WriteUint32(0); // compressed size: correct later\n output.WriteUint32(0); // uncompressed size: correct later\n\n // Compute frequencies\n var F0 = new Array(256)\n var F = new Array(256)\n var C = new Array(256)\n for (var i = 0; i < 256; i++) {\n\tF[i] = new Array(256);\n\tC[i] = new Array(256);\n }\n\n BuildFrequencies1(src, F, F0)\n NormaliseFrequencies1(F, F0);\n WriteFrequencies1(output, F, F0);\n\n // Compute cumulative frequencies\n for (var i = 0; i < 256; i++) {\n\tif (!F0[i])\n\t continue;\n\n\tC[i][0] = 0;\n\tfor (var j = 1; j < 256; j++)\n\t C[i][j] = C[i][j-1] + F[i][j-1];\n }\n\n // Initialise rANS state\n var R = new Array(4);\n var L = new Array(4);\n for (var j = 0; j < 4; j++) {\n\tR[j] = RansEncInit();\n\tL[j] = 0;\n }\n var rans_out = new IOStream(\"\", nbytes, nbytes);\n\n // We have 4 rans codecs running in parallel on its own 1/4tr of buffer\n var nbytes4 = Math.floor(nbytes/4);\n var idx = new Array(4);\n var last = new Array(4)\n for (var j = 0; j < 4; j++) {\n\tidx[j] = (j+1)*nbytes4 - 2;\n\tlast[j] = src[idx[j]+1]\n }\n\n // Deal with the remainder if not a multiple of 4\n last[3] = src[nbytes-1];\n for (var i = nbytes-2; i > 4*nbytes4-2; i--) {\n\tR[3] = RansEncPut(R[3], rans_out, C[src[i]][last[3]], F[src[i]][last[3]], 12);\n\tlast[3] = src[i];\n }\n\n // Main encode loop\n while (idx[0] >= 0) {\n\tfor (var j = 3; j >= 0; j--) {\n\t var s = src[idx[j]]\n\t R[j] = RansEncPut(R[j], rans_out, C[s][last[j]], F[s][last[j]], 12);\n\t last[j] = s;\n\t idx[j]--;\n\t}\n }\n\n for (var j = 3; j >= 0; j--) {\n R[j] = RansEncPut(R[j], rans_out, C[0][last[j]], F[0][last[j]], 12)\n }\n\n for (var i = 3; i >= 0; i--)\n\tRansEncFlush(R[i], rans_out);\n\n // Stitch blocks together into final output buffer\n var freq_tab = output.pos;\n output.buf.writeInt32LE(freq_tab-9 + (rans_out.length - rans_out.pos), 1);\n output.buf.writeInt32LE(nbytes, 5);\n\n return Buffer.concat([output.buf.slice(0, output.pos),\n\t\t\t rans_out.buf.slice(rans_out.pos, rans_out.length)],\n\t\t\t output.pos + rans_out.length - rans_out.pos);\n}\n\nmodule.exports = { decode, encode }\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nconst IOStream = require(\"./iostream\");\n\n//----------------------------------------------------------------------\n// rANS primitives itself\n//\n// RansGet* is decoder side\n\nfunction RansGetCumulativeFreq(R, bits) {\n return R & ((1<<bits)-1)\n}\n\nfunction RansGetSymbolFromFreq(C, f) {\n // NOTE: Inefficient.\n // In practice we would implement this via a precomputed\n // lookup table C2S[f]; see RansBuildC2S below.\n var s = 0;\n while (f >= C[s+1])\n\ts++;\n\n //console.error(f, C, s)\n\n return s;\n}\n\nfunction RansBuildC2S(C, bits) {\n var max = 1<<bits\n var C2S = new Array(max);\n var s = 0;\n for (var f = 0; f < max; f++) {\n\twhile (f >= C[s+1])\n\t s++;\n\tC2S[f] = s;\n }\n return C2S;\n}\n\nfunction RansAdvanceStep(R, c, f, bits) {\n return f * (R >> bits) + (R & ((1<<bits)-1)) - c;\n}\n\nfunction RansRenorm(src, R) {\n if (R < (1<<15))\n\tR = (R << 16) + src.ReadUint16();\n\n return R;\n}\n\n\n// RanEnc* is for encoder\nfunction RansEncInit() {\n return 1<<15;\n}\n\nfunction RansEncFlush(R, dst) {\n dst.WriteByteNeg((R >> 24) & 0xff);\n dst.WriteByteNeg((R >> 16) & 0xff);\n dst.WriteByteNeg((R >> 8) & 0xff);\n dst.WriteByteNeg((R >> 0) & 0xff);\n}\n\nfunction RansEncRenorm(R, dst, freq, scale_bits) {\n //var R_max = (((1 << 15) >> scale_bits) << 16) * freq;\n var R_max = (1 << (31-scale_bits)) * freq\n\n while (R >= R_max) {\n\tdst.WriteByteNeg((R>>8) & 0xff);\n\tdst.WriteByteNeg(R & 0xff);\n\tR >>= 16;\n }\n return R;\n}\n\n// Puts a symbol with frequency freq, cumulative freq start\n// and total freq 1<<scale_bits.\n//\n// Note with static probabilities, /freq and %freq could be\n// precomputed via multiplies and shifts.\nfunction RansEncPut(R, dst, start, freq, scale_bits) {\n var scale = 1<<scale_bits;\n R = RansEncRenorm(R, dst, freq, scale_bits);\n R = (Math.floor(R / freq) << scale_bits) + (R % freq) + start;\n return R;\n}\n\n\n//----------------------------------------------------------------------\n// Run length encoding\nfunction EncodeRLE(src) {\n // Step 1: find which symbols benefit from RLE\n var L = new Array(256)\n for (var i = 0; i < 256; i++)\n\tL[i] = 0\n\n var last = -1\n for (var i = 0; i < src.length; i++) {\n\tL[src[i]] += src[i] == last ? 1 : -1\n\tlast = src[i]\n }\n\n var nrle = 0;\n for (var i = 0; i < 256; i++)\n\tif (L[i] > 0)\n\t nrle++\n\n if (!nrle) {\n\t// Format cannot cope with zero RLE symbols, so pick one!\n\tnrle = 1;\n\tL[0] = 1;\n }\n\n // Start meta-data as list of symbols to RLE\n var meta = new IOStream(\"\", 0, nrle+1 + src.length)\n meta.WriteByte(nrle)\n for (var i = 0; i < 256; i++)\n\tif (L[i] > 0)\n\t meta.WriteByte(i)\n\n // Step 2: Now apply RLE itself\n var data = new Buffer.allocUnsafe(src.length)\n var dpos = 0\n for (var i = 0; i < src.length; i++) {\n\tdata[dpos++] = src[i]\n\tif (L[src[i]] > 0) {\n\t last = src[i];\n\t var run = 0;\n\t while (i+run+1 < src.length && src[i+run+1] == last)\n\t\trun++;\n\t meta.WriteUint7(run)\n\t i += run\n\t}\n }\n\n // Compress the meta-data\n var cmeta = RansEncode0(meta.buf.slice(0, meta.pos))\n var hdr = new IOStream(\"\", 0, 16)\n hdr.WriteUint7(meta.pos*2) // Uncompressed meta-data length + compressed-bit-flag(0)\n hdr.WriteUint7(dpos) // Length of RLE encoded data\n hdr.WriteUint7(cmeta.length) // Compressed meta-data length\n var meta = Buffer.concat([hdr.buf.slice(0,hdr.pos), cmeta])\n\n return [meta, data.slice(0, dpos)]\n}\n\nfunction DecodeRLEMeta(src) {\n var u_meta_len = src.ReadUint7()\n var rle_len = src.ReadUint7()\n\n // Decode RLE lengths\n if (u_meta_len & 1) {\n\tvar rle_meta = src.ReadData((u_meta_len-1)/2)\n } else {\n\tvar comp_meta_len = src.ReadUint7()\n\tvar rle_meta = src.ReadData(comp_meta_len)\n\trle_meta = RansDecode0(new IOStream(rle_meta), u_meta_len/2)\n }\n\n // Decode list of symbols for which RLE lengths are applied\n var rle_meta = new IOStream(rle_meta)\n var L = new Array(256)\n var n = rle_meta.ReadByte()\n if (n == 0)\n\tn = 256;\n for (var i = 0; i < n; i++)\n\tL[rle_meta.ReadByte()] = 1\n\n return [L, rle_meta, rle_len]\n}\n\nfunction DecodeRLE(buf, L, rle_meta, len) {\n var src = new IOStream(buf);\n\n var out = new Buffer.allocUnsafe(len)\n\n // Expand up buf+meta to out; i = buf index, j = out index\n var j = 0;\n for (var i = 0; j < len; i++) {\n\tvar sym = buf[i];\n\tif (L[sym]) {\n\t var run = rle_meta.ReadUint7()\n\t for (var r = 0; r <= run; r++)\n\t\tout[j++] = sym\n\t} else {\n\t out[j++] = sym\n\t}\n }\n\n return out\n}\n\n//----------------------------------------------------------------------\n// Bit packing\n\nfunction EncodePack(src) {\n // Step 1: identify number of distinct symbols\n var F = new Array(256)\n for (var i = 0; i < 256; i++)\n\tF[i] = 0\n\n for (var i = 0; i < src.length; i++)\n\tF[src[i]]++\n\n var P = new Array(256)\n var nsym = 0;\n for (var i = 0; i < 256; i++)\n\tif (F[i] > 0)\n\t P[i] = nsym++\n\n if (nsym > 16) {\n\t//console.error(\"Too many symbols to pack:\",nsym)\n\treturn\n }\n\n\n // Pack data\n if (nsym <= 1) {\n\t// Constant\n\tvar data = new Buffer.allocUnsafe(0)\n }\n\n else if (nsym <= 2) {\n\t// 1 bit per value\n\tvar data = new Buffer.allocUnsafe(Math.ceil(src.length/8))\n\tvar j = -1\n\tfor (i = 0; i < src.length; i++) {\n\t if (i % 8 == 0)\n\t\tdata[++j] = 0\n\t data[j] += P[src[i]] << (i % 8)\n\t}\n }\n\n else if (nsym <= 4) {\n\t// 2 bits per value\n\tvar data = new Buffer.allocUnsafe(Math.ceil(src.length/4))\n\tvar j = -1\n\tfor (i = 0; i < src.length; i++) {\n\t if (i % 4 == 0)\n\t\tdata[++j] = 0\n\t data[j] += P[src[i]] << ((i % 4) * 2)\n\t}\n }\n\n else {\n\t// 4 bits per value\n\tvar data = new Buffer.allocUnsafe(Math.ceil(src.length/2))\n\tvar j = -1\n\tfor (i = 0; i < src.length; i++) {\n\t if (i % 2 == 0)\n\t\tdata[++j] = 0\n\t data[j] += P[src[i]] << ((i % 2) * 4)\n\t}\n }\n\n\n // Produce pack meta-data\n var meta = new IOStream(\"\", 0, nsym+5)\n meta.WriteByte(nsym)\n var j = 0\n for (var i = 0; i < 256; i++) {\n\tif (F[i] > 0) {\n\t F[i] = j++;\n\t meta.WriteByte(i)\n\t}\n }\n meta.WriteUint7(data.length)\n\n return [meta.buf.slice(0, meta.pos), data]\n}\n\n\n// Pack meta data is the number and value of distinct symbols plus\n// the length of the packed byte stream.\nfunction DecodePackMeta(src) {\n var nsym = src.ReadByte()\n var P = new Array(nsym)\n\n for (var i = 0; i < nsym; i++)\n\tP[i] = src.ReadByte()\n\n var len = src.ReadUint7()\n\n return [P, nsym, len]\n}\n\n// Extract bits from src producing output of length len.\n// Nsym is number of distinct symbols used.\nfunction DecodePack(data, P, nsym, len) {\n var out = new Buffer.allocUnsafe(len)\n var j = 0;\n\n // Constant value\n if (nsym <= 1) {\n\tfor (var i = 0; i < len; i++)\n\t out[i] = P[0]\n }\n\n // 1 bit per value\n else if (nsym <= 2) {\n\tfor (i = 0; i < len; i++) {\n\t if (i % 8 == 0)\n\t\tvar v = data[j++];\n\n\t out[i] = P[v & 1]\n\t v >>= 1\n\t}\n }\n\n // 2 bits per value\n else if (nsym <= 4) {\n\tfor (i = 0; i < len; i++) {\n\t if (i % 4 == 0)\n\t\tvar v = data[j++];\n\n\t out[i] = P[v & 3]\n\t v >>= 2\n\t}\n }\n\n // 4 bits per value\n else if (nsym <= 16) {\n\tfor (i = 0; i < len; i++) {\n\t if (i % 2 == 0)\n\t\tvar v = data[j++];\n\n\t out[i] = P[v & 15]\n\t v >>= 4\n\t}\n }\n\n return out\n}\n\n\n//----------------------------------------------------------------------\n// 4 way interleaving.\n// This is simply 4 rANS streams interleaved to form bytes 0,4,8...,\n// 1,5,9..., 2,6,10... and 3,7,11...\n//\n// It works well when the distributions differ for each of the 4 bytes,\n// for example when compressing a series of 32-bit integers.\n//\n// Maybe make this more general purpose of X* where we specify the stripe\n// size instead of fixing it at 4?\nfunction RansEncodeStripe(hdr, src, N) {\n if (N == 0)\n\tN = 4; // old default\n\n // Split into multiple streams\n var part = new Array(N)\n var ulen = new Array(N)\n for (var s = 0; s < N; s++) {\n\tulen[s] = Math.floor(src.length / N) + ((src.length % N) > s);\n\tpart[s] = new Array(ulen[s])\n }\n\n for (var x = 0, i = 0; i < src.length; i+=N, x++) {\n\tfor (var j = 0; j < N; j++)\n\t if (x < part[j].length)\n\t\tpart[j][x] = src[i+j]\n }\n\n // Compress each part\n var comp = new Array(N)\n var total = 0\n for (var s = 0; s < N; s++) {\n\t// Example: try O0 and O1 and choose best\n\tvar comp0 = encode(part[s], 0)\n\tvar comp1 = encode(part[s], 1)\n\tcomp[s] = (comp1.length < comp0.length) ? comp1 : comp0\n\ttotal += comp[s].length\n }\n\n // Serialise\n var out = new IOStream(\"\", 0, total+5*N+1)\n out.WriteByte(N)\n for (var s = 0; s < N; s++)\n\tout.WriteUint7(comp[s].length)\n\n for (var s = 0; s < N; s++)\n\tout.WriteData(comp[s], comp[s].length)\n\n return out.buf.slice(0, out.buf.pos)\n}\n\nfunction RansDecodeStripe(src, len) {\n var N = src.ReadByte()\n\n // Retrieve lengths\n var clen = new Array(N)\n var ulen = new Array(N)\n for (var j = 0; j < N; j++)\n\tclen[j] = src.ReadUint7()\n\n // Decode streams\n var T = new Array(N);\n for (var j = 0; j < N; j++) {\n\tulen[j] = Math.floor(len / N) + ((len % N) > j)\n\tT[j] = RansDecodeStream(src, ulen[j])\n }\n\n // Transpose\n var out = new Buffer.allocUnsafe(len)\n for (var j = 0; j < N; j++) {\n\tfor (var i = 0; i < ulen[j]; i++) {\n\t out[i*N + j] = T[j][i];\n\t}\n }\n\n return out;\n}\n\n\n//----------------------------------------------------------------------\n// Main rANS entry function: decodes a compressed src and\n// returns the uncompressed buffer.\nfunction decode(src) {\n var stream = new IOStream(src)\n return RansDecodeStream(stream, 0)\n}\n\nfunction RansDecodeStream(stream, n_out) {\n var format = stream.ReadByte();\n var order = format & 1\n var stripe = format & 8\n var nosz = format & 16\n var cat = format & 32\n var rle = format & 64\n var pack = format & 128\n\n if (!nosz)\n\tn_out = stream.ReadUint7();\n\n // N-way interleaving\n if (stripe)\n\treturn RansDecodeStripe(stream, n_out)\n\n // Bit packing\n if (pack) {\n\tvar pack_len = n_out\n\tvar [P, nsym, n_out] = DecodePackMeta(stream)\n }\n\n // Run length encoding\n if (rle) {\n\tvar rle_len = n_out\n\tvar [L, rle_meta, n_out] = DecodeRLEMeta(stream)\n }\n\n // Uncompress data (all, packed or run literals)\n if (cat)\n\tvar buf = stream.ReadData(n_out)\n else if (order == 0)\n\tvar buf = RansDecode0(stream, n_out)\n else\n\tvar buf = RansDecode1(stream, n_out)\n\n // Apply expansion transforms\n if (rle)\n\tbuf = DecodeRLE(buf, L, rle_meta, rle_len)\n\n if (pack)\n\tbuf = DecodePack(buf, P, nsym, pack_len)\n\n return buf\n}\n\nfunction encode(src, format) {\n var hdr = new IOStream(\"\", 0, 10);\n hdr.WriteByte(format);\n\n var order = format & 1\n var stripe= format & 8\n var nosz = format & 16\n var cat = format & 32\n var rle = format & 64\n var pack = format & 128\n\n var N = format>>8\n\n if (!nosz)\n\thdr.WriteUint7(src.length);\n\n if (stripe)\n\treturn Buffer.concat([hdr.buf.slice(0, hdr.pos), RansEncodeStripe(hdr, src, N)])\n\n var pack_meta = new Buffer.alloc(0)\n if (pack)\n\t[pack_meta, src] = EncodePack(src)\n\n var rle_meta = new Buffer.alloc(0)\n if (rle)\n\t[rle_meta, src] = EncodeRLE(src)\n\n if (src.length < 4 && order == 1) {\n\t// Protect against short order-1 data due to RLE/Pack\n\torder = 0\n\thdr.buf[0] &= ~1\n }\n\n if (cat)\n\tvar comp = src\n else if (order == 0)\n\tvar comp = RansEncode0(src)\n else\n\tvar comp = RansEncode1(src)\n\n return Buffer.concat([hdr.buf.slice(0,hdr.pos), pack_meta, rle_meta, comp])\n}\n\n//----------------------------------------------------------------------\n// Order-0 decoder\n\nfunction ReadAlphabet(src) {\n var A = new Array(256)\n for (var i = 0; i < 256; i++)\n\tA[i] = 0;\n\n var rle = 0\n var sym = src.ReadByte()\n var last_sym = sym\n\n do {\n\tA[sym] = 1;\n\tif (rle > 0) {\n\t rle--\n\t sym++\n\t} else {\n\t sym = src.ReadByte()\n\t if (sym == last_sym+1)\n\t\trle = src.ReadByte()\n\t}\n\tlast_sym = sym\n } while (sym != 0)\n\n return A\n}\n\n// Decode a single table of order-0 frequences,\n// filling out the F and C arrays.\nfunction ReadFrequencies0(src, F, C) {\n // Initialise; not in the specification - implicit?\n for (var i = 0; i < 256; i++)\n\tF[i] = 0;\n\n // Fetch alphabet\n var A = ReadAlphabet(src);\n\n // Fetch frequencies for the symbols listed in our alphabet\n for (var i = 0; i < 256; i++) {\n\tif (A[i] > 0)\n\t F[i] = src.ReadUint7()\n }\n\n NormaliseFrequencies0_Shift(F, 12)\n\n // Compute C[] from F[]\n C[0] = 0;\n for (var i = 0; i <= 255; i++)\n\tC[i+1] = C[i] + F[i];\n}\n\nfunction RansDecode0(src, nbytes) {\n // Decode frequencies\n var F = new Array(256);\n var C = new Array(256);\n ReadFrequencies0(src, F, C);\n\n // Fast lookup to avoid slow RansGetSymbolFromFreq\n var C2S = RansBuildC2S(C, 12);\n\n // Initialise rANS state\n var R = new Array(4);\n for (var i = 0; i < 4; i++)\n\tR[i] = src.ReadUint32();\n\n // Main decode loop\n var output = new Buffer.allocUnsafe(nbytes);\n for (var i = 0; i < nbytes; i++) {\n\tvar i4 = i%4;\n\tvar f = RansGetCumulativeFreq(R[i4], 12);\n\tvar s = C2S[f]; // Equiv to RansGetSymbolFromFreq(C, f);\n\n\toutput[i] = s;\n\tR[i4] = RansAdvanceStep(R[i4], C[s], F[s], 12);\n\tR[i4] = RansRenorm(src, R[i4]);\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------\n// Order-0 encoder\n\nfunction BuildFrequencies0(src, F) {\n for (var i = 0; i < 256; i++)\n\tF[i] = 0;\n\n for (var i = 0; i < src.length; i++)\n\tF[src[i]]++;\n}\n\nfunction NormaliseFrequencies0(F, bits) {\n // Compute total\n var tot = 0;\n for (var i = 0; i < 256; i++)\n\ttot += F[i];\n\n // Scale total of frequencies to max\n const max = (1<<bits);\n var scale = max / tot;\n do {\n\tvar max_val = 0;\n\tvar max_idx = 0;\n\tvar renorm = 0;\n\ttot = 0;\n\tfor (var i = 0; i < 256; i++) {\n\t if (F[i] == 0)\n\t\tcontinue\n\n\t if (max_val < F[i]) {\n\t\tmax_val = F[i]\n\t\tmax_idx = i\n\t }\n\n\t F[i] = Math.floor(F[i] * scale);\n\t if (F[i] == 0)\n\t\tF[i] = 1;\n\n\t tot += F[i];\n\t}\n\n\t// Adjust new tot to ensure it matches.\n\tif (tot < max) {\n\t // Too low, boost the most common symbol\n\t F[max_idx] += max-tot;\n\t} else if (tot-max < F[max_idx]/2 && F[max_idx] > 2) {\n\t // Too high, reduce the common symbol\n\t F[max_idx] -= tot-max;\n\t} else if (tot != max) {\n\t // Much too high, fudge scale and try again.\n\t scale = max / tot;\n\t renorm = 1;\n\t}\n } while (renorm)\n}\n\nfunction NormaliseFrequencies0_Shift(F, bits) {\n // Compute total and number of bits to shift by\n var tot = 0;\n for (var i = 0; i < 256; i++)\n\ttot += F[i];\n\n if (tot == 0 || tot == (1<<bits))\n\treturn\n\n var shift = 0;\n while (tot < (1<<bits)) {\n\ttot *= 2;\n\tshift++;\n }\n\n // Scale total of frequencies to (1<<bits)\n for (var i = 0; i < 256; i++)\n\tF[i] <<= shift;\n}\n\nfunction WriteAlphabet(out, F) {\n var rle = 0;\n for (var i = 0; i < 256; i++) {\n\tif (!F[i])\n\t continue\n\n\tif (rle > 0)\n\t rle--\n\telse {\n\t out.WriteByte(i)\n\n\t if (i > 0 && F[i-1] > 0) {\n\t\t// We've encoded two symbol frequencies in a row.\n\t\t// How many more are there? Store that count so\n\t\t// we can avoid writing consecutive symbols.\n\t\tfor (rle = i+1; rle<256 && F[rle]; rle++)\n\t\t ;\n\t\trle -= i+1;\n\n\t\tout.WriteByte(rle);\n\t }\n\t}\n }\n out.WriteByte(0)\n}\n\nfunction WriteFrequencies0(out, F) {\n WriteAlphabet(out, F)\n\n for (var i = 0; i < 256; i++) {\n\tif (F[i])\n\t out.WriteUint7(F[i])\n }\n}\n\nfunction RansEncode0(src) {\n const nbytes = src.length;\n var output = new IOStream(\"\", 0, 257*3+9);\n\n // Compute frequencies\n var F = new Array(256)\n BuildFrequencies0(src, F)\n var bit_size = Math.ceil(Math.log2(nbytes));\n if (bit_size > 12)\n\tbit_size = 12;\n NormaliseFrequencies0(F, bit_size);\n WriteFrequencies0(output, F);\n NormaliseFrequencies0(F, 12);\n\n // Compute cumulative frequencies\n var C = new Array(256)\n C[0] = 0;\n for (var i = 1; i < 256; i++)\n\tC[i] = C[i-1] + F[i-1];\n\n // Initialise rANS state\n var R = new Array(4);\n for (var i = 0; i < 4; i++)\n\tR[i] = RansEncInit();\n\n // Allow expansion room if trying to compress random data.\n var rans_out = new IOStream(\"\", (nbytes*1.05+100)>>0, (nbytes*1.05+100)>>0);\n\n // Main encode loop\n for (var i = nbytes-1; i >= 0; i--)\n\tR[i%4] = RansEncPut(R[i%4], rans_out, C[src[i]], F[src[i]], 12);\n\n for (var i = 3; i >= 0; i--)\n\tRansEncFlush(R[i], rans_out);\n\n // Stitch blocks together into final output buffer\n //console.error(\"pos=\",rans_out.pos, \" len=\",rans_out.length)\n //console.error(rans_out.buf.slice(rans_out.pos, rans_out.length))\n return Buffer.concat([output.buf.slice(0, output.pos),\n\t\t\t rans_out.buf.slice(rans_out.pos, rans_out.length)],\n\t\t\t output.pos + rans_out.length - rans_out.pos);\n}\n\n//----------------------------------------------------------------------\n// Order-1 decoder\n\n// Decode a table of order-1 frequences,\n// filling out the F and C arrays.\nfunction ReadFrequencies1(src, F, C, shift) {\n // Initialise; not in the specification - implicit?\n for (var i = 0; i < 256; i++) {\n\tF[i] = new Array(256);\n\tC[i] = new Array(256);\n\tfor (var j = 0; j < 256; j++)\n\t F[i][j] = 0;\n }\n\n // Fetch alphabet\n var A = ReadAlphabet(src);\n\n // Read F[]\n for (var i = 0; i < 256; i++) {\n\tif (!A[i])\n\t continue\n\n\tvar run = 0;\n\tfor (var j = 0; j < 256; j++) {\n\t if (!A[j])\n\t\tcontinue\n\n\t if (run > 0) {\n\t\trun--\n\t } else {\n\t\tF[i][j] = src.ReadUint7();\n\t\tif (F[i][j] == 0)\n\t\t run = src.ReadByte();\n\t }\n\t}\n\n\tNormaliseFrequencies0_Shift(F[i], shift)\n\n\t// Compute C[] from F[]\n\tC[i][0] = 0;\n\tfor (var j = 0; j < 256; j++)\n\t C[i][j+1] = C[i][j] + F[i][j];\n }\n}\n\nfunction RansDecode1(src, nbytes) {\n // FIXME: this bit is missing from the RansDecode0 pseudocode.\n\n var comp = src.ReadByte();\n var shift = comp >> 4;\n\n var freq_src = src\n if (comp & 1) {\n\tvar ulen = src.ReadUint7()\n\tvar clen = src.ReadUint7()\n\tvar comp = new IOStream(src.ReadData(clen))\n\tvar freq_src = new IOStream(RansDecode0(comp, ulen));\n }\n\n // Decode frequencies\n var F = new Array(256);\n var C = new Array(256);\n ReadFrequencies1(freq_src, F, C, shift);\n\n // Fast lookup to avoid slow RansGetSymbolFromFreq\n var C2S = new Array(256);\n for (var i = 0; i < 256; i++)\n\t// Could do only for symbols in alphabet?\n\tC2S[i] = RansBuildC2S(C[i], shift);\n\n // Initialise rANS state\n var R = new Array(4);\n var L = new Array(4);\n for (var j = 0; j < 4; j++) {\n\tR[j] = src.ReadUint32();\n\tL[j] = 0;\n }\n\n // Main decode loop\n var output = new Buffer.allocUnsafe(nbytes);\n var nbytes4 = Math.floor(nbytes/4);\n for (var i = 0; i < nbytes4; i++) {\n\tfor (var j = 0; j < 4; j++) {\n\t var f = RansGetCumulativeFreq(R[j], shift);\n\n\t //var s = RansGetSymbolFromFreq(C[L[j]], f);\n\t var s = C2S[L[j]][f]; // Precomputed version of above\n\n\t output[i+j*nbytes4] = s;\n\t R[j] = RansAdvanceStep(R[j], C[L[j]][s], F[L[j]][s], shift);\n\t R[j] = RansRenorm(src, R[j]);\n\t L[j] = s;\n\t}\n }\n\n // Now deal with the remainder if buffer size is not a multiple of 4,\n // using rANS state 3 exclusively. (It'd have been nice to have\n // designed this to just act as if we kept going with a bail out.)\n i = 4*i;\n while (i < nbytes) {\n\tvar f = RansGetCumulativeFreq(R[3], shift);\n\tvar s = RansGetSymbolFromFreq(C[L[3]], f);\n\toutput[i++] = s;\n\tR[3] = RansAdvanceStep(R[3], C[L[3]][s], F[L[3]][s], shift);\n\tR[3] = RansRenorm(src, R[3]);\n\tL[3] = s;\n }\n\n return output;\n}\n\n//----------------------------------------------------------------------\n// Order-1 encoder\n\nfunction BuildFrequencies1(src, F, F0) {\n for (var i = 0; i < 256; i++) {\n\tF0[i] = 0;\n\tfor (var j = 0; j < 256; j++)\n\t F[i][j] = 0;\n }\n\n var last = 0;\n for (var i = 0; i < src.length; i++) {\n\tF0[last]++;\n\tF[last][src[i]]++;\n\tlast = src[i];\n }\n F0[last]++;\n\n // Also accept we'll be starting at 4 points, not just byte 0\n F[0][src[1*(src.length >> 2)]]++;\n F[0][src[2*(src.length >> 2)]]++;\n F[0][src[3*(src.length >> 2)]]++;\n F0[0] += 3;\n}\n\nfunction NormaliseFrequencies1(F, F0, shift) {\n\n for (var i = 0; i < 256; i++) {\n\tif (!F0[i])\n\t continue;\n\n\tvar bit_size = Math.ceil(Math.log2(F0[i]));\n\tif (bit_size > shift)\n\t bit_size = shift;\n\n\tNormaliseFrequencies0(F[i], bit_size)\n }\n}\n\nfunction NormaliseFrequencies1_Shift(F, F0, shift) {\n for (var i = 0; i < 256; i++)\n\tif (F0[i])\n\t NormaliseFrequencies0_Shift(F[i], shift)\n}\n\nfunction WriteFrequencies1(out, F, F0) {\n WriteAlphabet(out, F0)\n\n for (var i = 0; i < 256; i++) {\n\tif (!F0[i])\n\t continue\n\n\tvar run = 0\n\tfor (var j = 0; j < 256; j++) {\n\t if (!F0[j])\n\t\tcontinue\n\n\t if (run) {\n\t\trun--\n\t } else {\n\t\tout.WriteUint7(F[i][j])\n\n\t\tif (!F[i][j]) {\n\t\t // Count how many more zero-freqs we have\n\t\t for (var k = j+1; k < 256; k++) {\n\t\t\tif (!F0[k])\n\t\t\t continue\n\n\t\t\tif (F[i][k] == 0)\n\t\t\t run++\n\t\t\telse\n\t\t\t break\n\t\t }\n\t\t out.WriteByte(run)\n\t\t}\n\t }\n\t}\n }\n}\n\nfunction RansEncode1(src) {\n const nbytes = src.length;\n var output = new IOStream(\"\", 0, 257*257*3+9);\n\n // Compute frequencies\n var F0 = new Array(256)\n var F = new Array(256)\n var C = new Array(256)\n for (var i = 0; i < 256; i++) {\n\tF[i] = new Array(256);\n\tC[i] = new Array(256);\n }\n\n // Frequency precision\n var shift = 12;\n\n BuildFrequencies1(src, F, F0)\n NormaliseFrequencies1(F, F0, shift);\n\n // Store frequencies, possibly compressed\n var freq = new IOStream(\"\", 0, 257*257*3+9);\n\n WriteFrequencies1(freq, F, F0);\n\n var cfreq = RansEncode0(freq.buf.slice(0, freq.pos))\n if (cfreq.length < freq.pos) {\n\toutput.WriteByte(1 | (shift<<4));\n\toutput.WriteUint7(freq.pos)\n\toutput.WriteUint7(cfreq.length)\n\toutput.WriteData(cfreq, cfreq.length);\n } else {\n\toutput.WriteByte(0 | (shift<<4));\n\toutput.WriteData(freq.buf, freq.pos);\n }\n\n // Normalise and compute cumulative frequencies\n NormaliseFrequencies1_Shift(F, F0, shift);\n for (var i = 0; i < 256; i++) {\n\tif (!F0[i])\n\t continue;\n\n\tC[i][0] = 0;\n\tfor (var j = 1; j < 256; j++)\n\t C[i][j] = C[i][j-1] + F[i][j-1];\n }\n\n // Initialise rANS state\n var R = new Array(4);\n var L = new Array(4);\n for (var j = 0; j < 4; j++) {\n\tR[j] = RansEncInit();\n\tL[j] = 0;\n }\n var rans_out = new IOStream(\"\", (nbytes*1.05+100)>>0, (nbytes*1.05+100)>>0);\n\n // We have 4 rans codecs running in parallel on its own 1/4tr of buffer\n var nbytes4 = Math.floor(nbytes/4);\n var idx = new Array(4);\n var last = new Array(4)\n for (var j = 0; j < 4; j++) {\n\tidx[j] = (j+1)*nbytes4 - 2;\n\tlast[j] = src[idx[j]+1]\n }\n\n // Deal with the remainder if not a multiple of 4\n last[3] = src[nbytes-1];\n for (var i = nbytes-2; i > 4*nbytes4-2; i--) {\n\tR[3] = RansEncPut(R[3], rans_out, C[src[i]][last[3]], F[src[i]][last[3]], shift);\n\tlast[3] = src[i];\n }\n\n // Main encode loop\n while (idx[0] >= 0) {\n\tfor (var j = 3; j >= 0; j--) {\n\t var s = src[idx[j]]\n\t R[j] = RansEncPut(R[j], rans_out, C[s][last[j]], F[s][last[j]], shift);\n\t last[j] = s;\n\t idx[j]--;\n\t}\n }\n\n for (var j = 3; j >= 0; j--) {\n R[j] = RansEncPut(R[j], rans_out, C[0][last[j]], F[0][last[j]], shift)\n }\n\n for (var i = 3; i >= 0; i--)\n\tRansEncFlush(R[i], rans_out);\n\n // Stitch blocks together into final output buffer\n return Buffer.concat([output.buf.slice(0, output.pos),\n\t\t\t rans_out.buf.slice(rans_out.pos, rans_out.length)],\n\t\t\t output.pos + rans_out.length - rans_out.pos);\n}\n\nmodule.exports = { decode, encode }\n","/*\n * Copyright (c) 2019 Genome Research Ltd.\n * Author(s): James Bonfield\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger\n * Institute nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH\n * LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// Name tokeniser\n//\n// This is a reference implementation designed to match the\n// written specification as closely as possible. It is *NOT*\n// an efficient implementation, but see comments below.\n\nconst IOStream = require(\"./iostream\");\nconst rans = require(\"./rans4x16\");\nconst arith_gen = require(\"./arith_gen\");\n\nvar arith = new arith_gen()\n\nconst TOK_TYPE = 0\nconst TOK_STRING = 1\nconst TOK_CHAR = 2\nconst TOK_DIGITS0 = 3\nconst TOK_DZLEN = 4\nconst TOK_DUP = 5\nconst TOK_DIFF = 6\nconst TOK_DIGITS = 7\nconst TOK_DELTA = 8\nconst TOK_DELTA0 = 9\nconst TOK_MATCH = 10\nconst TOK_NOP = 11\nconst TOK_END = 12\n\n//----------------------------------------------------------------------\n// Token byte streams\nfunction DecodeTokenByteStreams(src, in_size, use_arith, nnames) {\n var t = -1\n\n var B = new Array(256)\n\n while (!src.EOF()) {\n\tvar ttype = src.ReadByte()\n\tvar tok_new = ttype & 128\n\tvar tok_dup = ttype & 64\n\tvar type = ttype & 63\n\n\tif (tok_new) {\n\t t++\n\t B[t] = new Array(13)\n\t}\n\n\tif (type != TOK_TYPE && tok_new) {\n\t var M = new Array(nnames-1).fill(TOK_MATCH)\n\t B[t][TOK_TYPE] = new IOStream(Buffer.from([type].concat(M)))\n }\n\n\tif (tok_dup) {\n\t var dup_pos = src.ReadByte()\n\t var dup_type = src.ReadByte()\n\t B[t][type] = new IOStream(B[dup_pos][dup_type].buf)\n\t} else {\n\t var clen = src.ReadUint7()\n\t var data = src.ReadData(clen)\n\n\t if (use_arith)\n\t\tB[t][type] = arith.decode(data)\n\t else\n\t\tB[t][type] = rans.decode(data)\n\t B[t][type] = new IOStream(B[t][type])\n\t}\n }\n\n return B\n}\n\n//----------------------------------------------------------------------\n// Token decode\nfunction LeftPadNumber(val, len) {\n var str = val+\"\"\n while (str.length < len)\n\tstr = \"0\" + str\n\n return str\n}\n\nfunction DecodeSingleName(B, N, T, n) {\n var type = B[0][TOK_TYPE].ReadByte()\n var dist = B[0][type].ReadUint32()\n var m = n - dist\n\n if (type == TOK_DUP) {\n\tN[n] = N[m]\n\tT[n] = T[m]\n\treturn N[n]\n }\n \n var t = 1\n N[n] = \"\"\n T[n] = new Array(256)\n do {\n\ttype = B[t][TOK_TYPE].ReadByte()\n\n\tswitch(type) {\n\tcase TOK_CHAR:\n\t T[n][t] = B[t][TOK_CHAR].ReadChar()\n\t break\n\n\tcase TOK_STRING:\n\t T[n][t] = B[t][TOK_STRING].ReadString()\n\t break\n\t\n\tcase TOK_DIGITS:\n\t T[n][t] = B[t][TOK_DIGITS].ReadUint32()\n\t break\n\n\tcase TOK_DIGITS0:\n\t var d = B[t][TOK_DIGITS0].ReadUint32()\n\t var l = B[t][TOK_DZLEN].ReadByte()\n\t T[n][t] = LeftPadNumber(d, l)\n\t break\n\n\tcase TOK_DELTA:\n\t T[n][t] = (T[m][t]>>0) + B[t][TOK_DELTA].ReadByte()\n\t break\n\n\tcase TOK_DELTA0:\n\t var d = (T[m][t]>>0) + B[t][TOK_DELTA0].ReadByte()\n\t var l = T[m][t].length\n\t T[n][t] = LeftPadNumber(d, l)\n\t break\n\n\tcase TOK_MATCH:\n\t T[n][t] = T[m][t]\n\t break\n\n\tdefault:\n\t T[n][t] = \"\"\n\t break\n\t}\n\n\tN[n] += T[n][t++]\n } while (type != TOK_END)\n\n return N[n]\n}\n\n//----------------------------------------------------------------------\n// Main tokeniser decode entry function: decodes a compressed src and\n// returns the uncompressed buffer.\nfunction decode(src, len, separator) {\n var src = new IOStream(src)\n var ulen = src.ReadUint32()\n var nnames = src.ReadUint32()\n var use_arith = src.ReadByte()\n\n var B = DecodeTokenByteStreams(src, len, use_arith, nnames)\n var N = new Array(nnames)\n var T = new Array(nnames)\n\n var str = \"\"\n if (typeof separator === 'undefined')\n\tseparator = '\\n'\n for (var i = 0; i < nnames; i++)\n\tstr += DecodeSingleName(B, N, T, i) + separator\n\n return str\n}\n\n//----------------------------------------------------------------------\n// Main tokeniser encode function\n\n// Encoder is trickier than decode as we have a lot of decisions to make.\n// However here we just make a simple guess without anything complex,\n// to demonstrate the basic idea. See the C implementation for further\n// expansion on this.\nfunction encode(src, use_arith) {\n // Convert buffer to array of names\n var str = src.toString()\n if (str[str.length-1] == '\\n')\n\tstr = str.substring(0,str.length-1)\n var names = str.split(\"\\n\")\n\n var out = new IOStream(\"\", 0, str.length*2 + 10000) // guess max size\n out.WriteUint32(str.length)\n out.WriteUint32(names.length)\n out.WriteByte(use_arith)\n\n // Tokenise names\n var T = new Array(names.length)\n var H = {}\n var F = new Array(256).fill(0) // DELTA vs DIGIT frequency\n var max_tok = 0\n var max_len = 0\n for (var i = 0; i < names.length; i++) {\n\tvar [ntok,len] = TokeniseName(T, H, F, names[i], i)\n\tif (max_tok < ntok)\n\t max_tok = ntok\n\tif (max_len < len)\n\t max_len = len\n }\n\n // Convert tokens to byte streams and serialise\n for (var tnum = 0; tnum < max_tok; tnum++) {\n\tvar B = new Array(TOK_END+1)\n\tfor (var type = 0; type <= TOK_END; type++)\n\t B[type] = new IOStream(\"\", 0, names.length * max_len)\n\n\tFillByteStreams(B, T, tnum, names, max_tok, max_len)\n\tSerialiseByteStreams(B, tnum, use_arith, out)\n }\n\n return out.buf.slice(0, out.pos)\n}\n\nfunction FillByteStreams(B, T, tnum, names, max_tok, max_len) {\n // Create byte streams B[]\n for (var n = 0; n < names.length; n++) {\n\tif (tnum > 0 && T[n][0].type == TOK_DUP)\n\t continue\n\n\tif (!T[n][tnum])\n\t continue\n\n\tB[TOK_TYPE].WriteByte(T[n][tnum].type)\n\n\tswitch (T[n][tnum].type) {\n\tcase TOK_DIFF:\n\t B[TOK_DIFF].WriteUint32(T[n][tnum].val)\n\t break\n\n\tcase TOK_DUP:\n\t B[TOK_DUP].WriteUint32(T[n][tnum].val)\n\t break\n\n\tcase TOK_STRING:\n\t B[TOK_STRING].WriteString(T[n][tnum].val)\n\t break\n\n\tcase TOK_CHAR:\n\t B[TOK_CHAR].WriteChar(T[n][tnum].val)\n\t break\n\n\tcase TOK_DIGITS:\n\t B[TOK_DIGITS].WriteUint32(T[n][tnum].val)\n\t break\n\n\tcase TOK_DIGITS0:\n\t B[TOK_DIGITS0].WriteUint32(T[n][tnum].val)\n\t B[TOK_DZLEN].WriteByte(T[n][tnum].val.length)\n\t break\n\n\tcase TOK_DELTA:\n\t B[T[n][tnum].type].WriteByte(T[n][tnum].val)\n\t break\n\n\tcase TOK_DELTA0:\n\t B[T[n][tnum].type].WriteByte(T[n][tnum].val)\n\t break\n\t}\n }\n}\n\nfunction SerialiseByteStreams(B, tnum, use_arith, out) {\n // Compress and serialise byte streams B[]\n for (var type = 0; type <= TOK_END; type++) {\n\tif (B[type].pos <= 0)\n\t continue\n\n\tout.WriteByte(type + ((type == 0) ? 128 : 0))\n\n\t// IOStream to sized buffer\n\tB[type] = B[type].buf.slice(0, B[type].pos)\n\tvar comp = try_compress(B[type], use_arith)\n\n\tout.WriteUint7(comp.length)\n\tout.WriteData(comp, comp.length)\n }\n}\n\nfunction try_compress(src, use_arith) {\n var best = 1<<30\n var comp\n\n var methods = [0, 1, 64, 65, 128, 129, 193+8]\n for (var i in methods) {\n\tvar lvl = methods[i]\n\tif ((lvl & 1) && src.length < 100)\n\t continue\n\n\tif ((lvl & 8) && (src.length % 4) != 0)\n\t continue\n\n\ttry {\n\t var tmp = use_arith\n\t\t? arith.encode(src, lvl)\n\t\t: rans.encode(src, lvl)\n\t} catch (e) {\n\t var tmp = 0\n\t}\n\tif (tmp && best > tmp.length) {\n\t best = tmp.length\n\t comp = tmp\n\t}\n }\n\n return comp\n}\n\nfunction TokeniseName(T, H, F, name, n) {\n var max_len = 0\n\n // Always compare against last name only\n var p = n-1\n T[n] = new Array(256)\n\n if (H[name]) {\n\t//console.error(name,H[name],n)\n\tT[n][0] = {\n\t type: TOK_DUP,\n\t val: n - H[name]\n\t}\n } else {\n\tT[n][0] = {\n\t type: TOK_DIFF,\n\t val: n == 0 ? 0 : 1\n\t}\n }\n\n H[name] = n\n\n // Splits on alphanumerics, punctuation\n var tok = name.match(/([a-zA-Z0-9]{1,9})|([^a-zA-Z0-9]+)/g)\n for (var i = 0; i < tok.length; i++) {\n\tvar t = i+1 // token 0 = DIFF vs DUP\n\tvar type = TOK_STRING\n\tvar val = tok[i]\n\tif (tok[i].match(/^0+[0-9]*$/g))\n\t type = TOK_DIGITS0\n\telse if (tok[i].match(/^[0-9]+$/g))\n\t type = TOK_DIGITS\n\telse if (tok[i].length == 1)\n\t type = TOK_CHAR\n\n\tif (p >= 0 && T[p][t]) {\n\t if (T[p][t].str == tok[i]) {\n\t\ttype = TOK_MATCH\n\t\tval = \"\"\n\t } else if (T[p][t].type == TOK_DIGITS || T[p][t].type == TOK_DELTA) {\n\t\tvar d = val - T[p][t].str;\n\t\tF[t]++\n\t\tif (d >= 0 && d < 256 && F[t] > n/2) {\n\t\t type = TOK_DELTA\n\t\t val = d\n\t\t}\n\t } else if ((T[p][t].type == TOK_DIGITS0 || T[p][t].type == TOK_DELTA0)\n\t\t && T[p][t].str.length == val.length) {\n\t\tvar d = val - T[p][t].str;\n\t\tF[t]++\n\t\tif (d >= 0 && d < 256 && F[t] > n/2) {\n\t\t type = TOK_DELTA0\n\t\t val = d\n\t\t}\n\t }\n\t}\n\n\tT[n][t] = {\n\t str: tok[i],\n\t val: val,\n\t type: type\n\t}\n\n\tif (max_len < T[n][t].val.length+3) // +3 for integers; 5 -> (Uint32)5\n\t max_len = T[n][t].val.length+3\n\n\t//console.error(t,T[n][t])\n }\n T[n][++t] = {\n\ttype: TOK_END\n }\n\n return [t+1, max_len]\n}\n\nmodule.exports = { encode, decode }\n","/*\nbzip2.js - a small bzip2 decompression implementation\n\nCopyright 2011 by antimatter15 (antimatter15@gmail.com)\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n\nI hereby release this code under the GNU Library General Public License\n(LGPL) version 2, available at http://www.gnu.org/copyleft/lgpl.html\n*/\n\nvar bzip2 = {};\n\nbzip2.array = function (bytes) {\n var bit = 0,\n byte = 0;\n var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n return function (n) {\n var result = 0;\n while (n > 0) {\n var left = 8 - bit;\n if (n >= left) {\n result <<= left;\n result |= (BITMASK[left] & bytes[byte++]);\n bit = 0;\n n -= left;\n } else {\n result <<= n;\n result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));\n bit += n;\n n = 0;\n }\n }\n return result\n }\n}\n\nbzip2.simple = function (bits) {\n var size = bzip2.header(bits);\n var all, chunk, chunks = [];\n var index = 0;\n do {\n //all += chunk;\n chunk = bzip2.decompress(bits, size);\n //all.set(chunk, index);\n if (chunk != -1) {\n chunks.push(chunk);\n index += chunk.byteLength;\n }\n } while (chunk != -1);\n all = new Uint8Array(index);\n index = 0;\n for (var i = 0; i < chunks.length; ++i) {\n chunk = chunks[i];\n all.set(chunk, index);\n index += chunk.byteLength;\n }\n return all;\n}\n\nbzip2.header = function (bits) {\n if (bits(8 * 3) != 4348520)\n throw \"No magic number found\";\n var i = bits(8) - 48;\n if (i < 1 || i > 9)\n throw \"Not a BZIP archive\";\n return i;\n};\n\n//takes a function for reading the block data (starting with 0x314159265359)\n//a block size (0-9) (optional, defaults to 9)\n//a length at which to stop decompressing and return the output\nbzip2.decompress = function (bits, size, len) {\n var MAX_HUFCODE_BITS = 20;\n var MAX_SYMBOLS = 258;\n var SYMBOL_RUNA = 0;\n var SYMBOL_RUNB = 1;\n var GROUP_SIZE = 50;\n\n var bufsize = 100000 * 9;\n for (var h = '', i = 0; i < 6; i++)\n h += bits(8).toString(16);\n if (h == \"177245385090\")\n return -1; //last block\n if (h != \"314159265359\")\n throw \"eek not valid bzip data\";\n bits(32); //ignore CRC codes\n if (bits(1))\n throw \"unsupported obsolete version\";\n var origPtr = bits(24);\n if (origPtr > bufsize)\n throw \"Initial position larger than buffer size\";\n var t = bits(16);\n var symToByte = new Uint8Array(256),\n symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (15 - i))) {\n var k = bits(16);\n for (j = 0; j < 16; j++) {\n if (k & (1 << (15 - j))) {\n symToByte[symTotal++] = (16 * i) + j;\n }\n }\n }\n }\n\n var groupCount = bits(3);\n if (groupCount < 2 || groupCount > 6)\n throw \"another error\";\n var nSelectors = bits(15);\n if (nSelectors == 0)\n throw \"meh\";\n var mtfSymbol = []; //TODO: possibly replace JS array with typed arrays\n for (var i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n var selectors = new Uint8Array(32768);\n\n for (var i = 0; i < nSelectors; i++) {\n for (var j = 0; bits(1); j++)\n if (j >= groupCount)\n throw \"whoops another error\";\n var uc = mtfSymbol[j];\n mtfSymbol.splice(j, 1); //this is a probably inefficient MTF transform\n mtfSymbol.splice(0, 0, uc);\n selectors[i] = uc;\n }\n\n var symCount = symTotal + 2;\n var groups = [];\n for (var j = 0; j < groupCount; j++) {\n var length = new Uint8Array(MAX_SYMBOLS),\n temp = new Uint8Array(MAX_HUFCODE_BITS + 1);\n t = bits(5); //lengths\n for (var i = 0; i < symCount; i++) {\n while (true) {\n if (t < 1 || t > MAX_HUFCODE_BITS)\n throw \"I gave up a while ago on writing error messages\";\n if (!bits(1))\n break;\n if (!bits(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (var i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n var hufGroup;\n hufGroup = groups[j] = {};\n hufGroup.permute = new Uint32Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n var base = hufGroup.base.subarray(1);\n var limit = hufGroup.limit.subarray(1);\n var pp = 0;\n for (var i = minLen; i <= maxLen; i++)\n for (var t = 0; t < symCount; t++)\n if (length[t] == i)\n hufGroup.permute[pp++] = t;\n for (i = minLen; i <= maxLen; i++)\n temp[i] = limit[i] = 0;\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n limit[i] = pp - 1;\n pp <<= 1;\n base[i + 1] = pp - (t += temp[i]);\n }\n limit[maxLen] = pp + temp[maxLen] - 1;\n base[minLen] = 0;\n }\n var byteCount = new Uint32Array(256);\n for (var i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n var runPos, count, symCount, selector;\n runPos = count = symCount = selector = 0;\n var buf = new Uint32Array(bufsize);\n while (true) {\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors)\n throw \"meow i'm a kitty, that's an error\";\n hufGroup = groups[selectors[selector++]];\n base = hufGroup.base.subarray(1);\n limit = hufGroup.limit.subarray(1);\n }\n i = hufGroup.minLen;\n j = bits(i);\n while (true) {\n if (i > hufGroup.maxLen)\n throw \"rawr i'm a dinosaur\";\n if (j <= limit[i])\n break;\n i++;\n j = (j << 1) | bits(1);\n }\n j -= base[i];\n if (j < 0 || j >= MAX_SYMBOLS)\n throw \"moo i'm a cow\";\n var nextSym = hufGroup.permute[j];\n if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {\n if (!runPos) {\n runPos = 1;\n t = 0;\n }\n if (nextSym == SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n if (runPos) {\n runPos = 0;\n if (count + t >= bufsize)\n throw \"Boom.\";\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n buf[count++] = uc;\n }\n if (nextSym > symTotal)\n break;\n if (count >= bufsize)\n throw \"I can't think of anything. Error\";\n i = nextSym - 1;\n uc = mtfSymbol[i];\n mtfSymbol.splice(i, 1);\n mtfSymbol.splice(0, 0, uc);\n uc = symToByte[uc];\n byteCount[uc]++;\n buf[count++] = uc;\n }\n if (origPtr < 0 || origPtr >= count)\n throw \"I'm a monkey and I'm throwing something at someone, namely you\";\n var j = 0;\n for (var i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n for (var i = 0; i < count; i++) {\n uc = buf[i] & 0xff;\n buf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n var pos = 0,\n current = 0,\n run = 0;\n if (count) {\n pos = buf[origPtr];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n count = count;\n var output = new Uint8Array(bufsize);\n var copies, previous, outbyte;\n var index = 0;\n if (!len)\n len = Infinity;\n while (count) {\n count--;\n previous = current;\n pos = buf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ == 3) {\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n while (copies--) {\n //output += (String.fromCharCode(outbyte));\n output[index++] = outbyte;\n //index++;\n if (!--len)\n return output;\n }\n if (current != previous)\n run = 0;\n }\n //return output;\n //return output.subarray(0,index-1);\n return output.subarray(0, index);\n}\n\nmodule.exports = bzip2;\n","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message) && message.constructor !== Uint8Array)\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n","/*!\n * Based on xzwasm (c) Steve Sanderson. License: MIT - https://github.com/SteveSanderson/xzwasm\n * Contains xz-embedded by Lasse Collin and Igor Pavlov. License: Public domain - https://tukaani.org/xz/embedded.html\n * and walloc (c) 2020 Igalia, S.L. License: MIT - https://github.com/wingo/walloc\n */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"stream/web\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"stream/web\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"xz-decompress\"] = factory(require(\"stream/web\"));\n\telse\n\t\troot[\"xz-decompress\"] = factory(root[\"stream/web\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__2__) => {\nreturn /******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ \tvar __webpack_modules__ = ([\n/* 0 */,\n/* 1 */\n/***/ ((module) => {\n\nmodule.exports = \"data:application/wasm;base64,AGFzbQEAAAABOApgAX8Bf2ABfwBgAABgA39/fwF/YAABf2ACf38AYAN/f34BfmACf38Bf2AEf39/fwF/YAN/f38AAyEgAAABAgMDAwMEAQUAAgMCBgcIBwUDAAMHAQcABwcBAwkFAwEAAgYIAX8BQfCgBAsHTgUGbWVtb3J5AgAOY3JlYXRlX2NvbnRleHQACA9kZXN0cm95X2NvbnRleHQACQxzdXBwbHlfaW5wdXQACg9nZXRfbmV4dF9vdXRwdXQACwqNYCDfAgEFf0EAIQECQCAAQQdqIgJBEEkNAEEBIQEgAkEDdiIDQQJGDQBBAiEBIAJBIEkNAEEDIQEgA0EERg0AQQQhASACQTBJDQBBBSEBIANBBkYNAEEGIQEgAkHIAEkNAEEHIQEgAkHYAEkNAEEIIQEgAkGIAUkNAEEJIQEgAkGIAkkNACAAEIGAgIAAIgBBCGpBACAAGw8LAkACQCABQQJ0QcCIgIAAaiIEKAIAIgANAEEAIQACQAJAQQAoAuSIgIAAIgJFDQBBACACKAIANgLkiICAAAwBC0EAEIGAgIAAIgJFDQILIAJBgIB8cSIAIAJBCHZB/wFxIgJyIAE6AAAgAkEIdCAAckGAAmohAEEAIQJBACABQQJ0QYCIgIAAaigCACIDayEFIAMhAQNAIAAgBWoiACACNgIAIAAhAiABIANqIgFBgQJJDQALIAQgADYCAAsgBCAAKAIANgIACyAAC+4HAQd/AkACQAJAAkACQEEALQC0iICAAEUNAEEAQQA6ALSIgIAAQQAoArCIgIAAIgFFDQFBsIiAgAAhAgNAAkACQCABQQhqIgMgASgCBCIEaiIFQQh2Qf8BcSIGDQAgASECDAELAkADQCAFQYCAfHEgBmotAABB/gFHDQFBsIiAgAAhBgNAIAYiBygCACIGIAVHDQALIAcgBSgCADYCACABI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UQloCAgAALVAEDf0EAIQADQEEIIQEgACECA0BBACACQQFxa0GghuLtfnEgAkEBdnMhAiABQX9qIgENAAsgAEECdEHwiICAAGogAjYCACAAQQFqIgBBgAJHDQALC0oAIAJBf3MhAgJAIAFFDQADQCACQf8BcSAALQAAc0ECdEHwiICAAGooAgAgAkEIdnMhAiAAQQFqIQAgAUF/aiIBDQALCyACQX9zC10DAX4BfwF+QgAhAANAQQghASAAIQIDQEIAIAJCAYN9QsKenLzd8pW2SYMgAkIBiIUhAiABQX9qIgENAAsgAKdBA3RB8JCAgABqIAI3AwAgAEIBfCIAQoACUg0ACwtLACACQn+FIQICQCABRQ0AA0AgAkL/AYMgADEAAIWnQQN0QfCQgIAAaikDACACQgiIhSECIABBAWohACABQX9qIgENAAsLIAJCf4UL1RACDH8CfgJAAkAgACgCJEUNACAAKAIAIQIMAQtBACECIABBADoAKCAAQgA3AwAgAEIANwMYIABByABqQQBB5AAQhoCAgAAaIABBrAFqQQw2AgALIAAgASgCBCIDNgIQIABBsAFqIQQgAEHgAGohBSAAQcgAaiEGIABBtgFqIQcgAEGoAWohCCABKAIQIQkCQAJAAkACQANAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIOCgECAAQFBgcICQoPCyABKAIAIQogACgCqAEhAiAAKAKsASELIAEoAgQhDCABKAIIIQ0MAgsgCCAAKAKoASIMakEIaiABKAIAIAEoAgQiAmogASgCCCACayICIAAoAqwBIAxrIgwgAiAMSRsiAhCHgICAABogASABKAIEIAJqNgIEQQAhDCAAQQAgACgCqAEgAmoiAiACIAAoAqwBIgtGGzYCqAEgAiALRw0RIABBATYCAAJAIARBqIiAgABBBhCEgICAAEUNAEEFIQwMEgsgB0ECQQAQjYCAgAAgACgAuAFHDRBBBiEMIActAAANESAAIAAtALcBIgI2AiAgAkEESw0RQQEgAnRBE3FFDRELIAEoAgQiDCABKAIIIg1GDQ4CQCABKAIAIgogDGotAAAiCw0AIAAgDDYCECABIAxBAWo2AgRBBiECDA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AAgAzYCACAKQYAQIAprQQV2aiEKDAELIAAgDiADayIONgIEIAAgCyADayIDNgIAIAogCkEFdmshCkEAIQ0LIA8gCjsBACANIBFzIQ0gBEEBdCASciIEQYACSQ0ACwsgACACQQFqNgIgIAAoAhggAmogBDoAAAJAIAAoAiQgACgCICICTw0AIAAgAjYCJAtBACEDAkAgACgCZCIEQQRJDQACQCAEQQlLDQAgBEF9aiEDDAELIARBemohAwsgACADNgJkDAELIAAgDiADayIONgIEIAAgBCADayIDNgIAIA0gDyAPQQV2azsBACAAIApBAXRqIg9B+ANqIQQCQAJAIANB////B00NACAJIQoMAQsgACADQQh0IgM2AgAgACAJQQFqIgo2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQLAkACQCAOIANBC3YgBC8BACINbCIJSQ0AIAAgDiAJayIONgIEIAAgAyAJayIDNgIAIAQgDSANQQV2azsBACAPQZAEaiENAkACQCADQf///wdNDQAgCiEQDAELIAAgA0EIdCIDNgIAIAAgCkEBaiIQNgIQIAAgDkEIdCAAKAIMIApqLQAAciIONgIECwJAAkAgDiADQQt2IA0vAQAiCWwiBE8NACANIAlBgBAgCWtBBXZqOwEAIAxB2ARqIQMCQCAEQf///wdLDQAgACAEQQh0IgQ2AgAgACAQQQFqNgIQIAAgDkEIdCAAKAIMIBBqLQAAciIONgIECwJAIA4gBEELdiADLwEAIg1sIglJDQAgACAOIAlrNgIEIAAgBCAJazYCACADIA0gDUEFdms7AQAMAgsgAyANQYAQIA1rQQV2ajsBACAAIAk2AgAgAEEBNgJoIABBCUELIAAoAmRBB0kbNgJkDAMLIAAgDiAEayIONgIEIA0gCSAJQQV2azsBACAPQagEaiENAkACQCADIARrIgNB////B00NACAQIQoMAQsgACADQQh0IgM2AgAgACAQQQFqIgo2AhAgACAOQQh0IAAoAgwgEGotAAByIg42AgQLAkACQCAOIANBC3YgDS8BACIEbCIJTw0AIAAgCTYCACANIARBgBAgBGtBBXZqOwEAIAAoAlghAwwBCyAAIA4gCWsiDjYCBCAN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AiAFayIFNgIAIAMgBiAGQQV2azsBACABQQFyIQEMAQsgACAFNgIAIAMgBkGAECAGa0EFdmo7AQALIAEgCEkNAAsgAEHoAGogASAIayAJajYCAAsLNQEAQYAICy4IAAAAEAAAABgAAAAgAAAAKAAAADAAAABAAAAAUAAAAIAAAAAAAQAA/Td6WFoA\";\n\n/***/ }),\n/* 2 */\n/***/ ((module) => {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE__2__;\n\n/***/ })\n/******/ \t]);\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/define property getters */\n/******/ \t(() => {\n/******/ \t\t// define getter functions for harmony exports\n/******/ \t\t__webpack_require__.d = (exports, definition) => {\n/******/ \t\t\tfor(var key in definition) {\n/******/ \t\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t\t}\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t})();\n/******/ \t\n/******/ \t/* webpack/runtime/hasOwnProperty shorthand */\n/******/ \t(() => {\n/******/ \t\t__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))\n/******/ \t})();\n/******/ \t\n/******/ \t/* webpack/runtime/make namespace object */\n/******/ \t(() => {\n/******/ \t\t// define __esModule on exports\n/******/ \t\t__webpack_require__.r = (exports) => {\n/******/ \t\t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n/******/ \t\t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n/******/ \t\t\t}\n/******/ \t\t\tObject.defineProperty(exports, '__esModule', { value: true });\n/******/ \t\t};\n/******/ \t})();\n/******/ \t\n/************************************************************************/\nvar __webpack_exports__ = {};\n// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.\n(() => {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ XzReadableStream: () => (/* binding */ XzReadableStream)\n/* harmony export */ });\n/* harmony import */ var _dist_native_xz_decompress_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);\n\n\nconst ReadableStream = globalThis.ReadableStream\n // Node < 18 support web streams, but it's not available as a global, so we need to require it.\n // This won't be reached in modern browsers, and bundlers will ignore due to 'browser' field in package.json:\n || (__webpack_require__(2).ReadableStream);\n\nconst XZ_OK = 0;\nconst XZ_STREAM_END = 1;\n\nclass XzContext {\n constructor(moduleInstance) {\n this.exports = moduleInstance.exports;\n this.memory = this.exports.memory;\n this.ptr = this.exports.create_context();\n this._refresh();\n this.bufSize = this.mem32[0];\n this.inStart = this.mem32[1] - this.ptr;\n this.inEnd = this.inStart + this.bufSize;\n this.outStart = this.mem32[4] - this.ptr;\n }\n\n supplyInput(sourceDataUint8Array) {\n this._refresh();\n const inBuffer = this.mem8.subarray(this.inStart, this.inEnd);\n inBuffer.set(sourceDataUint8Array, 0);\n this.exports.supply_input(this.ptr, sourceDataUint8Array.byteLength);\n this._refresh();\n }\n\n getNextOutput() {\n const result = this.exports.get_next_output(this.ptr);\n this._refresh();\n if (result !== XZ_OK && result !== XZ_STREAM_END) {\n throw new Error(`get_next_output failed with error code ${result}`);\n }\n const outChunk = this.mem8.slice(this.outStart, this.outStart + /* outPos */ this.mem32[5]);\n return { outChunk, finished: result === XZ_STREAM_END };\n }\n\n needsMoreInput() {\n return /* inPos */ this.mem32[2] === /* inSize */ this.mem32[3];\n }\n\n outputBufferIsFull() {\n return /* outPos */ this.mem32[5] === this.bufSize;\n }\n\n resetOutputBuffer() {\n this.outPos = this.mem32[5] = 0;\n }\n\n dispose() {\n this.exports.destroy_context(this.ptr);\n this.exports = null;\n }\n\n _refresh() {\n if (this.memory.buffer !== this.mem8?.buffer) {\n this.mem8 = new Uint8Array(this.memory.buffer, this.ptr);\n this.mem32 = new Uint32Array(this.memory.buffer, this.ptr);\n }\n }\n}\n\nclass XzReadableStream extends ReadableStream {\n static _moduleInstancePromise;\n static _moduleInstance;\n static async _getModuleInstance() {\n const base64Wasm = _dist_native_xz_decompress_wasm__WEBPACK_IMPORTED_MODULE_0__.replace('data:application/wasm;base64,', '');\n const wasmBytes = Uint8Array.from(atob(base64Wasm), c => c.charCodeAt(0)).buffer;\n const wasmOptions = {};\n const module = await WebAssembly.instantiate(wasmBytes, wasmOptions);\n XzReadableStream._moduleInstance = module.instance;\n }\n\n constructor(compressedStream) {\n let xzContext;\n let unconsumedInput = null;\n const compressedReader = compressedStream.getReader();\n\n super({\n async start(controller) {\n if (!XzReadableStream._moduleInstance) {\n await (XzReadableStream._moduleInstancePromise || (XzReadableStream._moduleInstancePromise = XzReadableStream._getModuleInstance()));\n }\n xzContext = new XzContext(XzReadableStream._moduleInstance);\n },\n\n async pull(controller) {\n if (xzContext.needsMoreInput()) {\n if (unconsumedInput === null || unconsumedInput.byteLength === 0) {\n const { done, value } = await compressedReader.read();\n if (!done) {\n unconsumedInput = value;\n }\n }\n const nextInputLength = Math.min(xzContext.bufSize, unconsumedInput.byteLength);\n xzContext.supplyInput(unconsumedInput.subarray(0, nextInputLength));\n unconsumedInput = unconsumedInput.subarray(nextInputLength);\n }\n\n const nextOutputResult = xzContext.getNextOutput();\n controller.enqueue(nextOutputResult.outChunk);\n xzContext.resetOutputBuffer();\n\n if (nextOutputResult.finished) {\n xzContext.dispose(); // Not sure if this always happens\n controller.close();\n }\n },\n cancel() {\n xzContext.dispose(); // Not sure if this always happens\n return compressedReader.cancel();\n }\n });\n }\n}\n\n})();\n\n/******/ \treturn __webpack_exports__;\n/******/ })()\n;\n});","// Generated by `./pycrc.py --algorithm=table-driven --model=crc-32 --generate=c`\nlet TABLE = [\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n];\nif (typeof Int32Array !== 'undefined') {\n TABLE = new Int32Array(TABLE);\n}\nconst crc32 = (current, previous) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n let crc = previous === 0 ? 0 : ~~previous ^ -1;\n for (let index = 0; index < current.length; index++) {\n crc = TABLE[(crc ^ current[index]) & 0xff] ^ (crc >>> 8);\n }\n return crc ^ -1;\n};\nexport default crc32;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-prototype-builtins */\nimport { Buffer } from 'buffer';\nconst createBuffer = (value, encoding) => Buffer.from(value, encoding);\nexport default createBuffer;\n","import crc32 from './calculators/crc32.js';\nimport defineCrc from './define_crc.js';\nexport default defineCrc('crc-32', crc32);\n","import createBuffer from './create_buffer.js';\nexport default function defineCrc(model, calculator) {\n const result = (value, previous) => calculator(createBuffer(value), previous) >>> 0;\n result.signed = (value, previous) => calculator(createBuffer(value), previous);\n result.unsigned = result;\n result.model = model;\n return result;\n}\n"],"names":["baseNumbers","a","A","c","C","g","G","t","T","n","N","makeFlagsHelper","x","r","code","name","flags","BamFlagsDecoder","CramFlagsDecoder","MateFlagsDecoder","CramRecord","constructor","cramFlags","readLength","mappingQuality","lengthOnRef","qualityScores","mateRecordNumber","readBases","readFeatures","mateToUse","readGroupId","readName","sequenceId","uniqueId","templateSize","alignmentStart","tags","this","mate","mateFlags","mateReadName","mateSequenceId","mateAlignmentStart","isPaired","isProperlyPaired","isSegmentUnmapped","isMateUnmapped","isReverseComplemented","isMateReverseComplemented","isRead1","isRead2","isSecondary","isFailedQc","isDuplicate","isSupplementary","isDetached","hasMateDownStream","isPreservingQualityScores","isUnknownBases","getReadBases","_refRegion","decoded","cramRecord","refRegion","regionSeqOffset","start","seq","slice","toUpperCase","bases","regionPos","currentReadFeature","length","feature","pos","added","data","sub","chunk","decodeReadSequence","getPairOrientation","s1","s2","o1","o2","tmp","isize","templateLength","undefined","Error","join","addReferenceSequence","compressionScheme","forEach","readFeature","refCoord","refPos","refBase","charAt","ref","baseNumber","base","substitutionMatrix","decodeBaseSubstitution","end","toJSON","Object","keys","k","startsWith","CramError","CramUnimplementedError","CramMalformedError","CramArgumentError","unzip","input","from","inflate","TF_SHIFT","TOTFREQ","RANS_BYTE_L","FC","F","advanceStep","freq","scaleBits","AriDecoder","fc","Array","i","R","DecodingSymbol","symbolInit","sym","advanceSymbolStep","get","advanceSymbol","pptr","advance","renormalize","assert","result","ByteBuffer","nodeBuffer","initialInputPosition","_buffer","_position","b","getByte","getByteAt","position","put","val","putAt","setPosition","getInt","readInt32LE","remaining","CramBufferOverrunError","getBits","cursor","numBits","bytePosition","bitPosition","dlen","parseItf8","buffer","initialOffset","offset","countFlags","parseLtf8","readUInt16LE","greaterThan","Number","MAX_SAFE_INTEGER","lessThan","MIN_SAFE_INTEGER","toNumber","parseItem","parser","startBufferPosition","startFilePosition","value","_endPosition","_size","tinyMemoize","_class","methodName","method","prototype","memoAttrName","res","call","Promise","resolve","catch","cramFileDefinition","_startOffset","dataView","DataView","byteOffset","magic","subarray","toString","majorVersion","getUint8","minorVersion","fileId","replaceAll","maxLength","makeTagSet","stringStart","stringEnd","str","push","formatMap","map","key","ents","console","warn","isMappedSliceHeader","header","refSeqId","cramUnmappedSliceHeader","numRecords","newOffset1","recordCounter","rc","newOffset2","numBlocks","newOffset3","numContentIds","newOffset4","contentIds","id","newOffset5","md5","cramMappedSliceHeader","refSeqStart","refSeqSpan","newOffset6","newOffset7","refBaseBlockId","newOffset8","cramEncodingSub","codecId","parametersBytes","parameters","bc","blockContentId","off","M2","M","numCodes","symbols","val2","numLengths","bitLengths","len","lengthsEncoding","valuesEncoding","stopByte","K","l2m","log2m","cramDataSeriesEncodingMap","mapSize","mapCount","String","fromCharCode","cramTagEncodingMap","k0","cramContainerHeader1","getInt32","alignmentSpan","numBases","numLandmarks","cramContainerHeader2","landmarks","landmark","crc32","getUint32","getSectionParsers","cramBlockHeader","d","compressionMethod","contentType","contentId","compressedSize","uncompressedSize","cramBlockCrc32","cramCompressionHeader","preservation","offsetRet","size","subbuf","tagSets","cramTagDictionary","cramPreservationMap","dataSeriesEncoding","tagEncoding","cramEncoding","readNullTerminatedString","parseTagData","tagType","Uint32Array","Int32Array","Int16Array","Uint16Array","Int8Array","Float32Array","parseInt","replace","arrayType","array","arr","Uint8Array","parseTagValueArray","decodeRecord","decodeDataSeries","sliceHeader","coreDataBlock","blocksByContentId","cursors","recordNumber","parsedContent","APdelta","lastAlignmentStart","readNamesIncluded","isUnmapped","setMateUnmapped","isOnNegativeStrand","setMateReverseComplemented","isWithMateDownstream","TLindex","TN","getTagNames","ntags","tagId","tagName","tagData","getCodecForTag","decode","isDecodeSequenceAsStar","readFeatureCount","currentReadPos","currentRefPos","decodeRFData","type","dataSeriesName","byteLength","toArray","readPosDelta","data1Schema","B","S","X","D","I","q","Q","H","P","data2Schema","decodeReadFeatures","isNaN","associateIntraSliceMate","allRecords","currentRecordNumber","thisRecord","mateRecord","complicatedMultiSegment","matedRecords","getAllMatedRecords","startRecord","records","starts","ends","estimatedTemplateLength","Math","max","min","calculateMultiSegmentMatedTemplateLength","lengthEstimate","calculateIntraSliceMatePairTemplateLength","CramSlice","container","containerPosition","sliceSize","file","getHeader","getDefinition","sectionParsers","containerHeader","readBlock","content","getBlocks","blockPosition","blocks","block","getCoreDataBlock","_getBlocksContentIdIndex","getBlockByContentId","getReferenceRegion","getCompressionScheme","refBlock","span","referenceRequired","fetchReferenceSequenceCallback","getAllRecords","getRecords","_fetchRecords","options","checkSequenceMD5","seqMd5","sequenceMD5","storedMd5","byte","coreBlock","externalBlocks","Map","getCursor","set","codec","getCodecForDataSeries","init","contentPosition","e","filterFunction","cacheKey","filePosition","recordsPromise","featureCache","filter","singleRefId","refRegions","record","seqId","NEGATIVE_INFINITY","all","values","async","split","CramCodec","dataType","instantiateCodec","super","arrayLength","_getLengthCodec","dataCodec","_getDataCodec","encodingParams","codecClasses","_decodeData","_decodeInt","_decodeByte","contentBlock","bytesRead","codes","codeBook","sortedCodes","sortedValuesByBitCode","sortedBitCodes","sortedBitLengthsByBitCode","bitCodeToValue","includes","TypeError","buildCodeBook","buildCodes","buildCaches","bitLength","_decode","_decodeZeroLengthCode","symbol","sort","codeLength","codeValue","entries","bitLengthInt","bitCode","delta","ii","numberOfSetBits","maxBitCode","fill","coreCursor","prevLen","bits","index","j","_decodeByteArray","dataBuffer","startPosition","stopPosition","numLeadingOnes","encodingData","CodecClass","dataSeriesTypes","BF","CF","RI","RL","AP","RG","MF","NS","NP","TS","NF","TC","FN","FP","BS","IN","SC","DL","BA","BB","RS","PD","HC","MQ","RN","QS","QQ","TL","CramContainerCompressionScheme","dataSeriesCodecCache","tagCodecCache","RR","tagIdsDictionary","TD","byteArray","matrix","parseSubstitutionMatrix","SM","test","ret","tagListId","endsWith","CramContainer","_readContainerHeader","getCompressionHeaderBlock","getFirstBlock","getSlice","slicePosition","fileSize","stat","bytes1","allocUnsafe","read","header1","numLandmarksSize","v","bytes2","header2","validateChecksums","checkCrc32","assign","maybeUrl","maybePath","maybeFilehandle","parseHeaderText","text","lines","line","tag","fields","f","indexOf","CramFile","args","url","path","filehandle","seqFetch","cacheSize","maxSize","uInt32","uInt8","getEndianness","headbytes","definition","getSamHeader","firstContainer","getContainerById","firstBlock","headerLength","getHeaderText","containerNumber","currentContainer","getContainerAtPosition","currentHeader","recordedCrc32","description","calculatedCrc32","unsigned","containerCount","readBlockHeader","_parseSection","section","preReadBuffer","_uncompress","inputBuffer","outputBuffer","copy","decompressedResponse","Response","XzReadableStream","buf","ReadableStream","controller","enqueue","close","arrayBuffer","order","outputSize","output","out","syms","cp","decoder","rle","readStatsO0","rans0","rans1","rans2","rans3","outputEnd","c0","c1","c2","c3","uncompressOrder0Way4","rlei","rlej","RansDecSymbol","readStatsO1","rans7","isz4","i0","i1","i2","i7","l0","l1","l2","l7","c7","uncompressOrder1Way4","blockHeader","blockContentPosition","uncompressedData","compressedData","crc","addRecordToIndex","containerStart","sliceStart","sliceBytes","s","CraiIndex","parseIndex","uncompressedBuffer","readFile","readUInt32LE","currentRecord","currentString","charCode","ent","e2","getIndex","parseIndexP","hasDataForReferenceSequence","getEntriesForRange","queryStart","queryEnd","seqEntries","compare","entry","entryStart","entryEnd","bins","IndexedCramFile","cram","cramUrl","cramPath","cramFilehandle","getRecordsForRange","opts","viewAsPairs","pairAcrossChr","maxInsertSize","slices","sliceResults","getRecordsInSlice","concat","readNames","readIds","unmatedPairs","matePromises","abs","mateSlices","mateBlocks","mateChunks","localeCompare","item","ary","mateRecordPromises","mateFeatPromises","recordPromise","featPromise","then","feats","mateRecs","newMateFeats","newMates","reduce","current","RangeCoder","IOStream","ByteModel","bzip2","ARITH_PACK","module","exports","src","stream","decodeStream","n_out","ReadByte","ReadUint7","e_len","decodeStripe","decodePackMeta","decodeCat","decodeExt","decodeRLE1","decodeRLE0","decode1","decode0","decodePack","encode","WriteByte","WriteUint7","Buffer","encodeStripe","pack_meta","encodePack","WriteStream","encodeRLE1","encodeRLE0","encode1","encode0","max_sym","byte_model","RangeStartDecode","ModelDecode","n_in","ModelEncode","RangeFinishEncode","last","decompress","encodeExt","model_lit","model_run","part","run","rctx","nsym","packMeta","meta","floor","hdr","ulen","comp","total","comp0","comp1","WriteData","clen","low","range","FFnum","carry","cache","RangeGetFrequency","tot_freq","RangeDecode","sym_low","sym_freq","RangeShiftLow","dst","RangeEncode","old_low","log","total_freq","acc","ModelRenormalise","read_array","tab","z","run_len","fqz_update_ctx","params","state","context","qctx","qshift","qtab","qbits","qloc","do_pos","ptab","p","ploc","do_delta","dtab","dloc","prevq","do_sel","sloc","decode_fqz_single_param","ReadUint16","pflags","do_dedup","fixed_len","do_qmap","do_qtab","qmap","decode_fqz_new_record","gparams","model","rev","max_sel","sel","stab","do_rev","rec","is_dup","dup","store_array","tmp1","sz1","i_start","tmp2","sz2","curr","q_lens","gflags","nparam","error","decode_fqz_params","qual","fqz_create_models","qual_len","reverse_qualities","decode_fqz","q_dirs","qhist","qd_last","qd_fixed","pbits","pshift","dbits","dshift","sbits","do_stab","pick_fqz_params","dsqr","WriteUint16","encode_fqz_params","model_qual","model_len","model_sel","process","exit","qlast","q1","encode_fqz","r4x8","r4x16","arith","fqzcomp","tok3","r4x8_uncompress","r4x16_uncompress","arith_uncompress","fqzcomp_uncompress","tok3_uncompress","start_pos","EOF","ReadData","ReadChar","ReadUint32","ReadString","ReadITF8","WriteChar","charCodeAt","WriteString","u","WriteUint32","writeInt32LE","WriteITF8","WriteByteNeg","RansGetCumulativeFreq","RansGetSymbolFromFreq","RansBuildC2S","C2S","RansAdvanceStep","RansRenorm","RansEncFlush","RansEncPut","scale_bits","R_max","RansEncRenorm","ReadFrequencies0","last_sym","NormaliseFrequencies0","tot","scale","max_val","max_idx","renorm","WriteFrequencies0","nbytes","i4","RansDecode0","ReadFrequencies1","L","nbytes4","RansDecode1","BuildFrequencies0","alloc","rans_out","freq_tab","RansEncode0","F0","BuildFrequencies1","NormaliseFrequencies1","WriteFrequencies1","idx","RansEncode1","RansEncodeStripe","RansDecodeStream","format","stripe","cat","pack","RansDecodeStripe","pack_len","DecodePackMeta","rle_len","rle_meta","u_meta_len","comp_meta_len","DecodeRLEMeta","shift","freq_src","ReadAlphabet","NormaliseFrequencies0_Shift","DecodeRLE","DecodePack","ceil","EncodePack","nrle","dpos","cmeta","EncodeRLE","bit_size","log2","WriteAlphabet","cfreq","NormaliseFrequencies1_Shift","rans","LeftPadNumber","DecodeSingleName","m","l","FillByteStreams","tnum","names","max_tok","max_len","SerialiseByteStreams","use_arith","try_compress","best","methods","lvl","TokeniseName","tok","match","substring","ntok","TOK_END","separator","nnames","in_size","ttype","tok_new","tok_dup","dup_pos","dup_type","DecodeTokenByteStreams","bytes","bit","BITMASK","left","chunks","bufsize","h","origPtr","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","uc","splice","symCount","groups","minLen","maxLen","hufGroup","temp","MAX_HUFCODE_BITS","permute","limit","pp","runPos","count","selector","byteCount","GROUP_SIZE","nextSym","copies","previous","outbyte","Infinity","charenc","utf8","stringToBytes","bin","unescape","encodeURIComponent","bytesToString","decodeURIComponent","escape","base64map","crypt","rotl","rotr","endian","randomBytes","random","bytesToWords","words","wordsToBytes","bytesToHex","hex","hexToBytes","substr","bytesToBase64","base64","triplet","base64ToBytes","imod4","pow","isBuffer","obj","readFloatLE","isSlowBuffer","_isBuffer","message","encoding","isArray","FF","_ff","GG","_gg","HH","_hh","II","_ii","aa","bb","cc","dd","_blocksize","_digestsize","digestbytes","asBytes","asString","factory","__WEBPACK_EXTERNAL_MODULE__2__","__webpack_modules__","__webpack_module_cache__","moduleId","cachedModule","o","defineProperty","enumerable","prop","hasOwnProperty","Symbol","toStringTag","_dist_native_xz_decompress_wasm__WEBPACK_IMPORTED_MODULE_0__","globalThis","XzContext","moduleInstance","memory","ptr","create_context","_refresh","bufSize","mem32","inStart","inEnd","outStart","supplyInput","sourceDataUint8Array","mem8","supply_input","getNextOutput","get_next_output","outChunk","finished","needsMoreInput","outputBufferIsFull","resetOutputBuffer","outPos","dispose","destroy_context","static","_getModuleInstance","base64Wasm","wasmBytes","atob","WebAssembly","instantiate","_moduleInstance","instance","compressedStream","xzContext","unconsumedInput","compressedReader","getReader","_moduleInstancePromise","pull","done","nextInputLength","nextOutputResult","cancel","TABLE","calculator","signed"],"sourceRoot":""} |