@chainlink/functions-toolkit
Version:
An NPM package with collection of functions that can be used for working with Chainlink Functions.
594 lines (476 loc) • 1.02 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.simulateScript = f()}})(function(){var define,module,exports;return (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=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global,Buffer){(function (){
(()=>{"use strict";var e={300:e=>{e.exports=require("buffer")},113:e=>{e.exports=require("crypto")},477:e=>{e.exports=require("querystring")},576:e=>{e.exports=require("string_decoder")},310:e=>{e.exports=require("url")},837:e=>{e.exports=require("util")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{r.r(n),r.d(n,{simulateScript:()=>We});const e=require("vm");var t=r.n(e);function o(e,t){return function(){return e.apply(t,arguments)}}const{toString:i}=Object.prototype,{getPrototypeOf:s}=Object,a=(c=Object.create(null),e=>{const t=i.call(e);return c[t]||(c[t]=t.slice(8,-1).toLowerCase())});var c;const u=e=>(e=e.toLowerCase(),t=>a(t)===e),l=e=>t=>typeof t===e,{isArray:f}=Array,d=l("undefined"),p=u("ArrayBuffer"),h=l("string"),m=l("function"),g=l("number"),y=e=>null!==e&&"object"==typeof e,b=e=>{if("object"!==a(e))return!1;const t=s(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},w=u("Date"),E=u("File"),S=u("Blob"),O=u("FileList"),R=u("URLSearchParams");function x(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),f(e))for(n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else{const o=r?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let s;for(n=0;n<i;n++)s=o[n],t.call(null,e[s],s,e)}}function v(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,o=r.length;for(;o-- >0;)if(n=r[o],t===n.toLowerCase())return n;return null}const A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,T=e=>!d(e)&&e!==A,B=(N="undefined"!=typeof Uint8Array&&s(Uint8Array),e=>N&&e instanceof N);var N;const P=u("HTMLFormElement"),j=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),C=u("RegExp"),U=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};x(r,((r,o)=>{!1!==t(r,o,e)&&(n[o]=r)})),Object.defineProperties(e,n)},I="abcdefghijklmnopqrstuvwxyz",_="0123456789",F={DIGIT:_,ALPHA:I,ALPHA_DIGIT:I+I.toUpperCase()+_},L=u("AsyncFunction"),D={isArray:f,isArrayBuffer:p,isBuffer:function(e){return null!==e&&!d(e)&&null!==e.constructor&&!d(e.constructor)&&m(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||m(e.append)&&("formdata"===(t=a(e))||"object"===t&&m(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&p(e.buffer),t},isString:h,isNumber:g,isBoolean:e=>!0===e||!1===e,isObject:y,isPlainObject:b,isUndefined:d,isDate:w,isFile:E,isBlob:S,isRegExp:C,isFunction:m,isStream:e=>y(e)&&m(e.pipe),isURLSearchParams:R,isTypedArray:B,isFileList:O,forEach:x,merge:function e(){const{caseless:t}=T(this)&&this||{},r={},n=(n,o)=>{const i=t&&v(r,o)||o;b(r[i])&&b(n)?r[i]=e(r[i],n):b(n)?r[i]=e({},n):f(n)?r[i]=n.slice():r[i]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&x(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(x(t,((t,n)=>{r&&m(t)?e[n]=o(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let o,i,a;const c={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],n&&!n(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==r&&s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:a,kindOfTest:u,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(f(e))return e;let t=e.length;if(!g(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:P,hasOwnProperty:j,hasOwnProp:j,reduceDescriptors:U,freezeMethods:e=>{U(e,((t,r)=>{if(m(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];m(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return f(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:v,global:A,isContextDefined:T,ALPHABET:F,generateString:(e=16,t=F.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&m(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(y(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const o=f(e)?[]:{};return x(e,((e,t)=>{const i=r(e,n+1);!d(i)&&(o[t]=i)})),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn:L,isThenable:e=>e&&(y(e)||m(e))&&m(e.then)&&m(e.catch)};function k(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o)}D.inherits(k,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:D.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const q=k.prototype,M={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{M[e]={value:e}})),Object.defineProperties(k,M),Object.defineProperty(q,"isAxiosError",{value:!0}),k.from=(e,t,r,n,o,i)=>{const s=Object.create(q);return D.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),k.call(s,e.message,t,r,n,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const H=k;function z(e){return D.isPlainObject(e)||D.isArray(e)}function J(e){return D.endsWith(e,"[]")?e.slice(0,-2):e}function W(e,t,r){return e?e.concat(t).map((function(e,t){return e=J(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const $=D.toFlatObject(D,{},null,(function(e){return/^is[A-Z]/.test(e)})),K=function(e,t,r){if(!D.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=D.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!D.isUndefined(t[e])}))).metaTokens,o=r.visitor||u,i=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&D.isSpecCompliantForm(t);if(!D.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(D.isDate(e))return e.toISOString();if(!a&&D.isBlob(e))throw new H("Blob is not supported. Use a Buffer instead.");return D.isArrayBuffer(e)||D.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(D.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(D.isArray(e)&&function(e){return D.isArray(e)&&!e.some(z)}(e)||(D.isFileList(e)||D.endsWith(r,"[]"))&&(a=D.toArray(e)))return r=J(r),a.forEach((function(e,n){!D.isUndefined(e)&&null!==e&&t.append(!0===s?W([r],n,i):null===s?r:r+"[]",c(e))})),!1;return!!z(e)||(t.append(W(o,r,i),c(e)),!1)}const l=[],f=Object.assign($,{defaultVisitor:u,convertValue:c,isVisitable:z});if(!D.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!D.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),D.forEach(r,(function(r,i){!0===(!(D.isUndefined(r)||null===r)&&o.call(t,r,D.isString(i)?i.trim():i,n,f))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t};function V(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function G(e,t){this._pairs=[],e&&K(e,this,t)}const X=G.prototype;X.append=function(e,t){this._pairs.push([e,t])},X.toString=function(e){const t=e?function(t){return e.call(this,t,V)}:V;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};const Q=G;function Z(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Y(e,t,r){if(!t)return e;const n=r&&r.encode||Z,o=r&&r.serialize;let i;if(i=o?o(t,r):D.isURLSearchParams(t)?t.toString():new Q(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}const ee=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){D.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},te={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},re={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Q,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},isStandardBrowserEnv:(()=>{let e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&"undefined"!=typeof window&&"undefined"!=typeof document})(),isStandardBrowserWebWorkerEnv:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,protocols:["http","https","file","blob","url","data"]},ne=function(e){function t(e,r,n,o){let i=e[o++];const s=Number.isFinite(+i),a=o>=e.length;return i=!i&&D.isArray(n)?n.length:i,a?(D.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!s):(n[i]&&D.isObject(n[i])||(n[i]=[]),t(e,r,n[i],o)&&D.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n<o;n++)i=r[n],t[i]=e[i];return t}(n[i])),!s)}if(D.isFormData(e)&&D.isFunction(e.entries)){const r={};return D.forEachEntry(e,((e,n)=>{t(function(e){return D.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null},oe={"Content-Type":void 0},ie={transitional:te,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=D.isObject(e);if(o&&D.isHTMLForm(e)&&(e=new FormData(e)),D.isFormData(e))return n&&n?JSON.stringify(ne(e)):e;if(D.isArrayBuffer(e)||D.isBuffer(e)||D.isStream(e)||D.isFile(e)||D.isBlob(e))return e;if(D.isArrayBufferView(e))return e.buffer;if(D.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return K(e,new re.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return re.isNode&&D.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=D.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return K(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),function(e,t,r){if(D.isString(e))try{return(0,JSON.parse)(e),D.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ie.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&D.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw H.from(e,H.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:re.classes.FormData,Blob:re.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};D.forEach(["delete","get","head"],(function(e){ie.headers[e]={}})),D.forEach(["post","put","patch"],(function(e){ie.headers[e]=D.merge(oe)}));const se=ie,ae=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ce=Symbol("internals");function ue(e){return e&&String(e).trim().toLowerCase()}function le(e){return!1===e||null==e?e:D.isArray(e)?e.map(le):String(e)}function fe(e,t,r,n,o){return D.isFunction(n)?n.call(this,t,r):(o&&(t=r),D.isString(t)?D.isString(n)?-1!==t.indexOf(n):D.isRegExp(n)?n.test(t):void 0:void 0)}class de{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=ue(t);if(!o)throw new Error("header name must be a non-empty string");const i=D.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=le(e))}const i=(e,t)=>D.forEach(e,((e,r)=>o(e,r,t)));return D.isPlainObject(e)||e instanceof this.constructor?i(e,t):D.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?i((e=>{const t={};let r,n,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&ae[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t):null!=e&&o(t,e,r),this}get(e,t){if(e=ue(e)){const r=D.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(D.isFunction(t))return t.call(this,e,r);if(D.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ue(e)){const r=D.findKey(this,e);return!(!r||void 0===this[r]||t&&!fe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=ue(e)){const o=D.findKey(r,e);!o||t&&!fe(0,r[o],o,t)||(delete r[o],n=!0)}}return D.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!fe(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return D.forEach(this,((n,o)=>{const i=D.findKey(r,o);if(i)return t[i]=le(n),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(o):String(o).trim();s!==o&&delete t[o],t[s]=le(n),r[s]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return D.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&D.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ce]=this[ce]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=ue(e);t[n]||(function(e,t){const r=D.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})}))}(r,e),t[n]=!0)}return D.isArray(e)?e.forEach(n):n(e),this}}de.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.freezeMethods(de.prototype),D.freezeMethods(de);const pe=de;function he(e,t){const r=this||se,n=t||r,o=pe.from(n.headers);let i=n.data;return D.forEach(e,(function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function me(e){return!(!e||!e.__CANCEL__)}function ge(e,t,r){H.call(this,null==e?"canceled":e,H.ERR_CANCELED,t,r),this.name="CanceledError"}D.inherits(ge,H,{__CANCEL__:!0});const ye=ge,be=re.isStandardBrowserEnv?{write:function(e,t,r,n,o,i){const s=[];s.push(e+"="+encodeURIComponent(t)),D.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),D.isString(n)&&s.push("path="+n),D.isString(o)&&s.push("domain="+o),!0===i&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function we(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ee=re.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function n(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=n(window.location.href),function(e){const t=D.isString(e)?n(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function Se(e,t){let r=0;const n=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=n[s];o||(o=c),r[i]=a,n[i]=c;let l=s,f=0;for(;l!==i;)f+=r[l++],l%=e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),c-o<t)return;const d=u&&c-u;return d?Math.round(1e3*f/d):void 0}}(50,250);return o=>{const i=o.loaded,s=o.lengthComputable?o.total:void 0,a=i-r,c=n(a);r=i;const u={loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&i<=s?(s-i)/c:void 0,event:o};u[t?"download":"upload"]=!0,e(u)}}const Oe={http:null,xhr:"undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let n=e.data;const o=pe.from(e.headers).normalize(),i=e.responseType;let s;function a(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s)}D.isFormData(n)&&(re.isStandardBrowserEnv||re.isStandardBrowserWebWorkerEnv?o.setContentType(!1):o.setContentType("multipart/form-data;",!1));let c=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.set("Authorization","Basic "+btoa(t+":"+r))}const u=we(e.baseURL,e.url);function l(){if(!c)return;const n=pe.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders());!function(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new H("Request failed with status code "+r.status,[H.ERR_BAD_REQUEST,H.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),a()}),(function(e){r(e),a()}),{data:i&&"text"!==i&&"json"!==i?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:e,request:c}),c=null}if(c.open(e.method.toUpperCase(),Y(u,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=l:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(l)},c.onabort=function(){c&&(r(new H("Request aborted",H.ECONNABORTED,e,c)),c=null)},c.onerror=function(){r(new H("Network Error",H.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||te;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new H(t,n.clarifyTimeoutError?H.ETIMEDOUT:H.ECONNABORTED,e,c)),c=null},re.isStandardBrowserEnv){const t=(e.withCredentials||Ee(u))&&e.xsrfCookieName&&be.read(e.xsrfCookieName);t&&o.set(e.xsrfHeaderName,t)}void 0===n&&o.setContentType(null),"setRequestHeader"in c&&D.forEach(o.toJSON(),(function(e,t){c.setRequestHeader(t,e)})),D.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),i&&"json"!==i&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",Se(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",Se(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{c&&(r(!t||t.type?new ye(null,e,c):t),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const f=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);f&&-1===re.protocols.indexOf(f)?r(new H("Unsupported protocol "+f+":",H.ERR_BAD_REQUEST,e)):c.send(n||null)}))}};D.forEach(Oe,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));function Re(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ye(null,e)}function xe(e){return Re(e),e.headers=pe.from(e.headers),e.data=he.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),(e=>{e=D.isArray(e)?e:[e];const{length:t}=e;let r,n;for(let o=0;o<t&&(r=e[o],!(n=D.isString(r)?Oe[r.toLowerCase()]:r));o++);if(!n){if(!1===n)throw new H(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(D.hasOwnProp(Oe,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`)}if(!D.isFunction(n))throw new TypeError("adapter is not a function");return n})(e.adapter||se.adapter)(e).then((function(t){return Re(e),t.data=he.call(e,e.transformResponse,t),t.headers=pe.from(t.headers),t}),(function(t){return me(t)||(Re(e),t&&t.response&&(t.response.data=he.call(e,e.transformResponse,t.response),t.response.headers=pe.from(t.response.headers))),Promise.reject(t)}))}const ve=e=>e instanceof pe?e.toJSON():e;function Ae(e,t){t=t||{};const r={};function n(e,t,r){return D.isPlainObject(e)&&D.isPlainObject(t)?D.merge.call({caseless:r},e,t):D.isPlainObject(t)?D.merge({},t):D.isArray(t)?t.slice():t}function o(e,t,r){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e,r):n(e,t,r)}function i(e,t){if(!D.isUndefined(t))return n(void 0,t)}function s(e,t){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t)=>o(ve(e),ve(t),!0)};return D.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||o,s=i(e[n],t[n],n);D.isUndefined(s)&&i!==a||(r[n]=s)})),r}const Te={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Te[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Be={};Te.transitional=function(e,t,r){function n(e,t){return"[Axios v1.4.0] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,i)=>{if(!1===e)throw new H(n(o," has been removed"+(t?" in "+t:"")),H.ERR_DEPRECATED);return t&&!Be[o]&&(Be[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}};const Ne={assertOptions:function(e,t,r){if("object"!=typeof e)throw new H("options must be an object",H.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],s=t[i];if(s){const t=e[i],r=void 0===t||s(t,i,e);if(!0!==r)throw new H("option "+i+" must be "+r,H.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new H("Unknown option "+i,H.ERR_BAD_OPTION)}},validators:Te},Pe=Ne.validators;class je{constructor(e){this.defaults=e,this.interceptors={request:new ee,response:new ee}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Ae(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;let i;void 0!==r&&Ne.assertOptions(r,{silentJSONParsing:Pe.transitional(Pe.boolean),forcedJSONParsing:Pe.transitional(Pe.boolean),clarifyTimeoutError:Pe.transitional(Pe.boolean)},!1),null!=n&&(D.isFunction(n)?t.paramsSerializer={serialize:n}:Ne.assertOptions(n,{encode:Pe.function,serialize:Pe.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase(),i=o&&D.merge(o.common,o[t.method]),i&&D.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=pe.concat(i,o);const s=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))}));const c=[];let u;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,f=0;if(!a){const e=[xe.bind(this),void 0];for(e.unshift.apply(e,s),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);f<l;)u=u.then(e[f++],e[f++]);return u}l=s.length;let d=t;for(f=0;f<l;){const e=s[f++],t=s[f++];try{d=e(d)}catch(e){t.call(this,e);break}}try{u=xe.call(this,d)}catch(e){return Promise.reject(e)}for(f=0,l=c.length;f<l;)u=u.then(c[f++],c[f++]);return u}getUri(e){return Y(we((e=Ae(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}D.forEach(["delete","get","head","options"],(function(e){je.prototype[e]=function(t,r){return this.request(Ae(r||{},{method:e,url:t,data:(r||{}).data}))}})),D.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,o){return this.request(Ae(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}je.prototype[e]=t(),je.prototype[e+"Form"]=t(!0)}));const Ce=je;class Ue{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,o){r.reason||(r.reason=new ye(e,n,o),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new Ue((function(t){e=t})),cancel:e}}}const Ie=Ue,_e={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(_e).forEach((([e,t])=>{_e[t]=e}));const Fe=_e,Le=function e(t){const r=new Ce(t),n=o(Ce.prototype.request,r);return D.extend(n,Ce.prototype,r,{allOwnKeys:!0}),D.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Ae(t,r))},n}(se);Le.Axios=Ce,Le.CanceledError=ye,Le.CancelToken=Ie,Le.isCancel=me,Le.VERSION="1.4.0",Le.toFormData=K,Le.AxiosError=H,Le.Cancel=Le.CanceledError,Le.all=function(e){return Promise.all(e)},Le.spread=function(e){return function(t){return e.apply(null,t)}},Le.isAxiosError=function(e){return D.isObject(e)&&!0===e.isAxiosError},Le.mergeConfig=Ae,Le.AxiosHeaders=pe,Le.formToJSON=e=>ne(D.isHTMLForm(e)?new FormData(e):e),Le.HttpStatusCode=Fe,Le.default=Le;const De=Le;class ke{buildFunctionsmodule=e=>({makeHttpRequest:this.makeHttpRequestFactory(e),encodeUint256:ke.encodeUint256,encodeInt256:ke.encodeInt256,encodeString:ke.encodeString});makeHttpRequestFactory=e=>{let t=0;return async r=>{let{url:n,method:o="get",params:i,headers:s,data:a,timeout:c=5e3,responseType:u="json"}=r;if(t<e){let e;if(t++,c>9e3)throw Error("HTTP request timeout >9000");if(n.length>2048)throw Error("HTTP request URL length >2048");try{return e=await De({method:o.toLowerCase(),url:n,params:i,headers:s,data:a,timeout:c,responseType:u,maxBodyLength:2e3,maxContentLength:2e6}),delete e.request,delete e.config,e.error=!1,e}catch(e){const t=e;return delete t.request,delete t.config,t.response&&delete t.response.request,t.error=!0,t}}throw Error("exceeded numAllowedQueries")}};static encodeUint256=e=>{if("number"==typeof e){if(!Number.isInteger(e))throw Error("encodeUint256 invalid input");if(e<0)throw Error("encodeUint256 invalid input");return ke.encodeUint256(BigInt(e))}if("bigint"==typeof e){if(e>ke.maxUint256)throw Error("encodeUint256 invalid input");if(e<BigInt(0))throw Error("encodeUint256 invalid input");if(e===BigInt(0))return Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex");const t=e.toString(16).padStart(64,"0");return Buffer.from(t,"hex")}throw Error("encodeUint256 invalid input")};static encodeInt256=e=>{if("number"==typeof e){if(!Number.isInteger(e))throw Error("encodeInt256 invalid input");return ke.encodeInt256(BigInt(e))}if("bigint"!=typeof e)throw Error("encodeInt256 invalid input");if(e<ke.maxNegInt256)throw Error("encodeInt256 invalid input");if(e>ke.maxPosInt256)throw Error("encodeInt256 invalid input");return e<BigInt(0)?ke.encodeNegSignedInt(e):ke.encodePosSignedInt(e)};static encodeString=e=>{if("string"!=typeof e)throw Error("encodeString invalid input");return Buffer.from(e)};static encodePosSignedInt=e=>{const t=e.toString(16).padStart(64,"0");return Buffer.from(t,"hex")};static encodeNegSignedInt=e=>{const t=(((e,t)=>{let r=BigInt(1),{base:n,exponent:o}=((e,t)=>{let r=BigInt(0);if("number"==typeof e){if(!Number.isInteger(e))throw Error("safePow invalid base");r=BigInt(e)}else r=e;let n=BigInt(0);if("number"==typeof t){if(!Number.isInteger(t))throw Error("safePow invalid exponent");n=BigInt(t)}else n=t;if(n<BigInt(0))throw Error("safePow invalid exponent (must be positive)");return{base:r,exponent:n}})(e,t);for(;o>BigInt(0);)o%BigInt(2)===BigInt(1)&&(r*=n),n*=n,o/=BigInt(2);return r})(BigInt(2),BigInt(256))+e).toString(16).slice(-64);return Buffer.from(t,"hex")};static maxUint256=BigInt("115792089237316195423570985008687907853269984665640564039457584007913129639935");static maxPosInt256=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819967");static maxNegInt256=BigInt("-57896044618658097711785492504343953926634992332820282019728792003956564819968")}const qe=e=>{switch(e){case"buffer":return r(300);case"crypto":return r(113);case"querystring":return r(477);case"string_decoder":return r(576);case"url":return r(310);case"util":return r(837);default:(e=>{throw Error(`Import of module ${e} not allowed`)})(e)}},Me=5,He=256,ze=1e4,Je={Buffer,URL,Date,Object,Array,Function,String,Number,Boolean,RegExp,Math,JSON,Promise,Map,Set,WeakMap,WeakSet,Proxy,Reflect,Symbol,BigInt},We=async e=>{let{source:r,secrets:n,args:o,maxHttpRequests:i=Me,maxResponseBytes:s=He,maxExecutionDurationMs:a=ze}=e;try{$e({source:r,args:o,secrets:n})}catch(e){return{error:Error(`${e}`)}}const c=(new ke).buildFunctionsmodule(i);let u="";const l={args:o,secrets:n,Functions:c,require:qe,eval:()=>{throw Error("eval not allowed")},console:{...console,log:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];const n=t.map((e=>`${e}`)).join(" ");u+=n+"\n"}},...Je};let f;try{const e=Date.now();f=Ke(await t().runInNewContext(`(async () => {\n${r}\n})()`,l),s);const n=Date.now()-e;if(n>a)throw Error(`Execution time exceeded\nScript took ${n}ms to complete but must be completed within ${a}ms`)}catch(e){return{error:Error(`${e}`),capturedStdout:u}}return{result:f,capturedStdout:u}},$e=e=>{let{secrets:t,args:r,source:n}=e;if("string"!=typeof n)throw Error("Invalid source code");if(r){if(!Array.isArray(r))throw Error("Invalid args");for(const e of r)if("string"!=typeof e)throw Error("Invalid args")}if(t&&("object"!=typeof t||!Object.values(t).every((e=>"string"==typeof e))))throw Error("secrets param not a string map")},Ke=(e,t)=>{if(Buffer.isBuffer(e)){if(e.length>t)throw Error(`returned Buffer >${t} bytes`);return 0===e.length?"0x0":`0x${e.toString("hex")}`}throw Error("returned value not a Buffer")}})(),exports.simulateScript=n.simulateScript,Object.defineProperty(exports,"__esModule",{value:!0})})();
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"buffer":65,"crypto":75,"querystring":184,"string_decoder":214,"url":215,"util":219,"vm":220}],2:[function(require,module,exports){
'use strict';
const asn1 = exports;
asn1.bignum = require('bn.js');
asn1.define = require('./asn1/api').define;
asn1.base = require('./asn1/base');
asn1.constants = require('./asn1/constants');
asn1.decoders = require('./asn1/decoders');
asn1.encoders = require('./asn1/encoders');
},{"./asn1/api":3,"./asn1/base":5,"./asn1/constants":9,"./asn1/decoders":11,"./asn1/encoders":14,"bn.js":16}],3:[function(require,module,exports){
'use strict';
const encoders = require('./encoders');
const decoders = require('./decoders');
const inherits = require('inherits');
const api = exports;
api.define = function define(name, body) {
return new Entity(name, body);
};
function Entity(name, body) {
this.name = name;
this.body = body;
this.decoders = {};
this.encoders = {};
}
Entity.prototype._createNamed = function createNamed(Base) {
const name = this.name;
function Generated(entity) {
this._initNamed(entity, name);
}
inherits(Generated, Base);
Generated.prototype._initNamed = function _initNamed(entity, name) {
Base.call(this, entity, name);
};
return new Generated(this);
};
Entity.prototype._getDecoder = function _getDecoder(enc) {
enc = enc || 'der';
// Lazily create decoder
if (!this.decoders.hasOwnProperty(enc))
this.decoders[enc] = this._createNamed(decoders[enc]);
return this.decoders[enc];
};
Entity.prototype.decode = function decode(data, enc, options) {
return this._getDecoder(enc).decode(data, options);
};
Entity.prototype._getEncoder = function _getEncoder(enc) {
enc = enc || 'der';
// Lazily create encoder
if (!this.encoders.hasOwnProperty(enc))
this.encoders[enc] = this._createNamed(encoders[enc]);
return this.encoders[enc];
};
Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
return this._getEncoder(enc).encode(data, reporter);
};
},{"./decoders":11,"./encoders":14,"inherits":146}],4:[function(require,module,exports){
'use strict';
const inherits = require('inherits');
const Reporter = require('../base/reporter').Reporter;
const Buffer = require('safer-buffer').Buffer;
function DecoderBuffer(base, options) {
Reporter.call(this, options);
if (!Buffer.isBuffer(base)) {
this.error('Input not Buffer');
return;
}
this.base = base;
this.offset = 0;
this.length = base.length;
}
inherits(DecoderBuffer, Reporter);
exports.DecoderBuffer = DecoderBuffer;
DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
if (data instanceof DecoderBuffer) {
return true;
}
// Or accept compatible API
const isCompatible = typeof data === 'object' &&
Buffer.isBuffer(data.base) &&
data.constructor.name === 'DecoderBuffer' &&
typeof data.offset === 'number' &&
typeof data.length === 'number' &&
typeof data.save === 'function' &&
typeof data.restore === 'function' &&
typeof data.isEmpty === 'function' &&
typeof data.readUInt8 === 'function' &&
typeof data.skip === 'function' &&
typeof data.raw === 'function';
return isCompatible;
};
DecoderBuffer.prototype.save = function save() {
return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
};
DecoderBuffer.prototype.restore = function restore(save) {
// Return skipped data
const res = new DecoderBuffer(this.base);
res.offset = save.offset;
res.length = this.offset;
this.offset = save.offset;
Reporter.prototype.restore.call(this, save.reporter);
return res;
};
DecoderBuffer.prototype.isEmpty = function isEmpty() {
return this.offset === this.length;
};
DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
if (this.offset + 1 <= this.length)
return this.base.readUInt8(this.offset++, true);
else
return this.error(fail || 'DecoderBuffer overrun');
};
DecoderBuffer.prototype.skip = function skip(bytes, fail) {
if (!(this.offset + bytes <= this.length))
return this.error(fail || 'DecoderBuffer overrun');
const res = new DecoderBuffer(this.base);
// Share reporter state
res._reporterState = this._reporterState;
res.offset = this.offset;
res.length = this.offset + bytes;
this.offset += bytes;
return res;
};
DecoderBuffer.prototype.raw = function raw(save) {
return this.base.slice(save ? save.offset : this.offset, this.length);
};
function EncoderBuffer(value, reporter) {
if (Array.isArray(value)) {
this.length = 0;
this.value = value.map(function(item) {
if (!EncoderBuffer.isEncoderBuffer(item))
item = new EncoderBuffer(item, reporter);
this.length += item.length;
return item;
}, this);
} else if (typeof value === 'number') {
if (!(0 <= value && value <= 0xff))
return reporter.error('non-byte EncoderBuffer value');
this.value = value;
this.length = 1;
} else if (typeof value === 'string') {
this.value = value;
this.length = Buffer.byteLength(value);
} else if (Buffer.isBuffer(value)) {
this.value = value;
this.length = value.length;
} else {
return reporter.error('Unsupported type: ' + typeof value);
}
}
exports.EncoderBuffer = EncoderBuffer;
EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
if (data instanceof EncoderBuffer) {
return true;
}
// Or accept compatible API
const isCompatible = typeof data === 'object' &&
data.constructor.name === 'EncoderBuffer' &&
typeof data.length === 'number' &&
typeof data.join === 'function';
return isCompatible;
};
EncoderBuffer.prototype.join = function join(out, offset) {
if (!out)
out = Buffer.alloc(this.length);
if (!offset)
offset = 0;
if (this.length === 0)
return out;
if (Array.isArray(this.value)) {
this.value.forEach(function(item) {
item.join(out, offset);
offset += item.length;
});
} else {
if (typeof this.value === 'number')
out[offset] = this.value;
else if (typeof this.value === 'string')
out.write(this.value, offset);
else if (Buffer.isBuffer(this.value))
this.value.copy(out, offset);
offset += this.length;
}
return out;
};
},{"../base/reporter":7,"inherits":146,"safer-buffer":189}],5:[function(require,module,exports){
'use strict';
const base = exports;
base.Reporter = require('./reporter').Reporter;
base.DecoderBuffer = require('./buffer').DecoderBuffer;
base.EncoderBuffer = require('./buffer').EncoderBuffer;
base.Node = require('./node');
},{"./buffer":4,"./node":6,"./reporter":7}],6:[function(require,module,exports){
'use strict';
const Reporter = require('../base/reporter').Reporter;
const EncoderBuffer = require('../base/buffer').EncoderBuffer;
const DecoderBuffer = require('../base/buffer').DecoderBuffer;
const assert = require('minimalistic-assert');
// Supported tags
const tags = [
'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
];
// Public methods list
const methods = [
'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
'any', 'contains'
].concat(tags);
// Overrided methods list
const overrided = [
'_peekTag', '_decodeTag', '_use',
'_decodeStr', '_decodeObjid', '_decodeTime',
'_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
'_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
'_encodeNull', '_encodeInt', '_encodeBool'
];
function Node(enc, parent, name) {
const state = {};
this._baseState = state;
state.name = name;
state.enc = enc;
state.parent = parent || null;
state.children = null;
// State
state.tag = null;
state.args = null;
state.reverseArgs = null;
state.choice = null;
state.optional = false;
state.any = false;
state.obj = false;
state.use = null;
state.useDecoder = null;
state.key = null;
state['default'] = null;
state.explicit = null;
state.implicit = null;
state.contains = null;
// Should create new instance on each method
if (!state.parent) {
state.children = [];
this._wrap();
}
}
module.exports = Node;
const stateProps = [
'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
'implicit', 'contains'
];
Node.prototype.clone = function clone() {
const state = this._baseState;
const cstate = {};
stateProps.forEach(function(prop) {
cstate[prop] = state[prop];
});
const res = new this.constructor(cstate.parent);
res._baseState = cstate;
return res;
};
Node.prototype._wrap = function wrap() {
const state = this._baseState;
methods.forEach(function(method) {
this[method] = function _wrappedMethod() {
const clone = new this.constructor(this);
state.children.push(clone);
return clone[method].apply(clone, arguments);
};
}, this);
};
Node.prototype._init = function init(body) {
const state = this._baseState;
assert(state.parent === null);
body.call(this);
// Filter children
state.children = state.children.filter(function(child) {
return child._baseState.parent === this;
}, this);
assert.equal(state.children.length, 1, 'Root node can have only one child');
};
Node.prototype._useArgs = function useArgs(args) {
const state = this._baseState;
// Filter children and args
const children = args.filter(function(arg) {
return arg instanceof this.constructor;
}, this);
args = args.filter(function(arg) {
return !(arg instanceof this.constructor);
}, this);
if (children.length !== 0) {
assert(state.children === null);
state.children = children;
// Replace parent to maintain backward link
children.forEach(function(child) {
child._baseState.parent = this;
}, this);
}
if (args.length !== 0) {
assert(state.args === null);
state.args = args;
state.reverseArgs = args.map(function(arg) {
if (typeof arg !== 'object' || arg.constructor !== Object)
return arg;
const res = {};
Object.keys(arg).forEach(function(key) {
if (key == (key | 0))
key |= 0;
const value = arg[key];
res[value] = key;
});
return res;
});
}
};
//
// Overrided methods
//
overrided.forEach(function(method) {
Node.prototype[method] = function _overrided() {
const state = this._baseState;
throw new Error(method + ' not implemented for encoding: ' + state.enc);
};
});
//
// Public methods
//
tags.forEach(function(tag) {
Node.prototype[tag] = function _tagMethod() {
const state = this._baseState;
const args = Array.prototype.slice.call(arguments);
assert(state.tag === null);
state.tag = tag;
this._useArgs(args);
return this;
};
});
Node.prototype.use = function use(item) {
assert(item);
const state = this._baseState;
assert(state.use === null);
state.use = item;
return this;
};
Node.prototype.optional = function optional() {
const state = this._baseState;
state.optional = true;
return this;
};
Node.prototype.def = function def(val) {
const state = this._baseState;
assert(state['default'] === null);
state['default'] = val;
state.optional = true;
return this;
};
Node.prototype.explicit = function explicit(num) {
const state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.explicit = num;
return this;
};
Node.prototype.implicit = function implicit(num) {
const state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.implicit = num;
return this;
};
Node.prototype.obj = function obj() {
const state = this._baseState;
const args = Array.prototype.slice.call(arguments);
state.obj = true;
if (args.length !== 0)
this._useArgs(args);
return this;
};
Node.prototype.key = function key(newKey) {
const state = this._baseState;
assert(state.key === null);
state.key = newKey;
return this;
};
Node.prototype.any = function any() {
const state = this._baseState;
state.any = true;
return this;
};
Node.prototype.choice = function choice(obj) {
const state = this._baseState;
assert(state.choice === null);
state.choice = obj;
this._useArgs(Object.keys(obj).map(function(key) {
return obj[key];
}));
return this;
};
Node.prototype.contains = function contains(item) {
const state = this._baseState;
assert(state.use === null);
state.contains = item;
return this;
};
//
// Decoding
//
Node.prototype._decode = function decode(input, options) {
const state = this._baseState;
// Decode root node
if (state.parent === null)
return input.wrapResult(state.children[0]._decode(input, options));
let result = state['default'];
let present = true;
let prevKey = null;
if (state.key !== null)
prevKey = input.enterKey(state.key);
// Check if tag is there
if (state.optional) {
let tag = null;
if (state.explicit !== null)
tag = state.explicit;
else if (state.implicit !== null)
tag = state.implicit;
else if (state.tag !== null)
tag = state.tag;
if (tag === null && !state.any) {
// Trial and Error
const save = input.save();
try {
if (state.choice === null)
this._decodeGeneric(state.tag, input, options);
else
this._decodeChoice(input, options);
present = true;
} catch (e) {
present = false;
}
input.restore(save);
} else {
present = this._peekTag(input, tag, state.any);
if (input.isError(present))
return present;
}
}
// Push object on stack
let prevObj;
if (state.obj && present)
prevObj = input.enterObject();
if (present) {
// Unwrap explicit values
if (state.explicit !== null) {
const explicit = this._decodeTag(input, state.explicit);
if (input.isError(explicit))
return explicit;
input = explicit;
}
const start = input.offset;
// Unwrap implicit and normal values
if (state.use === null && state.choice === null) {
let save;
if (state.any)
save = input.save();
const body = this._decodeTag(
input,
state.implicit !== null ? state.implicit : state.tag,
state.any
);
if (input.isError(body))
return body;
if (state.any)
result = input.raw(save);
else
input =