@bitblit/ratchet-common 4.0.366-alpha → 4.0.367-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.mjs +1 -1
- package/package.json +1 -1
package/lib/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"util";import e from"jsonwebtoken";import{DateTime as r}from"luxon";import{$enum as n}from"ts-enum-util";import s from"url";import i from"cross-fetch";const o={error:"error",warn:"warn",info:"info",verbose:"verbose",debug:"debug",silly:"silly"};class a{_lastLogMessage={messageSource:"No message yet",timestamp:(new Date).getTime(),lvl:o.info};_buffer=[];_bufferIdx=0;_lastSnapshotIdx=0;_bufferSize;constructor(t){if(!t)throw new Error("Cannot create ring buffer of size 0");this._bufferSize=t}get currentIndex(){return this._bufferIdx}get lastSnapshotIdx(){return this._lastSnapshotIdx}set bufferSize(t){if(!t)throw new Error("Cannot create ring buffer of size 0");this._bufferSize=t,this.clearRingBuffer()}getMessages(t=null,e=!1,r=!1){let n=null;if(this._bufferIdx<this._bufferSize){const e=null==t?0:t;n=this._buffer.slice(e,this._bufferIdx)}else{n=[];const e=this._bufferIdx-this._bufferSize;for(let r=t?Math.max(t,e):e;r<this._bufferIdx;r++)n.push(this._buffer[r%this._bufferSize])}return e&&this.clearRingBuffer(),r&&(n=n.reverse()),n}takeSnapshot(){const t=Math.max(0,this._bufferIdx-this._bufferSize),e={messages:this.getMessages(this._lastSnapshotIdx),logMessagesTruncated:Math.max(0,t-this._lastSnapshotIdx)};return this._lastSnapshotIdx=this._bufferIdx,e}getLastLogMessage(){return Object.assign({},this._lastLogMessage)}clearRingBuffer(){this._buffer=[],this._bufferIdx=0,this._lastSnapshotIdx=0}addToRingBuffer(t){this._lastLogMessage=t,this._buffer[this._bufferIdx%this._bufferSize]=t,this._bufferIdx++}}const l={Console:"Console",ConsoleNoDebug:"ConsoleNoDebug",StdOut:"StdOut"};class c{static LOG_LEVELS_IN_ORDER=[o.error,o.warn,o.info,o.verbose,o.debug,o.silly];static handlerFunctionMap(t=l.Console){const e=new Map;if(t===l.StdOut){if(!process?.stdout?.write)throw new Error("Cannot use standard out - process.stdout.write not found");const t=(t,e)=>process.stdout.write(t,"utf-8",e);e.set(o.error,t),e.set(o.warn,t),e.set(o.info,t),e.set(o.verbose,t),e.set(o.debug,t),e.set(o.silly,t)}else e.set(o.error,console.error),e.set(o.warn,console.warn),e.set(o.info,console.info),e.set(o.verbose,t===l.ConsoleNoDebug?console.log:console.debug),e.set(o.debug,t===l.ConsoleNoDebug?console.log:console.debug),e.set(o.silly,t===l.ConsoleNoDebug?console.log:console.debug);return e}static defaultHandlerFunction(){return console.info}static levelIsEnabled(t,e){const r=c.LOG_LEVELS_IN_ORDER.indexOf(t),n=c.LOG_LEVELS_IN_ORDER.indexOf(e);return r>-1&&n>-1&&n>=r}}const u={ClassicSingleLine:"ClassicSingleLine",StructuredJson:"StructuredJson",None:"None"};class d{formatMessage(e,r){let n=null;return e&&(n="",n+=r.options.trace?r.options.trace+" ":"",n+="["+e.lvl+"] ",n+=t.format(e.messageSource,...e.subsVars)),n}}class h{formatMessage(t,e){return null}}class g{formatMessage(e,r){let n=null;if(e){const s=Object.assign({},r.options.globalVars||{},e.params||{});s.msg=t.format(e.messageSource,...e.subsVars),s.utcDateTime=new Date(e.timestamp).toISOString(),s.logLevel=e.lvl,r.options.trace&&(s.trace=r.options.trace),s.logName=r.loggerInstanceName,s.logId=r.loggerInstanceId,n=JSON.stringify(s)+"\n"}return n}}class f{static isNullOrUndefined(t){return Object.is(t,null)||Object.is(t,void 0)}static notNullOrUndefined(t,e="object"){if(f.isNullOrUndefined(t))throw new Error(e+" may not be null or undefined")}static notNullUndefinedOrOnlyWhitespaceString(t,e="string"){if(f.isNullOrUndefined(t)||""===t.trim())throw new Error(e+" may not be null or undefined or only whitespace string")}static notNullUndefinedOrEmptyArray(t,e="string"){if(f.isNullOrUndefined(t)||0===t.length)throw new Error(e+" may not be null or undefined or an empty array")}static equal(t,e,r="Values must be equal"){if(t!==e)throw new Error(r)}static true(t,e="Value must be true"){f.equal(t,!0,e)}static noNullOrUndefinedValuesInArray(t,e=null,r=null){if(f.notNullOrUndefined(t,"Source array may not be null"),null!==e&&t.length!==e)throw new Error(`Expected array of length ${e} but was ${t.length} ${r}`);for(let e=0;e<t.length;e++)if(f.isNullOrUndefined(t[e]))throw new Error(`Array index ${e} was null or undefined ${r}`)}static noNullOrUndefinedValuesInRestArgs(t,...e){if(f.notNullOrUndefined(e,"Source array may not be null"),null!==t&&e.length!==t)throw new Error(`Expected array of length ${t} but was ${e.length}`);for(let t=0;t<e.length;t++)if(f.isNullOrUndefined(e[t]))throw new Error(`Array index ${t} was null or undefined`)}static constructorArgumentsMatchLengthAndAreNonNull(){const t=Array.from(arguments),e=this.constructor.length;return f.noNullOrUndefinedValuesInArray(t,e)}}class p{static RFC_3986_RESERVED=["!","*","'","(",")",";",":","@","&","=","+","$",",","/","?","#","[","]","%"];static DIGITS="0123456789";static HEXITS=p.DIGITS+"ABCDEF";static UPPER_CASE_LATIN="ABCDEFGHIJKLMNOPQRSTUVWXYZ";static LOWER_CASE_LATIN="abcdefghijklmnopqrstuvwxyz";static CASE_INSENSITIVE_LATIN=p.UPPER_CASE_LATIN+p.LOWER_CASE_LATIN;static stringIsInGivenAlphabet(t,e){let r=!1;if(t&&e)for(let n=0;n<t.length&&!r;n++)r=e.includes(t.charAt(n));return r}static stringToUint8Array(t){return t?(new TextEncoder).encode(t):null}static uint8ArrayToString(t){return t?(new TextDecoder).decode(t):null}static attemptJsonParse(t){let e=null;if(p.trimToNull(t))try{e=JSON.parse(t)}catch(t){e=null}return e}static canParseAsJson(t){return!!p.attemptJsonParse(t)}static allUnique(t){let e=!0;if(t){const r=new Set;for(let n=0;n<t.length&&e;n++){const s=t.charAt(n);e=!r.has(s),r.add(s)}}return e}static allPermutationsOfLength(t,e){const r=[];if(t>0&&e&&e.length>0){f.true(p.allUnique(e),"Alphabet must be unique");const n=1===t?[""]:p.allPermutationsOfLength(t-1,e);for(let t=0;t<e.length;t++)n.forEach((n=>r.push(e.charAt(t)+n)))}return r}static breakIntoBlocks(t,e,r){let n="";for(;t.length>e;)n=r+t.substring(t.length-e)+n,t=t.substring(0,t.length-e);return n=t.length>0?t+n:n.substring(1),n}static createShortUid(t=0,e=1e3,r=36){const n=Math.floor(Date.now()/1e3),s=parseInt(String(Math.floor(Math.random()*e))+String(n)).toString(r);return t>0?p.breakIntoBlocks(s,t,"-"):s}static createType4Guid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}))}static createRandomHexString(t=10){let e="";for(let r=0;r<t;r++)e+=Math.floor(16*Math.random()).toString(16);return e}static canonicalize(t){let e=t?t.toLowerCase():"";return e=e.replace(" ","-"),p.RFC_3986_RESERVED.forEach((t=>{e=e.replace(t,"")})),e}static formatBytes(t,e=2){if(0==t)return"0 Bytes";const r=e||2,n=Math.floor(Math.log(t)/Math.log(1024));return parseFloat((t/Math.pow(1024,n)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][n]}static safeString(t){let e=null;if(null!=t){e="string"==typeof t?t:String(t)}return e}static stringContainsOnlyNumbers(t){return/^[0-9]+$/.test(t)}static stringContainsOnlyAlphanumeric(t){return/^[0-9a-zA-Z]+$/.test(t)}static stringContainsOnlyHex(t){return/^[0-9a-fA-F]+$/.test(t)}static stringContainsOnly(t,e){const r=t||"",n=e||"";let s=!0;for(let t=0;t<r.length&&s;t++)s=n.indexOf(r.charAt(t))>=0;return s}static obscure(t,e=2,r=2){if(!t)return t;const n=t.length;let s=e,i=r;for(;n>0&&n<s+i+1;)s=Math.max(0,s-1),i=Math.max(0,i-1);const o=n-(s+i);let a="";a+=t.substring(0,s);for(let t=0;t<o;t++)a+="*";return a+=t.substring(n-i),a}static leadingZeros(t,e){const r="00000000000000000000000000000000000000000000000000";let n=!1,s=String(t);if(s.startsWith("-")&&(n=!0,s=s.substring(1)),e>50)throw new Error("Cannot format number that large");let i=(r+s).slice(-1*e);return n&&(i="-"+i),i}static trimToEmpty(t){return(t?p.safeString(t):"").trim()}static trimToNull(t){const e=p.trimToEmpty(t);return e.length>0?e:null}static trimAllStringPropertiesToNullInPlace(t){return p.trimAllStringPropertiesInPlace(t,!1)}static trimAllStringPropertiesToEmptyInPlace(t){return p.trimAllStringPropertiesInPlace(t,!0)}static trimAllStringPropertiesInPlace(t,e){return Object.keys(t).forEach((r=>{const n=t[r];null!=n&&"string"==typeof n&&(t[r]=e?p.trimToEmpty(t[r]):p.trimToNull(t[r]))})),t}static stripNonNumeric(t){let e=t;if(null!=t&&!p.stringContainsOnlyNumbers(t)){e="";for(let r=0;r<t.length;r++){const n=t.charAt(r);(p.stringContainsOnlyNumbers(n)||0===r&&"-"===n)&&(e+=n)}}return e}static csvSafe(t){let e=p.trimToEmpty(p.safeString(t));return e.split('"').join('\\"'),-1===e.indexOf(",")&&-1===e.indexOf('"')&&-1===e.indexOf("'")||(e='"'+e+'"'),e}static stripNonAscii(t){return[...t].reduce(((t,e)=>e.charCodeAt(0)>127?t:t+e))}static replaceAll(t,e,r){let n=t;return n?.length&&e?.length&&r?.length&&(n=n.split(e).join(r)),n}}class m{loggerInstanceName;_guid=Math.floor(1e6*Math.random());_loggerMeta;_ringBuffer;_formatter;_level;_handlerFunctionMap;_options;constructor(t="default",e){this.loggerInstanceName=t,this.options=e}addPreProcessor(t){return t&&(this._options.preProcessors=this._options.preProcessors||[],this._options.preProcessors.push(t)),Object.assign([],this._options.preProcessors)}get ringBuffer(){return this._ringBuffer}dumpConfigurationIntoLog(){this.error("ERROR enabled"),this.warn("WARN enabled"),this.info("INFO enabled"),this.verbose("VERBOSE enabled"),this.debug("DEBUG enabled"),this.silly("SILLY enabled")}dumpOptionsIntoLog(){if(this.info("Guid: %s Options: %j",this._guid,this.options),this?.options?.preProcessors?.length){const t=this.options.preProcessors.map((t=>p.trimToNull(t.label())||"Unlabelled"));this.info("Preprocessors: %j",t)}}get guid(){return this._guid}changeRingBufferSize(t){this._ringBuffer=null,t&&(this._ringBuffer=new a(t),this._options.ringBufferSize=t)}updateTracePrefix(t){this._options.trace=t}get options(){return Object.assign({},this._options)}set options(t){switch(this._options=Object.assign({},t),this._options.ringBufferSize&&(this._ringBuffer=new a(this._options.ringBufferSize)),this._options.formatType){case u.None:this._formatter=new h;break;case u.StructuredJson:this._formatter=new g;break;default:this._formatter=new d}this._level=this._options.initialLevel,this._handlerFunctionMap=c.handlerFunctionMap(this._options.outputFunction);const e=this._loggerMeta?this._loggerMeta.loggerInstanceId:null;this._loggerMeta={options:this._options,loggerInstanceName:this.loggerInstanceName,loggerInstanceId:e||p.createRandomHexString(8)}}get level(){return this._level}set level(t){if(!t)throw new Error("Cannot set level to null/undefined");this._level=t}consoleLogPassThru(t,...e){if(c.levelIsEnabled(t,this._level)){let r=this._options.trace||"";r+="["+t+"] ",e.unshift(r);(this._handlerFunctionMap.get(t)||c.defaultHandlerFunction)(...e)}}createLogMessage(t,e,r,...n){return{lvl:t,timestamp:Date.now(),messageSource:r,subsVars:n,params:e}}formatMessage(t){return t?this._formatter.formatMessage(t,this._loggerMeta):null}formatMessages(t){return(t||[]).map((t=>this.formatMessage(t))).filter((t=>!!t))}recordMessageBuilder(t){return this.recordMessage(t.toMessage())}recordMessage(t){let e=null;if(c.levelIsEnabled(t.lvl,this._level)){let r=Object.assign({},t);if(this._options.preProcessors?.length)for(let t=0;t<this._options.preProcessors.length;t++)r=this._options.preProcessors[t].process(r);if(e=this.formatMessage(r),e){(this._handlerFunctionMap.get(r.lvl)||c.defaultHandlerFunction)(e),this._ringBuffer&&this._ringBuffer.addToRingBuffer(r)}}return e}error(t,...e){const r=this.createLogMessage(o.error,{},t,...e);return this.recordMessage(r)}errorP(...t){this.consoleLogPassThru(o.error,...t)}warn(t,...e){const r=this.createLogMessage(o.warn,{},t,...e);return this.recordMessage(r)}warnP(...t){this.consoleLogPassThru(o.warn,...t)}info(t,...e){const r=this.createLogMessage(o.info,{},t,...e);return this.recordMessage(r)}infoP(...t){this.consoleLogPassThru(o.info,...t)}verbose(t,...e){const r=this.createLogMessage(o.verbose,{},t,...e);return this.recordMessage(r)}verboseP(...t){this.consoleLogPassThru(o.verbose,...t)}debug(t,...e){const r=this.createLogMessage(o.debug,{},t,...e);return this.recordMessage(r)}debugP(...t){this.consoleLogPassThru(o.debug,...t)}silly(t,...e){const r=this.createLogMessage(o.silly,{},t,...e);return this.recordMessage(r)}sillyP(...t){this.consoleLogPassThru(o.silly,...t)}logByLevel(t,e,...r){const n=this.createLogMessage(t,{},e,...r);this.recordMessage(n)}importMessages(t,e="",r=!0){const n=e||"";t&&t.length>0&&(this.silly("Received import data : %d msgs",t.length),t.forEach((t=>{if(t.messageSource){let e=n;if(r){e+=" ("+String(new Date).substring(15,24)+") : ",e+=t.messageSource}this.logByLevel(t.lvl,e)}})))}}class y{static LOGGER_INSTANCE_MAP_GLOBAL_KEY="RATCHET_GLOBAL_LOGGER_MAP_V01";static GLOBAL_PROVIDER=process||global||window;static DEFAULT_OPTIONS={initialLevel:o.info,formatType:u.ClassicSingleLine,trace:null,globalVars:{},outputFunction:l.Console,ringBufferSize:0,preProcessors:[]};static applyDefaultsToOptions(t){const e=t||{};return e.initialLevel=e.initialLevel??y.DEFAULT_OPTIONS.initialLevel,e.formatType=e.formatType??y.DEFAULT_OPTIONS.formatType,e.trace=e.trace??y.DEFAULT_OPTIONS.trace,e.globalVars=e.globalVars??y.DEFAULT_OPTIONS.globalVars,e.outputFunction=e.outputFunction??y.DEFAULT_OPTIONS.outputFunction,e.ringBufferSize=e.ringBufferSize??y.DEFAULT_OPTIONS.ringBufferSize,e}static loggerInstances(){if(!y.GLOBAL_PROVIDER)throw new Error("Cannot create logger - could not find a global provider");let t=y.GLOBAL_PROVIDER[y.LOGGER_INSTANCE_MAP_GLOBAL_KEY];return t||(t=new Map,y.GLOBAL_PROVIDER[y.LOGGER_INSTANCE_MAP_GLOBAL_KEY]=t),t}static changeDefaultOptions(t,e){if(!t||!t.initialLevel||!t.formatType)throw new Error("Default options must be non-null, and provide initial level and format type");y.DEFAULT_OPTIONS=Object.assign({},t),e&&Array.from(y.loggerInstances().values()).forEach((e=>e.options=t))}static getLogger(t="default",e){let r=y.loggerInstances().get(t);if(!r){const n=y.applyDefaultsToOptions(e);r=new m(t,n),y.loggerInstances().set(t,r)}return r}static recordMessageBuilder(t){return y.getLogger().recordMessageBuilder(t)}static recordMessage(t){return y.getLogger().recordMessage(t)}static formatMessages(t){return y.getLogger().formatMessages(t)}static updateTracePrefix(t){return y.getLogger().updateTracePrefix(t)}static changeRingBufferSize(t){return y.getLogger().changeRingBufferSize(t)}static getRingBuffer(){return y.getLogger().ringBuffer}static dumpConfigurationIntoLog(){return y.getLogger().dumpConfigurationIntoLog()}static dumpOptionsIntoLog(){return y.getLogger().dumpOptionsIntoLog()}static getLevel(){return y.getLogger().level}static setLevel(t){y.getLogger().level=t}static getOptions(){return y.getLogger().options}static getMessages(t=null,e=!1,r=!1){const n=y.getLogger().ringBuffer;return n?n.getMessages(t,e,r):null}static consoleLogPassThru(t,...e){return y.getLogger().consoleLogPassThru(t,...e)}static error(t,...e){return y.getLogger().error(t,...e)}static errorP(...t){return y.getLogger().errorP(...t)}static warn(t,...e){return y.getLogger().warn(t,...e)}static warnP(...t){return y.getLogger().warnP(...t)}static info(t,...e){return y.getLogger().info(t,...e)}static infoP(...t){return y.getLogger().infoP(...t)}static verbose(t,...e){return y.getLogger().verbose(t,...e)}static verboseP(...t){return y.getLogger().verboseP(...t)}static debug(t,...e){return y.getLogger().debug(t,...e)}static debugP(...t){return y.getLogger().debugP(...t)}static silly(t,...e){return y.getLogger().silly(t,...e)}static sillyP(...t){return y.getLogger().sillyP(...t)}static takeSnapshot(){const t=y.getLogger().ringBuffer;return t?t.takeSnapshot():null}static logByLevel(t,e,...r){return y.getLogger().logByLevel(t,e,...r)}static importMessages(t,e="",r=!0){return y.getLogger().importMessages(t,e,r)}static getLastLogMessage(){const t=y.getLogger().ringBuffer;return t?t.getLastLogMessage():null}}class b{static MAX_LEADING_ZEROS_FORMAT_LENGTH=1e3;static DEFAULT_SAFE_NUMBER_OPTIONS={ifNotNumber:null,returnValueForNull:null,returnValueForUndefined:null,preParseCharacterMapping:{",":""}};static toFixedDecimalNumber(t,e){const r=b.safeNumber(t);return null==r?r:b.safeNumber(r.toFixed(e))}static leadingZeros(t,e){const r=String(t);if(r.length<e){let t="0000";if(e>b.MAX_LEADING_ZEROS_FORMAT_LENGTH)throw"Cannot format number that large (max length is "+b.MAX_LEADING_ZEROS_FORMAT_LENGTH+")";for(;t.length<e;)t+=t;return(t+r).slice(-1*e)}return r}static between(t,e,r){const n=b.safeNumber(t),s=b.safeNumber(e),i=b.safeNumber(r);return n>=s&&n<=i||n>=i&&n<=s}static safeNumber(t,e=null,r){const n={ifNotNumber:e,returnValueForNull:r?e:null,returnValueForUndefined:r?e:void 0};return void 0===r&&(n.returnValueForUndefined=null),b.safeNumberOpt(t,n)}static safeNumberOpt(t,e){let r;const n=Object.assign({},b.DEFAULT_SAFE_NUMBER_OPTIONS,e||{});if(null===t)r=n.returnValueForNull;else if(void 0===t)r=n.returnValueForUndefined;else{const e=typeof t;if("number"==e)r=t;else if("string"==e){let e=t.trim();if(0===e.length)r=n.ifNotNumber;else{if(n.preParseCharacterMapping&&Object.keys(n.preParseCharacterMapping).length>0){let t="";for(let r=0;r<e.length;r++){const s=e.charAt(r);t+=void 0===n.preParseCharacterMapping[s]?s:n.preParseCharacterMapping[s]}e=t}r=Number.parseFloat(e)}}else y.warn("Value is of type %s, returning default",e),r=n.ifNotNumber;isNaN(r)&&(y.debug("Parsed string to NaN - using NaN value from param"),r=n.ifNotNumber)}return r}static numberCSVToList(t){let e=null;return t&&(e=t.split(",").map((t=>b.safeNumber(t.trim()))),e=e.filter((t=>"number"==typeof t&&!isNaN(t)))),e}static fitToWindow(t,e,r){let n=t;if(null===t||null===e||null===r||e<0||r<0||t<0)throw new Error("All values must be non-null and larger than 0");const s=Math.min(e,r),i=Math.max(e,r),o=i-s;if(i===s)n=i;else{for(;n<s;)n+=o;for(;n>i;)n-=o}return n}static groupNumbersIntoContiguousRanges(t,e=3){f.notNullOrUndefined(t);const r=Object.assign([],t);r.sort(((t,e)=>t-e));const n=[],s=[];let i=0;for(let t=1;t<r.length;t++)if(r[t]===r[t-1]+1);else{if(i===t-1)n.push(r[t-1]);else{if(t-i<e)for(let e=i;e<t;e++)n.push(r[e]);else s.push({min:r[i],max:r[t-1]})}i=t}return{singles:n,ranges:s}}static distributeItemsEvenly(t,e){f.notNullOrUndefined(t,"items"),f.notNullOrUndefined(e,"buckets"),f.true(t>0&&t===Math.floor(t),"Items integer larger than 0"),f.true(e>0&&e===Math.floor(e),"Buckets integer larger than 0");const r=e/t,n=[];for(let t=0;t<e;t++)n.push(0);let s=0,i=t;for(;i>0;)n[Math.floor(s)%e]++,i--,s+=r;return n}static createRange(t,e,r=1){const n=[];let s=t;for(;s<e;)n.push(s),s+=r;return n}}class E{static allTrue(t,e=!1){let r=null;return r=!!t&&(t.length>0?t.reduce(((t,e)=>t&&e),!0):e),r}static anyTrue(t,e=!1){let r=null;return r=!!t&&(t.length>0?t.reduce(((t,e)=>t||e),!1):e),r}static parseBool(t){return!0===t||null!=t&&"string"==typeof t&&"true"===t.toLowerCase()}static intToBool(t){return null!=t&&0!==b.safeNumber(t)}static boolToInt(t){return E.parseBool(t)?1:0}}class S{constructor(){}static translateToOriginVector(t){let e=null;return S.validPoints(t)&&(e={x:null,y:null},t.forEach((t=>{e.x=null===e.x||t.x<e.x?t.x:e.x,e.y=null===e.y||t.y<e.y?t.y:e.y})),e.x*=-1,e.y*=-1),e}static minimalContainingPlane(t){let e=null;return S.validPoints(t)&&(e={width:0,height:0},t.forEach((t=>{e.width=Math.max(e.width,t.x+1),e.height=Math.max(e.height,t.y+1)}))),e}static scaleVector(t,e){let r=null;return S.validPlane(t)&&S.validPlane(e)&&(r={x:e.width/t.width,y:e.height/t.height}),r}static samePoint(t,e){return!!t&&!!e&&t.x===e.x&&t.y===e.y}static atLeastOneDimensionShared(t,e){return!(!t||!e||t.x!==e.x&&t.y!==e.y)}static validPlane(t){return!!t&&!!t.height&&!!t.width}static validLine(t){return!!t&&S.validPoint(t.p1)&&S.validPoint(t.p2)&&!S.samePoint(t.p1,t.p2)}static validLines(t){return!!t&&E.allTrue(t.map((t=>S.validLine(t))))}static validPolyLine(t){return!!t&&t.pts?.length>1&&E.allTrue(t.pts.map((t=>S.validPoint(t))))}static polyLineToLines(t){let e=null;if(S.validPolyLine(t)){e=[];for(let r=1;r<t.pts.length;r++)e.push({p1:t.pts[r-1],p2:t.pts[r]})}return e}static lastPointOnPolyLine(t){return S.validPolyLine(t)?t.pts[t.pts.length-1]:null}static lineToPolyLine(t){return S.validLine(t)?{pts:[t.p1,t.p2]}:null}static linesToPolyLines(t){let e=null;if(S.validLines(t)){e=[];let r=S.lineToPolyLine(t[0]);for(let n=1;n<t.length;n++)S.samePoint(S.lastPointOnPolyLine(r),t[n].p1)?r.pts.push(t[n].p2):(e.push(r),r=S.lineToPolyLine(t[n]));e.push(r)}return e}static validPoint(t){return!!t&&null!=t.x&&null!=t.x&&null!==t.y&&void 0!==t.y}static validPoints(t){return!!t&&E.allTrue(t.map((t=>S.validPoint(t))),!1)}static planeContainsPoint(t,e){return S.validPlane(e)&&S.validPoint(t)&&t.x>=0&&t.x<e.width&&t.y>=0&&t.y<e.height}static planeContainsPoints(t,e){return t&&t.map((t=>S.planeContainsPoint(t,e))).reduce(((t,e)=>t&&e),!0)}static linesToPoints(t){let e=null;return S.validLines(t)&&(e=t.map((t=>[t.p1,t.p2])).flat()),e}static pointsToLines(t){let e=null;if(S.validPoints(t)){if(t.length%2!=0)throw new Error("Cannot convert non-even array of points into lines");e=[];for(let r=0;r<t.length;r+=2)e.push({p1:t[r],p2:t[r+1]})}return e}static rotateRightAboutOrigin90Degrees(t,e=1){let r=null,n={x:0,y:0};if(S.validPoints(t)){r=Object.assign([],t),n=S.translateToOriginVector(r),r=S.translate(r,n);let e=S.minimalContainingPlane(r);r=S.xToY(r),e={width:e.height,height:e.width},n={x:-1*n.y,y:-1*n.x},r=S.mirrorPointsOnPlane(r,e,!0,!1),r=S.translate(r,n)}const s=e>4?e%4:e;return s>1&&(r=S.rotateRightAboutOrigin90Degrees(r,s-1)),r}static planeContainsLines(t,e){return t&&S.planeContainsPoints(t.map((t=>[t.p1,t.p2])).flat(),e)}static planeContainsPolyLine(t,e){return S.planeContainsLines(S.polyLineToLines(t),e)}static planeContainsLine(t,e){return S.validPlane(e)&&S.validLine(t)&&S.planeContainsPoint(t.p1,e)&&S.planeContainsPoint(t.p2,e)}static xToY(t){let e=null;return S.validPoints(t)&&(e=t.map((t=>({x:t.y,y:t.x})))),e}static translate(t,e){let r=null;return S.validPoints(t)&&S.validPoint(e)&&(r=t.map((t=>({x:t.x+e.x,y:t.y+e.y})))),r}static mirrorPointsOnPlane(t,e,r,n){let s=null;return S.validPoints(t)&&S.validPlane(e)&&(s=r||n?t.map((t=>({x:r?e.width-1-t.x:t.x,y:n?e.height-1-t.y:t.y}))):Object.assign([],t)),s}static transformPointsToNewPlane(t,e,r){let n=null;if(S.validPoints(t)&&S.validPlane(e)&&S.validPlane(r)){const s=S.scaleVector(e,r);n=t.map((t=>({x:t.x*s.x,y:t.y*s.y}))),n=S.mirrorPointsOnPlane(n,r,r.rightToLeft!==e.rightToLeft,r.topToBottom!==e.topToBottom)}return n}static transformPointToNewPlane(t,e,r){const n=S.transformPointsToNewPlane([t],e,r);return 1===n.length?n[0]:null}static transformLines(t,e,r){return null}static fitCurve(t,e){if(t.sort(((t,e)=>t.x-e.x)),e<=t[0].x)return t[0].y;if(e>=t[t.length-1].x)return t[t.length-1].y;{let r=0;for(;t[r+1].x<e;)r++;const n=t[r+1].x-t[r].x,s=t[r+1].y-t[r].y,i=(e-t[r].x)/n*s;return t[r].y+i}}}class w{constructor(){}static buildInformation(){return{version:"366",hash:"6a2e3ab20a9aa553758702097b3be8d8174a2a2a",branch:"alpha-2024-06-19-1",tag:"alpha-2024-06-19-1",timeBuiltISO:"2024-06-19T12:19:55-0700",notes:"No notes"}}}class T{entries=[];update(t,e=1){if(t){const r=this.entries.find((e=>e.item===t));r?r.count+=e:this.entries.push({item:t,count:e})}}sort(){this.entries.sort(((t,e)=>{let r=e.count-t.count;return 0===r&&(r=String(e.item).localeCompare(String(t.item))),r}))}sortKeys(){this.entries.sort(((t,e)=>String(e.item).localeCompare(String(t.item))))}reverse(){this.entries.reverse()}getEntries(){return this.entries}getTotalCount(){let t=0;return this.entries.forEach((e=>t+=e.count)),t}countForValue(t){const e=this.entries.find((e=>e.item===t));return e?e.count:0}percentForValue(t){const e=this.getTotalCount();return 0===e?0:this.countForValue(t)/e}}var O;!function(t){t[t.RETURN_NULL=0]="RETURN_NULL",t[t.THROW_EXCEPTION=1]="THROW_EXCEPTION",t[t.ADD_FLAG=2]="ADD_FLAG"}(O||(O={}));class _{static formatMsDuration(t,e=!1){const r=Math.floor(t%1e3),n=Math.floor(t/1e3)%60,s=Math.floor(t/6e4)%60,i=Math.floor(t/36e5)%24,o=Math.floor(t/864e5),a=b.leadingZeros;let l=a(i,2)+"h"+a(s,2)+"m";return l+=e?a(n,2)+"."+a(r,3)+"s":a(n,2)+"s",o>0&&(l=o+"d"+l),l}static colonFormatMsDuration(t,e=!1){const r=t%1e3,n=Math.floor(t/1e3)%60,s=Math.floor(t/6e4)%60,i=Math.floor(t/36e5),o=b.leadingZeros;let a=o(i,2)+":"+o(s,2)+":";return a+=e?o(n,2)+"."+o(r,3):o(n,2),a}static daysBetween(t,e){return r.fromJSDate(t).diff(r.fromJSDate(e)).days}static createSteps(t,e,n,s,i){let o=r.fromMillis(t).setZone(n);const a=r.fromMillis(e),l=[];for(;o<a;)l.push(o.toFormat(s)),o=o.plus(i);return l}}class L{_encryptionKeyPromise;_decryptKeysPromise;_jtiGenerator;_decryptOnlyKeyUseLogLevel;_parseFailureLogLevel;static EXPIRED_FLAG_NAME="__jwtServiceExpiredFlag";constructor(t,e,r=p.createType4Guid,n=o.info,s=o.debug){this._encryptionKeyPromise=t,this._decryptKeysPromise=e,this._jtiGenerator=r,this._decryptOnlyKeyUseLogLevel=n,this._parseFailureLogLevel=s,f.notNullOrUndefined(t,"encryptionKeyPromise")}get encryptionKeyPromise(){return this._encryptionKeyPromise}get decryptKeysPromise(){return this._decryptKeysPromise}get jtiGenerator(){return this._jtiGenerator}get decryptOnlyKeyUseLogLevel(){return this._decryptOnlyKeyUseLogLevel}get parseFailureLogLevel(){return this._parseFailureLogLevel}static hasExpiredFlag(t){return t&&!0===t[L.EXPIRED_FLAG_NAME]}static async invalidSafeDecode(t,r,n=o.silly){let s=null;try{s=e.verify(t,r,{ignoreExpiration:!0})}catch(t){y.logByLevel(n,"Caught %s - ignoring",t)}return s}static async secondsRemainingUntilExpiration(t){let e=null;if(p.trimToNull(t)){const r=await L.decodeTokenNoVerify(t),n=Math.floor(Date.now()/1e3);if(r.exp){const t=r.exp>100*n?Math.floor(r.exp/1e3):r.exp;e=Math.max(0,t-n)}}return e}static async msRemainingUntilExpiration(t){const e=await L.secondsRemainingUntilExpiration(t);let r=null;return null!=e&&(r=1e3*e),r}async decodeToken(t,e=0){const r=await this.encryptionKeyArray();let n=Object.assign([],r);this.decryptKeysPromise&&(n=n.concat(await this.decryptKeysPromise));const s=[];let i=null;for(let e=0;e<n.length&&!i;e++){s.push(p.obscure(n[e],1,1));const a=e===n.length-1&&this.parseFailureLogLevel?this.parseFailureLogLevel:o.silly;i=await L.invalidSafeDecode(t,n[e],a),i&&e>=r.length&&y.logByLevel(this.decryptOnlyKeyUseLogLevel,"Used old key to decode token : %s",p.obscure(n[e],2))}if(i){const t=Math.floor(Date.now()/1e3),r=i?.exp&&i.exp>100*t?Math.floor(i.exp/1e3):i?.exp,n=i?.nbf&&i.nbf>100*t?Math.floor(i.nbf/1e3):i?.nbf;if(r&&t>=r||n&&t<=n){const n=t-r;switch(y.debug("JWT token expired or before NBF : on %d, %s ago",i.exp,_.formatMsDuration(1e3*n)),e){case 1:throw new Error("JWT Token was expired");case 2:i[L.EXPIRED_FLAG_NAME]=!0;break;default:i=null}}}else y.warn("Unable to parse a payload (Tried %j) from : %s",s,t);return i}async encryptionKeyArray(){const t=await this.encryptionKeyPromise,e=Array.isArray(t)?t:[t];if(e.length<1)throw new Error("Cannot create JwtRatchet with empty encryption key set");return e}async selectRandomEncryptionKey(){const t=await this.encryptionKeyArray();return t[Math.floor(Math.random()*t.length)]}async createTokenString(t,r,n){const s=p.trimToNull(n)?p.trimToNull(n):await this.selectRandomEncryptionKey();if(f.notNullOrUndefined(t,"payload"),t.jti=this.jtiGenerator?this.jtiGenerator():null,r){const e=Math.floor(Date.now()/1e3)+r;y.debug("Forcing expiration to %d",e),t.exp=e}return e.sign(t,s)}async refreshJWTString(t,e,r){const n=e?2:1,s=await this.decodeToken(t,n),i=s.exp&&s.iat?s.exp-s.iat:null,o=r||i;L.removeJwtFields(s),L.removeExpiredFlag(s);return await this.createTokenString(s,o)}static decodeTokenNoVerify(t){return e.decode(t)}static removeJwtFields(t){t&&["iss","sub","aud","exp","nbf","iat","jti"].forEach((e=>{delete t[e]}))}static removeExpiredFlag(t){t&&delete t[L.EXPIRED_FLAG_NAME]}}class M{static safeStringifyErr(t,e=!0){let r="ERR WAS NULL";if(t)if(t.message)r=t.message;else try{r=JSON.stringify(t)}catch(e){y.error("Failed to json stringify"),r=String(t)}return e&&y.error("%s",r,t),r}static asErr(t){let e=null;return t&&(e=t instanceof Error?t:new Error("Force-Cast to error : "+String(t))),e}static fErr(e,...r){const n=t.format(e,...r);return new Error(n)}static throwFormattedErr(t,...e){throw M.fErr(t,...e)}}class A{static expandNestedKeysToObjects(t,e="."){if(!e||1!==e.length)throw new Error("Invalid separator (must be single character)");const r={};return Object.keys(t).forEach((n=>{const s=n.split(e);let i=r;for(;s.length>1;)i[s[0]]=i[s[0]]||{},i=i[s[0]],s.splice(0,1);i[s[0]]=t[n]})),r}static mapByUniqueProperty(t,e){if(!t||!e)throw new Error("Neither input nor propName can be null");const r=new Map;return t.forEach((t=>{const n=t?t[e]:null;if(null==n)throw new Error("No value for "+e+" found in "+JSON.stringify(t));if(r.has(n))throw new Error("Multiple values found for "+n);r.set(n,t)})),r}static groupByProperty(t,e){if(!t||!e)throw new Error("Neither input nor propName can be null");const r=new Map;return t.forEach((t=>{const n=t?t[e]:null;if(null==n)throw M.fErr("No value for %s found in %j",e,t);r.has(n)||r.set(n,[]),r.get(n).push(t)})),r}static findValue(t,e){return e&&0!=e.length?t?A.findValue(t[e[0]],e.slice(1)):null:t}static findValueDotPath(t,e){return e&&0!=e.length?t?A.findValue(t,e.split(".")):null:t}static simpleDeepCompare(t,e){return null==t&&null==e||null!=t&&null!=e&&JSON.stringify(t)==JSON.stringify(e)}static toKeyValueList(t){const e=[];for(const r of Object.keys(t))e.push({key:r,value:t[r]});return e}static fromKeyValueList(t){const e={};return t.forEach((t=>e[t.key]=t.value)),e}static cleanup(t,e=!1,r=!0,n=!0,s=!0){if(null==t||"object"!=typeof t)return t;const i=JSON.parse(JSON.stringify(t));return Object.keys(i).forEach((t=>{if(i[t]&&"object"==typeof i[t])if(Array.isArray(i[t]))for(let e=0;e<i[t].length;e++)i[t][e]=A.cleanup(i[t][e]);else i[t]=A.cleanup(i[t]);else void 0===i[t]&&n||null===i[t]&&r||""===i[t]&&s||0===i[t]&&e?delete i[t]:i[t]=i[t]})),i}static extractValueFromMapIgnoreCase(t,e){let r=null;if(t&&e){const n=e.toLowerCase();Object.keys(t).forEach((s=>{if(s.toLowerCase()===n){const n=t[s];r&&y.warn("Multiple entries found for %s (replacing %s with %s",e,r,n),r=n}}))}return r}static safeCallFunction(t,e){let r=!1;if(t&&t[e]&&"function"==typeof t[e])try{t[e](),r=!0}catch(r){y.warn("Error calling %s on %s : %s",e,t,r,r)}return r}static caseInsensitiveAccess(t,e){let r=null;if(t&&e&&(r=t[e],!r)){const n=Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()));n&&(r=t[n])}return r}}class N{static wrapElementsInArray(t){return t.map((t=>[t]))}static compareTwoArrays(t,e,r){t.sort(r),e.sort(r);let n=0,s=0;const i={matching:[],setOneOnly:[],setTwoOnly:[]};for(;n<t.length&&s<e.length;){const o=t[n],a=e[s],l=r(o,a);0===l?(i.matching.push(o),n++,s++):l<0?(i.setOneOnly.push(o),n++):(i.setTwoOnly.push(a),s++)}return n<t.length-1&&(i.setOneOnly=i.setOneOnly.concat(t.slice(n))),s<e.length-1&&(i.setTwoOnly=i.setTwoOnly.concat(e.slice(s))),i}static extractSubarrayFromSortedByNumberField(t,e,r,n){if(!t||0===t.length)return t;let s=null===r?0:N.findSplit(t,e,r)||0;const i=null===n?t.length:N.findSplit(t,e,n),o=A.findValueDotPath(t[s],e);return s===t.length-1&&o<r?[]:(s<t.length&&s<i&&o<r&&s++,t.slice(s,i+1))}static findSplit(t,e,r){if(f.notNullOrUndefined(t),f.notNullOrUndefined(e),f.notNullOrUndefined(r),0===t.length||A.findValueDotPath(t[0],e)>r)return null;let n=0,s=t.length,i=null;for(;null===i;){const o=Math.floor((n+s)/2),a=A.findValueDotPath(t[o],e);n===s||n===s-1?i=n:a<=r?n=o:s=o}return i}}class x{static safeObjectToBase64JSON(t){return t?x.generateBase64VersionOfString(JSON.stringify(t)):null}static safeBase64JSONParse(t){let e={};try{t&&(e=JSON.parse(x.base64StringToString(t,"utf-8")))}catch(r){y.warn("Error parsing b64/json : %s as json, got %s",t,r,r),e={}}return e}static generateBase64VersionOfBlob(t){return new Promise((function(e,r){if(t&&0!=t.size){const r=new FileReader;r.onloadend=function(){e(r.result.toString())},r.readAsDataURL(t)}else r("Wont convert null or non-blob or empty blob")}))}static generateBase64VersionOfString(t){return x.generateBase64VersionOfUint8Array(p.stringToUint8Array(t))}static generateBase64VersionOfUint8Array(t){return x.uint8ArrayToBase64String(t)}static base64StringToUint8Array(t){try{return x.base64StringToBytes(t)}catch(e){throw y.error("Failed to decode base64: %s",t),e}}static base64StringToString(t,e="utf8"){return new TextDecoder(e).decode(x.base64StringToUint8Array(t))}static BASE64_ABC=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"];static BASE64_CODES=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];static getBase64Code(t){if(t>=x.BASE64_CODES.length)throw new Error("Unable to parse base64 string.");const e=x.BASE64_CODES[t];if(255===e)throw new Error("Unable to parse base64 string.");return e}static uint8ArrayToBase64UrlString(t){let e=x.uint8ArrayToBase64String(t);return e=e.split("+").join("-").split("/").join("_").split("=").join(""),e}static uint8ArrayToBase64String(t){let e,r="";const n=t.length;for(e=2;e<n;e+=3)r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4|t[e-1]>>4],r+=x.BASE64_ABC[(15&t[e-1])<<2|t[e]>>6],r+=x.BASE64_ABC[63&t[e]];return e===n+1&&(r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4],r+="=="),e===n&&(r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4|t[e-1]>>4],r+=x.BASE64_ABC[(15&t[e-1])<<2],r+="="),r}static base64StringToBytes(t){if(t.length%4!=0)throw M.fErr("Unable to parse base64 string, length: %s",t.length);const e=t.indexOf("=");if(-1!==e&&e<t.length-2)throw M.fErr("Unable to parse base64 string, index %s",e);const r=t.endsWith("==")?2:t.endsWith("=")?1:0,n=t.length,s=new Uint8Array(n/4*3);let i;for(let e=0,r=0;e<n;e+=4,r+=3)i=x.getBase64Code(t.charCodeAt(e))<<18|x.getBase64Code(t.charCodeAt(e+1))<<12|x.getBase64Code(t.charCodeAt(e+2))<<6|x.getBase64Code(t.charCodeAt(e+3)),s[r]=i>>16,s[r+1]=i>>8&255,s[r+2]=255&i;return s.subarray(0,s.length-r)}static base64UrlStringToBytes(t){let e=t.split("-").join("+").split("_").join("/");for(;e.length%4!=0;)e+="=";return y.info("pre: %s post %s",t,e),x.base64StringToBytes(e)}static encodeStringToBase64String(t,e=new TextEncoder){return x.uint8ArrayToBase64String(e.encode(t))}static encodeStringToBase64UrlString(t,e=new TextEncoder){return x.uint8ArrayToBase64UrlString(e.encode(t))}static decodeBase64StringToString(t,e=new TextDecoder){return e.decode(x.base64StringToBytes(t))}static decodeBase64UrlStringToString(t,e=new TextDecoder){return e.decode(x.base64UrlStringToBytes(t))}}class I{sources;mostRecent;constructor(t,e=!0){if(!t||0==t.length)throw Error("Cannot create composite provider with null/empty sources");this.sources=t,this.mostRecent=e}lastSuccess(){let t=null;return this.sources.forEach((e=>{const r=e.lastSuccess();null!=r&&(t=null==t||r>t&&this.mostRecent||r<t&&!this.mostRecent?r:t)})),t}}class v{static COMMON_US_DATE_FORMAT="MM/dd/yyyy";static DEFAULT_DATE_FORMAT="yyyy-MM-dd";static FULL_DATE_FORMAT="yyyy-MM-dd_HH_mm_ss";static PACIFIC_TIME_ZONE="America/Los_Angeles";static UTC_TIME_ZONE="etc/UTC";static formatFullDate(t){return r.fromJSDate(t).toFormat(v.FULL_DATE_FORMAT)}static formatDefaultDateOnly(t){return r.fromJSDate(t).toFormat(v.DEFAULT_DATE_FORMAT)}static parseDefaultDate(t){return r.fromFormat(t,v.DEFAULT_DATE_FORMAT).toJSDate()}static parseCommonUsDate(t){let e=null;if(t){let n=v.COMMON_US_DATE_FORMAT;2===t.indexOf("-")&&(n=n.split("/").join("-")),e=r.fromFormat(t,n).toJSDate()}return e}}class P{static listEnumKeys(t){return n(t).getValues()}static keyToEnum(t,e,r=!1){const s=n(t);let i=null;if(e&&(i=s.asValueOrDefault(e,null),!i&&!r)){const r=P.listEnumKeys(t).find((t=>t.toUpperCase()===e.toUpperCase()));r&&(i=s.asValueOrDefault(r,null))}return i}static parseCsvToEnumArray(t,e){return p.trimToEmpty(e).split(",").map((t=>t.trim())).map((e=>P.keyToEnum(t,e))).filter((t=>!!t))}}class R{static fetchDirName(t){if(!t)throw new Error("Need to provide root (should be import.meta.url)");return s.fileURLToPath(new URL(".",t))}static fetchFileName(t){if(!t)throw new Error("Need to provide root (should be import.meta.url)");return s.fileURLToPath(t)}}class C{_config;_cacheObject;_lastUpdatedEpochMS;_timeRemainingMS;constructor(t){this._config=Object.assign({},this.defaultConfig(),t||{}),this._config.overrideTimeRemainingMS&&this._config.timeToLiveMS&&M.throwFormattedErr("Cannot define both time to live and overrideTimeRemainingMS"),this._config.overrideTimeRemainingMS||this._config.timeToLiveMS||M.throwFormattedErr("Must define exactly one of timeToLiveMS or overrideTimeRemainingMS"),this._config.initialValue&&this.update(this._config.initialValue),this._timeRemainingMS=this._config.overrideTimeRemainingMS||this.defaultTimeRemainingMS}defaultConfig(){return{generator:null,initialValue:null,logLevel:o.debug,overrideTimeRemainingMS:null,timeToLiveMS:6e4}}async defaultTimeRemainingMS(t){let e=0;if(t){const r=(new Date).getTime()-t;e=Math.max(0,this._config.timeToLiveMS-r)}return e}update(t,e=!1){this._cacheObject=t,e||(this._lastUpdatedEpochMS=(new Date).getTime()),y.logByLevel(this._config.logLevel,"Updated cache value to %j",t)}async fetchCacheObjectTimeRemainingMS(){return this._timeRemainingMS(this._lastUpdatedEpochMS)}async fetch(){if(await this._timeRemainingMS(this._lastUpdatedEpochMS)||(this._cacheObject=null,this._lastUpdatedEpochMS=null),!this._cacheObject&&this._config.generator){const t=await this._config.generator();y.logByLevel(this._config.logLevel,"Auto call to generator returned %j",t),this.update(t)}return this._cacheObject}}class B{timeToLiveMS;generator;initialValue;logLevel;overrideTimeRemainingMS}class U{constructor(){}static distanceBetweenLocations(t,e,r,n,s="M"){const i=s?s.toUpperCase():"";if(-1===["M","K","N","F","E"].indexOf(i))throw new Error("Invalid unit");if(t==r&&e==n)return 0;{const s=Math.PI*t/180,o=Math.PI*r/180,a=e-n,l=Math.PI*a/180;let c=Math.sin(s)*Math.sin(o)+Math.cos(s)*Math.cos(o)*Math.cos(l);return c>1&&(c=1),c=Math.acos(c),c=180*c/Math.PI,c=60*c*1.1515,"F"===i&&(c*=5280),"K"===i&&(c*=1.609344),"E"===i&&(c*=1609.344),"N"===i&&(c*=.8684),c}}static distanceBetweenRatchetGeoLocations(t,e,r="M"){return U.distanceBetweenLocations(t.lat,t.lng,e.lat,e.lng,r)}static degreeOfLatLngInMiles(t=0){const e=t*Math.PI/180,r=Math.cos(e);return b.safeNumber((69.172*r).toFixed(4))}static milesInDegLatLng(t,e=0){f.notNullOrUndefined(t),f.true(t>=0);return t/U.degreeOfLatLngInMiles(e)}static centerOfBounds(t){return f.notNullOrUndefined(t),{lat:(t.extent.lat+t.origin.lat)/2,lng:(t.extent.lng+t.origin.lng)/2}}static calculateSplits(t,e,r){f.notNullOrUndefined(t),f.notNullOrUndefined(e),f.notNullOrUndefined(r),t.sort(((t,e)=>t.origin[r]-e.origin[r]));const n=t.map((t=>U.centerOfBounds(t))).map((t=>t[r])),s=[];for(let t=1;t<n.length;t++){const r=n[t]-n[t-1];s.length<e?(s.push({idx:t,size:r}),s.sort(((t,e)=>t.size-e.size))):r>s[0].size?(s[0]={idx:t,size:r},s.sort(((t,e)=>t.size-e.size))):y.silly("Skipping, size : %d, %j",r,s)}return y.info("Splits at : %j",s),s.sort(((t,e)=>t.idx-e.idx)),s}static clusterGeoBounds(t,e=2,r=5){let n=null;if(e*r<2&&M.throwFormattedErr("Cannot set slices to less than 2 : %d x %d",e,r),t){n=[];const s=Object.assign([],t);s.sort(((t,e)=>t.origin.lng-e.origin.lng));const i=U.calculateSplits(t,r-1,"lng");i.sort(((t,e)=>t.idx-e.idx));for(let t=0;t<=i.length;t++){const r=0===t?0:i[t-1].idx,o=t===i.length?s.length:i[t].idx,a=s.slice(r,o);a.sort(((t,e)=>t.origin.lat-e.origin.lat));const l=U.calculateSplits(a,e-1,"lat");for(let t=0;t<=l.length;t++){const e=0==t?0:l[t-1].idx,r=t===l.length?a.length:l[t].idx,s=a.slice(e,r);n.push(U.combineBounds(s))}}y.info("New bounds : %j",n)}return n}static canonicalizeBounds(t,e=!1){f.notNullOrUndefined(t,"RatchetLocationBounds");const r=Math.min(t.extent.lat,t.origin.lat),n=Math.max(t.extent.lat,t.origin.lat),s=Math.min(t.extent.lng,t.origin.lng),i=Math.max(t.extent.lng,t.origin.lng);if(r<0&&n>0||r>0&&n<0||(r<0&&n>0||r>0&&n<0)){if(e)return t;throw new Error("Cannot canonicalize, bounds crosses over boundary")}return{origin:{lat:r,lng:s},extent:{lat:n,lng:i}}}static combineBounds(t){let e=null;return t&&t.length>0&&(e={origin:{lat:t.map((t=>t.origin.lat)).reduce(((t,e)=>Math.min(t,e))),lng:t.map((t=>t.origin.lng)).reduce(((t,e)=>Math.min(t,e)))},extent:{lat:t.map((t=>t.extent.lat)).reduce(((t,e)=>Math.max(t,e))),lng:t.map((t=>t.extent.lng)).reduce(((t,e)=>Math.max(t,e)))}}),e}static roundLocation(t,e){return{lat:b.safeNumber(t.lat.toFixed(e)),lng:b.safeNumber(t.lng.toFixed(e))}}static locationToBounds(t,e){const r=U.milesInDegLatLng(e,t.lat);return{origin:{lat:t.lat-r,lng:t.lng-r},extent:{lat:t.lat+r,lng:t.lng+r}}}static sameLocation(t,e){return!!t&&!!e&&t.lat===e.lat&&t.lng===e.lng}static pointInBounds(t,e){return!!t&&!!e&&b.between(t.lat,e.origin.lat,e.extent.lat)&&b.between(t.lng,e.origin.lng,e.extent.lng)}static pointInAnyBound(t,e,r=10){let n=!1;if(e.length>r){const r=U.buildRatchetLocationBoundsMap(e);n=U.pointInRatchetLocationBoundsMap(t,r)}else for(let r=0;r<e.length&&!n;r++)n=U.pointInBounds(t,e[r]);return n}static pointInRatchetLocationBoundsMap(t,e){let r=!1;const n=U.findRatchetLocationBoundsMapEntry(t,e);if(n){const e=n.bounds;for(let n=0;n<e.length&&!r;n++)r=U.pointInBounds(t,e[n])}return r}static findRatchetLocationBoundsMapEntry(t,e){let r=null;if(t.lat>=e.latOffset&&t.lat<=e.maxLat&&t.lng>=e.lngOffset&&t.lng<=e.maxLng){const n=Math.trunc(t.lat)-e.latOffset,s=Math.trunc(t.lng)-e.lngOffset;r=e.mapping[n][s]}return r}static buildRatchetLocationBoundsMap(t){const e=t.map((t=>t.origin.lat)).reduce(((t,e)=>Math.min(t,e))),r=t.map((t=>t.origin.lng)).reduce(((t,e)=>Math.min(t,e))),n=t.map((t=>t.extent.lat)).reduce(((t,e)=>Math.max(t,e))),s=t.map((t=>t.extent.lng)).reduce(((t,e)=>Math.max(t,e))),i=Math.trunc(e)-1,o=Math.trunc(r)-1,a=Math.trunc(n)-i+1,l=Math.trunc(s)-o+1,c=[];for(let t=0;t<a;t++){const e=[];for(let r=0;r<l;r++)e.push({lat:i+t,lng:o+r,bounds:[]});c.push(e)}return t.forEach((t=>{for(let e=Math.trunc(t.origin.lat);e<=Math.trunc(t.extent.lat);e++){const r=c[e-i];for(let e=Math.trunc(t.origin.lng);e<=Math.trunc(t.extent.lng);e++){r[e-o].bounds.push(t)}}})),{latOffset:i,lngOffset:o,maxLat:i+a,maxLng:o+l,mapping:c}}}class D{constructor(){}static fetchGlobalRecord(t){let e=null;if(process?.env?(y.silly("Using process.env as global"),e=process.env):global?.process?.env?(y.silly("Using global.process.env as global"),e=global.process.env):global&&(y.silly("Using process.env as global"),e=global),!e){if(!t)throw M.fErr("Could not find process.env OR global in scope");y.silly("Returning null as global"),e=null}return e}static fetchGlobalVar(t){f.notNullOrUndefined(t,"envVar");return D.fetchGlobalRecord()[t]}static setGlobalVar(t,e){f.notNullOrUndefined(t,"envVar"),f.notNullOrUndefined(e,"value");D.fetchGlobalRecord()[t]=e}}class F{key;value}class j{static op(...t){}}class V{title;timeoutMS;__timeoutTokenFlagField=!0;constructor(t,e){this.title=t,this.timeoutMS=e,Object.setPrototypeOf(this,V.prototype)}writeToLog(t=o.warn){y.logByLevel(t,"Timed out after %d ms waiting for results of %s",this.timeoutMS,this.title)}static isTimeoutToken(t){return!!t&&!!t.__timeoutTokenFlagField}}class k{get createTime(){return this._createTime}starts=new Map;ends=new Map;_createTime=Date.now();_label=p.createRandomHexString(4);_labelIncludedInOutput=!1;constructor(){}withLabel(t){return this._label=p.trimToNull(t),this}withLabelIncludedInOutput(t){return this._labelIncludedInOutput=t,this}get label(){return this._label}set label(t){this._label=t}get labelIncludedInOutput(){return this._labelIncludedInOutput}set labelIncludedInOutput(t){this._labelIncludedInOutput=t}start(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name");const e=Date.now();return this.starts.set(p.trimToNull(t),e),e}stop(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name");const e=Date.now();return this.ends.set(p.trimToNull(t),e),e}reset(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name"),this.starts.delete(p.trimToNull(t)),this.ends.delete(p.trimToNull(t))}hasTimer(t){return f.notNullUndefinedOrOnlyWhitespaceString(t,"name"),this.starts.has(t)}log(t,e,r=o.info){y.logByLevel(r,this.dump(t,e))}logExpected(t,e,r,n=o.info){y.logByLevel(n,this.dumpExpected(t,e,r))}timerNames(){return Array.from(this.starts.keys())}dumpAll(t=", ",e){const r=this.timerNames().map((t=>this.dump(t,e)));let n="Overall: "+this.dump(null,e);return r.length>0&&(n+=t,n+=r.join(t)),n}dump(t,e){let r=this._labelIncludedInOutput?this._label+" ":"";const n=p.trimToNull(t);if(n&&!this.hasTimer(n))r+="No such timer : "+n;else{const s=t?this.starts.get(n):this._createTime,i=t?this.ends.get(n):Date.now();r+=(n||"Default")+" ",s&&i?r+="completed in "+_.formatMsDuration(i-s,!e):s&&(r+="running for "+_.formatMsDuration(Date.now()-s,!e))}return r}dumpExpected(t,e,r){let n=this._labelIncludedInOutput?this._label+" ":"";const s=p.trimToNull(e);if(s&&!this.hasTimer(s))n+="No such timer : "+s;else if(!t||t<=0)n+="Cannot generate output for 0 percent complete";else if(t>1)n+="Cannot generate output for percent > 1";else{n+=(s||"Default")+" ";const i=e?this.starts.get(s):this._createTime,o=e?this.ends.get(s):Date.now();if(i&&o)n+="completed in "+_.formatMsDuration(o-i,!r);else if(i){const e=Date.now()-i,s=e/t-e;n+="running for "+_.formatMsDuration(e,!r)+" approx "+_.formatMsDuration(s,!r)+" remaining"}}return n}expectedRemainingMS(t,e){let r=null;if(!t||t<=0);else if(t>1);else{const n=p.trimToNull(e),s=e?this.starts.get(n):this._createTime,i=e?this.ends.get(n):Date.now();if(s&&i)r=i-s;else if(s){const e=Date.now()-s;r=e/t-e}}return r}elapsedMS(t){let e=null;const r=p.trimToNull(t);if(r&&!this.hasTimer(r))e=null;else{const n=t?this.starts.get(r):this._createTime,s=t?this.ends.get(r):Date.now();n&&s?e=s-n:n&&(e=Date.now()-n)}return e}}class G{static resolveOnEvent(t,e,r=[],n=null){return t&&e&&0!==e.length&&t.on||Promise.reject("Cannot continue - missing source object or name, or the object is not an event source"),new Promise(((s,i)=>{e.forEach((e=>{t.on(e,(()=>{s(n)}))})),r&&r.forEach((e=>{t.on(e,(t=>{i(t)}))}))}))}static timeout(t,e,r){return Promise.race([t,G.createTimeoutPromise(e,r)])}static createTimeoutPromise(t,e){return new Promise(((r,n)=>{const s=setTimeout((()=>{clearTimeout(s);const n=new V(t,e);r(n)}),e)}))}static async wait(t){await G.createTimeoutPromise("Wait "+t,t),y.silly("Finished wait of %d ms",t)}static dumpResult(t,e=!1){y.info("Success, result was : \n\n%s\n\n",JSON.stringify(t)),process.exit(0)}static dumpError(t,e=!1){y.warn("Failure, err was : \n\n%s\n\n -- \n\n%s\n\n",JSON.stringify(t),String(t)),console.trace(),process.exit(1)}static logErrorAndReturnNull(t,e=!1){return y.warn("Failure, err was : \n\n%s\n\n -- \n\n%s\n\n",JSON.stringify(t),String(t)),null}static runPromiseAndDump(t){t.then(G.dumpResult).catch(G.dumpError)}static async waitFor(t,e,r,n,s="waitFor",i=0){if(null==e||r<50||n<1||i<0||"function"!=typeof t)return y.warn("%s: Invalid configuration for waitFor - exiting immediately",s),y.warn("ExpectedValue : %s ; interval: %d ; maxCycles: %d ; test : %s",e,r,n,typeof t),!1;let o=null;try{o=t(i)}catch(t){return y.warn("%s: Caught error while waiting, giving up",s),!1}return null===o?(y.debug("%s:CurVal was null - aborting",s),!1):o==e?(y.debug("%s:Found expected value",s),!0):i>n?(y.debug("%s:Exceeded max cycles, giving up",s),!1):(y.debug("%s : value not reached yet, waiting (count = %d of %d)",s,i,n),await G.wait(r),G.waitFor(t,e,r,n,s,i+1))}static async runBoundedParallel(t,e,r,n=1,s=o.debug){const i=new k;let a=[],l=e;y.logByLevel(s,"Processing %d total elements %d at a time",e.length,n);const c=r||this;let u=0;const d=l.length;for(;l.length>0;){const e=l.slice(0,Math.min(l.length,n));l=l.slice(e.length);const r=e.map((e=>t.apply(c,e))),o=await Promise.all(r);u+=r.length,a=a.concat(o);const h=u/d;y.logByLevel(s,"%d elements remain : %s",l.length,i.dumpExpected(h))}return i.log(),a}static async runBoundedParallelSingleParam(t,e,r,n=1,s=o.debug){const i=N.wrapElementsInArray(e);return G.runBoundedParallel(t,i,r,n,s)}static async asyncForEachSerial(t,e){for(let r=0;r<t.length;r++)await e(t[r],r,t)}static async asyncForEachParallel(t,e){const r=[];for(let n=0;n<t.length;n++)r.push(e(t[n],n,t));await Promise.all(r)}constructor(){}}class z{constructor(){}static sortNullToTop(t,e,r){return z.nullSafeSort(t,e,!0,r)}static sortNullToBottom(t,e,r){return z.nullSafeSort(t,e,!1,r)}static nullSafeSort(t,e,r,n){let s;return s=f.isNullOrUndefined(t)&&f.isNullOrUndefined(e)?0:f.isNullOrUndefined(t)?r?-1/0:1/0:f.isNullOrUndefined(e)?r?1/0:-1/0:n(t,e),s}static sortNumericStringsAsNumbers(t,e,r){const n=b.safeNumber(t),s=b.safeNumber(e);return z.nullSafeSort(n,s,r,((t,e)=>t-e))}}class W{timezoneIanaName;static PACIFIC=new W("America/Los_Angeles");constructor(t){if(this.timezoneIanaName=t,!t||0===t.trim().length)throw"Timezone cannot be null or empty"}get ianaName(){return this.timezoneIanaName}currentHour(){return r.local().setZone(this.timezoneIanaName).hour}toEpochSeconds(t){return Math.round(t.toMillis()/1e3)}startOfTodayEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({hour:0,minute:0,second:0,millisecond:0}))}startOfMatchingDayEpochSeconds(t){return this.toEpochSeconds(r.fromMillis(t).set({hour:0,minute:0,second:0,millisecond:0}))}startOfMatchingDayEpochMS(t){return 1e3*this.startOfMatchingDayEpochSeconds(t)}startOfCurrentHourEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({minute:0,second:0,millisecond:0}))}startOfCurrentMinuteEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({second:0,millisecond:0}))}startOfCurrentSecondEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({millisecond:0}))}startOfTodayEpochMS(){return r.local().setZone(this.timezoneIanaName).set({hour:0,minute:0,second:0,millisecond:0}).toMillis()}dailySlotCount(t){return Math.ceil(864e5/t)}currentTimeSlotIdx(t){if(t<1)throw new Error("Cannot process with slot less than one ms wide");const e=this.startOfTodayEpochMS(),r=(new Date).getTime()-e;return Math.floor(r/t)}matchingTimeSlotIdx(t,e){if(e<1)throw new Error("Cannot process with slot less than one ms wide");const r=t-this.startOfMatchingDayEpochMS(t);return Math.floor(r/e)}startOfCurrentSlotEpochMS(t){return this.startOfTodayEpochMS()+this.currentTimeSlotIdx(t)*t}startOfMatchingSlotEpochMS(t,e){return this.startOfMatchingDayEpochMS(t)+this.matchingTimeSlotIdx(t,e)*e}}class K{constructor(){}static mergeArrays(t){let e=null;if(t?.length){let r=0;t.forEach((t=>{r+=t.length})),e=new Uint8Array(r);let n=0;t.forEach((t=>{e.set(t,n),n+=t.length}))}return e}static deepEqual(t,e){let r=!1;if(t&&e&&t.length===e.length){let n=!1;for(let r=0;r<t.length&&!n;r++)n=t[r]!==e[r];r=!n}return r}}class H{constructor(){}static async webReadableStreamToUint8Array(t){const e=[],r=new WritableStream({write:async(t,r)=>("string"==typeof t?e.push(p.stringToUint8Array(t)):e.push(t),null),abort(t){M.throwFormattedErr("StringWebWritableStream failure : %s",t)}},{highWaterMark:3,size:()=>1});return await t.pipeTo(r),K.mergeArrays(e)}static async webReadableStreamToString(t){const e=await H.webReadableStreamToUint8Array(t);return(new TextDecoder).decode(e)}static stringToWebReadableStream(t){return new ReadableStream({start:e=>(t&&e.enqueue(t),e.close(),null)},{highWaterMark:t?t.length:null})}}class J{wrapped;constructor(t,e){if(!t)throw Error("Cannot set level to null/undefined");this.wrapped={lvl:t,timestamp:Date.now(),messageSource:e}}clone(){const t=new J(this.wrapped.lvl,this.wrapped.messageSource);return t.wrapped=Object.assign({},this.wrapped),t}level(t){if(!t)throw Error("Cannot set level to null/undefined");return this.wrapped.lvl=t,this}timestamp(t){if(!t)throw Error("Cannot set timestamp to null/undefined");return this.wrapped.timestamp=t,this}messageSource(t){return this.wrapped.messageSource=t,this}subVars(t){return this.wrapped.subsVars=t||[],this}params(t){return this.wrapped.params=t||{},this}p(t,e){return this.wrapped.params=this.wrapped.params||{},this.wrapped.params[t]=e,this}toMessage(){return Object.assign({},this.wrapped)}}class Z{static EMAIL=new RegExp(".+@.+\\.[a-z]+");constructor(){}static convertResolvedReadyToSendEmailToRaw(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");const e="To: "+t.destinationAddresses.join(", ")+"\n",r=t.bccAddresses&&t.bccAddresses.length>0?"Bcc: "+t.bccAddresses.join(", ")+"\n":"",n=t.fromAddress,s="NextPart",i="AltPart";let o="From: "+n+"\n";return o+=e,o+=r,o+="Subject: "+t.subject+"\n",o+="MIME-Version: 1.0\n",o+='Content-Type: multipart/mixed; boundary="'+s+'"\n',o+="\n\n--"+s+"\n",o+='Content-Type: multipart/alternative; boundary="'+i+'"\n',p.trimToNull(t.htmlMessage)&&(o+="\n\n--"+i+"\n",o+='Content-Type: text/html; charset="UTF-8"\n\n',o+=t.htmlMessage),p.trimToNull(t.txtMessage)&&(o+="\n\n--"+i+"\n",o+="Content-Type: text/plain\n\n",o+=t.txtMessage),o+="\n\n--"+i+"--\n",t.attachments&&t.attachments.forEach((t=>{o+="\n\n--"+s+"\n",o+="Content-Type: "+t.contentType+'; name="'+t.filename+'"\n',o+="Content-Transfer-Encoding: base64\n",o+="Content-Disposition: attachment\n\n",o+=t.base64Data.replace(/([^\0]{76})/g,"$1\n")+"\n\n"})),o+="\n\n--"+s+"--\n",o}static validEmail(t){return null!==t&&Z.EMAIL.test(t)}}class q{config;constructor(t){this.config=t,f.notNullOrUndefined(t,"config"),f.notNullOrUndefined(t.provider,"config.provider")}async fillEmailBody(t,e,r,n=null,s=null,i=null){return f.notNullOrUndefined(r),this.config.templateRenderer||M.throwFormattedErr("Cannot use fill body if template renderer not set"),t.htmlMessage=await this.config.templateRenderer.renderTemplate(r,e,s,i),t.txtMessage=n?await this.config.templateRenderer.renderTemplate(n,e):null,t}async fillEmailBodyAndSend(t,e,r,n=null,s=null,i=null){const o=await this.fillEmailBody(t,e,r,n,s,i);return await this.sendEmail(o)}filterEmailsToValid(t){return(t||[]).filter((t=>{if(this.config.allowedDestinationEmails&&0!=this.config.allowedDestinationEmails.length){return!!this.config.allowedDestinationEmails.find((e=>e.test(t)))}return!0}))}async archiveEmailIfConfigured(t,e){let r=null;if(t&&this.config.provider.archiveEmail&&!t.doNotArchive){y.debug("Archiving outbound email to : %j",t.destinationAddresses);try{r={raw:await this.config.provider.archiveEmail(t,e),error:null,meta:{}}}catch(e){y.warn("Failed to archive email %j : %s",t,e),r={raw:null,error:M.safeStringifyErr(e),meta:{}}}}return r}applyLimitsToBodySizesIfAnyInPlace(t){if(this.config.maxMessageBodySizeInBytes){const e=p.trimToEmpty(t.txtMessage).length+p.trimToEmpty(t.htmlMessage).length;if(e>this.config.maxMessageBodySizeInBytes){if(y.warn("Max message size is %d but size is %d - converting",this.config.maxMessageBodySizeInBytes,e),t.attachments=t.attachments||[],p.trimToNull(t.txtMessage)){const e={filename:"original-txt-body.txt",contentType:"text/plain",base64Data:x.generateBase64VersionOfString(t.txtMessage)};t.attachments.push(e)}if(p.trimToNull(t.htmlMessage)){const e={filename:"original-html-body.html",contentType:"text/html",base64Data:x.generateBase64VersionOfString(t.htmlMessage)};t.attachments.push(e)}t.htmlMessage=null,t.txtMessage="The message was too large and was converted to attachment(s). Please see attached files for content"}}}applyLimitsToAttachmentSizesIfAnyInPlace(t){if(this.config.maxAttachmentSizeInBase64Bytes){const e=[];t.attachments&&t.attachments.forEach((t=>{t.base64Data&&t.base64Data.length<this.config.maxAttachmentSizeInBase64Bytes?e.push(t):(y.warn("Removing too-large attachment : %s : %s : %d",t.filename,t.contentType,t.base64Data.length),e.push({filename:"attachment-removed-notice-"+p.createRandomHexString(4)+".txt",contentType:"text/plain",base64Data:x.generateBase64VersionOfString("Attachment "+t.filename+" of type "+t.contentType+" was removed since it was "+t.base64Data.length+" bytes but max allowed is "+this.config.maxAttachmentSizeInBase64Bytes)}))})),t.attachments=e}}async sendEmail(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");let e=null;const r=await this.resolveReadyToSendEmail(t);try{const n=await this.config.provider.sendEmail(r);e={request:t,resolved:r,success:!0,rawResult:n,error:null,meta:{},archiveResults:await this.archiveEmailIfConfigured(r,n)}}catch(n){e={request:t,resolved:r,success:!1,rawResult:null,error:M.safeStringifyErr(n),meta:{},archiveResults:null}}return e}async resolveReadyToSendEmail(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");let e=this.filterEmailsToValid(t.destinationAddresses);const r=t.doNotAutoBcc?[]:this.config.autoBccAddresses||[],n=(t.bccAddresses||[]).concat(r);0===e.length&&n.length>0&&(y.debug("Destination emails filtered to none but BCC defined, copying BCC"),e=n);const s=Object.assign({},t);return s.srcDestinationAddresses=t.destinationAddresses,s.srcBccAddresses=t.bccAddresses,s.destinationAddresses=e,s.bccAddresses=n,this.applyLimitsToBodySizesIfAnyInPlace(s),this.applyLimitsToAttachmentSizesIfAnyInPlace(s),0===s.destinationAddresses.length&&y.info("After cleaning email lists, no destination addresses left - not sending email"),s.fromAddress=s.fromAddress||this.config.defaultSendingAddress,s}}class Y{failEmails;constructor(t=[]){this.failEmails=t}async sendEmail(t){return y.info("Called send email : %j",t),this.failEmails&&this.failEmails.forEach((e=>{if(t?.destinationAddresses?.includes(e))throw M.fErr("Forced-fail email address: %s",e)})),"OK"}async archiveEmail(t){return y.info("Called archive email : %j",t),this.failEmails&&this.failEmails.forEach((e=>{if(t?.destinationAddresses?.includes(e))throw M.fErr("Forced-fail email address: %s",e)})),"OK"}}class X{static LOCAL_IP=null;static findLocalIp(t=!0){return y.info("Attempting to find local IP (V 2)"),X.LOCAL_IP&&t?Promise.resolve(X.LOCAL_IP):"undefined"!=typeof window?new Promise((function(t,e){try{const e=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;if(e){const r=new e({iceServers:[]}),n=Object.create(null);n["0.0.0.0"]=!1,r.createDataChannel("",{reliable:!1}),r.onicecandidate=function(e){e.candidate&&X.grepSDP("a="+e.candidate.candidate,n,t)},r.createOffer((function(e){X.grepSDP(e.sdp,n,t),r.setLocalDescription(e)}),(function(e){y.warn("Offer failed : %s",e),t(X.updateLocalIP("FIND_UNSUPPORTED"))}))}else y.warn("IP Address find not supported on this device"),t(X.updateLocalIP("FIND_UNSUPPORTED"))}catch(e){y.warn("Error finding local ip address : %s",e),t(X.updateLocalIP("ERROR"))}})):(y.warn("Window not found, cannot calculate local ip"),Promise.resolve(X.updateLocalIP("NO_WINDOW")))}static parseUrl(t){const e=t.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);return e&&{href:t,protocol:e[1],host:e[2],hostname:e[3],port:e[4],pathname:e[5],search:e[6],hash:e[7]}}static updateLocalIP(t){return X.LOCAL_IP=t,X.LOCAL_IP}static grepSDP(t,e,r){t.split("\r\n").forEach((function(t){if(~t.indexOf("a=candidate")){const n=t.split(" "),s=n[4];"host"===n[7]&&X.updateAddressList(s,e,r)}else if(~t.indexOf("c=")){const n=t.split(" ")[2];X.updateAddressList(n,e,r)}}))}static updateAddressList(t,e,r){if(t in e)return;e[t]=!0;const n=Object.keys(e).filter((function(t){return e[t]}));if(n&&1==n.length)r(X.updateLocalIP(n[0]));else{const t=n.sort().join(",");y.warn("Multiple addresses found, returning sorted join : %s",t),r(X.updateLocalIP(t))}}}class ${currentIp="UNSET";constructor(){X.findLocalIp(!1).then((t=>{y.info("Setting local IP to %s",t),this.currentIp=t})).catch((t=>{y.warn("Unable to set current IP - leaving as UNSET : %s",t)}))}ready(){return"UNSET"!==this.currentIp}currentLocalIpAddress(){return this.currentIp}}class Q{fixed;constructor(t){this.fixed=t}currentLocalIpAddress(){return this.fixed}}class tt extends Error{static RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY="__ratchetRestfulApiHttpErrorFlag";_httpStatusCode=500;_errors;_detailErrorCode;_endUserErrors;_details;_requestId;_wrappedError;constructor(...t){super(tt.combineErrorStringsWithDefault(t)),Object.setPrototypeOf(this,tt.prototype),this._errors=t,this[tt.RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY]=!0}static combineErrorStringsWithDefault(t,e="Internal Server Error"){return t&&t.length>0?t.join(","):e}setFormattedErrorMessage(e,...r){const n=t.format(e,...r);this.errors=[n]}withFormattedErrorMessage(t,...e){return this.setFormattedErrorMessage(t,...e),this}withHttpStatusCode(t){return this.httpStatusCode=t,this}withErrors(t){return this.errors=t,this}withDetailErrorCode(t){return this._detailErrorCode=t,this}withEndUserErrors(t){return this._endUserErrors=t,this}withDetails(t){return this._details=t,this}withRequestId(t){return this._requestId=t,this}withWrappedError(t){return this._wrappedError=t,this}isWrappedError(){return!!this._wrappedError}static wrapError(t){let e=null;return e=tt.objectIsRestfulApiHttpError(t)?t:new tt(t.message).withWrappedError(t).withHttpStatusCode(500),e}static objectIsRestfulApiHttpError(t){return t&&!0===t[tt.RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY]}get httpStatusCode(){return this._httpStatusCode}get errors(){return this._errors}get detailErrorCode(){return this._detailErrorCode}get endUserErrors(){return this._endUserErrors}get details(){return this._details}get requestId(){return this._requestId}get wrappedError(){return this._wrappedError}set httpStatusCode(t){this._httpStatusCode=t||500}set errors(t){this._errors=t||["Internal Server Error"],this.message=tt.combineErrorStringsWithDefault(this._errors)}set detailErrorCode(t){this._detailErrorCode=t}set endUserErrors(t){this._endUserErrors=t}set details(t){this._details=t}set requestId(t){this._requestId=t||"MISSING"}set wrappedError(t){this._wrappedError=t}static errorIsX0x(t,e){let r=!1;if(t&&tt.objectIsRestfulApiHttpError(t)){const n=t,s=b.safeNumber(n.httpStatusCode),i=100*e;r=s>=i&&s<=i+99}return r}static errorIs40x(t){return tt.errorIsX0x(t,4)}static errorIs50x(t){return tt.errorIsX0x(t,5)}}class et{static GOOGLE_VERIFY_URL="https://www.google.com/recaptcha/api/siteverify?secret={{KEY}}&response={{TOKEN}}";static async verifyRecaptchaToken(t,e,r=i){y.debug("Verifying recaptcha token : %s",e);let n=null;if(!p.safeString(e))return y.warn("Recaptcha validation error, no token passed : %s",e),n;y.info("Validating Recaptcha via Google API : %s",e);let s=et.GOOGLE_VERIFY_URL;s=s.split("{{KEY}}").join(t),s=s.split("{{TOKEN}}").join(e);try{const t=await r(s),e=await t.json();n=e&&e.success}catch(t){y.error("Failed to read from google : %s",t),n=!1}return n}}class rt{accountSid;authToken;outBoundNumber;static TWILLIO_BASE_API_URL="https://api.twilio.com/2010-04-01";constructor(t,e,r){this.accountSid=t,this.authToken=e,this.outBoundNumber=r,f.notNullOrUndefined(t,"accountSid"),f.notNullOrUndefined(e,"authToken"),f.notNullOrUndefined(r,"outBoundNumber"),f.true(rt.isValidE164Number(r),"outBoundNumber invalid format")}static async sendMessageDirect(t,e,r,n,s){const i=new rt(t,e,r);return await i.sendMessage(n,s)}static generateTwilioBasicAuth(t,e){return"Basic "+x.generateBase64VersionOfString(t+":"+e)}async sendMessage(t,e){const r=[];if(f.notNullOrUndefined(t,"recipientPhoneNumbers"),f.notNullOrUndefined(p.trimToNull(e),"message"),f.true(t.length>0,"recipientPhoneNumbers non-empty"),t&&t.length>0&&p.trimToNull(e)){y.info("Sending %s to %j",e,t);for(let n=0;n<t.length;n++){const s=t[n];if(y.info("To: %s",s),!rt.isValidE164Number(s))throw new Error("number must be E164 format!");const o="Body="+encodeURIComponent(e)+"&From="+encodeURIComponent(this.outBoundNumber)+"&To="+encodeURIComponent(s),a={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:o},l=await i(rt.TWILLIO_BASE_API_URL+"/Accounts/"+this.accountSid+"/Messages.json",a),c=await l.json();y.debug("TwilioRatchet: For %s got %j",s,c),r.push(c)}}else y.warn("Not sending empty message / empty recipients");return r}static isValidE164Number(t){return/^\+?[1-9]\d{1,14}$/.test(t)}}class nt{accountSid;authToken;serviceSid;static TWILLIO_BASE_VERIFY_URL="https://verify.twilio.com/v2/Services/";constructor(t,e,r){this.accountSid=t,this.authToken=e,this.serviceSid=r,f.notNullUndefinedOrOnlyWhitespaceString(t,"accountSid"),f.notNullUndefinedOrOnlyWhitespaceString(e,"authToken"),f.notNullUndefinedOrOnlyWhitespaceString(r,"serviceSid")}async sendVerificationTokenUsingTwilioVerify(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"recipientPhoneNumber"),f.true(rt.isValidE164Number(t),"recipientPhoneNumber must be E164");const e=t.startsWith("+1")?t:"+1"+t,r="Channel=sms&To="+encodeURIComponent(e),n={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:r},s=nt.TWILLIO_BASE_VERIFY_URL+this.serviceSid+"/Verifications",o=await i(s,n);return await o.text()}async simpleCheckVerificationTokenUsingTwilioVerify(t,e){const r=await this.checkVerificationTokenUsingTwilioVerify(t,e);return r&&"approved"===r.status}async checkVerificationTokenUsingTwilioVerify(t,e){f.notNullUndefinedOrOnlyWhitespaceString(t,"recipientPhoneNumber"),f.true(rt.isValidE164Number(t),"recipientPhoneNumber must be E164");const r=t.startsWith("+1")?t:"+1"+t,n="To="+encodeURIComponent(r)+"&Code="+encodeURIComponent(e),s={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:n},o=nt.TWILLIO_BASE_VERIFY_URL+this.serviceSid+"/VerificationCheck";y.info("Using %s / %j",o,s);const a=await i(o,s);return await a.json()}}class st{static keysOnly(t){return{transform:(e,r,n)=>r?t.transform(e,r,n):e}}static valuesOnly(t){return{transform:(e,r,n)=>r?e:t.transform(e,r,n)}}static stringReplaceTransform(t,e){return{transform:(r,n,s)=>r==t?e:r}}static stripStringTransform(t){return{transform:(e,r,n)=>e==t?null:e}}static retainAll(t){return{transform:(e,r,n)=>-1==t.indexOf(e)?null:e}}static removeAll(t){return{transform:(e,r,n)=>t.indexOf(e)>-1?null:e}}static snakeToCamelCase(){return{transform(t,e,r){let n=t;return"string"==typeof t&&(n=t.replace(/_([a-z0-9])/gi,(function(t,e){return e.toUpperCase()}))),n}}}static stringToNumber(){return{transform(t,e,r){let n=t;if("string"==typeof t){const e=b.safeNumber(t);null!==e&&(n=e)}return n}}}static camelToSnakeCase(){return{transform(t,e,r){let n=t;return"string"==typeof t&&(n=t.replace(/\.?([A-Z]+)/g,(function(t,e){return"_"+e.toLowerCase()})).replace(/^_/,"")),n}}}static concatenateToNewField(t,e,r=!0){return{transform(n,s,i){if("object"==typeof n){let s="";e.forEach((t=>{if(null!=s){const e=n[t];s=null==e&&r?null:null==e?s:s+String(e)}})),null!=s&&(n[t]=s,e.forEach((t=>delete n[t])))}return n}}}static numberToBool(t){return{transform:(e,r,n)=>("object"==typeof e&&t.forEach((t=>{const r=e[t];if("number"==typeof r){const n=0!=r;e[t]=n}})),e)}}static boolToNumber(t){return{transform:(e,r,n)=>("object"==typeof e&&t.forEach((t=>{const r=e[t];if("boolean"==typeof r){const n=r?1:0;e[t]=n}})),e)}}static makeDuplicateField(t,e){return{transform(r,n,s){if("object"==typeof r){const n=r[t];null!=n&&(r[e]=n)}return r}}}static addField(t,e){return{transform:(r,n,s)=>("object"==typeof r&&(r[t]=e),r)}}static reformatDateFields(t,e,n){return{transform:(s,i,o)=>("object"==typeof s&&t.forEach((t=>{const i=s[t];if(null!=i)try{const o=r.fromFormat(i,e).toFormat(n);s[t]=o}catch(t){y.warn("Failed to reparse date %s in format %s : %s",i,e,t)}})),s)}}}class it{static transform(t,e=[]){return it.transformGeneric(t,e,!1,null)}static transformGeneric(t,e=[],r,n){let s=null;const i=typeof t;switch(i){case"undefined":case"symbol":case"function":s=t;break;case"number":case"string":case"boolean":s=it.applyTransformToPrimitive(t,e,r,n);break;case"object":s=it.applyTransformToObject(t,e,r,n);break;default:throw new Error("Unrecognized type "+i)}return s}static applyTransformToObject(t,e=[],r,n=null){y.silly("Tranform: %j, %s, %j",t,r,n);let s=null;return null!=t&&(Array.isArray(t)?(s=[],t.forEach((n=>{const i=it.transformGeneric(n,e,r,t);null!=i&&s.push(i)}))):(s={},Object.keys(t).forEach((r=>{const n=t[r],i=it.applyTransformToPrimitive(r,e,!0,t);if(null!=i){let r=it.transformGeneric(n,e,!1,t);r=it.applyTransformToPrimitive(r,e,!1,t),null!=r&&(s[i]=r)}})),s=it.applyTransformToPrimitive(s,e,!1,t))),s}static applyTransformToPrimitive(t,e=[],r,n){let s=t;return e.forEach((t=>{s=null==s?null:t.transform(s,r,n)})),s}}const ot={Success:"Success",RolledBack:"RolledBack",RollbackFailed:"RollbackFailed"};class at{static async execute(t,e,r){f.notNullOrUndefined(t,"steps"),f.notNullOrUndefined(e,"initialContext"),f.true(t.length>0,"steps may not be empty");const n=Object.assign({},r||{});n.stepLogLevel=n.stepLogLevel||o.info;const s={finalContext:e,finalState:null},i=t.map(((t,e)=>t.name||"Step "+e));y.info("Beginning transaction of %d steps",t.length);let a=0;do{y.logByLevel(n.stepLogLevel,"Processing step %d of %d (%s)",a+1,t.length,i[a]);try{await t[a].execute(s.finalContext,a),a++}catch(t){y.error("Failure detected on step %d : %s : %s : Rolling back",a,i[a],t,t),s.error=t,s.errorStep=a}}while(!s.error&&a<t.length);if(s.error)do{y.logByLevel(n.stepLogLevel,"Rolling back step %d of %d (%s)",a+1,t.length,i[a]);try{t[a].rollback?await t[a].rollback(s.finalContext,a):y.info("Skipping - no rollback defined")}catch(t){y.error("Very bad - rollback code failed on step %d : %s : Aborting in invalid state: %s",a,i[a],t,t),s.rollbackError=t,s.rollbackErrorStep=a}a--}while(a>=0);if(s.finalState=s.rollbackError?ot.RollbackFailed:s.error?ot.RolledBack:ot.Success,y.info("Transaction completed with status : %s",s.finalState),n?.executeAfterRollback&&s.finalState!==ot.Success)try{y.info("Applying executeAfterRollback"),await n.executeAfterRollback(s)}catch(t){y.error("Very bad - failure in executeAfterRollback : %s",t,t)}if(n?.executeAfterRollbackFailure&&s.finalState!==ot.Success)try{y.info("Applying executeAfterRollbackFailure"),await n.executeAfterRollbackFailure(s)}catch(t){y.error("Very bad - failure in executeAfterRollbackFailure : %s",t,t)}return s}}export{N as ArrayRatchet,x as Base64Ratchet,E as BooleanRatchet,$ as BrowserLocalIpProvider,st as BuiltInTransforms,d as ClassicSingleLineLogMessageFormatter,I as CompositeLastSuccessProvider,v as DateRatchet,_ as DurationRatchet,P as EnumRatchet,M as ErrorRatchet,R as EsmRatchet,O as ExpiredJwtHandling,C as ExpiringObject,B as ExpiringObjectConfig,Q as FixedLocalIpProvider,U as GeolocationRatchet,D as GlobalRatchet,et as GoogleRecaptchaRatchet,T as Histogram,L as JwtRatchet,F as KeyValue,J as LogMessageBuilder,u as LogMessageFormatType,y as Logger,m as LoggerInstance,o as LoggerLevelName,l as LoggerOutputFunction,a as LoggerRingBuffer,c as LoggerUtil,q as Mailer,Z as MailerUtil,A as MapRatchet,X as NetworkRatchet,j as No,h as NoneLogMessageFormatter,b as NumberRatchet,G as PromiseRatchet,S as Ratchet2d,w as RatchetInfo,f as RequireRatchet,tt as RestfulApiHttpError,z as SortRatchet,k as StopWatch,p as StringRatchet,g as StructuredJsonLogMessageFormatter,Y as TestMailSendingProvider,W as TimeZoneRatchet,V as TimeoutToken,ot as TransactionFinalState,at as TransactionRatchet,it as TransformRatchet,rt as TwilioRatchet,nt as TwilioVerifyRatchet,K as Uint8ArrayRatchet,H as WebStreamRatchet};
|
|
1
|
+
import t from"util";import e from"jsonwebtoken";import{DateTime as r}from"luxon";import{$enum as n}from"ts-enum-util";import s from"url";import i from"cross-fetch";const o={error:"error",warn:"warn",info:"info",verbose:"verbose",debug:"debug",silly:"silly"};class a{_lastLogMessage={messageSource:"No message yet",timestamp:(new Date).getTime(),lvl:o.info};_buffer=[];_bufferIdx=0;_lastSnapshotIdx=0;_bufferSize;constructor(t){if(!t)throw new Error("Cannot create ring buffer of size 0");this._bufferSize=t}get currentIndex(){return this._bufferIdx}get lastSnapshotIdx(){return this._lastSnapshotIdx}set bufferSize(t){if(!t)throw new Error("Cannot create ring buffer of size 0");this._bufferSize=t,this.clearRingBuffer()}getMessages(t=null,e=!1,r=!1){let n=null;if(this._bufferIdx<this._bufferSize){const e=null==t?0:t;n=this._buffer.slice(e,this._bufferIdx)}else{n=[];const e=this._bufferIdx-this._bufferSize;for(let r=t?Math.max(t,e):e;r<this._bufferIdx;r++)n.push(this._buffer[r%this._bufferSize])}return e&&this.clearRingBuffer(),r&&(n=n.reverse()),n}takeSnapshot(){const t=Math.max(0,this._bufferIdx-this._bufferSize),e={messages:this.getMessages(this._lastSnapshotIdx),logMessagesTruncated:Math.max(0,t-this._lastSnapshotIdx)};return this._lastSnapshotIdx=this._bufferIdx,e}getLastLogMessage(){return Object.assign({},this._lastLogMessage)}clearRingBuffer(){this._buffer=[],this._bufferIdx=0,this._lastSnapshotIdx=0}addToRingBuffer(t){this._lastLogMessage=t,this._buffer[this._bufferIdx%this._bufferSize]=t,this._bufferIdx++}}const l={Console:"Console",ConsoleNoDebug:"ConsoleNoDebug",StdOut:"StdOut"};class c{static LOG_LEVELS_IN_ORDER=[o.error,o.warn,o.info,o.verbose,o.debug,o.silly];static handlerFunctionMap(t=l.Console){const e=new Map;if(t===l.StdOut){if(!process?.stdout?.write)throw new Error("Cannot use standard out - process.stdout.write not found");const t=(t,e)=>process.stdout.write(t,"utf-8",e);e.set(o.error,t),e.set(o.warn,t),e.set(o.info,t),e.set(o.verbose,t),e.set(o.debug,t),e.set(o.silly,t)}else e.set(o.error,console.error),e.set(o.warn,console.warn),e.set(o.info,console.info),e.set(o.verbose,t===l.ConsoleNoDebug?console.log:console.debug),e.set(o.debug,t===l.ConsoleNoDebug?console.log:console.debug),e.set(o.silly,t===l.ConsoleNoDebug?console.log:console.debug);return e}static defaultHandlerFunction(){return console.info}static levelIsEnabled(t,e){const r=c.LOG_LEVELS_IN_ORDER.indexOf(t),n=c.LOG_LEVELS_IN_ORDER.indexOf(e);return r>-1&&n>-1&&n>=r}}const u={ClassicSingleLine:"ClassicSingleLine",StructuredJson:"StructuredJson",None:"None"};class d{formatMessage(e,r){let n=null;return e&&(n="",n+=r.options.trace?r.options.trace+" ":"",n+="["+e.lvl+"] ",n+=t.format(e.messageSource,...e.subsVars)),n}}class h{formatMessage(t,e){return null}}class g{formatMessage(e,r){let n=null;if(e){const s=Object.assign({},r.options.globalVars||{},e.params||{});s.msg=t.format(e.messageSource,...e.subsVars),s.utcDateTime=new Date(e.timestamp).toISOString(),s.logLevel=e.lvl,r.options.trace&&(s.trace=r.options.trace),s.logName=r.loggerInstanceName,s.logId=r.loggerInstanceId,n=JSON.stringify(s)+"\n"}return n}}class f{static isNullOrUndefined(t){return Object.is(t,null)||Object.is(t,void 0)}static notNullOrUndefined(t,e="object"){if(f.isNullOrUndefined(t))throw new Error(e+" may not be null or undefined")}static notNullUndefinedOrOnlyWhitespaceString(t,e="string"){if(f.isNullOrUndefined(t)||""===t.trim())throw new Error(e+" may not be null or undefined or only whitespace string")}static notNullUndefinedOrEmptyArray(t,e="string"){if(f.isNullOrUndefined(t)||0===t.length)throw new Error(e+" may not be null or undefined or an empty array")}static equal(t,e,r="Values must be equal"){if(t!==e)throw new Error(r)}static true(t,e="Value must be true"){f.equal(t,!0,e)}static noNullOrUndefinedValuesInArray(t,e=null,r=null){if(f.notNullOrUndefined(t,"Source array may not be null"),null!==e&&t.length!==e)throw new Error(`Expected array of length ${e} but was ${t.length} ${r}`);for(let e=0;e<t.length;e++)if(f.isNullOrUndefined(t[e]))throw new Error(`Array index ${e} was null or undefined ${r}`)}static noNullOrUndefinedValuesInRestArgs(t,...e){if(f.notNullOrUndefined(e,"Source array may not be null"),null!==t&&e.length!==t)throw new Error(`Expected array of length ${t} but was ${e.length}`);for(let t=0;t<e.length;t++)if(f.isNullOrUndefined(e[t]))throw new Error(`Array index ${t} was null or undefined`)}static constructorArgumentsMatchLengthAndAreNonNull(){const t=Array.from(arguments),e=this.constructor.length;return f.noNullOrUndefinedValuesInArray(t,e)}}class p{static RFC_3986_RESERVED=["!","*","'","(",")",";",":","@","&","=","+","$",",","/","?","#","[","]","%"];static DIGITS="0123456789";static HEXITS=p.DIGITS+"ABCDEF";static UPPER_CASE_LATIN="ABCDEFGHIJKLMNOPQRSTUVWXYZ";static LOWER_CASE_LATIN="abcdefghijklmnopqrstuvwxyz";static CASE_INSENSITIVE_LATIN=p.UPPER_CASE_LATIN+p.LOWER_CASE_LATIN;static stringIsInGivenAlphabet(t,e){let r=!1;if(t&&e)for(let n=0;n<t.length&&!r;n++)r=e.includes(t.charAt(n));return r}static stringToUint8Array(t){return t?(new TextEncoder).encode(t):null}static uint8ArrayToString(t){return t?(new TextDecoder).decode(t):null}static attemptJsonParse(t){let e=null;if(p.trimToNull(t))try{e=JSON.parse(t)}catch(t){e=null}return e}static canParseAsJson(t){return!!p.attemptJsonParse(t)}static allUnique(t){let e=!0;if(t){const r=new Set;for(let n=0;n<t.length&&e;n++){const s=t.charAt(n);e=!r.has(s),r.add(s)}}return e}static allPermutationsOfLength(t,e){const r=[];if(t>0&&e&&e.length>0){f.true(p.allUnique(e),"Alphabet must be unique");const n=1===t?[""]:p.allPermutationsOfLength(t-1,e);for(let t=0;t<e.length;t++)n.forEach((n=>r.push(e.charAt(t)+n)))}return r}static breakIntoBlocks(t,e,r){let n="";for(;t.length>e;)n=r+t.substring(t.length-e)+n,t=t.substring(0,t.length-e);return n=t.length>0?t+n:n.substring(1),n}static createShortUid(t=0,e=1e3,r=36){const n=Math.floor(Date.now()/1e3),s=parseInt(String(Math.floor(Math.random()*e))+String(n)).toString(r);return t>0?p.breakIntoBlocks(s,t,"-"):s}static createType4Guid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}))}static createRandomHexString(t=10){let e="";for(let r=0;r<t;r++)e+=Math.floor(16*Math.random()).toString(16);return e}static canonicalize(t){let e=t?t.toLowerCase():"";return e=e.replace(" ","-"),p.RFC_3986_RESERVED.forEach((t=>{e=e.replace(t,"")})),e}static formatBytes(t,e=2){if(0==t)return"0 Bytes";const r=e||2,n=Math.floor(Math.log(t)/Math.log(1024));return parseFloat((t/Math.pow(1024,n)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][n]}static safeString(t){let e=null;if(null!=t){e="string"==typeof t?t:String(t)}return e}static stringContainsOnlyNumbers(t){return/^[0-9]+$/.test(t)}static stringContainsOnlyAlphanumeric(t){return/^[0-9a-zA-Z]+$/.test(t)}static stringContainsOnlyHex(t){return/^[0-9a-fA-F]+$/.test(t)}static stringContainsOnly(t,e){const r=t||"",n=e||"";let s=!0;for(let t=0;t<r.length&&s;t++)s=n.indexOf(r.charAt(t))>=0;return s}static obscure(t,e=2,r=2){if(!t)return t;const n=t.length;let s=e,i=r;for(;n>0&&n<s+i+1;)s=Math.max(0,s-1),i=Math.max(0,i-1);const o=n-(s+i);let a="";a+=t.substring(0,s);for(let t=0;t<o;t++)a+="*";return a+=t.substring(n-i),a}static leadingZeros(t,e){const r="00000000000000000000000000000000000000000000000000";let n=!1,s=String(t);if(s.startsWith("-")&&(n=!0,s=s.substring(1)),e>50)throw new Error("Cannot format number that large");let i=(r+s).slice(-1*e);return n&&(i="-"+i),i}static trimToEmpty(t){return(t?p.safeString(t):"").trim()}static trimToNull(t){const e=p.trimToEmpty(t);return e.length>0?e:null}static trimAllStringPropertiesToNullInPlace(t){return p.trimAllStringPropertiesInPlace(t,!1)}static trimAllStringPropertiesToEmptyInPlace(t){return p.trimAllStringPropertiesInPlace(t,!0)}static trimAllStringPropertiesInPlace(t,e){return Object.keys(t).forEach((r=>{const n=t[r];null!=n&&"string"==typeof n&&(t[r]=e?p.trimToEmpty(t[r]):p.trimToNull(t[r]))})),t}static stripNonNumeric(t){let e=t;if(null!=t&&!p.stringContainsOnlyNumbers(t)){e="";for(let r=0;r<t.length;r++){const n=t.charAt(r);(p.stringContainsOnlyNumbers(n)||0===r&&"-"===n)&&(e+=n)}}return e}static csvSafe(t){let e=p.trimToEmpty(p.safeString(t));return e.split('"').join('\\"'),-1===e.indexOf(",")&&-1===e.indexOf('"')&&-1===e.indexOf("'")||(e='"'+e+'"'),e}static stripNonAscii(t){return[...t].reduce(((t,e)=>e.charCodeAt(0)>127?t:t+e))}static replaceAll(t,e,r){let n=t;return n?.length&&e?.length&&r?.length&&(n=n.split(e).join(r)),n}}class m{loggerInstanceName;_guid=Math.floor(1e6*Math.random());_loggerMeta;_ringBuffer;_formatter;_level;_handlerFunctionMap;_options;constructor(t="default",e){this.loggerInstanceName=t,this.options=e}addPreProcessor(t){return t&&(this._options.preProcessors=this._options.preProcessors||[],this._options.preProcessors.push(t)),Object.assign([],this._options.preProcessors)}get ringBuffer(){return this._ringBuffer}dumpConfigurationIntoLog(){this.error("ERROR enabled"),this.warn("WARN enabled"),this.info("INFO enabled"),this.verbose("VERBOSE enabled"),this.debug("DEBUG enabled"),this.silly("SILLY enabled")}dumpOptionsIntoLog(){if(this.info("Guid: %s Options: %j",this._guid,this.options),this?.options?.preProcessors?.length){const t=this.options.preProcessors.map((t=>p.trimToNull(t.label())||"Unlabelled"));this.info("Preprocessors: %j",t)}}get guid(){return this._guid}changeRingBufferSize(t){this._ringBuffer=null,t&&(this._ringBuffer=new a(t),this._options.ringBufferSize=t)}updateTracePrefix(t){this._options.trace=t}get options(){return Object.assign({},this._options)}set options(t){switch(this._options=Object.assign({},t),this._options.ringBufferSize&&(this._ringBuffer=new a(this._options.ringBufferSize)),this._options.formatType){case u.None:this._formatter=new h;break;case u.StructuredJson:this._formatter=new g;break;default:this._formatter=new d}this._level=this._options.initialLevel,this._handlerFunctionMap=c.handlerFunctionMap(this._options.outputFunction);const e=this._loggerMeta?this._loggerMeta.loggerInstanceId:null;this._loggerMeta={options:this._options,loggerInstanceName:this.loggerInstanceName,loggerInstanceId:e||p.createRandomHexString(8)}}get level(){return this._level}set level(t){if(!t)throw new Error("Cannot set level to null/undefined");this._level=t}consoleLogPassThru(t,...e){if(c.levelIsEnabled(t,this._level)){let r=this._options.trace||"";r+="["+t+"] ",e.unshift(r);(this._handlerFunctionMap.get(t)||c.defaultHandlerFunction)(...e)}}createLogMessage(t,e,r,...n){return{lvl:t,timestamp:Date.now(),messageSource:r,subsVars:n,params:e}}formatMessage(t){return t?this._formatter.formatMessage(t,this._loggerMeta):null}formatMessages(t){return(t||[]).map((t=>this.formatMessage(t))).filter((t=>!!t))}recordMessageBuilder(t){return this.recordMessage(t.toMessage())}recordMessage(t){let e=null;if(c.levelIsEnabled(t.lvl,this._level)){let r=Object.assign({},t);if(this._options.preProcessors?.length)for(let t=0;t<this._options.preProcessors.length;t++)r=this._options.preProcessors[t].process(r);if(e=this.formatMessage(r),e){(this._handlerFunctionMap.get(r.lvl)||c.defaultHandlerFunction)(e),this._ringBuffer&&this._ringBuffer.addToRingBuffer(r)}}return e}error(t,...e){const r=this.createLogMessage(o.error,{},t,...e);return this.recordMessage(r)}errorP(...t){this.consoleLogPassThru(o.error,...t)}warn(t,...e){const r=this.createLogMessage(o.warn,{},t,...e);return this.recordMessage(r)}warnP(...t){this.consoleLogPassThru(o.warn,...t)}info(t,...e){const r=this.createLogMessage(o.info,{},t,...e);return this.recordMessage(r)}infoP(...t){this.consoleLogPassThru(o.info,...t)}verbose(t,...e){const r=this.createLogMessage(o.verbose,{},t,...e);return this.recordMessage(r)}verboseP(...t){this.consoleLogPassThru(o.verbose,...t)}debug(t,...e){const r=this.createLogMessage(o.debug,{},t,...e);return this.recordMessage(r)}debugP(...t){this.consoleLogPassThru(o.debug,...t)}silly(t,...e){const r=this.createLogMessage(o.silly,{},t,...e);return this.recordMessage(r)}sillyP(...t){this.consoleLogPassThru(o.silly,...t)}logByLevel(t,e,...r){const n=this.createLogMessage(t,{},e,...r);this.recordMessage(n)}importMessages(t,e="",r=!0){const n=e||"";t&&t.length>0&&(this.silly("Received import data : %d msgs",t.length),t.forEach((t=>{if(t.messageSource){let e=n;if(r){e+=" ("+String(new Date).substring(15,24)+") : ",e+=t.messageSource}this.logByLevel(t.lvl,e)}})))}}class y{static LOGGER_INSTANCE_MAP_GLOBAL_KEY="RATCHET_GLOBAL_LOGGER_MAP_V01";static GLOBAL_PROVIDER=process||global||window;static DEFAULT_OPTIONS={initialLevel:o.info,formatType:u.ClassicSingleLine,trace:null,globalVars:{},outputFunction:l.Console,ringBufferSize:0,preProcessors:[]};static applyDefaultsToOptions(t){const e=t||{};return e.initialLevel=e.initialLevel??y.DEFAULT_OPTIONS.initialLevel,e.formatType=e.formatType??y.DEFAULT_OPTIONS.formatType,e.trace=e.trace??y.DEFAULT_OPTIONS.trace,e.globalVars=e.globalVars??y.DEFAULT_OPTIONS.globalVars,e.outputFunction=e.outputFunction??y.DEFAULT_OPTIONS.outputFunction,e.ringBufferSize=e.ringBufferSize??y.DEFAULT_OPTIONS.ringBufferSize,e}static loggerInstances(){if(!y.GLOBAL_PROVIDER)throw new Error("Cannot create logger - could not find a global provider");let t=y.GLOBAL_PROVIDER[y.LOGGER_INSTANCE_MAP_GLOBAL_KEY];return t||(t=new Map,y.GLOBAL_PROVIDER[y.LOGGER_INSTANCE_MAP_GLOBAL_KEY]=t),t}static changeDefaultOptions(t,e){if(!t||!t.initialLevel||!t.formatType)throw new Error("Default options must be non-null, and provide initial level and format type");y.DEFAULT_OPTIONS=Object.assign({},t),e&&Array.from(y.loggerInstances().values()).forEach((e=>e.options=t))}static getLogger(t="default",e){let r=y.loggerInstances().get(t);if(!r){const n=y.applyDefaultsToOptions(e);r=new m(t,n),y.loggerInstances().set(t,r)}return r}static recordMessageBuilder(t){return y.getLogger().recordMessageBuilder(t)}static recordMessage(t){return y.getLogger().recordMessage(t)}static formatMessages(t){return y.getLogger().formatMessages(t)}static updateTracePrefix(t){return y.getLogger().updateTracePrefix(t)}static changeRingBufferSize(t){return y.getLogger().changeRingBufferSize(t)}static getRingBuffer(){return y.getLogger().ringBuffer}static dumpConfigurationIntoLog(){return y.getLogger().dumpConfigurationIntoLog()}static dumpOptionsIntoLog(){return y.getLogger().dumpOptionsIntoLog()}static getLevel(){return y.getLogger().level}static setLevel(t){y.getLogger().level=t}static getOptions(){return y.getLogger().options}static getMessages(t=null,e=!1,r=!1){const n=y.getLogger().ringBuffer;return n?n.getMessages(t,e,r):null}static consoleLogPassThru(t,...e){return y.getLogger().consoleLogPassThru(t,...e)}static error(t,...e){return y.getLogger().error(t,...e)}static errorP(...t){return y.getLogger().errorP(...t)}static warn(t,...e){return y.getLogger().warn(t,...e)}static warnP(...t){return y.getLogger().warnP(...t)}static info(t,...e){return y.getLogger().info(t,...e)}static infoP(...t){return y.getLogger().infoP(...t)}static verbose(t,...e){return y.getLogger().verbose(t,...e)}static verboseP(...t){return y.getLogger().verboseP(...t)}static debug(t,...e){return y.getLogger().debug(t,...e)}static debugP(...t){return y.getLogger().debugP(...t)}static silly(t,...e){return y.getLogger().silly(t,...e)}static sillyP(...t){return y.getLogger().sillyP(...t)}static takeSnapshot(){const t=y.getLogger().ringBuffer;return t?t.takeSnapshot():null}static logByLevel(t,e,...r){return y.getLogger().logByLevel(t,e,...r)}static importMessages(t,e="",r=!0){return y.getLogger().importMessages(t,e,r)}static getLastLogMessage(){const t=y.getLogger().ringBuffer;return t?t.getLastLogMessage():null}}class b{static MAX_LEADING_ZEROS_FORMAT_LENGTH=1e3;static DEFAULT_SAFE_NUMBER_OPTIONS={ifNotNumber:null,returnValueForNull:null,returnValueForUndefined:null,preParseCharacterMapping:{",":""}};static toFixedDecimalNumber(t,e){const r=b.safeNumber(t);return null==r?r:b.safeNumber(r.toFixed(e))}static leadingZeros(t,e){const r=String(t);if(r.length<e){let t="0000";if(e>b.MAX_LEADING_ZEROS_FORMAT_LENGTH)throw"Cannot format number that large (max length is "+b.MAX_LEADING_ZEROS_FORMAT_LENGTH+")";for(;t.length<e;)t+=t;return(t+r).slice(-1*e)}return r}static between(t,e,r){const n=b.safeNumber(t),s=b.safeNumber(e),i=b.safeNumber(r);return n>=s&&n<=i||n>=i&&n<=s}static safeNumber(t,e=null,r){const n={ifNotNumber:e,returnValueForNull:r?e:null,returnValueForUndefined:r?e:void 0};return void 0===r&&(n.returnValueForUndefined=null),b.safeNumberOpt(t,n)}static safeNumberOpt(t,e){let r;const n=Object.assign({},b.DEFAULT_SAFE_NUMBER_OPTIONS,e||{});if(null===t)r=n.returnValueForNull;else if(void 0===t)r=n.returnValueForUndefined;else{const e=typeof t;if("number"==e)r=t;else if("string"==e){let e=t.trim();if(0===e.length)r=n.ifNotNumber;else{if(n.preParseCharacterMapping&&Object.keys(n.preParseCharacterMapping).length>0){let t="";for(let r=0;r<e.length;r++){const s=e.charAt(r);t+=void 0===n.preParseCharacterMapping[s]?s:n.preParseCharacterMapping[s]}e=t}r=Number.parseFloat(e)}}else y.warn("Value is of type %s, returning default",e),r=n.ifNotNumber;isNaN(r)&&(y.debug("Parsed string to NaN - using NaN value from param"),r=n.ifNotNumber)}return r}static numberCSVToList(t){let e=null;return t&&(e=t.split(",").map((t=>b.safeNumber(t.trim()))),e=e.filter((t=>"number"==typeof t&&!isNaN(t)))),e}static fitToWindow(t,e,r){let n=t;if(null===t||null===e||null===r||e<0||r<0||t<0)throw new Error("All values must be non-null and larger than 0");const s=Math.min(e,r),i=Math.max(e,r),o=i-s;if(i===s)n=i;else{for(;n<s;)n+=o;for(;n>i;)n-=o}return n}static groupNumbersIntoContiguousRanges(t,e=3){f.notNullOrUndefined(t);const r=Object.assign([],t);r.sort(((t,e)=>t-e));const n=[],s=[];let i=0;for(let t=1;t<r.length;t++)if(r[t]===r[t-1]+1);else{if(i===t-1)n.push(r[t-1]);else{if(t-i<e)for(let e=i;e<t;e++)n.push(r[e]);else s.push({min:r[i],max:r[t-1]})}i=t}return{singles:n,ranges:s}}static distributeItemsEvenly(t,e){f.notNullOrUndefined(t,"items"),f.notNullOrUndefined(e,"buckets"),f.true(t>0&&t===Math.floor(t),"Items integer larger than 0"),f.true(e>0&&e===Math.floor(e),"Buckets integer larger than 0");const r=e/t,n=[];for(let t=0;t<e;t++)n.push(0);let s=0,i=t;for(;i>0;)n[Math.floor(s)%e]++,i--,s+=r;return n}static createRange(t,e,r=1){const n=[];let s=t;for(;s<e;)n.push(s),s+=r;return n}}class E{static allTrue(t,e=!1){let r=null;return r=!!t&&(t.length>0?t.reduce(((t,e)=>t&&e),!0):e),r}static anyTrue(t,e=!1){let r=null;return r=!!t&&(t.length>0?t.reduce(((t,e)=>t||e),!1):e),r}static parseBool(t){return!0===t||null!=t&&"string"==typeof t&&"true"===t.toLowerCase()}static intToBool(t){return null!=t&&0!==b.safeNumber(t)}static boolToInt(t){return E.parseBool(t)?1:0}}class S{constructor(){}static translateToOriginVector(t){let e=null;return S.validPoints(t)&&(e={x:null,y:null},t.forEach((t=>{e.x=null===e.x||t.x<e.x?t.x:e.x,e.y=null===e.y||t.y<e.y?t.y:e.y})),e.x*=-1,e.y*=-1),e}static minimalContainingPlane(t){let e=null;return S.validPoints(t)&&(e={width:0,height:0},t.forEach((t=>{e.width=Math.max(e.width,t.x+1),e.height=Math.max(e.height,t.y+1)}))),e}static scaleVector(t,e){let r=null;return S.validPlane(t)&&S.validPlane(e)&&(r={x:e.width/t.width,y:e.height/t.height}),r}static samePoint(t,e){return!!t&&!!e&&t.x===e.x&&t.y===e.y}static atLeastOneDimensionShared(t,e){return!(!t||!e||t.x!==e.x&&t.y!==e.y)}static validPlane(t){return!!t&&!!t.height&&!!t.width}static validLine(t){return!!t&&S.validPoint(t.p1)&&S.validPoint(t.p2)&&!S.samePoint(t.p1,t.p2)}static validLines(t){return!!t&&E.allTrue(t.map((t=>S.validLine(t))))}static validPolyLine(t){return!!t&&t.pts?.length>1&&E.allTrue(t.pts.map((t=>S.validPoint(t))))}static polyLineToLines(t){let e=null;if(S.validPolyLine(t)){e=[];for(let r=1;r<t.pts.length;r++)e.push({p1:t.pts[r-1],p2:t.pts[r]})}return e}static lastPointOnPolyLine(t){return S.validPolyLine(t)?t.pts[t.pts.length-1]:null}static lineToPolyLine(t){return S.validLine(t)?{pts:[t.p1,t.p2]}:null}static linesToPolyLines(t){let e=null;if(S.validLines(t)){e=[];let r=S.lineToPolyLine(t[0]);for(let n=1;n<t.length;n++)S.samePoint(S.lastPointOnPolyLine(r),t[n].p1)?r.pts.push(t[n].p2):(e.push(r),r=S.lineToPolyLine(t[n]));e.push(r)}return e}static validPoint(t){return!!t&&null!=t.x&&null!=t.x&&null!==t.y&&void 0!==t.y}static validPoints(t){return!!t&&E.allTrue(t.map((t=>S.validPoint(t))),!1)}static planeContainsPoint(t,e){return S.validPlane(e)&&S.validPoint(t)&&t.x>=0&&t.x<e.width&&t.y>=0&&t.y<e.height}static planeContainsPoints(t,e){return t&&t.map((t=>S.planeContainsPoint(t,e))).reduce(((t,e)=>t&&e),!0)}static linesToPoints(t){let e=null;return S.validLines(t)&&(e=t.map((t=>[t.p1,t.p2])).flat()),e}static pointsToLines(t){let e=null;if(S.validPoints(t)){if(t.length%2!=0)throw new Error("Cannot convert non-even array of points into lines");e=[];for(let r=0;r<t.length;r+=2)e.push({p1:t[r],p2:t[r+1]})}return e}static rotateRightAboutOrigin90Degrees(t,e=1){let r=null,n={x:0,y:0};if(S.validPoints(t)){r=Object.assign([],t),n=S.translateToOriginVector(r),r=S.translate(r,n);let e=S.minimalContainingPlane(r);r=S.xToY(r),e={width:e.height,height:e.width},n={x:-1*n.y,y:-1*n.x},r=S.mirrorPointsOnPlane(r,e,!0,!1),r=S.translate(r,n)}const s=e>4?e%4:e;return s>1&&(r=S.rotateRightAboutOrigin90Degrees(r,s-1)),r}static planeContainsLines(t,e){return t&&S.planeContainsPoints(t.map((t=>[t.p1,t.p2])).flat(),e)}static planeContainsPolyLine(t,e){return S.planeContainsLines(S.polyLineToLines(t),e)}static planeContainsLine(t,e){return S.validPlane(e)&&S.validLine(t)&&S.planeContainsPoint(t.p1,e)&&S.planeContainsPoint(t.p2,e)}static xToY(t){let e=null;return S.validPoints(t)&&(e=t.map((t=>({x:t.y,y:t.x})))),e}static translate(t,e){let r=null;return S.validPoints(t)&&S.validPoint(e)&&(r=t.map((t=>({x:t.x+e.x,y:t.y+e.y})))),r}static mirrorPointsOnPlane(t,e,r,n){let s=null;return S.validPoints(t)&&S.validPlane(e)&&(s=r||n?t.map((t=>({x:r?e.width-1-t.x:t.x,y:n?e.height-1-t.y:t.y}))):Object.assign([],t)),s}static transformPointsToNewPlane(t,e,r){let n=null;if(S.validPoints(t)&&S.validPlane(e)&&S.validPlane(r)){const s=S.scaleVector(e,r);n=t.map((t=>({x:t.x*s.x,y:t.y*s.y}))),n=S.mirrorPointsOnPlane(n,r,r.rightToLeft!==e.rightToLeft,r.topToBottom!==e.topToBottom)}return n}static transformPointToNewPlane(t,e,r){const n=S.transformPointsToNewPlane([t],e,r);return 1===n.length?n[0]:null}static transformLines(t,e,r){return null}static fitCurve(t,e){if(t.sort(((t,e)=>t.x-e.x)),e<=t[0].x)return t[0].y;if(e>=t[t.length-1].x)return t[t.length-1].y;{let r=0;for(;t[r+1].x<e;)r++;const n=t[r+1].x-t[r].x,s=t[r+1].y-t[r].y,i=(e-t[r].x)/n*s;return t[r].y+i}}}class w{constructor(){}static buildInformation(){return{version:"367",hash:"4af1e13e7622c8aedc5061103c78c68876afe37c",branch:"alpha-2024-06-19-4",tag:"alpha-2024-06-19-4",timeBuiltISO:"2024-06-19T14:05:22-0700",notes:"No notes"}}}class T{entries=[];update(t,e=1){if(t){const r=this.entries.find((e=>e.item===t));r?r.count+=e:this.entries.push({item:t,count:e})}}sort(){this.entries.sort(((t,e)=>{let r=e.count-t.count;return 0===r&&(r=String(e.item).localeCompare(String(t.item))),r}))}sortKeys(){this.entries.sort(((t,e)=>String(e.item).localeCompare(String(t.item))))}reverse(){this.entries.reverse()}getEntries(){return this.entries}getTotalCount(){let t=0;return this.entries.forEach((e=>t+=e.count)),t}countForValue(t){const e=this.entries.find((e=>e.item===t));return e?e.count:0}percentForValue(t){const e=this.getTotalCount();return 0===e?0:this.countForValue(t)/e}}var O;!function(t){t[t.RETURN_NULL=0]="RETURN_NULL",t[t.THROW_EXCEPTION=1]="THROW_EXCEPTION",t[t.ADD_FLAG=2]="ADD_FLAG"}(O||(O={}));class _{static formatMsDuration(t,e=!1){const r=Math.floor(t%1e3),n=Math.floor(t/1e3)%60,s=Math.floor(t/6e4)%60,i=Math.floor(t/36e5)%24,o=Math.floor(t/864e5),a=b.leadingZeros;let l=a(i,2)+"h"+a(s,2)+"m";return l+=e?a(n,2)+"."+a(r,3)+"s":a(n,2)+"s",o>0&&(l=o+"d"+l),l}static colonFormatMsDuration(t,e=!1){const r=t%1e3,n=Math.floor(t/1e3)%60,s=Math.floor(t/6e4)%60,i=Math.floor(t/36e5),o=b.leadingZeros;let a=o(i,2)+":"+o(s,2)+":";return a+=e?o(n,2)+"."+o(r,3):o(n,2),a}static daysBetween(t,e){return r.fromJSDate(t).diff(r.fromJSDate(e)).days}static createSteps(t,e,n,s,i){let o=r.fromMillis(t).setZone(n);const a=r.fromMillis(e),l=[];for(;o<a;)l.push(o.toFormat(s)),o=o.plus(i);return l}}class L{_encryptionKeyPromise;_decryptKeysPromise;_jtiGenerator;_decryptOnlyKeyUseLogLevel;_parseFailureLogLevel;static EXPIRED_FLAG_NAME="__jwtServiceExpiredFlag";constructor(t,e,r=p.createType4Guid,n=o.info,s=o.debug){this._encryptionKeyPromise=t,this._decryptKeysPromise=e,this._jtiGenerator=r,this._decryptOnlyKeyUseLogLevel=n,this._parseFailureLogLevel=s,f.notNullOrUndefined(t,"encryptionKeyPromise")}get encryptionKeyPromise(){return this._encryptionKeyPromise}get decryptKeysPromise(){return this._decryptKeysPromise}get jtiGenerator(){return this._jtiGenerator}get decryptOnlyKeyUseLogLevel(){return this._decryptOnlyKeyUseLogLevel}get parseFailureLogLevel(){return this._parseFailureLogLevel}static hasExpiredFlag(t){return t&&!0===t[L.EXPIRED_FLAG_NAME]}static async invalidSafeDecode(t,r,n=o.silly){let s=null;try{s=e.verify(t,r,{ignoreExpiration:!0})}catch(t){y.logByLevel(n,"Caught %s - ignoring",t)}return s}static async secondsRemainingUntilExpiration(t){let e=null;if(p.trimToNull(t)){const r=await L.decodeTokenNoVerify(t),n=Math.floor(Date.now()/1e3);if(r.exp){const t=r.exp>100*n?Math.floor(r.exp/1e3):r.exp;e=Math.max(0,t-n)}}return e}static async msRemainingUntilExpiration(t){const e=await L.secondsRemainingUntilExpiration(t);let r=null;return null!=e&&(r=1e3*e),r}async decodeToken(t,e=0){const r=await this.encryptionKeyArray();let n=Object.assign([],r);this.decryptKeysPromise&&(n=n.concat(await this.decryptKeysPromise));const s=[];let i=null;for(let e=0;e<n.length&&!i;e++){s.push(p.obscure(n[e],1,1));const a=e===n.length-1&&this.parseFailureLogLevel?this.parseFailureLogLevel:o.silly;i=await L.invalidSafeDecode(t,n[e],a),i&&e>=r.length&&y.logByLevel(this.decryptOnlyKeyUseLogLevel,"Used old key to decode token : %s",p.obscure(n[e],2))}if(i){const t=Math.floor(Date.now()/1e3),r=i?.exp&&i.exp>100*t?Math.floor(i.exp/1e3):i?.exp,n=i?.nbf&&i.nbf>100*t?Math.floor(i.nbf/1e3):i?.nbf;if(r&&t>=r||n&&t<=n){const n=t-r;switch(y.debug("JWT token expired or before NBF : on %d, %s ago",i.exp,_.formatMsDuration(1e3*n)),e){case 1:throw new Error("JWT Token was expired");case 2:i[L.EXPIRED_FLAG_NAME]=!0;break;default:i=null}}}else y.warn("Unable to parse a payload (Tried %j) from : %s",s,t);return i}async encryptionKeyArray(){const t=await this.encryptionKeyPromise,e=Array.isArray(t)?t:[t];if(e.length<1)throw new Error("Cannot create JwtRatchet with empty encryption key set");return e}async selectRandomEncryptionKey(){const t=await this.encryptionKeyArray();return t[Math.floor(Math.random()*t.length)]}async createTokenString(t,r,n){const s=p.trimToNull(n)?p.trimToNull(n):await this.selectRandomEncryptionKey();if(f.notNullOrUndefined(t,"payload"),t.jti=this.jtiGenerator?this.jtiGenerator():null,r){const e=Math.floor(Date.now()/1e3)+r;y.debug("Forcing expiration to %d",e),t.exp=e}return e.sign(t,s)}async refreshJWTString(t,e,r){const n=e?2:1,s=await this.decodeToken(t,n),i=s.exp&&s.iat?s.exp-s.iat:null,o=r||i;L.removeJwtFields(s),L.removeExpiredFlag(s);return await this.createTokenString(s,o)}static decodeTokenNoVerify(t){return e.decode(t)}static removeJwtFields(t){t&&["iss","sub","aud","exp","nbf","iat","jti"].forEach((e=>{delete t[e]}))}static removeExpiredFlag(t){t&&delete t[L.EXPIRED_FLAG_NAME]}}class M{static safeStringifyErr(t,e=!0){let r="ERR WAS NULL";if(t)if(t.message)r=t.message;else try{r=JSON.stringify(t)}catch(e){y.error("Failed to json stringify"),r=String(t)}return e&&y.error("%s",r,t),r}static asErr(t){let e=null;return t&&(e=t instanceof Error?t:new Error("Force-Cast to error : "+String(t))),e}static fErr(e,...r){const n=t.format(e,...r);return new Error(n)}static throwFormattedErr(t,...e){throw M.fErr(t,...e)}}class A{static expandNestedKeysToObjects(t,e="."){if(!e||1!==e.length)throw new Error("Invalid separator (must be single character)");const r={};return Object.keys(t).forEach((n=>{const s=n.split(e);let i=r;for(;s.length>1;)i[s[0]]=i[s[0]]||{},i=i[s[0]],s.splice(0,1);i[s[0]]=t[n]})),r}static mapByUniqueProperty(t,e){if(!t||!e)throw new Error("Neither input nor propName can be null");const r=new Map;return t.forEach((t=>{const n=t?t[e]:null;if(null==n)throw new Error("No value for "+e+" found in "+JSON.stringify(t));if(r.has(n))throw new Error("Multiple values found for "+n);r.set(n,t)})),r}static groupByProperty(t,e){if(!t||!e)throw new Error("Neither input nor propName can be null");const r=new Map;return t.forEach((t=>{const n=t?t[e]:null;if(null==n)throw M.fErr("No value for %s found in %j",e,t);r.has(n)||r.set(n,[]),r.get(n).push(t)})),r}static findValue(t,e){return e&&0!=e.length?t?A.findValue(t[e[0]],e.slice(1)):null:t}static findValueDotPath(t,e){return e&&0!=e.length?t?A.findValue(t,e.split(".")):null:t}static simpleDeepCompare(t,e){return null==t&&null==e||null!=t&&null!=e&&JSON.stringify(t)==JSON.stringify(e)}static toKeyValueList(t){const e=[];for(const r of Object.keys(t))e.push({key:r,value:t[r]});return e}static fromKeyValueList(t){const e={};return t.forEach((t=>e[t.key]=t.value)),e}static cleanup(t,e=!1,r=!0,n=!0,s=!0){if(null==t||"object"!=typeof t)return t;const i=JSON.parse(JSON.stringify(t));return Object.keys(i).forEach((t=>{if(i[t]&&"object"==typeof i[t])if(Array.isArray(i[t]))for(let e=0;e<i[t].length;e++)i[t][e]=A.cleanup(i[t][e]);else i[t]=A.cleanup(i[t]);else void 0===i[t]&&n||null===i[t]&&r||""===i[t]&&s||0===i[t]&&e?delete i[t]:i[t]=i[t]})),i}static extractValueFromMapIgnoreCase(t,e){let r=null;if(t&&e){const n=e.toLowerCase();Object.keys(t).forEach((s=>{if(s.toLowerCase()===n){const n=t[s];r&&y.warn("Multiple entries found for %s (replacing %s with %s",e,r,n),r=n}}))}return r}static safeCallFunction(t,e){let r=!1;if(t&&t[e]&&"function"==typeof t[e])try{t[e](),r=!0}catch(r){y.warn("Error calling %s on %s : %s",e,t,r,r)}return r}static caseInsensitiveAccess(t,e){let r=null;if(t&&e&&(r=t[e],!r)){const n=Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()));n&&(r=t[n])}return r}}class N{static wrapElementsInArray(t){return t.map((t=>[t]))}static compareTwoArrays(t,e,r){t.sort(r),e.sort(r);let n=0,s=0;const i={matching:[],setOneOnly:[],setTwoOnly:[]};for(;n<t.length&&s<e.length;){const o=t[n],a=e[s],l=r(o,a);0===l?(i.matching.push(o),n++,s++):l<0?(i.setOneOnly.push(o),n++):(i.setTwoOnly.push(a),s++)}return n<t.length-1&&(i.setOneOnly=i.setOneOnly.concat(t.slice(n))),s<e.length-1&&(i.setTwoOnly=i.setTwoOnly.concat(e.slice(s))),i}static extractSubarrayFromSortedByNumberField(t,e,r,n){if(!t||0===t.length)return t;let s=null===r?0:N.findSplit(t,e,r)||0;const i=null===n?t.length:N.findSplit(t,e,n),o=A.findValueDotPath(t[s],e);return s===t.length-1&&o<r?[]:(s<t.length&&s<i&&o<r&&s++,t.slice(s,i+1))}static findSplit(t,e,r){if(f.notNullOrUndefined(t),f.notNullOrUndefined(e),f.notNullOrUndefined(r),0===t.length||A.findValueDotPath(t[0],e)>r)return null;let n=0,s=t.length,i=null;for(;null===i;){const o=Math.floor((n+s)/2),a=A.findValueDotPath(t[o],e);n===s||n===s-1?i=n:a<=r?n=o:s=o}return i}}class x{static safeObjectToBase64JSON(t){return t?x.generateBase64VersionOfString(JSON.stringify(t)):null}static safeBase64JSONParse(t){let e={};try{t&&(e=JSON.parse(x.base64StringToString(t,"utf-8")))}catch(r){y.warn("Error parsing b64/json : %s as json, got %s",t,r,r),e={}}return e}static generateBase64VersionOfBlob(t){return new Promise((function(e,r){if(t&&0!=t.size){const r=new FileReader;r.onloadend=function(){e(r.result.toString())},r.readAsDataURL(t)}else r("Wont convert null or non-blob or empty blob")}))}static generateBase64VersionOfString(t){return x.generateBase64VersionOfUint8Array(p.stringToUint8Array(t))}static generateBase64VersionOfUint8Array(t){return x.uint8ArrayToBase64String(t)}static base64StringToUint8Array(t){try{return x.base64StringToBytes(t)}catch(e){throw y.error("Failed to decode base64: %s",t),e}}static base64StringToString(t,e="utf8"){return new TextDecoder(e).decode(x.base64StringToUint8Array(t))}static BASE64_ABC=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"];static BASE64_CODES=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];static getBase64Code(t){if(t>=x.BASE64_CODES.length)throw new Error("Unable to parse base64 string.");const e=x.BASE64_CODES[t];if(255===e)throw new Error("Unable to parse base64 string.");return e}static uint8ArrayToBase64UrlString(t){let e=x.uint8ArrayToBase64String(t);return e=e.split("+").join("-").split("/").join("_").split("=").join(""),e}static uint8ArrayToBase64String(t){let e,r="";const n=t.length;for(e=2;e<n;e+=3)r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4|t[e-1]>>4],r+=x.BASE64_ABC[(15&t[e-1])<<2|t[e]>>6],r+=x.BASE64_ABC[63&t[e]];return e===n+1&&(r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4],r+="=="),e===n&&(r+=x.BASE64_ABC[t[e-2]>>2],r+=x.BASE64_ABC[(3&t[e-2])<<4|t[e-1]>>4],r+=x.BASE64_ABC[(15&t[e-1])<<2],r+="="),r}static base64StringToBytes(t){if(t.length%4!=0)throw M.fErr("Unable to parse base64 string, length: %s",t.length);const e=t.indexOf("=");if(-1!==e&&e<t.length-2)throw M.fErr("Unable to parse base64 string, index %s",e);const r=t.endsWith("==")?2:t.endsWith("=")?1:0,n=t.length,s=new Uint8Array(n/4*3);let i;for(let e=0,r=0;e<n;e+=4,r+=3)i=x.getBase64Code(t.charCodeAt(e))<<18|x.getBase64Code(t.charCodeAt(e+1))<<12|x.getBase64Code(t.charCodeAt(e+2))<<6|x.getBase64Code(t.charCodeAt(e+3)),s[r]=i>>16,s[r+1]=i>>8&255,s[r+2]=255&i;return s.subarray(0,s.length-r)}static base64UrlStringToBytes(t){let e=t.split("-").join("+").split("_").join("/");for(;e.length%4!=0;)e+="=";return y.info("pre: %s post %s",t,e),x.base64StringToBytes(e)}static encodeStringToBase64String(t,e=new TextEncoder){return x.uint8ArrayToBase64String(e.encode(t))}static encodeStringToBase64UrlString(t,e=new TextEncoder){return x.uint8ArrayToBase64UrlString(e.encode(t))}static decodeBase64StringToString(t,e=new TextDecoder){return e.decode(x.base64StringToBytes(t))}static decodeBase64UrlStringToString(t,e=new TextDecoder){return e.decode(x.base64UrlStringToBytes(t))}}class I{sources;mostRecent;constructor(t,e=!0){if(!t||0==t.length)throw Error("Cannot create composite provider with null/empty sources");this.sources=t,this.mostRecent=e}lastSuccess(){let t=null;return this.sources.forEach((e=>{const r=e.lastSuccess();null!=r&&(t=null==t||r>t&&this.mostRecent||r<t&&!this.mostRecent?r:t)})),t}}class v{static COMMON_US_DATE_FORMAT="MM/dd/yyyy";static DEFAULT_DATE_FORMAT="yyyy-MM-dd";static FULL_DATE_FORMAT="yyyy-MM-dd_HH_mm_ss";static PACIFIC_TIME_ZONE="America/Los_Angeles";static UTC_TIME_ZONE="etc/UTC";static formatFullDate(t){return r.fromJSDate(t).toFormat(v.FULL_DATE_FORMAT)}static formatDefaultDateOnly(t){return r.fromJSDate(t).toFormat(v.DEFAULT_DATE_FORMAT)}static parseDefaultDate(t){return r.fromFormat(t,v.DEFAULT_DATE_FORMAT).toJSDate()}static parseCommonUsDate(t){let e=null;if(t){let n=v.COMMON_US_DATE_FORMAT;2===t.indexOf("-")&&(n=n.split("/").join("-")),e=r.fromFormat(t,n).toJSDate()}return e}}class P{static listEnumKeys(t){return n(t).getValues()}static keyToEnum(t,e,r=!1){const s=n(t);let i=null;if(e&&(i=s.asValueOrDefault(e,null),!i&&!r)){const r=P.listEnumKeys(t).find((t=>t.toUpperCase()===e.toUpperCase()));r&&(i=s.asValueOrDefault(r,null))}return i}static parseCsvToEnumArray(t,e){return p.trimToEmpty(e).split(",").map((t=>t.trim())).map((e=>P.keyToEnum(t,e))).filter((t=>!!t))}}class R{static fetchDirName(t){if(!t)throw new Error("Need to provide root (should be import.meta.url)");return s.fileURLToPath(new URL(".",t))}static fetchFileName(t){if(!t)throw new Error("Need to provide root (should be import.meta.url)");return s.fileURLToPath(t)}}class C{_config;_cacheObject;_lastUpdatedEpochMS;_timeRemainingMS;constructor(t){this._config=Object.assign({},this.defaultConfig(),t||{}),this._config.overrideTimeRemainingMS&&this._config.timeToLiveMS&&M.throwFormattedErr("Cannot define both time to live and overrideTimeRemainingMS"),this._config.overrideTimeRemainingMS||this._config.timeToLiveMS||M.throwFormattedErr("Must define exactly one of timeToLiveMS or overrideTimeRemainingMS"),this._config.initialValue&&this.update(this._config.initialValue),this._timeRemainingMS=this._config.overrideTimeRemainingMS||this.defaultTimeRemainingMS}defaultConfig(){return{generator:null,initialValue:null,logLevel:o.debug,overrideTimeRemainingMS:null,timeToLiveMS:6e4}}async defaultTimeRemainingMS(t){let e=0;if(t){const r=(new Date).getTime()-t;e=Math.max(0,this._config.timeToLiveMS-r)}return e}update(t,e=!1){this._cacheObject=t,e||(this._lastUpdatedEpochMS=(new Date).getTime()),y.logByLevel(this._config.logLevel,"Updated cache value to %j",t)}async fetchCacheObjectTimeRemainingMS(){return this._timeRemainingMS(this._lastUpdatedEpochMS)}async fetch(){if(await this._timeRemainingMS(this._lastUpdatedEpochMS)||(this._cacheObject=null,this._lastUpdatedEpochMS=null),!this._cacheObject&&this._config.generator){const t=await this._config.generator();y.logByLevel(this._config.logLevel,"Auto call to generator returned %j",t),this.update(t)}return this._cacheObject}}class B{timeToLiveMS;generator;initialValue;logLevel;overrideTimeRemainingMS}class U{constructor(){}static distanceBetweenLocations(t,e,r,n,s="M"){const i=s?s.toUpperCase():"";if(-1===["M","K","N","F","E"].indexOf(i))throw new Error("Invalid unit");if(t==r&&e==n)return 0;{const s=Math.PI*t/180,o=Math.PI*r/180,a=e-n,l=Math.PI*a/180;let c=Math.sin(s)*Math.sin(o)+Math.cos(s)*Math.cos(o)*Math.cos(l);return c>1&&(c=1),c=Math.acos(c),c=180*c/Math.PI,c=60*c*1.1515,"F"===i&&(c*=5280),"K"===i&&(c*=1.609344),"E"===i&&(c*=1609.344),"N"===i&&(c*=.8684),c}}static distanceBetweenRatchetGeoLocations(t,e,r="M"){return U.distanceBetweenLocations(t.lat,t.lng,e.lat,e.lng,r)}static degreeOfLatLngInMiles(t=0){const e=t*Math.PI/180,r=Math.cos(e);return b.safeNumber((69.172*r).toFixed(4))}static milesInDegLatLng(t,e=0){f.notNullOrUndefined(t),f.true(t>=0);return t/U.degreeOfLatLngInMiles(e)}static centerOfBounds(t){return f.notNullOrUndefined(t),{lat:(t.extent.lat+t.origin.lat)/2,lng:(t.extent.lng+t.origin.lng)/2}}static calculateSplits(t,e,r){f.notNullOrUndefined(t),f.notNullOrUndefined(e),f.notNullOrUndefined(r),t.sort(((t,e)=>t.origin[r]-e.origin[r]));const n=t.map((t=>U.centerOfBounds(t))).map((t=>t[r])),s=[];for(let t=1;t<n.length;t++){const r=n[t]-n[t-1];s.length<e?(s.push({idx:t,size:r}),s.sort(((t,e)=>t.size-e.size))):r>s[0].size?(s[0]={idx:t,size:r},s.sort(((t,e)=>t.size-e.size))):y.silly("Skipping, size : %d, %j",r,s)}return y.info("Splits at : %j",s),s.sort(((t,e)=>t.idx-e.idx)),s}static clusterGeoBounds(t,e=2,r=5){let n=null;if(e*r<2&&M.throwFormattedErr("Cannot set slices to less than 2 : %d x %d",e,r),t){n=[];const s=Object.assign([],t);s.sort(((t,e)=>t.origin.lng-e.origin.lng));const i=U.calculateSplits(t,r-1,"lng");i.sort(((t,e)=>t.idx-e.idx));for(let t=0;t<=i.length;t++){const r=0===t?0:i[t-1].idx,o=t===i.length?s.length:i[t].idx,a=s.slice(r,o);a.sort(((t,e)=>t.origin.lat-e.origin.lat));const l=U.calculateSplits(a,e-1,"lat");for(let t=0;t<=l.length;t++){const e=0==t?0:l[t-1].idx,r=t===l.length?a.length:l[t].idx,s=a.slice(e,r);n.push(U.combineBounds(s))}}y.info("New bounds : %j",n)}return n}static canonicalizeBounds(t,e=!1){f.notNullOrUndefined(t,"RatchetLocationBounds");const r=Math.min(t.extent.lat,t.origin.lat),n=Math.max(t.extent.lat,t.origin.lat),s=Math.min(t.extent.lng,t.origin.lng),i=Math.max(t.extent.lng,t.origin.lng);if(r<0&&n>0||r>0&&n<0||(r<0&&n>0||r>0&&n<0)){if(e)return t;throw new Error("Cannot canonicalize, bounds crosses over boundary")}return{origin:{lat:r,lng:s},extent:{lat:n,lng:i}}}static combineBounds(t){let e=null;return t&&t.length>0&&(e={origin:{lat:t.map((t=>t.origin.lat)).reduce(((t,e)=>Math.min(t,e))),lng:t.map((t=>t.origin.lng)).reduce(((t,e)=>Math.min(t,e)))},extent:{lat:t.map((t=>t.extent.lat)).reduce(((t,e)=>Math.max(t,e))),lng:t.map((t=>t.extent.lng)).reduce(((t,e)=>Math.max(t,e)))}}),e}static roundLocation(t,e){return{lat:b.safeNumber(t.lat.toFixed(e)),lng:b.safeNumber(t.lng.toFixed(e))}}static locationToBounds(t,e){const r=U.milesInDegLatLng(e,t.lat);return{origin:{lat:t.lat-r,lng:t.lng-r},extent:{lat:t.lat+r,lng:t.lng+r}}}static sameLocation(t,e){return!!t&&!!e&&t.lat===e.lat&&t.lng===e.lng}static pointInBounds(t,e){return!!t&&!!e&&b.between(t.lat,e.origin.lat,e.extent.lat)&&b.between(t.lng,e.origin.lng,e.extent.lng)}static pointInAnyBound(t,e,r=10){let n=!1;if(e.length>r){const r=U.buildRatchetLocationBoundsMap(e);n=U.pointInRatchetLocationBoundsMap(t,r)}else for(let r=0;r<e.length&&!n;r++)n=U.pointInBounds(t,e[r]);return n}static pointInRatchetLocationBoundsMap(t,e){let r=!1;const n=U.findRatchetLocationBoundsMapEntry(t,e);if(n){const e=n.bounds;for(let n=0;n<e.length&&!r;n++)r=U.pointInBounds(t,e[n])}return r}static findRatchetLocationBoundsMapEntry(t,e){let r=null;if(t.lat>=e.latOffset&&t.lat<=e.maxLat&&t.lng>=e.lngOffset&&t.lng<=e.maxLng){const n=Math.trunc(t.lat)-e.latOffset,s=Math.trunc(t.lng)-e.lngOffset;r=e.mapping[n][s]}return r}static buildRatchetLocationBoundsMap(t){const e=t.map((t=>t.origin.lat)).reduce(((t,e)=>Math.min(t,e))),r=t.map((t=>t.origin.lng)).reduce(((t,e)=>Math.min(t,e))),n=t.map((t=>t.extent.lat)).reduce(((t,e)=>Math.max(t,e))),s=t.map((t=>t.extent.lng)).reduce(((t,e)=>Math.max(t,e))),i=Math.trunc(e)-1,o=Math.trunc(r)-1,a=Math.trunc(n)-i+1,l=Math.trunc(s)-o+1,c=[];for(let t=0;t<a;t++){const e=[];for(let r=0;r<l;r++)e.push({lat:i+t,lng:o+r,bounds:[]});c.push(e)}return t.forEach((t=>{for(let e=Math.trunc(t.origin.lat);e<=Math.trunc(t.extent.lat);e++){const r=c[e-i];for(let e=Math.trunc(t.origin.lng);e<=Math.trunc(t.extent.lng);e++){r[e-o].bounds.push(t)}}})),{latOffset:i,lngOffset:o,maxLat:i+a,maxLng:o+l,mapping:c}}}class D{constructor(){}static fetchGlobalRecord(t){let e=null;if(process?.env?(y.silly("Using process.env as global"),e=process.env):global?.process?.env?(y.silly("Using global.process.env as global"),e=global.process.env):global&&(y.silly("Using process.env as global"),e=global),!e){if(!t)throw M.fErr("Could not find process.env OR global in scope");y.silly("Returning null as global"),e=null}return e}static fetchGlobalVar(t){f.notNullOrUndefined(t,"envVar");return D.fetchGlobalRecord()[t]}static setGlobalVar(t,e){f.notNullOrUndefined(t,"envVar"),f.notNullOrUndefined(e,"value");D.fetchGlobalRecord()[t]=e}}class F{key;value}class j{static op(...t){}}class V{title;timeoutMS;__timeoutTokenFlagField=!0;constructor(t,e){this.title=t,this.timeoutMS=e,Object.setPrototypeOf(this,V.prototype)}writeToLog(t=o.warn){y.logByLevel(t,"Timed out after %d ms waiting for results of %s",this.timeoutMS,this.title)}static isTimeoutToken(t){return!!t&&!!t.__timeoutTokenFlagField}}class k{get createTime(){return this._createTime}starts=new Map;ends=new Map;_createTime=Date.now();_label=p.createRandomHexString(4);_labelIncludedInOutput=!1;constructor(){}withLabel(t){return this._label=p.trimToNull(t),this}withLabelIncludedInOutput(t){return this._labelIncludedInOutput=t,this}get label(){return this._label}set label(t){this._label=t}get labelIncludedInOutput(){return this._labelIncludedInOutput}set labelIncludedInOutput(t){this._labelIncludedInOutput=t}start(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name");const e=Date.now();return this.starts.set(p.trimToNull(t),e),e}stop(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name");const e=Date.now();return this.ends.set(p.trimToNull(t),e),e}reset(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"name"),this.starts.delete(p.trimToNull(t)),this.ends.delete(p.trimToNull(t))}hasTimer(t){return f.notNullUndefinedOrOnlyWhitespaceString(t,"name"),this.starts.has(t)}log(t,e,r=o.info){y.logByLevel(r,this.dump(t,e))}logExpected(t,e,r,n=o.info){y.logByLevel(n,this.dumpExpected(t,e,r))}timerNames(){return Array.from(this.starts.keys())}dumpAll(t=", ",e){const r=this.timerNames().map((t=>this.dump(t,e)));let n="Overall: "+this.dump(null,e);return r.length>0&&(n+=t,n+=r.join(t)),n}dump(t,e){let r=this._labelIncludedInOutput?this._label+" ":"";const n=p.trimToNull(t);if(n&&!this.hasTimer(n))r+="No such timer : "+n;else{const s=t?this.starts.get(n):this._createTime,i=t?this.ends.get(n):Date.now();r+=(n||"Default")+" ",s&&i?r+="completed in "+_.formatMsDuration(i-s,!e):s&&(r+="running for "+_.formatMsDuration(Date.now()-s,!e))}return r}dumpExpected(t,e,r){let n=this._labelIncludedInOutput?this._label+" ":"";const s=p.trimToNull(e);if(s&&!this.hasTimer(s))n+="No such timer : "+s;else if(!t||t<=0)n+="Cannot generate output for 0 percent complete";else if(t>1)n+="Cannot generate output for percent > 1";else{n+=(s||"Default")+" ";const i=e?this.starts.get(s):this._createTime,o=e?this.ends.get(s):Date.now();if(i&&o)n+="completed in "+_.formatMsDuration(o-i,!r);else if(i){const e=Date.now()-i,s=e/t-e;n+="running for "+_.formatMsDuration(e,!r)+" approx "+_.formatMsDuration(s,!r)+" remaining"}}return n}expectedRemainingMS(t,e){let r=null;if(!t||t<=0);else if(t>1);else{const n=p.trimToNull(e),s=e?this.starts.get(n):this._createTime,i=e?this.ends.get(n):Date.now();if(s&&i)r=i-s;else if(s){const e=Date.now()-s;r=e/t-e}}return r}elapsedMS(t){let e=null;const r=p.trimToNull(t);if(r&&!this.hasTimer(r))e=null;else{const n=t?this.starts.get(r):this._createTime,s=t?this.ends.get(r):Date.now();n&&s?e=s-n:n&&(e=Date.now()-n)}return e}}class G{static resolveOnEvent(t,e,r=[],n=null){return t&&e&&0!==e.length&&t.on||Promise.reject("Cannot continue - missing source object or name, or the object is not an event source"),new Promise(((s,i)=>{e.forEach((e=>{t.on(e,(()=>{s(n)}))})),r&&r.forEach((e=>{t.on(e,(t=>{i(t)}))}))}))}static timeout(t,e,r){return Promise.race([t,G.createTimeoutPromise(e,r)])}static createTimeoutPromise(t,e){return new Promise(((r,n)=>{const s=setTimeout((()=>{clearTimeout(s);const n=new V(t,e);r(n)}),e)}))}static async wait(t){await G.createTimeoutPromise("Wait "+t,t),y.silly("Finished wait of %d ms",t)}static dumpResult(t,e=!1){y.info("Success, result was : \n\n%s\n\n",JSON.stringify(t)),process.exit(0)}static dumpError(t,e=!1){y.warn("Failure, err was : \n\n%s\n\n -- \n\n%s\n\n",JSON.stringify(t),String(t)),console.trace(),process.exit(1)}static logErrorAndReturnNull(t,e=!1){return y.warn("Failure, err was : \n\n%s\n\n -- \n\n%s\n\n",JSON.stringify(t),String(t)),null}static runPromiseAndDump(t){t.then(G.dumpResult).catch(G.dumpError)}static async waitFor(t,e,r,n,s="waitFor",i=0){if(null==e||r<50||n<1||i<0||"function"!=typeof t)return y.warn("%s: Invalid configuration for waitFor - exiting immediately",s),y.warn("ExpectedValue : %s ; interval: %d ; maxCycles: %d ; test : %s",e,r,n,typeof t),!1;let o=null;try{o=t(i)}catch(t){return y.warn("%s: Caught error while waiting, giving up",s),!1}return null===o?(y.debug("%s:CurVal was null - aborting",s),!1):o==e?(y.debug("%s:Found expected value",s),!0):i>n?(y.debug("%s:Exceeded max cycles, giving up",s),!1):(y.debug("%s : value not reached yet, waiting (count = %d of %d)",s,i,n),await G.wait(r),G.waitFor(t,e,r,n,s,i+1))}static async runBoundedParallel(t,e,r,n=1,s=o.debug){const i=new k;let a=[],l=e;y.logByLevel(s,"Processing %d total elements %d at a time",e.length,n);const c=r||this;let u=0;const d=l.length;for(;l.length>0;){const e=l.slice(0,Math.min(l.length,n));l=l.slice(e.length);const r=e.map((e=>t.apply(c,e))),o=await Promise.all(r);u+=r.length,a=a.concat(o);const h=u/d;y.logByLevel(s,"%d elements remain : %s",l.length,i.dumpExpected(h))}return i.log(),a}static async runBoundedParallelSingleParam(t,e,r,n=1,s=o.debug){const i=N.wrapElementsInArray(e);return G.runBoundedParallel(t,i,r,n,s)}static async asyncForEachSerial(t,e){for(let r=0;r<t.length;r++)await e(t[r],r,t)}static async asyncForEachParallel(t,e){const r=[];for(let n=0;n<t.length;n++)r.push(e(t[n],n,t));await Promise.all(r)}constructor(){}}class z{constructor(){}static sortNullToTop(t,e,r){return z.nullSafeSort(t,e,!0,r)}static sortNullToBottom(t,e,r){return z.nullSafeSort(t,e,!1,r)}static nullSafeSort(t,e,r,n){let s;return s=f.isNullOrUndefined(t)&&f.isNullOrUndefined(e)?0:f.isNullOrUndefined(t)?r?-1/0:1/0:f.isNullOrUndefined(e)?r?1/0:-1/0:n(t,e),s}static sortNumericStringsAsNumbers(t,e,r){const n=b.safeNumber(t),s=b.safeNumber(e);return z.nullSafeSort(n,s,r,((t,e)=>t-e))}}class W{timezoneIanaName;static PACIFIC=new W("America/Los_Angeles");constructor(t){if(this.timezoneIanaName=t,!t||0===t.trim().length)throw"Timezone cannot be null or empty"}get ianaName(){return this.timezoneIanaName}currentHour(){return r.local().setZone(this.timezoneIanaName).hour}toEpochSeconds(t){return Math.round(t.toMillis()/1e3)}startOfTodayEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({hour:0,minute:0,second:0,millisecond:0}))}startOfMatchingDayEpochSeconds(t){return this.toEpochSeconds(r.fromMillis(t).set({hour:0,minute:0,second:0,millisecond:0}))}startOfMatchingDayEpochMS(t){return 1e3*this.startOfMatchingDayEpochSeconds(t)}startOfCurrentHourEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({minute:0,second:0,millisecond:0}))}startOfCurrentMinuteEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({second:0,millisecond:0}))}startOfCurrentSecondEpochSeconds(){return this.toEpochSeconds(r.local().setZone(this.timezoneIanaName).set({millisecond:0}))}startOfTodayEpochMS(){return r.local().setZone(this.timezoneIanaName).set({hour:0,minute:0,second:0,millisecond:0}).toMillis()}dailySlotCount(t){return Math.ceil(864e5/t)}currentTimeSlotIdx(t){if(t<1)throw new Error("Cannot process with slot less than one ms wide");const e=this.startOfTodayEpochMS(),r=(new Date).getTime()-e;return Math.floor(r/t)}matchingTimeSlotIdx(t,e){if(e<1)throw new Error("Cannot process with slot less than one ms wide");const r=t-this.startOfMatchingDayEpochMS(t);return Math.floor(r/e)}startOfCurrentSlotEpochMS(t){return this.startOfTodayEpochMS()+this.currentTimeSlotIdx(t)*t}startOfMatchingSlotEpochMS(t,e){return this.startOfMatchingDayEpochMS(t)+this.matchingTimeSlotIdx(t,e)*e}}class K{constructor(){}static mergeArrays(t){let e=null;if(t?.length){let r=0;t.forEach((t=>{r+=t.length})),e=new Uint8Array(r);let n=0;t.forEach((t=>{e.set(t,n),n+=t.length}))}return e}static deepEqual(t,e){let r=!1;if(t&&e&&t.length===e.length){let n=!1;for(let r=0;r<t.length&&!n;r++)n=t[r]!==e[r];r=!n}return r}}class H{constructor(){}static async webReadableStreamToUint8Array(t){const e=[],r=new WritableStream({write:async(t,r)=>("string"==typeof t?e.push(p.stringToUint8Array(t)):e.push(t),null),abort(t){M.throwFormattedErr("StringWebWritableStream failure : %s",t)}},{highWaterMark:3,size:()=>1});return await t.pipeTo(r),K.mergeArrays(e)}static async webReadableStreamToString(t){const e=await H.webReadableStreamToUint8Array(t);return(new TextDecoder).decode(e)}static stringToWebReadableStream(t){return new ReadableStream({start:e=>(t&&e.enqueue(t),e.close(),null)},{highWaterMark:t?t.length:null})}}class J{wrapped;constructor(t,e){if(!t)throw Error("Cannot set level to null/undefined");this.wrapped={lvl:t,timestamp:Date.now(),messageSource:e}}clone(){const t=new J(this.wrapped.lvl,this.wrapped.messageSource);return t.wrapped=Object.assign({},this.wrapped),t}level(t){if(!t)throw Error("Cannot set level to null/undefined");return this.wrapped.lvl=t,this}timestamp(t){if(!t)throw Error("Cannot set timestamp to null/undefined");return this.wrapped.timestamp=t,this}messageSource(t){return this.wrapped.messageSource=t,this}subVars(t){return this.wrapped.subsVars=t||[],this}params(t){return this.wrapped.params=t||{},this}p(t,e){return this.wrapped.params=this.wrapped.params||{},this.wrapped.params[t]=e,this}toMessage(){return Object.assign({},this.wrapped)}}class Z{static EMAIL=new RegExp(".+@.+\\.[a-z]+");constructor(){}static convertResolvedReadyToSendEmailToRaw(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");const e="To: "+t.destinationAddresses.join(", ")+"\n",r=t.bccAddresses&&t.bccAddresses.length>0?"Bcc: "+t.bccAddresses.join(", ")+"\n":"",n=t.fromAddress,s="NextPart",i="AltPart";let o="From: "+n+"\n";return o+=e,o+=r,o+="Subject: "+t.subject+"\n",o+="MIME-Version: 1.0\n",o+='Content-Type: multipart/mixed; boundary="'+s+'"\n',o+="\n\n--"+s+"\n",o+='Content-Type: multipart/alternative; boundary="'+i+'"\n',p.trimToNull(t.htmlMessage)&&(o+="\n\n--"+i+"\n",o+='Content-Type: text/html; charset="UTF-8"\n\n',o+=t.htmlMessage),p.trimToNull(t.txtMessage)&&(o+="\n\n--"+i+"\n",o+="Content-Type: text/plain\n\n",o+=t.txtMessage),o+="\n\n--"+i+"--\n",t.attachments&&t.attachments.forEach((t=>{o+="\n\n--"+s+"\n",o+="Content-Type: "+t.contentType+'; name="'+t.filename+'"\n',o+="Content-Transfer-Encoding: base64\n",o+="Content-Disposition: attachment\n\n",o+=t.base64Data.replace(/([^\0]{76})/g,"$1\n")+"\n\n"})),o+="\n\n--"+s+"--\n",o}static validEmail(t){return null!==t&&Z.EMAIL.test(t)}}class q{config;constructor(t){this.config=t,f.notNullOrUndefined(t,"config"),f.notNullOrUndefined(t.provider,"config.provider")}async fillEmailBody(t,e,r,n=null,s=null,i=null){return f.notNullOrUndefined(r),this.config.templateRenderer||M.throwFormattedErr("Cannot use fill body if template renderer not set"),t.htmlMessage=await this.config.templateRenderer.renderTemplate(r,e,s,i),t.txtMessage=n?await this.config.templateRenderer.renderTemplate(n,e):null,t}async fillEmailBodyAndSend(t,e,r,n=null,s=null,i=null){const o=await this.fillEmailBody(t,e,r,n,s,i);return await this.sendEmail(o)}filterEmailsToValid(t){return(t||[]).filter((t=>{if(this.config.allowedDestinationEmails&&0!=this.config.allowedDestinationEmails.length){return!!this.config.allowedDestinationEmails.find((e=>e.test(t)))}return!0}))}async archiveEmailIfConfigured(t,e){let r=null;if(t&&this.config.provider.archiveEmail&&!t.doNotArchive){y.debug("Archiving outbound email to : %j",t.destinationAddresses);try{r={raw:await this.config.provider.archiveEmail(t,e),error:null,meta:{}}}catch(e){y.warn("Failed to archive email %j : %s",t,e),r={raw:null,error:M.safeStringifyErr(e),meta:{}}}}return r}applyLimitsToBodySizesIfAnyInPlace(t){if(this.config.maxMessageBodySizeInBytes){const e=p.trimToEmpty(t.txtMessage).length+p.trimToEmpty(t.htmlMessage).length;if(e>this.config.maxMessageBodySizeInBytes){if(y.warn("Max message size is %d but size is %d - converting",this.config.maxMessageBodySizeInBytes,e),t.attachments=t.attachments||[],p.trimToNull(t.txtMessage)){const e={filename:"original-txt-body.txt",contentType:"text/plain",base64Data:x.generateBase64VersionOfString(t.txtMessage)};t.attachments.push(e)}if(p.trimToNull(t.htmlMessage)){const e={filename:"original-html-body.html",contentType:"text/html",base64Data:x.generateBase64VersionOfString(t.htmlMessage)};t.attachments.push(e)}t.htmlMessage=null,t.txtMessage="The message was too large and was converted to attachment(s). Please see attached files for content"}}}applyLimitsToAttachmentSizesIfAnyInPlace(t){if(this.config.maxAttachmentSizeInBase64Bytes){const e=[];t.attachments&&t.attachments.forEach((t=>{t.base64Data&&t.base64Data.length<this.config.maxAttachmentSizeInBase64Bytes?e.push(t):(y.warn("Removing too-large attachment : %s : %s : %d",t.filename,t.contentType,t.base64Data.length),e.push({filename:"attachment-removed-notice-"+p.createRandomHexString(4)+".txt",contentType:"text/plain",base64Data:x.generateBase64VersionOfString("Attachment "+t.filename+" of type "+t.contentType+" was removed since it was "+t.base64Data.length+" bytes but max allowed is "+this.config.maxAttachmentSizeInBase64Bytes)}))})),t.attachments=e}}async sendEmail(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");let e=null;const r=await this.resolveReadyToSendEmail(t);try{const n=await this.config.provider.sendEmail(r);e={request:t,resolved:r,success:!0,rawResult:n,error:null,meta:{},archiveResults:await this.archiveEmailIfConfigured(r,n)}}catch(n){e={request:t,resolved:r,success:!1,rawResult:null,error:M.safeStringifyErr(n),meta:{},archiveResults:null}}return e}async resolveReadyToSendEmail(t){f.notNullOrUndefined(t,"RTS must be defined"),f.notNullOrUndefined(t.destinationAddresses,"Destination addresses must be defined");let e=this.filterEmailsToValid(t.destinationAddresses);const r=t.doNotAutoBcc?[]:this.config.autoBccAddresses||[],n=(t.bccAddresses||[]).concat(r);0===e.length&&n.length>0&&(y.debug("Destination emails filtered to none but BCC defined, copying BCC"),e=n);const s=Object.assign({},t);return s.srcDestinationAddresses=t.destinationAddresses,s.srcBccAddresses=t.bccAddresses,s.destinationAddresses=e,s.bccAddresses=n,this.applyLimitsToBodySizesIfAnyInPlace(s),this.applyLimitsToAttachmentSizesIfAnyInPlace(s),0===s.destinationAddresses.length&&y.info("After cleaning email lists, no destination addresses left - not sending email"),s.fromAddress=s.fromAddress||this.config.defaultSendingAddress,s}}class Y{failEmails;constructor(t=[]){this.failEmails=t}async sendEmail(t){return y.info("Called send email : %j",t),this.failEmails&&this.failEmails.forEach((e=>{if(t?.destinationAddresses?.includes(e))throw M.fErr("Forced-fail email address: %s",e)})),"OK"}async archiveEmail(t){return y.info("Called archive email : %j",t),this.failEmails&&this.failEmails.forEach((e=>{if(t?.destinationAddresses?.includes(e))throw M.fErr("Forced-fail email address: %s",e)})),"OK"}}class X{static LOCAL_IP=null;static findLocalIp(t=!0){return y.info("Attempting to find local IP (V 2)"),X.LOCAL_IP&&t?Promise.resolve(X.LOCAL_IP):"undefined"!=typeof window?new Promise((function(t,e){try{const e=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;if(e){const r=new e({iceServers:[]}),n=Object.create(null);n["0.0.0.0"]=!1,r.createDataChannel("",{reliable:!1}),r.onicecandidate=function(e){e.candidate&&X.grepSDP("a="+e.candidate.candidate,n,t)},r.createOffer((function(e){X.grepSDP(e.sdp,n,t),r.setLocalDescription(e)}),(function(e){y.warn("Offer failed : %s",e),t(X.updateLocalIP("FIND_UNSUPPORTED"))}))}else y.warn("IP Address find not supported on this device"),t(X.updateLocalIP("FIND_UNSUPPORTED"))}catch(e){y.warn("Error finding local ip address : %s",e),t(X.updateLocalIP("ERROR"))}})):(y.warn("Window not found, cannot calculate local ip"),Promise.resolve(X.updateLocalIP("NO_WINDOW")))}static parseUrl(t){const e=t.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);return e&&{href:t,protocol:e[1],host:e[2],hostname:e[3],port:e[4],pathname:e[5],search:e[6],hash:e[7]}}static updateLocalIP(t){return X.LOCAL_IP=t,X.LOCAL_IP}static grepSDP(t,e,r){t.split("\r\n").forEach((function(t){if(~t.indexOf("a=candidate")){const n=t.split(" "),s=n[4];"host"===n[7]&&X.updateAddressList(s,e,r)}else if(~t.indexOf("c=")){const n=t.split(" ")[2];X.updateAddressList(n,e,r)}}))}static updateAddressList(t,e,r){if(t in e)return;e[t]=!0;const n=Object.keys(e).filter((function(t){return e[t]}));if(n&&1==n.length)r(X.updateLocalIP(n[0]));else{const t=n.sort().join(",");y.warn("Multiple addresses found, returning sorted join : %s",t),r(X.updateLocalIP(t))}}}class ${currentIp="UNSET";constructor(){X.findLocalIp(!1).then((t=>{y.info("Setting local IP to %s",t),this.currentIp=t})).catch((t=>{y.warn("Unable to set current IP - leaving as UNSET : %s",t)}))}ready(){return"UNSET"!==this.currentIp}currentLocalIpAddress(){return this.currentIp}}class Q{fixed;constructor(t){this.fixed=t}currentLocalIpAddress(){return this.fixed}}class tt extends Error{static RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY="__ratchetRestfulApiHttpErrorFlag";_httpStatusCode=500;_errors;_detailErrorCode;_endUserErrors;_details;_requestId;_wrappedError;constructor(...t){super(tt.combineErrorStringsWithDefault(t)),Object.setPrototypeOf(this,tt.prototype),this._errors=t,this[tt.RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY]=!0}static combineErrorStringsWithDefault(t,e="Internal Server Error"){return t&&t.length>0?t.join(","):e}setFormattedErrorMessage(e,...r){const n=t.format(e,...r);this.errors=[n]}withFormattedErrorMessage(t,...e){return this.setFormattedErrorMessage(t,...e),this}withHttpStatusCode(t){return this.httpStatusCode=t,this}withErrors(t){return this.errors=t,this}withDetailErrorCode(t){return this._detailErrorCode=t,this}withEndUserErrors(t){return this._endUserErrors=t,this}withDetails(t){return this._details=t,this}withRequestId(t){return this._requestId=t,this}withWrappedError(t){return this._wrappedError=t,this}isWrappedError(){return!!this._wrappedError}static wrapError(t){let e=null;return e=tt.objectIsRestfulApiHttpError(t)?t:new tt(t.message).withWrappedError(t).withHttpStatusCode(500),e}static objectIsRestfulApiHttpError(t){return t&&!0===t[tt.RATCHET_RESTFUL_API_HTTP_ERROR_FLAG_KEY]}get httpStatusCode(){return this._httpStatusCode}get errors(){return this._errors}get detailErrorCode(){return this._detailErrorCode}get endUserErrors(){return this._endUserErrors}get details(){return this._details}get requestId(){return this._requestId}get wrappedError(){return this._wrappedError}set httpStatusCode(t){this._httpStatusCode=t||500}set errors(t){this._errors=t||["Internal Server Error"],this.message=tt.combineErrorStringsWithDefault(this._errors)}set detailErrorCode(t){this._detailErrorCode=t}set endUserErrors(t){this._endUserErrors=t}set details(t){this._details=t}set requestId(t){this._requestId=t||"MISSING"}set wrappedError(t){this._wrappedError=t}static errorIsX0x(t,e){let r=!1;if(t&&tt.objectIsRestfulApiHttpError(t)){const n=t,s=b.safeNumber(n.httpStatusCode),i=100*e;r=s>=i&&s<=i+99}return r}static errorIs40x(t){return tt.errorIsX0x(t,4)}static errorIs50x(t){return tt.errorIsX0x(t,5)}}class et{static GOOGLE_VERIFY_URL="https://www.google.com/recaptcha/api/siteverify?secret={{KEY}}&response={{TOKEN}}";static async verifyRecaptchaToken(t,e,r=i){y.debug("Verifying recaptcha token : %s",e);let n=null;if(!p.safeString(e))return y.warn("Recaptcha validation error, no token passed : %s",e),n;y.info("Validating Recaptcha via Google API : %s",e);let s=et.GOOGLE_VERIFY_URL;s=s.split("{{KEY}}").join(t),s=s.split("{{TOKEN}}").join(e);try{const t=await r(s),e=await t.json();n=e&&e.success}catch(t){y.error("Failed to read from google : %s",t),n=!1}return n}}class rt{accountSid;authToken;outBoundNumber;static TWILLIO_BASE_API_URL="https://api.twilio.com/2010-04-01";constructor(t,e,r){this.accountSid=t,this.authToken=e,this.outBoundNumber=r,f.notNullOrUndefined(t,"accountSid"),f.notNullOrUndefined(e,"authToken"),f.notNullOrUndefined(r,"outBoundNumber"),f.true(rt.isValidE164Number(r),"outBoundNumber invalid format")}static async sendMessageDirect(t,e,r,n,s){const i=new rt(t,e,r);return await i.sendMessage(n,s)}static generateTwilioBasicAuth(t,e){return"Basic "+x.generateBase64VersionOfString(t+":"+e)}async sendMessage(t,e){const r=[];if(f.notNullOrUndefined(t,"recipientPhoneNumbers"),f.notNullOrUndefined(p.trimToNull(e),"message"),f.true(t.length>0,"recipientPhoneNumbers non-empty"),t&&t.length>0&&p.trimToNull(e)){y.info("Sending %s to %j",e,t);for(let n=0;n<t.length;n++){const s=t[n];if(y.info("To: %s",s),!rt.isValidE164Number(s))throw new Error("number must be E164 format!");const o="Body="+encodeURIComponent(e)+"&From="+encodeURIComponent(this.outBoundNumber)+"&To="+encodeURIComponent(s),a={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:o},l=await i(rt.TWILLIO_BASE_API_URL+"/Accounts/"+this.accountSid+"/Messages.json",a),c=await l.json();y.debug("TwilioRatchet: For %s got %j",s,c),r.push(c)}}else y.warn("Not sending empty message / empty recipients");return r}static isValidE164Number(t){return/^\+?[1-9]\d{1,14}$/.test(t)}}class nt{accountSid;authToken;serviceSid;static TWILLIO_BASE_VERIFY_URL="https://verify.twilio.com/v2/Services/";constructor(t,e,r){this.accountSid=t,this.authToken=e,this.serviceSid=r,f.notNullUndefinedOrOnlyWhitespaceString(t,"accountSid"),f.notNullUndefinedOrOnlyWhitespaceString(e,"authToken"),f.notNullUndefinedOrOnlyWhitespaceString(r,"serviceSid")}async sendVerificationTokenUsingTwilioVerify(t){f.notNullUndefinedOrOnlyWhitespaceString(t,"recipientPhoneNumber"),f.true(rt.isValidE164Number(t),"recipientPhoneNumber must be E164");const e=t.startsWith("+1")?t:"+1"+t,r="Channel=sms&To="+encodeURIComponent(e),n={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:r},s=nt.TWILLIO_BASE_VERIFY_URL+this.serviceSid+"/Verifications",o=await i(s,n);return await o.text()}async simpleCheckVerificationTokenUsingTwilioVerify(t,e){const r=await this.checkVerificationTokenUsingTwilioVerify(t,e);return r&&"approved"===r.status}async checkVerificationTokenUsingTwilioVerify(t,e){f.notNullUndefinedOrOnlyWhitespaceString(t,"recipientPhoneNumber"),f.true(rt.isValidE164Number(t),"recipientPhoneNumber must be E164");const r=t.startsWith("+1")?t:"+1"+t,n="To="+encodeURIComponent(r)+"&Code="+encodeURIComponent(e),s={method:"post",headers:{authorization:rt.generateTwilioBasicAuth(this.accountSid,this.authToken),"Content-Type":"application/x-www-form-urlencoded"},body:n},o=nt.TWILLIO_BASE_VERIFY_URL+this.serviceSid+"/VerificationCheck";y.info("Using %s / %j",o,s);const a=await i(o,s);return await a.json()}}class st{static keysOnly(t){return{transform:(e,r,n)=>r?t.transform(e,r,n):e}}static valuesOnly(t){return{transform:(e,r,n)=>r?e:t.transform(e,r,n)}}static stringReplaceTransform(t,e){return{transform:(r,n,s)=>r==t?e:r}}static stripStringTransform(t){return{transform:(e,r,n)=>e==t?null:e}}static retainAll(t){return{transform:(e,r,n)=>-1==t.indexOf(e)?null:e}}static removeAll(t){return{transform:(e,r,n)=>t.indexOf(e)>-1?null:e}}static snakeToCamelCase(){return{transform(t,e,r){let n=t;return"string"==typeof t&&(n=t.replace(/_([a-z0-9])/gi,(function(t,e){return e.toUpperCase()}))),n}}}static stringToNumber(){return{transform(t,e,r){let n=t;if("string"==typeof t){const e=b.safeNumber(t);null!==e&&(n=e)}return n}}}static camelToSnakeCase(){return{transform(t,e,r){let n=t;return"string"==typeof t&&(n=t.replace(/\.?([A-Z]+)/g,(function(t,e){return"_"+e.toLowerCase()})).replace(/^_/,"")),n}}}static concatenateToNewField(t,e,r=!0){return{transform(n,s,i){if("object"==typeof n){let s="";e.forEach((t=>{if(null!=s){const e=n[t];s=null==e&&r?null:null==e?s:s+String(e)}})),null!=s&&(n[t]=s,e.forEach((t=>delete n[t])))}return n}}}static numberToBool(t){return{transform:(e,r,n)=>("object"==typeof e&&t.forEach((t=>{const r=e[t];if("number"==typeof r){const n=0!=r;e[t]=n}})),e)}}static boolToNumber(t){return{transform:(e,r,n)=>("object"==typeof e&&t.forEach((t=>{const r=e[t];if("boolean"==typeof r){const n=r?1:0;e[t]=n}})),e)}}static makeDuplicateField(t,e){return{transform(r,n,s){if("object"==typeof r){const n=r[t];null!=n&&(r[e]=n)}return r}}}static addField(t,e){return{transform:(r,n,s)=>("object"==typeof r&&(r[t]=e),r)}}static reformatDateFields(t,e,n){return{transform:(s,i,o)=>("object"==typeof s&&t.forEach((t=>{const i=s[t];if(null!=i)try{const o=r.fromFormat(i,e).toFormat(n);s[t]=o}catch(t){y.warn("Failed to reparse date %s in format %s : %s",i,e,t)}})),s)}}}class it{static transform(t,e=[]){return it.transformGeneric(t,e,!1,null)}static transformGeneric(t,e=[],r,n){let s=null;const i=typeof t;switch(i){case"undefined":case"symbol":case"function":s=t;break;case"number":case"string":case"boolean":s=it.applyTransformToPrimitive(t,e,r,n);break;case"object":s=it.applyTransformToObject(t,e,r,n);break;default:throw new Error("Unrecognized type "+i)}return s}static applyTransformToObject(t,e=[],r,n=null){y.silly("Tranform: %j, %s, %j",t,r,n);let s=null;return null!=t&&(Array.isArray(t)?(s=[],t.forEach((n=>{const i=it.transformGeneric(n,e,r,t);null!=i&&s.push(i)}))):(s={},Object.keys(t).forEach((r=>{const n=t[r],i=it.applyTransformToPrimitive(r,e,!0,t);if(null!=i){let r=it.transformGeneric(n,e,!1,t);r=it.applyTransformToPrimitive(r,e,!1,t),null!=r&&(s[i]=r)}})),s=it.applyTransformToPrimitive(s,e,!1,t))),s}static applyTransformToPrimitive(t,e=[],r,n){let s=t;return e.forEach((t=>{s=null==s?null:t.transform(s,r,n)})),s}}const ot={Success:"Success",RolledBack:"RolledBack",RollbackFailed:"RollbackFailed"};class at{static async execute(t,e,r){f.notNullOrUndefined(t,"steps"),f.notNullOrUndefined(e,"initialContext"),f.true(t.length>0,"steps may not be empty");const n=Object.assign({},r||{});n.stepLogLevel=n.stepLogLevel||o.info;const s={finalContext:e,finalState:null},i=t.map(((t,e)=>t.name||"Step "+e));y.info("Beginning transaction of %d steps",t.length);let a=0;do{y.logByLevel(n.stepLogLevel,"Processing step %d of %d (%s)",a+1,t.length,i[a]);try{await t[a].execute(s.finalContext,a),a++}catch(t){y.error("Failure detected on step %d : %s : %s : Rolling back",a,i[a],t,t),s.error=t,s.errorStep=a}}while(!s.error&&a<t.length);if(s.error)do{y.logByLevel(n.stepLogLevel,"Rolling back step %d of %d (%s)",a+1,t.length,i[a]);try{t[a].rollback?await t[a].rollback(s.finalContext,a):y.info("Skipping - no rollback defined")}catch(t){y.error("Very bad - rollback code failed on step %d : %s : Aborting in invalid state: %s",a,i[a],t,t),s.rollbackError=t,s.rollbackErrorStep=a}a--}while(a>=0);if(s.finalState=s.rollbackError?ot.RollbackFailed:s.error?ot.RolledBack:ot.Success,y.info("Transaction completed with status : %s",s.finalState),n?.executeAfterRollback&&s.finalState!==ot.Success)try{y.info("Applying executeAfterRollback"),await n.executeAfterRollback(s)}catch(t){y.error("Very bad - failure in executeAfterRollback : %s",t,t)}if(n?.executeAfterRollbackFailure&&s.finalState!==ot.Success)try{y.info("Applying executeAfterRollbackFailure"),await n.executeAfterRollbackFailure(s)}catch(t){y.error("Very bad - failure in executeAfterRollbackFailure : %s",t,t)}return s}}export{N as ArrayRatchet,x as Base64Ratchet,E as BooleanRatchet,$ as BrowserLocalIpProvider,st as BuiltInTransforms,d as ClassicSingleLineLogMessageFormatter,I as CompositeLastSuccessProvider,v as DateRatchet,_ as DurationRatchet,P as EnumRatchet,M as ErrorRatchet,R as EsmRatchet,O as ExpiredJwtHandling,C as ExpiringObject,B as ExpiringObjectConfig,Q as FixedLocalIpProvider,U as GeolocationRatchet,D as GlobalRatchet,et as GoogleRecaptchaRatchet,T as Histogram,L as JwtRatchet,F as KeyValue,J as LogMessageBuilder,u as LogMessageFormatType,y as Logger,m as LoggerInstance,o as LoggerLevelName,l as LoggerOutputFunction,a as LoggerRingBuffer,c as LoggerUtil,q as Mailer,Z as MailerUtil,A as MapRatchet,X as NetworkRatchet,j as No,h as NoneLogMessageFormatter,b as NumberRatchet,G as PromiseRatchet,S as Ratchet2d,w as RatchetInfo,f as RequireRatchet,tt as RestfulApiHttpError,z as SortRatchet,k as StopWatch,p as StringRatchet,g as StructuredJsonLogMessageFormatter,Y as TestMailSendingProvider,W as TimeZoneRatchet,V as TimeoutToken,ot as TransactionFinalState,at as TransactionRatchet,it as TransformRatchet,rt as TwilioRatchet,nt as TwilioVerifyRatchet,K as Uint8ArrayRatchet,H as WebStreamRatchet};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|