From 053b0a5485ee01b387cc2e016bcb245c0e764d86 Mon Sep 17 00:00:00 2001 From: vict0rsch Date: Fri, 19 Aug 2022 21:02:18 +0100 Subject: [PATCH 01/80] include gist management --- gulpfile.js | 1 + src/popup/popup.html | 1 + src/shared/js/utils/gist.js | 13 +++++++++++++ src/shared/min/utils.min.js | 32 ++++++++++++++++---------------- 4 files changed, 31 insertions(+), 16 deletions(-) create mode 100644 src/shared/js/utils/gist.js diff --git a/gulpfile.js b/gulpfile.js index 1eb18b7e..27db7bbd 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -36,6 +36,7 @@ function utilsJS() { src([ "src/shared/js/utils/miniquery.js", "src/shared/js/utils/config.js", + "src/shared/js/utils/gist.js", "src/shared/js/utils/levenshtein.js", "src/shared/js/utils/bibtexParser.js", "src/shared/js/utils/functions.js", diff --git a/src/popup/popup.html b/src/popup/popup.html index 0a21c16e..1590361a 100755 --- a/src/popup/popup.html +++ b/src/popup/popup.html @@ -30,6 +30,7 @@ + diff --git a/src/shared/js/utils/gist.js b/src/shared/js/utils/gist.js new file mode 100644 index 00000000..4ad12ec3 --- /dev/null +++ b/src/shared/js/utils/gist.js @@ -0,0 +1,13 @@ +/* simple-github-gist-api browserified -> browserify main.js -o gist.js + see ~/Documents/Github/simple-github-gist-api +*/ +!function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n;return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils.forEach(["delete","get","head"],(function forEachMethodNoData(method){defaults.headers[method]={}})),utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){defaults.headers[method]=utils.merge(DEFAULT_CONTENT_TYPE)})),module.exports=defaults}).call(this)}).call(this,require("_process"))},{"../adapters/http":3,"../adapters/xhr":3,"../core/AxiosError":9,"../helpers/normalizeHeaderName":26,"../helpers/toFormData":31,"../utils":33,"./env/FormData":27,"./transitional":17,_process:37}],17:[function(require,module,exports){"use strict";module.exports={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1}},{}],18:[function(require,module,exports){module.exports={version:"0.27.2"}},{}],19:[function(require,module,exports){"use strict";module.exports=function bind(fn,thisArg){return function wrap(){for(var args=new Array(arguments.length),i=0;i=0)return;parsed[key]="set-cookie"===key?(parsed[key]?parsed[key]:[]).concat([val]):parsed[key]?parsed[key]+", "+val:val}})),parsed):parsed}},{"./../utils":33}],29:[function(require,module,exports){"use strict";module.exports=function parseProtocol(url){var match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}},{}],30:[function(require,module,exports){"use strict";module.exports=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}}},{}],31:[function(require,module,exports){(function(Buffer){(function(){"use strict";var utils=require("../utils");function toFormData(obj,formData){formData=formData||new FormData;var stack=[];function convertValue(value){return null===value?"":utils.isDate(value)?value.toISOString():utils.isArrayBuffer(value)||utils.isTypedArray(value)?"function"==typeof Blob?new Blob([value]):Buffer.from(value):value}function build(data,parentKey){if(utils.isPlainObject(data)||utils.isArray(data)){if(-1!==stack.indexOf(data))throw Error("Circular reference detected in "+parentKey);stack.push(data),utils.forEach(data,(function each(value,key){if(!utils.isUndefined(value)){var fullKey=parentKey?parentKey+"."+key:key,arr;if(value&&!parentKey&&"object"==typeof value)if(utils.endsWith(key,"{}"))value=JSON.stringify(value);else if(utils.endsWith(key,"[]")&&(arr=utils.toArray(value)))return void arr.forEach((function(el){!utils.isUndefined(el)&&formData.append(fullKey,convertValue(el))}));build(value,fullKey)}})),stack.pop()}else formData.append(parentKey,convertValue(data))}return build(obj),formData}module.exports=toFormData}).call(this)}).call(this,require("buffer").Buffer)},{"../utils":33,buffer:35}],32:[function(require,module,exports){"use strict";var VERSION=require("../env/data").version,AxiosError=require("../core/AxiosError"),validators={};["object","boolean","number","function","string","symbol"].forEach((function(type,i){validators[type]=function validator(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}}));var deprecatedWarnings={};function assertOptions(options,schema,allowUnknown){if("object"!=typeof options)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var keys=Object.keys(options),i=keys.length;i-- >0;){var opt=keys[i],validator=schema[opt];if(validator){var value=options[opt],result=void 0===value||validator(value,opt,options);if(!0!==result)throw new AxiosError("option "+opt+" must be "+result,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==allowUnknown)throw new AxiosError("Unknown option "+opt,AxiosError.ERR_BAD_OPTION)}}validators.transitional=function transitional(validator,version,message){function formatMessage(opt,desc){return"[Axios v"+VERSION+"] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return function(value,opt,opts){if(!1===validator)throw new AxiosError(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),!validator||validator(value,opt,opts)}},module.exports={assertOptions:assertOptions,validators:validators}},{"../core/AxiosError":9,"../env/data":18}],33:[function(require,module,exports){"use strict";var bind=require("./helpers/bind"),toString=Object.prototype.toString,kindOf=(cache=Object.create(null),function(thing){var str=toString.call(thing);return cache[str]||(cache[str]=str.slice(8,-1).toLowerCase())}),cache;function kindOfTest(type){return type=type.toLowerCase(),function isKindOf(thing){return kindOf(thing)===type}}function isArray(val){return Array.isArray(val)}function isUndefined(val){return void 0===val}function isBuffer(val){return null!==val&&!isUndefined(val)&&null!==val.constructor&&!isUndefined(val.constructor)&&"function"==typeof val.constructor.isBuffer&&val.constructor.isBuffer(val)}var isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(val){var result;return result="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(val):val&&val.buffer&&isArrayBuffer(val.buffer)}function isString(val){return"string"==typeof val}function isNumber(val){return"number"==typeof val}function isObject(val){return null!==val&&"object"==typeof val}function isPlainObject(val){if("object"!==kindOf(val))return!1;var prototype=Object.getPrototypeOf(val);return null===prototype||prototype===Object.prototype}var isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList");function isFunction(val){return"[object Function]"===toString.call(val)}function isStream(val){return isObject(val)&&isFunction(val.pipe)}function isFormData(thing){var pattern="[object FormData]";return thing&&("function"==typeof FormData&&thing instanceof FormData||toString.call(thing)===pattern||isFunction(thing.toString)&&thing.toString()===pattern)}var isURLSearchParams=kindOfTest("URLSearchParams");function trim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function isStandardBrowserEnv(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function forEach(obj,fn){if(null!=obj)if("object"!=typeof obj&&(obj=[obj]),isArray(obj))for(var i=0,l=obj.length;i0;)merged[prop=props[i]]||(destObj[prop]=sourceObj[prop],merged[prop]=!0);sourceObj=Object.getPrototypeOf(sourceObj)}while(sourceObj&&(!filter||filter(sourceObj,destObj))&&sourceObj!==Object.prototype);return destObj}function endsWith(str,searchString,position){str=String(str),(void 0===position||position>str.length)&&(position=str.length),position-=searchString.length;var lastIndex=str.indexOf(searchString,position);return-1!==lastIndex&&lastIndex===position}function toArray(thing){if(!thing)return null;var i=thing.length;if(isUndefined(i))return null;for(var arr=new Array(i);i-- >0;)arr[i]=thing[i];return arr}var isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(thing){return TypedArray&&thing instanceof TypedArray}),TypedArray;module.exports={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:isTypedArray,isFileList:isFileList}},{"./helpers/bind":19}],34:[function(require,module,exports){"use strict";exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("="),placeHoldersLen;return-1===validLen&&(validLen=len),[validLen,validLen===len?0:4-validLen%4]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var tmp,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen,i;for(i=0;i>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+16383));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],35:[function(require,module,exports){(function(Buffer){(function(){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}function createBuffer(length){if(length>2147483647)throw new RangeError('The value "'+length+'" is invalid for option "size"');var buf=new Uint8Array(length);return buf.__proto__=Buffer.prototype,buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return fromString(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(null==value)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('The "value" argument must not be of type number. Received type number');var valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);var b=fromObject(value);if(b)return b;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError('"size" argument must be of type number');if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"')}function alloc(size,fill,encoding){return assertSize(size),size<=0?createBuffer(size):void 0!==fill?"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill):createBuffer(size)}function allocUnsafe(size){return assertSize(size),createBuffer(size<0?0:0|checked(size))}function fromString(string,encoding){if("string"==typeof encoding&&""!==encoding||(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=array.length<0?0:0|checked(array.length),buf=createBuffer(length),i=0;i=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof string);var len=string.length,mustMatch=arguments.length>2&&!0===arguments[2];if(!mustMatch&&0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),numberIsNaN(byteOffset=+byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1,arrLength=arr.length,valLength=val.length,i;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1,secondByte,thirdByte,fourthByte,tempCodePoint;if(i+bytesPerSequence<=end)switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:128==(192&(secondByte=buf[i+1]))&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function isBuffer(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);imax&&(str+=" ... "),""},Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(this===target)return 0;for(var x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0),len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function slice(start,end){var len=this.length;(start=~~start)<0?(start+=len)<0&&(start=0):start>len&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;byteLength>0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return val>=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function readInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){var maxBytes;(value=+value,offset>>>=0,byteLength>>>=0,noAssert)||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,noAssert)||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var i=byteLength-1,mul=1;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len},Buffer.prototype.fill=function fill(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(1===val.length){var code=val.charCodeAt(0);("utf8"===encoding&&code<128||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(start<0||this.length>>=0,end=void 0===end?this.length:end>>>0,val||(val=0),"number"==typeof val)for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!=obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),(value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias))*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],37:[function(require,module,exports){var process=module.exports={},cachedSetTimeout,cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex1)for(var i=1;i app. Playing with this gist directly, may have adverse effects in your application."}};exports.default=constants},{}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const GithubGist_1=require("./models/GithubGist");exports.default=GithubGist_1.default},{"./models/GithubGist":41}],40:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const axios_1=require("axios"),auth_config_1=require("../util/auth-config"),constants_1=require("../constants");class GistFile{constructor(options){var _a,_b;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=newContent=>{this.fileContent=newContent,this.fileHasUpdates=!0},this.save=()=>__awaiter(this,void 0,void 0,(function*(){if(!this.hasUpdates)return;const url=`${constants_1.default.githubGists}/${this.gistId}`,body={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}};yield axios_1.default.post(url,body,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1})),this.fetchLatest=()=>__awaiter(this,void 0,void 0,(function*(){const latestCommit=yield this.getLatestGistCommit(),url=this.getLatestGistFileFetchUrl(latestCommit),response=yield axios_1.default.get(url,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=response.data,this.fileHasUpdates=!1})),this.getLatestGistFileFetchUrl=commitId=>{const{addCorsPrefix:addCorsPrefix,customCorsPrefix:customCorsPrefix,gistOwner:gistOwner,gistId:gistId}=this,url=`https://gist.githubusercontent.com/${gistOwner}`+`/${gistId}/raw/${commitId}/${this.fileName}`;return addCorsPrefix?null!=customCorsPrefix?customCorsPrefix(url):constants_1.default.corsAnywhere+url:url},this.getLatestGistCommit=()=>__awaiter(this,void 0,void 0,(function*(){const dummyParam=`dummyParam=${Math.random()}`,url=`${constants_1.default.githubGists}/${this.gistId}?${dummyParam}`;try{const result=yield axios_1.default.get(url,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken})),response=result.data,latestCommit=response.history[0];return latestCommit.version}catch(e){throw new Error("Error while fetching the latest commit.")}})),this.personalAccessToken=options.personalAccessToken,this.gistId=options.gistId,this.gistOwner=options.gistOwner,this.fileName=options.fileName,this.fileContent=options.fileContent,this.isPublic=options.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null===(_a=options.cors)||void 0===_a?void 0:_a.addPrefix),this.customCorsPrefix=null===(_b=options.cors)||void 0===_b?void 0:_b.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(value){this.fileHasUpdates=value}}exports.default=GistFile},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const axios_1=require("axios"),auth_config_1=require("../util/auth-config"),token_validity_1=require("../util/token-validity"),is_string_empty_1=require("../util/is-string-empty"),formatted_gist_identifier_1=require("../util/formatted-gist-identifier"),constants_1=require("../constants"),GistFile_1=require("./GistFile");class GithubGist{constructor(options){var _a,_b;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>__awaiter(this,void 0,void 0,(function*(){yield(0,token_validity_1.default)(this.personalAccessToken),yield this.fetchGist(),(0,is_string_empty_1.default)(this.gistId)&&(yield this.createGist())})),this.createFile=(name,content)=>{const existingFile=this.gistFiles.find(file=>file.name===name);if(existingFile)return existingFile.overwrite(content),!1;const file=this.constructGistFile(name,content);return this.gistFiles.push(file),!0},this.getFile=name=>{const file=this.gistFiles.find(file=>file.name===name);return file||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(file=>file.name),this.save=()=>__awaiter(this,void 0,void 0,(function*(){const files={};for(const file of this.gistFiles)!1!==file.hasUpdates&&(files[file.name]={content:file.content});if(0===Object.keys(files).length)return;const url=`${constants_1.default.githubGists}/${this.gistId}`,body={public:this.isPublic,files:files};yield axios_1.default.post(url,body,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(file=>{file.hasUpdates=!1})})),this.fetchGist=()=>__awaiter(this,void 0,void 0,(function*(){const result=yield axios_1.default.get(constants_1.default.githubGists,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken})),gists=result.data;for(const gist of gists){const fileNames=Object.keys(gist.files);if(fileNames.includes(this.formattedAppIdentifier)){yield this.initialize(gist);break}}})),this.createGist=()=>__awaiter(this,void 0,void 0,(function*(){const{identifier:{content:content},githubGists:githubGists}=constants_1.default,rootFileContent=content.replace("",this.appIdentifier),payload={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:rootFileContent}}},result=yield axios_1.default.post(githubGists,payload,(0,auth_config_1.default)({personalAccessToken:this.personalAccessToken})),gist=result.data;yield this.initialize(gist)})),this.initialize=gist=>__awaiter(this,void 0,void 0,(function*(){this.gistId=gist.id,this.gistOwner=gist.owner.login;const fetchFileContent=[];this.gistFiles=[];for(const fileName of Object.keys(gist.files)){const file=this.constructGistFile(fileName,"");fetchFileContent.push(file.fetchLatest()),this.gistFiles.push(file)}yield Promise.all(fetchFileContent)})),this.constructGistFile=(fileName,content)=>new GistFile_1.default({fileName:fileName,fileContent:content,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=options.personalAccessToken,this.appIdentifier=options.appIdentifier,this.formattedAppIdentifier=(0,formatted_gist_identifier_1.default)(options.appIdentifier),this.isPublic=Boolean(options.isPublic),this.addCorsPrefix=Boolean(null===(_a=options.cors)||void 0===_a?void 0:_a.addPrefix),this.customCorsPrefix=null===(_b=options.cors)||void 0===_b?void 0:_b.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}exports.default=GithubGist},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const getAuthConfig=props=>({headers:{Authorization:`token ${props.personalAccessToken}`}});exports.default=getAuthConfig},{}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const constants_1=require("../constants"),formattedGistIdentifier=identifierName=>{const{prefix:prefix,suffix:suffix}=constants_1.default.identifier;return prefix+identifierName+suffix};exports.default=formattedGistIdentifier},{"../constants":38}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const isStringEmpty=s=>0===s.length;exports.default=isStringEmpty},{}],45:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const axios_1=require("axios"),constants_1=require("../constants"),isTokenStringValid=token=>__awaiter(void 0,void 0,void 0,(function*(){const rateLimitEndpoint=constants_1.default.githubRateLimit;return axios_1.default.get(rateLimitEndpoint,{headers:{Authorization:`token ${token}`}}).then(result=>result.headers["x-oauth-scopes"].includes("gist"))})),validateToken=token=>__awaiter(void 0,void 0,void 0,(function*(){if(!(yield isTokenStringValid(token)))throw new Error("Token is invalid or it doesn't have gist access.")}));exports.default=validateToken},{"../constants":38,axios:2}]},{},[1]); \ No newline at end of file diff --git a/src/shared/min/utils.min.js b/src/shared/min/utils.min.js index 0995f70d..3d2da3e4 100644 --- a/src/shared/min/utils.min.js +++ b/src/shared/min/utils.min.js @@ -1,4 +1,4 @@ -const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:findEl("memory-container--"+e).querySelector("."+t),fadeOut=(e,t=250,a=()=>{})=>{(e=findEl(e)).style.transition=t+"ms",e.style.opacity=0,setTimeout(()=>{e.style.display="none",a()},t)},fadeIn=(e,t="block",a=250,r=()=>{})=>{(e=findEl(e)).style.opacity=0,"none"===e.style.display&&(e.style.display=t),setTimeout(()=>{e.style.transition=a+"ms",e.style.opacity=1,setTimeout(()=>{r()},a)},0)},val=(e,t)=>{if(e instanceof HTMLInputElement&&"checkbox"===e.type){if(void 0===t)return e.checked;e.checked=t}if("string"==typeof e&&(e=findEl(e)),void 0===t)return e?e.value:"";e&&(e.value=t)},showId=(e,t="block")=>{let a=findEl(e);a&&(a.style.display=t)},hideId=e=>{(el=findEl(e))&&(el.style.display="none")},setTextId=(e,t)=>{let a=findEl(e);a&&(a.innerText=t)},setHTML=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&(e.innerHTML=t)},dispatch=(e,t)=>{if("string"==typeof e&&(e=findEl(e)),"string"==typeof t){if("focus"===t)return void e.focus();if("blur"===t)return void e.blur();t=new Event(t)}e&&e.dispatchEvent(t)},hasClass=(e,t)=>{let a;if(a="string"==typeof e?findEl(e):e)return a.classList.contains(t)},addClass=(e,t)=>{let a;(a="string"==typeof e?findEl(e):e)&&a.classList.add(t)},removeClass=(e,t)=>{let a;(a="string"==typeof e?findEl(e):e)&&a.classList.remove(t)},addListener=(e,t,a)=>{(e="string"==typeof e?findEl(e):e)&&e.addEventListener(t,a)},setPlaceholder=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&void 0!==e.placeholder&&(e.placeholder=t)},style=(e,t,a)=>{if(e="string"==typeof e?findEl(e):e){if(void 0===a)return e.style[t];e.style[t]=a}},disable=(e,t=!0)=>{(e="string"==typeof e?findEl(e):e)&&(e.disabled=t)},slideUp=(e,t=250,a=()=>{})=>{(e="string"==typeof e?findEl(e):e)&&(e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.height=e.offsetHeight+"px",e.offsetHeight,e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,window.setTimeout(()=>{e.style.display="none",e.style.removeProperty("height"),e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property"),e.style.removeProperty("box-sizing"),a()},t))},slideDown=(t,a=500,r=()=>{})=>{if(t="string"==typeof t?findEl(t):t){t.style.removeProperty("display");let e=window.getComputedStyle(t).display;"none"===e&&(e="block"),t.style.display=e;var i=t.offsetHeight;t.style.overflow="hidden",t.style.height=0,t.style.paddingTop=0,t.style.paddingBottom=0,t.style.marginTop=0,t.style.marginBottom=0,t.offsetHeight,t.style.transitionProperty="height, margin, padding",t.style.transitionDuration=a+"ms",t.style.height=i+"px",t.style.removeProperty("padding-top"),t.style.removeProperty("padding-bottom"),t.style.removeProperty("margin-top"),t.style.removeProperty("margin-bottom"),window.setTimeout(()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow"),t.style.removeProperty("transition-duration"),t.style.removeProperty("transition-property"),r()},a)}},slideToggle=(e,t=500,a=()=>{})=>("none"===window.getComputedStyle(e).display?slideDown:slideUp)(e,t,a),queryAll=(e,t)=>Array.from(e.querySelectorAll(t));var dummyModule;"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={findEl:findEl,fadeOut:fadeOut,fadeIn:fadeIn,val:val,showId:showId,hideId:hideId,setTextId:setTextId,setHTML:setHTML,dispatch:dispatch,hasClass:hasClass,addClass:addClass,removeClass:removeClass,addListener:addListener,setPlaceholder:setPlaceholder,style:style,disable:disable,slideUp:slideUp,slideDown:slideDown,slideToggle:slideToggle,queryAll:queryAll});const createElementFromHTML=e=>{var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild};Object.defineProperty(Array.prototype,"last",{value:function(e=0){return this.reverse()[e]}}),Object.defineProperty(String.prototype,"capitalize",{value:function(e=!1){return e?this.split(" ").map(e=>e.capitalize()).join(" "):this.charAt(0).toUpperCase()+this.slice(1).toLowerCase()}});var global={},dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule;function _min(e,t,a,r,i){return eBoolean(e.match(/journals\.aps\.org\/\w+\/(abstract|pdf)\//g))],acs:["pubs.acs.org/doi/"],arxiv:["arxiv.org/abs/","arxiv.org/pdf/","scirate.com/arxiv/"],biorxiv:["biorxiv.org/content"],cvf:["openaccess.thecvf.com/content"],frontiers:["frontiersin.org/articles"],ijcai:[e=>/ijcai\.org\/proceedings\/\d{4}\/\d+/gi.test(e)],ieee:["ieeexplore.ieee.org/document/","ieeexplore.ieee.org/abstract/document/","ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber="],iop:["iopscience.iop.org/article/"],jmlr:[e=>e.includes("jmlr.org/papers/v")&&!e.endsWith("/")],nature:["nature.com/articles/"],neurips:["neurips.cc/paper/","nips.cc/paper/"],openreview:["openreview.net/forum","openreview.net/pdf"],pmc:["ncbi.nlm.nih.gov/pmc/articles/PMC"],pmlr:["proceedings.mlr.press/"],pnas:["pnas.org/content/","pnas.org/doi/"],science:[e=>Boolean(e.match(/science\.org\/doi\/?(abs|full|pdf|epdf)?\//g))],sciencedirect:["sciencedirect.com/science/article/pii/","sciencedirect.com/science/article/abs/pii/","reader.elsevier.com/reader/sd/pii/"],springer:[...global.sourceExtras.springer.types.map(e=>`link.springer.com/${e}/`),"link.springer.com/content/pdf/"],wiley:[e=>Boolean(e.match(/onlinelibrary\.wiley\.com\/doi\/(abs|full|pdf|epdf)\//g))]},global.sourcesNames={acl:"Association for Computational Linguistics (ACL)",acm:"Association for Computing Machinery (ACM)",acs:"American Chemical Society (ACS)",aps:"American Physical Society",arxiv:"ArXiv",biorxiv:"BioRxiv",cvf:"Computer Vision Foundation (CVF)",ijcai:"International Joint Conferences on Artificial Intelligence (IJCAI)",iop:"Institute Of Physics (IOP)",jmlr:"Journal of Machine Learning Research (JMLR)",nature:"Nature",neurips:"NeurIPS",openreview:"OpenReview",pmc:"PubMed Central",pmlr:"Proceedings of Machine Learning Research (PMLR)",pnas:"Proceedings of the National Academy of Sciences (PNAS)",science:"Science",sciencedirect:"ScienceDirect",springer:"Springer",wiley:"Wiley"},global.overrideORConfs={"robot-learning":"CoRL",ijcai:"IJCAI"},global.overridePMLRConfs={"Conference on Learning Theory":"CoLT","International Conference on Machine Learning":"ICML","Conference on Uncertainty in Artificial Intelligence":"UAI","Conference on Robot Learning":"CoRL","International Conference on Artificial Intelligence and Statistics":"AISTATS","International Conference on Algorithmic Learning Theory":"ALT"},global.overrideDBLPVenues={"J. Mach. Learn. Res.":"JMLR"},global.consolHeaderStyle="font-family:system-ui;font-size:1.2rem;font-weight:lighter;display:inline-block;border:2px solid #A41716;border-radius: 8px;padding: 16px; margin: 20px;",global.fuzzyTitleMatchMinDist=4,global.defaultTitleFunctionCode=`(paper) => { +const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:findEl("memory-container--"+e).querySelector("."+t),fadeOut=(e,t=250,r=()=>{})=>{(e=findEl(e)).style.transition=t+"ms",e.style.opacity=0,setTimeout(()=>{e.style.display="none",r()},t)},fadeIn=(e,t="block",r=250,i=()=>{})=>{(e=findEl(e)).style.opacity=0,"none"===e.style.display&&(e.style.display=t),setTimeout(()=>{e.style.transition=r+"ms",e.style.opacity=1,setTimeout(()=>{i()},r)},0)},val=(e,t)=>{if(e instanceof HTMLInputElement&&"checkbox"===e.type){if(void 0===t)return e.checked;e.checked=t}if("string"==typeof e&&(e=findEl(e)),void 0===t)return e?e.value:"";e&&(e.value=t)},showId=(e,t="block")=>{let r=findEl(e);r&&(r.style.display=t)},hideId=e=>{(el=findEl(e))&&(el.style.display="none")},setTextId=(e,t)=>{let r=findEl(e);r&&(r.innerText=t)},setHTML=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&(e.innerHTML=t)},dispatch=(e,t)=>{if("string"==typeof e&&(e=findEl(e)),"string"==typeof t){if("focus"===t)return void e.focus();if("blur"===t)return void e.blur();t=new Event(t)}e&&e.dispatchEvent(t)},hasClass=(e,t)=>{let r;if(r="string"==typeof e?findEl(e):e)return r.classList.contains(t)},addClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.add(t)},removeClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.remove(t)},addListener=(e,t,r)=>{(e="string"==typeof e?findEl(e):e)&&e.addEventListener(t,r)},setPlaceholder=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&void 0!==e.placeholder&&(e.placeholder=t)},style=(e,t,r)=>{if(e="string"==typeof e?findEl(e):e){if(void 0===r)return e.style[t];e.style[t]=r}},disable=(e,t=!0)=>{(e="string"==typeof e?findEl(e):e)&&(e.disabled=t)},slideUp=(e,t=250,r=()=>{})=>{(e="string"==typeof e?findEl(e):e)&&(e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.height=e.offsetHeight+"px",e.offsetHeight,e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,window.setTimeout(()=>{e.style.display="none",e.style.removeProperty("height"),e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property"),e.style.removeProperty("box-sizing"),r()},t))},slideDown=(t,r=500,i=()=>{})=>{if(t="string"==typeof t?findEl(t):t){t.style.removeProperty("display");let e=window.getComputedStyle(t).display;"none"===e&&(e="block"),t.style.display=e;var n=t.offsetHeight;t.style.overflow="hidden",t.style.height=0,t.style.paddingTop=0,t.style.paddingBottom=0,t.style.marginTop=0,t.style.marginBottom=0,t.offsetHeight,t.style.transitionProperty="height, margin, padding",t.style.transitionDuration=r+"ms",t.style.height=n+"px",t.style.removeProperty("padding-top"),t.style.removeProperty("padding-bottom"),t.style.removeProperty("margin-top"),t.style.removeProperty("margin-bottom"),window.setTimeout(()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow"),t.style.removeProperty("transition-duration"),t.style.removeProperty("transition-property"),i()},r)}},slideToggle=(e,t=500,r=()=>{})=>("none"===window.getComputedStyle(e).display?slideDown:slideUp)(e,t,r),queryAll=(e,t)=>Array.from(e.querySelectorAll(t));var dummyModule;"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={findEl:findEl,fadeOut:fadeOut,fadeIn:fadeIn,val:val,showId:showId,hideId:hideId,setTextId:setTextId,setHTML:setHTML,dispatch:dispatch,hasClass:hasClass,addClass:addClass,removeClass:removeClass,addListener:addListener,setPlaceholder:setPlaceholder,style:style,disable:disable,slideUp:slideUp,slideDown:slideDown,slideToggle:slideToggle,queryAll:queryAll});const createElementFromHTML=e=>{var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild};Object.defineProperty(Array.prototype,"last",{value:function(e=0){return this.reverse()[e]}}),Object.defineProperty(String.prototype,"capitalize",{value:function(e=!1){return e?this.split(" ").map(e=>e.capitalize()).join(" "):this.charAt(0).toUpperCase()+this.slice(1).toLowerCase()}});var global={},dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule;function _min(e,t,r,i,n){return eBoolean(e.match(/journals\.aps\.org\/\w+\/(abstract|pdf)\//g))],acs:["pubs.acs.org/doi/"],arxiv:["arxiv.org/abs/","arxiv.org/pdf/","scirate.com/arxiv/"],biorxiv:["biorxiv.org/content"],cvf:["openaccess.thecvf.com/content"],frontiers:["frontiersin.org/articles"],ijcai:[e=>/ijcai\.org\/proceedings\/\d{4}\/\d+/gi.test(e)],ieee:["ieeexplore.ieee.org/document/","ieeexplore.ieee.org/abstract/document/","ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber="],iop:["iopscience.iop.org/article/"],jmlr:[e=>e.includes("jmlr.org/papers/v")&&!e.endsWith("/")],nature:["nature.com/articles/"],neurips:["neurips.cc/paper/","nips.cc/paper/"],openreview:["openreview.net/forum","openreview.net/pdf"],pmc:["ncbi.nlm.nih.gov/pmc/articles/PMC"],pmlr:["proceedings.mlr.press/"],pnas:["pnas.org/content/","pnas.org/doi/"],science:[e=>Boolean(e.match(/science\.org\/doi\/?(abs|full|pdf|epdf)?\//g))],sciencedirect:["sciencedirect.com/science/article/pii/","sciencedirect.com/science/article/abs/pii/","reader.elsevier.com/reader/sd/pii/"],springer:[...global.sourceExtras.springer.types.map(e=>`link.springer.com/${e}/`),"link.springer.com/content/pdf/"],wiley:[e=>Boolean(e.match(/onlinelibrary\.wiley\.com\/doi\/(abs|full|pdf|epdf)\//g))]},global.sourcesNames={acl:"Association for Computational Linguistics (ACL)",acm:"Association for Computing Machinery (ACM)",acs:"American Chemical Society (ACS)",aps:"American Physical Society",arxiv:"ArXiv",biorxiv:"BioRxiv",cvf:"Computer Vision Foundation (CVF)",ijcai:"International Joint Conferences on Artificial Intelligence (IJCAI)",iop:"Institute Of Physics (IOP)",jmlr:"Journal of Machine Learning Research (JMLR)",nature:"Nature",neurips:"NeurIPS",openreview:"OpenReview",pmc:"PubMed Central",pmlr:"Proceedings of Machine Learning Research (PMLR)",pnas:"Proceedings of the National Academy of Sciences (PNAS)",science:"Science",sciencedirect:"ScienceDirect",springer:"Springer",wiley:"Wiley"},global.overrideORConfs={"robot-learning":"CoRL",ijcai:"IJCAI"},global.overridePMLRConfs={"Conference on Learning Theory":"CoLT","International Conference on Machine Learning":"ICML","Conference on Uncertainty in Artificial Intelligence":"UAI","Conference on Robot Learning":"CoRL","International Conference on Artificial Intelligence and Statistics":"AISTATS","International Conference on Algorithmic Learning Theory":"ALT"},global.overrideDBLPVenues={"J. Mach. Learn. Res.":"JMLR"},global.consolHeaderStyle="font-family:system-ui;font-size:1.2rem;font-weight:lighter;display:inline-block;border:2px solid #A41716;border-radius: 8px;padding: 16px; margin: 20px;",global.fuzzyTitleMatchMinDist=4,global.defaultTitleFunctionCode=`(paper) => { const title = paper.title.replaceAll("\\n", ''); const id = paper.id; let name = \`\${title} - \${id}\`; @@ -8,24 +8,24 @@ const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:f /!\\ It has to stay in your downloads for PaperMemory to be able to access your papers. /!\\ To be able to open files from this folder instead of re-downloading them, PaperMemory will match their titles and downloaded urls. /!\\ If you change the default title function in the Advanced Options and do not include a paper's title in the file name, PaperMemory may not be able to open the file and will instead open the pdf url. - /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle});const levenshtein=(e,t)=>{if(e===t)return 0;e.length>t.length&&(a=e,e=t,t=a);for(var a,r=e.length,i=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,a=(this.match("{",!1),this.pos),r=!1;;){if(!r)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,a=!1;;){if(!a){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}a="\\"==this.input[this.pos]&&0==a,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, -`;delete e.entryType,delete e.citationKey;var a,r=Math.max(...Object.keys(e).map(e=>e.length));for(const i in e)e.hasOwnProperty(i)&&e[i]&&(a=e[i].replaceAll(/\s+/g," ").trim(),bkey=i+" ".repeat(r-i.length),t+=` ${bkey} = {${a}}, -`);return(t.slice(0,-2)+"\n}").replaceAll("\t"," ").replaceAll("--","-")},extractBibtexValue=(e,t)=>{const a=bibtexToObject(e);return a.hasOwnProperty(t)?a[t]:""},extractAuthor=e=>extractBibtexValue(e,"author").replaceAll("{","").replaceAll("}","").replaceAll("\\","").split(" and ").map(e=>e.split(", ").reverse().join(" ")).join(" and "),logTrace=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={bibtexToObject:bibtexToObject,bibtexToString:bibtexToString,extractBibtexValue:extractBibtexValue,extractAuthor:extractAuthor}),"undefined"!=typeof LOGTRACE&&LOGTRACE),log=(...e)=>{if(logTrace){const n=(new Error).stack;e.push("\n\nLog trace:\n"+n.split("\n").slice(2).join("\n"))}let t="%c%s ",a=!1,r=!1,i=!1,o=!1,s=!1;"[info]"===e[0]?(a=!0,e=e.slice(1)):"[warn]"===e[0]?(r=!0,e=e.slice(1)):"[error]"===e[0]?(i=!0,e=e.slice(1)):"[ok]"===e[0]?(s=!0,e=e.slice(1)):"[debug]"===e[0]&&(o=!0,e=e.slice(1)),e.forEach(e=>{switch(typeof e){case"bigint":case"number":t+="%d ";break;case"string":t+="%s ";break;default:t+="%o "}}),console.log(t,"color: "+(a?"#8BB4F7; font-weight:bold;":r?"#f3bd1e; font-weight:bold;":i?"#FF4F54; font-weight:bold;":s?"#23F62B; font-weight:bold;":o?"#BA357E; font-weight:bold;":"tan"),"[PM]",...e)},info=(...e)=>log("[info]",...e),warn=(...e)=>log("[warn]",...e),debug=(...e)=>log("[debug]",...e),logOk=(...e)=>log("[ok]",...e),logError=(...e)=>log("[error]",...e),getDisplayId=e=>{var t=e;if((e=e.split("_")[0].split(".")[0]).startsWith("OR-")||(e=e.split("-").slice(0,2).join("-")),global.state.papers.hasOwnProperty(t)){const a=global.state.papers[t];if("nature"===a.source){if(a.note.match(/^Published\ @.+\(\d+\)$/)){const r=a.note.split("@")[1].split("(")[0].trim();e+="-"+r.split(" ").map(e=>e[0].toUpperCase()).join("")}e+="-"+a.year}"acs"===a.source&&(e+="-"+a.year),"iop"===a.source&&(e+="-"+a.year)}return e},isObject=e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,isPdfUrl=e=>e.endsWith(".pdf")||e.endsWith("/pdf")||e.includes("openreview.net/pdf")||e.match(/\/e?pdf\//g)||e.includes("ieee.org/stamp/stamp.jsp?tp=&arnumber="),delay=(t,a)=>{let r=0;return(...e)=>{clearTimeout(r),r=setTimeout(t.bind(this,...e),a||0)}},cleanPapers=e=>{let t={...e};return delete t.__dataVersion,t},firstNonStopLowercase=e=>{let t=e.toLowerCase(),a=t.split(" ").map(miniHash);e=a.filter(e=>!global.englishStopWords.has(e));return(0e.toLowerCase().replace(/\W/g,""),fallbackCopyTextToClipboard=e=>{var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{var a=document.execCommand("copy")?"successful":"unsuccessful";log("Fallback: Copying text command was "+a)}catch(e){console.error("Fallback: Oops, unable to copy",e)}document.body.removeChild(t)},copyTextToClipboard=e=>{navigator.clipboard?navigator.clipboard.writeText(e).then(()=>{log("Async: Copying to clipboard was successful!")},e=>{console.error("Async: Could not copy text: ",e)}):fallbackCopyTextToClipboard(e)},parseUrl=e=>{var t=document.createElement("a");return t.href=e,t},downloadTextFile=(e,t,a)=>{var r=document.createElement("a");"text/plain"===a?(e=e.replace(/\\n/g,"%0D%0A").replace(/"/g,""),r.download=t,r.href="data:text/plain,"+e):(e=new Blob([e],{type:a}),r.href=URL.createObjectURL(e),r.download=t),r.click()},eventId=e=>e.target.closest(".memory-container").id.split("--")[1],downloadFile=(e,t)=>{var a;window.ActiveXObject?window.ActiveXObject&&document.execCommand&&((a=window.open(e,"_blank")).document.close(),a.document.execCommand("SaveAs",!0,t||e),a.close()):((a=document.createElement("a")).href=e,a.target="_blank",e=e.substring(e.lastIndexOf("/")+1),a.download=t||e,navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/)&&navigator.userAgent.search("Chrome")<0?document.location=a.href:(t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1}),a.dispatchEvent(t),(window.URL||window.webkitURL).revokeObjectURL(a.href)))},hashCode=e=>e.split("").reduce((e,t)=>(e=(e<<5)-e+t.charCodeAt(0))&e,0),parseCVFUrl=e=>{const t=e.replace("https://openaccess.thecvf.com/content","").slice(1).split("/")[0].split("_");let a,r;r=1===t.length?(a=t[0].slice(0,-4),t[0].slice(-4)):(a=t[0].toUpperCase(),t[1]);e=e.split("/").last().split(".")[0],e=(hashCode(e)+"").replace("-","").slice(0,8),e=`${a}-${r}_`+e;return{conf:a,year:r,id:e}},cleanBiorxivURL=e=>e=(e=e.replace(".full.pdf","")).match(/\d$/)?e:e.split(".").slice(0,-1).join("."),textareaFocusEnd=e=>{setTimeout(()=>{e.selectionStart=e.selectionEnd=1e4},0)},tablerSvg=(e,t,a)=>{switch(t=(t=void 0===t?"":t)&&`id="${t}"`,a=(a=(a=void 0===a?[]:a).filter(e=>e))&&`class="${a.join(" ")}"`,e){case"adjustments":return``;case"circle-x":return``;case"star":return``;case"writing":return``;case"file-symlink":return``;case"link":return``;case"clipboard-list":return``;case"archive":return``;case"external-link":return``;case"file-download":return``;case"cirlce-x":return``;case"settings":return``;case"messages":return``;case"vocabulary":return``;case"database-export":return``;case"eyeglass":return``;case"markdown":return``;case"math-function":return``;default:return""}},stringifyError=e=>{const t=chrome.runtime.id;return e.stack.split("\n").map(e=>e.split(" ").map(e=>e.split(t).last()).join(" ")).join("
")},arraysIdentical=(e,t)=>{var a=e.length;if(a!=t.length)return!1;for(;a--;)if(e[a]!==t[a])return!1;return!0},parseTags=e=>{let t=Array.from(e.selectedOptions,e=>e.value.trim()).filter(e=>e);return t.sort(),t},getPaperEdits=(e,t)=>{let a,r,i,o;return o=t?(a=val("popup-form-note-textarea--"+e),i=val(document.getElementById("popup-form-note--"+e).querySelector(".form-code-input")),r=parseTags(findEl("popup-item-tags--"+e)),findEl("checkFavorite--"+e).checked):(a=val(findEl(e,"form-note-textarea")),i=val(findEl(e,"form-code-input")),r=parseTags(findEl(e,"memory-item-tags")),hasClass("memory-container--"+e,"favorite")),{note:a,tags:r,codeLink:i,favorite:o}},setFormChangeListener=(e,t)=>{let a,r,i,o;t?(a="#popup-item-tags--"+e.replace(".","\\."),i="popup-form-codeLink--"+e,r="popup-form-note-textarea--"+e,o="checkFavorite--"+e,$(a).on("change",delay(monitorPaperEdits(e,t),300)),addListener(i,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(r,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(o,"change",delay(monitorPaperEdits(e,t),300))):(a=".memory-item-tags",i=".form-code-input",r=".form-note-textarea",addEventToClass(i,"keyup",delay(monitorPaperEdits(void 0,t),300)),addEventToClass(r,"keyup",delay(monitorPaperEdits(void 0,t),300)))},monitorPaperEdits=(p,c)=>e=>{let t;t=void 0===p?eventId(e):p;var a=getPaperEdits(t,c),r=global.state.papers[t];let i=!1,o={};for(const l in a){var s=r[l],n=(o[l]=s,a[l]);"tags"===l?arraysIdentical(s,n)||(i=!0):s!==n&&(i=!0)}i&&(console.log("Updating meta data for",t),(c?handlePopupSaveEdits:handleMemorySaveEdits)(t))},cutAuthors=(e,t,a)=>{void 0===t&&(t=140),void 0===a&&(a=", ");let r="";var e=e.split(" and "),i=e[e.length-1];for(const o of e){if(!(5+r.length+a.length+o.length+i.lengthnew Promise(t=>{chrome.runtime.sendMessage(e,e=>{t(e)})}),getStoredFiles=()=>new Promise(t=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},e=>t(e.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt"))))}),noParamUrl=e=>e.split("?")[0].split("#")[0],silentPromiseTimeout=(e,a=5e3)=>{let r;return Promise.race([e,new Promise((e,t)=>r=setTimeout(e,a))]).finally(()=>clearTimeout(r))},shouldWarn=async(e,t=()=>{})=>{if("pdf-title"===e){var a=await getStorage("titleFunctionCode");if(a&&a!==global.defaultTitleFunctionCode)if(!(await getStorage("userWarnings")??{})[e])return t(!0)}return t(!1)},migrateData=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={log:log,info:info,logError:logError,logOk:logOk,debug:debug,warn:warn,getDisplayId:getDisplayId,isObject:isObject,isPdfUrl:isPdfUrl,delay:delay,cleanPapers:cleanPapers,firstNonStopLowercase:firstNonStopLowercase,fallbackCopyTextToClipboard:fallbackCopyTextToClipboard,copyTextToClipboard:copyTextToClipboard,parseUrl:parseUrl,downloadTextFile:downloadTextFile,eventId:eventId,downloadFile:downloadFile,hashCode:hashCode,parseCVFUrl:parseCVFUrl,cleanBiorxivURL:cleanBiorxivURL,textareaFocusEnd:textareaFocusEnd,tablerSvg:tablerSvg,stringifyError:stringifyError,arraysIdentical:arraysIdentical,parseTags:parseTags,getPaperEdits:getPaperEdits,setFormChangeListener:setFormChangeListener,monitorPaperEdits:monitorPaperEdits,cutAuthors:cutAuthors,sendMessageToBackground:sendMessageToBackground,getStoredFiles:getStoredFiles,miniHash:miniHash,noParamUrl:noParamUrl,silentPromiseTimeout:silentPromiseTimeout,shouldWarn:shouldWarn}),async(a,t,e=!0)=>{if(void 0===a)return chrome.storage.local.set({papers:{__dataVersion:t}}),{papers:{__dataVersion:t},success:!0};var r,i,o,s=a.__dataVersion||-1,n=[];let l={...a};try{if(502<=s)return{papers:a,success:!0};e&&backupData({...a}),delete a.__dataVersion;for(const p in a)s<5&&(info("Applying migration 5"),a[p].hasOwnProperty("bibtex")||(a[p].bibtex="",log("Migrating bibtex for "+p)),a[p].pdfLink.endsWith(".pdf")||(a[p].pdfLink=a[p].pdfLink+".pdf"),a[p].codeLink||(a[p].codeLink=""),a[p].source||(a[p].id.includes("NeurIPS")?a[p].source="neurips":a[p].source="arxiv")),s<208&&(info("Applying migration 0.2.8"),"arxiv"!==a[p].source&&a[p].md.includes("https://arxiv.com/abs/")&&(a[p].md=`[${a[p].title}](${a[p].pdfLink})`),"arxiv"!==a[p].source&&a[p].pdfLink.includes("arxiv.org/pdf/")&&(a[p].source="arxiv"),p.match(/^\d/)&&"arxiv"===a[p].source&&(r="Arxiv-"+p,i={...a[p],id:r},a[r]=i,n.push(p))),s<209&&(info("Applying migration 0.2.9"),a[p].hasOwnProperty("favorite")||(a[p].favorite=!1,a[p].favoriteDate="")),s<210&&(info("Applying migration 0.2.10"),"arxiv"===a[p].source&&(o=a[p].pdfLink.match(/v\d+\.pdf/gi))&&0{delete a[e],log("Deleting "+e)}),(l={...a}).__dataVersion=t,e&&chrome.storage.local.set({papers:l},()=>{log("Migrated papers:"),log(l),log("Data version is now "+t)}),{papers:l,success:!0}}catch(e){return log(`Error migrating data from version ${s} to ${t}:`),log(e),{papers:l,success:!1,error:e}}}),logStorage=t=>{chrome.storage.local.get(t,e=>{log(e[t])})},getStorage=async a=>new Promise((t,e)=>{chrome.storage.local.get(a,e=>{t("string"==typeof a?e[a]:e)})}),setStorage=async(a,r,i=()=>{})=>new Promise((e,t)=>{chrome.storage.local.set({[a]:r},()=>{i(),e(!0)})}),deletePaperInStorage=async(e,t)=>{let a=!1;(t=t||(await getStorage("papers")??{})).hasOwnProperty(e)&&(updateDuplicatedUrls(null,e,!0),a=(a=delete global.state.titleHashToIds[miniHash(t[e].title)])&&delete t[e]),a?(setStorage("papers",t),log("Successfully deleted paper",e)):log("Error: no deletion")},getTheme=async()=>{return await getStorage("checkDarkMode")?"dark":"light"},backupData=async a=>{chrome.storage.local.get("papersBackup",({papersBackup:e})=>{void 0===e&&(e={});for(const t of Object.keys(e).map(e=>parseInt(e)).sort((e,t)=>e{log("Backed up data with version: "+a.__dataVersion)})})};function dateDiffInDays(e,t){e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),t=Date.UTC(t.getFullYear(),t.getMonth(),t.getDate());return Math.floor((t-e)/864e5)}const weeklyBackup=async()=>{var e=await getStorage("weeklyBackups")??{};const t=new Date,a=Object.keys(e).map(e=>new Date(e)).sort((e,t)=>e.getTime()-t.getTime());if(0{let e=!1,t;const a=await getStorage("prefs")??{};(e=0===Object.keys(a).length?!0:e)&&(t=await getStorage(global.prefsStorageKeys)??{});let r={};for(const i of global.prefsCheckNames)r[i]=(t??a).hasOwnProperty(i)?(t??a)[i]:!(0<=global.prefsCheckDefaultFalse.indexOf(i));return r.checkOfficialRepos&&(setStorage("pwcPrefs",{official:!0}),delete r.checkOfficialRepos,setStorage("prefs",r)),e&&setStorage("prefs",r),r},getManifestDataVersion=()=>{const e=chrome.runtime.getManifest();return e.version.split(".").map((e,t)=>parseInt(e)*10**(4-2*t)).reduce((e,t)=>e+t)},versionToSemantic=e=>(e=(e-=1e4*(major=parseInt(e/1e4,10)))-100*(minor=parseInt(e/100,10)),`${major}.${minor}.`+e),validatePaper=(e,t=!0)=>{const a={addDate:{type:"string",desc:"the paper's date of addition to the Memory",default:e=>(new Date).toJSON()},author:{type:"string",desc:"` and `-separated authors `${firstName} ${lastName}`"},bibtex:{type:"string",desc:"BibTex citation with new lines (`\n`)"},code:{type:"object",desc:"the paper's code object as returned by the PapersWithCode API",default:e=>({})},codeLink:{type:"string",desc:"the paper's code link",default:e=>""},count:{type:"number",desc:"the paper's number of visits",default:e=>1},extras:{type:"object",desc:"extra information about the paper which may be required per source",optional:!0},favorite:{type:"boolean",desc:"user wants to star the paper",default:e=>!1},favoriteDate:{type:"string",desc:"date the paper was added as a favorite",default:e=>""},id:{type:"string",desc:"Unique PaperMemory ID"},key:{type:"string",desc:"BibTex citation key",default:e=>"defaultKey_"+e.id},lastOpenDate:{type:"string",desc:"When the paper was last opened",default:e=>(new Date).toJSON()},md:{type:"string",desc:"markdown-formatted string `[${title}](${pdfLink})`",default:e=>`[${e.title}](${e.pdfLink})`},note:{type:"string",desc:"the user's note for this paper",default:e=>""},pdfLink:{type:"string",desc:"the link to the paper's pdf"},source:{type:"string",desc:"the paper's source i.e. where it was added to the memory from"},tags:{type:"array[string]",desc:"the user's tags for this paper",default:e=>[]},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication"}};let r=[];for(const l in a)if(e.hasOwnProperty(l)){const p=a[l].type;var i,o=typeof e[l];p.includes("array")||"object"===p?p.includes("array")?Array.isArray(e[l])?(s=p.split("[")[1].replace("]",""),0{let t=!0,a="",r="",i;try{e.__dataVersion||(e.__dataVersion=1);var o,s=await migrateData(e,getManifestDataVersion(),!1);if(!s.success)return r="Could not migrate the data before storing it",s.error&&(r+=":
"+stringifyError(s.error)),{success:!1,message:r};for(const n in i=s.papers)n.startsWith("__")||(paperWarnings=validatePaper(i[n]).warnings)&&0"+paperWarnings.join("
"));a&&(o=await getStorage("papers")??{},setStorage("uploadBackup",o)),t=!1}catch(e){log("prepareOverwriteData error",e),r='
/!\\ OverwriteMemoryError:

'+stringifyError(e),t=!0}return{success:!t,message:r,warning:a,papersToWrite:i}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let a={};if(!e)return a;for(const i in global.knownPaperPages){var r=global.knownPaperPages[i];a[i]=!1;for(const o of r)"string"==typeof o?e.includes(o)&&(a[i]=!0):"function"==typeof o&&(a[i]=o(e))}return a.localFile=isKnownLocalFile(e),a.stored=!t&&await findLocalFile(e),a}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,a,r;const i=e.pdfLink;let o="";switch(e.source){case"arxiv":o="https://arxiv.org/abs/"+e.id.split("-")[1];break;case"neurips":o=i.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":o=i.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":o=i.replace("/pdf?","/forum?");break;case"biorxiv":o=i.replace(".full.pdf","");break;case"pmlr":o=i.split("/").slice(0,-1).join("/")+".html";break;case"acl":o=i.replace(".pdf","");break;case"pnas":o=i.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":o=i.replace(".pdf","");break;case"acs":o=i.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":o=i.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":o=i.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var s=i.match(/PMC\d+/)[0];o=i.split(s)[0]+s;break;case"ijcai":var s=i.replace(".pdf","").split("/").last().match(/[1-9]\d*/),n=i.match(/proceedings\/\d+/gi)[0].split("/")[1];o=`https://www.ijcai.org/proceedings/${n}/`+s;break;case"acm":o=i.replace("/doi/pdf/","/doi/");break;case"ieee":o="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":o=e.extra.url;break;case"aps":[t,a]=parseUrl(i).pathname.split("/").slice(1,3),o=i.replace(`/${t}/${a}/`,`/${t}/abstract/`);break;case"wiley":o=i.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":n=i.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];o="https://www.sciencedirect.com/science/article/pii/"+n;break;case"science":(r=i.split("/doi/")[1]).startsWith("10.")||(r=r.split("/").slice(1).join("/")),o="https://science.org/doi/full/"+r;break;case"frontiers":o=i.replace(/\/pdf$/,"/full");break;default:o="https://xkcd.com/1969/"}return o.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var a=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),r=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let i={};for(const s of t){let t;try{(t=await parseIdFromUrl(s.finalUrl))&&e.hasOwnProperty(t)&&(i[t]=s)}catch(e){t=null}if(!t){const n=r[s.id];var o=Object.entries(a).find(([,e])=>n.includes(e));o&&(i[o[0]]=s)}}return i},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:a,...r}=e;let i={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,...r};for(const o in a)(!t.hasOwnProperty(o)||a[o]&&!t[o])&&(i[o]=a[o]);e.incrementCount&&1===i.count&&(i.count+=1);for(const s of e.overwrites)a.hasOwnProperty(s)&&(i[s]=a[s]);return i},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async(t,e,i,o=!0,s={update:()=>{},preprints:()=>{}})=>{const n=Date.now();let l,p,c={};console.group("%cPaperMemory parsing 📕",global.consolHeaderStyle),global.state.papers=await getStorage("papers")??{};var a=await parseIdFromUrl(t),r=global.state.papers.hasOwnProperty(a);if(a&&r)l=updatePaperVisits(global.state.papers[a]),p=!1;else{if(!(l=await makePaper(e,t)))return;r=findFuzzyPaperMatch(global.state.titleHashToIds,l);if(r&&o){let e=global.state.papers[r];log("New paper",l,"already exists as",e),addPaperToTitleHashToId(l),!l.venue&&e.venue||l.venue&&e.venue?(e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate"]}),updateDuplicatedUrls(t,r)):!e.venue&&l.venue&&(await updateDuplicatedUrls(paperToAbs(e),l.id),await updateDuplicatedUrls(paperToPDF(e),l.id),await deletePaperInStorage(e.id,global.state.papers),e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year"]})),l=updatePaperVisits(e),p=!1}else p=!0}if(!l.codeLink||!l.venue)try{const m=await tryPWCMatch(l);var d=!l.codeLink&&m?.url,u=m?.note,h=m?.bibtex,f=!l.venue&&m?.venue;(c={codeLink:d,note:u,venue:f,bibtex:h}).codeLink&&(l.codeLink=c.codeLink,m.hasOwnProperty("note")&&delete m.note,l.code=m)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},p&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),p=!1),o&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{s.update(l);let e;if(p||c.codeLink?p?(o?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it."),log("paper: ",l),e="Added to your Memory",c.codeLink&&(e+="
(+ repo from PapersWithCode)
"),i&&i.checkFeedback&&o&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",i&&i.checkFeedback&&o&&feedback(e)):o&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue){var t,a=await tryPreprintMatch(l);for(const r of["note","venue","bibtex"])l[r]&&"bibtex"!==r||(t=a[r]??c[r])&&(log(`Updating preprint ${r} to`,t),l[r]=t);global.state.papers=await getStorage("papers")??{},p&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e.id.includes(a))?.id,parseIdFromUrl=async t=>{let a;var e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),r=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var i=t.match(/\d{4}\.\d{4,5}/g)[0];a="Arxiv-"+i;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(a));s&&(a=s.find(e=>!e.startsWith("Arxiv-"))??a)}else if(e.neurips){var i=t.split("/paper/")[1].split("/")[0],o=t.split("/").last().split("-")[0].slice(0,8);a=`NeurIPS-${i}_`+o}else if(e.cvf)a=parseCVFUrl(t).id;else if(e.openreview){i=t.match(/id=\w+/)[0].replace("id=","");a=findPaperId(r,"openreview",i)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),a="Biorxiv-"+e;const n=Object.values(global.state.titleHashToIds).find(e=>e.includes(a));n&&(a=n.find(e=>!e.startsWith("Biorxiv-"))??a)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];o="20"+l.match(/\d+/)[0];a=`PMLR-${o}-`+l}else if(e.acl){i=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();a=findPaperId(r,"acl",i)}else if(e.pnas){o=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];a=findPaperId(r,"pnas",o)}else if(e.nature){i=(t=t.replace(".pdf","").split("#")[0]).split("/").last();a=findPaperId(r,"nature",i)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);a="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1]);a="IOPscience_"+doi}else if(e.jmlr){const p=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();o="20"+p.match(/\d+/)[0];a=`JMLR-${o}_`+p}else if(e.pmc){i=t.match(/PMC\d+/g)[0].replace("PMC","");a=findPaperId(r,"pmc",i)}else if(e.ijcai){o=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),i=t.match(/proceedings\/\d+/gi)[0].split("/")[1];a=`IJCAI-${i}_`+o}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];a=findPaperId(r,"acm",miniHash(doi))}else if(e.ieee){i=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];a=findPaperId(r,"ieee",i)}else if(e.springer){const c=global.sourceExtras.springer.types;let e=c.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}o=t.split(`/${e}/`)[1].split("?")[0].replace(".pdf","");a=findPaperId(r,"springer",miniHash(o))}else if(e.aps){var[i,o]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${i}/${o}/`).last();a=findPaperId(r,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");a=findPaperId(r,"wiley",miniHash(doi))}else if(e.sciencedirect){i=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];a=findPaperId(r,"sciencedirect",miniHash(i))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),a=findPaperId(r,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),a=findPaperId(r,"frontiers",miniHash(doi));else{if(!e.localFile)throw new Error("unknown paper url");a=e.localFile}return a},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var a=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>r.includes(e.title));return 0!==a.length&&a[0].id},makeMdLink=(e,t={})=>{var a=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let r="",i=(!t.checkMdYearVenue||(r=(r=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&r[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(r="",e.venue&&(r+=e.venue+" "),r+=e.year),e.title);return`[${i=r?`${i} (${r.replace(/\s+/g," ")})`:i}](${a})`},initState=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),async(e,t)=>{const a=[];a.unshift(Date.now()),console.groupCollapsed("%cPaperMemory Init ✅",global.consolHeaderStyle),void 0===e&&(e=await getStorage("papers")??{},log("Time to retrieve stored papers (s): "+(Date.now()-a[0])/1e3)),a.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),log("Time to parse data version (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),global.state.titleFunction=(await getTitleFunction()).titleFunction,log("Time to make title function (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),weeklyBackup(),log("Time to backup papers (weekly) (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now());var r,i,o=await migrateData(e,global.state.dataVersion);log("Time to migrate data (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),e=o.papers,global.state.papers=e,global.state.prefs=await getPrefs(),log("Time to retrieve user preferences (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},log("Time to retrieve sources to ignore (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},log("Time to retrieve sources to urlHashToId (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),global.state.titleHashToIds={};for([r,i]of Object.entries(cleanPapers(e))){var s=miniHash(i.title);global.state.titleHashToIds.hasOwnProperty(s)||(global.state.titleHashToIds[s]=[]),global.state.titleHashToIds[s].push(r)}log("Time to hash titles (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),log("Time to match all local files (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),log("Time to sort memory (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now()),makeTags(),log("Time to make tags (s): "+(Date.now()-a[0])/1e3),a.unshift(Date.now())),info("State init duration (s): "+(Date.now()-a.last())/1e3),console.groupEnd()}),sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers),global.state.papersList.sort(orderPapers)},orderPapers=(e,t)=>{let a=e[global.state.sortKey],r=t[global.state.sortKey];return void 0===a&&(a=""),void 0===r&&(r=""),"string"==typeof a&&(a=a.toLowerCase(),r=r.toLowerCase()),0<=global.descendingSortKeys.indexOf(global.state.sortKey)?a>r?-1:1:a>r?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const a of t.tags)e.add(a);global.state.paperTags=Array.from(e),global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},a=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let r=t[a[e=void 0===e?getRandomInt(a.length):e]];return r=void 0===r?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:r},getTitleFunction=async(code=null)=>{let titleFunction;code=code||await getStorage("titleFunctionCode"),void 0===code&&(code=global.defaultTitleFunctionCode);let errorMessage;try{titleFunction=eval(code)}catch(error){errorMessage="Error parsing the title function: "+error,log("Error parsing the title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}try{const examplePaper=await getExamplePaper(0),result=titleFunction(examplePaper);if("string"!=typeof result)throw new Error(`Result ${result} is not a string`)}catch(error){errorMessage="Error executing the title function: "+error,log("Error testing the user's title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}return{titleFunction:titleFunction,code:code.trim(),errorMessage:errorMessage}},stateTitleFunction=paperOrId=>{let paper=paperOrId;if("string"==typeof paperOrId&&(paper=global.state.papers[paperOrId],void 0===paper))return log("Error in stateTitleFunction: unknown id",paperOrId),"Unknown ID";let name;try{name=global.state.titleFunction(paper)}catch(error){log("Error in stateTitleFunction:",error),name=eval(global.defaultTitleFunctionCode)(paper)}return name.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,a,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===a))&&e.length){for(const r of e)warn("Removing duplicated url",t,"for",a),delete global.state.urlHashToId[r];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=a,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={initState:initState,getExamplePaper:getExamplePaper,getTitleFunction:getTitleFunction,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,a;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(a=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:r,year:i}=parseCVFUrl(e);t=t.replace(`/content_${r}_${i}/`,`/content_${r.toLowerCase()}_${i}/`),a=await fetch(t).then(e=>e.ok?e.text():"")}return a},fetchOpenReviewNoteJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?id="+e).then(e=>e.json())},fetchOpenReviewForumJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?forum="+e).then(e=>e.json())},fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),a=t.ok?await t.text():"";return a.trim()}catch(e){return console.log("fetchText error:",e),""}},fetchJSON=async e=>{try{const t=await fetch(e);return t.ok?await t.json():null}catch(e){return console.log("fetchJSON error:",e),null}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const s=e.message;log("Crossref data.message: ",s);var t=s.author.map(e=>e.given+" "+e.family).join(" and ");const n=s.issued?s.issued["date-parts"][0][0]+"":s.published?s.published["date-parts"][0][0]+"":null;if(n){var a=s.title[0];if(a){var r=s["container-title"][0]??"Springer",i=[miniHash(s.author[0].family),n.slice(2),firstNonStopLowercase(a)].join(""),o=s.DOI;let e={entryType:"book"===s.type?"book":"book-chapter"===s.type?"InBook":s.type.includes("article")?"Article":"InProceedings",citationKey:i,publisher:s.publisher,author:t,title:a,year:n,doi:o};s.page&&(e.pages=s.page),s.volume&&(e.volume=s.volume),s.type.includes("journal")&&(e.journal=r),s.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=i.URL),(t=s.link.find(e=>"text/html"===e["content-type"])??s.link[0])&&(e.url=t.URL));a=bibtexToString(e);return{...e,bibtex:a,venue:r}}error("Cannot find title in CrossRef data",s)}else error("Cannot find year in CrossRef data",s)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{e=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return extractCrossrefData(e)},fetchSemanticsScholarDataForDoi=async e=>{const t=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`);let a;var r;return t&&(a={},t.venue&&(a.venue=t.venue),t.year&&(a.year=t.year),t.authors&&(a.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(a.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(a.title),r=bibtexToString({entryType:"article",citationKey:e,...a}),a.bibtex=r,a.key=e),a},getMetaContent=(e,t,a=!1)=>{e="meta"+Object.entries(e).map(([e,t])=>`[${e}='${t}']`).join("");return a?queryAll(t,e).map(e=>e.getAttribute("content")??""):t.querySelector(e)?.getAttribute("content")??""},extractDataFromDCMetaTags=e=>{const t=getMetaContent({name:"dc.Creator"},e,!0).map(e=>e.replace(/([a-z])([A-Z])/g,"$1 $2")).join(" and ");if(!t)return null;var a=getMetaContent({name:"dc.Date"},e).split("-")[0],r=getMetaContent({name:"dc.Publisher"},e).replaceAll("\n"," "),i=getMetaContent({name:"dc.Title"},e),o=getMetaContent({name:"citation_journal_title"},e),s=(""+t.split(" and ")[1].split(" ")[0]+a+firstNonStopLowercase(i)).toLowerCase(),e=getMetaContent({name:"dc.Date",scheme:"doi"},e),n=bibtexToString({citationKey:s,entryType:"article",title:i,author:t,year:a,doi:e,publisher:r,journal:o});return{author:t,year:a,publisher:r,title:i,venue:o,key:s,doi:e,bibtex:n,note:`Published @ ${o} (${a})`}},makeArxivPaper=async e=>{e=e.match(/\/(\d{4}\.\d{4,5})/)[1];const t=await fetchArxivXML(e),a=await t.text();var r=(new DOMParser).parseFromString(a.replaceAll("\n",""),"text/xml");const i=queryAll(r,"author name").map(e=>e.innerHTML);var o=i.join(" and "),s=Array.from(r.getElementsByTagName("link")).map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),n=r.querySelector("entry title").innerHTML,r=r.querySelector("entry published").innerHTML.slice(0,4),l=i[0].split(" ").last().toLowerCase()+r+firstNonStopLowercase(n),e="Arxiv-"+e,p="";return{author:o,bibtex:p+`@article{${l}, -`+`title={${n} }, -`+`author={${o} }, -`+`year={${r}}, + /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle}),!function i(n,a,o){function s(t,e){if(!a[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=a[t]={exports:{}},n[t][0].call(r.exports,function(e){return s(n[t][1][e]||e)},r,r.exports,i,n,a,o)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;ee.length)&&(r=e.length),r-=t.length,-1!==(e=e.indexOf(t,r))&&e===r},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var r=new Array(t);0>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===i&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,a[o++]=255&t),1===i&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],a=0,o=r-i;a>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(i));return n.join("")}(e,a,o>2]+s[t<<4&63]+"==")):2==i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,a=i.length;n>>1;case"base64":return k(e).length;default:if(n)return i?-1:P(e).length;t=(""+t).toLowerCase(),n=!0}}function t(e,t,r){var i,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var a=this,o=t,s=r,l=a.length;(!s||s<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:f(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):f(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,i,n){var a=1,o=e.length,s=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o/=a=2,s/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n)for(var c=-1,p=r;p>8,i=i%256,n.push(i),n.push(r);return n}(t,e.length-r),e,r,i)}function A(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n>>10&1023|55296),p=56320|1023&p),i.push(p),n+=u}var d=i,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var h="",g=0;gt&&(e+=" ... "),""},u.prototype.compare=function(e,t,r,i,n){if(C(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),l=this.slice(i,n),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i=i||"utf8";for(var a,o,s,l=!1;;)switch(i){case"hex":var c=this,p=e,u=t,d=r,f=(u=Number(u)||0,c.length-u);(!d||(d=Number(d))>f)&&(d=f),(f=p.length)/2e.length)throw new RangeError("Index out of range")}function b(e,t,r,i){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function v(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,4),a.write(e,t,r,i,23,4),r+4}function w(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,8),a.write(e,t,r,i,52,8),r+8}u.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||h(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=t,n=1,a=this[e+--i];0=(n*=128)&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||h(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,i){e=+e,t>>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[t+n]=255&e;0<=--n&&(a*=256);)this[t+n]=e/a&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeIntLE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=0,a=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=r-1,a=1,o=0;for(this[t+n]=255&e;0<=--n&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a>>0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return w(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return w(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,i){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,i||0===i||(i=this.length),t>=e.length&&(t=e.length),(i=0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length);var n=(i=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(a=t;a>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(x,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function E(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}}.call(this)}.call(this,O("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,n){var a,o,s=8*n-i-1,l=(1<>1,p=-7,u=r?n-1:0,d=r?-1:1,n=e[t+u];for(u+=d,a=n&(1<<-p)-1,n>>=-p,p+=s;0>=-p,p+=i;0>1,u=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,f=i?1:-1,a=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,n),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),o=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield n.default.post(e,t,(0,a.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:n}=this,a="https://gist.githubusercontent.com/"+i+`/${n}/raw/${e}/`+this.fileName;return t?null!=r?r(a):o.default.corsAnywhere+a:a},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),a=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>n(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,a.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>n(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>n(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>n(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},n=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),a=n.data;yield this.initialize(a)}),this.initialize=i=>n(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=a.default.githubRateLimit;return n.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]);const levenshtein=(e,t)=>{if(e===t)return 0;e.length>t.length&&(r=e,e=t,t=r);for(var r,i=e.length,n=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,r=(this.match("{",!1),this.pos),i=!1;;){if(!i)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");i="\\"==this.input[this.pos]&&0==i,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,r=!1;;){if(!r){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, +`;delete e.entryType,delete e.citationKey;var r,i=Math.max(...Object.keys(e).map(e=>e.length));for(const n in e)e.hasOwnProperty(n)&&e[n]&&(r=e[n].replaceAll(/\s+/g," ").trim(),bkey=n+" ".repeat(i-n.length),t+=` ${bkey} = {${r}}, +`);return(t.slice(0,-2)+"\n}").replaceAll("\t"," ").replaceAll("--","-")},extractBibtexValue=(e,t)=>{const r=bibtexToObject(e);return r.hasOwnProperty(t)?r[t]:""},extractAuthor=e=>extractBibtexValue(e,"author").replaceAll("{","").replaceAll("}","").replaceAll("\\","").split(" and ").map(e=>e.split(", ").reverse().join(" ")).join(" and "),logTrace=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={bibtexToObject:bibtexToObject,bibtexToString:bibtexToString,extractBibtexValue:extractBibtexValue,extractAuthor:extractAuthor}),"undefined"!=typeof LOGTRACE&&LOGTRACE),log=(...e)=>{if(logTrace){const s=(new Error).stack;e.push("\n\nLog trace:\n"+s.split("\n").slice(2).join("\n"))}let t="%c%s ",r=!1,i=!1,n=!1,a=!1,o=!1;"[info]"===e[0]?(r=!0,e=e.slice(1)):"[warn]"===e[0]?(i=!0,e=e.slice(1)):"[error]"===e[0]?(n=!0,e=e.slice(1)):"[ok]"===e[0]?(o=!0,e=e.slice(1)):"[debug]"===e[0]&&(a=!0,e=e.slice(1)),e.forEach(e=>{switch(typeof e){case"bigint":case"number":t+="%d ";break;case"string":t+="%s ";break;default:t+="%o "}}),console.log(t,"color: "+(r?"#8BB4F7; font-weight:bold;":i?"#f3bd1e; font-weight:bold;":n?"#FF4F54; font-weight:bold;":o?"#23F62B; font-weight:bold;":a?"#BA357E; font-weight:bold;":"tan"),"[PM]",...e)},info=(...e)=>log("[info]",...e),warn=(...e)=>log("[warn]",...e),debug=(...e)=>log("[debug]",...e),logOk=(...e)=>log("[ok]",...e),logError=(...e)=>log("[error]",...e),getDisplayId=e=>{var t=e;if((e=e.split("_")[0].split(".")[0]).startsWith("OR-")||(e=e.split("-").slice(0,2).join("-")),global.state.papers.hasOwnProperty(t)){const r=global.state.papers[t];if("nature"===r.source){if(r.note.match(/^Published\ @.+\(\d+\)$/)){const i=r.note.split("@")[1].split("(")[0].trim();e+="-"+i.split(" ").map(e=>e[0].toUpperCase()).join("")}e+="-"+r.year}"acs"===r.source&&(e+="-"+r.year),"iop"===r.source&&(e+="-"+r.year)}return e},isObject=e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,isPdfUrl=e=>e.endsWith(".pdf")||e.endsWith("/pdf")||e.includes("openreview.net/pdf")||e.match(/\/e?pdf\//g)||e.includes("ieee.org/stamp/stamp.jsp?tp=&arnumber="),delay=(t,r)=>{let i=0;return(...e)=>{clearTimeout(i),i=setTimeout(t.bind(this,...e),r||0)}},cleanPapers=e=>{let t={...e};return delete t.__dataVersion,t},firstNonStopLowercase=e=>{let t=e.toLowerCase(),r=t.split(" ").map(miniHash);e=r.filter(e=>!global.englishStopWords.has(e));return(0e.toLowerCase().replace(/\W/g,""),fallbackCopyTextToClipboard=e=>{var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{var r=document.execCommand("copy")?"successful":"unsuccessful";log("Fallback: Copying text command was "+r)}catch(e){console.error("Fallback: Oops, unable to copy",e)}document.body.removeChild(t)},copyTextToClipboard=e=>{navigator.clipboard?navigator.clipboard.writeText(e).then(()=>{log("Async: Copying to clipboard was successful!")},e=>{console.error("Async: Could not copy text: ",e)}):fallbackCopyTextToClipboard(e)},parseUrl=e=>{var t=document.createElement("a");return t.href=e,t},downloadTextFile=(e,t,r)=>{var i=document.createElement("a");"text/plain"===r?(e=e.replace(/\\n/g,"%0D%0A").replace(/"/g,""),i.download=t,i.href="data:text/plain,"+e):(e=new Blob([e],{type:r}),i.href=URL.createObjectURL(e),i.download=t),i.click()},eventId=e=>e.target.closest(".memory-container").id.split("--")[1],downloadFile=(e,t)=>{var r;window.ActiveXObject?window.ActiveXObject&&document.execCommand&&((r=window.open(e,"_blank")).document.close(),r.document.execCommand("SaveAs",!0,t||e),r.close()):((r=document.createElement("a")).href=e,r.target="_blank",e=e.substring(e.lastIndexOf("/")+1),r.download=t||e,navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/)&&navigator.userAgent.search("Chrome")<0?document.location=r.href:(t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1}),r.dispatchEvent(t),(window.URL||window.webkitURL).revokeObjectURL(r.href)))},hashCode=e=>e.split("").reduce((e,t)=>(e=(e<<5)-e+t.charCodeAt(0))&e,0),parseCVFUrl=e=>{const t=e.replace("https://openaccess.thecvf.com/content","").slice(1).split("/")[0].split("_");let r,i;i=1===t.length?(r=t[0].slice(0,-4),t[0].slice(-4)):(r=t[0].toUpperCase(),t[1]);e=e.split("/").last().split(".")[0],e=(hashCode(e)+"").replace("-","").slice(0,8),e=`${r}-${i}_`+e;return{conf:r,year:i,id:e}},cleanBiorxivURL=e=>e=(e=e.replace(".full.pdf","")).match(/\d$/)?e:e.split(".").slice(0,-1).join("."),textareaFocusEnd=e=>{setTimeout(()=>{e.selectionStart=e.selectionEnd=1e4},0)},tablerSvg=(e,t,r)=>{switch(t=(t=void 0===t?"":t)&&`id="${t}"`,r=(r=(r=void 0===r?[]:r).filter(e=>e))&&`class="${r.join(" ")}"`,e){case"adjustments":return``;case"circle-x":return``;case"star":return``;case"writing":return``;case"file-symlink":return``;case"link":return``;case"clipboard-list":return``;case"archive":return``;case"external-link":return``;case"file-download":return``;case"cirlce-x":return``;case"settings":return``;case"messages":return``;case"vocabulary":return``;case"database-export":return``;case"eyeglass":return``;case"markdown":return``;case"math-function":return``;default:return""}},stringifyError=e=>{const t=chrome.runtime.id;return e.stack.split("\n").map(e=>e.split(" ").map(e=>e.split(t).last()).join(" ")).join("
")},arraysIdentical=(e,t)=>{var r=e.length;if(r!=t.length)return!1;for(;r--;)if(e[r]!==t[r])return!1;return!0},parseTags=e=>{let t=Array.from(e.selectedOptions,e=>e.value.trim()).filter(e=>e);return t.sort(),t},getPaperEdits=(e,t)=>{let r,i,n,a;return a=t?(r=val("popup-form-note-textarea--"+e),n=val(document.getElementById("popup-form-note--"+e).querySelector(".form-code-input")),i=parseTags(findEl("popup-item-tags--"+e)),findEl("checkFavorite--"+e).checked):(r=val(findEl(e,"form-note-textarea")),n=val(findEl(e,"form-code-input")),i=parseTags(findEl(e,"memory-item-tags")),hasClass("memory-container--"+e,"favorite")),{note:r,tags:i,codeLink:n,favorite:a}},setFormChangeListener=(e,t)=>{let r,i,n,a;t?(r="#popup-item-tags--"+e.replace(".","\\."),n="popup-form-codeLink--"+e,i="popup-form-note-textarea--"+e,a="checkFavorite--"+e,$(r).on("change",delay(monitorPaperEdits(e,t),300)),addListener(n,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(i,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(a,"change",delay(monitorPaperEdits(e,t),300))):(r=".memory-item-tags",n=".form-code-input",i=".form-note-textarea",addEventToClass(n,"keyup",delay(monitorPaperEdits(void 0,t),300)),addEventToClass(i,"keyup",delay(monitorPaperEdits(void 0,t),300)))},monitorPaperEdits=(c,p)=>e=>{let t;t=void 0===c?eventId(e):c;var r=getPaperEdits(t,p),i=global.state.papers[t];let n=!1,a={};for(const l in r){var o=i[l],s=(a[l]=o,r[l]);"tags"===l?arraysIdentical(o,s)||(n=!0):o!==s&&(n=!0)}n&&(console.log("Updating meta data for",t),(p?handlePopupSaveEdits:handleMemorySaveEdits)(t))},cutAuthors=(e,t,r)=>{void 0===t&&(t=140),void 0===r&&(r=", ");let i="";var e=e.split(" and "),n=e[e.length-1];for(const a of e){if(!(5+i.length+r.length+a.length+n.lengthnew Promise(t=>{chrome.runtime.sendMessage(e,e=>{t(e)})}),getStoredFiles=()=>new Promise(t=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},e=>t(e.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt"))))}),noParamUrl=e=>e.split("?")[0].split("#")[0],silentPromiseTimeout=(e,r=5e3)=>{let i;return Promise.race([e,new Promise((e,t)=>i=setTimeout(e,r))]).finally(()=>clearTimeout(i))},shouldWarn=async(e,t=()=>{})=>{if("pdf-title"===e){var r=await getStorage("titleFunctionCode");if(r&&r!==global.defaultTitleFunctionCode)if(!(await getStorage("userWarnings")??{})[e])return t(!0)}return t(!1)},migrateData=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={log:log,info:info,logError:logError,logOk:logOk,debug:debug,warn:warn,getDisplayId:getDisplayId,isObject:isObject,isPdfUrl:isPdfUrl,delay:delay,cleanPapers:cleanPapers,firstNonStopLowercase:firstNonStopLowercase,fallbackCopyTextToClipboard:fallbackCopyTextToClipboard,copyTextToClipboard:copyTextToClipboard,parseUrl:parseUrl,downloadTextFile:downloadTextFile,eventId:eventId,downloadFile:downloadFile,hashCode:hashCode,parseCVFUrl:parseCVFUrl,cleanBiorxivURL:cleanBiorxivURL,textareaFocusEnd:textareaFocusEnd,tablerSvg:tablerSvg,stringifyError:stringifyError,arraysIdentical:arraysIdentical,parseTags:parseTags,getPaperEdits:getPaperEdits,setFormChangeListener:setFormChangeListener,monitorPaperEdits:monitorPaperEdits,cutAuthors:cutAuthors,sendMessageToBackground:sendMessageToBackground,getStoredFiles:getStoredFiles,miniHash:miniHash,noParamUrl:noParamUrl,silentPromiseTimeout:silentPromiseTimeout,shouldWarn:shouldWarn}),async(r,t,e=!0)=>{if(void 0===r)return chrome.storage.local.set({papers:{__dataVersion:t}}),{papers:{__dataVersion:t},success:!0};var i,n,a,o=r.__dataVersion||-1,s=[];let l={...r};try{if(502<=o)return{papers:r,success:!0};e&&backupData({...r}),delete r.__dataVersion;for(const c in r)o<5&&(info("Applying migration 5"),r[c].hasOwnProperty("bibtex")||(r[c].bibtex="",log("Migrating bibtex for "+c)),r[c].pdfLink.endsWith(".pdf")||(r[c].pdfLink=r[c].pdfLink+".pdf"),r[c].codeLink||(r[c].codeLink=""),r[c].source||(r[c].id.includes("NeurIPS")?r[c].source="neurips":r[c].source="arxiv")),o<208&&(info("Applying migration 0.2.8"),"arxiv"!==r[c].source&&r[c].md.includes("https://arxiv.com/abs/")&&(r[c].md=`[${r[c].title}](${r[c].pdfLink})`),"arxiv"!==r[c].source&&r[c].pdfLink.includes("arxiv.org/pdf/")&&(r[c].source="arxiv"),c.match(/^\d/)&&"arxiv"===r[c].source&&(i="Arxiv-"+c,n={...r[c],id:i},r[i]=n,s.push(c))),o<209&&(info("Applying migration 0.2.9"),r[c].hasOwnProperty("favorite")||(r[c].favorite=!1,r[c].favoriteDate="")),o<210&&(info("Applying migration 0.2.10"),"arxiv"===r[c].source&&(a=r[c].pdfLink.match(/v\d+\.pdf/gi))&&0{delete r[e],log("Deleting "+e)}),(l={...r}).__dataVersion=t,e&&chrome.storage.local.set({papers:l},()=>{log("Migrated papers:"),log(l),log("Data version is now "+t)}),{papers:l,success:!0}}catch(e){return log(`Error migrating data from version ${o} to ${t}:`),log(e),{papers:l,success:!1,error:e}}}),logStorage=t=>{chrome.storage.local.get(t,e=>{log(e[t])})},getStorage=async r=>new Promise((t,e)=>{chrome.storage.local.get(r,e=>{t("string"==typeof r?e[r]:e)})}),setStorage=async(r,i,n=()=>{})=>new Promise((e,t)=>{chrome.storage.local.set({[r]:i},()=>{n(),e(!0)})}),deletePaperInStorage=async(e,t)=>{let r=!1;(t=t||(await getStorage("papers")??{})).hasOwnProperty(e)&&(updateDuplicatedUrls(null,e,!0),r=(r=delete global.state.titleHashToIds[miniHash(t[e].title)])&&delete t[e]),r?(setStorage("papers",t),log("Successfully deleted paper",e)):log("Error: no deletion")},getTheme=async()=>{return await getStorage("checkDarkMode")?"dark":"light"},backupData=async r=>{chrome.storage.local.get("papersBackup",({papersBackup:e})=>{void 0===e&&(e={});for(const t of Object.keys(e).map(e=>parseInt(e)).sort((e,t)=>e{log("Backed up data with version: "+r.__dataVersion)})})};function dateDiffInDays(e,t){e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),t=Date.UTC(t.getFullYear(),t.getMonth(),t.getDate());return Math.floor((t-e)/864e5)}const weeklyBackup=async()=>{var e=await getStorage("weeklyBackups")??{};const t=new Date,r=Object.keys(e).map(e=>new Date(e)).sort((e,t)=>e.getTime()-t.getTime());if(0{let e=!1,t;const r=await getStorage("prefs")??{};(e=0===Object.keys(r).length?!0:e)&&(t=await getStorage(global.prefsStorageKeys)??{});let i={};for(const n of global.prefsCheckNames)i[n]=(t??r).hasOwnProperty(n)?(t??r)[n]:!(0<=global.prefsCheckDefaultFalse.indexOf(n));return i.checkOfficialRepos&&(setStorage("pwcPrefs",{official:!0}),delete i.checkOfficialRepos,setStorage("prefs",i)),e&&setStorage("prefs",i),i},getManifestDataVersion=()=>{const e=chrome.runtime.getManifest();return e.version.split(".").map((e,t)=>parseInt(e)*10**(4-2*t)).reduce((e,t)=>e+t)},versionToSemantic=e=>(e=(e-=1e4*(major=parseInt(e/1e4,10)))-100*(minor=parseInt(e/100,10)),`${major}.${minor}.`+e),validatePaper=(e,t=!0)=>{const r={addDate:{type:"string",desc:"the paper's date of addition to the Memory",default:e=>(new Date).toJSON()},author:{type:"string",desc:"` and `-separated authors `${firstName} ${lastName}`"},bibtex:{type:"string",desc:"BibTex citation with new lines (`\n`)"},code:{type:"object",desc:"the paper's code object as returned by the PapersWithCode API",default:e=>({})},codeLink:{type:"string",desc:"the paper's code link",default:e=>""},count:{type:"number",desc:"the paper's number of visits",default:e=>1},extras:{type:"object",desc:"extra information about the paper which may be required per source",optional:!0},favorite:{type:"boolean",desc:"user wants to star the paper",default:e=>!1},favoriteDate:{type:"string",desc:"date the paper was added as a favorite",default:e=>""},id:{type:"string",desc:"Unique PaperMemory ID"},key:{type:"string",desc:"BibTex citation key",default:e=>"defaultKey_"+e.id},lastOpenDate:{type:"string",desc:"When the paper was last opened",default:e=>(new Date).toJSON()},md:{type:"string",desc:"markdown-formatted string `[${title}](${pdfLink})`",default:e=>`[${e.title}](${e.pdfLink})`},note:{type:"string",desc:"the user's note for this paper",default:e=>""},pdfLink:{type:"string",desc:"the link to the paper's pdf"},source:{type:"string",desc:"the paper's source i.e. where it was added to the memory from"},tags:{type:"array[string]",desc:"the user's tags for this paper",default:e=>[]},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication"}};let i=[];for(const l in r)if(e.hasOwnProperty(l)){const c=r[l].type;var n,a=typeof e[l];c.includes("array")||"object"===c?c.includes("array")?Array.isArray(e[l])?(o=c.split("[")[1].replace("]",""),0{let t=!0,r="",i="",n;try{e.__dataVersion||(e.__dataVersion=1);var a,o=await migrateData(e,getManifestDataVersion(),!1);if(!o.success)return i="Could not migrate the data before storing it",o.error&&(i+=":
"+stringifyError(o.error)),{success:!1,message:i};for(const s in n=o.papers)s.startsWith("__")||(paperWarnings=validatePaper(n[s]).warnings)&&0"+paperWarnings.join("
"));r&&(a=await getStorage("papers")??{},setStorage("uploadBackup",a)),t=!1}catch(e){log("prepareOverwriteData error",e),i='
/!\\ OverwriteMemoryError:

'+stringifyError(e),t=!0}return{success:!t,message:i,warning:r,papersToWrite:n}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let r={};if(!e)return r;for(const n in global.knownPaperPages){var i=global.knownPaperPages[n];r[n]=!1;for(const a of i)"string"==typeof a?e.includes(a)&&(r[n]=!0):"function"==typeof a&&(r[n]=a(e))}return r.localFile=isKnownLocalFile(e),r.stored=!t&&await findLocalFile(e),r}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,r,i;const n=e.pdfLink;let a="";switch(e.source){case"arxiv":a="https://arxiv.org/abs/"+e.id.split("-")[1];break;case"neurips":a=n.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":a=n.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":a=n.replace("/pdf?","/forum?");break;case"biorxiv":a=n.replace(".full.pdf","");break;case"pmlr":a=n.split("/").slice(0,-1).join("/")+".html";break;case"acl":a=n.replace(".pdf","");break;case"pnas":a=n.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":a=n.replace(".pdf","");break;case"acs":a=n.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":a=n.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":a=n.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var o=n.match(/PMC\d+/)[0];a=n.split(o)[0]+o;break;case"ijcai":var o=n.replace(".pdf","").split("/").last().match(/[1-9]\d*/),s=n.match(/proceedings\/\d+/gi)[0].split("/")[1];a=`https://www.ijcai.org/proceedings/${s}/`+o;break;case"acm":a=n.replace("/doi/pdf/","/doi/");break;case"ieee":a="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":a=e.extra.url;break;case"aps":[t,r]=parseUrl(n).pathname.split("/").slice(1,3),a=n.replace(`/${t}/${r}/`,`/${t}/abstract/`);break;case"wiley":a=n.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":s=n.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];a="https://www.sciencedirect.com/science/article/pii/"+s;break;case"science":(i=n.split("/doi/")[1]).startsWith("10.")||(i=i.split("/").slice(1).join("/")),a="https://science.org/doi/full/"+i;break;case"frontiers":a=n.replace(/\/pdf$/,"/full");break;default:a="https://xkcd.com/1969/"}return a.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var r=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),i=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let n={};for(const o of t){let t;try{(t=await parseIdFromUrl(o.finalUrl))&&e.hasOwnProperty(t)&&(n[t]=o)}catch(e){t=null}if(!t){const s=i[o.id];var a=Object.entries(r).find(([,e])=>s.includes(e));a&&(n[a[0]]=o)}}return n},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:r,...i}=e;let n={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,...i};for(const a in r)(!t.hasOwnProperty(a)||r[a]&&!t[a])&&(n[a]=r[a]);e.incrementCount&&1===n.count&&(n.count+=1);for(const o of e.overwrites)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async(t,e,n,a=!0,o={update:()=>{},preprints:()=>{}})=>{const s=Date.now();let l,c,p={};console.group("%cPaperMemory parsing 📕",global.consolHeaderStyle),global.state.papers=await getStorage("papers")??{};var r=await parseIdFromUrl(t),i=global.state.papers.hasOwnProperty(r);if(r&&i)l=updatePaperVisits(global.state.papers[r]),c=!1;else{if(!(l=await makePaper(e,t)))return;i=findFuzzyPaperMatch(global.state.titleHashToIds,l);if(i&&a){let e=global.state.papers[i];log("New paper",l,"already exists as",e),addPaperToTitleHashToId(l),!l.venue&&e.venue||l.venue&&e.venue?(e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate"]}),updateDuplicatedUrls(t,i)):!e.venue&&l.venue&&(await updateDuplicatedUrls(paperToAbs(e),l.id),await updateDuplicatedUrls(paperToPDF(e),l.id),await deletePaperInStorage(e.id,global.state.papers),e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year"]})),l=updatePaperVisits(e),c=!1}else c=!0}if(!l.codeLink||!l.venue)try{const g=await tryPWCMatch(l);var u=!l.codeLink&&g?.url,d=g?.note,f=g?.bibtex,h=!l.venue&&g?.venue;(p={codeLink:u,note:d,venue:h,bibtex:f}).codeLink&&(l.codeLink=p.codeLink,g.hasOwnProperty("note")&&delete g.note,l.code=g)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),c=!1),a&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{o.update(l);let e;if(c||p.codeLink?c?(a?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it."),log("paper: ",l),e="Added to your Memory",p.codeLink&&(e+="
(+ repo from PapersWithCode)
"),n&&n.checkFeedback&&a&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",n&&n.checkFeedback&&a&&feedback(e)):a&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue){var t,r=await tryPreprintMatch(l);for(const i of["note","venue","bibtex"])l[i]&&"bibtex"!==i||(t=r[i]??p[i])&&(log(`Updating preprint ${i} to`,t),l[i]=t);global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e.id.includes(r))?.id,parseIdFromUrl=async t=>{let r;var e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),i=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var n=t.match(/\d{4}\.\d{4,5}/g)[0];r="Arxiv-"+n;const o=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));o&&(r=o.find(e=>!e.startsWith("Arxiv-"))??r)}else if(e.neurips){var n=t.split("/paper/")[1].split("/")[0],a=t.split("/").last().split("-")[0].slice(0,8);r=`NeurIPS-${n}_`+a}else if(e.cvf)r=parseCVFUrl(t).id;else if(e.openreview){n=t.match(/id=\w+/)[0].replace("id=","");r=findPaperId(i,"openreview",n)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),r="Biorxiv-"+e;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));s&&(r=s.find(e=>!e.startsWith("Biorxiv-"))??r)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];a="20"+l.match(/\d+/)[0];r=`PMLR-${a}-`+l}else if(e.acl){n=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();r=findPaperId(i,"acl",n)}else if(e.pnas){a=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];r=findPaperId(i,"pnas",a)}else if(e.nature){n=(t=t.replace(".pdf","").split("#")[0]).split("/").last();r=findPaperId(i,"nature",n)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);r="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1]);r="IOPscience_"+doi}else if(e.jmlr){const c=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();a="20"+c.match(/\d+/)[0];r=`JMLR-${a}_`+c}else if(e.pmc){n=t.match(/PMC\d+/g)[0].replace("PMC","");r=findPaperId(i,"pmc",n)}else if(e.ijcai){a=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),n=t.match(/proceedings\/\d+/gi)[0].split("/")[1];r=`IJCAI-${n}_`+a}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];r=findPaperId(i,"acm",miniHash(doi))}else if(e.ieee){n=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];r=findPaperId(i,"ieee",n)}else if(e.springer){const p=global.sourceExtras.springer.types;let e=p.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}a=t.split(`/${e}/`)[1].split("?")[0].replace(".pdf","");r=findPaperId(i,"springer",miniHash(a))}else if(e.aps){var[n,a]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${n}/${a}/`).last();r=findPaperId(i,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");r=findPaperId(i,"wiley",miniHash(doi))}else if(e.sciencedirect){n=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];r=findPaperId(i,"sciencedirect",miniHash(n))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),r=findPaperId(i,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),r=findPaperId(i,"frontiers",miniHash(doi));else{if(!e.localFile)throw new Error("unknown paper url");r=e.localFile}return r},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var r=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>i.includes(e.title));return 0!==r.length&&r[0].id},makeMdLink=(e,t={})=>{var r=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let i="",n=(!t.checkMdYearVenue||(i=(i=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&i[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(i="",e.venue&&(i+=e.venue+" "),i+=e.year),e.title);return`[${n=i?`${n} (${i.replace(/\s+/g," ")})`:n}](${r})`},initState=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),async(e,t)=>{const r=[];r.unshift(Date.now()),console.groupCollapsed("%cPaperMemory Init ✅",global.consolHeaderStyle),void 0===e&&(e=await getStorage("papers")??{},log("Time to retrieve stored papers (s): "+(Date.now()-r[0])/1e3)),r.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),log("Time to parse data version (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleFunction=(await getTitleFunction()).titleFunction,log("Time to make title function (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),weeklyBackup(),log("Time to backup papers (weekly) (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now());var i,n,a=await migrateData(e,global.state.dataVersion);log("Time to migrate data (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),e=a.papers,global.state.papers=e,global.state.prefs=await getPrefs(),log("Time to retrieve user preferences (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},log("Time to retrieve sources to ignore (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},log("Time to retrieve sources to urlHashToId (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleHashToIds={};for([i,n]of Object.entries(cleanPapers(e))){var o=miniHash(n.title);global.state.titleHashToIds.hasOwnProperty(o)||(global.state.titleHashToIds[o]=[]),global.state.titleHashToIds[o].push(i)}log("Time to hash titles (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),log("Time to match all local files (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),log("Time to sort memory (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),makeTags(),log("Time to make tags (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now())),info("State init duration (s): "+(Date.now()-r.last())/1e3),console.groupEnd()}),sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers),global.state.papersList.sort(orderPapers)},orderPapers=(e,t)=>{let r=e[global.state.sortKey],i=t[global.state.sortKey];return void 0===r&&(r=""),void 0===i&&(i=""),"string"==typeof r&&(r=r.toLowerCase(),i=i.toLowerCase()),0<=global.descendingSortKeys.indexOf(global.state.sortKey)?r>i?-1:1:r>i?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const r of t.tags)e.add(r);global.state.paperTags=Array.from(e),global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},r=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let i=t[r[e=void 0===e?getRandomInt(r.length):e]];return i=void 0===i?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:i},getTitleFunction=async(code=null)=>{let titleFunction;code=code||await getStorage("titleFunctionCode"),void 0===code&&(code=global.defaultTitleFunctionCode);let errorMessage;try{titleFunction=eval(code)}catch(error){errorMessage="Error parsing the title function: "+error,log("Error parsing the title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}try{const examplePaper=await getExamplePaper(0),result=titleFunction(examplePaper);if("string"!=typeof result)throw new Error(`Result ${result} is not a string`)}catch(error){errorMessage="Error executing the title function: "+error,log("Error testing the user's title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}return{titleFunction:titleFunction,code:code.trim(),errorMessage:errorMessage}},stateTitleFunction=paperOrId=>{let paper=paperOrId;if("string"==typeof paperOrId&&(paper=global.state.papers[paperOrId],void 0===paper))return log("Error in stateTitleFunction: unknown id",paperOrId),"Unknown ID";let name;try{name=global.state.titleFunction(paper)}catch(error){log("Error in stateTitleFunction:",error),name=eval(global.defaultTitleFunctionCode)(paper)}return name.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,r,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===r))&&e.length){for(const i of e)warn("Removing duplicated url",t,"for",r),delete global.state.urlHashToId[i];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=r,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={initState:initState,getExamplePaper:getExamplePaper,getTitleFunction:getTitleFunction,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,r;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(r=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:i,year:n}=parseCVFUrl(e);t=t.replace(`/content_${i}_${n}/`,`/content_${i.toLowerCase()}_${n}/`),r=await fetch(t).then(e=>e.ok?e.text():"")}return r},fetchOpenReviewNoteJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?id="+e).then(e=>e.json())},fetchOpenReviewForumJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?forum="+e).then(e=>e.json())},fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),r=t.ok?await t.text():"";return r.trim()}catch(e){return console.log("fetchText error:",e),""}},fetchJSON=async e=>{try{const t=await fetch(e);return t.ok?await t.json():null}catch(e){return console.log("fetchJSON error:",e),null}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const o=e.message;log("Crossref data.message: ",o);var t=o.author.map(e=>e.given+" "+e.family).join(" and ");const s=o.issued?o.issued["date-parts"][0][0]+"":o.published?o.published["date-parts"][0][0]+"":null;if(s){var r=o.title[0];if(r){var i=o["container-title"][0]??"Springer",n=[miniHash(o.author[0].family),s.slice(2),firstNonStopLowercase(r)].join(""),a=o.DOI;let e={entryType:"book"===o.type?"book":"book-chapter"===o.type?"InBook":o.type.includes("article")?"Article":"InProceedings",citationKey:n,publisher:o.publisher,author:t,title:r,year:s,doi:a};o.page&&(e.pages=o.page),o.volume&&(e.volume=o.volume),o.type.includes("journal")&&(e.journal=i),o.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=n.URL),(t=o.link.find(e=>"text/html"===e["content-type"])??o.link[0])&&(e.url=t.URL));r=bibtexToString(e);return{...e,bibtex:r,venue:i}}error("Cannot find title in CrossRef data",o)}else error("Cannot find year in CrossRef data",o)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{e=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return extractCrossrefData(e)},fetchSemanticsScholarDataForDoi=async e=>{const t=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`);let r;var i;return t&&(r={},t.venue&&(r.venue=t.venue),t.year&&(r.year=t.year),t.authors&&(r.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(r.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(r.title),i=bibtexToString({entryType:"article",citationKey:e,...r}),r.bibtex=i,r.key=e),r},getMetaContent=(e,t,r=!1)=>{e="meta"+Object.entries(e).map(([e,t])=>`[${e}='${t}']`).join("");return r?queryAll(t,e).map(e=>e.getAttribute("content")??""):t.querySelector(e)?.getAttribute("content")??""},extractDataFromDCMetaTags=e=>{const t=getMetaContent({name:"dc.Creator"},e,!0).map(e=>e.replace(/([a-z])([A-Z])/g,"$1 $2")).join(" and ");if(!t)return null;var r=getMetaContent({name:"dc.Date"},e).split("-")[0],i=getMetaContent({name:"dc.Publisher"},e).replaceAll("\n"," "),n=getMetaContent({name:"dc.Title"},e),a=getMetaContent({name:"citation_journal_title"},e),o=(""+t.split(" and ")[1].split(" ")[0]+r+firstNonStopLowercase(n)).toLowerCase(),e=getMetaContent({name:"dc.Date",scheme:"doi"},e),s=bibtexToString({citationKey:o,entryType:"article",title:n,author:t,year:r,doi:e,publisher:i,journal:a});return{author:t,year:r,publisher:i,title:n,venue:a,key:o,doi:e,bibtex:s,note:`Published @ ${a} (${r})`}},makeArxivPaper=async e=>{e=e.match(/\/(\d{4}\.\d{4,5})/)[1];const t=await fetchArxivXML(e),r=await t.text();var i=(new DOMParser).parseFromString(r.replaceAll("\n",""),"text/xml");const n=queryAll(i,"author name").map(e=>e.innerHTML);var a=n.join(" and "),o=Array.from(i.getElementsByTagName("link")).map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),s=i.querySelector("entry title").innerHTML,i=i.querySelector("entry published").innerHTML.slice(0,4),l=n[0].split(" ").last().toLowerCase()+i+firstNonStopLowercase(s),e="Arxiv-"+e,c="";return{author:a,bibtex:c+`@article{${l}, +`+`title={${s} }, +`+`author={${a} }, +`+`year={${i}}, `+`journal={arXiv preprint arXiv: ${e}} -`+"}",id:e,key:l,pdfLink:s,title:n,venue:"",year:r}},makeNeuripsPaper=async e=>{const t=(e=e.endsWith(".pdf")?e.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html"):e).split("/").slice(-1)[0].replace("-Paper.pdf",""),a=await fetchDom(e);var r=Array.from(a.getElementsByTagName("a")).filter(e=>"Bibtex"===e.innerText)[0]?.getAttribute("href");let i,o,s,n,l;if(r)i=await fetchText("https://"+parseUrl(e).host+r),{author:o,citationKey,title:s,year:n}=bibtexToObject(i),o=flipAndAuthors(o),l=citationKey;else{const d=queryAll(a,".container-fluid .col p"),u=(s=a.getElementsByTagName("h4")[0].innerHTML,queryAll(document,"h4").filter(e=>"Authors"===e.innerText)[0]);o=u.nextElementSibling.innerText.split(", ").map(e=>e.split(" ").map(e=>e.capitalize()).join(" ")).join(" and "),n=d[0].innerHTML.match(/\d{4}/)[0],l="neurips"+n+t.slice(0,8),i="",i=(i=(i=(i=(i+=`@inproceedings{NEURIPS${n}_${t.slice(0,8)}, -`)+`author={${o}}, +`+"}",id:e,key:l,pdfLink:o,title:s,venue:"",year:i}},makeNeuripsPaper=async e=>{const t=(e=e.endsWith(".pdf")?e.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html"):e).split("/").slice(-1)[0].replace("-Paper.pdf",""),r=await fetchDom(e);var i=Array.from(r.getElementsByTagName("a")).filter(e=>"Bibtex"===e.innerText)[0]?.getAttribute("href");let n,a,o,s,l;if(i)n=await fetchText("https://"+parseUrl(e).host+i),{author:a,citationKey,title:o,year:s}=bibtexToObject(n),a=flipAndAuthors(a),l=citationKey;else{const u=queryAll(r,".container-fluid .col p"),d=(o=r.getElementsByTagName("h4")[0].innerHTML,queryAll(document,"h4").filter(e=>"Authors"===e.innerText)[0]);a=d.nextElementSibling.innerText.split(", ").map(e=>e.split(" ").map(e=>e.capitalize()).join(" ")).join(" and "),s=u[0].innerHTML.match(/\d{4}/)[0],l="neurips"+s+t.slice(0,8),n="",n=(n=(n=(n=(n+=`@inproceedings{NEURIPS${s}_${t.slice(0,8)}, +`)+`author={${a}}, `+`booktitle={Advances in Neural Information Processing Systems}, `)+`editor={H.Larochelle and M.Ranzato and R.Hadsell and M.F.Balcan and H.Lin}, `+`publisher={Curran Associates, Inc.}, -`)+`title={${s}}, +`)+`title={${o}}, `+`url={${e}}, -`)+`year={${n}} -`+"}",i=bibtexToString(i)}var r=e.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf"),e=`NeurIPS-${n}_`+t.slice(0,8),p="NeurIPS",c=`Accepted @ ${p} (${n})`;return{author:o,bibtex:i,id:e,key:l,note:c,pdfLink:r,title:s,venue:p,year:n}},makeCVFPaper=async e=>{const t=await fetchCvfHTML(e),a=(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html");var r=a.getElementById("papertitle").innerText.trim(),i=a.querySelector("#authors i").innerText.split(",").map(e=>e.trim()).join(" and "),{year:o,id:s,conf:n}=parseCVFUrl(e);let l="";if(e.endsWith(".pdf"))l=e;else{let e=Array.from(a.getElementsByTagName("a")).filter(e=>"pdf"===e.innerText)[0].getAttribute("href");(e=e.startsWith("../")?e.replaceAll("../",""):e).startsWith("/")||(e="/"+e),l="http://openaccess.thecvf.com"+e}e=n,n=`Accepted @ ${e} (${o})`;const p=bibtexToString(a.querySelector(".bibref").innerText);var c=p.split("{")[1].split(",")[0];return{author:i,bibtex:p,id:s,key:c,note:n,pdfLink:l,title:r,venue:e,year:o}},makeOpenReviewBibTex=(e,t)=>{var a=e.content.title,r=e.content.authors.join(" and "),i=e.cdate?new Date(e.cdate).getFullYear():"0000",e=(e.cdate||log("makeOpenReviewBibTex: no cdate found in",e),e.content.authors[0].split(" ").last()),o="";return o+`@inproceedings{${e=(e+=i)+firstNonStopLowercase(a)}, -`+`title={${a}}, -`+`author={${r}}, -`+`year={${i}}, +`)+`year={${s}} +`+"}",n=bibtexToString(n)}var i=e.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf"),e=`NeurIPS-${s}_`+t.slice(0,8),c="NeurIPS",p=`Accepted @ ${c} (${s})`;return{author:a,bibtex:n,id:e,key:l,note:p,pdfLink:i,title:o,venue:c,year:s}},makeCVFPaper=async e=>{const t=await fetchCvfHTML(e),r=(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html");var i=r.getElementById("papertitle").innerText.trim(),n=r.querySelector("#authors i").innerText.split(",").map(e=>e.trim()).join(" and "),{year:a,id:o,conf:s}=parseCVFUrl(e);let l="";if(e.endsWith(".pdf"))l=e;else{let e=Array.from(r.getElementsByTagName("a")).filter(e=>"pdf"===e.innerText)[0].getAttribute("href");(e=e.startsWith("../")?e.replaceAll("../",""):e).startsWith("/")||(e="/"+e),l="http://openaccess.thecvf.com"+e}e=s,s=`Accepted @ ${e} (${a})`;const c=bibtexToString(r.querySelector(".bibref").innerText);var p=c.split("{")[1].split(",")[0];return{author:n,bibtex:c,id:o,key:p,note:s,pdfLink:l,title:i,venue:e,year:a}},makeOpenReviewBibTex=(e,t)=>{var r=e.content.title,i=e.content.authors.join(" and "),n=e.cdate?new Date(e.cdate).getFullYear():"0000",e=(e.cdate||log("makeOpenReviewBibTex: no cdate found in",e),e.content.authors[0].split(" ").last()),a="";return a+`@inproceedings{${e=(e+=n)+firstNonStopLowercase(r)}, +`+`title={${r}}, +`+`author={${i}}, +`+`year={${n}}, `+`url={${t}}, -`+"}"},makeOpenReviewPaper=async e=>{var t=await fetchOpenReviewNoteJSON(e),a=await fetchOpenReviewForumJSON(e),t=t.notes[0],a=a.notes,r=t.content.title,i=t.content.authors.join(" and "),o=bibtexToString(t.content._bibtex||makeOpenReviewBibTex(t,e)),s=bibtexToObject(o),n=s.citationKey,s=s.year;let l;l=t.pdf?"https://openreview.net/pdf?id="+t.id:(t.html||e).replace("/forum?id=","/pdf?id=");const p=t.invitation.split("/");let c=p[0].split(".")[0],d=p.slice(1).join("/").split("-")[0].replaceAll("/"," ").replace(" Conference",""),u=c,h=!1;global.overrideORConfs.hasOwnProperty(c)&&(u=global.overrideORConfs[c],h=!0),h&&(d=d.replace(u,""),c=u);e=(c+" "+d).replace(/ \d\d\d\d/g,"").replace(/\s\s+/g," "),t=`OR-${c}-${s}_`+t.id;let f,m,g,y="";return(f=a.filter(e=>e&&e.content&&-1<["Final Decision","Paper Decision","Acceptance Decision"].indexOf(e.content.title)))&&00===t?e+"ed":e).join(" "),g=m+` @ ${e} (${s})`,m.toLowerCase().indexOf("rejected")<0&&(y=e)),{author:i,bibtex:o,id:t,key:n,note:g="Anonymous"===i?`Under review @ ${e} (${s}) (${(new Date).toLocaleDateString()})`:g,pdfLink:l,title:r,venue:y,year:s}},makeBioRxivPaper=async e=>{var t=e.replace(".full.pdf",""),a="https://api.biorxiv.org//details/biorxiv/"+e.split("/").slice(-2).join("/").replace(".full.pdf","").split("v")[0];const r=await fetch(a).then(e=>e.json());if("ok"!==r.messages[0].status)throw new Error(a+" returned "+r.messages[0].status);const i=r.collection.last(),o=await fetchText(t),s=(new DOMParser).parseFromString(o.replaceAll("\n",""),"text/html");a=s.querySelector(".bibtext a").getAttribute("href");const n=bibtexToString(await(await fetch(a)).text());var t=extractAuthor(n),a=await parseIdFromUrl(e),l=n.split("\n")[0].split("{")[1].replace(",","").trim(),e=cleanBiorxivURL(e)+".full.pdf",p=i.title,c=i.date.split("-")[0];return{author:t,bibtex:n,id:a,key:l,note:"",pdfLink:e,title:p,venue:"",year:c}},makePMLRPaper=async e=>{var t=e.split("/").last().split(".")[0],a=await parseIdFromUrl(e);const r=e.includes(".html")?e:e.split("/").slice(0,-2).join("/")+`/${t}.html`;e=r.replace(".html","")+`/${t}.pdf`;const i=await fetchDom(r);i.getElementById("button-bibtex1").getAttribute("onclick").match(/https.+\.bib/)[0];const o=i.getElementById("bibtex").innerText.replaceAll("\t"," ").replaceAll(/\s\s+/g," ");let s=o;for(const u of o.match(/,\ ?\w+ ?= ?{/g))s=s.replace(u,u.replace(", ",",\n ").replace(" = ","="));s.endsWith("}}")&&(s=s.slice(0,-2)+"}\n}"),s=bibtexToString(s);var n=extractAuthor(s),l=i.getElementsByTagName("h1")[0].innerText,p=extractBibtexValue(s,"year");let c=extractBibtexValue(s,"booktitle").replaceAll("Proceedings of the",""),d=c;note=`Accepted @ ${d} (${p})`;for(const h in global.overridePMLRConfs)if(c.includes(h)){d=global.overridePMLRConfs[h],c=d+" "+p,note="Accepted @ "+c;break}return{author:n,bibtex:s,id:a,key:t,note:note,pdfLink:e,title:l,venue:d,year:p}},findACLValue=(e,t)=>{return queryAll(e,"dt").filter(e=>e.innerText.includes(t))[0].nextElementSibling.innerText},makeACLPaper=async e=>{e=e.replace(".pdf","");const t=await fetchDom(e);e=t.getElementById("citeBibtexContent");if(e){var a=t.getElementById("title").innerText,e=bibtexToString(e.innerText);const l=bibtexToObject(e);var r=l.year,i=l.author.replace(/\s+/g," ").split(" and ").map(e=>e.split(",").map(e=>e.trim()).reverse().join(" ")).join(" and "),o=l.citationKey,s=findACLValue(t,"Venue"),n=findACLValue(t,"PDF");return{author:i,bibtex:e,id:`ACL-${s}-${r}_`+findACLValue(t,"Anthology ID"),key:o,note:`Accepted @ ${s} (${r})`,pdfLink:n,title:a,venue:s,year:r}}},makePNASPaper=async e=>{e=e.replace(".full.pdf","").replace(/\/doi\/e?pdf\//,"/doi/abs/");const t=await fetchDom(e);var a=t.getElementsByTagName("h1")[0].innerText,r=queryAll(t,".authors span[property='author'] a:not([property='email']):not(.orcid-id)").filter(e=>!e.getAttribute("href").includes("mailto:")).map(e=>e.innerText).join(" and "),i=t.querySelector("span[property='datePublished']").innerText.match(/\d{4}/g)[0],o=`PNAS-${i}_`+(e.endsWith("/")?e.split("/").slice(-2):e.split("/").slice(-1))[0];const s=e.includes("/doi/pdf/")||e.includes("/doi/epdf/")?e.replace("/doi/epdf/","/doi/pdf/"):e.replace("/doi/abs/","/doi/pdf/").replace("/doi/full/","/doi/pdf/");var e=Array.from(t.querySelector(".core-container").getElementsByTagName("a")).map(e=>e.getAttribute("href")).filter(e=>e?.includes("https://doi.org"))[0].split("/").slice(-2).join("/"),n="doi:"+e;return{author:r,bibtex:bibtexToString(`@article{${n}, author={${r}}, title={${a}}, journal = {Proceedings of the National Academy of Sciences}, year={${i}}, doi={${e}}, eprint={${s}}, URL={${s.replace("/doi/pdf/","/doi/abs/")}} }`),id:o,key:n,note:`Published @ PNAS (${i})`,pdfLink:s,title:a,venue:"PNAS",year:i}},makeNaturePaper=async e=>{var t=(e=e.replace(".pdf","").split("#")[0])+".pdf",a=e.split("/").last();const r=await fetchDom(e);e=r.querySelector("h1.c-article-title").innerText;const i=queryAll(r,"ul.c-article-author-list li").map(e=>e.innerText.replace(/(\ ?,)|&|…|\d/g,"").split(/orcid/i)[0].trim()).filter(e=>0e.innerText).filter(e=>e.includes("https://doi.org"))[0];var l=""+i.split(" ")[1]+o+firstNonStopLowercase(e);let p={citationKey:l,entryType:"article",author:i,title:e,journal:s,year:o};n&&(p.doi=n,p.url="https://doi.org/"+n);var c=bibtexToString(p);return{author:i,bibtex:c,id:a,key:l,note:`Published @ ${s} (${o})`,pdfLink:t,title:e,venue:s,year:o}},makeACSPaper=async e=>{const t=(e=e.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0]).replace("/abs/","/").split("/doi/")[1];console.log("doi: ",t);e=`https://pubs.acs.org/action/downloadCitation?doi=${t}&include=cit&format=bibtex&direct=true`,e=await fetchText(e);const a=bibtexToObject(e);var r=a.author.replaceAll("\n","").trim(),i=a.title.trim(),o=a.year.trim(),s=a.citationKey.trim(),n="https://pubs.acs.org/doi/pdf/"+t,l=`Published @ ${a.journal} (${a.year})`;return{author:r,bibtex:e,id:"ACS_"+t.replaceAll(".","").replaceAll("/",""),key:s,note:l,pdfLink:n,title:i,venue:a.journal,year:o}},makeIOPPaper=async e=>{(e=e.split("#")[0]).endsWith("/pdf")&&(e=e.slice(0,-4));var t=await fetchDom(e),t=queryAll(t,".btn-multi-block a").filter(e=>"BibTeX"===e.innerText).map(e=>e.getAttribute("href"))[0],t="https://"+parseUrl(e).host+t,t=await fetchText(t);const a=bibtexToObject(t);var r=a.author.replaceAll("\n","").trim(),i=a.title.trim(),o=a.year.trim(),s=a.citationKey.trim(),n=e+"/pdf",l=a.journal,p=`Published @ ${l} (${o})`;const c=e.split("/article/").last();return{author:r,bibtex:t,id:"IOPscience_"+c.replaceAll(".","").replaceAll("/",""),key:s,note:p,pdfLink:n,title:i,venue:l,year:o}},makeJMLRPaper=async e=>{var t=(e=(e=(e=e.includes("/papers/volume")?e.replace("/papers/volume","/papers/v"):e).endsWith(".pdf")?e.split("/").slice(0,-1).join("/"):e).replace(".html","")).split("/").last(),a=e+".bib",a=await fetchText(a);const{author:r,year:i,title:o,citationKey:s}=bibtexToObject(a);return{author:r,bibtex:a,id:`JMLR-${i}_`+t,key:s.trim(),note:`Published @ JMLR (${i})`,pdfLink:e.replace("/papers/v","/papers/volume")+`/${t}.pdf`,title:o,venue:"JMLR",year:i}},makePMCPaper=async e=>{var t=e.match(/PMC\d+/)[0].replace("PMC",""),a=e.split("PMC"+t)[0]+"PMC"+t;const r=await(await fetch(`https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=${t}&download=true`)).json();var i=(r["epub-date"]||r.issued)["date-parts"][0][0],o=r.author.map(e=>e.given+" "+e.family).join(" and "),s=r["container-title"].split(" ").map(e=>e.capitalize()).join(" "),n=r.title,t=`PMC-${i}_`+t,l=""+r.author[0].family+i+firstNonStopLowercase(n),p=bibtexToString({entryType:"article",citationKey:l,journal:s,issn:r.ISSN,volume:r.volume,page:r.page,doi:r.DOI,PMID:r.PMID,PMCID:r.PMCID,publisher:r.publisher,author:o,title:n});let c;if(isPdfUrl(e))c=e;else{const h=r.DOI.split("/")[1].split("-");var e=h[0].match(/\d+/)[0],d=h[1].replace(h[1].match(/^0*/)[0],""),u=h[2].replace(h[2].match(/^0*/)[0],"");c=a+`/pdf/${e}_${d}_Article_${u}.pdf`}return{author:o,bibtex:p,id:t,key:l,note:`Published @ ${s} (${i})`,pdfLink:c,title:n,venue:s,year:i}},makePubMedPaper=async e=>{const t=await fetchDom(e.split("?")[0]),a=Array.from(t.getElementsByTagName("meta")).filter(e=>e.getAttribute("name")?.includes("citation_")),r=Object.fromEntries(a.map(e=>[e.getAttribute("name").replace("citation_",""),e.getAttribute("content")])),i=document.querySelector("div.authors-list").innerText.replace(/\d/gi,"").split(",").map(e=>e.trim()).join(" and ");var e=r.title,o=r.journal_title,s=r.date.split("/")[2],n=`PubMed-${s}_`+r.pmid,l=""+i.split(" and ")[0].split(" ").last()+s+firstNonStopLowercase(r.title),p={entryType:"article",citationKey:l,publisher:r.publisher,doi:r.doi,issn:r.issn,journal:o,year:s,author:i},p=bibtexToString(p),c=`Accepted @ ${journal} (${s})`;return{author:i,bibtex:p,id:n,key:l,note:c,pdfLink:"",title:e,venue:o,year:s}},makeIJCAIPaper=async e=>{const t=e.endsWith(".pdf")?e.replace(".pdf","").split("/").last().match(/[1-9]\d*/)[0]:e.split("/").last();e=e.match(/proceedings\/\d+/gi)[0].split("/")[1];const a=(await fetchText(`https://www.ijcai.org/proceedings/${e}/bibtex/`+t)).replace(/}\n/gi,"},\n");var r=bibtexToObject(a.split("\n").filter(e=>!/note\s+=/gi.test(e)).join("\n")),i=r.citationKey,o=r.title,r=flipAndAuthors(r.author),s=`IJCAI-${e}_`+t,n=`Accepted @ IJCAI (${e})`,l=t.padStart(4,0);return{author:r,bibtex:a,id:s,key:i,note:n,pdfLink:`https://www.ijcai.org/proceedings/${e}/${l}.pdf`,title:o,venue:"IJCAI",year:e}},makeACMPaper=async e=>{let t;t=isPdfUrl(e)?e:e.replace(/\/doi\/?(abs|full)?\//,"/doi/pdf/");const a=await fetchDom(e.replace("/doi/pdf/","/doi/"));let r,i,o,s,n,l,p,c;var d=extractDataFromDCMetaTags(a);if(d)({author:r,year:i,title:o,venue:s,key:n,doi:l,bibtex:p,note:c}=d);else{o=a.querySelector(".citation__title").innerText,r=queryAll(a,"ul[ariaa-label='authors'] li.loa__item .loa__author-name").map(e=>e.innerText.replace(",","").trim()).join(" and ");const u=a.querySelector(".issue-item__detail a").innerText;s=u.split("'")[0].trim(),i="20"+u.split("'")[1].split(":")[0].trim(),l=t.split("/doi/pdf/")[1],c=`Accepted @ ${s} (${i})`,n=l,p=bibtexToString({entryType:"article",citationKey:l,journal:s,author:r,title:o,year:i,publisher:"Association for Computing Machinery",address:"New York, NY, USA",url:e.replace("/doi/pdf/","/doi/")})}d=`ACM-${i}_`+miniHash(l);return{author:r,bibtex:p,id:d,key:n,note:c,pdfLink:t,title:o,venue:s,year:i}},makeIEEEPaper=async e=>{isPdfUrl(e)&&(e=`https://ieeexplore.ieee.org/document/${e.split("/stamp/stamp.jsp?tp=&arnumber=")[1].match(/\d+/)[0]}/`,console.log("url: ",e));const t=await fetchDom(e),a=JSON.parse(Array.from(t.getElementsByTagName("script")).filter(e=>e.innerHTML?.includes("metadata="))[0].innerHTML.split("metadata=")[1].split(/};\s*/)[0]+"}");var r=a.title,i=a.authors.map(e=>e.name).join(" and "),o=a.publicationYear,e=""+parseUrl(e).origin+a.pdfUrl,s=a.publicationTitle,n=a.articleId;return{author:i,bibtex:bibtexToString({entryType:"article",citationKey:n,journal:s,volume:a.volume,pages:a.startPage+"-"+a.endPage,doi:a.doi,title:r,year:o,author:i}),id:`IEEE-${o}_`+n,key:n,note:`Accepted @ ${s} (${o})`,pdfLink:e,title:r,venue:s,year:o}},makeSpringerPaper=async t=>{const e=[...global.sourceExtras.springer.types,"content/pdf"];var a=e.find(e=>t.includes(`/${e}/`));if(!a)throw new Error(`Could not find Springer type for ${t} (known: ${e.join(", ")})`);var r=t.split(`/${a}/`)[1].split("?")[0].replace(".pdf",""),i=await fetchCrossRefDataForDoi(r);if(!i)throw new Error("Aborting Springer paper parsing, see error above");var{author:o,bibtex:s,citationKey:n,year:l,title:p,venue:c}=i;return{author:o,bibtex:s,id:`Springer-${l}_`+miniHash(r),key:n,note:`Published @ ${c} (${l})`,pdfLink:i.pdf??("content/pdf"===a?t:t.replace(`/${a}/`,"/content/pdf/")+".pdf"),title:p,venue:c,year:l,extra:{url:"https://doi.org/"+r}}},makeAPSPaper=async e=>{e=e.split("#")[0];var[t,a]=parseUrl(e).pathname.split("/").slice(1,3),r=e.split(`/${t}/${a}/`).last(),i=e.replace(`/${t}/${a}/`,`/${t}/export/`),i=await fetchText(i+"?type=bibtex&download=true"),o=bibtexToObject(i),e=e.replace(`/${t}/${a}/`,`/${t}/pdf/`),a=`APS-${o.year}_`+miniHash(r),t=o.journal??o.publisher,r=(await readJournalAbbreviations(),global.journalAbbreviations[miniHash(t)]??t),t=`Published @ ${r} (${o.year})`;return{author:flipAndAuthors(o.author),bibtex:i,id:a,key:o.citationKey,note:t,pdfLink:e,title:o.title,venue:r,year:o.year}},makeWileyPaper=async e=>{const t=e.replace(/\/doi\/(abs|epdf|full)\//g,"/doi/pdf/");e=t.replace("/doi/pdf/","/doi/abs/");const a=await fetchDom(e);var e=queryAll("meta[name=citation_author]").map(e=>e.getAttribute("content")).join(" and "),r=a.querySelector("meta[name=citation_journal_title]").getAttribute("content"),i=a.querySelector("meta[name=citation_title]").getAttribute("content"),o=a.querySelector("meta[name=citation_publisher]").getAttribute("content"),s=a.querySelector("meta[name=citation_publication_date]")?.getAttribute("content")?.split("/")[0]??a.querySelector("meta[name=citation_online_date]")?.getAttribute("content")?.split("/")[0],n=a.querySelector("meta[name=citation_doi]").getAttribute("content"),l=`Published @ ${r} (${s})`,p=`Wiley-${s}_`+miniHash(n);return{author:e,bibtex:bibtexToString({citationKey:n,entryType:"article",title:i,author:e,year:s,doi:n,publisher:o,journal:r}),id:p,key:n,note:l,pdfLink:t,title:i,venue:r,year:s}},makeScienceDirectPaper=async e=>{var e=e.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0],t=await fetchText(`https://www.sciencedirect.com/sdfe/arp/cite?pii=${e}&format=text%2Fx-bibtex&withabstract=false`),{author:a,journal:r,year:i,title:o,citationKey:s}=bibtexToObject(t),n=`Published @ ${r} (${i})`;return{author:a,bibtex:t,id:`ScienceDirect-${i}_`+miniHash(e),key:s,note:n,pdfLink:"https://reader.elsevier.com/reader/sd/pii/"+e,title:o,venue:r??"Science Direct",year:i}},makeSciencePaper=async e=>{let t,a,r,i,o,s,n,l,p,c,d;s="https://science.org/doi/pdf/"+(c=(c=noParamUrl(e).split("/doi/")[1]).startsWith("10.")?c:c.split("/").slice(1).join("/")),d="https://science.org/doi/full/"+c;var e=await fetchCrossRefDataForDoi(c);return e?({author:t,bibtex:a,title:n,venue:l,year:p}=e,i=e.citationKey,o=`Published @ ${l} (${p})`):(e=await fetchDom(d),{author:t,year:p,publisher,title:n,venue:l,key:i,bibtex:a,note:o}=extractDataFromDCMetaTags(e)),r=`Science-${p}_`+miniHash(c),{author:t,bibtex:a,id:r,key:i,note:o,pdfLink:s,title:n,venue:l,year:p}},makeFrontiersPaper=async e=>{e=e.replace(/\/pdf$/,"/full");var t=noParamUrl(e).split("/articles/")[1].split("/full")[0],a=await fetchText(`https://www.frontiersin.org/articles/${t}/bibTex`);const r=Object.fromEntries(Object.entries(bibtexToObject(a)).map(([e,t])=>["citationKey"===e||"entryType"===e?e:e.toLowerCase(),t]));r.author=flipAndAuthors(r.author),delete r.abstract;var{author:a,journal:i,year:o,title:s,citationKey:n}=r,l=`Published @ ${i} (${o})`;return{author:a,bibtex:bibtexToString(r),id:`Frontiers-${o}_`+miniHash(t),key:n,note:l,pdfLink:e.replace(/\/full$/,"/pdf"),title:s,venue:i,year:o}},tryPWCMatch=async e=>{let t;var a={type:"papersWithCode",pwcPrefs:await getStorage("pwcPrefs")??{},paper:e},{url:a,note:r,venue:i,pubYear:o}=await sendMessageToBackground(a)??{};return a&&!e.codeLink?log("[PapersWithCode] Discovered a code repository:",a):log("[PapersWithCode] No code repository found"),i&&!e.venue?(log("[PapersWithCode] Found a publication venue:",i),e=bibtexToObject(e.bibtex),t=bibtexToString({...e,year:o,journal:i})):log("[PapersWithCode] No publication found"),{codeLink:a,note:r,venue:i,bibtex:t}},tryCrossRef=async e=>{try{var t="https://api.crossref.org/works?rows=1&mailto=schmidtv%40mila.quebec&select=event%2Ctitle&query.title="+encodeURI(e.title);const r=await fetch(t).then(e=>e.json());if("ok"!==r.status)return log(`[Crossref] ${t} returned `+r.message.status),{note:null};if(0===r.message.items.length)return{note:null};if(r.message.items[0].title[0].toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," ")!==e.title.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," "))return{note:null};if(!r.message.items[0].event||!r.message.items[0].event.name)return{note:null};info("Found a CrossRef match");var a=r.message.items[0].event.name.trim();return{venue:a,note:`Accepted @ ${a} -- [crossref.org]`}}catch(e){return logError("[Crossref]",e),{note:null}}},tryDBLP=async e=>{try{var t,a,r,i,o=encodeURI(e.title);const s=await fetch(`https://dblp.org/search/publ/api?q=${o}&format=json`).then(e=>e.json());if(!(s.result&&s.result.hits&&s.result.hits.hit&&s.result.hits.hit.length))return{note:null};for(const n of s.result.hits.hit.sort((e,t)=>parseInt(e.info.year,10)-parseInt(t.info.year,10)))if(decodeHtml(n.info.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," "))===e.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," ")&&"CoRR"!==n.info.venue)return info("Found a DBLP match"),t=await fetchText(n.info.url+".bib"),a=miniHash(n.info.venue),await readJournalAbbreviations(),r=(global.journalAbbreviations[a]??n.info.venue).trim(),i=n.info.year,n.info.url,{venue:r,note:`Accepted @ ${r} ${i} -- [dblp.org]`,bibtex:t};return{note:null}}catch(e){return logError("[DBLP]",e),{note:null}}},trySemanticScholar=async t=>{try{var e=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURI(t.title)}&fields=title,venue,year,authors,externalIds,url&limit=50`);if(e&&e.data&&0e.name).join(" and ");let e=s.externalIds.DOI;return e=e&&e.replaceAll("_","\\{_}"),{venue:a,note:i,bibtex:bibtexToString({entryType:"article",citationKey:miniHash(s.authors[0].name.split(" ").last())+r+firstNonStopLowercase(t.title),title:t.title,author:o,journal:a,year:r,doi:e,bibSource:"Semantic Scholar "+s.url})}}}catch(e){logError("[SemanticScholar]",e)}},tryGoogleScholar=async e=>{return await sendMessageToBackground({type:"google-scholar",paper:e})},tryPreprintMatch=async(e,t=!1)=>{let a,r,i,o,s={},n=["DBLP","SemanticScholar","CrossRef","GoogleScholar"],l=[silentPromiseTimeout(tryDBLP(e)),silentPromiseTimeout(trySemanticScholar(e)),silentPromiseTimeout(tryGoogleScholar(e)),silentPromiseTimeout(tryCrossRef(e))];t&&(l.push(silentPromiseTimeout(tryPWCMatch(e))),n.push("PapersWithCode"));for(var[p,c]of Object.entries(n)){if(s[c]=await l[p],{note:a,venue:r,bibtex:i}=s[c]??{},a)break;log(`[${c}] No publication found`)}return t&&(t="PapersWithCode",s.hasOwnProperty(t)||(s[t]=await l[t]),s[t].codeLink&&!e.codeLink&&(o=s[t].codeLink)),{note:a,venue:r,bibtex:i,code:o}},initPaper=async e=>{e.note||(e.note=""),e.md=`[${e.title}](${e.pdfLink})`,e.tags=[],e.codeLink="",e.favorite=!1,e.favoriteDate="",e.addDate=(new Date).toJSON(),e.lastOpenDate=e.addDate,e.count=1,e.code={};for(const t in e)e.hasOwnProperty(t)&&"string"==typeof e[t]&&(e[t]=e[t].trim());return e=await autoTagPaper(e),validatePaper(e),e},autoTagPaper=async a=>{try{var e,r,i=await getStorage("autoTags");if(!i||!i.length)return a;let t=new Set;for(const o of i)o.tags?.length&&(o.title||o.author)&&(e=!o.title||new RegExp(o.title,"i").test(a.title),r=!o.author||new RegExp(o.author,"i").test(a.author),e&&r&&o.tags.forEach(e=>t.add(e)));return a.tags=Array.from(t).sort(),a.tags.length&&log("Automatically adding tags:",a.tags),a}catch(e){return log("Error auto-tagging:",e),log("Paper:",a),a}},makePaper=async(e,t)=>{let a;if(e.arxiv)(a=await makeArxivPaper(t)).source="arxiv";else if(e.neurips)(a=await makeNeuripsPaper(t)).source="neurips";else if(e.cvf)(a=await makeCVFPaper(t)).source="cvf";else if(e.openreview)(a=await makeOpenReviewPaper(t)).source="openreview";else if(e.biorxiv)(a=await makeBioRxivPaper(t)).source="biorxiv";else if(e.pmlr)(a=await makePMLRPaper(t)).source="pmlr";else if(e.acl)(a=await makeACLPaper(t))&&(a.source="acl");else if(e.pnas)(a=await makePNASPaper(t))&&(a.source="pnas");else if(e.nature)(a=await makeNaturePaper(t))&&(a.source="nature");else if(e.acs)(a=await makeACSPaper(t))&&(a.source="acs");else if(e.iop)(a=await makeIOPPaper(t))&&(a.source="iop");else if(e.jmlr)(a=await makeJMLRPaper(t))&&(a.source="jmlr");else if(e.pmc)(a=await makePMCPaper(t))&&(a.source="pmc");else if(e.ijcai)(a=await makeIJCAIPaper(t))&&(a.source="ijcai");else if(e.acm)(a=await makeACMPaper(t))&&(a.source="acm");else if(e.ieee)(a=await makeIEEEPaper(t))&&(a.source="ieee");else if(e.springer)(a=await makeSpringerPaper(t))&&(a.source="springer");else if(e.aps)(a=await makeAPSPaper(t))&&(a.source="aps");else if(e.wiley)(a=await makeWileyPaper(t))&&(a.source="wiley");else if(e.sciencedirect)(a=await makeScienceDirectPaper(t))&&(a.source="sciencedirect");else if(e.science)(a=await makeSciencePaper(t))&&(a.source="science");else{if(!e.frontiers)throw new Error("Unknown paper source: "+JSON.stringify({is:e,url:t}));(a=await makeFrontiersPaper(t))&&(a.source="frontiers")}if(void 0!==a)return initPaper(a)},findFuzzyPaperMatch=(e,t)=>{t=miniHash(t.title);if(e.hasOwnProperty(t)){const a=e[t];e=a.find(t=>!global.preprintSources.some(e=>t.toLowerCase().startsWith(e)));return e?e:a[0]}return null};"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={autoTagPaper:autoTagPaper,decodeHtml:decodeHtml,fetchArxivXML:fetchArxivXML,fetchCrossRefDataForDoi:fetchCrossRefDataForDoi,fetchCvfHTML:fetchCvfHTML,fetchDom:fetchDom,fetchOpenReviewForumJSON:fetchOpenReviewForumJSON,fetchOpenReviewNoteJSON:fetchOpenReviewNoteJSON,fetchSemanticsScholarDataForDoi:fetchSemanticsScholarDataForDoi,fetchText:fetchText,findACLValue:findACLValue,findFuzzyPaperMatch:findFuzzyPaperMatch,flipAndAuthors:flipAndAuthors,flipAuthor:flipAuthor,initPaper:initPaper,makeACLPaper:makeACLPaper,makeACMPaper:makeACMPaper,makeACSPaper:makeACSPaper,makeAPSPaper:makeAPSPaper,makeArxivPaper:makeArxivPaper,makeBioRxivPaper:makeBioRxivPaper,makeCVFPaper:makeCVFPaper,makeIEEEPaper:makeIEEEPaper,makeIJCAIPaper:makeIJCAIPaper,makeIOPPaper:makeIOPPaper,makeJMLRPaper:makeJMLRPaper,makeNaturePaper:makeNaturePaper,makeNeuripsPaper:makeNeuripsPaper,makeOpenReviewBibTex:makeOpenReviewBibTex,makeOpenReviewPaper:makeOpenReviewPaper,makePaper:makePaper,makePMCPaper:makePMCPaper,makePMLRPaper:makePMLRPaper,makePNASPaper:makePNASPaper,makePubMedPaper:makePubMedPaper,makeSpringerPaper:makeSpringerPaper,makeWileyPaper:makeWileyPaper,tryCrossRef:tryCrossRef,tryDBLP:tryDBLP,tryPreprintMatch:tryPreprintMatch,tryPWCMatch:tryPWCMatch,trySemanticScholar:trySemanticScholar}); \ No newline at end of file +`+"}"},makeOpenReviewPaper=async e=>{var t=await fetchOpenReviewNoteJSON(e),r=await fetchOpenReviewForumJSON(e),t=t.notes[0],r=r.notes,i=t.content.title,n=t.content.authors.join(" and "),a=bibtexToString(t.content._bibtex||makeOpenReviewBibTex(t,e)),o=bibtexToObject(a),s=o.citationKey,o=o.year;let l;l=t.pdf?"https://openreview.net/pdf?id="+t.id:(t.html||e).replace("/forum?id=","/pdf?id=");const c=t.invitation.split("/");let p=c[0].split(".")[0],u=c.slice(1).join("/").split("-")[0].replaceAll("/"," ").replace(" Conference",""),d=p,f=!1;global.overrideORConfs.hasOwnProperty(p)&&(d=global.overrideORConfs[p],f=!0),f&&(u=u.replace(d,""),p=d);e=(p+" "+u).replace(/ \d\d\d\d/g,"").replace(/\s\s+/g," "),t=`OR-${p}-${o}_`+t.id;let h,g,m,y="";return(h=r.filter(e=>e&&e.content&&-1<["Final Decision","Paper Decision","Acceptance Decision"].indexOf(e.content.title)))&&00===t?e+"ed":e).join(" "),m=g+` @ ${e} (${o})`,g.toLowerCase().indexOf("rejected")<0&&(y=e)),{author:n,bibtex:a,id:t,key:s,note:m="Anonymous"===n?`Under review @ ${e} (${o}) (${(new Date).toLocaleDateString()})`:m,pdfLink:l,title:i,venue:y,year:o}},makeBioRxivPaper=async e=>{var t=e.replace(".full.pdf",""),r="https://api.biorxiv.org//details/biorxiv/"+e.split("/").slice(-2).join("/").replace(".full.pdf","").split("v")[0];const i=await fetch(r).then(e=>e.json());if("ok"!==i.messages[0].status)throw new Error(r+" returned "+i.messages[0].status);const n=i.collection.last(),a=await fetchText(t),o=(new DOMParser).parseFromString(a.replaceAll("\n",""),"text/html");r=o.querySelector(".bibtext a").getAttribute("href");const s=bibtexToString(await(await fetch(r)).text());var t=extractAuthor(s),r=await parseIdFromUrl(e),l=s.split("\n")[0].split("{")[1].replace(",","").trim(),e=cleanBiorxivURL(e)+".full.pdf",c=n.title,p=n.date.split("-")[0];return{author:t,bibtex:s,id:r,key:l,note:"",pdfLink:e,title:c,venue:"",year:p}},makePMLRPaper=async e=>{var t=e.split("/").last().split(".")[0],r=await parseIdFromUrl(e);const i=e.includes(".html")?e:e.split("/").slice(0,-2).join("/")+`/${t}.html`;e=i.replace(".html","")+`/${t}.pdf`;const n=await fetchDom(i);n.getElementById("button-bibtex1").getAttribute("onclick").match(/https.+\.bib/)[0];const a=n.getElementById("bibtex").innerText.replaceAll("\t"," ").replaceAll(/\s\s+/g," ");let o=a;for(const d of a.match(/,\ ?\w+ ?= ?{/g))o=o.replace(d,d.replace(", ",",\n ").replace(" = ","="));o.endsWith("}}")&&(o=o.slice(0,-2)+"}\n}"),o=bibtexToString(o);var s=extractAuthor(o),l=n.getElementsByTagName("h1")[0].innerText,c=extractBibtexValue(o,"year");let p=extractBibtexValue(o,"booktitle").replaceAll("Proceedings of the",""),u=p;note=`Accepted @ ${u} (${c})`;for(const f in global.overridePMLRConfs)if(p.includes(f)){u=global.overridePMLRConfs[f],p=u+" "+c,note="Accepted @ "+p;break}return{author:s,bibtex:o,id:r,key:t,note:note,pdfLink:e,title:l,venue:u,year:c}},findACLValue=(e,t)=>{return queryAll(e,"dt").filter(e=>e.innerText.includes(t))[0].nextElementSibling.innerText},makeACLPaper=async e=>{e=e.replace(".pdf","");const t=await fetchDom(e);e=t.getElementById("citeBibtexContent");if(e){var r=t.getElementById("title").innerText,e=bibtexToString(e.innerText);const l=bibtexToObject(e);var i=l.year,n=l.author.replace(/\s+/g," ").split(" and ").map(e=>e.split(",").map(e=>e.trim()).reverse().join(" ")).join(" and "),a=l.citationKey,o=findACLValue(t,"Venue"),s=findACLValue(t,"PDF");return{author:n,bibtex:e,id:`ACL-${o}-${i}_`+findACLValue(t,"Anthology ID"),key:a,note:`Accepted @ ${o} (${i})`,pdfLink:s,title:r,venue:o,year:i}}},makePNASPaper=async e=>{e=e.replace(".full.pdf","").replace(/\/doi\/e?pdf\//,"/doi/abs/");const t=await fetchDom(e);var r=t.getElementsByTagName("h1")[0].innerText,i=queryAll(t,".authors span[property='author'] a:not([property='email']):not(.orcid-id)").filter(e=>!e.getAttribute("href").includes("mailto:")).map(e=>e.innerText).join(" and "),n=t.querySelector("span[property='datePublished']").innerText.match(/\d{4}/g)[0],a=`PNAS-${n}_`+(e.endsWith("/")?e.split("/").slice(-2):e.split("/").slice(-1))[0];const o=e.includes("/doi/pdf/")||e.includes("/doi/epdf/")?e.replace("/doi/epdf/","/doi/pdf/"):e.replace("/doi/abs/","/doi/pdf/").replace("/doi/full/","/doi/pdf/");var e=Array.from(t.querySelector(".core-container").getElementsByTagName("a")).map(e=>e.getAttribute("href")).filter(e=>e?.includes("https://doi.org"))[0].split("/").slice(-2).join("/"),s="doi:"+e;return{author:i,bibtex:bibtexToString(`@article{${s}, author={${i}}, title={${r}}, journal = {Proceedings of the National Academy of Sciences}, year={${n}}, doi={${e}}, eprint={${o}}, URL={${o.replace("/doi/pdf/","/doi/abs/")}} }`),id:a,key:s,note:`Published @ PNAS (${n})`,pdfLink:o,title:r,venue:"PNAS",year:n}},makeNaturePaper=async e=>{var t=(e=e.replace(".pdf","").split("#")[0])+".pdf",r=e.split("/").last();const i=await fetchDom(e);e=i.querySelector("h1.c-article-title").innerText;const n=queryAll(i,"ul.c-article-author-list li").map(e=>e.innerText.replace(/(\ ?,)|&|…|\d/g,"").split(/orcid/i)[0].trim()).filter(e=>0e.innerText).filter(e=>e.includes("https://doi.org"))[0];var l=""+n.split(" ")[1]+a+firstNonStopLowercase(e);let c={citationKey:l,entryType:"article",author:n,title:e,journal:o,year:a};s&&(c.doi=s,c.url="https://doi.org/"+s);var p=bibtexToString(c);return{author:n,bibtex:p,id:r,key:l,note:`Published @ ${o} (${a})`,pdfLink:t,title:e,venue:o,year:a}},makeACSPaper=async e=>{const t=(e=e.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0]).replace("/abs/","/").split("/doi/")[1];console.log("doi: ",t);e=`https://pubs.acs.org/action/downloadCitation?doi=${t}&include=cit&format=bibtex&direct=true`,e=await fetchText(e);const r=bibtexToObject(e);var i=r.author.replaceAll("\n","").trim(),n=r.title.trim(),a=r.year.trim(),o=r.citationKey.trim(),s="https://pubs.acs.org/doi/pdf/"+t,l=`Published @ ${r.journal} (${r.year})`;return{author:i,bibtex:e,id:"ACS_"+t.replaceAll(".","").replaceAll("/",""),key:o,note:l,pdfLink:s,title:n,venue:r.journal,year:a}},makeIOPPaper=async e=>{(e=e.split("#")[0]).endsWith("/pdf")&&(e=e.slice(0,-4));var t=await fetchDom(e),t=queryAll(t,".btn-multi-block a").filter(e=>"BibTeX"===e.innerText).map(e=>e.getAttribute("href"))[0],t="https://"+parseUrl(e).host+t,t=await fetchText(t);const r=bibtexToObject(t);var i=r.author.replaceAll("\n","").trim(),n=r.title.trim(),a=r.year.trim(),o=r.citationKey.trim(),s=e+"/pdf",l=r.journal,c=`Published @ ${l} (${a})`;const p=e.split("/article/").last();return{author:i,bibtex:t,id:"IOPscience_"+p.replaceAll(".","").replaceAll("/",""),key:o,note:c,pdfLink:s,title:n,venue:l,year:a}},makeJMLRPaper=async e=>{var t=(e=(e=(e=e.includes("/papers/volume")?e.replace("/papers/volume","/papers/v"):e).endsWith(".pdf")?e.split("/").slice(0,-1).join("/"):e).replace(".html","")).split("/").last(),r=e+".bib",r=await fetchText(r);const{author:i,year:n,title:a,citationKey:o}=bibtexToObject(r);return{author:i,bibtex:r,id:`JMLR-${n}_`+t,key:o.trim(),note:`Published @ JMLR (${n})`,pdfLink:e.replace("/papers/v","/papers/volume")+`/${t}.pdf`,title:a,venue:"JMLR",year:n}},makePMCPaper=async e=>{var t=e.match(/PMC\d+/)[0].replace("PMC",""),r=e.split("PMC"+t)[0]+"PMC"+t;const i=await(await fetch(`https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=${t}&download=true`)).json();var n=(i["epub-date"]||i.issued)["date-parts"][0][0],a=i.author.map(e=>e.given+" "+e.family).join(" and "),o=i["container-title"].split(" ").map(e=>e.capitalize()).join(" "),s=i.title,t=`PMC-${n}_`+t,l=""+i.author[0].family+n+firstNonStopLowercase(s),c=bibtexToString({entryType:"article",citationKey:l,journal:o,issn:i.ISSN,volume:i.volume,page:i.page,doi:i.DOI,PMID:i.PMID,PMCID:i.PMCID,publisher:i.publisher,author:a,title:s});let p;if(isPdfUrl(e))p=e;else{const f=i.DOI.split("/")[1].split("-");var e=f[0].match(/\d+/)[0],u=f[1].replace(f[1].match(/^0*/)[0],""),d=f[2].replace(f[2].match(/^0*/)[0],"");p=r+`/pdf/${e}_${u}_Article_${d}.pdf`}return{author:a,bibtex:c,id:t,key:l,note:`Published @ ${o} (${n})`,pdfLink:p,title:s,venue:o,year:n}},makePubMedPaper=async e=>{const t=await fetchDom(e.split("?")[0]),r=Array.from(t.getElementsByTagName("meta")).filter(e=>e.getAttribute("name")?.includes("citation_")),i=Object.fromEntries(r.map(e=>[e.getAttribute("name").replace("citation_",""),e.getAttribute("content")])),n=document.querySelector("div.authors-list").innerText.replace(/\d/gi,"").split(",").map(e=>e.trim()).join(" and ");var e=i.title,a=i.journal_title,o=i.date.split("/")[2],s=`PubMed-${o}_`+i.pmid,l=""+n.split(" and ")[0].split(" ").last()+o+firstNonStopLowercase(i.title),c={entryType:"article",citationKey:l,publisher:i.publisher,doi:i.doi,issn:i.issn,journal:a,year:o,author:n},c=bibtexToString(c),p=`Accepted @ ${journal} (${o})`;return{author:n,bibtex:c,id:s,key:l,note:p,pdfLink:"",title:e,venue:a,year:o}},makeIJCAIPaper=async e=>{const t=e.endsWith(".pdf")?e.replace(".pdf","").split("/").last().match(/[1-9]\d*/)[0]:e.split("/").last();e=e.match(/proceedings\/\d+/gi)[0].split("/")[1];const r=(await fetchText(`https://www.ijcai.org/proceedings/${e}/bibtex/`+t)).replace(/}\n/gi,"},\n");var i=bibtexToObject(r.split("\n").filter(e=>!/note\s+=/gi.test(e)).join("\n")),n=i.citationKey,a=i.title,i=flipAndAuthors(i.author),o=`IJCAI-${e}_`+t,s=`Accepted @ IJCAI (${e})`,l=t.padStart(4,0);return{author:i,bibtex:r,id:o,key:n,note:s,pdfLink:`https://www.ijcai.org/proceedings/${e}/${l}.pdf`,title:a,venue:"IJCAI",year:e}},makeACMPaper=async e=>{let t;t=isPdfUrl(e)?e:e.replace(/\/doi\/?(abs|full)?\//,"/doi/pdf/");const r=await fetchDom(e.replace("/doi/pdf/","/doi/"));let i,n,a,o,s,l,c,p;var u=extractDataFromDCMetaTags(r);if(u)({author:i,year:n,title:a,venue:o,key:s,doi:l,bibtex:c,note:p}=u);else{a=r.querySelector(".citation__title").innerText,i=queryAll(r,"ul[ariaa-label='authors'] li.loa__item .loa__author-name").map(e=>e.innerText.replace(",","").trim()).join(" and ");const d=r.querySelector(".issue-item__detail a").innerText;o=d.split("'")[0].trim(),n="20"+d.split("'")[1].split(":")[0].trim(),l=t.split("/doi/pdf/")[1],p=`Accepted @ ${o} (${n})`,s=l,c=bibtexToString({entryType:"article",citationKey:l,journal:o,author:i,title:a,year:n,publisher:"Association for Computing Machinery",address:"New York, NY, USA",url:e.replace("/doi/pdf/","/doi/")})}u=`ACM-${n}_`+miniHash(l);return{author:i,bibtex:c,id:u,key:s,note:p,pdfLink:t,title:a,venue:o,year:n}},makeIEEEPaper=async e=>{isPdfUrl(e)&&(e=`https://ieeexplore.ieee.org/document/${e.split("/stamp/stamp.jsp?tp=&arnumber=")[1].match(/\d+/)[0]}/`,console.log("url: ",e));const t=await fetchDom(e),r=JSON.parse(Array.from(t.getElementsByTagName("script")).filter(e=>e.innerHTML?.includes("metadata="))[0].innerHTML.split("metadata=")[1].split(/};\s*/)[0]+"}");var i=r.title,n=r.authors.map(e=>e.name).join(" and "),a=r.publicationYear,e=""+parseUrl(e).origin+r.pdfUrl,o=r.publicationTitle,s=r.articleId;return{author:n,bibtex:bibtexToString({entryType:"article",citationKey:s,journal:o,volume:r.volume,pages:r.startPage+"-"+r.endPage,doi:r.doi,title:i,year:a,author:n}),id:`IEEE-${a}_`+s,key:s,note:`Accepted @ ${o} (${a})`,pdfLink:e,title:i,venue:o,year:a}},makeSpringerPaper=async t=>{const e=[...global.sourceExtras.springer.types,"content/pdf"];var r=e.find(e=>t.includes(`/${e}/`));if(!r)throw new Error(`Could not find Springer type for ${t} (known: ${e.join(", ")})`);var i=t.split(`/${r}/`)[1].split("?")[0].replace(".pdf",""),n=await fetchCrossRefDataForDoi(i);if(!n)throw new Error("Aborting Springer paper parsing, see error above");var{author:a,bibtex:o,citationKey:s,year:l,title:c,venue:p}=n;return{author:a,bibtex:o,id:`Springer-${l}_`+miniHash(i),key:s,note:`Published @ ${p} (${l})`,pdfLink:n.pdf??("content/pdf"===r?t:t.replace(`/${r}/`,"/content/pdf/")+".pdf"),title:c,venue:p,year:l,extra:{url:"https://doi.org/"+i}}},makeAPSPaper=async e=>{e=e.split("#")[0];var[t,r]=parseUrl(e).pathname.split("/").slice(1,3),i=e.split(`/${t}/${r}/`).last(),n=e.replace(`/${t}/${r}/`,`/${t}/export/`),n=await fetchText(n+"?type=bibtex&download=true"),a=bibtexToObject(n),e=e.replace(`/${t}/${r}/`,`/${t}/pdf/`),r=`APS-${a.year}_`+miniHash(i),t=a.journal??a.publisher,i=(await readJournalAbbreviations(),global.journalAbbreviations[miniHash(t)]??t),t=`Published @ ${i} (${a.year})`;return{author:flipAndAuthors(a.author),bibtex:n,id:r,key:a.citationKey,note:t,pdfLink:e,title:a.title,venue:i,year:a.year}},makeWileyPaper=async e=>{const t=e.replace(/\/doi\/(abs|epdf|full)\//g,"/doi/pdf/");e=t.replace("/doi/pdf/","/doi/abs/");const r=await fetchDom(e);var e=queryAll("meta[name=citation_author]").map(e=>e.getAttribute("content")).join(" and "),i=r.querySelector("meta[name=citation_journal_title]").getAttribute("content"),n=r.querySelector("meta[name=citation_title]").getAttribute("content"),a=r.querySelector("meta[name=citation_publisher]").getAttribute("content"),o=r.querySelector("meta[name=citation_publication_date]")?.getAttribute("content")?.split("/")[0]??r.querySelector("meta[name=citation_online_date]")?.getAttribute("content")?.split("/")[0],s=r.querySelector("meta[name=citation_doi]").getAttribute("content"),l=`Published @ ${i} (${o})`,c=`Wiley-${o}_`+miniHash(s);return{author:e,bibtex:bibtexToString({citationKey:s,entryType:"article",title:n,author:e,year:o,doi:s,publisher:a,journal:i}),id:c,key:s,note:l,pdfLink:t,title:n,venue:i,year:o}},makeScienceDirectPaper=async e=>{var e=e.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0],t=await fetchText(`https://www.sciencedirect.com/sdfe/arp/cite?pii=${e}&format=text%2Fx-bibtex&withabstract=false`),{author:r,journal:i,year:n,title:a,citationKey:o}=bibtexToObject(t),s=`Published @ ${i} (${n})`;return{author:r,bibtex:t,id:`ScienceDirect-${n}_`+miniHash(e),key:o,note:s,pdfLink:"https://reader.elsevier.com/reader/sd/pii/"+e,title:a,venue:i??"Science Direct",year:n}},makeSciencePaper=async e=>{let t,r,i,n,a,o,s,l,c,p,u;o="https://science.org/doi/pdf/"+(p=(p=noParamUrl(e).split("/doi/")[1]).startsWith("10.")?p:p.split("/").slice(1).join("/")),u="https://science.org/doi/full/"+p;var e=await fetchCrossRefDataForDoi(p);return e?({author:t,bibtex:r,title:s,venue:l,year:c}=e,n=e.citationKey,a=`Published @ ${l} (${c})`):(e=await fetchDom(u),{author:t,year:c,publisher,title:s,venue:l,key:n,bibtex:r,note:a}=extractDataFromDCMetaTags(e)),i=`Science-${c}_`+miniHash(p),{author:t,bibtex:r,id:i,key:n,note:a,pdfLink:o,title:s,venue:l,year:c}},makeFrontiersPaper=async e=>{e=e.replace(/\/pdf$/,"/full");var t=noParamUrl(e).split("/articles/")[1].split("/full")[0],r=await fetchText(`https://www.frontiersin.org/articles/${t}/bibTex`);const i=Object.fromEntries(Object.entries(bibtexToObject(r)).map(([e,t])=>["citationKey"===e||"entryType"===e?e:e.toLowerCase(),t]));i.author=flipAndAuthors(i.author),delete i.abstract;var{author:r,journal:n,year:a,title:o,citationKey:s}=i,l=`Published @ ${n} (${a})`;return{author:r,bibtex:bibtexToString(i),id:`Frontiers-${a}_`+miniHash(t),key:s,note:l,pdfLink:e.replace(/\/full$/,"/pdf"),title:o,venue:n,year:a}},tryPWCMatch=async e=>{let t;var r={type:"papersWithCode",pwcPrefs:await getStorage("pwcPrefs")??{},paper:e},{url:r,note:i,venue:n,pubYear:a}=await sendMessageToBackground(r)??{};return r&&!e.codeLink?log("[PapersWithCode] Discovered a code repository:",r):log("[PapersWithCode] No code repository found"),n&&!e.venue?(log("[PapersWithCode] Found a publication venue:",n),e=bibtexToObject(e.bibtex),t=bibtexToString({...e,year:a,journal:n})):log("[PapersWithCode] No publication found"),{codeLink:r,note:i,venue:n,bibtex:t}},tryCrossRef=async e=>{try{var t="https://api.crossref.org/works?rows=1&mailto=schmidtv%40mila.quebec&select=event%2Ctitle&query.title="+encodeURI(e.title);const i=await fetch(t).then(e=>e.json());if("ok"!==i.status)return log(`[Crossref] ${t} returned `+i.message.status),{note:null};if(0===i.message.items.length)return{note:null};if(i.message.items[0].title[0].toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," ")!==e.title.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," "))return{note:null};if(!i.message.items[0].event||!i.message.items[0].event.name)return{note:null};info("Found a CrossRef match");var r=i.message.items[0].event.name.trim();return{venue:r,note:`Accepted @ ${r} -- [crossref.org]`}}catch(e){return logError("[Crossref]",e),{note:null}}},tryDBLP=async e=>{try{var t,r,i,n,a=encodeURI(e.title);const o=await fetch(`https://dblp.org/search/publ/api?q=${a}&format=json`).then(e=>e.json());if(!(o.result&&o.result.hits&&o.result.hits.hit&&o.result.hits.hit.length))return{note:null};for(const s of o.result.hits.hit.sort((e,t)=>parseInt(e.info.year,10)-parseInt(t.info.year,10)))if(decodeHtml(s.info.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," "))===e.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," ")&&"CoRR"!==s.info.venue)return info("Found a DBLP match"),t=await fetchText(s.info.url+".bib"),r=miniHash(s.info.venue),await readJournalAbbreviations(),i=(global.journalAbbreviations[r]??s.info.venue).trim(),n=s.info.year,s.info.url,{venue:i,note:`Accepted @ ${i} ${n} -- [dblp.org]`,bibtex:t};return{note:null}}catch(e){return logError("[DBLP]",e),{note:null}}},trySemanticScholar=async t=>{try{var e=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURI(t.title)}&fields=title,venue,year,authors,externalIds,url&limit=50`);if(e&&e.data&&0e.name).join(" and ");let e=o.externalIds.DOI;return e=e&&e.replaceAll("_","\\{_}"),{venue:r,note:n,bibtex:bibtexToString({entryType:"article",citationKey:miniHash(o.authors[0].name.split(" ").last())+i+firstNonStopLowercase(t.title),title:t.title,author:a,journal:r,year:i,doi:e,bibSource:"Semantic Scholar "+o.url})}}}catch(e){logError("[SemanticScholar]",e)}},tryGoogleScholar=async e=>{return await sendMessageToBackground({type:"google-scholar",paper:e})},tryPreprintMatch=async(e,t=!1)=>{let r,i,n,a,o={},s=["DBLP","SemanticScholar","CrossRef","GoogleScholar"],l=[silentPromiseTimeout(tryDBLP(e)),silentPromiseTimeout(trySemanticScholar(e)),silentPromiseTimeout(tryGoogleScholar(e)),silentPromiseTimeout(tryCrossRef(e))];t&&(l.push(silentPromiseTimeout(tryPWCMatch(e))),s.push("PapersWithCode"));for(var[c,p]of Object.entries(s)){if(o[p]=await l[c],{note:r,venue:i,bibtex:n}=o[p]??{},r)break;log(`[${p}] No publication found`)}return t&&(t="PapersWithCode",o.hasOwnProperty(t)||(o[t]=await l[t]),o[t].codeLink&&!e.codeLink&&(a=o[t].codeLink)),{note:r,venue:i,bibtex:n,code:a}},initPaper=async e=>{e.note||(e.note=""),e.md=`[${e.title}](${e.pdfLink})`,e.tags=[],e.codeLink="",e.favorite=!1,e.favoriteDate="",e.addDate=(new Date).toJSON(),e.lastOpenDate=e.addDate,e.count=1,e.code={};for(const t in e)e.hasOwnProperty(t)&&"string"==typeof e[t]&&(e[t]=e[t].trim());return e=await autoTagPaper(e),validatePaper(e),e},autoTagPaper=async r=>{try{var e,i,n=await getStorage("autoTags");if(!n||!n.length)return r;let t=new Set;for(const a of n)a.tags?.length&&(a.title||a.author)&&(e=!a.title||new RegExp(a.title,"i").test(r.title),i=!a.author||new RegExp(a.author,"i").test(r.author),e&&i&&a.tags.forEach(e=>t.add(e)));return r.tags=Array.from(t).sort(),r.tags.length&&log("Automatically adding tags:",r.tags),r}catch(e){return log("Error auto-tagging:",e),log("Paper:",r),r}},makePaper=async(e,t)=>{let r;if(e.arxiv)(r=await makeArxivPaper(t)).source="arxiv";else if(e.neurips)(r=await makeNeuripsPaper(t)).source="neurips";else if(e.cvf)(r=await makeCVFPaper(t)).source="cvf";else if(e.openreview)(r=await makeOpenReviewPaper(t)).source="openreview";else if(e.biorxiv)(r=await makeBioRxivPaper(t)).source="biorxiv";else if(e.pmlr)(r=await makePMLRPaper(t)).source="pmlr";else if(e.acl)(r=await makeACLPaper(t))&&(r.source="acl");else if(e.pnas)(r=await makePNASPaper(t))&&(r.source="pnas");else if(e.nature)(r=await makeNaturePaper(t))&&(r.source="nature");else if(e.acs)(r=await makeACSPaper(t))&&(r.source="acs");else if(e.iop)(r=await makeIOPPaper(t))&&(r.source="iop");else if(e.jmlr)(r=await makeJMLRPaper(t))&&(r.source="jmlr");else if(e.pmc)(r=await makePMCPaper(t))&&(r.source="pmc");else if(e.ijcai)(r=await makeIJCAIPaper(t))&&(r.source="ijcai");else if(e.acm)(r=await makeACMPaper(t))&&(r.source="acm");else if(e.ieee)(r=await makeIEEEPaper(t))&&(r.source="ieee");else if(e.springer)(r=await makeSpringerPaper(t))&&(r.source="springer");else if(e.aps)(r=await makeAPSPaper(t))&&(r.source="aps");else if(e.wiley)(r=await makeWileyPaper(t))&&(r.source="wiley");else if(e.sciencedirect)(r=await makeScienceDirectPaper(t))&&(r.source="sciencedirect");else if(e.science)(r=await makeSciencePaper(t))&&(r.source="science");else{if(!e.frontiers)throw new Error("Unknown paper source: "+JSON.stringify({is:e,url:t}));(r=await makeFrontiersPaper(t))&&(r.source="frontiers")}if(void 0!==r)return initPaper(r)},findFuzzyPaperMatch=(e,t)=>{t=miniHash(t.title);if(e.hasOwnProperty(t)){const r=e[t];e=r.find(t=>!global.preprintSources.some(e=>t.toLowerCase().startsWith(e)));return e?e:r[0]}return null};"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={autoTagPaper:autoTagPaper,decodeHtml:decodeHtml,fetchArxivXML:fetchArxivXML,fetchCrossRefDataForDoi:fetchCrossRefDataForDoi,fetchCvfHTML:fetchCvfHTML,fetchDom:fetchDom,fetchOpenReviewForumJSON:fetchOpenReviewForumJSON,fetchOpenReviewNoteJSON:fetchOpenReviewNoteJSON,fetchSemanticsScholarDataForDoi:fetchSemanticsScholarDataForDoi,fetchText:fetchText,findACLValue:findACLValue,findFuzzyPaperMatch:findFuzzyPaperMatch,flipAndAuthors:flipAndAuthors,flipAuthor:flipAuthor,initPaper:initPaper,makeACLPaper:makeACLPaper,makeACMPaper:makeACMPaper,makeACSPaper:makeACSPaper,makeAPSPaper:makeAPSPaper,makeArxivPaper:makeArxivPaper,makeBioRxivPaper:makeBioRxivPaper,makeCVFPaper:makeCVFPaper,makeIEEEPaper:makeIEEEPaper,makeIJCAIPaper:makeIJCAIPaper,makeIOPPaper:makeIOPPaper,makeJMLRPaper:makeJMLRPaper,makeNaturePaper:makeNaturePaper,makeNeuripsPaper:makeNeuripsPaper,makeOpenReviewBibTex:makeOpenReviewBibTex,makeOpenReviewPaper:makeOpenReviewPaper,makePaper:makePaper,makePMCPaper:makePMCPaper,makePMLRPaper:makePMLRPaper,makePNASPaper:makePNASPaper,makePubMedPaper:makePubMedPaper,makeSpringerPaper:makeSpringerPaper,makeWileyPaper:makeWileyPaper,tryCrossRef:tryCrossRef,tryDBLP:tryDBLP,tryPreprintMatch:tryPreprintMatch,tryPWCMatch:tryPWCMatch,trySemanticScholar:trySemanticScholar}); \ No newline at end of file From cbda9d68ea8906f89cb3c54cb49e572f7f4c9294 Mon Sep 17 00:00:00 2001 From: vict0rsch Date: Fri, 19 Aug 2022 21:22:14 +0100 Subject: [PATCH 02/80] PAT input functional --- src/options/options.css | 24 ++++++++++++++++++++++++ src/options/options.html | 23 +++++++++++++++++++++++ src/options/options.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) diff --git a/src/options/options.css b/src/options/options.css index 9e14f27d..a9cdea67 100644 --- a/src/options/options.css +++ b/src/options/options.css @@ -428,3 +428,27 @@ input { opacity: 0.6; } } + +/* +--------------------- +----- SYNCING ----- +--------------------- +*/ + +#pat-input { + margin-left: 1rem; + width: 350px; +} +#save-pat { + margin-left: 1rem; + background-color: rgb(27, 159, 7); + color: rgb(223, 223, 223); +} +#delete-pat { + margin-left: 2rem; + background-color: rgb(196, 18, 18); + color: rgb(223, 223, 223); +} +#pat-feedback { + color: rgb(150, 102, 13); +} diff --git a/src/options/options.html b/src/options/options.html index 700c4754..08e96edc 100644 --- a/src/options/options.html +++ b/src/options/options.html @@ -442,6 +442,29 @@
Import papers

+
+

Online synchronization

+ +

Explain

+ +

Generate new Github Personal Access + Token

+ +
+ + + + +
+

+

+
+
+
+ +
+

Local file storage

diff --git a/src/options/options.js b/src/options/options.js index 0bb62331..015ad78f 100644 --- a/src/options/options.js +++ b/src/options/options.js @@ -902,6 +902,36 @@ const setupSourcesSelection = async () => { } }; +// --------------------- +// ----- SYNCING ----- +// --------------------- + +const setupSync = () => { + addListener("save-pat", "click", async () => { + const pat = val("pat-input"); + console.log(pat); + if (!pat) { + setHTML("pat-feedback", "Invalid PAT"); + return; + } + const githubGist = new GithubGist.default({ + personalAccessToken: pat, + appIdentifier: "PaperMemorySync", + isPublic: false, + }); + try { + await githubGist.touch(); + + console.log("Gist ID", githubGist.id); + console.log("Github Owner Username", githubGist.ownerUsername); + } catch (e) { + // gist initialization failed. + console.log(e); + setHTML("pat-feedback", e); + } + }); +}; + // ---------------------------- // ----- Document Ready ----- // ---------------------------- @@ -918,4 +948,5 @@ const setupSourcesSelection = async () => { setupSourcesSelection(); setupTitleFunction(); setupDataManagement(); + setupSync(); })(); From 93861ba4eff8d8ac246c0900560756182e243385 Mon Sep 17 00:00:00 2001 From: vict0rsch Date: Sat, 20 Aug 2022 00:37:50 +0100 Subject: [PATCH 03/80] add `sync.js` --- gulpfile.js | 1 + src/shared/js/utils/sync.js | 29 +++++++++++++++++++++++++++++ src/shared/min/utils.min.js | 4 ++-- 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 src/shared/js/utils/sync.js diff --git a/gulpfile.js b/gulpfile.js index 27db7bbd..d8a83e19 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -37,6 +37,7 @@ function utilsJS() { "src/shared/js/utils/miniquery.js", "src/shared/js/utils/config.js", "src/shared/js/utils/gist.js", + "src/shared/js/utils/sync.js", "src/shared/js/utils/levenshtein.js", "src/shared/js/utils/bibtexParser.js", "src/shared/js/utils/functions.js", diff --git a/src/shared/js/utils/sync.js b/src/shared/js/utils/sync.js new file mode 100644 index 00000000..593ef78b --- /dev/null +++ b/src/shared/js/utils/sync.js @@ -0,0 +1,29 @@ +const getGist = async (pat, store = true) => { + if (!pat) { + pat = await getStorage("syncPAT"); + } + if (!pat) + return { + ok: false, + payload: "noPAT", + }; + + const githubGist = new GithubGist.default({ + personalAccessToken: pat, + appIdentifier: "PaperMemorySync", + isPublic: false, + }); + + try { + await githubGist.touch(); + store && (await setStorage("syncPAT", pat)); + return { ok: true, payload: { gist: githubGist, pat } }; + } catch (e) { + console.log(e); + return { + ok: false, + payload: "wrongPAT", + error: e, + }; + } +}; diff --git a/src/shared/min/utils.min.js b/src/shared/min/utils.min.js index 3d2da3e4..85af892b 100644 --- a/src/shared/min/utils.min.js +++ b/src/shared/min/utils.min.js @@ -1,4 +1,4 @@ -const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:findEl("memory-container--"+e).querySelector("."+t),fadeOut=(e,t=250,r=()=>{})=>{(e=findEl(e)).style.transition=t+"ms",e.style.opacity=0,setTimeout(()=>{e.style.display="none",r()},t)},fadeIn=(e,t="block",r=250,i=()=>{})=>{(e=findEl(e)).style.opacity=0,"none"===e.style.display&&(e.style.display=t),setTimeout(()=>{e.style.transition=r+"ms",e.style.opacity=1,setTimeout(()=>{i()},r)},0)},val=(e,t)=>{if(e instanceof HTMLInputElement&&"checkbox"===e.type){if(void 0===t)return e.checked;e.checked=t}if("string"==typeof e&&(e=findEl(e)),void 0===t)return e?e.value:"";e&&(e.value=t)},showId=(e,t="block")=>{let r=findEl(e);r&&(r.style.display=t)},hideId=e=>{(el=findEl(e))&&(el.style.display="none")},setTextId=(e,t)=>{let r=findEl(e);r&&(r.innerText=t)},setHTML=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&(e.innerHTML=t)},dispatch=(e,t)=>{if("string"==typeof e&&(e=findEl(e)),"string"==typeof t){if("focus"===t)return void e.focus();if("blur"===t)return void e.blur();t=new Event(t)}e&&e.dispatchEvent(t)},hasClass=(e,t)=>{let r;if(r="string"==typeof e?findEl(e):e)return r.classList.contains(t)},addClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.add(t)},removeClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.remove(t)},addListener=(e,t,r)=>{(e="string"==typeof e?findEl(e):e)&&e.addEventListener(t,r)},setPlaceholder=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&void 0!==e.placeholder&&(e.placeholder=t)},style=(e,t,r)=>{if(e="string"==typeof e?findEl(e):e){if(void 0===r)return e.style[t];e.style[t]=r}},disable=(e,t=!0)=>{(e="string"==typeof e?findEl(e):e)&&(e.disabled=t)},slideUp=(e,t=250,r=()=>{})=>{(e="string"==typeof e?findEl(e):e)&&(e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.height=e.offsetHeight+"px",e.offsetHeight,e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,window.setTimeout(()=>{e.style.display="none",e.style.removeProperty("height"),e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property"),e.style.removeProperty("box-sizing"),r()},t))},slideDown=(t,r=500,i=()=>{})=>{if(t="string"==typeof t?findEl(t):t){t.style.removeProperty("display");let e=window.getComputedStyle(t).display;"none"===e&&(e="block"),t.style.display=e;var n=t.offsetHeight;t.style.overflow="hidden",t.style.height=0,t.style.paddingTop=0,t.style.paddingBottom=0,t.style.marginTop=0,t.style.marginBottom=0,t.offsetHeight,t.style.transitionProperty="height, margin, padding",t.style.transitionDuration=r+"ms",t.style.height=n+"px",t.style.removeProperty("padding-top"),t.style.removeProperty("padding-bottom"),t.style.removeProperty("margin-top"),t.style.removeProperty("margin-bottom"),window.setTimeout(()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow"),t.style.removeProperty("transition-duration"),t.style.removeProperty("transition-property"),i()},r)}},slideToggle=(e,t=500,r=()=>{})=>("none"===window.getComputedStyle(e).display?slideDown:slideUp)(e,t,r),queryAll=(e,t)=>Array.from(e.querySelectorAll(t));var dummyModule;"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={findEl:findEl,fadeOut:fadeOut,fadeIn:fadeIn,val:val,showId:showId,hideId:hideId,setTextId:setTextId,setHTML:setHTML,dispatch:dispatch,hasClass:hasClass,addClass:addClass,removeClass:removeClass,addListener:addListener,setPlaceholder:setPlaceholder,style:style,disable:disable,slideUp:slideUp,slideDown:slideDown,slideToggle:slideToggle,queryAll:queryAll});const createElementFromHTML=e=>{var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild};Object.defineProperty(Array.prototype,"last",{value:function(e=0){return this.reverse()[e]}}),Object.defineProperty(String.prototype,"capitalize",{value:function(e=!1){return e?this.split(" ").map(e=>e.capitalize()).join(" "):this.charAt(0).toUpperCase()+this.slice(1).toLowerCase()}});var global={},dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule;function _min(e,t,r,i,n){return eBoolean(e.match(/journals\.aps\.org\/\w+\/(abstract|pdf)\//g))],acs:["pubs.acs.org/doi/"],arxiv:["arxiv.org/abs/","arxiv.org/pdf/","scirate.com/arxiv/"],biorxiv:["biorxiv.org/content"],cvf:["openaccess.thecvf.com/content"],frontiers:["frontiersin.org/articles"],ijcai:[e=>/ijcai\.org\/proceedings\/\d{4}\/\d+/gi.test(e)],ieee:["ieeexplore.ieee.org/document/","ieeexplore.ieee.org/abstract/document/","ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber="],iop:["iopscience.iop.org/article/"],jmlr:[e=>e.includes("jmlr.org/papers/v")&&!e.endsWith("/")],nature:["nature.com/articles/"],neurips:["neurips.cc/paper/","nips.cc/paper/"],openreview:["openreview.net/forum","openreview.net/pdf"],pmc:["ncbi.nlm.nih.gov/pmc/articles/PMC"],pmlr:["proceedings.mlr.press/"],pnas:["pnas.org/content/","pnas.org/doi/"],science:[e=>Boolean(e.match(/science\.org\/doi\/?(abs|full|pdf|epdf)?\//g))],sciencedirect:["sciencedirect.com/science/article/pii/","sciencedirect.com/science/article/abs/pii/","reader.elsevier.com/reader/sd/pii/"],springer:[...global.sourceExtras.springer.types.map(e=>`link.springer.com/${e}/`),"link.springer.com/content/pdf/"],wiley:[e=>Boolean(e.match(/onlinelibrary\.wiley\.com\/doi\/(abs|full|pdf|epdf)\//g))]},global.sourcesNames={acl:"Association for Computational Linguistics (ACL)",acm:"Association for Computing Machinery (ACM)",acs:"American Chemical Society (ACS)",aps:"American Physical Society",arxiv:"ArXiv",biorxiv:"BioRxiv",cvf:"Computer Vision Foundation (CVF)",ijcai:"International Joint Conferences on Artificial Intelligence (IJCAI)",iop:"Institute Of Physics (IOP)",jmlr:"Journal of Machine Learning Research (JMLR)",nature:"Nature",neurips:"NeurIPS",openreview:"OpenReview",pmc:"PubMed Central",pmlr:"Proceedings of Machine Learning Research (PMLR)",pnas:"Proceedings of the National Academy of Sciences (PNAS)",science:"Science",sciencedirect:"ScienceDirect",springer:"Springer",wiley:"Wiley"},global.overrideORConfs={"robot-learning":"CoRL",ijcai:"IJCAI"},global.overridePMLRConfs={"Conference on Learning Theory":"CoLT","International Conference on Machine Learning":"ICML","Conference on Uncertainty in Artificial Intelligence":"UAI","Conference on Robot Learning":"CoRL","International Conference on Artificial Intelligence and Statistics":"AISTATS","International Conference on Algorithmic Learning Theory":"ALT"},global.overrideDBLPVenues={"J. Mach. Learn. Res.":"JMLR"},global.consolHeaderStyle="font-family:system-ui;font-size:1.2rem;font-weight:lighter;display:inline-block;border:2px solid #A41716;border-radius: 8px;padding: 16px; margin: 20px;",global.fuzzyTitleMatchMinDist=4,global.defaultTitleFunctionCode=`(paper) => { +const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:findEl("memory-container--"+e).querySelector("."+t),fadeOut=(e,t=250,r=()=>{})=>{(e=findEl(e)).style.transition=t+"ms",e.style.opacity=0,setTimeout(()=>{e.style.display="none",r()},t)},fadeIn=(e,t="block",r=250,i=()=>{})=>{(e=findEl(e)).style.opacity=0,"none"===e.style.display&&(e.style.display=t),setTimeout(()=>{e.style.transition=r+"ms",e.style.opacity=1,setTimeout(()=>{i()},r)},0)},val=(e,t)=>{if(e instanceof HTMLInputElement&&"checkbox"===e.type){if(void 0===t)return e.checked;e.checked=t}if("string"==typeof e&&(e=findEl(e)),void 0===t)return e?e.value:"";e&&(e.value=t)},showId=(e,t="block")=>{let r=findEl(e);r&&(r.style.display=t)},hideId=e=>{(el=findEl(e))&&(el.style.display="none")},setTextId=(e,t)=>{let r=findEl(e);r&&(r.innerText=t)},setHTML=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&(e.innerHTML=t)},dispatch=(e,t)=>{if("string"==typeof e&&(e=findEl(e)),"string"==typeof t){if("focus"===t)return void e.focus();if("blur"===t)return void e.blur();t=new Event(t)}e&&e.dispatchEvent(t)},hasClass=(e,t)=>{let r;if(r="string"==typeof e?findEl(e):e)return r.classList.contains(t)},addClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.add(t)},removeClass=(e,t)=>{let r;(r="string"==typeof e?findEl(e):e)&&r.classList.remove(t)},addListener=(e,t,r)=>{(e="string"==typeof e?findEl(e):e)&&e.addEventListener(t,r)},setPlaceholder=(e,t)=>{(e="string"==typeof e?findEl(e):e)&&void 0!==e.placeholder&&(e.placeholder=t)},style=(e,t,r)=>{if(e="string"==typeof e?findEl(e):e){if(void 0===r)return e.style[t];e.style[t]=r}},disable=(e,t=!0)=>{(e="string"==typeof e?findEl(e):e)&&(e.disabled=t)},slideUp=(e,t=250,r=()=>{})=>{(e="string"==typeof e?findEl(e):e)&&(e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.height=e.offsetHeight+"px",e.offsetHeight,e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,window.setTimeout(()=>{e.style.display="none",e.style.removeProperty("height"),e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property"),e.style.removeProperty("box-sizing"),r()},t))},slideDown=(t,r=500,i=()=>{})=>{if(t="string"==typeof t?findEl(t):t){t.style.removeProperty("display");let e=window.getComputedStyle(t).display;"none"===e&&(e="block"),t.style.display=e;var n=t.offsetHeight;t.style.overflow="hidden",t.style.height=0,t.style.paddingTop=0,t.style.paddingBottom=0,t.style.marginTop=0,t.style.marginBottom=0,t.offsetHeight,t.style.transitionProperty="height, margin, padding",t.style.transitionDuration=r+"ms",t.style.height=n+"px",t.style.removeProperty("padding-top"),t.style.removeProperty("padding-bottom"),t.style.removeProperty("margin-top"),t.style.removeProperty("margin-bottom"),window.setTimeout(()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow"),t.style.removeProperty("transition-duration"),t.style.removeProperty("transition-property"),i()},r)}},slideToggle=(e,t=500,r=()=>{})=>("none"===window.getComputedStyle(e).display?slideDown:slideUp)(e,t,r),queryAll=(e,t)=>Array.from(e.querySelectorAll(t));var dummyModule;"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={findEl:findEl,fadeOut:fadeOut,fadeIn:fadeIn,val:val,showId:showId,hideId:hideId,setTextId:setTextId,setHTML:setHTML,dispatch:dispatch,hasClass:hasClass,addClass:addClass,removeClass:removeClass,addListener:addListener,setPlaceholder:setPlaceholder,style:style,disable:disable,slideUp:slideUp,slideDown:slideDown,slideToggle:slideToggle,queryAll:queryAll});const createElementFromHTML=e=>{var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild};Object.defineProperty(Array.prototype,"last",{value:function(e=0){return this.reverse()[e]}}),Object.defineProperty(String.prototype,"capitalize",{value:function(e=!1){return e?this.split(" ").map(e=>e.capitalize()).join(" "):this.charAt(0).toUpperCase()+this.slice(1).toLowerCase()}});var global={},dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule,dummyModule;"undefined"!=typeof window&&(global=window),global.state={dataVersion:0,memoryIsOpen:!1,menuIsOpen:!1,papers:{},papersList:[],paperTags:new Set,pdfTitleFn:null,showFavorites:!1,sortedPapers:[],sortKey:"",papersReady:!1,prefs:{},files:{},ignoreSources:{},lastRefresh:new Date,titleHashToIds:{},urlHashToId:{},memoryItemsPerPage:25,currentMemoryPagination:0},global.descendingSortKeys=["addDate","count","lastOpenDate","favoriteDate","year"],global.select2Options={placeholder:"Tag paper",maximumSelectionLength:5,allowClear:!0,tags:!0,tokenSeparators:[","," "]},global.prefsCheckNames=["checkBib","checkMd","checkDownload","checkPdfTitle","checkFeedback","checkDarkMode","checkDirectOpen","checkStore","checkScirate","checkOfficialRepos","checkPreferPdf","checkPdfOnly","checkNoAuto","checkMdYearVenue"],global.prefsCheckDefaultFalse=["checkDarkMode","checkDirectOpen","checkStore","checkScirate","checkOfficialRepos","checkPdfOnly","checkNoAuto","checkMdYearVenue"],global.prefsStorageKeys=[...global.prefsCheckNames,"pdfTitleFn"],global.sourceExtras={springer:{types:["chapter","article","book","referenceworkentry"]}},global.preprintSources=["arxiv","biorxiv"],global.knownPaperPages={acl:["aclanthology.org/"],acm:["dl.acm.org/doi/"],aps:[e=>Boolean(e.match(/journals\.aps\.org\/\w+\/(abstract|pdf)\//g))],acs:["pubs.acs.org/doi/"],arxiv:["arxiv.org/abs/","arxiv.org/pdf/","scirate.com/arxiv/"],biorxiv:["biorxiv.org/content"],cvf:["openaccess.thecvf.com/content"],frontiers:["frontiersin.org/articles"],ijcai:[e=>/ijcai\.org\/proceedings\/\d{4}\/\d+/gi.test(e)],ieee:["ieeexplore.ieee.org/document/","ieeexplore.ieee.org/abstract/document/","ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber="],iop:["iopscience.iop.org/article/"],jmlr:[e=>e.includes("jmlr.org/papers/v")&&!e.endsWith("/")],nature:["nature.com/articles/"],neurips:["neurips.cc/paper/","nips.cc/paper/"],openreview:["openreview.net/forum","openreview.net/pdf"],pmc:["ncbi.nlm.nih.gov/pmc/articles/PMC"],pmlr:["proceedings.mlr.press/"],pnas:["pnas.org/content/","pnas.org/doi/"],science:[e=>Boolean(e.match(/science\.org\/doi\/?(abs|full|pdf|epdf)?\//g))],sciencedirect:["sciencedirect.com/science/article/pii/","sciencedirect.com/science/article/abs/pii/","reader.elsevier.com/reader/sd/pii/"],springer:[...global.sourceExtras.springer.types.map(e=>`link.springer.com/${e}/`),"link.springer.com/content/pdf/"],wiley:[e=>Boolean(e.match(/onlinelibrary\.wiley\.com\/doi\/(abs|full|pdf|epdf)\//g))]},global.sourcesNames={acl:"Association for Computational Linguistics (ACL)",acm:"Association for Computing Machinery (ACM)",acs:"American Chemical Society (ACS)",aps:"American Physical Society",arxiv:"ArXiv",biorxiv:"BioRxiv",cvf:"Computer Vision Foundation (CVF)",ijcai:"International Joint Conferences on Artificial Intelligence (IJCAI)",iop:"Institute Of Physics (IOP)",jmlr:"Journal of Machine Learning Research (JMLR)",nature:"Nature",neurips:"NeurIPS",openreview:"OpenReview",pmc:"PubMed Central",pmlr:"Proceedings of Machine Learning Research (PMLR)",pnas:"Proceedings of the National Academy of Sciences (PNAS)",science:"Science",sciencedirect:"ScienceDirect",springer:"Springer",wiley:"Wiley"},global.overrideORConfs={"robot-learning":"CoRL",ijcai:"IJCAI"},global.overridePMLRConfs={"Conference on Learning Theory":"CoLT","International Conference on Machine Learning":"ICML","Conference on Uncertainty in Artificial Intelligence":"UAI","Conference on Robot Learning":"CoRL","International Conference on Artificial Intelligence and Statistics":"AISTATS","International Conference on Algorithmic Learning Theory":"ALT"},global.overrideDBLPVenues={"J. Mach. Learn. Res.":"JMLR"},global.consolHeaderStyle="font-family:system-ui;font-size:1.2rem;font-weight:lighter;display:inline-block;border:2px solid #A41716;border-radius: 8px;padding: 16px; margin: 20px;",global.fuzzyTitleMatchMinDist=4,global.defaultTitleFunctionCode=`(paper) => { const title = paper.title.replaceAll("\\n", ''); const id = paper.id; let name = \`\${title} - \${id}\`; @@ -8,7 +8,7 @@ const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:f /!\\ It has to stay in your downloads for PaperMemory to be able to access your papers. /!\\ To be able to open files from this folder instead of re-downloading them, PaperMemory will match their titles and downloaded urls. /!\\ If you change the default title function in the Advanced Options and do not include a paper's title in the file name, PaperMemory may not be able to open the file and will instead open the pdf url. - /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle}),!function i(n,a,o){function s(t,e){if(!a[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=a[t]={exports:{}},n[t][0].call(r.exports,function(e){return s(n[t][1][e]||e)},r,r.exports,i,n,a,o)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;ee.length)&&(r=e.length),r-=t.length,-1!==(e=e.indexOf(t,r))&&e===r},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var r=new Array(t);0>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===i&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,a[o++]=255&t),1===i&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],a=0,o=r-i;a>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(i));return n.join("")}(e,a,o>2]+s[t<<4&63]+"==")):2==i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,a=i.length;n>>1;case"base64":return k(e).length;default:if(n)return i?-1:P(e).length;t=(""+t).toLowerCase(),n=!0}}function t(e,t,r){var i,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var a=this,o=t,s=r,l=a.length;(!s||s<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:f(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):f(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,i,n){var a=1,o=e.length,s=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o/=a=2,s/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n)for(var c=-1,p=r;p>8,i=i%256,n.push(i),n.push(r);return n}(t,e.length-r),e,r,i)}function A(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n>>10&1023|55296),p=56320|1023&p),i.push(p),n+=u}var d=i,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var h="",g=0;gt&&(e+=" ... "),""},u.prototype.compare=function(e,t,r,i,n){if(C(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),l=this.slice(i,n),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i=i||"utf8";for(var a,o,s,l=!1;;)switch(i){case"hex":var c=this,p=e,u=t,d=r,f=(u=Number(u)||0,c.length-u);(!d||(d=Number(d))>f)&&(d=f),(f=p.length)/2e.length)throw new RangeError("Index out of range")}function b(e,t,r,i){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function v(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,4),a.write(e,t,r,i,23,4),r+4}function w(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,8),a.write(e,t,r,i,52,8),r+8}u.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||h(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=t,n=1,a=this[e+--i];0=(n*=128)&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||h(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,i){e=+e,t>>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[t+n]=255&e;0<=--n&&(a*=256);)this[t+n]=e/a&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeIntLE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=0,a=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=r-1,a=1,o=0;for(this[t+n]=255&e;0<=--n&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a>>0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return w(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return w(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,i){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,i||0===i||(i=this.length),t>=e.length&&(t=e.length),(i=0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length);var n=(i=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(a=t;a>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(x,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function E(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}}.call(this)}.call(this,O("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,n){var a,o,s=8*n-i-1,l=(1<>1,p=-7,u=r?n-1:0,d=r?-1:1,n=e[t+u];for(u+=d,a=n&(1<<-p)-1,n>>=-p,p+=s;0>=-p,p+=i;0>1,u=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,f=i?1:-1,a=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,n),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),o=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield n.default.post(e,t,(0,a.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:n}=this,a="https://gist.githubusercontent.com/"+i+`/${n}/raw/${e}/`+this.fileName;return t?null!=r?r(a):o.default.corsAnywhere+a:a},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),a=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>n(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,a.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>n(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>n(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>n(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},n=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),a=n.data;yield this.initialize(a)}),this.initialize=i=>n(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=a.default.githubRateLimit;return n.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]);const levenshtein=(e,t)=>{if(e===t)return 0;e.length>t.length&&(r=e,e=t,t=r);for(var r,i=e.length,n=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,r=(this.match("{",!1),this.pos),i=!1;;){if(!i)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");i="\\"==this.input[this.pos]&&0==i,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,r=!1;;){if(!r){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, + /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle}),!function i(n,a,o){function s(t,e){if(!a[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=a[t]={exports:{}},n[t][0].call(r.exports,function(e){return s(n[t][1][e]||e)},r,r.exports,i,n,a,o)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;ee.length)&&(r=e.length),r-=t.length,-1!==(e=e.indexOf(t,r))&&e===r},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var r=new Array(t);0>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===i&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,a[o++]=255&t),1===i&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],a=0,o=r-i;a>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(i));return n.join("")}(e,a,o>2]+s[t<<4&63]+"==")):2==i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,a=i.length;n>>1;case"base64":return k(e).length;default:if(n)return i?-1:x(e).length;t=(""+t).toLowerCase(),n=!0}}function t(e,t,r){var i,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var a=this,o=t,s=r,l=a.length;(!s||s<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:f(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):f(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,i,n){var a=1,o=e.length,s=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o/=a=2,s/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n)for(var c=-1,p=r;p>8,i=i%256,n.push(i),n.push(r);return n}(t,e.length-r),e,r,i)}function A(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n>>10&1023|55296),p=56320|1023&p),i.push(p),n+=u}var d=i,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var h="",g=0;gt&&(e+=" ... "),""},u.prototype.compare=function(e,t,r,i,n){if(C(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),l=this.slice(i,n),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i=i||"utf8";for(var a,o,s,l=!1;;)switch(i){case"hex":var c=this,p=e,u=t,d=r,f=(u=Number(u)||0,c.length-u);(!d||(d=Number(d))>f)&&(d=f),(f=p.length)/2e.length)throw new RangeError("Index out of range")}function b(e,t,r,i){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function v(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,4),a.write(e,t,r,i,23,4),r+4}function w(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,8),a.write(e,t,r,i,52,8),r+8}u.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||h(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=t,n=1,a=this[e+--i];0=(n*=128)&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||h(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,i){e=+e,t>>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[t+n]=255&e;0<=--n&&(a*=256);)this[t+n]=e/a&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeIntLE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=0,a=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=r-1,a=1,o=0;for(this[t+n]=255&e;0<=--n&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a>>0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return w(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return w(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,i){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,i||0===i||(i=this.length),t>=e.length&&(t=e.length),(i=0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length);var n=(i=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(a=t;a>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function E(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}}.call(this)}.call(this,O("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,n){var a,o,s=8*n-i-1,l=(1<>1,p=-7,u=r?n-1:0,d=r?-1:1,n=e[t+u];for(u+=d,a=n&(1<<-p)-1,n>>=-p,p+=s;0>=-p,p+=i;0>1,u=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,f=i?1:-1,a=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,n),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),o=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield n.default.post(e,t,(0,a.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:n}=this,a="https://gist.githubusercontent.com/"+i+`/${n}/raw/${e}/`+this.fileName;return t?null!=r?r(a):o.default.corsAnywhere+a:a},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),a=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>n(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,a.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>n(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>n(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>n(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},n=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),a=n.data;yield this.initialize(a)}),this.initialize=i=>n(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=a.default.githubRateLimit;return n.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]);const getGist=async(e,t=!0)=>{if(!(e=e||await getStorage("syncPAT")))return{ok:!1,payload:"noPAT"};const r=new GithubGist.default({personalAccessToken:e,appIdentifier:"PaperMemorySync",isPublic:!1});try{return await r.touch(),t&&await setStorage("syncPAT",e),{ok:!0,payload:{gist:r,pat:e}}}catch(e){return console.log(e),{ok:!1,payload:"wrongPAT",error:e}}};function _min(e,t,r,i,n){return e{if(e===t)return 0;e.length>t.length&&(r=e,e=t,t=r);for(var r,i=e.length,n=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,r=(this.match("{",!1),this.pos),i=!1;;){if(!i)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");i="\\"==this.input[this.pos]&&0==i,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,r=!1;;){if(!r){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, `;delete e.entryType,delete e.citationKey;var r,i=Math.max(...Object.keys(e).map(e=>e.length));for(const n in e)e.hasOwnProperty(n)&&e[n]&&(r=e[n].replaceAll(/\s+/g," ").trim(),bkey=n+" ".repeat(i-n.length),t+=` ${bkey} = {${r}}, `);return(t.slice(0,-2)+"\n}").replaceAll("\t"," ").replaceAll("--","-")},extractBibtexValue=(e,t)=>{const r=bibtexToObject(e);return r.hasOwnProperty(t)?r[t]:""},extractAuthor=e=>extractBibtexValue(e,"author").replaceAll("{","").replaceAll("}","").replaceAll("\\","").split(" and ").map(e=>e.split(", ").reverse().join(" ")).join(" and "),logTrace=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={bibtexToObject:bibtexToObject,bibtexToString:bibtexToString,extractBibtexValue:extractBibtexValue,extractAuthor:extractAuthor}),"undefined"!=typeof LOGTRACE&&LOGTRACE),log=(...e)=>{if(logTrace){const s=(new Error).stack;e.push("\n\nLog trace:\n"+s.split("\n").slice(2).join("\n"))}let t="%c%s ",r=!1,i=!1,n=!1,a=!1,o=!1;"[info]"===e[0]?(r=!0,e=e.slice(1)):"[warn]"===e[0]?(i=!0,e=e.slice(1)):"[error]"===e[0]?(n=!0,e=e.slice(1)):"[ok]"===e[0]?(o=!0,e=e.slice(1)):"[debug]"===e[0]&&(a=!0,e=e.slice(1)),e.forEach(e=>{switch(typeof e){case"bigint":case"number":t+="%d ";break;case"string":t+="%s ";break;default:t+="%o "}}),console.log(t,"color: "+(r?"#8BB4F7; font-weight:bold;":i?"#f3bd1e; font-weight:bold;":n?"#FF4F54; font-weight:bold;":o?"#23F62B; font-weight:bold;":a?"#BA357E; font-weight:bold;":"tan"),"[PM]",...e)},info=(...e)=>log("[info]",...e),warn=(...e)=>log("[warn]",...e),debug=(...e)=>log("[debug]",...e),logOk=(...e)=>log("[ok]",...e),logError=(...e)=>log("[error]",...e),getDisplayId=e=>{var t=e;if((e=e.split("_")[0].split(".")[0]).startsWith("OR-")||(e=e.split("-").slice(0,2).join("-")),global.state.papers.hasOwnProperty(t)){const r=global.state.papers[t];if("nature"===r.source){if(r.note.match(/^Published\ @.+\(\d+\)$/)){const i=r.note.split("@")[1].split("(")[0].trim();e+="-"+i.split(" ").map(e=>e[0].toUpperCase()).join("")}e+="-"+r.year}"acs"===r.source&&(e+="-"+r.year),"iop"===r.source&&(e+="-"+r.year)}return e},isObject=e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,isPdfUrl=e=>e.endsWith(".pdf")||e.endsWith("/pdf")||e.includes("openreview.net/pdf")||e.match(/\/e?pdf\//g)||e.includes("ieee.org/stamp/stamp.jsp?tp=&arnumber="),delay=(t,r)=>{let i=0;return(...e)=>{clearTimeout(i),i=setTimeout(t.bind(this,...e),r||0)}},cleanPapers=e=>{let t={...e};return delete t.__dataVersion,t},firstNonStopLowercase=e=>{let t=e.toLowerCase(),r=t.split(" ").map(miniHash);e=r.filter(e=>!global.englishStopWords.has(e));return(0e.toLowerCase().replace(/\W/g,""),fallbackCopyTextToClipboard=e=>{var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{var r=document.execCommand("copy")?"successful":"unsuccessful";log("Fallback: Copying text command was "+r)}catch(e){console.error("Fallback: Oops, unable to copy",e)}document.body.removeChild(t)},copyTextToClipboard=e=>{navigator.clipboard?navigator.clipboard.writeText(e).then(()=>{log("Async: Copying to clipboard was successful!")},e=>{console.error("Async: Could not copy text: ",e)}):fallbackCopyTextToClipboard(e)},parseUrl=e=>{var t=document.createElement("a");return t.href=e,t},downloadTextFile=(e,t,r)=>{var i=document.createElement("a");"text/plain"===r?(e=e.replace(/\\n/g,"%0D%0A").replace(/"/g,""),i.download=t,i.href="data:text/plain,"+e):(e=new Blob([e],{type:r}),i.href=URL.createObjectURL(e),i.download=t),i.click()},eventId=e=>e.target.closest(".memory-container").id.split("--")[1],downloadFile=(e,t)=>{var r;window.ActiveXObject?window.ActiveXObject&&document.execCommand&&((r=window.open(e,"_blank")).document.close(),r.document.execCommand("SaveAs",!0,t||e),r.close()):((r=document.createElement("a")).href=e,r.target="_blank",e=e.substring(e.lastIndexOf("/")+1),r.download=t||e,navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/)&&navigator.userAgent.search("Chrome")<0?document.location=r.href:(t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1}),r.dispatchEvent(t),(window.URL||window.webkitURL).revokeObjectURL(r.href)))},hashCode=e=>e.split("").reduce((e,t)=>(e=(e<<5)-e+t.charCodeAt(0))&e,0),parseCVFUrl=e=>{const t=e.replace("https://openaccess.thecvf.com/content","").slice(1).split("/")[0].split("_");let r,i;i=1===t.length?(r=t[0].slice(0,-4),t[0].slice(-4)):(r=t[0].toUpperCase(),t[1]);e=e.split("/").last().split(".")[0],e=(hashCode(e)+"").replace("-","").slice(0,8),e=`${r}-${i}_`+e;return{conf:r,year:i,id:e}},cleanBiorxivURL=e=>e=(e=e.replace(".full.pdf","")).match(/\d$/)?e:e.split(".").slice(0,-1).join("."),textareaFocusEnd=e=>{setTimeout(()=>{e.selectionStart=e.selectionEnd=1e4},0)},tablerSvg=(e,t,r)=>{switch(t=(t=void 0===t?"":t)&&`id="${t}"`,r=(r=(r=void 0===r?[]:r).filter(e=>e))&&`class="${r.join(" ")}"`,e){case"adjustments":return``;case"circle-x":return``;case"star":return``;case"writing":return``;case"file-symlink":return``;case"link":return``;case"clipboard-list":return``;case"archive":return``;case"external-link":return``;case"file-download":return``;case"cirlce-x":return``;case"settings":return``;case"messages":return``;case"vocabulary":return``;case"database-export":return``;case"eyeglass":return``;case"markdown":return``;case"math-function":return``;default:return""}},stringifyError=e=>{const t=chrome.runtime.id;return e.stack.split("\n").map(e=>e.split(" ").map(e=>e.split(t).last()).join(" ")).join("
")},arraysIdentical=(e,t)=>{var r=e.length;if(r!=t.length)return!1;for(;r--;)if(e[r]!==t[r])return!1;return!0},parseTags=e=>{let t=Array.from(e.selectedOptions,e=>e.value.trim()).filter(e=>e);return t.sort(),t},getPaperEdits=(e,t)=>{let r,i,n,a;return a=t?(r=val("popup-form-note-textarea--"+e),n=val(document.getElementById("popup-form-note--"+e).querySelector(".form-code-input")),i=parseTags(findEl("popup-item-tags--"+e)),findEl("checkFavorite--"+e).checked):(r=val(findEl(e,"form-note-textarea")),n=val(findEl(e,"form-code-input")),i=parseTags(findEl(e,"memory-item-tags")),hasClass("memory-container--"+e,"favorite")),{note:r,tags:i,codeLink:n,favorite:a}},setFormChangeListener=(e,t)=>{let r,i,n,a;t?(r="#popup-item-tags--"+e.replace(".","\\."),n="popup-form-codeLink--"+e,i="popup-form-note-textarea--"+e,a="checkFavorite--"+e,$(r).on("change",delay(monitorPaperEdits(e,t),300)),addListener(n,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(i,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(a,"change",delay(monitorPaperEdits(e,t),300))):(r=".memory-item-tags",n=".form-code-input",i=".form-note-textarea",addEventToClass(n,"keyup",delay(monitorPaperEdits(void 0,t),300)),addEventToClass(i,"keyup",delay(monitorPaperEdits(void 0,t),300)))},monitorPaperEdits=(c,p)=>e=>{let t;t=void 0===c?eventId(e):c;var r=getPaperEdits(t,p),i=global.state.papers[t];let n=!1,a={};for(const l in r){var o=i[l],s=(a[l]=o,r[l]);"tags"===l?arraysIdentical(o,s)||(n=!0):o!==s&&(n=!0)}n&&(console.log("Updating meta data for",t),(p?handlePopupSaveEdits:handleMemorySaveEdits)(t))},cutAuthors=(e,t,r)=>{void 0===t&&(t=140),void 0===r&&(r=", ");let i="";var e=e.split(" and "),n=e[e.length-1];for(const a of e){if(!(5+i.length+r.length+a.length+n.lengthnew Promise(t=>{chrome.runtime.sendMessage(e,e=>{t(e)})}),getStoredFiles=()=>new Promise(t=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},e=>t(e.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt"))))}),noParamUrl=e=>e.split("?")[0].split("#")[0],silentPromiseTimeout=(e,r=5e3)=>{let i;return Promise.race([e,new Promise((e,t)=>i=setTimeout(e,r))]).finally(()=>clearTimeout(i))},shouldWarn=async(e,t=()=>{})=>{if("pdf-title"===e){var r=await getStorage("titleFunctionCode");if(r&&r!==global.defaultTitleFunctionCode)if(!(await getStorage("userWarnings")??{})[e])return t(!0)}return t(!1)},migrateData=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={log:log,info:info,logError:logError,logOk:logOk,debug:debug,warn:warn,getDisplayId:getDisplayId,isObject:isObject,isPdfUrl:isPdfUrl,delay:delay,cleanPapers:cleanPapers,firstNonStopLowercase:firstNonStopLowercase,fallbackCopyTextToClipboard:fallbackCopyTextToClipboard,copyTextToClipboard:copyTextToClipboard,parseUrl:parseUrl,downloadTextFile:downloadTextFile,eventId:eventId,downloadFile:downloadFile,hashCode:hashCode,parseCVFUrl:parseCVFUrl,cleanBiorxivURL:cleanBiorxivURL,textareaFocusEnd:textareaFocusEnd,tablerSvg:tablerSvg,stringifyError:stringifyError,arraysIdentical:arraysIdentical,parseTags:parseTags,getPaperEdits:getPaperEdits,setFormChangeListener:setFormChangeListener,monitorPaperEdits:monitorPaperEdits,cutAuthors:cutAuthors,sendMessageToBackground:sendMessageToBackground,getStoredFiles:getStoredFiles,miniHash:miniHash,noParamUrl:noParamUrl,silentPromiseTimeout:silentPromiseTimeout,shouldWarn:shouldWarn}),async(r,t,e=!0)=>{if(void 0===r)return chrome.storage.local.set({papers:{__dataVersion:t}}),{papers:{__dataVersion:t},success:!0};var i,n,a,o=r.__dataVersion||-1,s=[];let l={...r};try{if(502<=o)return{papers:r,success:!0};e&&backupData({...r}),delete r.__dataVersion;for(const c in r)o<5&&(info("Applying migration 5"),r[c].hasOwnProperty("bibtex")||(r[c].bibtex="",log("Migrating bibtex for "+c)),r[c].pdfLink.endsWith(".pdf")||(r[c].pdfLink=r[c].pdfLink+".pdf"),r[c].codeLink||(r[c].codeLink=""),r[c].source||(r[c].id.includes("NeurIPS")?r[c].source="neurips":r[c].source="arxiv")),o<208&&(info("Applying migration 0.2.8"),"arxiv"!==r[c].source&&r[c].md.includes("https://arxiv.com/abs/")&&(r[c].md=`[${r[c].title}](${r[c].pdfLink})`),"arxiv"!==r[c].source&&r[c].pdfLink.includes("arxiv.org/pdf/")&&(r[c].source="arxiv"),c.match(/^\d/)&&"arxiv"===r[c].source&&(i="Arxiv-"+c,n={...r[c],id:i},r[i]=n,s.push(c))),o<209&&(info("Applying migration 0.2.9"),r[c].hasOwnProperty("favorite")||(r[c].favorite=!1,r[c].favoriteDate="")),o<210&&(info("Applying migration 0.2.10"),"arxiv"===r[c].source&&(a=r[c].pdfLink.match(/v\d+\.pdf/gi))&&0{delete r[e],log("Deleting "+e)}),(l={...r}).__dataVersion=t,e&&chrome.storage.local.set({papers:l},()=>{log("Migrated papers:"),log(l),log("Data version is now "+t)}),{papers:l,success:!0}}catch(e){return log(`Error migrating data from version ${o} to ${t}:`),log(e),{papers:l,success:!1,error:e}}}),logStorage=t=>{chrome.storage.local.get(t,e=>{log(e[t])})},getStorage=async r=>new Promise((t,e)=>{chrome.storage.local.get(r,e=>{t("string"==typeof r?e[r]:e)})}),setStorage=async(r,i,n=()=>{})=>new Promise((e,t)=>{chrome.storage.local.set({[r]:i},()=>{n(),e(!0)})}),deletePaperInStorage=async(e,t)=>{let r=!1;(t=t||(await getStorage("papers")??{})).hasOwnProperty(e)&&(updateDuplicatedUrls(null,e,!0),r=(r=delete global.state.titleHashToIds[miniHash(t[e].title)])&&delete t[e]),r?(setStorage("papers",t),log("Successfully deleted paper",e)):log("Error: no deletion")},getTheme=async()=>{return await getStorage("checkDarkMode")?"dark":"light"},backupData=async r=>{chrome.storage.local.get("papersBackup",({papersBackup:e})=>{void 0===e&&(e={});for(const t of Object.keys(e).map(e=>parseInt(e)).sort((e,t)=>e{log("Backed up data with version: "+r.__dataVersion)})})};function dateDiffInDays(e,t){e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),t=Date.UTC(t.getFullYear(),t.getMonth(),t.getDate());return Math.floor((t-e)/864e5)}const weeklyBackup=async()=>{var e=await getStorage("weeklyBackups")??{};const t=new Date,r=Object.keys(e).map(e=>new Date(e)).sort((e,t)=>e.getTime()-t.getTime());if(0{let e=!1,t;const r=await getStorage("prefs")??{};(e=0===Object.keys(r).length?!0:e)&&(t=await getStorage(global.prefsStorageKeys)??{});let i={};for(const n of global.prefsCheckNames)i[n]=(t??r).hasOwnProperty(n)?(t??r)[n]:!(0<=global.prefsCheckDefaultFalse.indexOf(n));return i.checkOfficialRepos&&(setStorage("pwcPrefs",{official:!0}),delete i.checkOfficialRepos,setStorage("prefs",i)),e&&setStorage("prefs",i),i},getManifestDataVersion=()=>{const e=chrome.runtime.getManifest();return e.version.split(".").map((e,t)=>parseInt(e)*10**(4-2*t)).reduce((e,t)=>e+t)},versionToSemantic=e=>(e=(e-=1e4*(major=parseInt(e/1e4,10)))-100*(minor=parseInt(e/100,10)),`${major}.${minor}.`+e),validatePaper=(e,t=!0)=>{const r={addDate:{type:"string",desc:"the paper's date of addition to the Memory",default:e=>(new Date).toJSON()},author:{type:"string",desc:"` and `-separated authors `${firstName} ${lastName}`"},bibtex:{type:"string",desc:"BibTex citation with new lines (`\n`)"},code:{type:"object",desc:"the paper's code object as returned by the PapersWithCode API",default:e=>({})},codeLink:{type:"string",desc:"the paper's code link",default:e=>""},count:{type:"number",desc:"the paper's number of visits",default:e=>1},extras:{type:"object",desc:"extra information about the paper which may be required per source",optional:!0},favorite:{type:"boolean",desc:"user wants to star the paper",default:e=>!1},favoriteDate:{type:"string",desc:"date the paper was added as a favorite",default:e=>""},id:{type:"string",desc:"Unique PaperMemory ID"},key:{type:"string",desc:"BibTex citation key",default:e=>"defaultKey_"+e.id},lastOpenDate:{type:"string",desc:"When the paper was last opened",default:e=>(new Date).toJSON()},md:{type:"string",desc:"markdown-formatted string `[${title}](${pdfLink})`",default:e=>`[${e.title}](${e.pdfLink})`},note:{type:"string",desc:"the user's note for this paper",default:e=>""},pdfLink:{type:"string",desc:"the link to the paper's pdf"},source:{type:"string",desc:"the paper's source i.e. where it was added to the memory from"},tags:{type:"array[string]",desc:"the user's tags for this paper",default:e=>[]},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication"}};let i=[];for(const l in r)if(e.hasOwnProperty(l)){const c=r[l].type;var n,a=typeof e[l];c.includes("array")||"object"===c?c.includes("array")?Array.isArray(e[l])?(o=c.split("[")[1].replace("]",""),0{let t=!0,r="",i="",n;try{e.__dataVersion||(e.__dataVersion=1);var a,o=await migrateData(e,getManifestDataVersion(),!1);if(!o.success)return i="Could not migrate the data before storing it",o.error&&(i+=":
"+stringifyError(o.error)),{success:!1,message:i};for(const s in n=o.papers)s.startsWith("__")||(paperWarnings=validatePaper(n[s]).warnings)&&0"+paperWarnings.join("
"));r&&(a=await getStorage("papers")??{},setStorage("uploadBackup",a)),t=!1}catch(e){log("prepareOverwriteData error",e),i='
/!\\ OverwriteMemoryError:

'+stringifyError(e),t=!0}return{success:!t,message:i,warning:r,papersToWrite:n}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let r={};if(!e)return r;for(const n in global.knownPaperPages){var i=global.knownPaperPages[n];r[n]=!1;for(const a of i)"string"==typeof a?e.includes(a)&&(r[n]=!0):"function"==typeof a&&(r[n]=a(e))}return r.localFile=isKnownLocalFile(e),r.stored=!t&&await findLocalFile(e),r}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,r,i;const n=e.pdfLink;let a="";switch(e.source){case"arxiv":a="https://arxiv.org/abs/"+e.id.split("-")[1];break;case"neurips":a=n.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":a=n.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":a=n.replace("/pdf?","/forum?");break;case"biorxiv":a=n.replace(".full.pdf","");break;case"pmlr":a=n.split("/").slice(0,-1).join("/")+".html";break;case"acl":a=n.replace(".pdf","");break;case"pnas":a=n.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":a=n.replace(".pdf","");break;case"acs":a=n.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":a=n.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":a=n.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var o=n.match(/PMC\d+/)[0];a=n.split(o)[0]+o;break;case"ijcai":var o=n.replace(".pdf","").split("/").last().match(/[1-9]\d*/),s=n.match(/proceedings\/\d+/gi)[0].split("/")[1];a=`https://www.ijcai.org/proceedings/${s}/`+o;break;case"acm":a=n.replace("/doi/pdf/","/doi/");break;case"ieee":a="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":a=e.extra.url;break;case"aps":[t,r]=parseUrl(n).pathname.split("/").slice(1,3),a=n.replace(`/${t}/${r}/`,`/${t}/abstract/`);break;case"wiley":a=n.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":s=n.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];a="https://www.sciencedirect.com/science/article/pii/"+s;break;case"science":(i=n.split("/doi/")[1]).startsWith("10.")||(i=i.split("/").slice(1).join("/")),a="https://science.org/doi/full/"+i;break;case"frontiers":a=n.replace(/\/pdf$/,"/full");break;default:a="https://xkcd.com/1969/"}return a.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var r=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),i=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let n={};for(const o of t){let t;try{(t=await parseIdFromUrl(o.finalUrl))&&e.hasOwnProperty(t)&&(n[t]=o)}catch(e){t=null}if(!t){const s=i[o.id];var a=Object.entries(r).find(([,e])=>s.includes(e));a&&(n[a[0]]=o)}}return n},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:r,...i}=e;let n={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,...i};for(const a in r)(!t.hasOwnProperty(a)||r[a]&&!t[a])&&(n[a]=r[a]);e.incrementCount&&1===n.count&&(n.count+=1);for(const o of e.overwrites)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async(t,e,n,a=!0,o={update:()=>{},preprints:()=>{}})=>{const s=Date.now();let l,c,p={};console.group("%cPaperMemory parsing 📕",global.consolHeaderStyle),global.state.papers=await getStorage("papers")??{};var r=await parseIdFromUrl(t),i=global.state.papers.hasOwnProperty(r);if(r&&i)l=updatePaperVisits(global.state.papers[r]),c=!1;else{if(!(l=await makePaper(e,t)))return;i=findFuzzyPaperMatch(global.state.titleHashToIds,l);if(i&&a){let e=global.state.papers[i];log("New paper",l,"already exists as",e),addPaperToTitleHashToId(l),!l.venue&&e.venue||l.venue&&e.venue?(e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate"]}),updateDuplicatedUrls(t,i)):!e.venue&&l.venue&&(await updateDuplicatedUrls(paperToAbs(e),l.id),await updateDuplicatedUrls(paperToPDF(e),l.id),await deletePaperInStorage(e.id,global.state.papers),e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year"]})),l=updatePaperVisits(e),c=!1}else c=!0}if(!l.codeLink||!l.venue)try{const g=await tryPWCMatch(l);var u=!l.codeLink&&g?.url,d=g?.note,f=g?.bibtex,h=!l.venue&&g?.venue;(p={codeLink:u,note:d,venue:h,bibtex:f}).codeLink&&(l.codeLink=p.codeLink,g.hasOwnProperty("note")&&delete g.note,l.code=g)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),c=!1),a&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{o.update(l);let e;if(c||p.codeLink?c?(a?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it."),log("paper: ",l),e="Added to your Memory",p.codeLink&&(e+="
(+ repo from PapersWithCode)
"),n&&n.checkFeedback&&a&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",n&&n.checkFeedback&&a&&feedback(e)):a&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue){var t,r=await tryPreprintMatch(l);for(const i of["note","venue","bibtex"])l[i]&&"bibtex"!==i||(t=r[i]??p[i])&&(log(`Updating preprint ${i} to`,t),l[i]=t);global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e.id.includes(r))?.id,parseIdFromUrl=async t=>{let r;var e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),i=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var n=t.match(/\d{4}\.\d{4,5}/g)[0];r="Arxiv-"+n;const o=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));o&&(r=o.find(e=>!e.startsWith("Arxiv-"))??r)}else if(e.neurips){var n=t.split("/paper/")[1].split("/")[0],a=t.split("/").last().split("-")[0].slice(0,8);r=`NeurIPS-${n}_`+a}else if(e.cvf)r=parseCVFUrl(t).id;else if(e.openreview){n=t.match(/id=\w+/)[0].replace("id=","");r=findPaperId(i,"openreview",n)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),r="Biorxiv-"+e;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));s&&(r=s.find(e=>!e.startsWith("Biorxiv-"))??r)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];a="20"+l.match(/\d+/)[0];r=`PMLR-${a}-`+l}else if(e.acl){n=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();r=findPaperId(i,"acl",n)}else if(e.pnas){a=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];r=findPaperId(i,"pnas",a)}else if(e.nature){n=(t=t.replace(".pdf","").split("#")[0]).split("/").last();r=findPaperId(i,"nature",n)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);r="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1]);r="IOPscience_"+doi}else if(e.jmlr){const c=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();a="20"+c.match(/\d+/)[0];r=`JMLR-${a}_`+c}else if(e.pmc){n=t.match(/PMC\d+/g)[0].replace("PMC","");r=findPaperId(i,"pmc",n)}else if(e.ijcai){a=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),n=t.match(/proceedings\/\d+/gi)[0].split("/")[1];r=`IJCAI-${n}_`+a}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];r=findPaperId(i,"acm",miniHash(doi))}else if(e.ieee){n=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];r=findPaperId(i,"ieee",n)}else if(e.springer){const p=global.sourceExtras.springer.types;let e=p.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}a=t.split(`/${e}/`)[1].split("?")[0].replace(".pdf","");r=findPaperId(i,"springer",miniHash(a))}else if(e.aps){var[n,a]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${n}/${a}/`).last();r=findPaperId(i,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");r=findPaperId(i,"wiley",miniHash(doi))}else if(e.sciencedirect){n=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];r=findPaperId(i,"sciencedirect",miniHash(n))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),r=findPaperId(i,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),r=findPaperId(i,"frontiers",miniHash(doi));else{if(!e.localFile)throw new Error("unknown paper url");r=e.localFile}return r},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var r=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>i.includes(e.title));return 0!==r.length&&r[0].id},makeMdLink=(e,t={})=>{var r=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let i="",n=(!t.checkMdYearVenue||(i=(i=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&i[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(i="",e.venue&&(i+=e.venue+" "),i+=e.year),e.title);return`[${n=i?`${n} (${i.replace(/\s+/g," ")})`:n}](${r})`},initState=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),async(e,t)=>{const r=[];r.unshift(Date.now()),console.groupCollapsed("%cPaperMemory Init ✅",global.consolHeaderStyle),void 0===e&&(e=await getStorage("papers")??{},log("Time to retrieve stored papers (s): "+(Date.now()-r[0])/1e3)),r.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),log("Time to parse data version (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleFunction=(await getTitleFunction()).titleFunction,log("Time to make title function (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),weeklyBackup(),log("Time to backup papers (weekly) (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now());var i,n,a=await migrateData(e,global.state.dataVersion);log("Time to migrate data (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),e=a.papers,global.state.papers=e,global.state.prefs=await getPrefs(),log("Time to retrieve user preferences (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},log("Time to retrieve sources to ignore (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},log("Time to retrieve sources to urlHashToId (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleHashToIds={};for([i,n]of Object.entries(cleanPapers(e))){var o=miniHash(n.title);global.state.titleHashToIds.hasOwnProperty(o)||(global.state.titleHashToIds[o]=[]),global.state.titleHashToIds[o].push(i)}log("Time to hash titles (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),log("Time to match all local files (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),log("Time to sort memory (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),makeTags(),log("Time to make tags (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now())),info("State init duration (s): "+(Date.now()-r.last())/1e3),console.groupEnd()}),sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers),global.state.papersList.sort(orderPapers)},orderPapers=(e,t)=>{let r=e[global.state.sortKey],i=t[global.state.sortKey];return void 0===r&&(r=""),void 0===i&&(i=""),"string"==typeof r&&(r=r.toLowerCase(),i=i.toLowerCase()),0<=global.descendingSortKeys.indexOf(global.state.sortKey)?r>i?-1:1:r>i?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const r of t.tags)e.add(r);global.state.paperTags=Array.from(e),global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},r=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let i=t[r[e=void 0===e?getRandomInt(r.length):e]];return i=void 0===i?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:i},getTitleFunction=async(code=null)=>{let titleFunction;code=code||await getStorage("titleFunctionCode"),void 0===code&&(code=global.defaultTitleFunctionCode);let errorMessage;try{titleFunction=eval(code)}catch(error){errorMessage="Error parsing the title function: "+error,log("Error parsing the title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}try{const examplePaper=await getExamplePaper(0),result=titleFunction(examplePaper);if("string"!=typeof result)throw new Error(`Result ${result} is not a string`)}catch(error){errorMessage="Error executing the title function: "+error,log("Error testing the user's title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}return{titleFunction:titleFunction,code:code.trim(),errorMessage:errorMessage}},stateTitleFunction=paperOrId=>{let paper=paperOrId;if("string"==typeof paperOrId&&(paper=global.state.papers[paperOrId],void 0===paper))return log("Error in stateTitleFunction: unknown id",paperOrId),"Unknown ID";let name;try{name=global.state.titleFunction(paper)}catch(error){log("Error in stateTitleFunction:",error),name=eval(global.defaultTitleFunctionCode)(paper)}return name.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,r,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===r))&&e.length){for(const i of e)warn("Removing duplicated url",t,"for",r),delete global.state.urlHashToId[i];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=r,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={initState:initState,getExamplePaper:getExamplePaper,getTitleFunction:getTitleFunction,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,r;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(r=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:i,year:n}=parseCVFUrl(e);t=t.replace(`/content_${i}_${n}/`,`/content_${i.toLowerCase()}_${n}/`),r=await fetch(t).then(e=>e.ok?e.text():"")}return r},fetchOpenReviewNoteJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?id="+e).then(e=>e.json())},fetchOpenReviewForumJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?forum="+e).then(e=>e.json())},fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),r=t.ok?await t.text():"";return r.trim()}catch(e){return console.log("fetchText error:",e),""}},fetchJSON=async e=>{try{const t=await fetch(e);return t.ok?await t.json():null}catch(e){return console.log("fetchJSON error:",e),null}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const o=e.message;log("Crossref data.message: ",o);var t=o.author.map(e=>e.given+" "+e.family).join(" and ");const s=o.issued?o.issued["date-parts"][0][0]+"":o.published?o.published["date-parts"][0][0]+"":null;if(s){var r=o.title[0];if(r){var i=o["container-title"][0]??"Springer",n=[miniHash(o.author[0].family),s.slice(2),firstNonStopLowercase(r)].join(""),a=o.DOI;let e={entryType:"book"===o.type?"book":"book-chapter"===o.type?"InBook":o.type.includes("article")?"Article":"InProceedings",citationKey:n,publisher:o.publisher,author:t,title:r,year:s,doi:a};o.page&&(e.pages=o.page),o.volume&&(e.volume=o.volume),o.type.includes("journal")&&(e.journal=i),o.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=n.URL),(t=o.link.find(e=>"text/html"===e["content-type"])??o.link[0])&&(e.url=t.URL));r=bibtexToString(e);return{...e,bibtex:r,venue:i}}error("Cannot find title in CrossRef data",o)}else error("Cannot find year in CrossRef data",o)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{e=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return extractCrossrefData(e)},fetchSemanticsScholarDataForDoi=async e=>{const t=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`);let r;var i;return t&&(r={},t.venue&&(r.venue=t.venue),t.year&&(r.year=t.year),t.authors&&(r.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(r.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(r.title),i=bibtexToString({entryType:"article",citationKey:e,...r}),r.bibtex=i,r.key=e),r},getMetaContent=(e,t,r=!1)=>{e="meta"+Object.entries(e).map(([e,t])=>`[${e}='${t}']`).join("");return r?queryAll(t,e).map(e=>e.getAttribute("content")??""):t.querySelector(e)?.getAttribute("content")??""},extractDataFromDCMetaTags=e=>{const t=getMetaContent({name:"dc.Creator"},e,!0).map(e=>e.replace(/([a-z])([A-Z])/g,"$1 $2")).join(" and ");if(!t)return null;var r=getMetaContent({name:"dc.Date"},e).split("-")[0],i=getMetaContent({name:"dc.Publisher"},e).replaceAll("\n"," "),n=getMetaContent({name:"dc.Title"},e),a=getMetaContent({name:"citation_journal_title"},e),o=(""+t.split(" and ")[1].split(" ")[0]+r+firstNonStopLowercase(n)).toLowerCase(),e=getMetaContent({name:"dc.Date",scheme:"doi"},e),s=bibtexToString({citationKey:o,entryType:"article",title:n,author:t,year:r,doi:e,publisher:i,journal:a});return{author:t,year:r,publisher:i,title:n,venue:a,key:o,doi:e,bibtex:s,note:`Published @ ${a} (${r})`}},makeArxivPaper=async e=>{e=e.match(/\/(\d{4}\.\d{4,5})/)[1];const t=await fetchArxivXML(e),r=await t.text();var i=(new DOMParser).parseFromString(r.replaceAll("\n",""),"text/xml");const n=queryAll(i,"author name").map(e=>e.innerHTML);var a=n.join(" and "),o=Array.from(i.getElementsByTagName("link")).map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),s=i.querySelector("entry title").innerHTML,i=i.querySelector("entry published").innerHTML.slice(0,4),l=n[0].split(" ").last().toLowerCase()+i+firstNonStopLowercase(s),e="Arxiv-"+e,c="";return{author:a,bibtex:c+`@article{${l}, `+`title={${s} }, From 91872494a810923b58703106dd999f46c95e7f3d Mon Sep 17 00:00:00 2001 From: vict0rsch Date: Sat, 20 Aug 2022 12:03:58 +0100 Subject: [PATCH 04/80] write papers to gist --- src/options/options.css | 5 --- src/options/options.html | 19 ++++++++++- src/options/options.js | 67 +++++++++++++++++++++++++++++-------- src/popup/popup.html | 1 + src/shared/js/utils/sync.js | 9 +++++ src/shared/min/utils.min.js | 2 +- 6 files changed, 82 insertions(+), 21 deletions(-) diff --git a/src/options/options.css b/src/options/options.css index a9cdea67..efd46d4a 100644 --- a/src/options/options.css +++ b/src/options/options.css @@ -444,11 +444,6 @@ input { background-color: rgb(27, 159, 7); color: rgb(223, 223, 223); } -#delete-pat { - margin-left: 2rem; - background-color: rgb(196, 18, 18); - color: rgb(223, 223, 223); -} #pat-feedback { color: rgb(150, 102, 13); } diff --git a/src/options/options.html b/src/options/options.html index 08e96edc..1922c6b5 100644 --- a/src/options/options.html +++ b/src/options/options.html @@ -455,11 +455,28 @@

Online synchronization

-

+ +
diff --git a/src/options/options.js b/src/options/options.js index 015ad78f..c16bdb31 100644 --- a/src/options/options.js +++ b/src/options/options.js @@ -906,30 +906,69 @@ const setupSourcesSelection = async () => { // ----- SYNCING ----- // --------------------- -const setupSync = () => { +const setupSync = async () => { + const { ok, payload, error } = await getGist(); + + if (!ok) { + if (error) { + setHTML("pat-feedback", "Invalid PAT" + "

" + error); + } + } else { + const { gist, pat } = payload; + val("pat-input", pat); + await showSync(); + } + addListener("save-pat", "click", async () => { const pat = val("pat-input"); - console.log(pat); if (!pat) { setHTML("pat-feedback", "Invalid PAT"); return; } - const githubGist = new GithubGist.default({ - personalAccessToken: pat, - appIdentifier: "PaperMemorySync", - isPublic: false, - }); - try { - await githubGist.touch(); - - console.log("Gist ID", githubGist.id); - console.log("Github Owner Username", githubGist.ownerUsername); - } catch (e) { - // gist initialization failed. + const { ok, payload, error } = await getGist(pat); + if (payload === "wrongPat") { console.log(e); setHTML("pat-feedback", e); + } else { + const { gist, pat } = payload; + console.log("Gist ID", gist.id); + console.log("Github Owner Username", gist.ownerUsername); + console.log("Personal Access Token", pat); + setHTML("pat-feedback", "Ok! Token is valid."); + showSync(); } }); + + addListener("stop-gh-sync", "click", async () => { + const c = confirm("Are you sure you want to stop syncing to Github?"); + if (!c) return; + const pat = ""; + setStorage("syncPAT", pat); + val("pat-input", pat); + }); + addListener("start-gh-sync", "click", async () => { + const { ok, payload, error } = await getGist(); + if (!ok) { + alert("Your Personal Access Token is invalid.\n\n" + (error ?? "")); + return; + } + const { gist } = payload; + const dataFile = getDataFile(gist); + const papersString = JSON.stringify(global.state.papers, null, ""); + console.log("dataFile: ", dataFile); + dataFile.overwrite(papersString); + await dataFile.save(); + alert("Synced!"); + }); +}; + +const showSync = async () => { + const syncState = await getStorage("syncState"); + if (!syncState) { + showId("start-sync"); + } else { + showId("stop-sync"); + } }; // ---------------------------- diff --git a/src/popup/popup.html b/src/popup/popup.html index 1590361a..340877cf 100755 --- a/src/popup/popup.html +++ b/src/popup/popup.html @@ -31,6 +31,7 @@ + diff --git a/src/shared/js/utils/sync.js b/src/shared/js/utils/sync.js index 593ef78b..a8cf192a 100644 --- a/src/shared/js/utils/sync.js +++ b/src/shared/js/utils/sync.js @@ -27,3 +27,12 @@ const getGist = async (pat, store = true) => { }; } }; + +const getDataFile = (gist) => { + let dataFile = gist.getFile("PaperMemory-sync-data.json"); + if (!dataFile) { + gist.createFile("PaperMemory-sync-data.json"); + dataFile = gist.getFile("PaperMemory-sync-data.json"); + } + return dataFile; +}; diff --git a/src/shared/min/utils.min.js b/src/shared/min/utils.min.js index 85af892b..62b6ff31 100644 --- a/src/shared/min/utils.min.js +++ b/src/shared/min/utils.min.js @@ -8,7 +8,7 @@ const findEl=(e,t)=>void 0===t?"string"==typeof e?document.getElementById(e):e:f /!\\ It has to stay in your downloads for PaperMemory to be able to access your papers. /!\\ To be able to open files from this folder instead of re-downloading them, PaperMemory will match their titles and downloaded urls. /!\\ If you change the default title function in the Advanced Options and do not include a paper's title in the file name, PaperMemory may not be able to open the file and will instead open the pdf url. - /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle}),!function i(n,a,o){function s(t,e){if(!a[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=a[t]={exports:{}},n[t][0].call(r.exports,function(e){return s(n[t][1][e]||e)},r,r.exports,i,n,a,o)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;ee.length)&&(r=e.length),r-=t.length,-1!==(e=e.indexOf(t,r))&&e===r},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var r=new Array(t);0>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===i&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,a[o++]=255&t),1===i&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],a=0,o=r-i;a>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(i));return n.join("")}(e,a,o>2]+s[t<<4&63]+"==")):2==i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,a=i.length;n>>1;case"base64":return k(e).length;default:if(n)return i?-1:x(e).length;t=(""+t).toLowerCase(),n=!0}}function t(e,t,r){var i,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var a=this,o=t,s=r,l=a.length;(!s||s<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:f(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):f(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,i,n){var a=1,o=e.length,s=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o/=a=2,s/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n)for(var c=-1,p=r;p>8,i=i%256,n.push(i),n.push(r);return n}(t,e.length-r),e,r,i)}function A(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n>>10&1023|55296),p=56320|1023&p),i.push(p),n+=u}var d=i,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var h="",g=0;gt&&(e+=" ... "),""},u.prototype.compare=function(e,t,r,i,n){if(C(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),l=this.slice(i,n),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i=i||"utf8";for(var a,o,s,l=!1;;)switch(i){case"hex":var c=this,p=e,u=t,d=r,f=(u=Number(u)||0,c.length-u);(!d||(d=Number(d))>f)&&(d=f),(f=p.length)/2e.length)throw new RangeError("Index out of range")}function b(e,t,r,i){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function v(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,4),a.write(e,t,r,i,23,4),r+4}function w(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,8),a.write(e,t,r,i,52,8),r+8}u.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||h(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=t,n=1,a=this[e+--i];0=(n*=128)&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||h(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,i){e=+e,t>>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[t+n]=255&e;0<=--n&&(a*=256);)this[t+n]=e/a&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeIntLE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=0,a=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=r-1,a=1,o=0;for(this[t+n]=255&e;0<=--n&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a>>0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return w(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return w(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,i){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,i||0===i||(i=this.length),t>=e.length&&(t=e.length),(i=0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length);var n=(i=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(a=t;a>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function E(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}}.call(this)}.call(this,O("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,n){var a,o,s=8*n-i-1,l=(1<>1,p=-7,u=r?n-1:0,d=r?-1:1,n=e[t+u];for(u+=d,a=n&(1<<-p)-1,n>>=-p,p+=s;0>=-p,p+=i;0>1,u=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,f=i?1:-1,a=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,n),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),o=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield n.default.post(e,t,(0,a.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:n}=this,a="https://gist.githubusercontent.com/"+i+`/${n}/raw/${e}/`+this.fileName;return t?null!=r?r(a):o.default.corsAnywhere+a:a},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),a=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>n(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,a.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>n(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>n(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>n(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},n=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),a=n.data;yield this.initialize(a)}),this.initialize=i=>n(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=a.default.githubRateLimit;return n.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]);const getGist=async(e,t=!0)=>{if(!(e=e||await getStorage("syncPAT")))return{ok:!1,payload:"noPAT"};const r=new GithubGist.default({personalAccessToken:e,appIdentifier:"PaperMemorySync",isPublic:!1});try{return await r.touch(),t&&await setStorage("syncPAT",e),{ok:!0,payload:{gist:r,pat:e}}}catch(e){return console.log(e),{ok:!1,payload:"wrongPAT",error:e}}};function _min(e,t,r,i,n){return e{if(e===t)return 0;e.length>t.length&&(r=e,e=t,t=r);for(var r,i=e.length,n=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,r=(this.match("{",!1),this.pos),i=!1;;){if(!i)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");i="\\"==this.input[this.pos]&&0==i,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,r=!1;;){if(!r){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, + /!\\ Unfortunately, PaperMemory cannot detect papers that have not been *downloaded there* so putting papers in this folder will not make them discoverable by the \`browser.downloads\` API PaperMemory uses.`,global.englishStopWords=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now"]),global.journalAbbreviations=null,"undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={state:global.state,descendingSortKeys:global.descendingSortKeys,select2Options:global.select2Options,prefsCheckNames:global.prefsCheckNames,prefsCheckDefaultFalse:global.prefsCheckDefaultFalse,prefsStorageKeys:global.prefsStorageKeys,sourceExtras:global.sourceExtras,preprintSources:global.preprintSources,knownPaperPages:global.knownPaperPages,sourcesNames:global.sourcesNames,overrideORConfs:global.overrideORConfs,overridePMLRConfs:global.overridePMLRConfs,overrideDBLPVenues:global.overrideDBLPVenues,fuzzyTitleMatchMinDist:global.fuzzyTitleMatchMinDist,defaultTitleFunctionCode:global.defaultTitleFunctionCode,storeReadme:global.storeReadme,englishStopWords:global.englishStopWords,journalAbbreviations:global.journalAbbreviations,consolHeaderStyle:global.consolHeaderStyle}),!function i(n,a,o){function s(t,e){if(!a[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=a[t]={exports:{}},n[t][0].call(r.exports,function(e){return s(n[t][1][e]||e)},r,r.exports,i,n,a,o)}return a[t].exports}for(var l="function"==typeof require&&require,e=0;ee.length)&&(r=e.length),r-=t.length,-1!==(e=e.indexOf(t,r))&&e===r},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var r=new Array(t);0>16&255,a[o++]=t>>8&255,a[o++]=255&t;return 2===i&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,a[o++]=255&t),1===i&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,a[o++]=t>>8&255,a[o++]=255&t),a},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],a=0,o=r-i;a>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(i));return n.join("")}(e,a,o>2]+s[t<<4&63]+"==")):2==i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,a=i.length;n>>1;case"base64":return k(e).length;default:if(n)return i?-1:x(e).length;t=(""+t).toLowerCase(),n=!0}}function t(e,t,r){var i,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var a=this,o=t,s=r,l=a.length;(!s||s<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:f(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):f(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,i,n){var a=1,o=e.length,s=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o/=a=2,s/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n)for(var c=-1,p=r;p>8,i=i%256,n.push(i),n.push(r);return n}(t,e.length-r),e,r,i)}function A(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n>>10&1023|55296),p=56320|1023&p),i.push(p),n+=u}var d=i,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var h="",g=0;gt&&(e+=" ... "),""},u.prototype.compare=function(e,t,r,i,n){if(C(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),l=this.slice(i,n),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i=i||"utf8";for(var a,o,s,l=!1;;)switch(i){case"hex":var c=this,p=e,u=t,d=r,f=(u=Number(u)||0,c.length-u);(!d||(d=Number(d))>f)&&(d=f),(f=p.length)/2e.length)throw new RangeError("Index out of range")}function b(e,t,r,i){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function v(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,4),a.write(e,t,r,i,23,4),r+4}function w(e,t,r,i,n){return t=+t,r>>>=0,n||b(e,0,r,8),a.write(e,t,r,i,52,8),r+8}u.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||h(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||h(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=this[e],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||h(e,t,this.length);for(var i=t,n=1,a=this[e+--i];0=(n*=128)&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return e>>>=0,t||h(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt16BE=function(e,t){e>>>=0,t||h(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||h(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||h(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||h(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,i){e=+e,t>>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,i||g(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[t+n]=255&e;0<=--n&&(a*=256);)this[t+n]=e/a&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeIntLE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=0,a=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,i){e=+e,t>>>=0,i||g(this,e,t,r,(i=Math.pow(2,8*r-1))-1,-i);var n=r-1,a=1,o=0;for(this[t+n]=255&e;0<=--n&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a>>0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return w(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return w(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,i){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,i||0===i||(i=this.length),t>=e.length&&(t=e.length),(i=0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length);var n=(i=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(a=t;a>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function E(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}}.call(this)}.call(this,O("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,n){var a,o,s=8*n-i-1,l=(1<>1,p=-7,u=r?n-1:0,d=r?-1:1,n=e[t+u];for(u+=d,a=n&(1<<-p)-1,n>>=-p,p+=s;0>=-p,p+=i;0>1,u=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,f=i?1:-1,a=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,n),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,n),o=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield n.default.post(e,t,(0,a.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:n}=this,a="https://gist.githubusercontent.com/"+i+`/${n}/raw/${e}/`+this.fileName;return t?null!=r?r(a):o.default.corsAnywhere+a:a},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield n.default.get(e,(0,a.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),a=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>n(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,a.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>n(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>n(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>n(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},n=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),a=n.data;yield this.initialize(a)}),this.initialize=i=>n(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{a(l.next(e))}catch(e){t(e)}}function n(e){try{a(l.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,n)}a((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const n=e("axios"),a=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=a.default.githubRateLimit;return n.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]);const getGist=async(e,t=!0)=>{if(!(e=e||await getStorage("syncPAT")))return{ok:!1,payload:"noPAT"};const r=new GithubGist.default({personalAccessToken:e,appIdentifier:"PaperMemorySync",isPublic:!1});try{return await r.touch(),t&&await setStorage("syncPAT",e),{ok:!0,payload:{gist:r,pat:e}}}catch(e){return console.log(e),{ok:!1,payload:"wrongPAT",error:e}}},getDataFile=e=>{let t=e.getFile("PaperMemory-sync-data.json");return t||(e.createFile("PaperMemory-sync-data.json"),t=e.getFile("PaperMemory-sync-data.json")),t};function _min(e,t,r,i,n){return e{if(e===t)return 0;e.length>t.length&&(r=e,e=t,t=r);for(var r,i=e.length,n=t.length;0this.pos&&"@"!=this.input[this.pos];)this.pos++;return"@"==this.input[this.pos]},this.skipWhitespace=function(e){for(;this.isWhitespace(this.input[this.pos]);)this.pos++;if("%"==this.input[this.pos]&&1==e){for(;"\n"!=this.input[this.pos];)this.pos++;this.skipWhitespace(e)}},this.value_braces=function(){for(var e,t=0,r=(this.match("{",!1),this.pos),i=!1;;){if(!i)if("}"==this.input[this.pos]){if(!(0=this.input.length-1)throw TypeError("Unterminated value: value_braces");i="\\"==this.input[this.pos]&&0==i,this.pos++}},this.value_comment=function(){for(var e="",t=0;!this.tryMatch("}",!1)||0!=t;){if(e+=this.input[this.pos],"{"==this.input[this.pos]&&t++,"}"==this.input[this.pos]&&t--,this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_comment",+this.input.substring(start));this.pos++}return e},this.value_quotes=function(){this.match('"',!1);for(var e,t=this.pos,r=!1;;){if(!r){if('"'==this.input[this.pos])return e=this.pos,this.match('"',!1),this.input.substring(t,e);if(this.pos>=this.input.length-1)throw TypeError("Unterminated value: value_quotes",this.input.substring(t))}r="\\"==this.input[this.pos]&&0==r,this.pos++}},this.single_value=function(){var e=this.pos;if(this.tryMatch("{"))return this.value_braces();if(this.tryMatch('"'))return this.value_quotes();var t=this.key();if(t.match("^[0-9]+$"))return t;if(0<=this.months.indexOf(t.toLowerCase()))return t.toLowerCase();throw"Value expected: single_value"+this.input.substring(e)+" for key: "+t},this.value=function(){var e=[];for(e.push(this.single_value());this.tryMatch("#");)this.match("#"),e.push(this.single_value());return e.join("")},this.key=function(e){for(var t=this.pos;;){if(this.pos>=this.input.length)throw TypeError("Runaway key: key");if(0<=this.notKey.indexOf(this.input[this.pos]))return e&&","!=this.input[this.pos]?(this.pos=t,null):this.input.substring(t,this.pos);this.pos++}},this.key_equals_value=function(){var e,t=this.key();if(this.tryMatch("="))return this.match("="),e=this.value(),[t=t.trim(),e];throw TypeError("Value expected, equals sign missing: key_equals_value",this.input.substring(this.pos))},this.key_value_list=function(){var e=this.key_equals_value();for(this.currentEntry.entryTags={},this.currentEntry.entryTags[e[0]]=e[1];this.tryMatch(",")&&(this.match(","),!this.tryMatch("}"));)e=this.key_equals_value(),this.currentEntry.entryTags[e[0]]=e[1]},this.entry_body=function(e){this.currentEntry={},this.currentEntry.citationKey=this.key(!0),this.currentEntry.entryType=e.substring(1),null!=this.currentEntry.citationKey&&this.match(","),this.key_value_list(),this.entries.push(this.currentEntry)},this.directive=function(){return this.match("@"),"@"+this.key()},this.preamble=function(){this.currentEntry={},this.currentEntry.entryType="PREAMBLE",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.comment=function(){this.currentEntry={},this.currentEntry.entryType="COMMENT",this.currentEntry.entry=this.value_comment(),this.entries.push(this.currentEntry)},this.entry=function(e){this.entry_body(e)},this.alernativeCitationKey=function(){this.entries.forEach(function(e){!e.citationKey&&e.entryTags&&(e.citationKey="",e.entryTags.author&&(e.citationKey+=e.entryTags.author.split(",")[0]+=", "),e.citationKey+=e.entryTags.year)})},this.bibtex=function(){for(;this.matchAt();){var e=this.directive();this.match("{"),"@STRING"==e.toUpperCase()?this.string():"@PREAMBLE"==e.toUpperCase()?this.preamble():"@COMMENT"==e.toUpperCase()?this.comment():this.entry(e),this.match("}")}this.alernativeCitationKey()}}const bibtexToObject=e=>{var t=new BibtexParser,e=(t.setInput(e),t.bibtex(),t.getEntries()[0]);return{...e.entryTags,entryType:e.entryType,citationKey:e.citationKey}},bibtexToString=e=>{let t=`@${(e={...e="string"==typeof e?bibtexToObject(e):e}).entryType.toLowerCase()}{${e.citationKey}, `;delete e.entryType,delete e.citationKey;var r,i=Math.max(...Object.keys(e).map(e=>e.length));for(const n in e)e.hasOwnProperty(n)&&e[n]&&(r=e[n].replaceAll(/\s+/g," ").trim(),bkey=n+" ".repeat(i-n.length),t+=` ${bkey} = {${r}}, `);return(t.slice(0,-2)+"\n}").replaceAll("\t"," ").replaceAll("--","-")},extractBibtexValue=(e,t)=>{const r=bibtexToObject(e);return r.hasOwnProperty(t)?r[t]:""},extractAuthor=e=>extractBibtexValue(e,"author").replaceAll("{","").replaceAll("}","").replaceAll("\\","").split(" and ").map(e=>e.split(", ").reverse().join(" ")).join(" and "),logTrace=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={bibtexToObject:bibtexToObject,bibtexToString:bibtexToString,extractBibtexValue:extractBibtexValue,extractAuthor:extractAuthor}),"undefined"!=typeof LOGTRACE&&LOGTRACE),log=(...e)=>{if(logTrace){const s=(new Error).stack;e.push("\n\nLog trace:\n"+s.split("\n").slice(2).join("\n"))}let t="%c%s ",r=!1,i=!1,n=!1,a=!1,o=!1;"[info]"===e[0]?(r=!0,e=e.slice(1)):"[warn]"===e[0]?(i=!0,e=e.slice(1)):"[error]"===e[0]?(n=!0,e=e.slice(1)):"[ok]"===e[0]?(o=!0,e=e.slice(1)):"[debug]"===e[0]&&(a=!0,e=e.slice(1)),e.forEach(e=>{switch(typeof e){case"bigint":case"number":t+="%d ";break;case"string":t+="%s ";break;default:t+="%o "}}),console.log(t,"color: "+(r?"#8BB4F7; font-weight:bold;":i?"#f3bd1e; font-weight:bold;":n?"#FF4F54; font-weight:bold;":o?"#23F62B; font-weight:bold;":a?"#BA357E; font-weight:bold;":"tan"),"[PM]",...e)},info=(...e)=>log("[info]",...e),warn=(...e)=>log("[warn]",...e),debug=(...e)=>log("[debug]",...e),logOk=(...e)=>log("[ok]",...e),logError=(...e)=>log("[error]",...e),getDisplayId=e=>{var t=e;if((e=e.split("_")[0].split(".")[0]).startsWith("OR-")||(e=e.split("-").slice(0,2).join("-")),global.state.papers.hasOwnProperty(t)){const r=global.state.papers[t];if("nature"===r.source){if(r.note.match(/^Published\ @.+\(\d+\)$/)){const i=r.note.split("@")[1].split("(")[0].trim();e+="-"+i.split(" ").map(e=>e[0].toUpperCase()).join("")}e+="-"+r.year}"acs"===r.source&&(e+="-"+r.year),"iop"===r.source&&(e+="-"+r.year)}return e},isObject=e=>"object"==typeof e&&!Array.isArray(e)&&null!==e,isPdfUrl=e=>e.endsWith(".pdf")||e.endsWith("/pdf")||e.includes("openreview.net/pdf")||e.match(/\/e?pdf\//g)||e.includes("ieee.org/stamp/stamp.jsp?tp=&arnumber="),delay=(t,r)=>{let i=0;return(...e)=>{clearTimeout(i),i=setTimeout(t.bind(this,...e),r||0)}},cleanPapers=e=>{let t={...e};return delete t.__dataVersion,t},firstNonStopLowercase=e=>{let t=e.toLowerCase(),r=t.split(" ").map(miniHash);e=r.filter(e=>!global.englishStopWords.has(e));return(0e.toLowerCase().replace(/\W/g,""),fallbackCopyTextToClipboard=e=>{var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{var r=document.execCommand("copy")?"successful":"unsuccessful";log("Fallback: Copying text command was "+r)}catch(e){console.error("Fallback: Oops, unable to copy",e)}document.body.removeChild(t)},copyTextToClipboard=e=>{navigator.clipboard?navigator.clipboard.writeText(e).then(()=>{log("Async: Copying to clipboard was successful!")},e=>{console.error("Async: Could not copy text: ",e)}):fallbackCopyTextToClipboard(e)},parseUrl=e=>{var t=document.createElement("a");return t.href=e,t},downloadTextFile=(e,t,r)=>{var i=document.createElement("a");"text/plain"===r?(e=e.replace(/\\n/g,"%0D%0A").replace(/"/g,""),i.download=t,i.href="data:text/plain,"+e):(e=new Blob([e],{type:r}),i.href=URL.createObjectURL(e),i.download=t),i.click()},eventId=e=>e.target.closest(".memory-container").id.split("--")[1],downloadFile=(e,t)=>{var r;window.ActiveXObject?window.ActiveXObject&&document.execCommand&&((r=window.open(e,"_blank")).document.close(),r.document.execCommand("SaveAs",!0,t||e),r.close()):((r=document.createElement("a")).href=e,r.target="_blank",e=e.substring(e.lastIndexOf("/")+1),r.download=t||e,navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/)&&navigator.userAgent.search("Chrome")<0?document.location=r.href:(t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1}),r.dispatchEvent(t),(window.URL||window.webkitURL).revokeObjectURL(r.href)))},hashCode=e=>e.split("").reduce((e,t)=>(e=(e<<5)-e+t.charCodeAt(0))&e,0),parseCVFUrl=e=>{const t=e.replace("https://openaccess.thecvf.com/content","").slice(1).split("/")[0].split("_");let r,i;i=1===t.length?(r=t[0].slice(0,-4),t[0].slice(-4)):(r=t[0].toUpperCase(),t[1]);e=e.split("/").last().split(".")[0],e=(hashCode(e)+"").replace("-","").slice(0,8),e=`${r}-${i}_`+e;return{conf:r,year:i,id:e}},cleanBiorxivURL=e=>e=(e=e.replace(".full.pdf","")).match(/\d$/)?e:e.split(".").slice(0,-1).join("."),textareaFocusEnd=e=>{setTimeout(()=>{e.selectionStart=e.selectionEnd=1e4},0)},tablerSvg=(e,t,r)=>{switch(t=(t=void 0===t?"":t)&&`id="${t}"`,r=(r=(r=void 0===r?[]:r).filter(e=>e))&&`class="${r.join(" ")}"`,e){case"adjustments":return``;case"circle-x":return``;case"star":return``;case"writing":return``;case"file-symlink":return``;case"link":return``;case"clipboard-list":return``;case"archive":return``;case"external-link":return``;case"file-download":return``;case"cirlce-x":return``;case"settings":return``;case"messages":return``;case"vocabulary":return``;case"database-export":return``;case"eyeglass":return``;case"markdown":return``;case"math-function":return``;default:return""}},stringifyError=e=>{const t=chrome.runtime.id;return e.stack.split("\n").map(e=>e.split(" ").map(e=>e.split(t).last()).join(" ")).join("
")},arraysIdentical=(e,t)=>{var r=e.length;if(r!=t.length)return!1;for(;r--;)if(e[r]!==t[r])return!1;return!0},parseTags=e=>{let t=Array.from(e.selectedOptions,e=>e.value.trim()).filter(e=>e);return t.sort(),t},getPaperEdits=(e,t)=>{let r,i,n,a;return a=t?(r=val("popup-form-note-textarea--"+e),n=val(document.getElementById("popup-form-note--"+e).querySelector(".form-code-input")),i=parseTags(findEl("popup-item-tags--"+e)),findEl("checkFavorite--"+e).checked):(r=val(findEl(e,"form-note-textarea")),n=val(findEl(e,"form-code-input")),i=parseTags(findEl(e,"memory-item-tags")),hasClass("memory-container--"+e,"favorite")),{note:r,tags:i,codeLink:n,favorite:a}},setFormChangeListener=(e,t)=>{let r,i,n,a;t?(r="#popup-item-tags--"+e.replace(".","\\."),n="popup-form-codeLink--"+e,i="popup-form-note-textarea--"+e,a="checkFavorite--"+e,$(r).on("change",delay(monitorPaperEdits(e,t),300)),addListener(n,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(i,"keyup",delay(monitorPaperEdits(e,t),300)),addListener(a,"change",delay(monitorPaperEdits(e,t),300))):(r=".memory-item-tags",n=".form-code-input",i=".form-note-textarea",addEventToClass(n,"keyup",delay(monitorPaperEdits(void 0,t),300)),addEventToClass(i,"keyup",delay(monitorPaperEdits(void 0,t),300)))},monitorPaperEdits=(c,p)=>e=>{let t;t=void 0===c?eventId(e):c;var r=getPaperEdits(t,p),i=global.state.papers[t];let n=!1,a={};for(const l in r){var o=i[l],s=(a[l]=o,r[l]);"tags"===l?arraysIdentical(o,s)||(n=!0):o!==s&&(n=!0)}n&&(console.log("Updating meta data for",t),(p?handlePopupSaveEdits:handleMemorySaveEdits)(t))},cutAuthors=(e,t,r)=>{void 0===t&&(t=140),void 0===r&&(r=", ");let i="";var e=e.split(" and "),n=e[e.length-1];for(const a of e){if(!(5+i.length+r.length+a.length+n.lengthnew Promise(t=>{chrome.runtime.sendMessage(e,e=>{t(e)})}),getStoredFiles=()=>new Promise(t=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},e=>t(e.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt"))))}),noParamUrl=e=>e.split("?")[0].split("#")[0],silentPromiseTimeout=(e,r=5e3)=>{let i;return Promise.race([e,new Promise((e,t)=>i=setTimeout(e,r))]).finally(()=>clearTimeout(i))},shouldWarn=async(e,t=()=>{})=>{if("pdf-title"===e){var r=await getStorage("titleFunctionCode");if(r&&r!==global.defaultTitleFunctionCode)if(!(await getStorage("userWarnings")??{})[e])return t(!0)}return t(!1)},migrateData=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={log:log,info:info,logError:logError,logOk:logOk,debug:debug,warn:warn,getDisplayId:getDisplayId,isObject:isObject,isPdfUrl:isPdfUrl,delay:delay,cleanPapers:cleanPapers,firstNonStopLowercase:firstNonStopLowercase,fallbackCopyTextToClipboard:fallbackCopyTextToClipboard,copyTextToClipboard:copyTextToClipboard,parseUrl:parseUrl,downloadTextFile:downloadTextFile,eventId:eventId,downloadFile:downloadFile,hashCode:hashCode,parseCVFUrl:parseCVFUrl,cleanBiorxivURL:cleanBiorxivURL,textareaFocusEnd:textareaFocusEnd,tablerSvg:tablerSvg,stringifyError:stringifyError,arraysIdentical:arraysIdentical,parseTags:parseTags,getPaperEdits:getPaperEdits,setFormChangeListener:setFormChangeListener,monitorPaperEdits:monitorPaperEdits,cutAuthors:cutAuthors,sendMessageToBackground:sendMessageToBackground,getStoredFiles:getStoredFiles,miniHash:miniHash,noParamUrl:noParamUrl,silentPromiseTimeout:silentPromiseTimeout,shouldWarn:shouldWarn}),async(r,t,e=!0)=>{if(void 0===r)return chrome.storage.local.set({papers:{__dataVersion:t}}),{papers:{__dataVersion:t},success:!0};var i,n,a,o=r.__dataVersion||-1,s=[];let l={...r};try{if(502<=o)return{papers:r,success:!0};e&&backupData({...r}),delete r.__dataVersion;for(const c in r)o<5&&(info("Applying migration 5"),r[c].hasOwnProperty("bibtex")||(r[c].bibtex="",log("Migrating bibtex for "+c)),r[c].pdfLink.endsWith(".pdf")||(r[c].pdfLink=r[c].pdfLink+".pdf"),r[c].codeLink||(r[c].codeLink=""),r[c].source||(r[c].id.includes("NeurIPS")?r[c].source="neurips":r[c].source="arxiv")),o<208&&(info("Applying migration 0.2.8"),"arxiv"!==r[c].source&&r[c].md.includes("https://arxiv.com/abs/")&&(r[c].md=`[${r[c].title}](${r[c].pdfLink})`),"arxiv"!==r[c].source&&r[c].pdfLink.includes("arxiv.org/pdf/")&&(r[c].source="arxiv"),c.match(/^\d/)&&"arxiv"===r[c].source&&(i="Arxiv-"+c,n={...r[c],id:i},r[i]=n,s.push(c))),o<209&&(info("Applying migration 0.2.9"),r[c].hasOwnProperty("favorite")||(r[c].favorite=!1,r[c].favoriteDate="")),o<210&&(info("Applying migration 0.2.10"),"arxiv"===r[c].source&&(a=r[c].pdfLink.match(/v\d+\.pdf/gi))&&0{delete r[e],log("Deleting "+e)}),(l={...r}).__dataVersion=t,e&&chrome.storage.local.set({papers:l},()=>{log("Migrated papers:"),log(l),log("Data version is now "+t)}),{papers:l,success:!0}}catch(e){return log(`Error migrating data from version ${o} to ${t}:`),log(e),{papers:l,success:!1,error:e}}}),logStorage=t=>{chrome.storage.local.get(t,e=>{log(e[t])})},getStorage=async r=>new Promise((t,e)=>{chrome.storage.local.get(r,e=>{t("string"==typeof r?e[r]:e)})}),setStorage=async(r,i,n=()=>{})=>new Promise((e,t)=>{chrome.storage.local.set({[r]:i},()=>{n(),e(!0)})}),deletePaperInStorage=async(e,t)=>{let r=!1;(t=t||(await getStorage("papers")??{})).hasOwnProperty(e)&&(updateDuplicatedUrls(null,e,!0),r=(r=delete global.state.titleHashToIds[miniHash(t[e].title)])&&delete t[e]),r?(setStorage("papers",t),log("Successfully deleted paper",e)):log("Error: no deletion")},getTheme=async()=>{return await getStorage("checkDarkMode")?"dark":"light"},backupData=async r=>{chrome.storage.local.get("papersBackup",({papersBackup:e})=>{void 0===e&&(e={});for(const t of Object.keys(e).map(e=>parseInt(e)).sort((e,t)=>e{log("Backed up data with version: "+r.__dataVersion)})})};function dateDiffInDays(e,t){e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),t=Date.UTC(t.getFullYear(),t.getMonth(),t.getDate());return Math.floor((t-e)/864e5)}const weeklyBackup=async()=>{var e=await getStorage("weeklyBackups")??{};const t=new Date,r=Object.keys(e).map(e=>new Date(e)).sort((e,t)=>e.getTime()-t.getTime());if(0{let e=!1,t;const r=await getStorage("prefs")??{};(e=0===Object.keys(r).length?!0:e)&&(t=await getStorage(global.prefsStorageKeys)??{});let i={};for(const n of global.prefsCheckNames)i[n]=(t??r).hasOwnProperty(n)?(t??r)[n]:!(0<=global.prefsCheckDefaultFalse.indexOf(n));return i.checkOfficialRepos&&(setStorage("pwcPrefs",{official:!0}),delete i.checkOfficialRepos,setStorage("prefs",i)),e&&setStorage("prefs",i),i},getManifestDataVersion=()=>{const e=chrome.runtime.getManifest();return e.version.split(".").map((e,t)=>parseInt(e)*10**(4-2*t)).reduce((e,t)=>e+t)},versionToSemantic=e=>(e=(e-=1e4*(major=parseInt(e/1e4,10)))-100*(minor=parseInt(e/100,10)),`${major}.${minor}.`+e),validatePaper=(e,t=!0)=>{const r={addDate:{type:"string",desc:"the paper's date of addition to the Memory",default:e=>(new Date).toJSON()},author:{type:"string",desc:"` and `-separated authors `${firstName} ${lastName}`"},bibtex:{type:"string",desc:"BibTex citation with new lines (`\n`)"},code:{type:"object",desc:"the paper's code object as returned by the PapersWithCode API",default:e=>({})},codeLink:{type:"string",desc:"the paper's code link",default:e=>""},count:{type:"number",desc:"the paper's number of visits",default:e=>1},extras:{type:"object",desc:"extra information about the paper which may be required per source",optional:!0},favorite:{type:"boolean",desc:"user wants to star the paper",default:e=>!1},favoriteDate:{type:"string",desc:"date the paper was added as a favorite",default:e=>""},id:{type:"string",desc:"Unique PaperMemory ID"},key:{type:"string",desc:"BibTex citation key",default:e=>"defaultKey_"+e.id},lastOpenDate:{type:"string",desc:"When the paper was last opened",default:e=>(new Date).toJSON()},md:{type:"string",desc:"markdown-formatted string `[${title}](${pdfLink})`",default:e=>`[${e.title}](${e.pdfLink})`},note:{type:"string",desc:"the user's note for this paper",default:e=>""},pdfLink:{type:"string",desc:"the link to the paper's pdf"},source:{type:"string",desc:"the paper's source i.e. where it was added to the memory from"},tags:{type:"array[string]",desc:"the user's tags for this paper",default:e=>[]},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication"}};let i=[];for(const l in r)if(e.hasOwnProperty(l)){const c=r[l].type;var n,a=typeof e[l];c.includes("array")||"object"===c?c.includes("array")?Array.isArray(e[l])?(o=c.split("[")[1].replace("]",""),0{let t=!0,r="",i="",n;try{e.__dataVersion||(e.__dataVersion=1);var a,o=await migrateData(e,getManifestDataVersion(),!1);if(!o.success)return i="Could not migrate the data before storing it",o.error&&(i+=":
"+stringifyError(o.error)),{success:!1,message:i};for(const s in n=o.papers)s.startsWith("__")||(paperWarnings=validatePaper(n[s]).warnings)&&0"+paperWarnings.join("
"));r&&(a=await getStorage("papers")??{},setStorage("uploadBackup",a)),t=!1}catch(e){log("prepareOverwriteData error",e),i='
/!\\ OverwriteMemoryError:

'+stringifyError(e),t=!0}return{success:!t,message:i,warning:r,papersToWrite:n}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let r={};if(!e)return r;for(const n in global.knownPaperPages){var i=global.knownPaperPages[n];r[n]=!1;for(const a of i)"string"==typeof a?e.includes(a)&&(r[n]=!0):"function"==typeof a&&(r[n]=a(e))}return r.localFile=isKnownLocalFile(e),r.stored=!t&&await findLocalFile(e),r}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,r,i;const n=e.pdfLink;let a="";switch(e.source){case"arxiv":a="https://arxiv.org/abs/"+e.id.split("-")[1];break;case"neurips":a=n.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":a=n.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":a=n.replace("/pdf?","/forum?");break;case"biorxiv":a=n.replace(".full.pdf","");break;case"pmlr":a=n.split("/").slice(0,-1).join("/")+".html";break;case"acl":a=n.replace(".pdf","");break;case"pnas":a=n.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":a=n.replace(".pdf","");break;case"acs":a=n.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":a=n.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":a=n.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var o=n.match(/PMC\d+/)[0];a=n.split(o)[0]+o;break;case"ijcai":var o=n.replace(".pdf","").split("/").last().match(/[1-9]\d*/),s=n.match(/proceedings\/\d+/gi)[0].split("/")[1];a=`https://www.ijcai.org/proceedings/${s}/`+o;break;case"acm":a=n.replace("/doi/pdf/","/doi/");break;case"ieee":a="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":a=e.extra.url;break;case"aps":[t,r]=parseUrl(n).pathname.split("/").slice(1,3),a=n.replace(`/${t}/${r}/`,`/${t}/abstract/`);break;case"wiley":a=n.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":s=n.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];a="https://www.sciencedirect.com/science/article/pii/"+s;break;case"science":(i=n.split("/doi/")[1]).startsWith("10.")||(i=i.split("/").slice(1).join("/")),a="https://science.org/doi/full/"+i;break;case"frontiers":a=n.replace(/\/pdf$/,"/full");break;default:a="https://xkcd.com/1969/"}return a.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var r=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),i=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let n={};for(const o of t){let t;try{(t=await parseIdFromUrl(o.finalUrl))&&e.hasOwnProperty(t)&&(n[t]=o)}catch(e){t=null}if(!t){const s=i[o.id];var a=Object.entries(r).find(([,e])=>s.includes(e));a&&(n[a[0]]=o)}}return n},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:r,...i}=e;let n={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,...i};for(const a in r)(!t.hasOwnProperty(a)||r[a]&&!t[a])&&(n[a]=r[a]);e.incrementCount&&1===n.count&&(n.count+=1);for(const o of e.overwrites)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async(t,e,n,a=!0,o={update:()=>{},preprints:()=>{}})=>{const s=Date.now();let l,c,p={};console.group("%cPaperMemory parsing 📕",global.consolHeaderStyle),global.state.papers=await getStorage("papers")??{};var r=await parseIdFromUrl(t),i=global.state.papers.hasOwnProperty(r);if(r&&i)l=updatePaperVisits(global.state.papers[r]),c=!1;else{if(!(l=await makePaper(e,t)))return;i=findFuzzyPaperMatch(global.state.titleHashToIds,l);if(i&&a){let e=global.state.papers[i];log("New paper",l,"already exists as",e),addPaperToTitleHashToId(l),!l.venue&&e.venue||l.venue&&e.venue?(e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate"]}),updateDuplicatedUrls(t,i)):!e.venue&&l.venue&&(await updateDuplicatedUrls(paperToAbs(e),l.id),await updateDuplicatedUrls(paperToPDF(e),l.id),await deletePaperInStorage(e.id,global.state.papers),e=mergePapers({newPaper:l,oldPaper:e,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year"]})),l=updatePaperVisits(e),c=!1}else c=!0}if(!l.codeLink||!l.venue)try{const g=await tryPWCMatch(l);var u=!l.codeLink&&g?.url,d=g?.note,f=g?.bibtex,h=!l.venue&&g?.venue;(p={codeLink:u,note:d,venue:h,bibtex:f}).codeLink&&(l.codeLink=p.codeLink,g.hasOwnProperty("note")&&delete g.note,l.code=g)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),c=!1),a&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{o.update(l);let e;if(c||p.codeLink?c?(a?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it."),log("paper: ",l),e="Added to your Memory",p.codeLink&&(e+="
(+ repo from PapersWithCode)
"),n&&n.checkFeedback&&a&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",n&&n.checkFeedback&&a&&feedback(e)):a&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue){var t,r=await tryPreprintMatch(l);for(const i of["note","venue","bibtex"])l[i]&&"bibtex"!==i||(t=r[i]??p[i])&&(log(`Updating preprint ${i} to`,t),l[i]=t);global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e.id.includes(r))?.id,parseIdFromUrl=async t=>{let r;var e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),i=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var n=t.match(/\d{4}\.\d{4,5}/g)[0];r="Arxiv-"+n;const o=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));o&&(r=o.find(e=>!e.startsWith("Arxiv-"))??r)}else if(e.neurips){var n=t.split("/paper/")[1].split("/")[0],a=t.split("/").last().split("-")[0].slice(0,8);r=`NeurIPS-${n}_`+a}else if(e.cvf)r=parseCVFUrl(t).id;else if(e.openreview){n=t.match(/id=\w+/)[0].replace("id=","");r=findPaperId(i,"openreview",n)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),r="Biorxiv-"+e;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));s&&(r=s.find(e=>!e.startsWith("Biorxiv-"))??r)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];a="20"+l.match(/\d+/)[0];r=`PMLR-${a}-`+l}else if(e.acl){n=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();r=findPaperId(i,"acl",n)}else if(e.pnas){a=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];r=findPaperId(i,"pnas",a)}else if(e.nature){n=(t=t.replace(".pdf","").split("#")[0]).split("/").last();r=findPaperId(i,"nature",n)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);r="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1]);r="IOPscience_"+doi}else if(e.jmlr){const c=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();a="20"+c.match(/\d+/)[0];r=`JMLR-${a}_`+c}else if(e.pmc){n=t.match(/PMC\d+/g)[0].replace("PMC","");r=findPaperId(i,"pmc",n)}else if(e.ijcai){a=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),n=t.match(/proceedings\/\d+/gi)[0].split("/")[1];r=`IJCAI-${n}_`+a}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];r=findPaperId(i,"acm",miniHash(doi))}else if(e.ieee){n=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];r=findPaperId(i,"ieee",n)}else if(e.springer){const p=global.sourceExtras.springer.types;let e=p.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}a=t.split(`/${e}/`)[1].split("?")[0].replace(".pdf","");r=findPaperId(i,"springer",miniHash(a))}else if(e.aps){var[n,a]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${n}/${a}/`).last();r=findPaperId(i,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");r=findPaperId(i,"wiley",miniHash(doi))}else if(e.sciencedirect){n=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];r=findPaperId(i,"sciencedirect",miniHash(n))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),r=findPaperId(i,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),r=findPaperId(i,"frontiers",miniHash(doi));else{if(!e.localFile)throw new Error("unknown paper url");r=e.localFile}return r},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var r=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>i.includes(e.title));return 0!==r.length&&r[0].id},makeMdLink=(e,t={})=>{var r=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let i="",n=(!t.checkMdYearVenue||(i=(i=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&i[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(i="",e.venue&&(i+=e.venue+" "),i+=e.year),e.title);return`[${n=i?`${n} (${i.replace(/\s+/g," ")})`:n}](${r})`},initState=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),async(e,t)=>{const r=[];r.unshift(Date.now()),console.groupCollapsed("%cPaperMemory Init ✅",global.consolHeaderStyle),void 0===e&&(e=await getStorage("papers")??{},log("Time to retrieve stored papers (s): "+(Date.now()-r[0])/1e3)),r.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),log("Time to parse data version (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleFunction=(await getTitleFunction()).titleFunction,log("Time to make title function (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),weeklyBackup(),log("Time to backup papers (weekly) (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now());var i,n,a=await migrateData(e,global.state.dataVersion);log("Time to migrate data (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),e=a.papers,global.state.papers=e,global.state.prefs=await getPrefs(),log("Time to retrieve user preferences (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},log("Time to retrieve sources to ignore (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},log("Time to retrieve sources to urlHashToId (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.titleHashToIds={};for([i,n]of Object.entries(cleanPapers(e))){var o=miniHash(n.title);global.state.titleHashToIds.hasOwnProperty(o)||(global.state.titleHashToIds[o]=[]),global.state.titleHashToIds[o].push(i)}log("Time to hash titles (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),log("Time to match all local files (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),log("Time to sort memory (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now()),makeTags(),log("Time to make tags (s): "+(Date.now()-r[0])/1e3),r.unshift(Date.now())),info("State init duration (s): "+(Date.now()-r.last())/1e3),console.groupEnd()}),sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers),global.state.papersList.sort(orderPapers)},orderPapers=(e,t)=>{let r=e[global.state.sortKey],i=t[global.state.sortKey];return void 0===r&&(r=""),void 0===i&&(i=""),"string"==typeof r&&(r=r.toLowerCase(),i=i.toLowerCase()),0<=global.descendingSortKeys.indexOf(global.state.sortKey)?r>i?-1:1:r>i?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const r of t.tags)e.add(r);global.state.paperTags=Array.from(e),global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},r=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let i=t[r[e=void 0===e?getRandomInt(r.length):e]];return i=void 0===i?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:i},getTitleFunction=async(code=null)=>{let titleFunction;code=code||await getStorage("titleFunctionCode"),void 0===code&&(code=global.defaultTitleFunctionCode);let errorMessage;try{titleFunction=eval(code)}catch(error){errorMessage="Error parsing the title function: "+error,log("Error parsing the title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}try{const examplePaper=await getExamplePaper(0),result=titleFunction(examplePaper);if("string"!=typeof result)throw new Error(`Result ${result} is not a string`)}catch(error){errorMessage="Error executing the title function: "+error,log("Error testing the user's title function. Function string then error:"),log(code),log(error),titleFunction=eval(global.defaultTitleFunctionCode),code=global.defaultTitleFunctionCode}return{titleFunction:titleFunction,code:code.trim(),errorMessage:errorMessage}},stateTitleFunction=paperOrId=>{let paper=paperOrId;if("string"==typeof paperOrId&&(paper=global.state.papers[paperOrId],void 0===paper))return log("Error in stateTitleFunction: unknown id",paperOrId),"Unknown ID";let name;try{name=global.state.titleFunction(paper)}catch(error){log("Error in stateTitleFunction:",error),name=eval(global.defaultTitleFunctionCode)(paper)}return name.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,r,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===r))&&e.length){for(const i of e)warn("Removing duplicated url",t,"for",r),delete global.state.urlHashToId[i];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=r,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&(dummyModule=module,dummyModule.exports={initState:initState,getExamplePaper:getExamplePaper,getTitleFunction:getTitleFunction,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,r;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(r=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:i,year:n}=parseCVFUrl(e);t=t.replace(`/content_${i}_${n}/`,`/content_${i.toLowerCase()}_${n}/`),r=await fetch(t).then(e=>e.ok?e.text():"")}return r},fetchOpenReviewNoteJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?id="+e).then(e=>e.json())},fetchOpenReviewForumJSON=async e=>{e=e.match(/id=([\w-])+/)[0].replace("id=","");return fetch("https://api.openreview.net/notes?forum="+e).then(e=>e.json())},fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),r=t.ok?await t.text():"";return r.trim()}catch(e){return console.log("fetchText error:",e),""}},fetchJSON=async e=>{try{const t=await fetch(e);return t.ok?await t.json():null}catch(e){return console.log("fetchJSON error:",e),null}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const o=e.message;log("Crossref data.message: ",o);var t=o.author.map(e=>e.given+" "+e.family).join(" and ");const s=o.issued?o.issued["date-parts"][0][0]+"":o.published?o.published["date-parts"][0][0]+"":null;if(s){var r=o.title[0];if(r){var i=o["container-title"][0]??"Springer",n=[miniHash(o.author[0].family),s.slice(2),firstNonStopLowercase(r)].join(""),a=o.DOI;let e={entryType:"book"===o.type?"book":"book-chapter"===o.type?"InBook":o.type.includes("article")?"Article":"InProceedings",citationKey:n,publisher:o.publisher,author:t,title:r,year:s,doi:a};o.page&&(e.pages=o.page),o.volume&&(e.volume=o.volume),o.type.includes("journal")&&(e.journal=i),o.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=n.URL),(t=o.link.find(e=>"text/html"===e["content-type"])??o.link[0])&&(e.url=t.URL));r=bibtexToString(e);return{...e,bibtex:r,venue:i}}error("Cannot find title in CrossRef data",o)}else error("Cannot find year in CrossRef data",o)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{e=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return extractCrossrefData(e)},fetchSemanticsScholarDataForDoi=async e=>{const t=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`);let r;var i;return t&&(r={},t.venue&&(r.venue=t.venue),t.year&&(r.year=t.year),t.authors&&(r.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(r.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(r.title),i=bibtexToString({entryType:"article",citationKey:e,...r}),r.bibtex=i,r.key=e),r},getMetaContent=(e,t,r=!1)=>{e="meta"+Object.entries(e).map(([e,t])=>`[${e}='${t}']`).join("");return r?queryAll(t,e).map(e=>e.getAttribute("content")??""):t.querySelector(e)?.getAttribute("content")??""},extractDataFromDCMetaTags=e=>{const t=getMetaContent({name:"dc.Creator"},e,!0).map(e=>e.replace(/([a-z])([A-Z])/g,"$1 $2")).join(" and ");if(!t)return null;var r=getMetaContent({name:"dc.Date"},e).split("-")[0],i=getMetaContent({name:"dc.Publisher"},e).replaceAll("\n"," "),n=getMetaContent({name:"dc.Title"},e),a=getMetaContent({name:"citation_journal_title"},e),o=(""+t.split(" and ")[1].split(" ")[0]+r+firstNonStopLowercase(n)).toLowerCase(),e=getMetaContent({name:"dc.Date",scheme:"doi"},e),s=bibtexToString({citationKey:o,entryType:"article",title:n,author:t,year:r,doi:e,publisher:i,journal:a});return{author:t,year:r,publisher:i,title:n,venue:a,key:o,doi:e,bibtex:s,note:`Published @ ${a} (${r})`}},makeArxivPaper=async e=>{e=e.match(/\/(\d{4}\.\d{4,5})/)[1];const t=await fetchArxivXML(e),r=await t.text();var i=(new DOMParser).parseFromString(r.replaceAll("\n",""),"text/xml");const n=queryAll(i,"author name").map(e=>e.innerHTML);var a=n.join(" and "),o=Array.from(i.getElementsByTagName("link")).map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),s=i.querySelector("entry title").innerHTML,i=i.querySelector("entry published").innerHTML.slice(0,4),l=n[0].split(" ").last().toLowerCase()+i+firstNonStopLowercase(s),e="Arxiv-"+e,c="";return{author:a,bibtex:c+`@article{${l}, `+`title={${s} }, From 7736d34812a912eacf465de98eaa26da8a6c10de Mon Sep 17 00:00:00 2001 From: vict0rsch Date: Sat, 20 Aug 2022 19:09:31 +0100 Subject: [PATCH 05/80] working pull from new PM instance --- src/background/background.js | 31 ++++++++++++++++ src/options/options.css | 23 ++++++++++++ src/options/options.html | 6 +++ src/options/options.js | 72 +++++++++++++++++++++++++++++++++--- src/popup/js/popup.js | 6 ++- src/popup/min/popup.min.js | 2 +- src/shared/js/utils/sync.js | 42 ++++++++++++++++++++- src/shared/min/utils.min.js | 2 +- 8 files changed, 175 insertions(+), 9 deletions(-) diff --git a/src/background/background.js b/src/background/background.js index 77b38ab1..8a53a87e 100755 --- a/src/background/background.js +++ b/src/background/background.js @@ -163,6 +163,25 @@ const findCodesForPaper = async (request) => { return { ...codes[0], ...code }; }; +const writeSyncPapers = async () => { + let success = false; + const { ok, error, payload } = await getGist(); + if (ok) { + console.log("Writing to Github..."); + const papers = (await getStorage("papers")) ?? {}; + const dataFile = getDataFile(payload.gist); + dataFile.overwrite(JSON.stringify(papers, null, "")); + await dataFile.save(); + console.log("Writing to Github... Done!"); + success = true; + } else { + console.warn(payload); + error && console.warn(error); + console.log("Writing to Github canceled."); + } + return success; +}; + chrome.runtime.onMessage.addListener((payload, sender, sendResponse) => { if (payload.type === "update-title") { const { title, url } = payload.options; @@ -190,6 +209,8 @@ chrome.runtime.onMessage.addListener((payload, sender, sendResponse) => { }); } else if (payload.type === "hello") { sendResponse("Connection to background script established."); + } else if (payload.type === "writeSync") { + writeSyncPapers().then(sendResponse); } return true; }); @@ -260,3 +281,13 @@ chrome.commands.onCommand.addListener((command) => { }); } }); + +chrome.runtime.onConnect.addListener(function (port) { + if (port.name === "PaperMemorySync") { + console.log("PaperMemorySync connected."); + port.onDisconnect.addListener(async function () { + console.log("PaperMemorySync: popup has been closed"); + await writeSyncPapers(); + }); + } +}); diff --git a/src/options/options.css b/src/options/options.css index efd46d4a..d16c8df0 100644 --- a/src/options/options.css +++ b/src/options/options.css @@ -444,6 +444,29 @@ input { background-color: rgb(27, 159, 7); color: rgb(223, 223, 223); } +#save-pat:hover { + color: white; +} #pat-feedback { color: rgb(150, 102, 13); } + +@keyframes rotation { + from { + transform: rotate(0deg); + } + to { + transform: rotate(359deg); + } +} + +.pm-loader { + animation: rotation 1.3s infinite linear; + height: 50px; + width: 50px; + border-left: 4px dotted salmon; + border-radius: 100%; + margin: auto; + margin-top: 1rem; + margin-bottom: 1rem; +} diff --git a/src/options/options.html b/src/options/options.html index 1922c6b5..6ad41591 100644 --- a/src/options/options.html +++ b/src/options/options.html @@ -456,6 +456,7 @@

Online synchronization

placeholder="ghp_0IurqH9T1wj0E1E3YuroyvykuYI17Rl5hdN9" />
+

@@ -468,6 +469,11 @@

Start syncing your data to Github?

In case anything goes wrong, we'll still download a backup locally

+ + +
+
+ ');const s=findEl("isArxiv").innerHTML;setHTML("isArxiv",a),addListener("no-paper-why-code","click",()=>{showPopupModal("noPaper")}),e&&addListener("manual-trigger-btn","click",async()=>{showId("manual-loader-container");try{var t=await isPaper(o);let e;var a=await addOrUpdatePaper(o,t);if(!a)return;(e=a.paper)&&(hideId("manual-loader-container"),setHTML("isArxiv",s),popupMain(o,t,!0))}catch(e){hideId("manual-loader-container"),setHTML("manual-parsing-error",`${"There was an issue parsing this paper.
Raise an issue on Github if you think it is a bug.
Attempted url: "+o}
`),warn("Manual Parsing Error:",e)}})},showConfirmDeleteModal=e=>{var t=global.state.papers[e].title;setTextId("delete-modal-title",t),setHTML("delete-paper-modal-hidden-id",e),showId("delete-paper-modal","flex")},copyAndConfirmMemoryItem=(e,t,a,o)=>{copyTextToClipboard(t);const s=o?findEl("popup-feedback-copied"):findEl(e,"memory-item-feedback");s&&(s.innerText=a,fadeIn(s),setTimeout(()=>{fadeOut(s)},2e3))},focusExistingOrCreateNewCodeTab=s=>{(s=s.replace("http://","https://")).startsWith("https://")||(s="https://"+s);var e=new URL(s)["origin"];chrome.tabs.query({url:e+"/*"},e=>{for(const t of e)if(t.url.includes(s)){const a={active:!0},o={focused:!0};return void chrome.windows.getCurrent(e=>{e.id!==t.windowId?chrome.windows.update(t.windowId,o,()=>{chrome.tabs.update(t.id,a)}):chrome.tabs.update(t.id,a)})}chrome.tabs.create({url:s})})},focusExistingOrCreateNewPaperTab=(i,l)=>{chrome.tabs.query({},async e=>{var t=global.state.prefs;let a=[];for(const r of e){let e;try{e=r.url&&await parseIdFromUrl(r.url)}catch(e){}e&&e===i.id&&a.push(r)}let o;var s,e=t.checkPreferPdf?a.filter(e=>e.url&&isPdfUrl(e.url)):a.filter(e=>e.url&&!isPdfUrl(e.url));0e.url.startsWith("file://")),o=(0{e.id!==o.windowId?chrome.windows.update(o.windowId,{focused:!0},()=>{chrome.tabs.update(o.id,{active:!0})}):chrome.tabs.update(o.id,{active:!0})}):global.state.files.hasOwnProperty(i.id)&&!l?chrome.downloads.open(global.state.files[i.id].id):chrome.tabs.create({url:(t.checkPreferPdf?paperToPDF:paperToAbs)(i)}),global.state.papers[i.id].count+=1,chrome.storage.local.set({papers:global.state.papers})})},saveNote=(t,a)=>{global.state.papers[t].note=a,chrome.storage.local.set({papers:global.state.papers},()=>{setHTML(findEl(t,"memory-note-div"),a?`
Note: ${a}
`:'
');var e=findEl("popup-form-note-textarea--"+t);val(e,a),val(findEl(t,"form-note-textarea"),a)})},saveCodeLink=(t,a)=>{a=a.trim(),global.state.papers[t].codeLink=a,chrome.storage.local.set({papers:global.state.papers},()=>{var e=a.replace(/^https?:\/\//,""),e=(setHTML(findEl(t,"memory-code-link"),e),setHTML("popup-code-link",e),val(findEl(t,"form-code-input"),a),(a?showId:hideId)("popup-code-link"),findEl("popup-form-codeLink--"+t));val(e,a)})},saveFavoriteItem=(o,s)=>{global.state.papers[o].favorite=s,global.state.papers[o].favoriteDate=(new Date).toJSON(),chrome.storage.local.set({papers:global.state.papers},()=>{var e,t;s?(addClass("memory-container--"+o,"favorite"),addClass(findEl(o,"memory-item-favorite").querySelector("svg"),"favorite")):(removeClass("memory-container--"+o,"favorite"),removeClass(findEl(o,"memory-item-favorite").querySelector("svg"),"favorite")),"favoriteDate"===global.state.sortKey&&(s||(sortMemory(),displayMemoryTable()),e=global.state.sortedPapers.filter(e=>e.favorite).length,(t=findEl("memory-search"))&&setPlaceholder(t,`Search ${e} entries`));let a=findEl("checkFavorite--"+o);a&&(a.checked=s)})},setMemorySortArrow=e=>{let t;t="up"===e?'':'',setHTML("memory-sort-arrow",t)},reverseMemory=()=>{global.state.sortedPapers.reverse(),global.state.papersList.reverse()},searchMemory=e=>{const t=e.toLowerCase().split(" ");let a=[];for(const o of global.state.sortedPapers){const s=o.title.toLowerCase(),r=o.author.toLowerCase(),i=o.note.toLowerCase(),l=o.tags.join(" ").toLowerCase(),n=getDisplayId(o.id).toLowerCase(),d=o.venue.toLowerCase();!t.every(e=>s.includes(e)||r.includes(e)||i.includes(e)||l.includes(e)||n.includes(e)||d.includes(e))||global.state.showFavorites&&!o.favorite||a.push(o)}global.state.papersList=a},searchMemoryByYear=e=>{var t=e.includes("<")?"smaller":e.includes(">")?"greater":"";const a=e.replace("y:","").replace(/(<|>)/g,"").toLowerCase().replaceAll(","," ").split(" ").filter(e=>04===e.length?e:"20"+e).map(e=>parseInt(e,10));console.log("searchYears: ",a);let o=[],s=(e,t)=>e===t;"smaller"==t?s=(e,t)=>tes(e,i))&&o.push(r)}global.state.papersList=o},searchMemoryByTags=e=>{const t=e.replace("t:","").toLowerCase().split(" ");let a=[];for(const o of global.state.sortedPapers){const s=o.tags.map(e=>e.toLowerCase());!t.every(t=>s.some(e=>0<=e.indexOf(t)))||global.state.showFavorites&&!o.favorite||a.push(o)}global.state.papersList=a},searchMemoryByCode=e=>{const a=e.replace("c:","").toLowerCase().split(" ");let o=[];for(const s of global.state.sortedPapers){let t=s.codeLink||"";t=t.toLowerCase(),!a.every(e=>t.includes(e))||global.state.showFavorites&&!s.favorite||o.push(s)}global.state.papersList=o},updatePaperTagsHTML=e=>{setHTML(findEl(e,"tag-list"),global.state.papers[e].tags.map(e=>`${e}`).join(""))},updateTagOptions=e=>{updateAllMemoryPaperTagOptions();var t=getTagsOptions(global.state.papers[e]);setHTML("popup-item-tags--"+e,t)},updatePaperTags=(t,e)=>{let a;a=e.startsWith("#")?findEl(e.replace("#","")):findEl(t,e);e=parseTags(a);let o=!1;new Set;arraysIdentical(global.state.papers[t].tags,e)||(o=!0),global.state.papers[t].tags=e,o&&chrome.storage.local.set({papers:global.state.papers},()=>{makeTags(),updateTagOptions(t),updatePaperTagsHTML(t);for(const e of queryAll(findEl(t,"tag-list"),".memory-tag"))addListener(e,"click",handleTagClick)})},displayOnScroll=o=>delay(()=>{var e=findEl("memory-table").getBoundingClientRect()["bottom"],t=o?findEl("memory-container").getBoundingClientRect().height:window.innerHeight,a=global.state.currentMemoryPagination*global.state.memoryItemsPerPage;Math.abs(e-t){var t=Date.now(),a=findEl("memory-table"),o=(0===e&&(setHTML(a,""),global.state.currentMemoryPagination=0),{edit:"Edit paper details",copyMd:"Copy Markdown-formatted link",copyBibtext:"Copy Bibtex citation",visits:"Number of times you have opened this paper",openLocal:"Open downloaded pdf"});let s=[];for(const r of global.state.papersList.slice(e*global.state.memoryItemsPerPage,(e+1)*global.state.memoryItemsPerPage))try{s.push(getMemoryItemHTML(r,o))}catch(e){log("displayMemoryTable error:"),log(e),log(r)}0===e?setHTML(a,s.join("")):a.insertAdjacentHTML("beforeend",s.join("")),addEventToClass(".back-to-focus","click",handleBackToFocus),addEventToClass(".memory-delete","click",handleDeleteItem),addEventToClass(".memory-item-link","click",handleOpenItemLink),addEventToClass(".memory-code-link","click",handleOpenItemCodeLink),addEventToClass(".memory-item-md","click",handleCopyMarkdownLink),addEventToClass(".memory-item-bibtex","click",handleCopyBibtex),addEventToClass(".memory-item-copy-link","click",handleCopyPDFLink),addEventToClass(".memory-item-openLocal","click",handleMemoryOpenLocal),addEventToClass(".memory-item-favorite","click",handleAddItemToFavorites),addEventToClass(".cancel-note-form","click",handleCancelPaperEdit),addEventToClass(".memory-item-edit","click",handleTogglePaperEdit),addEventToClass(".memory-tag","click",handleTagClick),setFormChangeListener(void 0,!1),addEventToClass(".form-note-textarea","focus",handleTextareaFocus);e=Date.now();info("Display duration (s): "+(e-t)/1e3)},makeMemoryHTML=async()=>{setPlaceholder("memory-search",`Search ${global.state.papersList.length} entries ...`),displayMemoryTable();let e=300;global.state.papersList.length<20?e=0:global.state.papersList.length<100&&(e=150),addListener("memory-search","keypress",delay(handleMemorySearchKeyPress(),e)),addListener("memory-search","clear-search",handleMemorySearchKeyPress(!0)),addListener("memory-search","keyup",handleMemorySearchKeyUp),addListener("delete-paper-modal-cancel-button","click",handleCancelModalClick),addListener("delete-paper-modal-confirm-button","click",handleConfirmDeleteModalClick),addListener("filter-favorites","click",handleFilterFavorites),addListener("memory-select","change",handleMemorySelectChange),addListener("memory-sort-arrow","click",handleMemorySortArrow),addListener("memory-container","scroll",displayOnScroll(!0))},openMemory=()=>{global.state.prefsIsOpen&&closeMenu(),global.state.memoryIsOpen=!0,hideId("memory-switch-open"),showId("memory-switch-close"),hideId("menu-switch"),dispatch("memory-switch","blur"),slideDown("memory-container",200,()=>{setTimeout(()=>{dispatch("memory-search","focus")},100)}),setTimeout(()=>{addListener("memory-search-clear-icon","click",handleClearSearch),val("memory-select","lastOpenDate"),setMemorySortArrow("down")},200)},closeMemory=()=>{dispatch("memory-switch","blur"),hideId("memory-switch-close"),showId("memory-switch-open"),slideUp("memory-container",200,()=>{val("memory-search",""),dispatch("memory-search","clear-search"),global.state.memoryIsOpen=!1,global.state.showFavorites&&dispatch("filter-favorites","click"),showId("menu-switch","flex")})},closeMenu=()=>{slideUp("menu-container",300),setHTML("menu-switch",tablerSvg("settings","menu-switch-svg",["tabler-icon","menu-svg"])),dispatch("menu-switch","blur"),global.state.prefsIsOpen=!1},openMenu=()=>{slideDown("menu-container",300),dispatch("menu-switch","blur"),setHTML("menu-switch",tablerSvg("circle-x","close-menu-btn",["tabler-icon","menu-svg"])),global.state.prefsIsOpen=!0},getAndTrackPopupMenuChecks=(e,t)=>{let a={};for(const o of t){a[o]=e.hasOwnProperty(o)?e[o]:!(0<=global.prefsCheckDefaultFalse.indexOf(o));const s=findEl(o);s&&(s.checked=a[o])}setStorage("prefs",a);for(const r of t)addListener(r,"change",handlePrefsCheckChange)},showPopupModal=e=>{document.querySelectorAll(".popup-modal-content").forEach(hideId),showId(`modal-${e}-content`,"contents"),style("popup-modal-wrapper","display","flex"),Array.from(document.getElementsByTagName("a")).forEach(e=>{addListener(e,"click",()=>{chrome.tabs.create({url:e.getAttribute("href")})})})},setStandardPopupClicks=()=>{addListener("helpGithubLink","click",()=>{chrome.tabs.create({url:"https://github.com/vict0rsch/PaperMemory"})}),addListener("whats-new-container","click",()=>{chrome.storage.local.get("whatsnew",({whatsnew:e})=>{var t=chrome.runtime.getManifest().version;(e=void 0===e?{}:e).hasOwnProperty(t)||hideId("whats-new-marker"),chrome.storage.local.set({whatsnew:{...e,[t]:!0}}),showPopupModal("whatsnew")})}),addListener("keyboardShortcuts","click",()=>{showPopupModal("keyboard")}),addListener("keyboardShortcutsMenu","click",()=>{showPopupModal("keyboard")}),shouldWarn("pdf-title",e=>{e&&(showId("warning-button"),addListener("warning-button","click",async()=>{showPopupModal("warning-pdf-title");let e=await getStorage("userWarnings")??{};e["pdf-title"]=!0,setStorage("userWarnings",e),hideId("warning-button")}))}),addListener("close-popup-modal","click",()=>{style("popup-modal-wrapper","display","none")}),addListener(window,"click",e=>{e.target===findEl("popup-modal-wrapper")&&style("popup-modal-wrapper","display","none")}),addListener("menu-switch","click",()=>{(global.state.prefsIsOpen?closeMenu:openMenu)()}),addListener("memory-switch","click",handleMemorySwitchClick)},popupMain=async(a,e,t=!1)=>{console.log(navigator.userAgent),"PuppeteerAgent"===navigator.userAgent&&(info("Is puppet"),style(document.body,"min-width","500px"),style(document.body,"max-width","500px"),style(document.body,"width","500px"),style("popup-modal-wrapper","min-width","500px"),style("popup-modal-wrapper","max-width","500px"),style("popup-modal-wrapper","width","500px")),addListener(document,"keydown",handlePopupKeydown),chrome.storage.local.get("whatsnew",({whatsnew:e})=>{var t=chrome.runtime.getManifest().version;e&&e.hasOwnProperty(t)||showId("whats-new-marker")}),t?(hideId("memory-switch"),showId("memory-spinner"),await initState(),hideId("memory-spinner"),showId("memory-switch"),makeMemoryHTML()):setStandardPopupClicks();const o=await getPrefs();if(getAndTrackPopupMenuChecks(o,global.prefsCheckNames),addListener("advanced-configuration","click",()=>{chrome.runtime.openOptionsPage()}),addListener("full-memory","click",()=>{chrome.tabs.create({url:chrome.extension.getURL("src/fullMemory/fullMemory.html")})}),Object.values(e).some(e=>e)){setTimeout(()=>{document.body.style.height="auto",document.body.style.minHeight="450px"},0),showId("isArxiv","flex");const s=await parseIdFromUrl(a);if(!(global.state.currentId=s)||!global.state.papers.hasOwnProperty(s))return log("Unknown id "+s),await updatePopupPaperNoMemory(a),void(o.checkDirectOpen&&!o.checkNoAuto&&dispatch("memory-switch","click"));const r=global.state.papers[s];t=r.id.replaceAll(".","\\.");setTextId("popup-paper-title",r.title.replaceAll("\n","")),setTextId("popup-authors",cutAuthors(r.author,350).replace(/({|})/g,"")),r.codeLink&&(showId("popup-code-link"),setTextId("popup-code-link",r.codeLink.replace(/^https?:\/\//,""))),log("Popup paper:",r),setHTML("popup-memory-edit",getPopupEditFormHTML(r)),setHTML("popup-copy-icons",getPopupPaperIconsHTML(r,a,e)),findEl("checkFavorite--"+s).checked=r.favorite,$("#popup-item-tags--"+t).select2({...global.select2Options,width:"87%"}),addListener("popup-form-note-textarea--"+s,"focus",()=>{textareaFocusEnd(this)}),setFormChangeListener(s,!0),addListener("popup-delete-paper","click",handlePopupDeletePaper(s)),addListener("popup-memory-item-scirate--"+s,"click",()=>{var e=r.id.split("-").last();chrome.tabs.update({url:"https://scirate.com/arxiv/"+e}),window.close()}),addListener("popup-memory-item-link--"+s,"click",()=>{var e=paperToPDF(r),t=paperToAbs(r);chrome.tabs.update({url:isPdfUrl(a)?t:e}),window.close()}),addListener("popup-code-link","click",()=>{var e=findEl("popup-code-link").textContent;e&&focusExistingOrCreateNewCodeTab(e)}),addListener("popup-memory-item-copy-link--"+s,"click",()=>{var e=(o.checkPreferPdf?paperToPDF:paperToAbs)(r),t=o.checkPreferPdf?"PDF":"Abstract";copyAndConfirmMemoryItem(s,e,t+" link copied!",!0)}),addListener("popup-memory-item-md--"+s,"click",()=>{var e=global.state.prefs,t=(console.log("state.prefs: ",state.prefs),makeMdLink(r,e)),e=e.checkPreferPdf?"PDF":"Abstract";copyAndConfirmMemoryItem(s,t,`Markdown link to ${e} copied!`,!0)}),addListener("popup-memory-item-bibtex--"+s,"click",()=>{var e=bibtexToString(global.state.papers[s].bibtex);copyAndConfirmMemoryItem(s,e,"Bibtex citation copied!",!0)}),addListener("popup-memory-item-openLocal--"+s,"click",async()=>{var e=await findLocalFile(r);e?chrome.downloads.open(e.id):chrome.tabs.create({url:r.pdfLink})}),addListener("popup-memory-item-download--"+s,"click",async()=>{downloadPaperPdf(r)})}else o.checkDirectOpen&&dispatch("memory-switch","click")},query={active:!0,lastFocusedWindow:!0};window.location.href.includes("popup")&&chrome.tabs.query(query,async e=>{var e=e[0].url,t=(await initState(),await isPaper(e));Object.values(t).some(e=>e)||showId("notArxiv"),hideId("memory-spinner"),showId("memory-switch"),makeMemoryHTML(),popupMain(e,t),-1
${s}
`},getPopupPaperIconsHTML=(e,t,a)=>{var o=e.id,t=isPdfUrl(t)?"HTML":"PDF";let s="";global.state.prefs.checkScirate&&"arxiv"===e.source&&(s=``);e=global.state.prefs.checkStore&&(a.localFile||a.stored)?``:``;return`${s}`+e},getTagsOptions=e=>{const o=new Set(e.tags);return Array.from(global.state.paperTags).sort().map((e,t)=>{let a='