{"version":3,"file":"index.cjs","sources":["../../../node_modules/.pnpm/react@16.14.0/node_modules/react/cjs/react-jsx-runtime.production.min.js","../../../node_modules/.pnpm/react@16.14.0/node_modules/react/cjs/react-jsx-runtime.development.js","../../../node_modules/.pnpm/react@16.14.0/node_modules/react/jsx-runtime.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_freeGlobal.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_root.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Symbol.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getRawTag.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_objectToString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetTag.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObjectLike.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isSymbol.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseToString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSlice.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_castSlice.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hasUnicode.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_asciiToArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_unicodeToArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stringToArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createCaseFirst.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/upperFirst.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/capitalize.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayReduce.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_basePropertyOf.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_deburrLetter.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/deburr.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_asciiWords.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hasUnicodeWord.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_unicodeWords.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/words.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createCompounder.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/camelCase.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseCreate.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseLodash.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_LazyWrapper.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_LodashWrapper.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_copyArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_wrapperClone.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/wrapperLodash.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/eq.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFunction.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isLength.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArrayLike.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isIndex.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isIterateeCall.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_trimmedEndIndex.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseTrim.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toNumber.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toFinite.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toInteger.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/chunk.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheClear.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_assocIndexOf.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheDelete.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_ListCache.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackClear.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackDelete.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_coreJsData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isMasked.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_toSource.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsNative.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getValue.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getNative.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Map.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeCreate.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashClear.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashDelete.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Hash.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheClear.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isKeyable.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getMapData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheDelete.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_MapCache.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Stack.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayEach.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_defineProperty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseAssignValue.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_assignValue.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_copyObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseTimes.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsArguments.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArguments.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubFalse.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isBuffer.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsTypedArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseUnary.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nodeUtil.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isTypedArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayLikeKeys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isPrototype.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_overArg.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeKeys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseKeys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/keys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseAssign.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeKeysIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseKeysIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/keysIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseAssignIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneBuffer.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayFilter.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getSymbols.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_copySymbols.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayPush.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getPrototype.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getSymbolsIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_copySymbolsIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetAllKeys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getAllKeys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getAllKeysIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_DataView.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Promise.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Set.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_WeakMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getTag.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_initCloneArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Uint8Array.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneArrayBuffer.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneDataView.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneRegExp.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneSymbol.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cloneTypedArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_initCloneByTag.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_initCloneObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseClone.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/clone.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/cloneDeep.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/compact.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isFlattenable.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseFlatten.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/concat.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/identity.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_metaMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSetData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createCtor.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createBind.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_apply.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_composeArgs.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_composeArgsRight.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_countHolders.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/noop.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_realNames.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getFuncName.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isLaziable.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_shortOut.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getWrapDetails.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_insertWrapDetails.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/constant.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSetToString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setToString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseFindIndex.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsNaN.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_strictIndexOf.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIndexOf.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayIncludes.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_updateWrapDetails.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setWrapToString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createRecurry.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getHolder.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_reorder.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_replaceHolders.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createHybrid.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createCurry.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createPartial.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mergeData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createWrap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/curry.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/now.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/debounce.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/escapeRegExp.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createBaseFor.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseFor.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseForOwn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createBaseEach.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseEach.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheAdd.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_SetCache.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arraySome.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cacheHas.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalArrays.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapToArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setToArray.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalByTag.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalObjects.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqualDeep.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqual.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsMatch.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isStrictComparable.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getMatchData.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_matchesStrictComparable.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseMatches.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isKey.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/memoize.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_memoizeCapped.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stringToPath.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_castPath.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_toKey.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/get.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseHasIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hasPath.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/hasIn.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseMatchesProperty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseProperty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_basePropertyDeep.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/property.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIteratee.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseFilter.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/filter.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createFind.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/findIndex.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/find.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/flatten.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayAggregator.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseAggregator.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createAggregator.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/groupBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayIncludesWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIntersection.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_overRest.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseRest.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArrayLikeObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_castArrayLikeObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/intersection.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/last.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/intersectionWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEmpty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEqual.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isUndefined.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/keyBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/map.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/mapValues.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_assignMergeValue.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_safeGet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toPlainObject.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseMergeDeep.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseMerge.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createAssigner.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/merge.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/mergeWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/negate.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_basePickBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/pickBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/omitBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSortBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_compareAscending.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_compareMultiple.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseOrderBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/orderBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/partition.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createRound.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/round.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/snakeCase.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSome.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/some.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/sortBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/startCase.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseSum.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/sum.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createSet.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseUniq.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/uniq.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/uniqBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/uniqWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseValues.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/values.js","../src/components/content/CCDA/ccda-viewer/helpers/displayForAddress.ts","../src/components/content/CCDA/ccda-viewer/helpers/displayForName.ts","../src/components/content/CCDA/ccda-viewer/helpers/displayForTelecom.ts","../src/components/content/CCDA/ccda-viewer/helpers/getAddress.ts","../src/components/content/CCDA/ccda-viewer/helpers/getTelecom.ts","../src/components/content/CCDA/ccda-viewer/helpers/getContactDetails.ts","../src/components/content/CCDA/ccda-viewer/helpers/getHumanName.ts","../src/components/content/CCDA/ccda-viewer/helpers/getId.ts","../src/components/content/CCDA/ccda-viewer/helpers/parseToISOString.ts","../src/components/content/CCDA/ccda-viewer/helpers/getPeriod.ts","../src/components/content/CCDA/ccda-viewer/helpers/fixHtml.ts","../src/components/content/CCDA/ccda-viewer/helpers/formatDate.ts","../src/components/content/CCDA/ccda-viewer/types/GeneralInfo.ts","../src/components/content/CCDA/ccda-viewer/components/Authenticator/data.ts","../src/components/content/CCDA/ccda-viewer/components/Table/BasicRow.tsx","../src/components/content/CCDA/ccda-viewer/components/Table/TupleRow.tsx","../src/components/content/CCDA/ccda-viewer/components/Table/Table.tsx","../src/components/content/CCDA/ccda-viewer/components/Authenticator/Authenticator.tsx","../src/components/content/CCDA/ccda-viewer/components/Header/data/getAuthor.ts","../src/components/content/CCDA/ccda-viewer/components/Author/data.ts","../src/components/content/CCDA/ccda-viewer/components/Author/Author.tsx","../src/components/content/CCDA/ccda-viewer/components/Header/data/getConsent.ts","../src/components/content/CCDA/ccda-viewer/components/Authorization/data.ts","../src/components/content/CCDA/ccda-viewer/components/Authorization/Authorization.tsx","../src/components/content/CCDA/ccda-viewer/components/Custodian/data.ts","../src/components/content/CCDA/ccda-viewer/components/Custodian/Custodian.tsx","../src/components/content/CCDA/ccda-viewer/components/DataEnterer/data.ts","../src/components/content/CCDA/ccda-viewer/components/DataEnterer/DataEnterer.tsx","../src/components/content/CCDA/ccda-viewer/components/Document/data.ts","../src/components/content/CCDA/ccda-viewer/components/Document/Document.tsx","../src/components/content/CCDA/ccda-viewer/components/Header/data/getDocumentationOf.ts","../src/components/content/CCDA/ccda-viewer/components/DocumentationOf/data.ts","../src/components/content/CCDA/ccda-viewer/components/DocumentationOf/DocumentationOf.tsx","../src/components/content/CCDA/ccda-viewer/components/Header/data/getEncounter.ts","../src/components/content/CCDA/ccda-viewer/components/Encounter/data.ts","../src/components/content/CCDA/ccda-viewer/components/Encounter/Encounter.tsx","../src/components/content/CCDA/ccda-viewer/components/Informant/data.ts","../src/components/content/CCDA/ccda-viewer/components/Informant/Informant.tsx","../src/components/content/CCDA/ccda-viewer/components/InformationRecipient/data.ts","../src/components/content/CCDA/ccda-viewer/components/InformationRecipient/InformationRecipient.tsx","../src/components/content/CCDA/ccda-viewer/components/Header/data/getInFulfillmentOf.ts","../src/components/content/CCDA/ccda-viewer/components/InFulfillmentOf/data.ts","../src/components/content/CCDA/ccda-viewer/components/InFulfillmentOf/InFulfillmentOf.tsx","../src/components/content/CCDA/ccda-viewer/components/LegalAuthenticator/data.ts","../src/components/content/CCDA/ccda-viewer/components/LegalAuthenticator/LegalAuthenticator.tsx","../src/components/content/CCDA/ccda-viewer/components/Participant/data.ts","../src/components/content/CCDA/ccda-viewer/components/Participant/Participant.tsx","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getBirthPlace.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getEthnicity.ts","../src/components/content/CCDA/ccda-viewer/components/Header/data/getGuardian.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getGuardian.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getLanguage.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getMaritalStatus.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getProviderOrganization.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getRace.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/getReligion.ts","../src/components/content/CCDA/ccda-viewer/components/Header/data/getPatient.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/data/index.ts","../src/components/content/CCDA/ccda-viewer/components/Patient/Patient.tsx","../src/components/content/CCDA/ccda-viewer/components/DocumentDetails.tsx","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/outline/esm/SearchIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/outline/esm/ThumbDownIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/outline/esm/ThumbUpIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/outline/esm/XIcon.js","../src/components/content/CCDA/constants.ts","../src/components/content/CCDA/ccda-viewer/helpers/navigate-into-view.tsx","../src/assets/zus-logo.svg","../src/hooks/use-isomorphic-layout-effect.ts","../src/styles/tailwind.theme.ts","../src/components/core/providers/theme/context.ts","../src/components/core/providers/theme/use-theme.ts","../src/hooks/use-breakpoints.ts","../src/hooks/use-header-offset.ts","../src/components/content/CCDA/ccda-viewer/components/Header/Header.tsx","../src/components/core/providers/analytics/context.ts","../src/components/core/providers/drawer-context.ts","../src/components/core/providers/drawer-provider.tsx","../src/components/core/providers/modal-context.ts","../src/components/core/providers/modal-provider.tsx","../src/components/core/providers/patient-context.tsx","../src/components/core/providers/authentication/context.ts","../src/components/core/providers/authentication/use-get-auth-token.tsx","../src/components/core/providers/ctw-context.tsx","../src/api/urls.ts","../src/utils/error.ts","../src/utils/react-query-error.ts","../src/utils/session.ts","../src/fhir/operation-outcome.ts","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/_mapping.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/placeholder.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/_baseConvert.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/ary.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isError.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isWeakMap.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/iteratee.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_flatRest.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/rearg.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toPath.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/_util.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/convert.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/_falseOptions.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/capitalize.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/chunk.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/cloneDeep.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/compact.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/concat.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/filter.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/find.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/get.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/groupBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/intersectionWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/isEqual.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/isFunction.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/keys.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/last.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/map.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/mapValues.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_parent.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseUnset.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_customOmitClone.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/omit.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/omit.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/orderBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/partition.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_basePick.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/pick.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/pick.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_createFlow.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/flow.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/flow.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/pipe.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/matchesProperty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/matchesProperty.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/propEq.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/set.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/set.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/sortBy.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsRegExp.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isRegExp.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/split.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/split.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/toLower.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/toLower.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/uniq.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/uniqWith.js","../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/fp/values.js","../src/fhir/formatters.ts","../src/fhir/system-urls.ts","../src/fhir/types.ts","../src/fhir/models/fhir-model.ts","../src/fhir/codeable-concept.ts","../src/fhir/models/operation-outcome-issue.ts","../src/fhir/models/operation-outcome.ts","../src/fhir/errors.ts","../src/components/core/toast.tsx","../src/utils/auth.ts","../src/utils/telemetry.ts","../src/utils/request.ts","../src/fhir/client.ts","../src/services/fqs/graphql-to-fhir.ts","../src/utils/types.ts","../src/services/fqs/client.ts","../src/components/core/providers/use-ctw.ts","../src/fhir/practitioner.ts","../src/utils/query-keys.ts","../src/services/fqs/queries/provenances.ts","../src/fhir/provenance.ts","../src/utils/sleep.ts","../src/services/fqs/long-poll-fqs.ts","../src/fhir/action-helper.ts","../src/fhir/models/organization.ts","../src/fhir/resource-helper.ts","../src/fhir/models/patient.ts","../src/fhir/display-onset.ts","../src/fhir/models/allergies.ts","../src/fhir/models/practitioner.ts","../src/fhir/mappings/ccs-chapter-names.ts","../src/components/content/forms/actions/conditions.ts","../src/fhir/models/condition.ts","../src/fhir/models/document.ts","../src/fhir/models/observation.ts","../src/fhir/models/diagnostic-report.ts","../src/fhir/medication.ts","../src/fhir/models/medication-dispense.ts","../src/fhir/models/medication-administration.ts","../src/fhir/models/medication-request.ts","../src/fhir/models/medication-statement.ts","../src/fhir/models/medication.ts","../src/components/content/document/helpers/empty-notes.ts","../src/components/content/resource/filters.ts","../src/components/content/resource/helpers/filters.ts","../src/components/content/document/helpers/filters.ts","../src/fhir/mappings/null-flavor.ts","../src/fhir/models/encounter.ts","../src/fhir/models/episode-of-care.ts","../src/components/content/forms/actions/patients.ts","../src/components/core/providers/telemetry/context.ts","../src/components/core/providers/telemetry/use-telemetry.ts","../src/components/core/providers/use-query-with-ctw.ts","../src/fhir/bundle.ts","../src/fhir/search-helpers.ts","../src/services/fqs/queries/fragments.ts","../src/services/fqs/queries/patients.ts","../src/services/fqs-rest/search-helpers.ts","../src/utils/sort.ts","../src/fhir/patient-helper.ts","../src/components/core/providers/patient-provider.tsx","../src/components/core/providers/analytics/use-analytics.ts","../src/components/content/CCDA/ccda-viewer/components/Section/Section.tsx","../src/components/content/CCDA/ccda-viewer/helpers/sectionNarrative/parse-elements.ts","../src/components/content/CCDA/ccda-viewer/helpers/sectionNarrative/get-section-narrative.ts","../src/components/core/ctw-box.tsx","../src/components/core/error-boundary.tsx","../src/components/content/CCDA/ccda-viewer/index.tsx","../src/components/content/CCDA/ccda_viewer/helpers/displayForAddress.ts","../src/components/content/CCDA/ccda_viewer/helpers/displayForName.ts","../src/components/content/CCDA/ccda_viewer/helpers/displayForTelecom.ts","../src/components/content/CCDA/ccda_viewer/helpers/getAddress.ts","../src/components/content/CCDA/ccda_viewer/helpers/getTelecom.ts","../src/components/content/CCDA/ccda_viewer/helpers/getContactDetails.ts","../src/components/content/CCDA/ccda_viewer/helpers/getHumanName.ts","../src/components/content/CCDA/ccda_viewer/helpers/getId.ts","../src/components/content/CCDA/ccda_viewer/helpers/parseToISOString.ts","../src/components/content/CCDA/ccda_viewer/helpers/getPeriod.ts","../src/components/content/CCDA/ccda_viewer/helpers/fixHtml.ts","../src/components/content/CCDA/ccda_viewer/helpers/formatDate.ts","../src/components/content/CCDA/ccda_viewer/types/GeneralInfo.ts","../src/components/content/CCDA/ccda_viewer/components/Authenticator/data.ts","../src/components/content/CCDA/ccda_viewer/components/Table/BasicRow.tsx","../src/components/content/CCDA/ccda_viewer/components/Table/TupleRow.tsx","../src/components/content/CCDA/ccda_viewer/components/Table/Table.tsx","../src/components/content/CCDA/ccda_viewer/components/Authenticator/Authenticator.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getAuthor.ts","../src/components/content/CCDA/ccda_viewer/components/Author/data.ts","../src/components/content/CCDA/ccda_viewer/components/Author/Author.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getConsent.ts","../src/components/content/CCDA/ccda_viewer/components/Authorization/data.ts","../src/components/content/CCDA/ccda_viewer/components/Authorization/Authorization.tsx","../src/components/content/CCDA/ccda_viewer/components/Custodian/data.ts","../src/components/content/CCDA/ccda_viewer/components/Custodian/Custodian.tsx","../src/components/content/CCDA/ccda_viewer/components/DataEnterer/data.ts","../src/components/content/CCDA/ccda_viewer/components/DataEnterer/DataEnterer.tsx","../src/components/content/CCDA/ccda_viewer/components/Document/data.ts","../src/components/content/CCDA/ccda_viewer/components/Document/Document.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getDocumentationOf.ts","../src/components/content/CCDA/ccda_viewer/components/DocumentationOf/data.ts","../src/components/content/CCDA/ccda_viewer/components/DocumentationOf/DocumentationOf.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getEncounter.ts","../src/components/content/CCDA/ccda_viewer/components/Encounter/data.ts","../src/components/content/CCDA/ccda_viewer/components/Encounter/Encounter.tsx","../src/components/content/CCDA/ccda_viewer/components/Informant/data.ts","../src/components/content/CCDA/ccda_viewer/components/Informant/Informant.tsx","../src/components/content/CCDA/ccda_viewer/components/InformationRecipient/data.ts","../src/components/content/CCDA/ccda_viewer/components/InformationRecipient/InformationRecipient.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getInFulfillmentOf.ts","../src/components/content/CCDA/ccda_viewer/components/InFulfillmentOf/data.ts","../src/components/content/CCDA/ccda_viewer/components/InFulfillmentOf/InFulfillmentOf.tsx","../src/components/content/CCDA/ccda_viewer/components/LegalAuthenticator/data.ts","../src/components/content/CCDA/ccda_viewer/components/LegalAuthenticator/LegalAuthenticator.tsx","../src/components/content/CCDA/ccda_viewer/components/Participant/data.ts","../src/components/content/CCDA/ccda_viewer/components/Participant/Participant.tsx","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getBirthPlace.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getEthnicity.ts","../src/components/content/CCDA/ccda_viewer/components/Header/data/getGuardian.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getGuardian.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getLanguage.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getMaritalStatus.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getProviderOrganization.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getRace.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/getReligion.ts","../src/components/content/CCDA/ccda_viewer/components/Header/data/getPatient.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/data/index.ts","../src/components/content/CCDA/ccda_viewer/components/Patient/Patient.tsx","../src/components/content/CCDA/ccda_viewer/components/DocumentDetails.tsx","../src/components/content/CCDA/ccda_viewer/components/Header/data/getTitle.ts","../src/components/content/CCDA/ccda_viewer/components/Header/data/index.ts","../src/components/content/CCDA/ccda_viewer/components/Header/Header.tsx","../src/components/content/CCDA/ccda_viewer/components/Section/Section.tsx","../src/components/content/CCDA/ccda_viewer/index.tsx","../src/components/content/CCDA/tiff-to-png.ts","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/ChevronLeftIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/ChevronRightIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/ExclamationCircleIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/ExclamationIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/FireIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/LockClosedIcon.js","../../../node_modules/.pnpm/@heroicons+react@1.0.6_react@16.14.0/node_modules/@heroicons/react/solid/esm/SearchIcon.js","../src/components/core/alert.tsx","../src/components/core/icons/file.tsx","../src/components/core/icons/image.tsx","../src/components/core/icons/pdf.tsx","../src/components/core/icons/content-type-icon.tsx","../src/components/core/spinner.tsx","../src/components/core/loading.tsx","../src/components/core/providers/feature-flag-provider.tsx","../src/hooks/use-feature-toggle.ts","../src/components/content/CCDA/binary-field.tsx","../src/components/content/CCDA/ccda-modal-base.tsx","../src/components/content/CCDA/base64toBlob.ts","../src/fhir/binaries.ts","../src/components/content/CCDA/view-document.tsx","../src/components/content/allergies/helpers/filters.ts","../src/services/fqs/queries/allergies.ts","../src/services/fqs/queries/fragments/condition.ts","../src/services/fqs/queries/conditions.ts","../src/components/content/resource/history.ts","../src/components/content/allergies/helpers/history.tsx","../src/components/content/allergies/helpers/sort.ts","../src/components/content/resource/helpers/details-card.tsx","../src/components/core/modal.tsx","../src/components/content/CCDA/modal-ccda.tsx","../src/components/content/CCDA/use-download-binary.ts","../src/components/content/CCDA/responsive-source-document-link.tsx","../src/components/content/resource/helpers/history-entry.tsx","../src/components/content/resource/helpers/history.tsx","../src/fhir/basic.ts","../src/components/content/hooks/use-toggle-dismiss.ts","../src/components/content/hooks/use-toggle-read.ts","../src/components/core/dropdown-menu-simple.tsx","../src/components/core/providers/use-request-context.tsx","../src/components/core/providers/user-builder-id.tsx","../../../node_modules/.pnpm/react-jason@1.1.2_react@16.14.0/node_modules/react-jason/themes/__shared__.js","../../../node_modules/.pnpm/react-jason@1.1.2_react@16.14.0/node_modules/react-jason/themes/github.js","../src/components/core/providers/toast-context.tsx","../src/components/core/providers/toast-provider.tsx","../src/components/core/drawer.tsx","../src/components/core/view-fhir.tsx","../../../node_modules/.pnpm/i18next@23.7.6/node_modules/i18next/dist/esm/i18next.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/utils.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/unescape.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/defaults.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/i18nInstance.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/initReactI18next.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/context.js","../../../node_modules/.pnpm/react-i18next@13.5.0_i18next@23.7.6_react-dom@16.14.0_react@16.14.0/node_modules/react-i18next/dist/es/useTranslation.js","../src/i18n/index.ts","../src/components/content/resource/use-additional-resource-actions.tsx","../src/components/core/table/table-colgroup.tsx","../src/components/core/table/table-head.tsx","../src/components/core/table/table-data-cell.tsx","../src/components/core/table/table-full-length-row.tsx","../src/components/core/loading-table.tsx","../src/components/core/table/table-rows.tsx","../src/components/core/pagination/expand-list.tsx","../src/components/core/table/table.tsx","../src/components/content/resource/resource-table.tsx","../src/components/content/hooks/use-patient-error.ts","../src/components/core/icons/no-auth-icon.tsx","../src/components/core/auth-error.tsx","../src/components/content/resource/patient-resource-table.tsx","../src/components/core/providers/theme/use-ctw-theme-ref.ts","../src/components/content/resource/resource-details-drawer.tsx","../src/components/core/menu/menu-item.tsx","../src/components/core/dropdown-action-menu.tsx","../src/components/content/resource/helpers/view-button.tsx","../src/components/core/filter-bar/filter-bar-utils.tsx","../src/components/core/filter-bar/filter-bar-pills/checkbox-pill.tsx","../src/components/core/list-box/list-box.tsx","../src/components/core/filter-bar/filter-bar-pills/select-pill.tsx","../src/components/core/filter-bar/filter-bar-pills/tag-pill.tsx","../src/components/core/filter-bar/filter-bar-pills.tsx","../src/components/core/filter-bar/filter-bar.tsx","../src/components/core/sort-button/sort-button.tsx","../src/components/content/resource/resource-table-actions.tsx","../src/components/core/badge.tsx","../src/components/core/tooltip.tsx","../src/components/content/resource/helpers/resource-title-column.tsx","../src/components/content/allergies/helpers/column.tsx","../src/components/core/icons/refresh.tsx","../src/components/content/forms/schemas/validations.ts","../src/components/content/forms/schemas/request-history-schema.tsx","../src/components/content/forms/save-button.tsx","../src/utils/errors.ts","../src/utils/form-helper.ts","../src/components/core/form/drawer-form.tsx","../src/components/content/forms/form-field.tsx","../src/components/content/forms/form-field-label.tsx","../src/components/core/form/drawer-form-with-fields.tsx","../src/api/patient-history.ts","../src/components/content/patient-history-request-drawer.tsx","../src/components/content/patient-history/use-patient-history.tsx","../src/components/content/patient-history/request-records-button.tsx","../src/components/core/empty-table.tsx","../src/components/core/providers/analytics/analytics-provider.tsx","../src/components/content/allergies/helpers/allergies-filter.tsx","../src/fhir/allergies.ts","../src/utils/filters.ts","../src/utils/local-storage.ts","../src/hooks/use-filtered-sorted-data.ts","../src/components/content/allergies/patient-allergies.tsx","../src/components/core/unread-notification-icon.tsx","../src/components/core/unread-notification.tsx","../src/components/content/allergies/unread-allergies-notification.tsx","../src/components/content/care-team/helpers/columns.tsx","../src/components/content/care-team/helpers/sorts.ts","../src/components/content/resource/helpers/view-date-range.ts","../src/fhir/models/careteam.ts","../src/fhir/models/careteam-practitioner.ts","../src/services/fqs/queries/care-teams.ts","../src/fhir/care-team.ts","../src/components/content/care-team/patient-careteam.tsx","../src/components/content/conditions/helpers/condition-header.tsx","../src/components/core/form/combobox-field.tsx","../src/api/autocomplete-conditions.ts","../src/components/content/forms/conditions-autocomplete.tsx","../src/components/content/forms/schemas/condition-schema.tsx","../src/components/core/modal-confirm-delete.tsx","../src/services/common.ts","../src/services/conditions.ts","../src/components/content/conditions/helpers/modal-hooks.tsx","../src/components/content/conditions/helpers/columns.tsx","../src/components/core/notes-list.tsx","../src/components/content/conditions/helpers/history.tsx","../src/components/core/coding-list.tsx","../src/components/content/conditions/helpers/details.tsx","../src/components/content/conditions/helpers/filters.ts","../src/components/content/conditions/helpers/sorts.ts","../src/components/content/conditions/helpers/views.tsx","../src/components/content/conditions/helpers/patient-conditions-base.tsx","../src/components/content/conditions/patient-conditions.tsx","../src/components/content/overview/overview-card.tsx","../src/components/content/overview/resource-overview-card.tsx","../src/components/content/hooks/use-grouped-by.ts","../src/components/content/resource/resource-table-grouped.tsx","../src/components/content/conditions/helpers/row-actions.tsx","../src/components/content/conditions/patient-conditions-all.tsx","../src/components/content/conditions/patient-conditions-all-grouped.tsx","../src/components/content/patient-history/patient-history-detail.tsx","../src/fhir/models/patient-history.ts","../src/components/content/patient-history/use-patient-history-status.ts","../src/components/content/patient-history/patient-history-last-completed.tsx","../src/components/content/patient-history/patient-history-with-action.tsx","../src/components/content/conditions/patient-conditions-outside.tsx","../src/components/content/conditions/patient-conditions-outside-badge.tsx","../src/components/content/overview/filters.tsx","../src/components/content/overview/resource-overview-card-grouped.tsx","../src/components/core/providers/zap-props-state-context.tsx","../src/components/content/conditions/patient-conditions-overview.tsx","../src/hooks/use-feature-variant.ts","../src/components/core/alert-feature-flag.tsx","../src/assets/zus.svg","../src/components/content/zus-aggregated-profile/zap-tab-group/patient-header.tsx","../src/components/core/providers/zap-tab-state-context.tsx","../src/components/core/render-if.tsx","../src/components/content/zus-aggregated-profile/zap-tab-group/zap-tab-group.tsx","../src/components/content/conditions/unread-conditions-notification.tsx","../src/components/core/beta-label.tsx","../src/components/content/vitals/vital-loinc-codes.ts","../src/services/fqs/queries/data-indicator.ts","../src/fhir/data-indicator.ts","../src/components/content/data-indicator.tsx","../src/components/content/diagnostic-reports/helpers/columns.tsx","../src/components/content/diagnostic-reports/helpers/filters.ts","../src/components/content/diagnostic-reports/helpers/sorts.ts","../src/components/content/observations/helpers/bubble.tsx","../src/components/content/observations/helpers/trends.tsx","../src/components/content/observations/helpers/columns.tsx","../src/components/content/observations/helpers/observations-table.tsx","../src/components/content/observations/helpers/details.tsx","../src/components/content/observations/helpers/drawer.tsx","../src/fhir/data-helper/diagnostic-report-trends.ts","../src/services/fqs/queries/diagnostic-reports-query.ts","../src/fhir/diagnostic-report.ts","../src/components/content/diagnostic-reports/patient-diagnostic-reports.tsx","../src/services/fqs/queries/documents.ts","../src/fhir/document.ts","../src/components/content/encounters/helpers/filters.tsx","../src/services/fqs/queries/fragments/codeable-concept.ts","../src/services/fqs/queries/fragments/encounter.ts","../src/services/fqs/queries/encounters.ts","../src/fhir/encounters.ts","../src/fhir/quantity.ts","../src/fhir/models/immunization.ts","../src/services/fqs/queries/immunizations.ts","../src/fhir/immunizations.ts","../src/services/fqs/queries/medication-administration.ts","../src/services/fqs/queries/medication-dispense.ts","../src/services/fqs/queries/medication-request.ts","../src/services/fqs/queries/medication-statements.ts","../src/fhir/medications.ts","../src/hooks/use-medications.ts","../src/components/content/unread-records-notification.tsx","../src/components/content/document/unread-documents-notification.tsx","../src/components/core/simple-more-list.tsx","../src/components/content/encounters/helpers/columns.tsx","../src/components/content/resource/helpers/notes-entry.tsx","../src/components/content/resource/helpers/notes.tsx","../src/utils/dates.ts","../src/components/content/encounters/helpers/modal-hooks.tsx","../src/components/content/encounters/helpers/sorts.ts","../src/components/content/encounters/patient-encounters.tsx","../src/components/content/encounters/unread-encounters-notification.tsx","../src/components/content/immunizations/unread-immunizations-notification.tsx","../src/components/content/medications/helpers/filters.ts","../src/components/content/medications/helpers/columns.tsx","../src/components/content/medications/helpers/history.tsx","../src/components/core/data-list.tsx","../src/components/content/medications/helpers/details.tsx","../src/components/content/medications/helpers/sorts.ts","../src/components/content/medications/helpers/patient-medications-base.tsx","../src/components/content/medications/helpers/views.ts","../src/components/content/medications/patient-medications.tsx","../src/api/autocomplete-medications.ts","../src/components/content/forms/medications-autocomplete.tsx","../src/components/content/forms/schemas/medication-schema.tsx","../src/components/content/forms/actions/medications.tsx","../src/components/content/medications/helpers/add-new-med-drawer.tsx","../src/components/content/medications/patient-medications-all.tsx","../src/components/content/medications/patient-medications-outside.tsx","../src/components/content/medications/patient-medications-outside-badge.tsx","../src/components/content/medications/unread-medications-notification.tsx","../src/components/content/overview/zus-information-card.tsx","../src/components/content/diagnostic-reports/patient-diagnostic-reports-overview.tsx","../src/components/content/encounters/encounters-overview-card.tsx","../src/hooks/use-builder-config.ts","../src/components/content/patients/patient-info-line.tsx","../src/components/content/episode-of-care/episode-of-care-drawer.tsx","../src/services/fqs/queries/episode-of-care.ts","../src/fhir/episode-of-care.ts","../src/components/content/episode-of-care/episode-of-care-overview-card.tsx","../src/components/content/medications/patient-medications-overview.tsx","../src/fhir/models/vitals-bucket.ts","../src/services/fqs/queries/vitals.ts","../src/fhir/vitals.ts","../src/components/content/vitals/helpers/use-patient-overview-vitals.ts","../src/components/content/vitals/patient-vitals-overview.tsx","../src/components/content/overview/helpers/use-overview-cards-loaded-state.ts","../src/components/content/overview/patient-overview.tsx","../src/components/content/overview/patient-overview-zap.tsx","../src/components/content/patient-record-search/helpers/feedback-provider.tsx","../src/components/content/patient-record-search/helpers/use-submit-feedback.ts","../src/components/content/patient-record-search/helpers/feedback-form.tsx","../src/components/content/patient-record-search/helpers/search-result.tsx","../src/components/content/document/helpers/details.tsx","../src/components/content/patient-record-search/helpers/relevant-content.tsx","../src/components/content/patient-record-search/helpers/search-result-row.tsx","../src/services/fqs/queries/observations.ts","../src/fhir/observations.ts","../src/services/patient-record-search/patient-record-search.ts","../src/components/content/patient-record-search/patient-record-search.tsx","../src/components/content/patient-sources/helpers/columns.tsx","../src/components/content/patient-sources/patient-sources.tsx","../src/components/content/timeline/helpers/columns.tsx","../src/components/content/timeline/helpers/filters.tsx","../src/components/content/timeline/helpers/modal-hooks.tsx","../src/components/content/timeline/helpers/sorts.ts","../src/fhir/models/timeline-event.ts","../src/fhir/timeline-event.ts","../src/components/content/timeline/patient-timeline.tsx","../src/components/content/vitals/helpers/filters.ts","../src/components/content/vitals/sorts.ts","../src/components/content/vitals/views.ts","../src/components/content/vitals/vital-rows.tsx","../src/components/core/rotated-table/rotated-table.tsx","../src/components/content/vitals/patient-vitals.tsx","../src/components/content/document/helpers/columns.tsx","../src/components/content/document/helpers/sorts.ts","../src/components/content/document/patient-documents.tsx","../src/components/content/immunizations/helpers/columns.tsx","../src/components/content/immunizations/helpers/filters.tsx","../src/components/content/immunizations/helpers/sort.ts","../src/components/content/immunizations/patient-immunizations.tsx","../src/components/content/zus-aggregated-profile/zus-aggregated-profile-tabs.tsx","../src/components/content/zus-aggregated-profile/zus-aggregated-profile.tsx","../src/components/content/conditions/patient-conditions-profile.tsx","../src/components/content/diagnostic-reports/unread-diagnostic-reports-notification.tsx","../src/components/content/medication-dispense/helpers/dispense-columns.tsx","../src/components/content/medication-dispense/helpers/filters.tsx","../src/fhir/medication-dispense.ts","../src/components/content/medication-dispense/patient-medication-dispense.tsx","../src/components/content/medications/patient-medications-profile.tsx","../src/services/patient-history/patient-history-types.ts","../src/components/content/patient-history/helpers/filters.tsx","../src/components/content/patient-history/use-builder-patient-history-list.ts","../src/components/core/pagination/simple-pagination.tsx","../src/components/content/patient-history/patient-history-table.tsx","../src/components/content/patients/patients-search.tsx","../src/components/content/patients/patients-table-helper.tsx","../src/components/content/patients/use-upid-polling.tsx","../src/utils/invalidate-queries.ts","../src/components/content/patients/patients-table.tsx","../src/components/content/zus-aggregated-profile/zus-aggregated-profile-iframe.tsx","../src/components/core/action-list/action-list.tsx","../src/components/core/icons/zus-icon.tsx","../src/components/core/pagination/pagination.tsx","../src/components/core/providers/authentication/authentication-provider.tsx","../src/components/core/providers/telemetry/telemetry-provider.tsx","../src/components/core/providers/theme/theme-provider.tsx","../src/components/core/providers/zap-props-provider.tsx","../src/components/core/providers/zap-tab-provider.tsx","../src/components/core/providers/ctw-provider.tsx","../src/components/core/toggle.tsx","../src/components/core/toggle-control.tsx"],"sourcesContent":["/** @license React v16.14.0\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),g=60103;exports.Fragment=60107;if(\"function\"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h(\"react.element\");exports.Fragment=h(\"react.fragment\")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=\"\"+k);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q;\n","/** @license React v16.14.0\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n  (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar REACT_ELEMENT_TYPE = 0xeac7;\nvar REACT_PORTAL_TYPE = 0xeaca;\nexports.Fragment = 0xeacb;\nvar REACT_STRICT_MODE_TYPE = 0xeacc;\nvar REACT_PROFILER_TYPE = 0xead2;\nvar REACT_PROVIDER_TYPE = 0xeacd;\nvar REACT_CONTEXT_TYPE = 0xeace;\nvar REACT_FORWARD_REF_TYPE = 0xead0;\nvar REACT_SUSPENSE_TYPE = 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = 0xead8;\nvar REACT_MEMO_TYPE = 0xead3;\nvar REACT_LAZY_TYPE = 0xead4;\nvar REACT_BLOCK_TYPE = 0xead9;\nvar REACT_SERVER_BLOCK_TYPE = 0xeada;\nvar REACT_FUNDAMENTAL_TYPE = 0xead5;\nvar REACT_SCOPE_TYPE = 0xead7;\nvar REACT_OPAQUE_ID_TYPE = 0xeae0;\nvar REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;\nvar REACT_OFFSCREEN_TYPE = 0xeae2;\nvar REACT_LEGACY_HIDDEN_TYPE = 0xeae3;\n\nif (typeof Symbol === 'function' && Symbol.for) {\n  var symbolFor = Symbol.for;\n  REACT_ELEMENT_TYPE = symbolFor('react.element');\n  REACT_PORTAL_TYPE = symbolFor('react.portal');\n  exports.Fragment = symbolFor('react.fragment');\n  REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');\n  REACT_PROFILER_TYPE = symbolFor('react.profiler');\n  REACT_PROVIDER_TYPE = symbolFor('react.provider');\n  REACT_CONTEXT_TYPE = symbolFor('react.context');\n  REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');\n  REACT_SUSPENSE_TYPE = symbolFor('react.suspense');\n  REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');\n  REACT_MEMO_TYPE = symbolFor('react.memo');\n  REACT_LAZY_TYPE = symbolFor('react.lazy');\n  REACT_BLOCK_TYPE = symbolFor('react.block');\n  REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');\n  REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');\n  REACT_SCOPE_TYPE = symbolFor('react.scope');\n  REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');\n  REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');\n  REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');\n  REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');\n}\n\nvar MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n  if (maybeIterable === null || typeof maybeIterable !== 'object') {\n    return null;\n  }\n\n  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n  if (typeof maybeIterator === 'function') {\n    return maybeIterator;\n  }\n\n  return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n  {\n    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n      args[_key2 - 1] = arguments[_key2];\n    }\n\n    printWarning('error', format, args);\n  }\n}\n\nfunction printWarning(level, format, args) {\n  // When changing this logic, you might want to also\n  // update consoleWithStackDev.www.js as well.\n  {\n    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n    var stack = '';\n\n    if (currentlyValidatingElement) {\n      var name = getComponentName(currentlyValidatingElement.type);\n      var owner = currentlyValidatingElement._owner;\n      stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));\n    }\n\n    stack += ReactDebugCurrentFrame.getStackAddendum();\n\n    if (stack !== '') {\n      format += '%s';\n      args = args.concat([stack]);\n    }\n\n    var argsWithFormat = args.map(function (item) {\n      return '' + item;\n    }); // Careful: RN currently depends on this prefix\n\n    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n    // breaks IE9: https://github.com/facebook/react/issues/13610\n    // eslint-disable-next-line react-internal/no-production-logging\n\n    Function.prototype.apply.call(console[level], console, argsWithFormat);\n  }\n}\n\n// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\n\nfunction isValidElementType(type) {\n  if (typeof type === 'string' || typeof type === 'function') {\n    return true;\n  } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n  if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) {\n    return true;\n  }\n\n  if (typeof type === 'object' && type !== null) {\n    if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n\nvar BEFORE_SLASH_RE = /^(.*)[\\\\\\/]/;\nfunction describeComponentFrame (name, source, ownerName) {\n  var sourceInfo = '';\n\n  if (source) {\n    var path = source.fileName;\n    var fileName = path.replace(BEFORE_SLASH_RE, '');\n\n    {\n      // In DEV, include code for a common special case:\n      // prefer \"folder/index.js\" instead of just \"index.js\".\n      if (/^index\\./.test(fileName)) {\n        var match = path.match(BEFORE_SLASH_RE);\n\n        if (match) {\n          var pathBeforeSlash = match[1];\n\n          if (pathBeforeSlash) {\n            var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');\n            fileName = folderName + '/' + fileName;\n          }\n        }\n      }\n    }\n\n    sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';\n  } else if (ownerName) {\n    sourceInfo = ' (created by ' + ownerName + ')';\n  }\n\n  return '\\n    in ' + (name || 'Unknown') + sourceInfo;\n}\n\nvar Resolved = 1;\nfunction refineResolvedLazyComponent(lazyComponent) {\n  return lazyComponent._status === Resolved ? lazyComponent._result : null;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n  var functionName = innerType.displayName || innerType.name || '';\n  return outerType.displayName || (functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName);\n}\n\nfunction getComponentName(type) {\n  if (type == null) {\n    // Host root, text node or just invalid type.\n    return null;\n  }\n\n  {\n    if (typeof type.tag === 'number') {\n      error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');\n    }\n  }\n\n  if (typeof type === 'function') {\n    return type.displayName || type.name || null;\n  }\n\n  if (typeof type === 'string') {\n    return type;\n  }\n\n  switch (type) {\n    case exports.Fragment:\n      return 'Fragment';\n\n    case REACT_PORTAL_TYPE:\n      return 'Portal';\n\n    case REACT_PROFILER_TYPE:\n      return \"Profiler\";\n\n    case REACT_STRICT_MODE_TYPE:\n      return 'StrictMode';\n\n    case REACT_SUSPENSE_TYPE:\n      return 'Suspense';\n\n    case REACT_SUSPENSE_LIST_TYPE:\n      return 'SuspenseList';\n  }\n\n  if (typeof type === 'object') {\n    switch (type.$$typeof) {\n      case REACT_CONTEXT_TYPE:\n        return 'Context.Consumer';\n\n      case REACT_PROVIDER_TYPE:\n        return 'Context.Provider';\n\n      case REACT_FORWARD_REF_TYPE:\n        return getWrappedName(type, type.render, 'ForwardRef');\n\n      case REACT_MEMO_TYPE:\n        return getComponentName(type.type);\n\n      case REACT_BLOCK_TYPE:\n        return getComponentName(type.render);\n\n      case REACT_LAZY_TYPE:\n        {\n          var thenable = type;\n          var resolvedThenable = refineResolvedLazyComponent(thenable);\n\n          if (resolvedThenable) {\n            return getComponentName(resolvedThenable);\n          }\n\n          break;\n        }\n    }\n  }\n\n  return null;\n}\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\nvar currentlyValidatingElement = null;\n\nfunction setCurrentlyValidatingElement(element) {\n  {\n    currentlyValidatingElement = element;\n  }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n  {\n    // $FlowFixMe This is okay but Flow doesn't know it.\n    var has = Function.call.bind(Object.prototype.hasOwnProperty);\n\n    for (var typeSpecName in typeSpecs) {\n      if (has(typeSpecs, typeSpecName)) {\n        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n        // fail the render phase where it didn't fail before. So we log it.\n        // After these have been cleaned up, we'll let them throw.\n\n        try {\n          // This is intentionally an invariant that gets caught. It's the same\n          // behavior as without this statement except with a better message.\n          if (typeof typeSpecs[typeSpecName] !== 'function') {\n            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n            err.name = 'Invariant Violation';\n            throw err;\n          }\n\n          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n        } catch (ex) {\n          error$1 = ex;\n        }\n\n        if (error$1 && !(error$1 instanceof Error)) {\n          setCurrentlyValidatingElement(element);\n\n          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n          setCurrentlyValidatingElement(null);\n        }\n\n        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n          // Only monitor this failure once because there tends to be a lot of the\n          // same error.\n          loggedTypeFailures[error$1.message] = true;\n          setCurrentlyValidatingElement(element);\n\n          error('Failed %s type: %s', location, error$1.message);\n\n          setCurrentlyValidatingElement(null);\n        }\n      }\n    }\n  }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar RESERVED_PROPS = {\n  key: true,\n  ref: true,\n  __self: true,\n  __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n  didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n  {\n    if (hasOwnProperty.call(config, 'ref')) {\n      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n      if (getter && getter.isReactWarning) {\n        return false;\n      }\n    }\n  }\n\n  return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n  {\n    if (hasOwnProperty.call(config, 'key')) {\n      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n      if (getter && getter.isReactWarning) {\n        return false;\n      }\n    }\n  }\n\n  return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n  {\n    if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n      var componentName = getComponentName(ReactCurrentOwner.current.type);\n\n      if (!didWarnAboutStringRefs[componentName]) {\n        error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);\n\n        didWarnAboutStringRefs[componentName] = true;\n      }\n    }\n  }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n  {\n    var warnAboutAccessingKey = function () {\n      if (!specialPropKeyWarningShown) {\n        specialPropKeyWarningShown = true;\n\n        error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n      }\n    };\n\n    warnAboutAccessingKey.isReactWarning = true;\n    Object.defineProperty(props, 'key', {\n      get: warnAboutAccessingKey,\n      configurable: true\n    });\n  }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n  {\n    var warnAboutAccessingRef = function () {\n      if (!specialPropRefWarningShown) {\n        specialPropRefWarningShown = true;\n\n        error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n      }\n    };\n\n    warnAboutAccessingRef.isReactWarning = true;\n    Object.defineProperty(props, 'ref', {\n      get: warnAboutAccessingRef,\n      configurable: true\n    });\n  }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n  var element = {\n    // This tag allows us to uniquely identify this as a React Element\n    $$typeof: REACT_ELEMENT_TYPE,\n    // Built-in properties that belong on the element\n    type: type,\n    key: key,\n    ref: ref,\n    props: props,\n    // Record the component responsible for creating this element.\n    _owner: owner\n  };\n\n  {\n    // The validation flag is currently mutative. We put it on\n    // an external backing store so that we can freeze the whole object.\n    // This can be replaced with a WeakMap once they are implemented in\n    // commonly used development environments.\n    element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n    // the validation flag non-enumerable (where possible, which should\n    // include every environment we run tests in), so the test framework\n    // ignores it.\n\n    Object.defineProperty(element._store, 'validated', {\n      configurable: false,\n      enumerable: false,\n      writable: true,\n      value: false\n    }); // self and source are DEV only properties.\n\n    Object.defineProperty(element, '_self', {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n      value: self\n    }); // Two elements created in two different places should be considered\n    // equal for testing purposes and therefore we hide it from enumeration.\n\n    Object.defineProperty(element, '_source', {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n      value: source\n    });\n\n    if (Object.freeze) {\n      Object.freeze(element.props);\n      Object.freeze(element);\n    }\n  }\n\n  return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n  {\n    var propName; // Reserved names are extracted\n\n    var props = {};\n    var key = null;\n    var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n    // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n    // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n    // but as an intermediary step, we will use jsxDEV for everything except\n    // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n    // key is explicitly declared to be undefined or not.\n\n    if (maybeKey !== undefined) {\n      key = '' + maybeKey;\n    }\n\n    if (hasValidKey(config)) {\n      key = '' + config.key;\n    }\n\n    if (hasValidRef(config)) {\n      ref = config.ref;\n      warnIfStringRefCannotBeAutoConverted(config, self);\n    } // Remaining properties are added to a new props object\n\n\n    for (propName in config) {\n      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n        props[propName] = config[propName];\n      }\n    } // Resolve default props\n\n\n    if (type && type.defaultProps) {\n      var defaultProps = type.defaultProps;\n\n      for (propName in defaultProps) {\n        if (props[propName] === undefined) {\n          props[propName] = defaultProps[propName];\n        }\n      }\n    }\n\n    if (key || ref) {\n      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n      if (key) {\n        defineKeyPropWarningGetter(props, displayName);\n      }\n\n      if (ref) {\n        defineRefPropWarningGetter(props, displayName);\n      }\n    }\n\n    return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n  }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n  currentlyValidatingElement = element;\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n  propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\nfunction isValidElement(object) {\n  {\n    return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n  }\n}\n\nfunction getDeclarationErrorAddendum() {\n  {\n    if (ReactCurrentOwner$1.current) {\n      var name = getComponentName(ReactCurrentOwner$1.current.type);\n\n      if (name) {\n        return '\\n\\nCheck the render method of `' + name + '`.';\n      }\n    }\n\n    return '';\n  }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n  {\n    if (source !== undefined) {\n      var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n      var lineNumber = source.lineNumber;\n      return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n    }\n\n    return '';\n  }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n  {\n    var info = getDeclarationErrorAddendum();\n\n    if (!info) {\n      var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n      if (parentName) {\n        info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n      }\n    }\n\n    return info;\n  }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n  {\n    if (!element._store || element._store.validated || element.key != null) {\n      return;\n    }\n\n    element._store.validated = true;\n    var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n      return;\n    }\n\n    ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n    // property, it may be the creator of the child that's responsible for\n    // assigning it a key.\n\n    var childOwner = '';\n\n    if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n      // Give the component that originally created this child.\n      childOwner = \" It was passed a child from \" + getComponentName(element._owner.type) + \".\";\n    }\n\n    setCurrentlyValidatingElement$1(element);\n\n    error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n    setCurrentlyValidatingElement$1(null);\n  }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n  {\n    if (typeof node !== 'object') {\n      return;\n    }\n\n    if (Array.isArray(node)) {\n      for (var i = 0; i < node.length; i++) {\n        var child = node[i];\n\n        if (isValidElement(child)) {\n          validateExplicitKey(child, parentType);\n        }\n      }\n    } else if (isValidElement(node)) {\n      // This element was passed in a valid location.\n      if (node._store) {\n        node._store.validated = true;\n      }\n    } else if (node) {\n      var iteratorFn = getIteratorFn(node);\n\n      if (typeof iteratorFn === 'function') {\n        // Entry iterators used to provide implicit keys,\n        // but now we print a separate warning for them later.\n        if (iteratorFn !== node.entries) {\n          var iterator = iteratorFn.call(node);\n          var step;\n\n          while (!(step = iterator.next()).done) {\n            if (isValidElement(step.value)) {\n              validateExplicitKey(step.value, parentType);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n  {\n    var type = element.type;\n\n    if (type === null || type === undefined || typeof type === 'string') {\n      return;\n    }\n\n    var propTypes;\n\n    if (typeof type === 'function') {\n      propTypes = type.propTypes;\n    } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n    // Inner props are checked in the reconciler.\n    type.$$typeof === REACT_MEMO_TYPE)) {\n      propTypes = type.propTypes;\n    } else {\n      return;\n    }\n\n    if (propTypes) {\n      // Intentionally inside to avoid triggering lazy initializers:\n      var name = getComponentName(type);\n      checkPropTypes(propTypes, element.props, 'prop', name, element);\n    } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n      propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n      var _name = getComponentName(type);\n\n      error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n    }\n\n    if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n      error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n    }\n  }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n  {\n    var keys = Object.keys(fragment.props);\n\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n\n      if (key !== 'children' && key !== 'key') {\n        setCurrentlyValidatingElement$1(fragment);\n\n        error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n        setCurrentlyValidatingElement$1(null);\n        break;\n      }\n    }\n\n    if (fragment.ref !== null) {\n      setCurrentlyValidatingElement$1(fragment);\n\n      error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n      setCurrentlyValidatingElement$1(null);\n    }\n  }\n}\n\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n  {\n    var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n    // succeed and there will likely be errors in render.\n\n    if (!validType) {\n      var info = '';\n\n      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n        info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n      }\n\n      var sourceInfo = getSourceInfoErrorAddendum(source);\n\n      if (sourceInfo) {\n        info += sourceInfo;\n      } else {\n        info += getDeclarationErrorAddendum();\n      }\n\n      var typeString;\n\n      if (type === null) {\n        typeString = 'null';\n      } else if (Array.isArray(type)) {\n        typeString = 'array';\n      } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n        typeString = \"<\" + (getComponentName(type.type) || 'Unknown') + \" />\";\n        info = ' Did you accidentally export a JSX literal instead of a component?';\n      } else {\n        typeString = typeof type;\n      }\n\n      error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n    }\n\n    var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n    // TODO: Drop this when these are no longer allowed as the type argument.\n\n    if (element == null) {\n      return element;\n    } // Skip key warning if the type isn't valid since our key validation logic\n    // doesn't expect a non-string/function type and can throw confusing errors.\n    // We don't want exception behavior to differ between dev and prod.\n    // (Rendering will throw with a helpful message and as soon as the type is\n    // fixed, the key warnings will appear.)\n\n\n    if (validType) {\n      var children = props.children;\n\n      if (children !== undefined) {\n        if (isStaticChildren) {\n          if (Array.isArray(children)) {\n            for (var i = 0; i < children.length; i++) {\n              validateChildKeys(children[i], type);\n            }\n\n            if (Object.freeze) {\n              Object.freeze(children);\n            }\n          } else {\n            error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n          }\n        } else {\n          validateChildKeys(children, type);\n        }\n      }\n    }\n\n    if (type === exports.Fragment) {\n      validateFragmentProps(element);\n    } else {\n      validatePropTypes(element);\n    }\n\n    return element;\n  }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n  {\n    return jsxWithValidation(type, props, key, true);\n  }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n  {\n    return jsxWithValidation(type, props, key, false);\n  }\n}\n\nvar jsx =  jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs =  jsxWithValidationStatic ;\n\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n  })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n  module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n  var index = -1,\n      length = array == null ? 0 : array.length,\n      result = Array(length);\n\n  while (++index < length) {\n    result[index] = iteratee(array[index], index, array);\n  }\n  return result;\n}\n\nmodule.exports = arrayMap;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n  var isOwn = hasOwnProperty.call(value, symToStringTag),\n      tag = value[symToStringTag];\n\n  try {\n    value[symToStringTag] = undefined;\n    var unmasked = true;\n  } catch (e) {}\n\n  var result = nativeObjectToString.call(value);\n  if (unmasked) {\n    if (isOwn) {\n      value[symToStringTag] = tag;\n    } else {\n      delete value[symToStringTag];\n    }\n  }\n  return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n  return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n    getRawTag = require('./_getRawTag'),\n    objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n    undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n  if (value == null) {\n    return value === undefined ? undefinedTag : nullTag;\n  }\n  return (symToStringTag && symToStringTag in Object(value))\n    ? getRawTag(value)\n    : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n  return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n  return typeof value == 'symbol' ||\n    (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var Symbol = require('./_Symbol'),\n    arrayMap = require('./_arrayMap'),\n    isArray = require('./isArray'),\n    isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n    symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n  // Exit early for strings to avoid a performance hit in some environments.\n  if (typeof value == 'string') {\n    return value;\n  }\n  if (isArray(value)) {\n    // Recursively convert values (susceptible to call stack limits).\n    return arrayMap(value, baseToString) + '';\n  }\n  if (isSymbol(value)) {\n    return symbolToString ? symbolToString.call(value) : '';\n  }\n  var result = (value + '');\n  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n  return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n  var index = -1,\n      length = array.length;\n\n  if (start < 0) {\n    start = -start > length ? 0 : (length + start);\n  }\n  end = end > length ? length : end;\n  if (end < 0) {\n    end += length;\n  }\n  length = start > end ? 0 : ((end - start) >>> 0);\n  start >>>= 0;\n\n  var result = Array(length);\n  while (++index < length) {\n    result[index] = array[index + start];\n  }\n  return result;\n}\n\nmodule.exports = baseSlice;\n","var baseSlice = require('./_baseSlice');\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n  var length = array.length;\n  end = end === undefined ? length : end;\n  return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nmodule.exports = castSlice;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n    rsComboMarksRange = '\\\\u0300-\\\\u036f',\n    reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n    rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n    rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange  + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n  return reHasUnicode.test(string);\n}\n\nmodule.exports = hasUnicode;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n  return string.split('');\n}\n\nmodule.exports = asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n    rsComboMarksRange = '\\\\u0300-\\\\u036f',\n    reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n    rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n    rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n    rsCombo = '[' + rsComboRange + ']',\n    rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n    rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n    rsNonAstral = '[^' + rsAstralRange + ']',\n    rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n    rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n    rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n    rsOptVar = '[' + rsVarRange + ']?',\n    rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n    rsSeq = rsOptVar + reOptMod + rsOptJoin,\n    rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n  return string.match(reUnicode) || [];\n}\n\nmodule.exports = unicodeToArray;\n","var asciiToArray = require('./_asciiToArray'),\n    hasUnicode = require('./_hasUnicode'),\n    unicodeToArray = require('./_unicodeToArray');\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n  return hasUnicode(string)\n    ? unicodeToArray(string)\n    : asciiToArray(string);\n}\n\nmodule.exports = stringToArray;\n","var castSlice = require('./_castSlice'),\n    hasUnicode = require('./_hasUnicode'),\n    stringToArray = require('./_stringToArray'),\n    toString = require('./toString');\n\n/**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\nfunction createCaseFirst(methodName) {\n  return function(string) {\n    string = toString(string);\n\n    var strSymbols = hasUnicode(string)\n      ? stringToArray(string)\n      : undefined;\n\n    var chr = strSymbols\n      ? strSymbols[0]\n      : string.charAt(0);\n\n    var trailing = strSymbols\n      ? castSlice(strSymbols, 1).join('')\n      : string.slice(1);\n\n    return chr[methodName]() + trailing;\n  };\n}\n\nmodule.exports = createCaseFirst;\n","var createCaseFirst = require('./_createCaseFirst');\n\n/**\n * Converts the first character of `string` to upper case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.upperFirst('fred');\n * // => 'Fred'\n *\n * _.upperFirst('FRED');\n * // => 'FRED'\n */\nvar upperFirst = createCaseFirst('toUpperCase');\n\nmodule.exports = upperFirst;\n","var toString = require('./toString'),\n    upperFirst = require('./upperFirst');\n\n/**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\nfunction capitalize(string) {\n  return upperFirst(toString(string).toLowerCase());\n}\n\nmodule.exports = capitalize;\n","/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n *  the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n  var index = -1,\n      length = array == null ? 0 : array.length;\n\n  if (initAccum && length) {\n    accumulator = array[++index];\n  }\n  while (++index < length) {\n    accumulator = iteratee(accumulator, array[index], index, array);\n  }\n  return accumulator;\n}\n\nmodule.exports = arrayReduce;\n","/**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyOf(object) {\n  return function(key) {\n    return object == null ? undefined : object[key];\n  };\n}\n\nmodule.exports = basePropertyOf;\n","var basePropertyOf = require('./_basePropertyOf');\n\n/** Used to map Latin Unicode letters to basic Latin letters. */\nvar deburredLetters = {\n  // Latin-1 Supplement block.\n  '\\xc0': 'A',  '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n  '\\xe0': 'a',  '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n  '\\xc7': 'C',  '\\xe7': 'c',\n  '\\xd0': 'D',  '\\xf0': 'd',\n  '\\xc8': 'E',  '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n  '\\xe8': 'e',  '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n  '\\xcc': 'I',  '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n  '\\xec': 'i',  '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n  '\\xd1': 'N',  '\\xf1': 'n',\n  '\\xd2': 'O',  '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n  '\\xf2': 'o',  '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n  '\\xd9': 'U',  '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n  '\\xf9': 'u',  '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n  '\\xdd': 'Y',  '\\xfd': 'y', '\\xff': 'y',\n  '\\xc6': 'Ae', '\\xe6': 'ae',\n  '\\xde': 'Th', '\\xfe': 'th',\n  '\\xdf': 'ss',\n  // Latin Extended-A block.\n  '\\u0100': 'A',  '\\u0102': 'A', '\\u0104': 'A',\n  '\\u0101': 'a',  '\\u0103': 'a', '\\u0105': 'a',\n  '\\u0106': 'C',  '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n  '\\u0107': 'c',  '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n  '\\u010e': 'D',  '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n  '\\u0112': 'E',  '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n  '\\u0113': 'e',  '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n  '\\u011c': 'G',  '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n  '\\u011d': 'g',  '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n  '\\u0124': 'H',  '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n  '\\u0128': 'I',  '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n  '\\u0129': 'i',  '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n  '\\u0134': 'J',  '\\u0135': 'j',\n  '\\u0136': 'K',  '\\u0137': 'k', '\\u0138': 'k',\n  '\\u0139': 'L',  '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n  '\\u013a': 'l',  '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n  '\\u0143': 'N',  '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n  '\\u0144': 'n',  '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n  '\\u014c': 'O',  '\\u014e': 'O', '\\u0150': 'O',\n  '\\u014d': 'o',  '\\u014f': 'o', '\\u0151': 'o',\n  '\\u0154': 'R',  '\\u0156': 'R', '\\u0158': 'R',\n  '\\u0155': 'r',  '\\u0157': 'r', '\\u0159': 'r',\n  '\\u015a': 'S',  '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n  '\\u015b': 's',  '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n  '\\u0162': 'T',  '\\u0164': 'T', '\\u0166': 'T',\n  '\\u0163': 't',  '\\u0165': 't', '\\u0167': 't',\n  '\\u0168': 'U',  '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n  '\\u0169': 'u',  '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n  '\\u0174': 'W',  '\\u0175': 'w',\n  '\\u0176': 'Y',  '\\u0177': 'y', '\\u0178': 'Y',\n  '\\u0179': 'Z',  '\\u017b': 'Z', '\\u017d': 'Z',\n  '\\u017a': 'z',  '\\u017c': 'z', '\\u017e': 'z',\n  '\\u0132': 'IJ', '\\u0133': 'ij',\n  '\\u0152': 'Oe', '\\u0153': 'oe',\n  '\\u0149': \"'n\", '\\u017f': 's'\n};\n\n/**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\nvar deburrLetter = basePropertyOf(deburredLetters);\n\nmodule.exports = deburrLetter;\n","var deburrLetter = require('./_deburrLetter'),\n    toString = require('./toString');\n\n/** Used to match Latin Unicode letters (excluding mathematical operators). */\nvar reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n/** Used to compose unicode character classes. */\nvar rsComboMarksRange = '\\\\u0300-\\\\u036f',\n    reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n    rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;\n\n/** Used to compose unicode capture groups. */\nvar rsCombo = '[' + rsComboRange + ']';\n\n/**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\nvar reComboMark = RegExp(rsCombo, 'g');\n\n/**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\nfunction deburr(string) {\n  string = toString(string);\n  return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n}\n\nmodule.exports = deburr;\n","/** Used to match words composed of alphanumeric characters. */\nvar reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n/**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction asciiWords(string) {\n  return string.match(reAsciiWord) || [];\n}\n\nmodule.exports = asciiWords;\n","/** Used to detect strings that need a more robust regexp to match words. */\nvar reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n/**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\nfunction hasUnicodeWord(string) {\n  return reHasUnicodeWord.test(string);\n}\n\nmodule.exports = hasUnicodeWord;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n    rsComboMarksRange = '\\\\u0300-\\\\u036f',\n    reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n    rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n    rsDingbatRange = '\\\\u2700-\\\\u27bf',\n    rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n    rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n    rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n    rsPunctuationRange = '\\\\u2000-\\\\u206f',\n    rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n    rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n    rsVarRange = '\\\\ufe0e\\\\ufe0f',\n    rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\",\n    rsBreak = '[' + rsBreakRange + ']',\n    rsCombo = '[' + rsComboRange + ']',\n    rsDigits = '\\\\d+',\n    rsDingbat = '[' + rsDingbatRange + ']',\n    rsLower = '[' + rsLowerRange + ']',\n    rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n    rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n    rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n    rsNonAstral = '[^' + rsAstralRange + ']',\n    rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n    rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n    rsUpper = '[' + rsUpperRange + ']',\n    rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n    rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n    rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n    rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n    reOptMod = rsModifier + '?',\n    rsOptVar = '[' + rsVarRange + ']?',\n    rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n    rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n    rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n    rsSeq = rsOptVar + reOptMod + rsOptJoin,\n    rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;\n\n/** Used to match complex or compound words. */\nvar reUnicodeWord = RegExp([\n  rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n  rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n  rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n  rsUpper + '+' + rsOptContrUpper,\n  rsOrdUpper,\n  rsOrdLower,\n  rsDigits,\n  rsEmoji\n].join('|'), 'g');\n\n/**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction unicodeWords(string) {\n  return string.match(reUnicodeWord) || [];\n}\n\nmodule.exports = unicodeWords;\n","var asciiWords = require('./_asciiWords'),\n    hasUnicodeWord = require('./_hasUnicodeWord'),\n    toString = require('./toString'),\n    unicodeWords = require('./_unicodeWords');\n\n/**\n * Splits `string` into an array of its words.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {RegExp|string} [pattern] The pattern to match words.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the words of `string`.\n * @example\n *\n * _.words('fred, barney, & pebbles');\n * // => ['fred', 'barney', 'pebbles']\n *\n * _.words('fred, barney, & pebbles', /[^, ]+/g);\n * // => ['fred', 'barney', '&', 'pebbles']\n */\nfunction words(string, pattern, guard) {\n  string = toString(string);\n  pattern = guard ? undefined : pattern;\n\n  if (pattern === undefined) {\n    return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n  }\n  return string.match(pattern) || [];\n}\n\nmodule.exports = words;\n","var arrayReduce = require('./_arrayReduce'),\n    deburr = require('./deburr'),\n    words = require('./words');\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\";\n\n/** Used to match apostrophes. */\nvar reApos = RegExp(rsApos, 'g');\n\n/**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\nfunction createCompounder(callback) {\n  return function(string) {\n    return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n  };\n}\n\nmodule.exports = createCompounder;\n","var capitalize = require('./capitalize'),\n    createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\nvar camelCase = createCompounder(function(result, word, index) {\n  word = word.toLowerCase();\n  return result + (index ? capitalize(word) : word);\n});\n\nmodule.exports = camelCase;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n  var type = typeof value;\n  return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n  function object() {}\n  return function(proto) {\n    if (!isObject(proto)) {\n      return {};\n    }\n    if (objectCreate) {\n      return objectCreate(proto);\n    }\n    object.prototype = proto;\n    var result = new object;\n    object.prototype = undefined;\n    return result;\n  };\n}());\n\nmodule.exports = baseCreate;\n","/**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\nfunction baseLodash() {\n  // No operation performed.\n}\n\nmodule.exports = baseLodash;\n","var baseCreate = require('./_baseCreate'),\n    baseLodash = require('./_baseLodash');\n\n/** Used as references for the maximum length and index of an array. */\nvar MAX_ARRAY_LENGTH = 4294967295;\n\n/**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\nfunction LazyWrapper(value) {\n  this.__wrapped__ = value;\n  this.__actions__ = [];\n  this.__dir__ = 1;\n  this.__filtered__ = false;\n  this.__iteratees__ = [];\n  this.__takeCount__ = MAX_ARRAY_LENGTH;\n  this.__views__ = [];\n}\n\n// Ensure `LazyWrapper` is an instance of `baseLodash`.\nLazyWrapper.prototype = baseCreate(baseLodash.prototype);\nLazyWrapper.prototype.constructor = LazyWrapper;\n\nmodule.exports = LazyWrapper;\n","var baseCreate = require('./_baseCreate'),\n    baseLodash = require('./_baseLodash');\n\n/**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\nfunction LodashWrapper(value, chainAll) {\n  this.__wrapped__ = value;\n  this.__actions__ = [];\n  this.__chain__ = !!chainAll;\n  this.__index__ = 0;\n  this.__values__ = undefined;\n}\n\nLodashWrapper.prototype = baseCreate(baseLodash.prototype);\nLodashWrapper.prototype.constructor = LodashWrapper;\n\nmodule.exports = LodashWrapper;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n  var index = -1,\n      length = source.length;\n\n  array || (array = Array(length));\n  while (++index < length) {\n    array[index] = source[index];\n  }\n  return array;\n}\n\nmodule.exports = copyArray;\n","var LazyWrapper = require('./_LazyWrapper'),\n    LodashWrapper = require('./_LodashWrapper'),\n    copyArray = require('./_copyArray');\n\n/**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\nfunction wrapperClone(wrapper) {\n  if (wrapper instanceof LazyWrapper) {\n    return wrapper.clone();\n  }\n  var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n  result.__actions__ = copyArray(wrapper.__actions__);\n  result.__index__  = wrapper.__index__;\n  result.__values__ = wrapper.__values__;\n  return result;\n}\n\nmodule.exports = wrapperClone;\n","var LazyWrapper = require('./_LazyWrapper'),\n    LodashWrapper = require('./_LodashWrapper'),\n    baseLodash = require('./_baseLodash'),\n    isArray = require('./isArray'),\n    isObjectLike = require('./isObjectLike'),\n    wrapperClone = require('./_wrapperClone');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n *   return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\nfunction lodash(value) {\n  if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n    if (value instanceof LodashWrapper) {\n      return value;\n    }\n    if (hasOwnProperty.call(value, '__wrapped__')) {\n      return wrapperClone(value);\n    }\n  }\n  return new LodashWrapper(value);\n}\n\n// Ensure wrappers are instances of `baseLodash`.\nlodash.prototype = baseLodash.prototype;\nlodash.prototype.constructor = lodash;\n\nmodule.exports = lodash;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n  return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var baseGetTag = require('./_baseGetTag'),\n    isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n    funcTag = '[object Function]',\n    genTag = '[object GeneratorFunction]',\n    proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n  if (!isObject(value)) {\n    return false;\n  }\n  // The use of `Object#toString` avoids issues with the `typeof` operator\n  // in Safari 9 which returns 'object' for typed arrays and other constructors.\n  var tag = baseGetTag(value);\n  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n  return typeof value == 'number' &&\n    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var isFunction = require('./isFunction'),\n    isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n  return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n  var type = typeof value;\n  length = length == null ? MAX_SAFE_INTEGER : length;\n\n  return !!length &&\n    (type == 'number' ||\n      (type != 'symbol' && reIsUint.test(value))) &&\n        (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var eq = require('./eq'),\n    isArrayLike = require('./isArrayLike'),\n    isIndex = require('./_isIndex'),\n    isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n *  else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n  if (!isObject(object)) {\n    return false;\n  }\n  var type = typeof index;\n  if (type == 'number'\n        ? (isArrayLike(object) && isIndex(index, object.length))\n        : (type == 'string' && index in object)\n      ) {\n    return eq(object[index], value);\n  }\n  return false;\n}\n\nmodule.exports = isIterateeCall;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n  var index = string.length;\n\n  while (index-- && reWhitespace.test(string.charAt(index))) {}\n  return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n  return string\n    ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n    : string;\n}\n\nmodule.exports = baseTrim;\n","var baseTrim = require('./_baseTrim'),\n    isObject = require('./isObject'),\n    isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n  if (typeof value == 'number') {\n    return value;\n  }\n  if (isSymbol(value)) {\n    return NAN;\n  }\n  if (isObject(value)) {\n    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n    value = isObject(other) ? (other + '') : other;\n  }\n  if (typeof value != 'string') {\n    return value === 0 ? value : +value;\n  }\n  value = baseTrim(value);\n  var isBinary = reIsBinary.test(value);\n  return (isBinary || reIsOctal.test(value))\n    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n    : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","var toNumber = require('./toNumber');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n    MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n  if (!value) {\n    return value === 0 ? value : 0;\n  }\n  value = toNumber(value);\n  if (value === INFINITY || value === -INFINITY) {\n    var sign = (value < 0 ? -1 : 1);\n    return sign * MAX_INTEGER;\n  }\n  return value === value ? value : 0;\n}\n\nmodule.exports = toFinite;\n","var toFinite = require('./toFinite');\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n  var result = toFinite(value),\n      remainder = result % 1;\n\n  return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nmodule.exports = toInteger;\n","var baseSlice = require('./_baseSlice'),\n    isIterateeCall = require('./_isIterateeCall'),\n    toInteger = require('./toInteger');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n    nativeMax = Math.max;\n\n/**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\nfunction chunk(array, size, guard) {\n  if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n    size = 1;\n  } else {\n    size = nativeMax(toInteger(size), 0);\n  }\n  var length = array == null ? 0 : array.length;\n  if (!length || size < 1) {\n    return [];\n  }\n  var index = 0,\n      resIndex = 0,\n      result = Array(nativeCeil(length / size));\n\n  while (index < length) {\n    result[resIndex++] = baseSlice(array, index, (index += size));\n  }\n  return result;\n}\n\nmodule.exports = chunk;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n  this.__data__ = [];\n  this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n  var length = array.length;\n  while (length--) {\n    if (eq(array[length][0], key)) {\n      return length;\n    }\n  }\n  return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n  var data = this.__data__,\n      index = assocIndexOf(data, key);\n\n  if (index < 0) {\n    return false;\n  }\n  var lastIndex = data.length - 1;\n  if (index == lastIndex) {\n    data.pop();\n  } else {\n    splice.call(data, index, 1);\n  }\n  --this.size;\n  return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n  var data = this.__data__,\n      index = assocIndexOf(data, key);\n\n  return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n  return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n  var data = this.__data__,\n      index = assocIndexOf(data, key);\n\n  if (index < 0) {\n    ++this.size;\n    data.push([key, value]);\n  } else {\n    data[index][1] = value;\n  }\n  return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n    listCacheDelete = require('./_listCacheDelete'),\n    listCacheGet = require('./_listCacheGet'),\n    listCacheHas = require('./_listCacheHas'),\n    listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n  var index = -1,\n      length = entries == null ? 0 : entries.length;\n\n  this.clear();\n  while (++index < length) {\n    var entry = entries[index];\n    this.set(entry[0], entry[1]);\n  }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n  this.__data__ = new ListCache;\n  this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n  var data = this.__data__,\n      result = data['delete'](key);\n\n  this.size = data.size;\n  return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n  return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n  return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n  return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n  return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n  if (func != null) {\n    try {\n      return funcToString.call(func);\n    } catch (e) {}\n    try {\n      return (func + '');\n    } catch (e) {}\n  }\n  return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n    isMasked = require('./_isMasked'),\n    isObject = require('./isObject'),\n    toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n    objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n  .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n *  else `false`.\n */\nfunction baseIsNative(value) {\n  if (!isObject(value) || isMasked(value)) {\n    return false;\n  }\n  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n  return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n  return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n    getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n  var value = getValue(object, key);\n  return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative'),\n    root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n  this.__data__ = nativeCreate ? nativeCreate(null) : {};\n  this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n  var result = this.has(key) && delete this.__data__[key];\n  this.size -= result ? 1 : 0;\n  return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n  var data = this.__data__;\n  if (nativeCreate) {\n    var result = data[key];\n    return result === HASH_UNDEFINED ? undefined : result;\n  }\n  return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n  var data = this.__data__;\n  return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n  var data = this.__data__;\n  this.size += this.has(key) ? 0 : 1;\n  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n  return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n    hashDelete = require('./_hashDelete'),\n    hashGet = require('./_hashGet'),\n    hashHas = require('./_hashHas'),\n    hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n  var index = -1,\n      length = entries == null ? 0 : entries.length;\n\n  this.clear();\n  while (++index < length) {\n    var entry = entries[index];\n    this.set(entry[0], entry[1]);\n  }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var Hash = require('./_Hash'),\n    ListCache = require('./_ListCache'),\n    Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n  this.size = 0;\n  this.__data__ = {\n    'hash': new Hash,\n    'map': new (Map || ListCache),\n    'string': new Hash\n  };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n  var type = typeof value;\n  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n    ? (value !== '__proto__')\n    : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n  var data = map.__data__;\n  return isKeyable(key)\n    ? data[typeof key == 'string' ? 'string' : 'hash']\n    : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n  var result = getMapData(this, key)['delete'](key);\n  this.size -= result ? 1 : 0;\n  return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n  return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n  return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n  var data = getMapData(this, key),\n      size = data.size;\n\n  data.set(key, value);\n  this.size += data.size == size ? 0 : 1;\n  return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n    mapCacheDelete = require('./_mapCacheDelete'),\n    mapCacheGet = require('./_mapCacheGet'),\n    mapCacheHas = require('./_mapCacheHas'),\n    mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n  var index = -1,\n      length = entries == null ? 0 : entries.length;\n\n  this.clear();\n  while (++index < length) {\n    var entry = entries[index];\n    this.set(entry[0], entry[1]);\n  }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var ListCache = require('./_ListCache'),\n    Map = require('./_Map'),\n    MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n  var data = this.__data__;\n  if (data instanceof ListCache) {\n    var pairs = data.__data__;\n    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n      pairs.push([key, value]);\n      this.size = ++data.size;\n      return this;\n    }\n    data = this.__data__ = new MapCache(pairs);\n  }\n  data.set(key, value);\n  this.size = data.size;\n  return this;\n}\n\nmodule.exports = stackSet;\n","var ListCache = require('./_ListCache'),\n    stackClear = require('./_stackClear'),\n    stackDelete = require('./_stackDelete'),\n    stackGet = require('./_stackGet'),\n    stackHas = require('./_stackHas'),\n    stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n  var data = this.__data__ = new ListCache(entries);\n  this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n  var index = -1,\n      length = array == null ? 0 : array.length;\n\n  while (++index < length) {\n    if (iteratee(array[index], index, array) === false) {\n      break;\n    }\n  }\n  return array;\n}\n\nmodule.exports = arrayEach;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n  try {\n    var func = getNative(Object, 'defineProperty');\n    func({}, '', {});\n    return func;\n  } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n  if (key == '__proto__' && defineProperty) {\n    defineProperty(object, key, {\n      'configurable': true,\n      'enumerable': true,\n      'value': value,\n      'writable': true\n    });\n  } else {\n    object[key] = value;\n  }\n}\n\nmodule.exports = baseAssignValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n    eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n  var objValue = object[key];\n  if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n      (value === undefined && !(key in object))) {\n    baseAssignValue(object, key, value);\n  }\n}\n\nmodule.exports = assignValue;\n","var assignValue = require('./_assignValue'),\n    baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n  var isNew = !object;\n  object || (object = {});\n\n  var index = -1,\n      length = props.length;\n\n  while (++index < length) {\n    var key = props[index];\n\n    var newValue = customizer\n      ? customizer(object[key], source[key], key, object, source)\n      : undefined;\n\n    if (newValue === undefined) {\n      newValue = source[key];\n    }\n    if (isNew) {\n      baseAssignValue(object, key, newValue);\n    } else {\n      assignValue(object, key, newValue);\n    }\n  }\n  return object;\n}\n\nmodule.exports = copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n  var index = -1,\n      result = Array(n);\n\n  while (++index < n) {\n    result[index] = iteratee(index);\n  }\n  return result;\n}\n\nmodule.exports = baseTimes;\n","var baseGetTag = require('./_baseGetTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n  return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsArguments = require('./_baseIsArguments'),\n    isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n *  else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n  return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n    !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n  return false;\n}\n\nmodule.exports = stubFalse;\n","var root = require('./_root'),\n    stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseGetTag = require('./_baseGetTag'),\n    isLength = require('./isLength'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n    arrayTag = '[object Array]',\n    boolTag = '[object Boolean]',\n    dateTag = '[object Date]',\n    errorTag = '[object Error]',\n    funcTag = '[object Function]',\n    mapTag = '[object Map]',\n    numberTag = '[object Number]',\n    objectTag = '[object Object]',\n    regexpTag = '[object RegExp]',\n    setTag = '[object Set]',\n    stringTag = '[object String]',\n    weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n    dataViewTag = '[object DataView]',\n    float32Tag = '[object Float32Array]',\n    float64Tag = '[object Float64Array]',\n    int8Tag = '[object Int8Array]',\n    int16Tag = '[object Int16Array]',\n    int32Tag = '[object Int32Array]',\n    uint8Tag = '[object Uint8Array]',\n    uint8ClampedTag = '[object Uint8ClampedArray]',\n    uint16Tag = '[object Uint16Array]',\n    uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n  return isObjectLike(value) &&\n    isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n  return function(value) {\n    return func(value);\n  };\n}\n\nmodule.exports = baseUnary;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n  try {\n    // Use `util.types` for Node.js 10+.\n    var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n    if (types) {\n      return types;\n    }\n\n    // Legacy `process.binding('util')` for Node.js < 10.\n    return freeProcess && freeProcess.binding && freeProcess.binding('util');\n  } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n    baseUnary = require('./_baseUnary'),\n    nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var baseTimes = require('./_baseTimes'),\n    isArguments = require('./isArguments'),\n    isArray = require('./isArray'),\n    isBuffer = require('./isBuffer'),\n    isIndex = require('./_isIndex'),\n    isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n  var isArr = isArray(value),\n      isArg = !isArr && isArguments(value),\n      isBuff = !isArr && !isArg && isBuffer(value),\n      isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n      skipIndexes = isArr || isArg || isBuff || isType,\n      result = skipIndexes ? baseTimes(value.length, String) : [],\n      length = result.length;\n\n  for (var key in value) {\n    if ((inherited || hasOwnProperty.call(value, key)) &&\n        !(skipIndexes && (\n           // Safari 9 has enumerable `arguments.length` in strict mode.\n           key == 'length' ||\n           // Node.js 0.10 has enumerable non-index properties on buffers.\n           (isBuff && (key == 'offset' || key == 'parent')) ||\n           // PhantomJS 2 has enumerable non-index properties on typed arrays.\n           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n           // Skip index properties.\n           isIndex(key, length)\n        ))) {\n      result.push(key);\n    }\n  }\n  return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n  var Ctor = value && value.constructor,\n      proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n  return value === proto;\n}\n\nmodule.exports = isPrototype;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n  return function(arg) {\n    return func(transform(arg));\n  };\n}\n\nmodule.exports = overArg;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","var isPrototype = require('./_isPrototype'),\n    nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n  if (!isPrototype(object)) {\n    return nativeKeys(object);\n  }\n  var result = [];\n  for (var key in Object(object)) {\n    if (hasOwnProperty.call(object, key) && key != 'constructor') {\n      result.push(key);\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseKeys;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n    baseKeys = require('./_baseKeys'),\n    isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n *   this.a = 1;\n *   this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var copyObject = require('./_copyObject'),\n    keys = require('./keys');\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n  return object && copyObject(source, keys(source), object);\n}\n\nmodule.exports = baseAssign;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n  var result = [];\n  if (object != null) {\n    for (var key in Object(object)) {\n      result.push(key);\n    }\n  }\n  return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var isObject = require('./isObject'),\n    isPrototype = require('./_isPrototype'),\n    nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n  if (!isObject(object)) {\n    return nativeKeysIn(object);\n  }\n  var isProto = isPrototype(object),\n      result = [];\n\n  for (var key in object) {\n    if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n      result.push(key);\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseKeysIn;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n    baseKeysIn = require('./_baseKeysIn'),\n    isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n *   this.a = 1;\n *   this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n  return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var copyObject = require('./_copyObject'),\n    keysIn = require('./keysIn');\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n  return object && copyObject(source, keysIn(source), object);\n}\n\nmodule.exports = baseAssignIn;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n    allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of  `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n  if (isDeep) {\n    return buffer.slice();\n  }\n  var length = buffer.length,\n      result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n  buffer.copy(result);\n  return result;\n}\n\nmodule.exports = cloneBuffer;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n  var index = -1,\n      length = array == null ? 0 : array.length,\n      resIndex = 0,\n      result = [];\n\n  while (++index < length) {\n    var value = array[index];\n    if (predicate(value, index, array)) {\n      result[resIndex++] = value;\n    }\n  }\n  return result;\n}\n\nmodule.exports = arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n  return [];\n}\n\nmodule.exports = stubArray;\n","var arrayFilter = require('./_arrayFilter'),\n    stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n  if (object == null) {\n    return [];\n  }\n  object = Object(object);\n  return arrayFilter(nativeGetSymbols(object), function(symbol) {\n    return propertyIsEnumerable.call(object, symbol);\n  });\n};\n\nmodule.exports = getSymbols;\n","var copyObject = require('./_copyObject'),\n    getSymbols = require('./_getSymbols');\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n  return copyObject(source, getSymbols(source), object);\n}\n\nmodule.exports = copySymbols;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n  var index = -1,\n      length = values.length,\n      offset = array.length;\n\n  while (++index < length) {\n    array[offset + index] = values[index];\n  }\n  return array;\n}\n\nmodule.exports = arrayPush;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","var arrayPush = require('./_arrayPush'),\n    getPrototype = require('./_getPrototype'),\n    getSymbols = require('./_getSymbols'),\n    stubArray = require('./stubArray');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n  var result = [];\n  while (object) {\n    arrayPush(result, getSymbols(object));\n    object = getPrototype(object);\n  }\n  return result;\n};\n\nmodule.exports = getSymbolsIn;\n","var copyObject = require('./_copyObject'),\n    getSymbolsIn = require('./_getSymbolsIn');\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n  return copyObject(source, getSymbolsIn(source), object);\n}\n\nmodule.exports = copySymbolsIn;\n","var arrayPush = require('./_arrayPush'),\n    isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n  var result = keysFunc(object);\n  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n    getSymbols = require('./_getSymbols'),\n    keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n  return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n    getSymbolsIn = require('./_getSymbolsIn'),\n    keysIn = require('./keysIn');\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n  return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nmodule.exports = getAllKeysIn;\n","var getNative = require('./_getNative'),\n    root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var getNative = require('./_getNative'),\n    root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n    root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var getNative = require('./_getNative'),\n    root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","var DataView = require('./_DataView'),\n    Map = require('./_Map'),\n    Promise = require('./_Promise'),\n    Set = require('./_Set'),\n    WeakMap = require('./_WeakMap'),\n    baseGetTag = require('./_baseGetTag'),\n    toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n    objectTag = '[object Object]',\n    promiseTag = '[object Promise]',\n    setTag = '[object Set]',\n    weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n    mapCtorString = toSource(Map),\n    promiseCtorString = toSource(Promise),\n    setCtorString = toSource(Set),\n    weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n    (Map && getTag(new Map) != mapTag) ||\n    (Promise && getTag(Promise.resolve()) != promiseTag) ||\n    (Set && getTag(new Set) != setTag) ||\n    (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n  getTag = function(value) {\n    var result = baseGetTag(value),\n        Ctor = result == objectTag ? value.constructor : undefined,\n        ctorString = Ctor ? toSource(Ctor) : '';\n\n    if (ctorString) {\n      switch (ctorString) {\n        case dataViewCtorString: return dataViewTag;\n        case mapCtorString: return mapTag;\n        case promiseCtorString: return promiseTag;\n        case setCtorString: return setTag;\n        case weakMapCtorString: return weakMapTag;\n      }\n    }\n    return result;\n  };\n}\n\nmodule.exports = getTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n  var length = array.length,\n      result = new array.constructor(length);\n\n  // Add properties assigned by `RegExp#exec`.\n  if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n    result.index = array.index;\n    result.input = array.input;\n  }\n  return result;\n}\n\nmodule.exports = initCloneArray;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n  new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n  return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n  var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nmodule.exports = cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n  result.lastIndex = regexp.lastIndex;\n  return result;\n}\n\nmodule.exports = cloneRegExp;\n","var Symbol = require('./_Symbol');\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nmodule.exports = cloneSymbol;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n  var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer'),\n    cloneDataView = require('./_cloneDataView'),\n    cloneRegExp = require('./_cloneRegExp'),\n    cloneSymbol = require('./_cloneSymbol'),\n    cloneTypedArray = require('./_cloneTypedArray');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n    dateTag = '[object Date]',\n    mapTag = '[object Map]',\n    numberTag = '[object Number]',\n    regexpTag = '[object RegExp]',\n    setTag = '[object Set]',\n    stringTag = '[object String]',\n    symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n    dataViewTag = '[object DataView]',\n    float32Tag = '[object Float32Array]',\n    float64Tag = '[object Float64Array]',\n    int8Tag = '[object Int8Array]',\n    int16Tag = '[object Int16Array]',\n    int32Tag = '[object Int32Array]',\n    uint8Tag = '[object Uint8Array]',\n    uint8ClampedTag = '[object Uint8ClampedArray]',\n    uint16Tag = '[object Uint16Array]',\n    uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n  var Ctor = object.constructor;\n  switch (tag) {\n    case arrayBufferTag:\n      return cloneArrayBuffer(object);\n\n    case boolTag:\n    case dateTag:\n      return new Ctor(+object);\n\n    case dataViewTag:\n      return cloneDataView(object, isDeep);\n\n    case float32Tag: case float64Tag:\n    case int8Tag: case int16Tag: case int32Tag:\n    case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n      return cloneTypedArray(object, isDeep);\n\n    case mapTag:\n      return new Ctor;\n\n    case numberTag:\n    case stringTag:\n      return new Ctor(object);\n\n    case regexpTag:\n      return cloneRegExp(object);\n\n    case setTag:\n      return new Ctor;\n\n    case symbolTag:\n      return cloneSymbol(object);\n  }\n}\n\nmodule.exports = initCloneByTag;\n","var baseCreate = require('./_baseCreate'),\n    getPrototype = require('./_getPrototype'),\n    isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n  return (typeof object.constructor == 'function' && !isPrototype(object))\n    ? baseCreate(getPrototype(object))\n    : {};\n}\n\nmodule.exports = initCloneObject;\n","var getTag = require('./_getTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n  return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nmodule.exports = baseIsMap;\n","var baseIsMap = require('./_baseIsMap'),\n    baseUnary = require('./_baseUnary'),\n    nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nmodule.exports = isMap;\n","var getTag = require('./_getTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n  return isObjectLike(value) && getTag(value) == setTag;\n}\n\nmodule.exports = baseIsSet;\n","var baseIsSet = require('./_baseIsSet'),\n    baseUnary = require('./_baseUnary'),\n    nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nmodule.exports = isSet;\n","var Stack = require('./_Stack'),\n    arrayEach = require('./_arrayEach'),\n    assignValue = require('./_assignValue'),\n    baseAssign = require('./_baseAssign'),\n    baseAssignIn = require('./_baseAssignIn'),\n    cloneBuffer = require('./_cloneBuffer'),\n    copyArray = require('./_copyArray'),\n    copySymbols = require('./_copySymbols'),\n    copySymbolsIn = require('./_copySymbolsIn'),\n    getAllKeys = require('./_getAllKeys'),\n    getAllKeysIn = require('./_getAllKeysIn'),\n    getTag = require('./_getTag'),\n    initCloneArray = require('./_initCloneArray'),\n    initCloneByTag = require('./_initCloneByTag'),\n    initCloneObject = require('./_initCloneObject'),\n    isArray = require('./isArray'),\n    isBuffer = require('./isBuffer'),\n    isMap = require('./isMap'),\n    isObject = require('./isObject'),\n    isSet = require('./isSet'),\n    keys = require('./keys'),\n    keysIn = require('./keysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n    CLONE_FLAT_FLAG = 2,\n    CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n    arrayTag = '[object Array]',\n    boolTag = '[object Boolean]',\n    dateTag = '[object Date]',\n    errorTag = '[object Error]',\n    funcTag = '[object Function]',\n    genTag = '[object GeneratorFunction]',\n    mapTag = '[object Map]',\n    numberTag = '[object Number]',\n    objectTag = '[object Object]',\n    regexpTag = '[object RegExp]',\n    setTag = '[object Set]',\n    stringTag = '[object String]',\n    symbolTag = '[object Symbol]',\n    weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n    dataViewTag = '[object DataView]',\n    float32Tag = '[object Float32Array]',\n    float64Tag = '[object Float64Array]',\n    int8Tag = '[object Int8Array]',\n    int16Tag = '[object Int16Array]',\n    int32Tag = '[object Int32Array]',\n    uint8Tag = '[object Uint8Array]',\n    uint8ClampedTag = '[object Uint8ClampedArray]',\n    uint16Tag = '[object Uint16Array]',\n    uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n *  1 - Deep clone\n *  2 - Flatten inherited properties\n *  4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n  var result,\n      isDeep = bitmask & CLONE_DEEP_FLAG,\n      isFlat = bitmask & CLONE_FLAT_FLAG,\n      isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n  if (customizer) {\n    result = object ? customizer(value, key, object, stack) : customizer(value);\n  }\n  if (result !== undefined) {\n    return result;\n  }\n  if (!isObject(value)) {\n    return value;\n  }\n  var isArr = isArray(value);\n  if (isArr) {\n    result = initCloneArray(value);\n    if (!isDeep) {\n      return copyArray(value, result);\n    }\n  } else {\n    var tag = getTag(value),\n        isFunc = tag == funcTag || tag == genTag;\n\n    if (isBuffer(value)) {\n      return cloneBuffer(value, isDeep);\n    }\n    if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n      result = (isFlat || isFunc) ? {} : initCloneObject(value);\n      if (!isDeep) {\n        return isFlat\n          ? copySymbolsIn(value, baseAssignIn(result, value))\n          : copySymbols(value, baseAssign(result, value));\n      }\n    } else {\n      if (!cloneableTags[tag]) {\n        return object ? value : {};\n      }\n      result = initCloneByTag(value, tag, isDeep);\n    }\n  }\n  // Check for circular references and return its corresponding clone.\n  stack || (stack = new Stack);\n  var stacked = stack.get(value);\n  if (stacked) {\n    return stacked;\n  }\n  stack.set(value, result);\n\n  if (isSet(value)) {\n    value.forEach(function(subValue) {\n      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n    });\n  } else if (isMap(value)) {\n    value.forEach(function(subValue, key) {\n      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n    });\n  }\n\n  var keysFunc = isFull\n    ? (isFlat ? getAllKeysIn : getAllKeys)\n    : (isFlat ? keysIn : keys);\n\n  var props = isArr ? undefined : keysFunc(value);\n  arrayEach(props || value, function(subValue, key) {\n    if (props) {\n      key = subValue;\n      subValue = value[key];\n    }\n    // Recursively populate clone (susceptible to call stack limits).\n    assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n  });\n  return result;\n}\n\nmodule.exports = baseClone;\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\nfunction clone(value) {\n  return baseClone(value, CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = clone;\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n    CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = cloneDeep;\n","/**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\nfunction compact(array) {\n  var index = -1,\n      length = array == null ? 0 : array.length,\n      resIndex = 0,\n      result = [];\n\n  while (++index < length) {\n    var value = array[index];\n    if (value) {\n      result[resIndex++] = value;\n    }\n  }\n  return result;\n}\n\nmodule.exports = compact;\n","var Symbol = require('./_Symbol'),\n    isArguments = require('./isArguments'),\n    isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n  return isArray(value) || isArguments(value) ||\n    !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n","var arrayPush = require('./_arrayPush'),\n    isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n  var index = -1,\n      length = array.length;\n\n  predicate || (predicate = isFlattenable);\n  result || (result = []);\n\n  while (++index < length) {\n    var value = array[index];\n    if (depth > 0 && predicate(value)) {\n      if (depth > 1) {\n        // Recursively flatten arrays (susceptible to call stack limits).\n        baseFlatten(value, depth - 1, predicate, isStrict, result);\n      } else {\n        arrayPush(result, value);\n      }\n    } else if (!isStrict) {\n      result[result.length] = value;\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseFlatten;\n","var arrayPush = require('./_arrayPush'),\n    baseFlatten = require('./_baseFlatten'),\n    copyArray = require('./_copyArray'),\n    isArray = require('./isArray');\n\n/**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\nfunction concat() {\n  var length = arguments.length;\n  if (!length) {\n    return [];\n  }\n  var args = Array(length - 1),\n      array = arguments[0],\n      index = length;\n\n  while (index--) {\n    args[index - 1] = arguments[index];\n  }\n  return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n}\n\nmodule.exports = concat;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n  return value;\n}\n\nmodule.exports = identity;\n","var WeakMap = require('./_WeakMap');\n\n/** Used to store function metadata. */\nvar metaMap = WeakMap && new WeakMap;\n\nmodule.exports = metaMap;\n","var identity = require('./identity'),\n    metaMap = require('./_metaMap');\n\n/**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\nvar baseSetData = !metaMap ? identity : function(func, data) {\n  metaMap.set(func, data);\n  return func;\n};\n\nmodule.exports = baseSetData;\n","var baseCreate = require('./_baseCreate'),\n    isObject = require('./isObject');\n\n/**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createCtor(Ctor) {\n  return function() {\n    // Use a `switch` statement to work with class constructors. See\n    // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n    // for more details.\n    var args = arguments;\n    switch (args.length) {\n      case 0: return new Ctor;\n      case 1: return new Ctor(args[0]);\n      case 2: return new Ctor(args[0], args[1]);\n      case 3: return new Ctor(args[0], args[1], args[2]);\n      case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n      case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n      case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n      case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n    }\n    var thisBinding = baseCreate(Ctor.prototype),\n        result = Ctor.apply(thisBinding, args);\n\n    // Mimic the constructor's `return` behavior.\n    // See https://es5.github.io/#x13.2.2 for more details.\n    return isObject(result) ? result : thisBinding;\n  };\n}\n\nmodule.exports = createCtor;\n","var createCtor = require('./_createCtor'),\n    root = require('./_root');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1;\n\n/**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createBind(func, bitmask, thisArg) {\n  var isBind = bitmask & WRAP_BIND_FLAG,\n      Ctor = createCtor(func);\n\n  function wrapper() {\n    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n    return fn.apply(isBind ? thisArg : this, arguments);\n  }\n  return wrapper;\n}\n\nmodule.exports = createBind;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n  switch (args.length) {\n    case 0: return func.call(thisArg);\n    case 1: return func.call(thisArg, args[0]);\n    case 2: return func.call(thisArg, args[0], args[1]);\n    case 3: return func.call(thisArg, args[0], args[1], args[2]);\n  }\n  return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\nfunction composeArgs(args, partials, holders, isCurried) {\n  var argsIndex = -1,\n      argsLength = args.length,\n      holdersLength = holders.length,\n      leftIndex = -1,\n      leftLength = partials.length,\n      rangeLength = nativeMax(argsLength - holdersLength, 0),\n      result = Array(leftLength + rangeLength),\n      isUncurried = !isCurried;\n\n  while (++leftIndex < leftLength) {\n    result[leftIndex] = partials[leftIndex];\n  }\n  while (++argsIndex < holdersLength) {\n    if (isUncurried || argsIndex < argsLength) {\n      result[holders[argsIndex]] = args[argsIndex];\n    }\n  }\n  while (rangeLength--) {\n    result[leftIndex++] = args[argsIndex++];\n  }\n  return result;\n}\n\nmodule.exports = composeArgs;\n","/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\nfunction composeArgsRight(args, partials, holders, isCurried) {\n  var argsIndex = -1,\n      argsLength = args.length,\n      holdersIndex = -1,\n      holdersLength = holders.length,\n      rightIndex = -1,\n      rightLength = partials.length,\n      rangeLength = nativeMax(argsLength - holdersLength, 0),\n      result = Array(rangeLength + rightLength),\n      isUncurried = !isCurried;\n\n  while (++argsIndex < rangeLength) {\n    result[argsIndex] = args[argsIndex];\n  }\n  var offset = argsIndex;\n  while (++rightIndex < rightLength) {\n    result[offset + rightIndex] = partials[rightIndex];\n  }\n  while (++holdersIndex < holdersLength) {\n    if (isUncurried || argsIndex < argsLength) {\n      result[offset + holders[holdersIndex]] = args[argsIndex++];\n    }\n  }\n  return result;\n}\n\nmodule.exports = composeArgsRight;\n","/**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\nfunction countHolders(array, placeholder) {\n  var length = array.length,\n      result = 0;\n\n  while (length--) {\n    if (array[length] === placeholder) {\n      ++result;\n    }\n  }\n  return result;\n}\n\nmodule.exports = countHolders;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n  // No operation performed.\n}\n\nmodule.exports = noop;\n","var metaMap = require('./_metaMap'),\n    noop = require('./noop');\n\n/**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\nvar getData = !metaMap ? noop : function(func) {\n  return metaMap.get(func);\n};\n\nmodule.exports = getData;\n","/** Used to lookup unminified function names. */\nvar realNames = {};\n\nmodule.exports = realNames;\n","var realNames = require('./_realNames');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\nfunction getFuncName(func) {\n  var result = (func.name + ''),\n      array = realNames[result],\n      length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n  while (length--) {\n    var data = array[length],\n        otherFunc = data.func;\n    if (otherFunc == null || otherFunc == func) {\n      return data.name;\n    }\n  }\n  return result;\n}\n\nmodule.exports = getFuncName;\n","var LazyWrapper = require('./_LazyWrapper'),\n    getData = require('./_getData'),\n    getFuncName = require('./_getFuncName'),\n    lodash = require('./wrapperLodash');\n\n/**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n *  else `false`.\n */\nfunction isLaziable(func) {\n  var funcName = getFuncName(func),\n      other = lodash[funcName];\n\n  if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n    return false;\n  }\n  if (func === other) {\n    return true;\n  }\n  var data = getData(other);\n  return !!data && func === data[0];\n}\n\nmodule.exports = isLaziable;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n    HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n  var count = 0,\n      lastCalled = 0;\n\n  return function() {\n    var stamp = nativeNow(),\n        remaining = HOT_SPAN - (stamp - lastCalled);\n\n    lastCalled = stamp;\n    if (remaining > 0) {\n      if (++count >= HOT_COUNT) {\n        return arguments[0];\n      }\n    } else {\n      count = 0;\n    }\n    return func.apply(undefined, arguments);\n  };\n}\n\nmodule.exports = shortOut;\n","var baseSetData = require('./_baseSetData'),\n    shortOut = require('./_shortOut');\n\n/**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\nvar setData = shortOut(baseSetData);\n\nmodule.exports = setData;\n","/** Used to match wrap detail comments. */\nvar reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n    reSplitDetails = /,? & /;\n\n/**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\nfunction getWrapDetails(source) {\n  var match = source.match(reWrapDetails);\n  return match ? match[1].split(reSplitDetails) : [];\n}\n\nmodule.exports = getWrapDetails;\n","/** Used to match wrap detail comments. */\nvar reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/;\n\n/**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\nfunction insertWrapDetails(source, details) {\n  var length = details.length;\n  if (!length) {\n    return source;\n  }\n  var lastIndex = length - 1;\n  details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n  details = details.join(length > 2 ? ', ' : ' ');\n  return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n}\n\nmodule.exports = insertWrapDetails;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n  return function() {\n    return value;\n  };\n}\n\nmodule.exports = constant;\n","var constant = require('./constant'),\n    defineProperty = require('./_defineProperty'),\n    identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n  return defineProperty(func, 'toString', {\n    'configurable': true,\n    'enumerable': false,\n    'value': constant(string),\n    'writable': true\n  });\n};\n\nmodule.exports = baseSetToString;\n","var baseSetToString = require('./_baseSetToString'),\n    shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n  var length = array.length,\n      index = fromIndex + (fromRight ? 1 : -1);\n\n  while ((fromRight ? index-- : ++index < length)) {\n    if (predicate(array[index], index, array)) {\n      return index;\n    }\n  }\n  return -1;\n}\n\nmodule.exports = baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n  return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n  var index = fromIndex - 1,\n      length = array.length;\n\n  while (++index < length) {\n    if (array[index] === value) {\n      return index;\n    }\n  }\n  return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var baseFindIndex = require('./_baseFindIndex'),\n    baseIsNaN = require('./_baseIsNaN'),\n    strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n  return value === value\n    ? strictIndexOf(array, value, fromIndex)\n    : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n  var length = array == null ? 0 : array.length;\n  return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","var arrayEach = require('./_arrayEach'),\n    arrayIncludes = require('./_arrayIncludes');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1,\n    WRAP_BIND_KEY_FLAG = 2,\n    WRAP_CURRY_FLAG = 8,\n    WRAP_CURRY_RIGHT_FLAG = 16,\n    WRAP_PARTIAL_FLAG = 32,\n    WRAP_PARTIAL_RIGHT_FLAG = 64,\n    WRAP_ARY_FLAG = 128,\n    WRAP_REARG_FLAG = 256,\n    WRAP_FLIP_FLAG = 512;\n\n/** Used to associate wrap methods with their bit flags. */\nvar wrapFlags = [\n  ['ary', WRAP_ARY_FLAG],\n  ['bind', WRAP_BIND_FLAG],\n  ['bindKey', WRAP_BIND_KEY_FLAG],\n  ['curry', WRAP_CURRY_FLAG],\n  ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n  ['flip', WRAP_FLIP_FLAG],\n  ['partial', WRAP_PARTIAL_FLAG],\n  ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n  ['rearg', WRAP_REARG_FLAG]\n];\n\n/**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\nfunction updateWrapDetails(details, bitmask) {\n  arrayEach(wrapFlags, function(pair) {\n    var value = '_.' + pair[0];\n    if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n      details.push(value);\n    }\n  });\n  return details.sort();\n}\n\nmodule.exports = updateWrapDetails;\n","var getWrapDetails = require('./_getWrapDetails'),\n    insertWrapDetails = require('./_insertWrapDetails'),\n    setToString = require('./_setToString'),\n    updateWrapDetails = require('./_updateWrapDetails');\n\n/**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\nfunction setWrapToString(wrapper, reference, bitmask) {\n  var source = (reference + '');\n  return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n}\n\nmodule.exports = setWrapToString;\n","var isLaziable = require('./_isLaziable'),\n    setData = require('./_setData'),\n    setWrapToString = require('./_setWrapToString');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1,\n    WRAP_BIND_KEY_FLAG = 2,\n    WRAP_CURRY_BOUND_FLAG = 4,\n    WRAP_CURRY_FLAG = 8,\n    WRAP_PARTIAL_FLAG = 32,\n    WRAP_PARTIAL_RIGHT_FLAG = 64;\n\n/**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n *  the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n  var isCurry = bitmask & WRAP_CURRY_FLAG,\n      newHolders = isCurry ? holders : undefined,\n      newHoldersRight = isCurry ? undefined : holders,\n      newPartials = isCurry ? partials : undefined,\n      newPartialsRight = isCurry ? undefined : partials;\n\n  bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n  bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n  if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n    bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n  }\n  var newData = [\n    func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n    newHoldersRight, argPos, ary, arity\n  ];\n\n  var result = wrapFunc.apply(undefined, newData);\n  if (isLaziable(func)) {\n    setData(result, newData);\n  }\n  result.placeholder = placeholder;\n  return setWrapToString(result, func, bitmask);\n}\n\nmodule.exports = createRecurry;\n","/**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\nfunction getHolder(func) {\n  var object = func;\n  return object.placeholder;\n}\n\nmodule.exports = getHolder;\n","var copyArray = require('./_copyArray'),\n    isIndex = require('./_isIndex');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMin = Math.min;\n\n/**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\nfunction reorder(array, indexes) {\n  var arrLength = array.length,\n      length = nativeMin(indexes.length, arrLength),\n      oldArray = copyArray(array);\n\n  while (length--) {\n    var index = indexes[length];\n    array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n  }\n  return array;\n}\n\nmodule.exports = reorder;\n","/** Used as the internal argument placeholder. */\nvar PLACEHOLDER = '__lodash_placeholder__';\n\n/**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\nfunction replaceHolders(array, placeholder) {\n  var index = -1,\n      length = array.length,\n      resIndex = 0,\n      result = [];\n\n  while (++index < length) {\n    var value = array[index];\n    if (value === placeholder || value === PLACEHOLDER) {\n      array[index] = PLACEHOLDER;\n      result[resIndex++] = index;\n    }\n  }\n  return result;\n}\n\nmodule.exports = replaceHolders;\n","var composeArgs = require('./_composeArgs'),\n    composeArgsRight = require('./_composeArgsRight'),\n    countHolders = require('./_countHolders'),\n    createCtor = require('./_createCtor'),\n    createRecurry = require('./_createRecurry'),\n    getHolder = require('./_getHolder'),\n    reorder = require('./_reorder'),\n    replaceHolders = require('./_replaceHolders'),\n    root = require('./_root');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1,\n    WRAP_BIND_KEY_FLAG = 2,\n    WRAP_CURRY_FLAG = 8,\n    WRAP_CURRY_RIGHT_FLAG = 16,\n    WRAP_ARY_FLAG = 128,\n    WRAP_FLIP_FLAG = 512;\n\n/**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n *  the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n *  to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n  var isAry = bitmask & WRAP_ARY_FLAG,\n      isBind = bitmask & WRAP_BIND_FLAG,\n      isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n      isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n      isFlip = bitmask & WRAP_FLIP_FLAG,\n      Ctor = isBindKey ? undefined : createCtor(func);\n\n  function wrapper() {\n    var length = arguments.length,\n        args = Array(length),\n        index = length;\n\n    while (index--) {\n      args[index] = arguments[index];\n    }\n    if (isCurried) {\n      var placeholder = getHolder(wrapper),\n          holdersCount = countHolders(args, placeholder);\n    }\n    if (partials) {\n      args = composeArgs(args, partials, holders, isCurried);\n    }\n    if (partialsRight) {\n      args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n    }\n    length -= holdersCount;\n    if (isCurried && length < arity) {\n      var newHolders = replaceHolders(args, placeholder);\n      return createRecurry(\n        func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n        args, newHolders, argPos, ary, arity - length\n      );\n    }\n    var thisBinding = isBind ? thisArg : this,\n        fn = isBindKey ? thisBinding[func] : func;\n\n    length = args.length;\n    if (argPos) {\n      args = reorder(args, argPos);\n    } else if (isFlip && length > 1) {\n      args.reverse();\n    }\n    if (isAry && ary < length) {\n      args.length = ary;\n    }\n    if (this && this !== root && this instanceof wrapper) {\n      fn = Ctor || createCtor(fn);\n    }\n    return fn.apply(thisBinding, args);\n  }\n  return wrapper;\n}\n\nmodule.exports = createHybrid;\n","var apply = require('./_apply'),\n    createCtor = require('./_createCtor'),\n    createHybrid = require('./_createHybrid'),\n    createRecurry = require('./_createRecurry'),\n    getHolder = require('./_getHolder'),\n    replaceHolders = require('./_replaceHolders'),\n    root = require('./_root');\n\n/**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createCurry(func, bitmask, arity) {\n  var Ctor = createCtor(func);\n\n  function wrapper() {\n    var length = arguments.length,\n        args = Array(length),\n        index = length,\n        placeholder = getHolder(wrapper);\n\n    while (index--) {\n      args[index] = arguments[index];\n    }\n    var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n      ? []\n      : replaceHolders(args, placeholder);\n\n    length -= holders.length;\n    if (length < arity) {\n      return createRecurry(\n        func, bitmask, createHybrid, wrapper.placeholder, undefined,\n        args, holders, undefined, undefined, arity - length);\n    }\n    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n    return apply(fn, this, args);\n  }\n  return wrapper;\n}\n\nmodule.exports = createCurry;\n","var apply = require('./_apply'),\n    createCtor = require('./_createCtor'),\n    root = require('./_root');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1;\n\n/**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n *  the new function.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createPartial(func, bitmask, thisArg, partials) {\n  var isBind = bitmask & WRAP_BIND_FLAG,\n      Ctor = createCtor(func);\n\n  function wrapper() {\n    var argsIndex = -1,\n        argsLength = arguments.length,\n        leftIndex = -1,\n        leftLength = partials.length,\n        args = Array(leftLength + argsLength),\n        fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n    while (++leftIndex < leftLength) {\n      args[leftIndex] = partials[leftIndex];\n    }\n    while (argsLength--) {\n      args[leftIndex++] = arguments[++argsIndex];\n    }\n    return apply(fn, isBind ? thisArg : this, args);\n  }\n  return wrapper;\n}\n\nmodule.exports = createPartial;\n","var composeArgs = require('./_composeArgs'),\n    composeArgsRight = require('./_composeArgsRight'),\n    replaceHolders = require('./_replaceHolders');\n\n/** Used as the internal argument placeholder. */\nvar PLACEHOLDER = '__lodash_placeholder__';\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1,\n    WRAP_BIND_KEY_FLAG = 2,\n    WRAP_CURRY_BOUND_FLAG = 4,\n    WRAP_CURRY_FLAG = 8,\n    WRAP_ARY_FLAG = 128,\n    WRAP_REARG_FLAG = 256;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMin = Math.min;\n\n/**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\nfunction mergeData(data, source) {\n  var bitmask = data[1],\n      srcBitmask = source[1],\n      newBitmask = bitmask | srcBitmask,\n      isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n  var isCombo =\n    ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n    ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n    ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n  // Exit early if metadata can't be merged.\n  if (!(isCommon || isCombo)) {\n    return data;\n  }\n  // Use source `thisArg` if available.\n  if (srcBitmask & WRAP_BIND_FLAG) {\n    data[2] = source[2];\n    // Set when currying a bound function.\n    newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n  }\n  // Compose partial arguments.\n  var value = source[3];\n  if (value) {\n    var partials = data[3];\n    data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n    data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n  }\n  // Compose partial right arguments.\n  value = source[5];\n  if (value) {\n    partials = data[5];\n    data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n    data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n  }\n  // Use source `argPos` if available.\n  value = source[7];\n  if (value) {\n    data[7] = value;\n  }\n  // Use source `ary` if it's smaller.\n  if (srcBitmask & WRAP_ARY_FLAG) {\n    data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n  }\n  // Use source `arity` if one is not provided.\n  if (data[9] == null) {\n    data[9] = source[9];\n  }\n  // Use source `func` and merge bitmasks.\n  data[0] = source[0];\n  data[1] = newBitmask;\n\n  return data;\n}\n\nmodule.exports = mergeData;\n","var baseSetData = require('./_baseSetData'),\n    createBind = require('./_createBind'),\n    createCurry = require('./_createCurry'),\n    createHybrid = require('./_createHybrid'),\n    createPartial = require('./_createPartial'),\n    getData = require('./_getData'),\n    mergeData = require('./_mergeData'),\n    setData = require('./_setData'),\n    setWrapToString = require('./_setWrapToString'),\n    toInteger = require('./toInteger');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_BIND_FLAG = 1,\n    WRAP_BIND_KEY_FLAG = 2,\n    WRAP_CURRY_FLAG = 8,\n    WRAP_CURRY_RIGHT_FLAG = 16,\n    WRAP_PARTIAL_FLAG = 32,\n    WRAP_PARTIAL_RIGHT_FLAG = 64;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n *    1 - `_.bind`\n *    2 - `_.bindKey`\n *    4 - `_.curry` or `_.curryRight` of a bound function\n *    8 - `_.curry`\n *   16 - `_.curryRight`\n *   32 - `_.partial`\n *   64 - `_.partialRight`\n *  128 - `_.rearg`\n *  256 - `_.ary`\n *  512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n  var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n  if (!isBindKey && typeof func != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  var length = partials ? partials.length : 0;\n  if (!length) {\n    bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n    partials = holders = undefined;\n  }\n  ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n  arity = arity === undefined ? arity : toInteger(arity);\n  length -= holders ? holders.length : 0;\n\n  if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n    var partialsRight = partials,\n        holdersRight = holders;\n\n    partials = holders = undefined;\n  }\n  var data = isBindKey ? undefined : getData(func);\n\n  var newData = [\n    func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n    argPos, ary, arity\n  ];\n\n  if (data) {\n    mergeData(newData, data);\n  }\n  func = newData[0];\n  bitmask = newData[1];\n  thisArg = newData[2];\n  partials = newData[3];\n  holders = newData[4];\n  arity = newData[9] = newData[9] === undefined\n    ? (isBindKey ? 0 : func.length)\n    : nativeMax(newData[9] - length, 0);\n\n  if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n    bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n  }\n  if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n    var result = createBind(func, bitmask, thisArg);\n  } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n    result = createCurry(func, bitmask, arity);\n  } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n    result = createPartial(func, bitmask, thisArg, partials);\n  } else {\n    result = createHybrid.apply(undefined, newData);\n  }\n  var setter = data ? baseSetData : setData;\n  return setWrapToString(setter(result, newData), func, bitmask);\n}\n\nmodule.exports = createWrap;\n","var createWrap = require('./_createWrap');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_CURRY_FLAG = 8;\n\n/**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n *   return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\nfunction curry(func, arity, guard) {\n  arity = guard ? undefined : arity;\n  var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n  result.placeholder = curry.placeholder;\n  return result;\n}\n\n// Assign default placeholders.\ncurry.placeholder = {};\n\nmodule.exports = curry;\n","var root = require('./_root');\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n *   console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n  return root.Date.now();\n};\n\nmodule.exports = now;\n","var isObject = require('./isObject'),\n    now = require('./now'),\n    toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n    nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n *  Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n *  The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n *  Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n *   'leading': true,\n *   'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n  var lastArgs,\n      lastThis,\n      maxWait,\n      result,\n      timerId,\n      lastCallTime,\n      lastInvokeTime = 0,\n      leading = false,\n      maxing = false,\n      trailing = true;\n\n  if (typeof func != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  wait = toNumber(wait) || 0;\n  if (isObject(options)) {\n    leading = !!options.leading;\n    maxing = 'maxWait' in options;\n    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n    trailing = 'trailing' in options ? !!options.trailing : trailing;\n  }\n\n  function invokeFunc(time) {\n    var args = lastArgs,\n        thisArg = lastThis;\n\n    lastArgs = lastThis = undefined;\n    lastInvokeTime = time;\n    result = func.apply(thisArg, args);\n    return result;\n  }\n\n  function leadingEdge(time) {\n    // Reset any `maxWait` timer.\n    lastInvokeTime = time;\n    // Start the timer for the trailing edge.\n    timerId = setTimeout(timerExpired, wait);\n    // Invoke the leading edge.\n    return leading ? invokeFunc(time) : result;\n  }\n\n  function remainingWait(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime,\n        timeWaiting = wait - timeSinceLastCall;\n\n    return maxing\n      ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n      : timeWaiting;\n  }\n\n  function shouldInvoke(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime;\n\n    // Either this is the first call, activity has stopped and we're at the\n    // trailing edge, the system time has gone backwards and we're treating\n    // it as the trailing edge, or we've hit the `maxWait` limit.\n    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n  }\n\n  function timerExpired() {\n    var time = now();\n    if (shouldInvoke(time)) {\n      return trailingEdge(time);\n    }\n    // Restart the timer.\n    timerId = setTimeout(timerExpired, remainingWait(time));\n  }\n\n  function trailingEdge(time) {\n    timerId = undefined;\n\n    // Only invoke if we have `lastArgs` which means `func` has been\n    // debounced at least once.\n    if (trailing && lastArgs) {\n      return invokeFunc(time);\n    }\n    lastArgs = lastThis = undefined;\n    return result;\n  }\n\n  function cancel() {\n    if (timerId !== undefined) {\n      clearTimeout(timerId);\n    }\n    lastInvokeTime = 0;\n    lastArgs = lastCallTime = lastThis = timerId = undefined;\n  }\n\n  function flush() {\n    return timerId === undefined ? result : trailingEdge(now());\n  }\n\n  function debounced() {\n    var time = now(),\n        isInvoking = shouldInvoke(time);\n\n    lastArgs = arguments;\n    lastThis = this;\n    lastCallTime = time;\n\n    if (isInvoking) {\n      if (timerId === undefined) {\n        return leadingEdge(lastCallTime);\n      }\n      if (maxing) {\n        // Handle invocations in a tight loop.\n        clearTimeout(timerId);\n        timerId = setTimeout(timerExpired, wait);\n        return invokeFunc(lastCallTime);\n      }\n    }\n    if (timerId === undefined) {\n      timerId = setTimeout(timerExpired, wait);\n    }\n    return result;\n  }\n  debounced.cancel = cancel;\n  debounced.flush = flush;\n  return debounced;\n}\n\nmodule.exports = debounce;\n","var toString = require('./toString');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n    reHasRegExpChar = RegExp(reRegExpChar.source);\n\n/**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\nfunction escapeRegExp(string) {\n  string = toString(string);\n  return (string && reHasRegExpChar.test(string))\n    ? string.replace(reRegExpChar, '\\\\$&')\n    : string;\n}\n\nmodule.exports = escapeRegExp;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n  return function(object, iteratee, keysFunc) {\n    var index = -1,\n        iterable = Object(object),\n        props = keysFunc(object),\n        length = props.length;\n\n    while (length--) {\n      var key = props[fromRight ? length : ++index];\n      if (iteratee(iterable[key], key, iterable) === false) {\n        break;\n      }\n    }\n    return object;\n  };\n}\n\nmodule.exports = createBaseFor;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var baseFor = require('./_baseFor'),\n    keys = require('./keys');\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n  return object && baseFor(object, iteratee, keys);\n}\n\nmodule.exports = baseForOwn;\n","var isArrayLike = require('./isArrayLike');\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n  return function(collection, iteratee) {\n    if (collection == null) {\n      return collection;\n    }\n    if (!isArrayLike(collection)) {\n      return eachFunc(collection, iteratee);\n    }\n    var length = collection.length,\n        index = fromRight ? length : -1,\n        iterable = Object(collection);\n\n    while ((fromRight ? index-- : ++index < length)) {\n      if (iteratee(iterable[index], index, iterable) === false) {\n        break;\n      }\n    }\n    return collection;\n  };\n}\n\nmodule.exports = createBaseEach;\n","var baseForOwn = require('./_baseForOwn'),\n    createBaseEach = require('./_createBaseEach');\n\n/**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\nvar baseEach = createBaseEach(baseForOwn);\n\nmodule.exports = baseEach;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n  this.__data__.set(value, HASH_UNDEFINED);\n  return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n  return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","var MapCache = require('./_MapCache'),\n    setCacheAdd = require('./_setCacheAdd'),\n    setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n  var index = -1,\n      length = values == null ? 0 : values.length;\n\n  this.__data__ = new MapCache;\n  while (++index < length) {\n    this.add(values[index]);\n  }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n *  else `false`.\n */\nfunction arraySome(array, predicate) {\n  var index = -1,\n      length = array == null ? 0 : array.length;\n\n  while (++index < length) {\n    if (predicate(array[index], index, array)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nmodule.exports = arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n  return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var SetCache = require('./_SetCache'),\n    arraySome = require('./_arraySome'),\n    cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n    COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n      arrLength = array.length,\n      othLength = other.length;\n\n  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n    return false;\n  }\n  // Check that cyclic values are equal.\n  var arrStacked = stack.get(array);\n  var othStacked = stack.get(other);\n  if (arrStacked && othStacked) {\n    return arrStacked == other && othStacked == array;\n  }\n  var index = -1,\n      result = true,\n      seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n  stack.set(array, other);\n  stack.set(other, array);\n\n  // Ignore non-index properties.\n  while (++index < arrLength) {\n    var arrValue = array[index],\n        othValue = other[index];\n\n    if (customizer) {\n      var compared = isPartial\n        ? customizer(othValue, arrValue, index, other, array, stack)\n        : customizer(arrValue, othValue, index, array, other, stack);\n    }\n    if (compared !== undefined) {\n      if (compared) {\n        continue;\n      }\n      result = false;\n      break;\n    }\n    // Recursively compare arrays (susceptible to call stack limits).\n    if (seen) {\n      if (!arraySome(other, function(othValue, othIndex) {\n            if (!cacheHas(seen, othIndex) &&\n                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n              return seen.push(othIndex);\n            }\n          })) {\n        result = false;\n        break;\n      }\n    } else if (!(\n          arrValue === othValue ||\n            equalFunc(arrValue, othValue, bitmask, customizer, stack)\n        )) {\n      result = false;\n      break;\n    }\n  }\n  stack['delete'](array);\n  stack['delete'](other);\n  return result;\n}\n\nmodule.exports = equalArrays;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n  var index = -1,\n      result = Array(map.size);\n\n  map.forEach(function(value, key) {\n    result[++index] = [key, value];\n  });\n  return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n  var index = -1,\n      result = Array(set.size);\n\n  set.forEach(function(value) {\n    result[++index] = value;\n  });\n  return result;\n}\n\nmodule.exports = setToArray;\n","var Symbol = require('./_Symbol'),\n    Uint8Array = require('./_Uint8Array'),\n    eq = require('./eq'),\n    equalArrays = require('./_equalArrays'),\n    mapToArray = require('./_mapToArray'),\n    setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n    COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n    dateTag = '[object Date]',\n    errorTag = '[object Error]',\n    mapTag = '[object Map]',\n    numberTag = '[object Number]',\n    regexpTag = '[object RegExp]',\n    setTag = '[object Set]',\n    stringTag = '[object String]',\n    symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n    dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n  switch (tag) {\n    case dataViewTag:\n      if ((object.byteLength != other.byteLength) ||\n          (object.byteOffset != other.byteOffset)) {\n        return false;\n      }\n      object = object.buffer;\n      other = other.buffer;\n\n    case arrayBufferTag:\n      if ((object.byteLength != other.byteLength) ||\n          !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n        return false;\n      }\n      return true;\n\n    case boolTag:\n    case dateTag:\n    case numberTag:\n      // Coerce booleans to `1` or `0` and dates to milliseconds.\n      // Invalid dates are coerced to `NaN`.\n      return eq(+object, +other);\n\n    case errorTag:\n      return object.name == other.name && object.message == other.message;\n\n    case regexpTag:\n    case stringTag:\n      // Coerce regexes to strings and treat strings, primitives and objects,\n      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n      // for more details.\n      return object == (other + '');\n\n    case mapTag:\n      var convert = mapToArray;\n\n    case setTag:\n      var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n      convert || (convert = setToArray);\n\n      if (object.size != other.size && !isPartial) {\n        return false;\n      }\n      // Assume cyclic values are equal.\n      var stacked = stack.get(object);\n      if (stacked) {\n        return stacked == other;\n      }\n      bitmask |= COMPARE_UNORDERED_FLAG;\n\n      // Recursively compare objects (susceptible to call stack limits).\n      stack.set(object, other);\n      var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n      stack['delete'](object);\n      return result;\n\n    case symbolTag:\n      if (symbolValueOf) {\n        return symbolValueOf.call(object) == symbolValueOf.call(other);\n      }\n  }\n  return false;\n}\n\nmodule.exports = equalByTag;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n      objProps = getAllKeys(object),\n      objLength = objProps.length,\n      othProps = getAllKeys(other),\n      othLength = othProps.length;\n\n  if (objLength != othLength && !isPartial) {\n    return false;\n  }\n  var index = objLength;\n  while (index--) {\n    var key = objProps[index];\n    if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n      return false;\n    }\n  }\n  // Check that cyclic values are equal.\n  var objStacked = stack.get(object);\n  var othStacked = stack.get(other);\n  if (objStacked && othStacked) {\n    return objStacked == other && othStacked == object;\n  }\n  var result = true;\n  stack.set(object, other);\n  stack.set(other, object);\n\n  var skipCtor = isPartial;\n  while (++index < objLength) {\n    key = objProps[index];\n    var objValue = object[key],\n        othValue = other[key];\n\n    if (customizer) {\n      var compared = isPartial\n        ? customizer(othValue, objValue, key, other, object, stack)\n        : customizer(objValue, othValue, key, object, other, stack);\n    }\n    // Recursively compare objects (susceptible to call stack limits).\n    if (!(compared === undefined\n          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n          : compared\n        )) {\n      result = false;\n      break;\n    }\n    skipCtor || (skipCtor = key == 'constructor');\n  }\n  if (result && !skipCtor) {\n    var objCtor = object.constructor,\n        othCtor = other.constructor;\n\n    // Non `Object` object instances with different constructors are not equal.\n    if (objCtor != othCtor &&\n        ('constructor' in object && 'constructor' in other) &&\n        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n          typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n      result = false;\n    }\n  }\n  stack['delete'](object);\n  stack['delete'](other);\n  return result;\n}\n\nmodule.exports = equalObjects;\n","var Stack = require('./_Stack'),\n    equalArrays = require('./_equalArrays'),\n    equalByTag = require('./_equalByTag'),\n    equalObjects = require('./_equalObjects'),\n    getTag = require('./_getTag'),\n    isArray = require('./isArray'),\n    isBuffer = require('./isBuffer'),\n    isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n    arrayTag = '[object Array]',\n    objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n  var objIsArr = isArray(object),\n      othIsArr = isArray(other),\n      objTag = objIsArr ? arrayTag : getTag(object),\n      othTag = othIsArr ? arrayTag : getTag(other);\n\n  objTag = objTag == argsTag ? objectTag : objTag;\n  othTag = othTag == argsTag ? objectTag : othTag;\n\n  var objIsObj = objTag == objectTag,\n      othIsObj = othTag == objectTag,\n      isSameTag = objTag == othTag;\n\n  if (isSameTag && isBuffer(object)) {\n    if (!isBuffer(other)) {\n      return false;\n    }\n    objIsArr = true;\n    objIsObj = false;\n  }\n  if (isSameTag && !objIsObj) {\n    stack || (stack = new Stack);\n    return (objIsArr || isTypedArray(object))\n      ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n      : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n  }\n  if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n    var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n        othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n    if (objIsWrapped || othIsWrapped) {\n      var objUnwrapped = objIsWrapped ? object.value() : object,\n          othUnwrapped = othIsWrapped ? other.value() : other;\n\n      stack || (stack = new Stack);\n      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n    }\n  }\n  if (!isSameTag) {\n    return false;\n  }\n  stack || (stack = new Stack);\n  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n    isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n *  1 - Unordered comparison\n *  2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n  if (value === other) {\n    return true;\n  }\n  if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n    return value !== value && other !== other;\n  }\n  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var Stack = require('./_Stack'),\n    baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n    COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n  var index = matchData.length,\n      length = index,\n      noCustomizer = !customizer;\n\n  if (object == null) {\n    return !length;\n  }\n  object = Object(object);\n  while (index--) {\n    var data = matchData[index];\n    if ((noCustomizer && data[2])\n          ? data[1] !== object[data[0]]\n          : !(data[0] in object)\n        ) {\n      return false;\n    }\n  }\n  while (++index < length) {\n    data = matchData[index];\n    var key = data[0],\n        objValue = object[key],\n        srcValue = data[1];\n\n    if (noCustomizer && data[2]) {\n      if (objValue === undefined && !(key in object)) {\n        return false;\n      }\n    } else {\n      var stack = new Stack;\n      if (customizer) {\n        var result = customizer(objValue, srcValue, key, object, source, stack);\n      }\n      if (!(result === undefined\n            ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n            : result\n          )) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nmodule.exports = baseIsMatch;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n *  equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n  return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","var isStrictComparable = require('./_isStrictComparable'),\n    keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n  var result = keys(object),\n      length = result.length;\n\n  while (length--) {\n    var key = result[length],\n        value = object[key];\n\n    result[length] = [key, value, isStrictComparable(value)];\n  }\n  return result;\n}\n\nmodule.exports = getMatchData;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n  return function(object) {\n    if (object == null) {\n      return false;\n    }\n    return object[key] === srcValue &&\n      (srcValue !== undefined || (key in Object(object)));\n  };\n}\n\nmodule.exports = matchesStrictComparable;\n","var baseIsMatch = require('./_baseIsMatch'),\n    getMatchData = require('./_getMatchData'),\n    matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n  var matchData = getMatchData(source);\n  if (matchData.length == 1 && matchData[0][2]) {\n    return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n  }\n  return function(object) {\n    return object === source || baseIsMatch(object, source, matchData);\n  };\n}\n\nmodule.exports = baseMatches;\n","var isArray = require('./isArray'),\n    isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n    reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n  if (isArray(value)) {\n    return false;\n  }\n  var type = typeof value;\n  if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n      value == null || isSymbol(value)) {\n    return true;\n  }\n  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n    (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  var memoized = function() {\n    var args = arguments,\n        key = resolver ? resolver.apply(this, args) : args[0],\n        cache = memoized.cache;\n\n    if (cache.has(key)) {\n      return cache.get(key);\n    }\n    var result = func.apply(this, args);\n    memoized.cache = cache.set(key, result) || cache;\n    return result;\n  };\n  memoized.cache = new (memoize.Cache || MapCache);\n  return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n  var result = memoize(func, function(key) {\n    if (cache.size === MAX_MEMOIZE_SIZE) {\n      cache.clear();\n    }\n    return key;\n  });\n\n  var cache = result.cache;\n  return result;\n}\n\nmodule.exports = memoizeCapped;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n  var result = [];\n  if (string.charCodeAt(0) === 46 /* . */) {\n    result.push('');\n  }\n  string.replace(rePropName, function(match, number, quote, subString) {\n    result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n  });\n  return result;\n});\n\nmodule.exports = stringToPath;\n","var isArray = require('./isArray'),\n    isKey = require('./_isKey'),\n    stringToPath = require('./_stringToPath'),\n    toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n  if (isArray(value)) {\n    return value;\n  }\n  return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n  if (typeof value == 'string' || isSymbol(value)) {\n    return value;\n  }\n  var result = (value + '');\n  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","var castPath = require('./_castPath'),\n    toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n  path = castPath(path, object);\n\n  var index = 0,\n      length = path.length;\n\n  while (object != null && index < length) {\n    object = object[toKey(path[index++])];\n  }\n  return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n  var result = object == null ? undefined : baseGet(object, path);\n  return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n  return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var castPath = require('./_castPath'),\n    isArguments = require('./isArguments'),\n    isArray = require('./isArray'),\n    isIndex = require('./_isIndex'),\n    isLength = require('./isLength'),\n    toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n  path = castPath(path, object);\n\n  var index = -1,\n      length = path.length,\n      result = false;\n\n  while (++index < length) {\n    var key = toKey(path[index]);\n    if (!(result = object != null && hasFunc(object, key))) {\n      break;\n    }\n    object = object[key];\n  }\n  if (result || ++index != length) {\n    return result;\n  }\n  length = object == null ? 0 : object.length;\n  return !!length && isLength(length) && isIndex(key, length) &&\n    (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","var baseHasIn = require('./_baseHasIn'),\n    hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n  return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","var baseIsEqual = require('./_baseIsEqual'),\n    get = require('./get'),\n    hasIn = require('./hasIn'),\n    isKey = require('./_isKey'),\n    isStrictComparable = require('./_isStrictComparable'),\n    matchesStrictComparable = require('./_matchesStrictComparable'),\n    toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n    COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n  if (isKey(path) && isStrictComparable(srcValue)) {\n    return matchesStrictComparable(toKey(path), srcValue);\n  }\n  return function(object) {\n    var objValue = get(object, path);\n    return (objValue === undefined && objValue === srcValue)\n      ? hasIn(object, path)\n      : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n  };\n}\n\nmodule.exports = baseMatchesProperty;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n  return function(object) {\n    return object == null ? undefined : object[key];\n  };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n  return function(object) {\n    return baseGet(object, path);\n  };\n}\n\nmodule.exports = basePropertyDeep;\n","var baseProperty = require('./_baseProperty'),\n    basePropertyDeep = require('./_basePropertyDeep'),\n    isKey = require('./_isKey'),\n    toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n *   { 'a': { 'b': 2 } },\n *   { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n  return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","var baseMatches = require('./_baseMatches'),\n    baseMatchesProperty = require('./_baseMatchesProperty'),\n    identity = require('./identity'),\n    isArray = require('./isArray'),\n    property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n  if (typeof value == 'function') {\n    return value;\n  }\n  if (value == null) {\n    return identity;\n  }\n  if (typeof value == 'object') {\n    return isArray(value)\n      ? baseMatchesProperty(value[0], value[1])\n      : baseMatches(value);\n  }\n  return property(value);\n}\n\nmodule.exports = baseIteratee;\n","var baseEach = require('./_baseEach');\n\n/**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction baseFilter(collection, predicate) {\n  var result = [];\n  baseEach(collection, function(value, index, collection) {\n    if (predicate(value, index, collection)) {\n      result.push(value);\n    }\n  });\n  return result;\n}\n\nmodule.exports = baseFilter;\n","var arrayFilter = require('./_arrayFilter'),\n    baseFilter = require('./_baseFilter'),\n    baseIteratee = require('./_baseIteratee'),\n    isArray = require('./isArray');\n\n/**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n *   { 'user': 'barney', 'age': 36, 'active': true },\n *   { 'user': 'fred',   'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\nfunction filter(collection, predicate) {\n  var func = isArray(collection) ? arrayFilter : baseFilter;\n  return func(collection, baseIteratee(predicate, 3));\n}\n\nmodule.exports = filter;\n","var baseIteratee = require('./_baseIteratee'),\n    isArrayLike = require('./isArrayLike'),\n    keys = require('./keys');\n\n/**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\nfunction createFind(findIndexFunc) {\n  return function(collection, predicate, fromIndex) {\n    var iterable = Object(collection);\n    if (!isArrayLike(collection)) {\n      var iteratee = baseIteratee(predicate, 3);\n      collection = keys(collection);\n      predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n    }\n    var index = findIndexFunc(collection, predicate, fromIndex);\n    return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n  };\n}\n\nmodule.exports = createFind;\n","var baseFindIndex = require('./_baseFindIndex'),\n    baseIteratee = require('./_baseIteratee'),\n    toInteger = require('./toInteger');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n *   { 'user': 'barney',  'active': false },\n *   { 'user': 'fred',    'active': false },\n *   { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\nfunction findIndex(array, predicate, fromIndex) {\n  var length = array == null ? 0 : array.length;\n  if (!length) {\n    return -1;\n  }\n  var index = fromIndex == null ? 0 : toInteger(fromIndex);\n  if (index < 0) {\n    index = nativeMax(length + index, 0);\n  }\n  return baseFindIndex(array, baseIteratee(predicate, 3), index);\n}\n\nmodule.exports = findIndex;\n","var createFind = require('./_createFind'),\n    findIndex = require('./findIndex');\n\n/**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n *   { 'user': 'barney',  'age': 36, 'active': true },\n *   { 'user': 'fred',    'age': 40, 'active': false },\n *   { 'user': 'pebbles', 'age': 1,  'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\nvar find = createFind(findIndex);\n\nmodule.exports = find;\n","var baseFlatten = require('./_baseFlatten');\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n  var length = array == null ? 0 : array.length;\n  return length ? baseFlatten(array, 1) : [];\n}\n\nmodule.exports = flatten;\n","/**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\nfunction arrayAggregator(array, setter, iteratee, accumulator) {\n  var index = -1,\n      length = array == null ? 0 : array.length;\n\n  while (++index < length) {\n    var value = array[index];\n    setter(accumulator, value, iteratee(value), array);\n  }\n  return accumulator;\n}\n\nmodule.exports = arrayAggregator;\n","var baseEach = require('./_baseEach');\n\n/**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\nfunction baseAggregator(collection, setter, iteratee, accumulator) {\n  baseEach(collection, function(value, key, collection) {\n    setter(accumulator, value, iteratee(value), collection);\n  });\n  return accumulator;\n}\n\nmodule.exports = baseAggregator;\n","var arrayAggregator = require('./_arrayAggregator'),\n    baseAggregator = require('./_baseAggregator'),\n    baseIteratee = require('./_baseIteratee'),\n    isArray = require('./isArray');\n\n/**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\nfunction createAggregator(setter, initializer) {\n  return function(collection, iteratee) {\n    var func = isArray(collection) ? arrayAggregator : baseAggregator,\n        accumulator = initializer ? initializer() : {};\n\n    return func(collection, setter, baseIteratee(iteratee, 2), accumulator);\n  };\n}\n\nmodule.exports = createAggregator;\n","var baseAssignValue = require('./_baseAssignValue'),\n    createAggregator = require('./_createAggregator');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\nvar groupBy = createAggregator(function(result, value, key) {\n  if (hasOwnProperty.call(result, key)) {\n    result[key].push(value);\n  } else {\n    baseAssignValue(result, key, [value]);\n  }\n});\n\nmodule.exports = groupBy;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n  var index = -1,\n      length = array == null ? 0 : array.length;\n\n  while (++index < length) {\n    if (comparator(value, array[index])) {\n      return true;\n    }\n  }\n  return false;\n}\n\nmodule.exports = arrayIncludesWith;\n","var SetCache = require('./_SetCache'),\n    arrayIncludes = require('./_arrayIncludes'),\n    arrayIncludesWith = require('./_arrayIncludesWith'),\n    arrayMap = require('./_arrayMap'),\n    baseUnary = require('./_baseUnary'),\n    cacheHas = require('./_cacheHas');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMin = Math.min;\n\n/**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\nfunction baseIntersection(arrays, iteratee, comparator) {\n  var includes = comparator ? arrayIncludesWith : arrayIncludes,\n      length = arrays[0].length,\n      othLength = arrays.length,\n      othIndex = othLength,\n      caches = Array(othLength),\n      maxLength = Infinity,\n      result = [];\n\n  while (othIndex--) {\n    var array = arrays[othIndex];\n    if (othIndex && iteratee) {\n      array = arrayMap(array, baseUnary(iteratee));\n    }\n    maxLength = nativeMin(array.length, maxLength);\n    caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n      ? new SetCache(othIndex && array)\n      : undefined;\n  }\n  array = arrays[0];\n\n  var index = -1,\n      seen = caches[0];\n\n  outer:\n  while (++index < length && result.length < maxLength) {\n    var value = array[index],\n        computed = iteratee ? iteratee(value) : value;\n\n    value = (comparator || value !== 0) ? value : 0;\n    if (!(seen\n          ? cacheHas(seen, computed)\n          : includes(result, computed, comparator)\n        )) {\n      othIndex = othLength;\n      while (--othIndex) {\n        var cache = caches[othIndex];\n        if (!(cache\n              ? cacheHas(cache, computed)\n              : includes(arrays[othIndex], computed, comparator))\n            ) {\n          continue outer;\n        }\n      }\n      if (seen) {\n        seen.push(computed);\n      }\n      result.push(value);\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseIntersection;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n  return function() {\n    var args = arguments,\n        index = -1,\n        length = nativeMax(args.length - start, 0),\n        array = Array(length);\n\n    while (++index < length) {\n      array[index] = args[start + index];\n    }\n    index = -1;\n    var otherArgs = Array(start + 1);\n    while (++index < start) {\n      otherArgs[index] = args[index];\n    }\n    otherArgs[start] = transform(array);\n    return apply(func, this, otherArgs);\n  };\n}\n\nmodule.exports = overRest;\n","var identity = require('./identity'),\n    overRest = require('./_overRest'),\n    setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n  return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","var isArrayLike = require('./isArrayLike'),\n    isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n *  else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n  return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","var isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\nfunction castArrayLikeObject(value) {\n  return isArrayLikeObject(value) ? value : [];\n}\n\nmodule.exports = castArrayLikeObject;\n","var arrayMap = require('./_arrayMap'),\n    baseIntersection = require('./_baseIntersection'),\n    baseRest = require('./_baseRest'),\n    castArrayLikeObject = require('./_castArrayLikeObject');\n\n/**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\nvar intersection = baseRest(function(arrays) {\n  var mapped = arrayMap(arrays, castArrayLikeObject);\n  return (mapped.length && mapped[0] === arrays[0])\n    ? baseIntersection(mapped)\n    : [];\n});\n\nmodule.exports = intersection;\n","/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n  var length = array == null ? 0 : array.length;\n  return length ? array[length - 1] : undefined;\n}\n\nmodule.exports = last;\n","var arrayMap = require('./_arrayMap'),\n    baseIntersection = require('./_baseIntersection'),\n    baseRest = require('./_baseRest'),\n    castArrayLikeObject = require('./_castArrayLikeObject'),\n    last = require('./last');\n\n/**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\nvar intersectionWith = baseRest(function(arrays) {\n  var comparator = last(arrays),\n      mapped = arrayMap(arrays, castArrayLikeObject);\n\n  comparator = typeof comparator == 'function' ? comparator : undefined;\n  if (comparator) {\n    mapped.pop();\n  }\n  return (mapped.length && mapped[0] === arrays[0])\n    ? baseIntersection(mapped, undefined, comparator)\n    : [];\n});\n\nmodule.exports = intersectionWith;\n","var baseKeys = require('./_baseKeys'),\n    getTag = require('./_getTag'),\n    isArguments = require('./isArguments'),\n    isArray = require('./isArray'),\n    isArrayLike = require('./isArrayLike'),\n    isBuffer = require('./isBuffer'),\n    isPrototype = require('./_isPrototype'),\n    isTypedArray = require('./isTypedArray');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n    setTag = '[object Set]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\nfunction isEmpty(value) {\n  if (value == null) {\n    return true;\n  }\n  if (isArrayLike(value) &&\n      (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n        isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n    return !value.length;\n  }\n  var tag = getTag(value);\n  if (tag == mapTag || tag == setTag) {\n    return !value.size;\n  }\n  if (isPrototype(value)) {\n    return !baseKeys(value).length;\n  }\n  for (var key in value) {\n    if (hasOwnProperty.call(value, key)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nmodule.exports = isEmpty;\n","var baseIsEqual = require('./_baseIsEqual');\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n  return baseIsEqual(value, other);\n}\n\nmodule.exports = isEqual;\n","var root = require('./_root');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsFinite = root.isFinite;\n\n/**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\nfunction isFinite(value) {\n  return typeof value == 'number' && nativeIsFinite(value);\n}\n\nmodule.exports = isFinite;\n","var baseGetTag = require('./_baseGetTag'),\n    isArray = require('./isArray'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n  return typeof value == 'string' ||\n    (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nmodule.exports = isString;\n","/**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\nfunction isUndefined(value) {\n  return value === undefined;\n}\n\nmodule.exports = isUndefined;\n","var baseAssignValue = require('./_baseAssignValue'),\n    createAggregator = require('./_createAggregator');\n\n/**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n *   { 'dir': 'left', 'code': 97 },\n *   { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n *   return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\nvar keyBy = createAggregator(function(result, value, key) {\n  baseAssignValue(result, key, value);\n});\n\nmodule.exports = keyBy;\n","var baseEach = require('./_baseEach'),\n    isArrayLike = require('./isArrayLike');\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n  var index = -1,\n      result = isArrayLike(collection) ? Array(collection.length) : [];\n\n  baseEach(collection, function(value, key, collection) {\n    result[++index] = iteratee(value, key, collection);\n  });\n  return result;\n}\n\nmodule.exports = baseMap;\n","var arrayMap = require('./_arrayMap'),\n    baseIteratee = require('./_baseIteratee'),\n    baseMap = require('./_baseMap'),\n    isArray = require('./isArray');\n\n/**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n *   return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n *   { 'user': 'barney' },\n *   { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\nfunction map(collection, iteratee) {\n  var func = isArray(collection) ? arrayMap : baseMap;\n  return func(collection, baseIteratee(iteratee, 3));\n}\n\nmodule.exports = map;\n","var baseAssignValue = require('./_baseAssignValue'),\n    baseForOwn = require('./_baseForOwn'),\n    baseIteratee = require('./_baseIteratee');\n\n/**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n *   'fred':    { 'user': 'fred',    'age': 40 },\n *   'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\nfunction mapValues(object, iteratee) {\n  var result = {};\n  iteratee = baseIteratee(iteratee, 3);\n\n  baseForOwn(object, function(value, key, object) {\n    baseAssignValue(result, key, iteratee(value, key, object));\n  });\n  return result;\n}\n\nmodule.exports = mapValues;\n","var baseAssignValue = require('./_baseAssignValue'),\n    eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n  if ((value !== undefined && !eq(object[key], value)) ||\n      (value === undefined && !(key in object))) {\n    baseAssignValue(object, key, value);\n  }\n}\n\nmodule.exports = assignMergeValue;\n","var baseGetTag = require('./_baseGetTag'),\n    getPrototype = require('./_getPrototype'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n    objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n *   this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n  if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n    return false;\n  }\n  var proto = getPrototype(value);\n  if (proto === null) {\n    return true;\n  }\n  var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n  return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n    funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n  if (key === 'constructor' && typeof object[key] === 'function') {\n    return;\n  }\n\n  if (key == '__proto__') {\n    return;\n  }\n\n  return object[key];\n}\n\nmodule.exports = safeGet;\n","var copyObject = require('./_copyObject'),\n    keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n *   this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n  return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n","var assignMergeValue = require('./_assignMergeValue'),\n    cloneBuffer = require('./_cloneBuffer'),\n    cloneTypedArray = require('./_cloneTypedArray'),\n    copyArray = require('./_copyArray'),\n    initCloneObject = require('./_initCloneObject'),\n    isArguments = require('./isArguments'),\n    isArray = require('./isArray'),\n    isArrayLikeObject = require('./isArrayLikeObject'),\n    isBuffer = require('./isBuffer'),\n    isFunction = require('./isFunction'),\n    isObject = require('./isObject'),\n    isPlainObject = require('./isPlainObject'),\n    isTypedArray = require('./isTypedArray'),\n    safeGet = require('./_safeGet'),\n    toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n *  counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n  var objValue = safeGet(object, key),\n      srcValue = safeGet(source, key),\n      stacked = stack.get(srcValue);\n\n  if (stacked) {\n    assignMergeValue(object, key, stacked);\n    return;\n  }\n  var newValue = customizer\n    ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n    : undefined;\n\n  var isCommon = newValue === undefined;\n\n  if (isCommon) {\n    var isArr = isArray(srcValue),\n        isBuff = !isArr && isBuffer(srcValue),\n        isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n    newValue = srcValue;\n    if (isArr || isBuff || isTyped) {\n      if (isArray(objValue)) {\n        newValue = objValue;\n      }\n      else if (isArrayLikeObject(objValue)) {\n        newValue = copyArray(objValue);\n      }\n      else if (isBuff) {\n        isCommon = false;\n        newValue = cloneBuffer(srcValue, true);\n      }\n      else if (isTyped) {\n        isCommon = false;\n        newValue = cloneTypedArray(srcValue, true);\n      }\n      else {\n        newValue = [];\n      }\n    }\n    else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n      newValue = objValue;\n      if (isArguments(objValue)) {\n        newValue = toPlainObject(objValue);\n      }\n      else if (!isObject(objValue) || isFunction(objValue)) {\n        newValue = initCloneObject(srcValue);\n      }\n    }\n    else {\n      isCommon = false;\n    }\n  }\n  if (isCommon) {\n    // Recursively merge objects and arrays (susceptible to call stack limits).\n    stack.set(srcValue, newValue);\n    mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n    stack['delete'](srcValue);\n  }\n  assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n","var Stack = require('./_Stack'),\n    assignMergeValue = require('./_assignMergeValue'),\n    baseFor = require('./_baseFor'),\n    baseMergeDeep = require('./_baseMergeDeep'),\n    isObject = require('./isObject'),\n    keysIn = require('./keysIn'),\n    safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n *  counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n  if (object === source) {\n    return;\n  }\n  baseFor(source, function(srcValue, key) {\n    stack || (stack = new Stack);\n    if (isObject(srcValue)) {\n      baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n    }\n    else {\n      var newValue = customizer\n        ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n        : undefined;\n\n      if (newValue === undefined) {\n        newValue = srcValue;\n      }\n      assignMergeValue(object, key, newValue);\n    }\n  }, keysIn);\n}\n\nmodule.exports = baseMerge;\n","var baseRest = require('./_baseRest'),\n    isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n  return baseRest(function(object, sources) {\n    var index = -1,\n        length = sources.length,\n        customizer = length > 1 ? sources[length - 1] : undefined,\n        guard = length > 2 ? sources[2] : undefined;\n\n    customizer = (assigner.length > 3 && typeof customizer == 'function')\n      ? (length--, customizer)\n      : undefined;\n\n    if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n      customizer = length < 3 ? undefined : customizer;\n      length = 1;\n    }\n    object = Object(object);\n    while (++index < length) {\n      var source = sources[index];\n      if (source) {\n        assigner(object, source, index, customizer);\n      }\n    }\n    return object;\n  });\n}\n\nmodule.exports = createAssigner;\n","var baseMerge = require('./_baseMerge'),\n    createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n *   'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n *   'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n  baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","var baseMerge = require('./_baseMerge'),\n    createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n *   if (_.isArray(objValue)) {\n *     return objValue.concat(srcValue);\n *   }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\nvar mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n  baseMerge(object, source, srcIndex, customizer);\n});\n\nmodule.exports = mergeWith;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n *   return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n  if (typeof predicate != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  return function() {\n    var args = arguments;\n    switch (args.length) {\n      case 0: return !predicate.call(this);\n      case 1: return !predicate.call(this, args[0]);\n      case 2: return !predicate.call(this, args[0], args[1]);\n      case 3: return !predicate.call(this, args[0], args[1], args[2]);\n    }\n    return !predicate.apply(this, args);\n  };\n}\n\nmodule.exports = negate;\n","var assignValue = require('./_assignValue'),\n    castPath = require('./_castPath'),\n    isIndex = require('./_isIndex'),\n    isObject = require('./isObject'),\n    toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n  if (!isObject(object)) {\n    return object;\n  }\n  path = castPath(path, object);\n\n  var index = -1,\n      length = path.length,\n      lastIndex = length - 1,\n      nested = object;\n\n  while (nested != null && ++index < length) {\n    var key = toKey(path[index]),\n        newValue = value;\n\n    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n      return object;\n    }\n\n    if (index != lastIndex) {\n      var objValue = nested[key];\n      newValue = customizer ? customizer(objValue, key, nested) : undefined;\n      if (newValue === undefined) {\n        newValue = isObject(objValue)\n          ? objValue\n          : (isIndex(path[index + 1]) ? [] : {});\n      }\n    }\n    assignValue(nested, key, newValue);\n    nested = nested[key];\n  }\n  return object;\n}\n\nmodule.exports = baseSet;\n","var baseGet = require('./_baseGet'),\n    baseSet = require('./_baseSet'),\n    castPath = require('./_castPath');\n\n/**\n * The base implementation of  `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n  var index = -1,\n      length = paths.length,\n      result = {};\n\n  while (++index < length) {\n    var path = paths[index],\n        value = baseGet(object, path);\n\n    if (predicate(value, path)) {\n      baseSet(result, castPath(path, object), value);\n    }\n  }\n  return result;\n}\n\nmodule.exports = basePickBy;\n","var arrayMap = require('./_arrayMap'),\n    baseIteratee = require('./_baseIteratee'),\n    basePickBy = require('./_basePickBy'),\n    getAllKeysIn = require('./_getAllKeysIn');\n\n/**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\nfunction pickBy(object, predicate) {\n  if (object == null) {\n    return {};\n  }\n  var props = arrayMap(getAllKeysIn(object), function(prop) {\n    return [prop];\n  });\n  predicate = baseIteratee(predicate);\n  return basePickBy(object, props, function(value, path) {\n    return predicate(value, path[0]);\n  });\n}\n\nmodule.exports = pickBy;\n","var baseIteratee = require('./_baseIteratee'),\n    negate = require('./negate'),\n    pickBy = require('./pickBy');\n\n/**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\nfunction omitBy(object, predicate) {\n  return pickBy(object, negate(baseIteratee(predicate)));\n}\n\nmodule.exports = omitBy;\n","/**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\nfunction baseSortBy(array, comparer) {\n  var length = array.length;\n\n  array.sort(comparer);\n  while (length--) {\n    array[length] = array[length].value;\n  }\n  return array;\n}\n\nmodule.exports = baseSortBy;\n","var isSymbol = require('./isSymbol');\n\n/**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\nfunction compareAscending(value, other) {\n  if (value !== other) {\n    var valIsDefined = value !== undefined,\n        valIsNull = value === null,\n        valIsReflexive = value === value,\n        valIsSymbol = isSymbol(value);\n\n    var othIsDefined = other !== undefined,\n        othIsNull = other === null,\n        othIsReflexive = other === other,\n        othIsSymbol = isSymbol(other);\n\n    if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n        (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n        (valIsNull && othIsDefined && othIsReflexive) ||\n        (!valIsDefined && othIsReflexive) ||\n        !valIsReflexive) {\n      return 1;\n    }\n    if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n        (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n        (othIsNull && valIsDefined && valIsReflexive) ||\n        (!othIsDefined && valIsReflexive) ||\n        !othIsReflexive) {\n      return -1;\n    }\n  }\n  return 0;\n}\n\nmodule.exports = compareAscending;\n","var compareAscending = require('./_compareAscending');\n\n/**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\nfunction compareMultiple(object, other, orders) {\n  var index = -1,\n      objCriteria = object.criteria,\n      othCriteria = other.criteria,\n      length = objCriteria.length,\n      ordersLength = orders.length;\n\n  while (++index < length) {\n    var result = compareAscending(objCriteria[index], othCriteria[index]);\n    if (result) {\n      if (index >= ordersLength) {\n        return result;\n      }\n      var order = orders[index];\n      return result * (order == 'desc' ? -1 : 1);\n    }\n  }\n  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n  // that causes it, under certain circumstances, to provide the same value for\n  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n  // for more details.\n  //\n  // This also ensures a stable sort in V8 and other engines.\n  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n  return object.index - other.index;\n}\n\nmodule.exports = compareMultiple;\n","var arrayMap = require('./_arrayMap'),\n    baseGet = require('./_baseGet'),\n    baseIteratee = require('./_baseIteratee'),\n    baseMap = require('./_baseMap'),\n    baseSortBy = require('./_baseSortBy'),\n    baseUnary = require('./_baseUnary'),\n    compareMultiple = require('./_compareMultiple'),\n    identity = require('./identity'),\n    isArray = require('./isArray');\n\n/**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\nfunction baseOrderBy(collection, iteratees, orders) {\n  if (iteratees.length) {\n    iteratees = arrayMap(iteratees, function(iteratee) {\n      if (isArray(iteratee)) {\n        return function(value) {\n          return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n        }\n      }\n      return iteratee;\n    });\n  } else {\n    iteratees = [identity];\n  }\n\n  var index = -1;\n  iteratees = arrayMap(iteratees, baseUnary(baseIteratee));\n\n  var result = baseMap(collection, function(value, key, collection) {\n    var criteria = arrayMap(iteratees, function(iteratee) {\n      return iteratee(value);\n    });\n    return { 'criteria': criteria, 'index': ++index, 'value': value };\n  });\n\n  return baseSortBy(result, function(object, other) {\n    return compareMultiple(object, other, orders);\n  });\n}\n\nmodule.exports = baseOrderBy;\n","var baseOrderBy = require('./_baseOrderBy'),\n    isArray = require('./isArray');\n\n/**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n *  The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n *   { 'user': 'fred',   'age': 48 },\n *   { 'user': 'barney', 'age': 34 },\n *   { 'user': 'fred',   'age': 40 },\n *   { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\nfunction orderBy(collection, iteratees, orders, guard) {\n  if (collection == null) {\n    return [];\n  }\n  if (!isArray(iteratees)) {\n    iteratees = iteratees == null ? [] : [iteratees];\n  }\n  orders = guard ? undefined : orders;\n  if (!isArray(orders)) {\n    orders = orders == null ? [] : [orders];\n  }\n  return baseOrderBy(collection, iteratees, orders);\n}\n\nmodule.exports = orderBy;\n","var createAggregator = require('./_createAggregator');\n\n/**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n *   { 'user': 'barney',  'age': 36, 'active': false },\n *   { 'user': 'fred',    'age': 40, 'active': true },\n *   { 'user': 'pebbles', 'age': 1,  'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\nvar partition = createAggregator(function(result, value, key) {\n  result[key ? 0 : 1].push(value);\n}, function() { return [[], []]; });\n\nmodule.exports = partition;\n","var root = require('./_root'),\n    toInteger = require('./toInteger'),\n    toNumber = require('./toNumber'),\n    toString = require('./toString');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsFinite = root.isFinite,\n    nativeMin = Math.min;\n\n/**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\nfunction createRound(methodName) {\n  var func = Math[methodName];\n  return function(number, precision) {\n    number = toNumber(number);\n    precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n    if (precision && nativeIsFinite(number)) {\n      // Shift with exponential notation to avoid floating-point issues.\n      // See [MDN](https://mdn.io/round#Examples) for more details.\n      var pair = (toString(number) + 'e').split('e'),\n          value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n      pair = (toString(value) + 'e').split('e');\n      return +(pair[0] + 'e' + (+pair[1] - precision));\n    }\n    return func(number);\n  };\n}\n\nmodule.exports = createRound;\n","var createRound = require('./_createRound');\n\n/**\n * Computes `number` rounded to `precision`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Math\n * @param {number} number The number to round.\n * @param {number} [precision=0] The precision to round to.\n * @returns {number} Returns the rounded number.\n * @example\n *\n * _.round(4.006);\n * // => 4\n *\n * _.round(4.006, 2);\n * // => 4.01\n *\n * _.round(4060, -2);\n * // => 4100\n */\nvar round = createRound('round');\n\nmodule.exports = round;\n","var createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\nvar snakeCase = createCompounder(function(result, word, index) {\n  return result + (index ? '_' : '') + word.toLowerCase();\n});\n\nmodule.exports = snakeCase;\n","var baseEach = require('./_baseEach');\n\n/**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n *  else `false`.\n */\nfunction baseSome(collection, predicate) {\n  var result;\n\n  baseEach(collection, function(value, index, collection) {\n    result = predicate(value, index, collection);\n    return !result;\n  });\n  return !!result;\n}\n\nmodule.exports = baseSome;\n","var arraySome = require('./_arraySome'),\n    baseIteratee = require('./_baseIteratee'),\n    baseSome = require('./_baseSome'),\n    isArray = require('./isArray'),\n    isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n *  else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n *   { 'user': 'barney', 'active': true },\n *   { 'user': 'fred',   'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\nfunction some(collection, predicate, guard) {\n  var func = isArray(collection) ? arraySome : baseSome;\n  if (guard && isIterateeCall(collection, predicate, guard)) {\n    predicate = undefined;\n  }\n  return func(collection, baseIteratee(predicate, 3));\n}\n\nmodule.exports = some;\n","var baseFlatten = require('./_baseFlatten'),\n    baseOrderBy = require('./_baseOrderBy'),\n    baseRest = require('./_baseRest'),\n    isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n *  The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n *   { 'user': 'fred',   'age': 48 },\n *   { 'user': 'barney', 'age': 36 },\n *   { 'user': 'fred',   'age': 30 },\n *   { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\nvar sortBy = baseRest(function(collection, iteratees) {\n  if (collection == null) {\n    return [];\n  }\n  var length = iteratees.length;\n  if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n    iteratees = [];\n  } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n    iteratees = [iteratees[0]];\n  }\n  return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n});\n\nmodule.exports = sortBy;\n","var createCompounder = require('./_createCompounder'),\n    upperFirst = require('./upperFirst');\n\n/**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\nvar startCase = createCompounder(function(result, word, index) {\n  return result + (index ? ' ' : '') + upperFirst(word);\n});\n\nmodule.exports = startCase;\n","/**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\nfunction baseSum(array, iteratee) {\n  var result,\n      index = -1,\n      length = array.length;\n\n  while (++index < length) {\n    var current = iteratee(array[index]);\n    if (current !== undefined) {\n      result = result === undefined ? current : (result + current);\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseSum;\n","var baseSum = require('./_baseSum'),\n    identity = require('./identity');\n\n/**\n * Computes the sum of the values in `array`.\n *\n * @static\n * @memberOf _\n * @since 3.4.0\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {number} Returns the sum.\n * @example\n *\n * _.sum([4, 2, 8, 6]);\n * // => 20\n */\nfunction sum(array) {\n  return (array && array.length)\n    ? baseSum(array, identity)\n    : 0;\n}\n\nmodule.exports = sum;\n","var Set = require('./_Set'),\n    noop = require('./noop'),\n    setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n  return new Set(values);\n};\n\nmodule.exports = createSet;\n","var SetCache = require('./_SetCache'),\n    arrayIncludes = require('./_arrayIncludes'),\n    arrayIncludesWith = require('./_arrayIncludesWith'),\n    cacheHas = require('./_cacheHas'),\n    createSet = require('./_createSet'),\n    setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n  var index = -1,\n      includes = arrayIncludes,\n      length = array.length,\n      isCommon = true,\n      result = [],\n      seen = result;\n\n  if (comparator) {\n    isCommon = false;\n    includes = arrayIncludesWith;\n  }\n  else if (length >= LARGE_ARRAY_SIZE) {\n    var set = iteratee ? null : createSet(array);\n    if (set) {\n      return setToArray(set);\n    }\n    isCommon = false;\n    includes = cacheHas;\n    seen = new SetCache;\n  }\n  else {\n    seen = iteratee ? [] : result;\n  }\n  outer:\n  while (++index < length) {\n    var value = array[index],\n        computed = iteratee ? iteratee(value) : value;\n\n    value = (comparator || value !== 0) ? value : 0;\n    if (isCommon && computed === computed) {\n      var seenIndex = seen.length;\n      while (seenIndex--) {\n        if (seen[seenIndex] === computed) {\n          continue outer;\n        }\n      }\n      if (iteratee) {\n        seen.push(computed);\n      }\n      result.push(value);\n    }\n    else if (!includes(seen, computed, comparator)) {\n      if (seen !== result) {\n        seen.push(computed);\n      }\n      result.push(value);\n    }\n  }\n  return result;\n}\n\nmodule.exports = baseUniq;\n","var baseUniq = require('./_baseUniq');\n\n/**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\nfunction uniq(array) {\n  return (array && array.length) ? baseUniq(array) : [];\n}\n\nmodule.exports = uniq;\n","var baseIteratee = require('./_baseIteratee'),\n    baseUniq = require('./_baseUniq');\n\n/**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\nfunction uniqBy(array, iteratee) {\n  return (array && array.length) ? baseUniq(array, baseIteratee(iteratee, 2)) : [];\n}\n\nmodule.exports = uniqBy;\n","var baseUniq = require('./_baseUniq');\n\n/**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\nfunction uniqWith(array, comparator) {\n  comparator = typeof comparator == 'function' ? comparator : undefined;\n  return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n}\n\nmodule.exports = uniqWith;\n","var arrayMap = require('./_arrayMap');\n\n/**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\nfunction baseValues(object, props) {\n  return arrayMap(props, function(key) {\n    return object[key];\n  });\n}\n\nmodule.exports = baseValues;\n","var baseValues = require('./_baseValues'),\n    keys = require('./keys');\n\n/**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n *   this.a = 1;\n *   this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\nfunction values(object) {\n  return object == null ? [] : baseValues(object, keys(object));\n}\n\nmodule.exports = values;\n","import { ModifiedAddress } from \"../types\";\nimport { capitalize, isArray, isEmpty } from \"@/utils/nodash\";\n\nconst addressParser = (addr: ModifiedAddress) => {\n  if (addr.text) return addr.text;\n  let result = \"\";\n\n  result += addr.use ? `${capitalize(addr.use)}: ` : \"\";\n  result += !isEmpty(addr.line) ? `${addr.line?.join(\"\\n\")}\\n` : \"\";\n  result += addr.city ? `${addr.city}, ` : \"\";\n  result += addr.state ? `${addr.state} ` : \"\";\n  result += addr.postalCode || \"\";\n  result += addr.country ? `\\n${addr.country}` : \"\";\n\n  return result;\n};\n\nexport const displayForAddress = (address: ModifiedAddress | ModifiedAddress[]): string => {\n  if (isEmpty(address)) return \"\";\n\n  if (isArray(address)) return address.map(addressParser).join(\"\\n\");\n\n  return addressParser(address);\n};\n","import { ModifiedHumanName } from \"../types\";\nimport { isArray, isEmpty } from \"@/utils/nodash\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isHumanNameArray(data: any): data is ModifiedHumanName[] {\n  return isArray(data) && data.every((name) => typeof name === \"object\");\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isStringArray(data: any): data is string[] {\n  return isArray(data) && data.every((name) => typeof name === \"string\");\n}\n\nconst nameParser = (name: ModifiedHumanName) => {\n  if (name.text) return name.text;\n  let displayName = \"\";\n  if (name.given && name.given.length > 0) {\n    displayName = name.given.join(\" \");\n    if (name.family) displayName = `${displayName} ${name.family}`;\n  }\n  if (name.prefix && name.prefix.length > 0) {\n    displayName = `${name.prefix.join(\" \")} ${displayName}`;\n  }\n  return displayName;\n};\n\nexport const displayForName = (\n  humanName: ModifiedHumanName[] | ModifiedHumanName | string | string[]\n): string => {\n  if (isEmpty(humanName)) return \"\";\n\n  if (typeof humanName === \"string\") return humanName;\n\n  if (isStringArray(humanName)) {\n    return humanName.reduce((acc, val, index) => {\n      const withNewLine = index === 0 ? \"\" : \"\\n\";\n      return `${acc}${withNewLine}${val}`;\n    }, \"\");\n  }\n\n  if (isHumanNameArray(humanName)) return humanName.map(nameParser).join(\", \");\n\n  return nameParser(humanName);\n};\n","import { ModifiedContactPoint } from \"../types\";\nimport { capitalize, isArray, isEmpty } from \"@/utils/nodash\";\n\nconst telecomParser = ({ use, system, value }: ModifiedContactPoint) => {\n  const withUse = use ? ` (${use})` : \"\";\n  const withSystem = system ? `${capitalize(system)}${withUse}:` : \"\";\n  return `${withSystem} ${value}`.trim();\n};\n\nexport const displayForTelecom = (\n  telecom: ModifiedContactPoint | ModifiedContactPoint[]\n): string => {\n  if (isEmpty(telecom)) return \"\";\n\n  if (isArray(telecom)) return telecom.map(telecomParser).join(\"\\n\");\n\n  return telecomParser(telecom);\n};\n","import xpath from \"xpath\";\nimport { displayForAddress } from \"./displayForAddress\";\nimport { ModifiedAddress } from \"../types\";\nimport { isArray, map } from \"@/utils/nodash\";\n\nexport const addressUseMap: Record<string, string> = {\n  BAD: \"bad\",\n  DIR: \"direct\",\n  H: \"home\",\n  HP: \"primary home\",\n  HV: \"vacation home\",\n  PHYS: \"physical\",\n  PST: \"postal\",\n  PUB: \"public\",\n  TMP: \"temporary\",\n  WP: \"work\",\n  CONF: \"confidential\",\n};\n\nexport const getAddress = (address: Document | Document[] | undefined): string => {\n  if (!address) return \"\";\n\n  const parser = (addressXml: Document) => {\n    const use = String(xpath.select1(\"string(@use)\", addressXml));\n\n    const addr: ModifiedAddress = {\n      line: map(xpath.select(\"*[name()='streetAddressLine']\", addressXml) as Document[], (l) =>\n        String(xpath.select(\"string(text())\", l))\n      ).filter(Boolean),\n      city: String(xpath.select(\"string(*[name()='city'])\", addressXml)),\n      state: String(xpath.select(\"string(*[name()='state'])\", addressXml)),\n      postalCode: String(xpath.select(\"string(*[name()='postalCode'])\", addressXml)),\n      country: String(xpath.select(\"string(*[name()='country'])\", addressXml)),\n      use: addressUseMap[use],\n    };\n\n    return displayForAddress(addr);\n  };\n\n  if (isArray(address)) return address.map(parser).join(\"\\n\");\n\n  return parser(address);\n};\n","import xpath from \"xpath\";\nimport { displayForTelecom } from \"./displayForTelecom\";\nimport { ModifiedContactPoint } from \"../types\";\nimport { isArray } from \"@/utils/nodash\";\n\nexport const contactPointUseMap: Record<string, string> = {\n  BAD: \"bad\",\n  CONF: \"confidential\",\n  OLD: \"old\",\n  H: \"home\",\n  HP: \"primary home\",\n  HV: \"vacation Home\",\n  TMP: \"temporary\",\n  WP: \"work\",\n  DIR: \"direct\",\n  PUB: \"public\",\n  AS: \"answering service\",\n  EC: \"emergency:\",\n  MC: \"mobile\",\n  PG: \"pager\",\n};\n\nexport const contactPointTelecomMap: Record<string, string> = {\n  tel: \"phone\",\n  mailto: \"email\",\n};\n\nexport const getTelecom = (telecom?: Document | Document[]): string => {\n  if (!telecom) return \"\";\n\n  const parser = (telecomXml: Document) => {\n    const valueFromTag = String(xpath.select1(\"string(@value)\", telecomXml));\n\n    const splitValue = valueFromTag.split(\":\");\n\n    let system;\n    let value;\n    if (splitValue.length === 2) [system, value] = splitValue;\n\n    if (splitValue.length === 1) [value] = splitValue;\n\n    if (!value) return \"\";\n\n    const backupSystem = value.includes(\"@\")\n      ? contactPointTelecomMap.mailto\n      : contactPointTelecomMap.tel;\n\n    const finalSystem = contactPointTelecomMap[system as string] || backupSystem;\n\n    const contactPoint: ModifiedContactPoint = {\n      system: finalSystem,\n      value,\n      use: contactPointUseMap[String(xpath.select1(\"string(@use)\", telecomXml))],\n    };\n    return displayForTelecom(contactPoint);\n  };\n\n  if (isArray(telecom)) return telecom.map(parser).join(\"\\n\");\n\n  return parser(telecom);\n};\n","import { getAddress } from \"./getAddress\";\nimport { getTelecom } from \"./getTelecom\";\n\nexport const getContactDetails = (\n  addressXml: Document | Document[],\n  telecomXml: Document | Document[]\n): string => {\n  const address = getAddress(addressXml);\n  const telecom = getTelecom(telecomXml);\n\n  return `${address || \"\"}${address && telecom ? \"\\n\" : \"\"}${telecom || \"\"}`;\n};\n","import xpath from \"xpath\";\nimport { displayForName } from \"./displayForName\";\nimport { ModifiedHumanName } from \"../types\";\nimport { isArray, map } from \"@/utils/nodash\";\n\nconst humanNameUseMap: Record<string, string> = {\n  A: \"Artist/Stage\",\n  ABC: \"Alphabetic\",\n  ASGN: \"Assigned\",\n  C: \"License\",\n  I: \"Indigenous/Tribal\",\n  IDE: \"Ideographic\",\n  L: \"Legal\",\n  P: \"Pseudonym\",\n  PHON: \"Phonetic\",\n  R: \"Religious\",\n  SNDX: \"Soundex\",\n  SRCH: \"Search\",\n  SYL: \"Syllabic\",\n};\n\nexport const getHumanName = (name?: Document | Document[]): string => {\n  if (!name) return \"\";\n\n  const parser = (nameXml: Document) => {\n    const patientParsedName: ModifiedHumanName = {\n      use: humanNameUseMap[String(xpath.select(\"string(@use)\", nameXml))],\n      given: map(xpath.select(\"(*[name()='given'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n      family: String(xpath.select1(\"string(*[name()='family']/text())\", nameXml)),\n      prefix: map(xpath.select(\"(*[name()='prefix'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n      suffix: map(xpath.select(\"(*[name()='suffix'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n    };\n    return displayForName(patientParsedName);\n  };\n\n  if (isArray(name)) return name.map(parser).join(\"\\n\");\n\n  return parser(name);\n};\n","import xpath from \"xpath\";\n\nexport const getId = (id: Document | undefined): string => {\n  if (!id) return \"\";\n\n  const rootValue = String(xpath.select1(\"string(@root)\", id));\n\n  const extensionValue = String(xpath.select1(\"string(@extension)\", id));\n\n  return `${extensionValue}${extensionValue ? \" (\" : \"\"}${rootValue}${extensionValue ? \")\" : \"\"}`;\n};\n","import { isFinite } from \"@/utils/nodash\";\n\n/**\n * Estimates the index of the timezone sign counting from the end of the string and the type of the sign itself (\"-\" or \"+\")\n *\n *\n * @param date Raw date from C-CDA\n * @returns Index of the timezone signs from the end and sign timezone itself\n *\n */\nconst getIndexFromEnd = (date: string): { index: number; timezoneSign?: \"+\" | \"-\" } => {\n  const rawDate = date.replace(/:/g, \"\");\n  const plusSign = rawDate.lastIndexOf(\"+\");\n  const minusSign = rawDate.lastIndexOf(\"-\");\n\n  if (plusSign > 0) {\n    // need to subtract 1 to count the array from the end from 0 index\n    return { index: rawDate.length - plusSign - 1, timezoneSign: \"+\" };\n  }\n\n  if (minusSign > 0) {\n    // check if \"-\" sign is for timezone, it is needed to correctly parse such date 2013-02-2209\n    const signOnThreePlacesLeft = rawDate[minusSign - 3];\n    if (\n      isFinite(Number(signOnThreePlacesLeft)) ||\n      signOnThreePlacesLeft === \"T\" // needed to correctly parse such date 2013-02-22T09-05:00\n    ) {\n      // need to subtract 1 to count the array from the end from 0 index\n      return { index: rawDate.length - minusSign - 1, timezoneSign: \"-\" };\n    }\n\n    return { index: -1 };\n  }\n  return { index: -1 };\n};\n\n/**\n * Checks if fragment of the date is valid.\n *\n *\n * @param fragment Fragment of the date (year, month, day, hour, minute, second)\n * @returns True if valid, otherwise false\n *\n */\nconst isCorrectValue = (fragment: string) =>\n  fragment && fragment.length > 1 && fragment.split(\"\").every((char) => isFinite(Number(char)));\n\nconst constructISOString = ({\n  year,\n  month,\n  day,\n  hour,\n  minute,\n  second,\n  timezoneHour,\n  timezoneMinute,\n  timezoneSign,\n}: {\n  year: string;\n  month: string;\n  day: string;\n  hour: string;\n  minute: string;\n  second: string;\n  timezoneHour: string;\n  timezoneMinute: string;\n  timezoneSign: string | undefined;\n}): string => {\n  let result = \"\";\n\n  if (isCorrectValue(year)) {\n    result += year;\n    if (isCorrectValue(month)) {\n      result += `-${month}`;\n      if (isCorrectValue(day)) {\n        result += `-${day}`;\n        if (isCorrectValue(hour)) {\n          result += `T${hour}`;\n\n          if (isCorrectValue(minute)) result += `:${minute}`;\n          else result += \":00\";\n\n          if (isCorrectValue(second)) result += `:${second}`;\n          else result += \":00\";\n\n          if (timezoneSign && isCorrectValue(timezoneHour)) {\n            result += `${timezoneSign}${timezoneHour}`;\n            if (isCorrectValue(timezoneMinute)) result += `:${timezoneMinute}`;\n            else result += \":00\";\n          } else result += \"-00:00\";\n        }\n      }\n    }\n  }\n  return result;\n};\n\n/**\n * Convert a raw date from C-CDA to ISOString.\n *\n *\n * @param rawDate Raw date from C-CDA\n * @returns Date in ISOString format\n *\n */\nexport const parseToISOString = (rawDate: string): string => {\n  if (!rawDate) return \"\";\n\n  const { index, timezoneSign } = getIndexFromEnd(rawDate);\n  // delete all junk that can be in date in C-CDA document\n  let date = rawDate\n    .replace(/T/g, \"\")\n    .replace(/-/g, \"\")\n    // plus sign can be only once, no need for regexp\n    .replace(\"+\", \"\")\n    .replace(/:/g, \"\");\n\n  let timezone = \"\";\n\n  // if sign index from the end is equal to 4 (-0500) or 2 (-05) and date has at least hour it means that there is a timezone\n  if ((index === 4 || index === 2) && date.length > 9) {\n    timezone = date.substring(date.length - index);\n    date = date.substring(0, date.length - index);\n  }\n\n  const year = date.slice(0, 4);\n  const month = date.slice(4, 6);\n  const day = date.slice(6, 8);\n  const hour = date.slice(8, 10);\n  const minute = date.slice(10, 12);\n  const second = date.slice(12, 14);\n\n  const timezoneHour = timezone.slice(0, 2);\n  const timezoneMinute = timezone.slice(2);\n\n  if (!day) return \"\";\n\n  return constructISOString({\n    year,\n    month,\n    day,\n    hour,\n    minute,\n    second,\n    timezoneHour,\n    timezoneMinute,\n    timezoneSign,\n  });\n};\n","import { isBefore, isEqual } from \"date-fns\";\nimport { Period } from \"fhir/r4\";\nimport xpath from \"xpath\";\nimport { parseToISOString } from \"./parseToISOString\";\n\nexport const getPeriod = (xmlData?: Document): Period => {\n  if (!xmlData) return {};\n\n  const low = String(xpath.select1(\"string(*[name()='low']/@value)\", xmlData));\n  const high = String(xpath.select1(\"string(*[name()='high']/@value)\", xmlData));\n\n  if (!low && !high) return {};\n\n  if (low && !high) {\n    return {\n      start: parseToISOString(low),\n    };\n  }\n\n  if (!low && high) {\n    return {\n      end: parseToISOString(high),\n    };\n  }\n\n  let start = parseToISOString(low);\n  let end = parseToISOString(high);\n\n  // it indicates that at least on of the dates has minutes so both have to be parsed to iso string\n  if (start.includes(\"T\") || end.includes(\"T\")) {\n    start = parseToISOString(start);\n    end = parseToISOString(end);\n  }\n\n  if (isBefore(new Date(start), new Date(end)) || isEqual(new Date(start), new Date(end))) {\n    return { start, end };\n  }\n\n  return { start };\n};\n","import { escapeRegExp, identity, isArray } from \"@/utils/nodash\";\n\nconst replaceInXML = (\n  xmlString: string,\n  toReplace: string | string[],\n  toReplaceWith: string,\n  escape = true,\n): string => {\n  if (isArray(toReplace)) {\n    return toReplace.reduce((acc, val) => replaceInXML(acc, val, toReplaceWith), xmlString);\n  }\n\n  const modify: (_: string) => string = escape ? escapeRegExp : identity;\n  return xmlString.replace(new RegExp(modify(toReplace), \"g\"), toReplaceWith);\n};\n\nconst replaceTag = (xmlString: string, oldTag: string, newTag: string) => {\n  const oldTags = [`</${oldTag}>`, `<${oldTag}>`, `</${oldTag}`, `<${oldTag}`];\n  const newTags = [`</${newTag}>`, `<${newTag}>`, `</${newTag}`, `<${newTag}`];\n\n  return oldTags.reduce(\n    (acc, _, index) => replaceInXML(acc, oldTags[index], newTags[index]),\n    xmlString,\n  );\n};\n\nexport const fixHtml = (xmlData: Element): string => {\n  let fixedHtml = xmlData.toString();\n\n  // these are not needed at all\n  fixedHtml = replaceInXML(\n    fixedHtml,\n    [\n      \"<list/>\",\n      \"<item/>\",\n      \"<content/>\",\n      \"<paragraph/>\",\n      \"<section/>\",\n      \"<br/>\",\n      '<text xmlns=\"urn:hl7-org:v3\">',\n      \"<text />\",\n      \"<text/>\",\n    ],\n    \"\",\n  );\n\n  // there can be more strange attributes in C-CDA that need to be changed\n  fixedHtml = replaceInXML(fixedHtml, ' styleCode=\"(.*?)\"', \"\", false);\n\n  fixedHtml = replaceTag(fixedHtml, \"section\", \"div\");\n  fixedHtml = replaceTag(fixedHtml, \"list\", \"ul\");\n  fixedHtml = replaceTag(fixedHtml, \"item\", \"li\");\n  fixedHtml = replaceTag(fixedHtml, \"content\", \"div\");\n  fixedHtml = replaceTag(fixedHtml, \"paragraph\", \"p\");\n\n  return fixedHtml;\n};\n","import { format } from \"date-fns\";\n\nexport const formatDate = (isoDate: string | undefined): string => {\n  if (!isoDate) return \"\";\n  const [date, time = \"\"] = isoDate.split(\"T\");\n\n  return (\n    format(new Date(date), \"MMMM dd, yyyy\") +\n    (time.split(\"\").some((char) => Number(char) > 0) ? `, ${time}` : \"\")\n  );\n};\n","type GeneralInfo = {\n  name: string;\n  contactDetails: string;\n};\n\ntype ExtendedGeneralInfo = GeneralInfo & {\n  relationship?: string;\n  time?: string;\n  functionCode?: string;\n};\n\ntype GeneralInfoWithOrg = GeneralInfo & {\n  organization: GeneralInfo;\n};\n\nexport const isGeneralInfoExist = (item: GeneralInfo | undefined): item is GeneralInfo => !!item;\n\nexport const isExtendedGeneralInfoExist = (\n  item: ExtendedGeneralInfo | undefined\n): item is ExtendedGeneralInfo => !!item;\n\nexport type { GeneralInfo, ExtendedGeneralInfo, GeneralInfoWithOrg };\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName, parseToISOString } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthenticatorData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const authenticators = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='authenticator']\",\n    document\n  ) as Document[];\n  if (isEmpty(authenticators)) return undefined;\n  return authenticators\n    .map((authenticator): ExtendedGeneralInfo | undefined => {\n      const assignedEntity = xpath.select1(\"*[name()='assignedEntity']\", authenticator) as\n        | Document\n        | undefined;\n      if (!assignedEntity) return undefined;\n      const assignedPerson = xpath.select1(\n        \"*[name()='assignedPerson']\",\n        assignedEntity\n      ) as Document;\n      const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n      const contactDetails = getContactDetails(\n        xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n        xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n      );\n\n      const time = parseToISOString(\n        String(xpath.select1(\"string(*[name()='time']/@value)\", authenticator))\n      );\n      return { name, contactDetails, time };\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","/* eslint-disable react/no-array-index-key */\nimport React from \"react\";\nimport { TableInfo } from \"../../types\";\nimport \"../../../styles.scss\";\n\ntype TdProps = {\n  dataChunk: TableInfo[];\n  indexKey: number;\n  chunkSize?: 2 | 3;\n};\nexport const BasicRow = ({ dataChunk, indexKey, chunkSize }: TdProps): JSX.Element | null => {\n  if (!dataChunk[0].value && !dataChunk[1]?.value && !dataChunk[2]?.value) {\n    return null;\n  }\n\n  let last: TableInfo | null = null;\n  let newDataChunk = dataChunk;\n  if (chunkSize === 3) {\n    newDataChunk = dataChunk.slice(0, 2);\n    [last] = dataChunk.slice(2);\n  }\n\n  return (\n    <>\n      <tr>\n        {newDataChunk.map((singleData, index) => {\n          if (!singleData.value) return null;\n          let colSpan = 1;\n          if (\n            (index === 0 && (!newDataChunk[index + 1] || !newDataChunk[index + 1].value)) ||\n            (index === 1 && (!newDataChunk[index - 1] || !newDataChunk[index - 1].value))\n          ) {\n            colSpan = 3;\n          }\n\n          return (\n            <React.Fragment\n              key={`${newDataChunk[0].label}-${String(\n                newDataChunk[0].value\n              )}-${index}-${indexKey}-${newDataChunk[1]?.label || \"\"}-${\n                newDataChunk[1]?.value || \"\"\n              }`}\n            >\n              <td\n                className=\"ctw-ccda-common-td1\"\n                rowSpan={last && last.value && index === 0 ? 2 : 1}\n              >\n                {singleData.label.replace(/:/g, \"\")}\n              </td>\n              <td\n                className=\"ctw-ccda-common-td2\"\n                colSpan={colSpan}\n                rowSpan={last && last.value && index === 0 ? 2 : 1}\n              >\n                {singleData.value}\n              </td>\n            </React.Fragment>\n          );\n        })}\n      </tr>\n      {last && last.value && (\n        <tr>\n          <td className=\"ctw-ccda-common-td1\">{last.label.replace(/:/g, \"\")}</td>\n          <td className=\"ctw-ccda-common-td2\">{last.value}</td>\n        </tr>\n      )}\n    </>\n  );\n};\n","/* eslint-disable react/no-array-index-key */\nimport React from \"react\";\nimport { TableInfo } from \"../../types\";\nimport \"../../../styles.scss\";\n\ntype TdProps = {\n  tuple: [TableInfo, TableInfo];\n  indexKey: number;\n};\nexport const TupleRow = ({ tuple, indexKey }: TdProps): JSX.Element | null => {\n  if (!tuple[0].value && !tuple[1].value) return null;\n\n  return (\n    <tr>\n      {tuple.map((singleData, index) => {\n        if (!singleData.value) return null;\n        let colSpan = 1;\n        if ((index === 0 && !tuple[1].value) || (index === 1 && !tuple[0].value)) {\n          colSpan = 3;\n        }\n\n        return (\n          <React.Fragment\n            key={`${tuple[0].label}-${tuple[0].value}-${index}-${indexKey}-${\n              tuple[1].label || \"\"\n            }-${tuple[1].value}`}\n          >\n            <td className=\"ctw-ccda-common-td1\">{singleData.label.replace(/:/g, \"\")}</td>\n            <td className=\"ctw-ccda-common-td2\" colSpan={colSpan}>\n              {singleData.value}\n            </td>\n          </React.Fragment>\n        );\n      })}\n    </tr>\n  );\n};\n","/* eslint-disable react/no-array-index-key */\nimport { BasicRow } from \"./BasicRow\";\nimport { TupleRow } from \"./TupleRow\";\nimport { TableInfo } from \"../../types\";\nimport { chunk, isArray, partition } from \"@/utils/nodash\";\nimport \"../../../styles.scss\";\n\ntype TableProps = {\n  data: (TableInfo | [TableInfo, TableInfo])[];\n  chunkSize?: 2 | 3;\n};\n\nexport const Table = ({ data, chunkSize = 2 }: TableProps): JSX.Element => {\n  const [normalEntries, tupleEntries] = partition(data, (d) => !isArray(d)) as [\n    TableInfo[],\n    [TableInfo, TableInfo][],\n  ];\n\n  const entries = chunk(normalEntries, chunkSize);\n\n  //    overflow: auto;\n  //   display: block;\n\n  return (\n    <table className=\"ctw-ccda-common-table\">\n      <tbody>\n        {entries.map((dataChunk: TableInfo[], index) => (\n          <BasicRow\n            key={`${dataChunk[0].label}-${index}`}\n            dataChunk={dataChunk}\n            chunkSize={chunkSize}\n            indexKey={index}\n          />\n        ))}\n        {tupleEntries.map((tuple: [TableInfo, TableInfo], index) => (\n          <TupleRow\n            key={`${tuple[0].label}-${tuple[1].label}-${index}`}\n            tuple={tuple}\n            indexKey={index}\n          />\n        ))}\n      </tbody>\n    </table>\n  );\n};\n","import { getAuthenticatorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Authenticator = ({ document }: DocumentOnlyProps): JSX.Element | null => {\n  const authenticators = getAuthenticatorData(document);\n\n  if (!authenticators || isEmpty(authenticators)) return null;\n\n  const finalData = authenticators.flatMap((authenticator) => [\n    {\n      label: \"Authenticator\",\n      value: `${authenticator.name || \"Unknown\"}${\n        authenticator.time ? ` signed at ${authenticator.time}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: authenticator.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getHumanName, parseToISOString } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthor = (document: Document): Record<string, LabelValueType[]> | undefined => {\n  const authors = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='author']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(authors)) return undefined;\n\n  const result = authors.map((author): LabelValueType[] => {\n    const personName = xpath.select1(\n      \"*[name()='assignedAuthor']/*[name()='assignedPerson']/*[name()='name']\",\n      author\n    ) as Document | undefined;\n    const deviceName = xpath.select1(\n      \"*[name()='assignedAuthor']/*[name()='assignedAuthoringDevice']\",\n      author\n    ) as Document | undefined;\n\n    let name = \"\";\n\n    if (personName) name = getHumanName(personName);\n    else if (deviceName) {\n      const manufacturerModelName = String(\n        xpath.select1(\"string(*[name()='manufacturerModelName'])\", deviceName)\n      );\n      const softwareName = String(xpath.select1(\"string(*[name()='softwareName'])\", deviceName));\n\n      name = [manufacturerModelName, softwareName].filter(Boolean).join(\"; \");\n    }\n    const representedOrganizationName = String(\n      xpath.select1(\n        \"string(*[name()='assignedAuthor']/*[name()='representedOrganization']/*[name()='name'])\",\n        author\n      )\n    );\n\n    const authoredOn = parseToISOString(String(xpath.select1(\"string(*[name()='time'])\", author)));\n\n    return [\n      { label: \"Name:\", value: name },\n      { label: \"Organization:\", value: representedOrganizationName },\n      { label: \"Authored on\", value: authoredOn },\n    ];\n  });\n\n  return result.reduce((acc, val, index) => ({ ...acc, [`author${index + 1}`]: val }), {});\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { GeneralInfoWithOrg, LabelValueType } from \"../../types\";\nimport { getAuthor as getAuthorDataFromHeader } from \"../Header/data/getAuthor\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthorData = (document: Document): GeneralInfoWithOrg[] | undefined => {\n  const authorXmls = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='author']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(authorXmls)) return undefined;\n\n  const authors = getAuthorDataFromHeader(document) as Record<string, LabelValueType[]>; // we can cast because we are sure that authors exist\n\n  return authorXmls.map((authorXml, index) => {\n    const assignedAuthor = xpath.select1(\"*[name()='assignedAuthor']\", authorXml) as Document;\n\n    const authorContactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", assignedAuthor) as Document[],\n      xpath.select(\"*[name()='telecom']\", assignedAuthor) as Document[]\n    );\n\n    const representedOrganization = xpath.select1(\n      \"*[name()='representedOrganization']\",\n      assignedAuthor\n    ) as Document | undefined;\n\n    const result: GeneralInfoWithOrg = {\n      name: authors[`author${index + 1}`][0].value,\n      contactDetails: authorContactDetails,\n      organization: {\n        name: authors[`author${index + 1}`][1].value,\n        contactDetails: \"\",\n      },\n    };\n\n    if (representedOrganization) {\n      const organizationContactDetails = getContactDetails(\n        xpath.select(\"*[name()='addr']\", representedOrganization) as Document[],\n        xpath.select(\"*[name()='telecom']\", representedOrganization) as Document[]\n      );\n\n      return {\n        ...result,\n        organization: {\n          ...result.organization,\n          contactDetails: organizationContactDetails,\n        },\n      };\n    }\n\n    return result;\n  });\n};\n","import { getAuthorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Author = ({ document }: DocumentOnlyProps) => {\n  const authors = getAuthorData(document);\n\n  if (!authors || isEmpty(authors)) return null;\n\n  const finalData = authors.flatMap((author) => [\n    {\n      label: \"Author\",\n      value: `${author.name || \"Unknown\"}${\n        author.organization.name ? `, Organization: ${author.organization.name}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: author.contactDetails,\n    },\n    {\n      label: \"Contact Details (Organization)\",\n      value: author.organization.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} chunkSize={3} />;\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getConsent = (document: Document): Record<string, LabelValueType[]> | undefined => {\n  const consents = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='authorization']/*[name()='consent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(consents)) return undefined;\n\n  const result = consents.map((consent) => {\n    const id = getId(xpath.select1(\"*[name()='id']\", consent) as Document);\n    const code = String(xpath.select1(\"string(*[name()='code']/@displayName)\", consent));\n    const status = String(xpath.select1(\"string(*[name()='statusCode']/@code)\", consent));\n    return [\n      { label: \"ID:\", value: id },\n      { label: \"Code:\", value: code },\n      { label: \"Status:\", value: status },\n    ];\n  });\n\n  return result.reduce((acc, order, index) => ({ ...acc, [`consent${index + 1}`]: order }), {});\n};\n","import { getConsent as getConsentDataFromHeader } from \"../Header/data/getConsent\";\n\nexport const getAuthorizationData = (document: Document) => {\n  const inFulfillmentOf = getConsentDataFromHeader(document);\n\n  return Object.values(inFulfillmentOf || {});\n};\n","import { getAuthorizationData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Authorization = ({ document }: DocumentOnlyProps) => {\n  const authorizations = getAuthorizationData(document);\n\n  if (isEmpty(authorizations)) return null;\n\n  const finalData = authorizations.flatMap((authorization) => [\n    {\n      label: \"Consent\",\n      value: `Order: ${authorization[0].value || \"Unknown\"}, ${\n        authorization[1].value || \"Unknown\"\n      }, ${authorization[2].value || \"Unknown\"}`,\n    },\n    { label: \"\", value: \"\" },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { GeneralInfo } from \"../../types\";\n\nexport const getCustodianData = (document: Document): GeneralInfo | undefined => {\n  const representedCustodianOrganization = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']\",\n    document\n  ) as Document | undefined;\n\n  if (!representedCustodianOrganization) return undefined;\n\n  const name = String(xpath.select1(\"string(*[name()='name'])\", representedCustodianOrganization));\n\n  const contactDetails = getContactDetails(\n    xpath.select1(\n      \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']/*[name()='addr']\",\n      document\n    ) as Document,\n    xpath.select1(\n      \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']/*[name()='telecom']\",\n      document\n    ) as Document\n  );\n\n  return { name, contactDetails };\n};\n","import { getCustodianData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Custodian = ({ document }: DocumentOnlyProps) => {\n  const custodian = getCustodianData(document);\n\n  if (!custodian) return null;\n\n  const { name, contactDetails } = custodian;\n  const finalData = [\n    {\n      label: \"Custodian\",\n      value: name,\n    },\n    {\n      label: \"Contact Details\",\n      value: contactDetails,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName } from \"../../helpers\";\nimport { GeneralInfo } from \"../../types\";\n\nexport const getDataEntererData = (document: Document): GeneralInfo | undefined => {\n  const dataEnterer = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='dataEnterer']/*[name()='assignedEntity']\",\n    document\n  ) as Document | undefined;\n\n  if (!dataEnterer) return undefined;\n\n  const assignedPerson = xpath.select1(\"*[name()='assignedPerson']\", dataEnterer) as Document;\n\n  const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", dataEnterer) as Document[],\n    xpath.select(\"*[name()='telecom']\", dataEnterer) as Document[]\n  );\n\n  return { name, contactDetails };\n};\n","import { getDataEntererData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const DataEnterer = ({ document }: DocumentOnlyProps) => {\n  const dataEnterer = getDataEntererData(document);\n\n  if (!dataEnterer) return null;\n\n  const { name, contactDetails } = dataEnterer;\n  const finalData = [\n    {\n      label: \"Data Enterer\",\n      value: name,\n    },\n    {\n      label: \"Contact Details\",\n      value: contactDetails,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getId, parseToISOString } from \"../../helpers\";\n\nconst confidentialityCodeMap: Record<string, string> = {\n  N: \"normal\",\n  R: \"restricted\",\n  V: \"very restricted\",\n};\nexport const getDocumentData = (document: Document) => {\n  const id = getId(\n    xpath.select1(\"*[name()='ClinicalDocument']/*[name()='id']\", document) as Document\n  );\n\n  const effectiveTimeValue = parseToISOString(\n    String(\n      xpath.select1(\n        \"string(*[name()='ClinicalDocument']/*[name()='effectiveTime']/@value)\",\n        document\n      )\n    )\n  );\n\n  const createdOn = formatDate(effectiveTimeValue);\n\n  const version = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='versionNumber']/@value)\", document)\n  );\n  const setId = getId(\n    xpath.select1(\"*[name()='ClinicalDocument']/*[name()='setId']\", document) as Document\n  );\n  const confidentialityCode =\n    confidentialityCodeMap[\n      String(\n        xpath.select1(\n          \"string(*[name()='ClinicalDocument']/*[name()='confidentialityCode']/@code)\",\n          document\n        )\n      )\n    ];\n  const code = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='code']/@displayName)\", document)\n  );\n  const languageCode = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='languageCode']/@code)\", document)\n  );\n  return {\n    id,\n    createdOn,\n    version,\n    setId,\n    confidentialityCode,\n    code,\n    languageCode,\n  };\n};\n","import { getDocumentData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Document = ({ document }: DocumentOnlyProps) => {\n  const { id, createdOn, version, setId, confidentialityCode, code, languageCode } =\n    getDocumentData(document);\n\n  const finalData = [\n    {\n      label: \"Document\",\n      value: (\n        <>\n          <b>ID: </b>\n          {id}\n          {setId && (\n            <>\n              <br />\n              <b>Set ID: </b>\n              {setId}\n            </>\n          )}\n        </>\n      ),\n    },\n    {\n      label: \"Created on\",\n      value: createdOn,\n    },\n    {\n      label: \"Version\",\n      value: version || \"Unknown\",\n    },\n    {\n      label: \"Confidentiality\",\n      value: confidentialityCode,\n    },\n    {\n      label: \"Code\",\n      value: code,\n    },\n    {\n      label: \"Language\",\n      value: languageCode,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getHumanName, getPeriod } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getDocumentationOf = (\n  document: Document\n): Record<string, LabelValueType[]> | undefined => {\n  const serviceEvents = xpath.select(\n    \"//*[name()='documentationOf']/*[name()='serviceEvent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(serviceEvents)) return undefined;\n\n  const result = serviceEvents.map((serviceEvent) => {\n    const effectiveTime = xpath.select1(\"*[name()='effectiveTime']\", serviceEvent) as Document;\n\n    const period = getPeriod(effectiveTime);\n\n    const performerNames = xpath.select(\n      \"*[name()='performer']/*[name()='assignedEntity']/*[name()='assignedPerson']/*[name()='name']\",\n      serviceEvent\n    ) as Document[];\n\n    const performers = performerNames.map((performer) => getHumanName(performer));\n\n    return [\n      {\n        label: \"Date/Time:\",\n        value:\n          period.start || period.end\n            ? `from ${formatDate(period.start) || \"unknown\"} to ${\n                formatDate(period.end) || \"unknown\"\n              }`\n            : \"\",\n      },\n      ...performers.map((performer) => ({\n        label: \"Performer:\",\n        value: performer,\n      })),\n    ];\n  });\n\n  return result.reduce((acc, val, index) => ({ ...acc, [`documentationOf${index + 1}`]: val }), {});\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isGeneralInfoExist, LabelValueType } from \"../../types\";\nimport { getDocumentationOf as getDocumentationOfDataFromHeader } from \"../Header/data/getDocumentationOf\";\nimport { get, isEmpty } from \"@/utils/nodash\";\n\nexport const getDocumentationOfData = (\n  document: Document\n): { dateTime: string; finalPerformers: ExtendedGeneralInfo[] }[] | undefined => {\n  const serviceEventXmls = xpath.select(\n    \"//*[name()='documentationOf']/*[name()='serviceEvent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(serviceEventXmls)) return undefined;\n\n  const documentationOfs = getDocumentationOfDataFromHeader(document) as Record<\n    string,\n    LabelValueType[]\n  >; // we can cast, it won't be undefined\n\n  return serviceEventXmls.map(\n    (serviceEventXml, index): { dateTime: string; finalPerformers: ExtendedGeneralInfo[] } => {\n      const performerXmls = xpath.select(\"*[name()='performer']\", serviceEventXml) as Document[];\n\n      const finalPerformers = performerXmls.map(\n        (performerXml, index2): ExtendedGeneralInfo | undefined => {\n          const functionCode = String(\n            xpath.select1(\"string(*[name()='functionCode']/@displayName)\", performerXml)\n          );\n          const name = get(\n            documentationOfs,\n            `documentationOf${index + 1}[${index2 + 1}].value`\n          ) as unknown as string; // rest elements are performers\n\n          const contactDetails = getContactDetails(\n            xpath.select(\"*[name()='assignedEntity']/*[name()='addr']\", performerXml) as Document[],\n            xpath.select(\n              \"*[name()='assignedEntity']/*[name()='telecom']\",\n              performerXml\n            ) as Document[]\n          );\n\n          if (!name && !functionCode && !contactDetails) return undefined;\n\n          return {\n            functionCode,\n            name,\n            contactDetails,\n          };\n        }\n      );\n\n      return {\n        dateTime: get(\n          documentationOfs,\n          `documentationOf${index + 1}[0].value`\n        ) as unknown as string, // first element is date time\n        finalPerformers: finalPerformers.filter(isGeneralInfoExist),\n      };\n    }\n  );\n};\n","import { getDocumentationOfData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const DocumentationOf = ({ document }: DocumentOnlyProps) => {\n  const documentationOfs = getDocumentationOfData(document);\n\n  if (!documentationOfs || isEmpty(documentationOfs)) return null;\n\n  const finalData = documentationOfs.flatMap((documentationOf) => [\n    { label: \"Documentation of - Date/Time\", value: documentationOf.dateTime },\n    { label: \"\", value: \"\" },\n    ...documentationOf.finalPerformers.flatMap((performer) => [\n      {\n        label: \"Performer\",\n        value: `${performer.name || \"Unknown\"}${\n          performer.functionCode ? ` - ${performer.functionCode}` : \"\"\n        }`,\n      },\n      { label: \"Contact Details\", value: performer.contactDetails },\n    ]),\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getId, getPeriod } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\n\nexport const getEncounter = (document: Document): LabelValueType[] | undefined => {\n  const encompassingEncounter = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='componentOf']/*[name()='encompassingEncounter']\",\n    document,\n  ) as Document | undefined;\n\n  if (!encompassingEncounter) return undefined;\n\n  const id = getId(xpath.select1(\"*[name()='id']\", encompassingEncounter) as Document);\n\n  const type = String(\n    xpath.select1(\n      \"string(*[name()='code']/@displayName)\",\n      encompassingEncounter,\n    ) as Document | null,\n  );\n\n  const period = getPeriod(\n    xpath.select1(\"*[name()='effectiveTime']\", encompassingEncounter) as Document,\n  );\n\n  return [\n    {\n      label: \"ID\",\n      value: period.start || period.end || id ? id || \"Unknown\" : \"\",\n    },\n    { label: \"Type\", value: type },\n    {\n      label: \"Date/Time\",\n      value:\n        period.start || period.end\n          ? `from ${formatDate(period.start) || \"unknown\"} to ${\n              formatDate(period.end) || \"unknown\"\n            }`\n          : \"\",\n    },\n  ];\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../helpers\";\nimport { LabelValueType } from \"../../types\";\nimport { getEncounter } from \"../Header/data/getEncounter\";\n\nexport const getEncounterData = (document: Document) => {\n  const encompassingEncounter = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='componentOf']/*[name()='encompassingEncounter']\",\n    document\n  ) as Document | undefined;\n\n  if (!encompassingEncounter) return undefined;\n\n  const encounter = getEncounter(document) as LabelValueType[];\n\n  const dischargeDisposition = String(\n    xpath.select1(\n      \"string(*[name()='dischargeDispositionCode']/@displayName)\",\n      encompassingEncounter\n    )\n  );\n\n  const encounterLocation = getId(\n    xpath.select1(\n      \"*[name()='location']/*[name()='healthCareFacility']/*[name()='id']\",\n      encompassingEncounter\n    ) as Document\n  );\n\n  return {\n    id: encounter[0], // we now that they are returned in that order\n    type: encounter[1],\n    dateTime: encounter[2],\n    dischargeDisposition,\n    encounterLocation: encounterLocation ? `ID: ${encounterLocation}` : null,\n  };\n};\n","import { getEncounterData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Encounter = ({ document }: DocumentOnlyProps) => {\n  const encounter = getEncounterData(document);\n\n  if (!encounter) return null;\n\n  const { dischargeDisposition, encounterLocation, id, type, dateTime } = encounter;\n\n  const finalData = [\n    {\n      label: \"Encounter\",\n      value:\n        dateTime.value || dischargeDisposition || encounterLocation || id.value ? (\n          <>\n            <b>ID: </b>\n            {id.value || \"Unknown\"}\n            {type.value && (\n              <>\n                <br />\n                <b>Type: </b>\n                {type.value}\n              </>\n            )}\n          </>\n        ) : null,\n    },\n    {\n      label: \"Date/Time\",\n      value: dateTime.value,\n    },\n    {\n      label: \"Discharge Disposition\",\n      value: dischargeDisposition,\n    },\n    {\n      label: \"Encounter Location\",\n      value: encounterLocation,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInformantData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const informants = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='informant']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(informants)) return undefined;\n\n  return informants\n    .map((informant): ExtendedGeneralInfo | undefined => {\n      const assignedEntity = xpath.select1(\"*[name()='assignedEntity']\", informant) as\n        | Document\n        | undefined;\n\n      if (assignedEntity) {\n        const assignedPerson = xpath.select1(\n          \"*[name()='assignedPerson']\",\n          assignedEntity\n        ) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n        );\n\n        return { name, contactDetails, relationship: \"\" };\n      }\n\n      const relatedEntity = xpath.select1(\"*[name()='relatedEntity']\", informant) as\n        | Document\n        | undefined;\n\n      if (relatedEntity) {\n        const relatedPerson = xpath.select1(\"*[name()='relatedPerson']\", relatedEntity) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", relatedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", relatedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", relatedEntity) as Document[]\n        );\n\n        const relationship = String(\n          xpath.select1(\"string(*[name()='code']/@displayName)\", relatedEntity)\n        ).toLowerCase();\n\n        return { name, contactDetails, relationship };\n      }\n\n      return undefined;\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","import { getInformantData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Informant = ({ document }: DocumentOnlyProps) => {\n  const informants = getInformantData(document);\n\n  if (!informants || isEmpty(informants)) return null;\n\n  const finalData = informants.flatMap((informant) => [\n    {\n      label: \"Informant\",\n      value: `${informant.name || \"Unknown\"}${\n        informant.relationship ? ` - ${informant.relationship}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: informant.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getHumanName, getId } from \"../../helpers\";\nimport { InformationRecipient } from \"../../types/InformationRecipient\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInformationRecipientData = (\n  document: Document\n): InformationRecipient[] | undefined => {\n  const intendedRecipients = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='informationRecipient']/*[name()='intendedRecipient']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(intendedRecipients)) return undefined;\n\n  return intendedRecipients.map((intendedRecipient) => {\n    let informationRecipientName = \"\";\n    const informationRecipient = xpath.select1(\n      \"*[name()='informationRecipient']\",\n      intendedRecipient\n    ) as Document | undefined;\n\n    if (informationRecipient) {\n      informationRecipientName = getHumanName(\n        xpath.select1(\"*[name()='name']\", informationRecipient) as Document\n      );\n    }\n\n    const ids = (xpath.select(\"*[name()='id']\", intendedRecipient) as Document[])\n      .map(getId)\n      .join(\", \");\n\n    let receivedOrganizationName = \"\";\n    const receivedOrganization = xpath.select1(\n      \"*[name()='receivedOrganization']\",\n      intendedRecipient\n    ) as Document | undefined;\n    if (receivedOrganization) {\n      receivedOrganizationName = String(\n        xpath.select1(\"string(*[name()='name']/node())\", receivedOrganization)\n      );\n    }\n\n    return {\n      name: informationRecipientName,\n      id: ids,\n      organization: receivedOrganizationName,\n    };\n  });\n};\n","import { getInformationRecipientData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const InformationRecipient = ({ document }: DocumentOnlyProps) => {\n  const informationRecipients = getInformationRecipientData(document);\n\n  if (!informationRecipients || isEmpty(informationRecipients)) return null;\n\n  const finalData = informationRecipients.flatMap((informationRecipient) => [\n    {\n      label: \"Information Recipient\",\n      value: informationRecipient.name ?? \"Unnamed\",\n    },\n    {\n      label: \"ID\",\n      value: informationRecipient.id,\n    },\n    {\n      label: \"Organization\",\n      value: informationRecipient.organization,\n    },\n  ]);\n\n  return <Table data={finalData} chunkSize={3} />;\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInFulfillmentOf = (\n  document: Document\n): Record<string, LabelValueType[]> | undefined => {\n  const orderXmls = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='inFulfillmentOf']/*[name()='order']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(orderXmls)) return undefined;\n\n  const orders = orderXmls.map((orderXml) => {\n    const id = getId(xpath.select1(\"*[name()='id']\", orderXml) as Document);\n    const code = String(xpath.select1(\"string(*[name()='code']/@displayName)\", orderXml));\n\n    return [\n      { label: \"Order ID:\", value: id },\n      { label: \"Code:\", value: code },\n    ];\n  });\n\n  return orders.reduce(\n    (acc, order, index) => ({ ...acc, [`inFulfillmentOf${index + 1}`]: order }),\n    {}\n  );\n};\n","import { getInFulfillmentOf as getInFulfillmentOfDataFromHeader } from \"../Header/data/getInFulfillmentOf\";\n\nexport const getInFulfillmentOfData = (document: Document) => {\n  const inFulfillmentOf = getInFulfillmentOfDataFromHeader(document);\n\n  return Object.values(inFulfillmentOf || {});\n};\n","import { getInFulfillmentOfData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const InFulfillmentOf = ({ document }: DocumentOnlyProps) => {\n  const inFulfillmentOfs = getInFulfillmentOfData(document);\n\n  if (isEmpty(inFulfillmentOfs)) return null;\n\n  const finalData = inFulfillmentOfs.flatMap((inFulfillmentOf) => [\n    {\n      label: \"In Fulfillment Of\",\n      value: `Order: ${inFulfillmentOf[0].value || \"Unknown\"}, ${\n        // [0] is id\n        inFulfillmentOf[1].value || \"Unknown\" // [1] is code\n      }`,\n    },\n    { label: \"\", value: \"\" },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getContactDetails, getHumanName, parseToISOString } from \"../../helpers\";\nimport { ExtendedGeneralInfo } from \"../../types\";\n\nexport const getLegalAuthenticatorData = (document: Document): ExtendedGeneralInfo | undefined => {\n  const legalAuthenticator = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='legalAuthenticator']\",\n    document\n  ) as Document | undefined;\n\n  if (!legalAuthenticator) return undefined;\n\n  const assignedEntity = xpath.select1(\n    \"*[name()='assignedEntity']\",\n    legalAuthenticator\n  ) as Document;\n\n  const assignedPerson = xpath.select1(\"*[name()='assignedPerson']\", assignedEntity) as Document;\n\n  const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n    xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n  );\n\n  const time = formatDate(\n    parseToISOString(String(xpath.select1(\"string(*[name()='time']/@value)\", legalAuthenticator)))\n  );\n\n  return { name, contactDetails, time };\n};\n","import { getLegalAuthenticatorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const LegalAuthenticator = ({ document }: DocumentOnlyProps) => {\n  const legalAuthenticator = getLegalAuthenticatorData(document);\n\n  if (!legalAuthenticator) return null;\n\n  const { name, time, contactDetails } = legalAuthenticator;\n\n  const withSignedAt = time ? ` signed at ${time}` : \"\";\n  const finalData = [\n    {\n      label: \"Legal Authenticator\",\n      value: `${name}${withSignedAt}`,\n    },\n    { label: \"Contact Details\", value: contactDetails },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName, getPeriod } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getParticipantData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const participants = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='participant']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(participants)) return undefined;\n\n  return participants\n    .map((participant): ExtendedGeneralInfo | undefined => {\n      const associatedEntity = xpath.select1(\"*[name()='associatedEntity']\", participant) as\n        | Document\n        | undefined;\n\n      if (associatedEntity) {\n        const associatedPerson = xpath.select1(\n          \"*[name()='associatedPerson']\",\n          associatedEntity\n        ) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", associatedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", associatedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", associatedEntity) as Document[]\n        );\n\n        const time = xpath.select1(\"*[name()='time']\", participant) as Document;\n\n        const period = getPeriod(time);\n\n        const relationship = String(\n          xpath.select1(\"string(*[name()='code']/@displayName)\", associatedEntity)\n        ).toLowerCase();\n\n        return {\n          name,\n          contactDetails,\n          time: `from ${period.start} to ${period.end}`,\n          relationship,\n        };\n      }\n\n      return undefined;\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","import { getParticipantData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Participant = ({ document }: DocumentOnlyProps) => {\n  const participants = getParticipantData(document);\n\n  if (!participants || isEmpty(participants)) return null;\n\n  const finalData = participants.flatMap((participant) => [\n    {\n      label: \"Participant\",\n      value: `${participant.name}${\n        participant.relationship ? ` - ${participant.relationship}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: participant.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getAddress } from \"../../../helpers\";\n\nexport const getBirthPlace = (patient: Document): string => {\n  const birthPlace = xpath.select1(\n    \"*[name()='birthplace']/*[name()='place']/*[name()='addr']\",\n    patient\n  ) as Document | undefined;\n\n  if (!birthPlace) return \"\";\n\n  return getAddress(birthPlace);\n};\n","import xpath from \"xpath\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getEthnicity = (patient: Document): string => {\n  const ethnicGroup = xpath.select1(\"*[name()='ethnicGroupCode']\", patient) as Document | undefined;\n\n  if (ethnicGroup) {\n    return String(xpath.select1(\"string(@displayName)\", ethnicGroup));\n  }\n\n  const detailedEthnicGroup = xpath.select(\n    \"*[name()='sdtc:ethnicGroupCode']\",\n    patient\n  ) as Document[];\n\n  if (isEmpty(detailedEthnicGroup)) return \"\";\n\n  return String(xpath.select1(\"string(@displayName)\", detailedEthnicGroup[0]));\n};\n","import xpath from \"xpath\";\nimport { getHumanName } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getGuardian = (patientRole: Document): LabelValueType[] | undefined => {\n  const guardians = xpath.select(\n    \"*[name()='patient']/*[name()='guardian']\",\n    patientRole\n  ) as Document[];\n\n  if (isEmpty(guardians)) return undefined;\n\n  return guardians.map((guardian) => {\n    const guardianPerson = xpath.select1(\"*[name()='guardianPerson']\", guardian) as Document;\n\n    const relationship = String(xpath.select1(\"string(*[name()='code']/@displayName)\", guardian));\n    const name = getHumanName(xpath.select(\"*[name()='name']\", guardianPerson) as Document[]);\n\n    const withRelationship = relationship ? ` - ${relationship}` : \"\";\n    return {\n      label: \"\",\n      value: `${name}${withRelationship}`,\n    };\n  });\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../../helpers\";\nimport { GeneralInfo, LabelValueType } from \"../../../types\";\nimport { getGuardian as getGuardianFromHeader } from \"../../Header/data/getGuardian\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getGuardian = (patientRole: Document): GeneralInfo[] | undefined => {\n  const guardians = xpath.select(\n    \"//*[name()='patientRole']/*[name()='patient']/*[name()='guardian']\",\n    document\n  ) as Document[] | undefined;\n\n  if (!guardians || isEmpty(guardians)) return undefined;\n\n  const guardianNames = getGuardianFromHeader(patientRole) as LabelValueType[];\n\n  return guardians.map((guardian, index) => {\n    const contactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", guardian) as Document[],\n      xpath.select(\"*[name()='telecom']\", guardian) as Document[]\n    );\n\n    return { name: guardianNames[index].value, contactDetails };\n  });\n};\n","import xpath from \"xpath\";\n\nexport const getLanguage = (patient: Document): string => {\n  const languages = xpath.select(\"*[name()='languageCommunication']\", patient) as Document[];\n\n  return languages.reduce((acc, language, index) => {\n    const languageCode = String(xpath.select1(\"string(*[name()='languageCode']/@code)\", language));\n    if (!languageCode) return acc;\n\n    const preferred = String(xpath.select1(\"string(*[name()='preferenceInd']/@value)\", language));\n\n    const withNewLine = index === 0 ? \"\" : \"\\n\";\n    const withPreferred = preferred !== \"\" ? `, preferred: ${preferred}` : \"\";\n    return `${acc}${withNewLine}${languageCode}${withPreferred}`;\n  }, \"\");\n};\n","import xpath from \"xpath\";\n\nexport const getMaritalStatus = (patient: Document): string =>\n  String(xpath.select1(\"string(*[name()='maritalStatusCode']/@displayName)\", patient));\n","import xpath from \"xpath\";\nimport { displayForName, getContactDetails, getId } from \"../../../helpers\";\nimport { GeneralInfo } from \"../../../types\";\n\nexport const getProviderOrganization = (patientRole: Document): GeneralInfo => {\n  const providerOrganization = xpath.select1(\"*[name()='providerOrganization']\", patientRole) as\n    | Document\n    | undefined;\n\n  const custodian = xpath.select1(\n    \"//*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']\",\n    patientRole,\n  ) as Document | undefined;\n\n  const finalProvider = providerOrganization || custodian;\n\n  if (!finalProvider) {\n    return {\n      name: \"\",\n      contactDetails: \"\",\n    };\n  }\n\n  const ids = (xpath.select(\"*[name()='id']\", finalProvider) as Document[]).map(getId).join(\", \");\n\n  const names = displayForName(xpath.select(\"string(*[name()='name'])\", finalProvider) as string[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", finalProvider) as Document[],\n    xpath.select(\"*[name()='telecom']\", finalProvider) as Document[],\n  );\n\n  const withNames = names ? `\\n${names}` : \"\";\n  return {\n    name: `${ids}${withNames}`,\n    contactDetails,\n  };\n};\n","import xpath from \"xpath\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getRace = (patient: Document): string => {\n  const race = xpath.select1(\"*[name()='raceCode']\", patient) as Document | undefined;\n\n  if (race) return String(xpath.select1(\"string(@displayName)\", race));\n\n  const detailedRace = xpath.select(\"*[name()='sdtc:raceCode']\", patient) as Document[];\n\n  if (isEmpty(detailedRace)) return \"\";\n\n  return String(xpath.select1(\"string(@displayName)\", detailedRace[0]));\n};\n","import xpath from \"xpath\";\n\nexport const getReligion = (patient: Document): string =>\n  String(xpath.select1(\"string(*[name()='religiousAffiliationCode']/@displayName)\", patient));\n","import { differenceInYears, format, isValid, parseISO } from \"date-fns\";\nimport xpath from \"xpath\";\nimport { getGuardian } from \"./getGuardian\";\nimport { getHumanName, getId, parseToISOString } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { map } from \"@/utils/nodash\";\n\nexport const getPatient = (document: Document): Record<string, LabelValueType[] | undefined> => {\n  const patientRoles = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='recordTarget']/*[name()='patientRole']\",\n    document\n  ) as Document[];\n\n  const result = patientRoles.map(\n    (\n      patientRole\n    ): {\n      patient: LabelValueType[];\n      guardian: LabelValueType[] | undefined;\n    } => {\n      const patient = xpath.select1(\"*[name()='patient']\", patientRole) as Document;\n\n      const patientName = getHumanName(xpath.select1(\"*[name()='name']\", patient) as Document);\n\n      const patientIds = (xpath.select(\"*[name()='id']\", patientRole) as Document[])\n        .map(getId)\n        .join(\", \");\n\n      const administrativeGenderCode = String(\n        xpath.select1(\"string(*[name()='administrativeGenderCode']/@displayName)\", patient)\n      );\n\n      const birthTime = parseISO(\n        parseToISOString(String(xpath.select1(\"string(*[name()='birthTime']/@value)\", patient)))\n      );\n\n      const deceasedTime = parseISO(\n        parseToISOString(\n          String(xpath.select1(\"string(*[name()='sdtc:deceasedTime']/@value)\", patient))\n        )\n      );\n\n      const deceasedInd =\n        String(xpath.select1(\"string(*[name()='sdtc:deceasedInd']/@value)\", patient)) === \"true\";\n\n      const withDeceased = deceasedInd\n        ? \"deceased\"\n        : differenceInYears(isValid(deceasedTime) ? deceasedTime : new Date(), birthTime);\n      const dateOfBirth = `${format(birthTime, \"MMMM dd, yyyy\")} (${withDeceased}${\n        deceasedInd ? \"\" : \" yr\"\n      }${isValid(deceasedTime) ? \" - deceased\" : \"\"})`;\n\n      const guardian = getGuardian(patientRole);\n\n      return {\n        patient: [\n          { label: \"Name:\", value: patientName },\n          {\n            label: \"ID:\",\n            value: patientIds,\n          },\n          {\n            label: \"Date of birth:\",\n            value: dateOfBirth,\n          },\n          { label: \"Gender:\", value: administrativeGenderCode },\n        ],\n        guardian,\n      };\n    }\n  );\n\n  return map(result, (res) => [res.patient, res.guardian]).reduce(\n    (acc, val, index) => ({\n      ...acc,\n      [`patient${index + 1}`]: val[0],\n      [`guardian${index + 1}`]: val[1],\n    }),\n    {}\n  );\n};\n","import xpath from \"xpath\";\nimport { getBirthPlace } from \"./getBirthPlace\";\nimport { getEthnicity } from \"./getEthnicity\";\nimport { getGuardian } from \"./getGuardian\";\nimport { getLanguage } from \"./getLanguage\";\nimport { getMaritalStatus } from \"./getMaritalStatus\";\nimport { getProviderOrganization } from \"./getProviderOrganization\";\nimport { getRace } from \"./getRace\";\nimport { getReligion } from \"./getReligion\";\nimport { getContactDetails } from \"../../../helpers\";\nimport { getPatient as getPatientDataFromHeader } from \"../../Header/data/getPatient\";\nimport { camelCase, isEmpty } from \"@/utils/nodash\";\n\nexport const getPatientData = (document: Document) => {\n  const patientRoles = xpath.select(\"//*[name()='patientRole']\", document) as\n    | Document[]\n    | undefined;\n\n  if (!patientRoles || isEmpty(patientRoles)) return undefined;\n\n  const dataFromHeader = getPatientDataFromHeader(document);\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const patients: any = Object.entries(dataFromHeader).reduce(\n    (result, [key, value]) => ({\n      ...result,\n      [key]: value?.reduce(\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        (valueAsObject: any, data: { label: string; value: string }) => ({\n          ...valueAsObject,\n          [camelCase(data.label)]: data.value,\n        }),\n        {}\n      ),\n    }),\n    {}\n  );\n\n  return patientRoles.map((patientRole, index) => {\n    const patient = xpath.select1(\"*[name()='patient']\", patientRole) as Document;\n\n    const race = getRace(patient);\n    const ethnicity = getEthnicity(patient);\n\n    const contactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", patientRole) as Document[],\n      xpath.select(\"*[name()='telecom']\", patientRole) as Document[]\n    );\n\n    const language = getLanguage(patient);\n\n    const providerOrganization = getProviderOrganization(patientRole);\n\n    const guardian = getGuardian(patientRole);\n\n    const maritalStatus = getMaritalStatus(patient);\n    const religion = getReligion(patient);\n    const birthPlace = getBirthPlace(patient);\n\n    return {\n      name: patients[`patient${index + 1}`].name,\n      contactDetails,\n      dateOfBirth: patients[`patient${index + 1}`].dateOfBirth,\n      gender: patients[`patient${index + 1}`].gender,\n      race,\n      ethnicity,\n      patientId: patients[`patient${index + 1}`].id,\n      language,\n      maritalStatus,\n      religion,\n      birthPlace,\n      guardian: guardian || [],\n      providerOrganization: providerOrganization.name,\n      providerOrganizationContactDetails: providerOrganization.contactDetails,\n    };\n  });\n};\n","import { getPatientData } from \"./data\";\nimport { DocumentOnlyProps, TableInfo } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isArray, isEmpty } from \"@/utils/nodash\";\n\nexport const Patient = ({ document }: DocumentOnlyProps): JSX.Element | null => {\n  const patients = getPatientData(document);\n\n  if (!patients || isEmpty(patients)) return null;\n\n  return (\n    <>\n      {patients.map((patient) => {\n        const finalData: ([TableInfo, TableInfo] | TableInfo)[] = [\n          { label: \"Patient\", value: patient.name },\n          { label: \"Contact Details\", value: patient.contactDetails },\n\n          { label: \"Date Of Birth\", value: patient.dateOfBirth },\n          { label: \"Gender\", value: patient.gender },\n\n          { label: \"Race\", value: patient.race },\n          { label: \"Ethnicity\", value: patient.ethnicity },\n\n          { label: \"Patient ID\", value: patient.patientId },\n          { label: \"Language\", value: patient.language },\n\n          { label: \"Marital Status\", value: patient.maritalStatus },\n          { label: \"Religion\", value: patient.religion },\n\n          { label: \"Birth Place\", value: patient.birthPlace },\n\n          ...(patient.guardian.map((guardian) => [\n            { label: \"Guardian\", value: guardian.name },\n            { label: \"Contact Details\", value: guardian.contactDetails },\n          ]) as [TableInfo, TableInfo][]), // ts does not understand, we must explicitly state it is ok\n\n          [\n            {\n              label: \"Provider Organization\",\n              value: patient.providerOrganization,\n            },\n            {\n              label: \"Contact Details (Organization)\",\n              value: patient.providerOrganizationContactDetails,\n            },\n          ],\n        ];\n\n        return (\n          <Table\n            key={`${patient.patientId}-${patient.name}-${patient.dateOfBirth}`}\n            data={finalData.filter((d) => isArray(d) || d.value)}\n          />\n        );\n      })}\n    </>\n  );\n};\n","import { Authenticator } from \"./Authenticator/Authenticator\";\nimport { Author } from \"./Author/Author\";\nimport { Authorization } from \"./Authorization/Authorization\";\nimport { Custodian } from \"./Custodian/Custodian\";\nimport { DataEnterer } from \"./DataEnterer/DataEnterer\";\nimport { Document } from \"./Document/Document\";\nimport { DocumentationOf } from \"./DocumentationOf/DocumentationOf\";\nimport { Encounter } from \"./Encounter/Encounter\";\nimport { Informant } from \"./Informant/Informant\";\nimport { InformationRecipient } from \"./InformationRecipient/InformationRecipient\";\nimport { InFulfillmentOf } from \"./InFulfillmentOf/InFulfillmentOf\";\nimport { LegalAuthenticator } from \"./LegalAuthenticator/LegalAuthenticator\";\nimport { Participant } from \"./Participant/Participant\";\nimport { Patient } from \"./Patient/Patient\";\nimport { DocumentOnlyProps } from \"../types\";\n\nexport const DocumentDetails = ({ document }: DocumentOnlyProps) => (\n  <div id=\"document-details\">\n    <Document document={document} />\n    <Custodian document={document} />\n    <Patient document={document} />\n    <Author document={document} />\n    <DataEnterer document={document} />\n    <Informant document={document} />\n    <InformationRecipient document={document} />\n    <LegalAuthenticator document={document} />\n    <Authenticator document={document} />\n    <Participant document={document} />\n    <DocumentationOf document={document} />\n    <InFulfillmentOf document={document} />\n    <Authorization document={document} />\n    <Encounter document={document} />\n  </div>\n);\n","import * as React from \"react\";\n\nfunction SearchIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 2,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(SearchIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction ThumbDownIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 2,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ThumbDownIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction ThumbUpIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 2,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ThumbUpIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction XIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 2,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M6 18L18 6M6 6l12 12\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(XIcon);\nexport default ForwardRef;","export const CTW_MODAL_ID = \"ctw-modal\";\nexport const DOCUMENT_HEADER_ID = \"document-header\";\nexport const TABLE_OF_CONTENT_ID = \"table-of-contents\";\n","export const navigateIntoView = (sectionId: string) => {\n  // This is the element that gets scrolled.\n  const modalElement = document.getElementById(\"ctw-modal\");\n  // The top header of the modal, which may be down a bit due to padding or stickied at top.\n  const headerOffset = document.getElementById(\"document-header\")?.getBoundingClientRect().y;\n  // This is the target position we want to scroll the section to.\n  const tocBottom = document.getElementById(\"table-of-contents\")?.getBoundingClientRect().bottom;\n  const sectionElement = document.getElementById(sectionId);\n  if (tocBottom === undefined || headerOffset === undefined || !modalElement || !sectionElement) {\n    return;\n  }\n\n  // Scroll the modal such that the section's new top is equal to the toc's bottom.\n  const sectionTop = sectionElement.getBoundingClientRect().top;\n  modalElement.scrollTop += sectionTop - tocBottom + headerOffset;\n};\n","export default \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyMiAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwXzIyNF82NzYwKSI+CjxwYXRoIGQ9Ik0xNi45NzY3IDE3LjIyMkwxMS40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a guard to protect against SSR uses.\nexport const useIsomorphicLayoutEffect =\n  typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n","// DO NOT IMPORT OUTSIDE THINGS WITHIN THIs FILE!\n// We compile this file and any imports will get compiled\n// to .js files which would then need to be cleaned up.\n\ntype Subset<K> = {\n  [attr in keyof K]?: K[attr] extends object ? Subset<K[attr]> : K[attr];\n};\n\nexport const CLASS_PREFIX = \"ctw-\";\n\nexport const defaultBreakpoints = {\n  xs: 400,\n  sm: 640,\n  md: 768,\n  lg: 1024,\n};\n\nexport const TailwindTheme = {\n  colors: {\n    transparent: \"transparent\",\n    white: \"#ffffff\",\n    black: \"#000000\",\n    primary: {\n      light: \"#D0FBE2\",\n      main: \"#008052\",\n      dark: \"#036240\",\n    },\n    icon: {\n      default: \"#374151\",\n      light: \"#D1D5DB\",\n      active: \"#A855F7\",\n    },\n    divider: {\n      main: \"#D1D5DB\",\n      light: \"#E5E7EB\",\n    },\n    content: {\n      black: \"#111827\",\n      light: \"#6B7280\",\n      lighter: \"#9CA3AF\",\n    },\n    error: {\n      main: \"#EF4444\",\n      light: \"#FEE2E2\",\n      dark: \"#7F1D1D\",\n      text: \"#991B1B\",\n      message: \"#B91C1B\",\n      bg: \"#FEF2F2\",\n      icon: \"#F97171\",\n    },\n    success: {\n      main: \"#10B981\",\n      light: \"#D1FAE5\",\n      dark: \"#065F46\",\n    },\n    caution: {\n      bg: \"#FFFBEB\",\n      icon: \"#F59E0B\",\n      light: \"#FEF3C7\",\n      text: \"#92400E\",\n      textHover: \"#D4753C\",\n    },\n    notification: {\n      light: \"#F3E8FF\",\n      main: \"#A855F7\",\n      icon: \"#EF4444\",\n      dark: \"#4B5563\",\n    },\n    info: {\n      bg: \"#F0F9FF\",\n      light: \"#E0F2FE\",\n      icon: \"#0EA5E9\",\n      text: \"#075985\",\n      textHover: \"#0979B6\",\n    },\n    bg: {\n      white: \"#FFFFFF\",\n      lighter: \"#F9FAFB\",\n      light: \"#F3F4F6\",\n      dark: \"#E5E7EB\",\n      black: \"#111827\",\n      zusLogoBlue: \"#71B2C9\",\n    },\n    zap: {\n      headerBg: \"#ffffff\",\n    },\n  },\n};\n\n// Some post processing workflows (older versions of PostCSS) will\n// incorrectly remove tailwind's empty CSS variables.\n// To fix this, we manually apply them in CTWProvider.\n// See https://github.com/tailwindlabs/tailwindcss/issues/2889#issuecomment-734238826\nexport const EmptyTailwindCSSVars: Record<string, string> = {\n  \"--tw-pan-x\": \" \",\n  \"--tw-pan-y\": \" \",\n  \"--tw-pinch-zoom\": \" \",\n  \"--tw-ordinal\": \" \",\n  \"--tw-slashed-zero\": \" \",\n  \"--tw-numeric-figure\": \" \",\n  \"--tw-numeric-spacing\": \" \",\n  \"--tw-numeric-fraction\": \" \",\n  \"--tw-ring-inset\": \" \",\n  \"--tw-blur\": \" \",\n  \"--tw-brightness\": \" \",\n  \"--tw-contrast\": \" \",\n  \"--tw-grayscale\": \" \",\n  \"--tw-hue-rotate\": \" \",\n  \"--tw-invert\": \" \",\n  \"--tw-saturate\": \" \",\n  \"--tw-sepia\": \" \",\n  \"--tw-drop-shadow\": \" \",\n  \"--tw-backdrop-blur\": \" \",\n  \"--tw-backdrop-brightness\": \" \",\n  \"--tw-backdrop-contrast\": \" \",\n  \"--tw-backdrop-grayscale\": \" \",\n  \"--tw-backdrop-hue-rotate\": \" \",\n  \"--tw-backdrop-invert\": \" \",\n  \"--tw-backdrop-opacity\": \" \",\n  \"--tw-backdrop-saturate\": \" \",\n  \"--tw-backdrop-sepia\": \" \",\n};\n\n// Theme type is a nested partial\nexport type ColorTheme = Subset<(typeof TailwindTheme)[\"colors\"]>;\nexport type Theme = {\n  colors?: ColorTheme;\n  breakpoints?: Subset<typeof defaultBreakpoints>;\n};\nexport const DefaultTheme = {\n  ...TailwindTheme,\n  breakpoints: defaultBreakpoints,\n};\n\n// Helps name a CSS variable based on the class prefix.\nexport function nameCSSVar(name: string): string {\n  return `--${CLASS_PREFIX}-${name}`;\n}\n\n// Takes a theme and turns it into a CSSProperties that sets CSS Variables.\nexport function mapToCSSVar(colorConfig: ColorTheme): Record<string, string> {\n  const properties: { [variable: string]: string } = {};\n  Object.entries(colorConfig).forEach(([colorTitle, colorValueOrObj]) => {\n    if (typeof colorValueOrObj === \"string\") {\n      properties[nameCSSVar(colorTitle)] = hexToRGB(colorValueOrObj);\n    } else {\n      Object.entries(colorValueOrObj).forEach(([colorName, value]) => {\n        properties[nameCSSVar(`${colorTitle}-${colorName}`)] = hexToRGB(value);\n      });\n    }\n  });\n  return properties;\n}\n\n// Converts hex values to RGB values if it's not already in RGB format.\nfunction hexToRGB(colorMapping: string, opacity?: string): string {\n  if (colorMapping.startsWith(\"#\")) {\n    const r = parseInt(colorMapping.slice(1, 3), 16);\n    const g = parseInt(colorMapping.slice(3, 5), 16);\n    const b = parseInt(colorMapping.slice(5, 7), 16);\n    if (opacity) {\n      return `rgba(${r}, ${g}, ${b}, ${opacity})`;\n    }\n    return `rgb(${r}, ${g}, ${b})`;\n  }\n  return colorMapping;\n}\n","import { createContext, createRef, RefObject } from \"react\";\nimport { IFrameTheme } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile-iframe\";\nimport { Locals } from \"@/i18n\";\nimport { DefaultTheme, Theme } from \"@/styles/tailwind.theme\";\n\nexport interface ThemeContextValue {\n  theme: Required<Theme>;\n  iframeTheme?: IFrameTheme;\n  ctwThemeRef: RefObject<HTMLDivElement>;\n  locals?: Locals;\n}\n\nexport const ThemeContext = createContext<ThemeContextValue>({\n  theme: DefaultTheme,\n  ctwThemeRef: createRef<HTMLDivElement>(),\n});\n","import { useContext } from \"react\";\nimport { ThemeContext } from \"./context\";\n\nexport function useTheme() {\n  return useContext(ThemeContext);\n}\n","import useResizeObserverTemp from \"@react-hook/resize-observer\";\nimport { RefObject, useCallback, useState } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"./use-isomorphic-layout-effect\";\nimport { useTheme } from \"@/components/core/providers/theme/use-theme\";\nimport { defaultBreakpoints } from \"@/styles/tailwind.theme\";\nimport { mapValues } from \"@/utils/nodash\";\n\n// This is an ugly hack / work around for a SSR/CommonJS/build\n// issue where useResizeObserver is getting compiled to\n// foo = require(\"@react-hook/resize-observer\")\n// instead of\n// foo = require(\"@react-hook/resize-observer\").default\n// causing a \"foo is not a function\" error.\n// This shouldn't be a problem when using ES Modules or for\n// libraries that don't use default exports!\nconst useResizeObserver: typeof useResizeObserverTemp =\n  // @ts-ignore\n  useResizeObserverTemp.default || useResizeObserverTemp;\n\ntype BreakpointKeys = keyof typeof defaultBreakpoints;\nexport type Breakpoints = Record<BreakpointKeys, boolean> & { width: number };\n\nexport function useBreakpoints<T extends HTMLElement>(target: RefObject<T>) {\n  const { theme } = useTheme();\n  const [breakpoints, setBreakpoints] = useState<Breakpoints>({\n    ...mapValues(defaultBreakpoints, () => false),\n    width: 0,\n  });\n\n  const updateBreakpoints = useCallback(() => {\n    const targetEl = target.current;\n    if (!targetEl) return;\n    const { width } = targetEl.getBoundingClientRect();\n\n    // Fix bug where display: none / hidden would cause\n    // a component to have 0 width. In this case we don't want\n    // to update our breakpoints. This fixes an issue with TabGroup\n    // where switching tabs in ZAP would cause a flash as\n    // the component was initially \"stacked\" due to 0 width.\n    if (width === 0) return;\n\n    const breakpointsTmp = { width } as Breakpoints;\n    Object.entries(theme.breakpoints).forEach(([key, value]) => {\n      breakpointsTmp[key as BreakpointKeys] = width < value;\n    });\n    setBreakpoints(breakpointsTmp);\n  }, [target, theme.breakpoints]);\n\n  // Update on initial render (useIsomorphicLayoutEffect) and\n  // on any resizes.\n  useIsomorphicLayoutEffect(updateBreakpoints, [target.current, theme]);\n  useResizeObserver(target.current, updateBreakpoints);\n\n  return breakpoints;\n}\n","import { useEffect, useState } from \"react\";\n\nconst useHeaderOffset = (elementId: string) => {\n  const [offset, setOffset] = useState(0);\n\n  useEffect(() => {\n    const updateOffset = () => {\n      const element = document.getElementById(elementId);\n      const newOffset = element ? element.getBoundingClientRect().height : 0;\n      setOffset(newOffset);\n    };\n\n    // Delay setting up the ResizeObserver to give the element time to reach its full size\n    const timeoutId = setTimeout(() => {\n      const element = document.getElementById(elementId);\n      if (element) {\n        const resizeObserver = new ResizeObserver(updateOffset);\n        resizeObserver.observe(element);\n\n        return () => {\n          resizeObserver.unobserve(element);\n        };\n      }\n\n      return undefined;\n    }, 500);\n\n    return () => {\n      clearTimeout(timeoutId);\n    };\n  }, [elementId]);\n\n  return offset;\n};\n\nexport default useHeaderOffset;\n","/* eslint-disable react/no-array-index-key */\nimport { faChevronDown } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { XIcon } from \"@heroicons/react/outline\";\nimport cx from \"classnames\";\nimport { ReactNode, useRef, useState } from \"react\";\nimport { DOCUMENT_HEADER_ID, TABLE_OF_CONTENT_ID } from \"../../../constants\";\nimport { navigateIntoView } from \"../../helpers/navigate-into-view\";\nimport { DocumentOnlyProps, SectionType } from \"../../types\";\nimport \"../../../styles.scss\";\nimport ZusSVG from \"@/assets/zus-logo.svg\";\nimport { Breakpoints, useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport useHeaderOffset from \"@/hooks/use-header-offset\";\nimport { PatientModel, useAnalytics, usePatient } from \"@/index\";\n\ntype HeaderProps = DocumentOnlyProps & {\n  children?: ReactNode;\n  sections: SectionType[];\n  onClose?: () => void;\n  overridePatient: PatientModel | undefined;\n};\n\nexport const Header = ({ children, sections, overridePatient }: HeaderProps): JSX.Element => {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n  const headerOffset = useHeaderOffset(DOCUMENT_HEADER_ID);\n\n  const tableOfContents = [\n    ...sections.map(({ title, id, isEmpty }) => ({ title, id, isEmpty })),\n    { title: \"Demographic Details\", id: \"demographic-details\", isEmpty: false },\n  ];\n\n  return (\n    <>\n      <div\n        className={cx(\"ctw-text-lg ctw-top-0 ctw-z-50\", {\n          \"ctw-sticky\": !breakpoints.md,\n        })}\n        id={TABLE_OF_CONTENT_ID}\n        ref={containerRef}\n        style={{ top: headerOffset }}\n      >\n        <TableOfContents\n          sections={tableOfContents}\n          breakpoints={breakpoints}\n          overridePatient={overridePatient}\n        />\n      </div>\n      <div className=\"ctw-ccda-header-container ctw-space-y-4\">\n        <div className=\"ctw-flex ctw-w-full\">\n          <div className=\"ctw-w-fit ctw-basis-1/2\">{children}</div>\n        </div>\n      </div>\n    </>\n  );\n};\n\nexport const DocumentHeader = ({\n  onClose,\n  actions,\n  overridePatient,\n}: {\n  onClose?: () => void;\n  actions?: ReactNode;\n  overridePatient?: PatientModel | undefined;\n}) => {\n  const zapContextPatient = usePatient();\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n\n  const patient = overridePatient || zapContextPatient.data;\n\n  return (\n    <div\n      className=\"ctw-flex ctw-justify-between ctw-bg-bg-black ctw-text-white ctw-p-3 ctw-top-0 ctw-z-50 ctw-sticky\"\n      ref={containerRef}\n      id={DOCUMENT_HEADER_ID}\n    >\n      <div className=\"ctw-flex ctw-space-x-4 ctw-overflow-hidden\">\n        <img src={ZusSVG} alt=\"Zus\" />\n        <div\n          className={cx(\"ctw-space-x-1\", {\n            \"ctw-text-ellipsis ctw-text-sm ctw-overflow-hidden ctw-whitespace-nowrap\":\n              breakpoints.sm,\n          })}\n        >\n          <span>{patient?.firstName}</span>\n          <span>{patient?.lastName}</span>\n          <span className=\"ctw-uppercase\">{`(${patient?.gender?.[0]}),`}</span>\n          <span>{patient?.dob}</span>\n          <span>{`(${patient?.age}yr)`}</span>\n        </div>\n      </div>\n      <div className=\"ctw-flex ctw-space-x-2\">\n        {actions && <div className=\"ctw-flex\">{actions}</div>}\n        <CloseDocument onClose={onClose}>\n          <span className=\" ctw-text-white ctw-text-sm\">Close</span>\n          <XIcon className=\"ctw-h-4 ctw-w-4 ctw-text-white\" aria-hidden=\"true\" />\n        </CloseDocument>\n      </div>\n    </div>\n  );\n};\n\nconst TableOfContents = ({\n  sections,\n  breakpoints,\n  overridePatient,\n}: {\n  sections: SectionType[];\n  breakpoints: Breakpoints | undefined;\n  overridePatient: PatientModel | undefined;\n}) => {\n  const [isHidden, setIsHidden] = useState(false);\n  const { trackInteraction } = useAnalytics();\n\n  const handleClick = () => {\n    setIsHidden(!isHidden);\n    trackInteraction(\"toggle_document_section\", {\n      action: isHidden ? \"collapse_document_section\" : \"expand_document_section\",\n    });\n  };\n\n  return (\n    <div className=\"ctw-bg-bg-lighter ctw-min-w-[300px] ctw-w-full ctw-flex ctw-flex-col\">\n      <div className=\"ctw-text-sm ctw-px-4 ctw-py-2  ctw-uppercase ctw-bg-bg-zusLogoBlue ctw-text-white \">\n        <button type=\"button\" className=\"ctw-ccda-section-arrow section\" onClick={handleClick}>\n          <span className=\"ctw-hidden\">hide</span>\n          <FontAwesomeIcon\n            icon={faChevronDown}\n            className={cx(\"ctw-ml-auto ctw-w-4\", { \"ctw-transform ctw-rotate-[270deg]\": isHidden })}\n          />\n        </button>\n        in this document\n      </div>\n      {!isHidden && (\n        <div>\n          <div\n            className={cx(\n              \"ctw-in-this-document-section ctw-items-baseline ctw-space-y-2.5 ctw-px-4 ctw-py-2\",\n              { \"!ctw-flex ctw-flex-col\": breakpoints?.lg },\n            )}\n          >\n            <TableOfContentsItems sections={sections} breakpoints={breakpoints} />\n            <Details breakpoints={breakpoints} overridePatient={overridePatient} />\n          </div>\n        </div>\n      )}\n    </div>\n  );\n};\n\nconst TableOfContentsItems = ({\n  sections,\n  breakpoints,\n}: {\n  sections: SectionType[];\n  breakpoints: Breakpoints | undefined;\n}) => {\n  // We use the section length to determine whether we should override the default number of columns\n  const betterWithTwoCols = sections.length > 7 && sections.length < 15;\n  const betterWithOneCol = sections.length < 8;\n  const divisor = () => {\n    if (betterWithOneCol) return 1;\n    if (breakpoints?.md || betterWithTwoCols) return 2;\n    return 3;\n  };\n\n  const gridTemplateRows = Math.ceil(sections.length / divisor());\n  const gridTemplateColumns = divisor();\n\n  return (\n    <div className=\"ctw-w-full ctw-space-y-1\">\n      <h1 className=\"ctw-font-medium ctw-text-content-light ctw-uppercase ctw-text-sm\">\n        Contents Menu\n      </h1>\n      <ol\n        style={\n          {\n            \"--number-of-columns\": gridTemplateColumns,\n            \"--number-of-rows\": gridTemplateRows,\n          } as React.CSSProperties\n        }\n        className={cx(\n          \"ctw-items-baseline ctw-list-decimal ctw-list-inside table-of-contents ctw-text-sm\",\n          { \"!ctw-gap-1 \": breakpoints?.sm },\n        )}\n      >\n        {sections.map(({ title, id, isEmpty }) => (\n          <button\n            key={`el-text-${id}`}\n            className={cx(\n              \"ctw-button-list-item\",\n              { \"!ctw-p-1\": breakpoints?.sm },\n              { \"ctw-text-content-light\": isEmpty },\n            )}\n            type=\"button\"\n            onClick={() => navigateIntoView(id)}\n          >\n            <li className=\"ctw-list-item\">\n              {title} {isEmpty && \" (empty)\"}\n            </li>\n          </button>\n        ))}\n      </ol>\n    </div>\n  );\n};\n\nconst Details = ({\n  breakpoints,\n  overridePatient,\n}: {\n  breakpoints: Breakpoints | undefined;\n  overridePatient: PatientModel | undefined;\n}) => {\n  const zapContextPatient = usePatient();\n  const patient = overridePatient || zapContextPatient.data;\n\n  return (\n    <div className={cx(\"ctw-text-base ctw-space-y-1\", { \"ctw-p-1\": breakpoints?.md })}>\n      <div className=\"ctw-font-medium ctw-text-content-light ctw-uppercase ctw-text-sm\">\n        Details\n      </div>\n      <div className=\"ctw-patient-details\">\n        <div className=\"item\">\n          <div className=\"ctw-capitalize ctw-font-medium\">patient name:</div>\n          <div className=\"ctw-space-x-1\">\n            <span>{patient?.firstName}</span>\n            <span>{patient?.lastName}</span>\n            <span className=\"ctw-uppercase\">{`(${patient?.gender?.[0]})`}</span>\n          </div>\n        </div>\n        <div className=\"item\">\n          <div className=\"ctw-capitalize ctw-font-medium\">dob:</div>\n          <div>{patient?.dob}</div>\n        </div>\n        <div className=\"item\">\n          <div className=\"ctw-capitalize ctw-font-medium\">phone:</div>\n          <div>{patient?.phoneNumber}</div>\n        </div>\n        <div className=\"item\">\n          <div className=\"ctw-capitalize ctw-font-medium\">email:</div>\n          <div>{patient?.email}</div>\n        </div>\n      </div>\n    </div>\n  );\n};\n\nconst CloseDocument = ({ onClose, children }: { onClose?: () => void; children?: ReactNode }) => {\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <button\n      type=\"button\"\n      aria-label=\"close\"\n      onClick={() => {\n        if (onClose) {\n          onClose();\n        }\n\n        trackInteraction(\"close_document\");\n      }}\n      className=\"ctw-btn-clear ctw-flex ctw-items-center ctw-space-x-1\"\n    >\n      {children}\n    </button>\n  );\n};\n","import { createContext } from \"react\";\n\ntype AnalyticsContextValue = {\n  componentName?: string;\n};\n\nexport const AnalyticsContext = createContext<AnalyticsContextValue>({});\n","import { createContext } from \"react\";\nimport { TrackingMetadata } from \"./analytics/use-analytics\";\nimport { DrawerProps } from \"../drawer\";\n\nexport type OpenDrawerProps = {\n  trackingMetadata?: TrackingMetadata;\n  component: ({\n    isOpen,\n    onClose,\n    onOpen,\n    onAfterOpen,\n    trackingMetadata,\n  }: Pick<DrawerProps, \"isOpen\" | \"onClose\" | \"onOpen\" | \"onAfterOpen\" | \"trackingMetadata\">) =>\n    | JSX.Element\n    | undefined;\n};\n\nexport type DrawerState = {\n  closeDrawer: () => void;\n  openDrawer: (props: OpenDrawerProps) => void;\n};\n\nexport const DrawerContext = createContext<DrawerState | undefined>(undefined);\n","import { ReactNode, useContext, useMemo, useState } from \"react\";\nimport { DrawerContext, DrawerState, OpenDrawerProps } from \"./drawer-context\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\n\ninterface ProviderProps {\n  children: ReactNode;\n}\n\n// Define this outside of the rendered component to avoid eslint error.\nconst dummyChild = (_props: unknown) => <div />;\n\nexport function DrawerProvider({ children }: ProviderProps) {\n  const [isOpen, setIsOpen] = useState(false);\n  const [drawerProps, setProps] = useState<OpenDrawerProps>({\n    // Create some dummy initial props for the drawer. These will get\n    // overwritten when openDrawer() is used.\n    component: dummyChild,\n  });\n  const analytics = useAnalytics();\n\n  const state = useMemo(\n    () => ({\n      closeDrawer: () => {\n        setIsOpen(false);\n      },\n      openDrawer: (props: OpenDrawerProps) => {\n        setProps(props);\n        // Ensure isOpen starts as false and then async set it to true.\n        // This ensures the drawer is added first before isOpen is set to\n        // true which fixes an issue around initial opening animation/transition.\n        setIsOpen(false);\n        setTimeout(() => {\n          setIsOpen(true);\n          analytics.trackInteraction(\"open_drawer\", {\n            // Datadog we write the drawer name into the metric name itself (prop ignored by analytics)\n            datadogMetricName: `open_drawer.${props.trackingMetadata?.action ?? \"\"}`.replace(\n              /(\\.)$/,\n              \"\",\n            ),\n            // We pass details of the drawer\n            ...props.trackingMetadata,\n          });\n        });\n      },\n    }),\n\n    [analytics],\n  );\n\n  return (\n    <DrawerContext.Provider value={state}>\n      {drawerProps.component({\n        isOpen,\n        onClose: () => {\n          setIsOpen(false);\n          setProps({\n            component: dummyChild,\n          });\n        },\n      })}\n      {children}\n    </DrawerContext.Provider>\n  );\n}\n\nexport const useDrawer = (): DrawerState => {\n  const context = useContext(DrawerContext);\n\n  if (!context) {\n    throw new Error(\"useDrawer must be used within a DrawerProvider\");\n  }\n\n  return context;\n};\n","import { createContext } from \"react\";\n\nexport type OpenModalProps = {\n  component: ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => JSX.Element;\n};\n\nexport type ModalState = {\n  openModal: (props: OpenModalProps) => void;\n};\n\nexport const ModalContext = createContext<ModalState | undefined>(undefined);\n","import { ReactNode, useContext, useMemo, useState } from \"react\";\nimport { ModalContext, ModalState, OpenModalProps } from \"./modal-context\";\n\n// NOTE: This is basically identical to DrawerProvider.\n// We use a seperate provider for modals for two reasons:\n//  1. Allows us to have both a drawer and a modal open at\n//     the same time via the providers.\n//  2. Allows modals and drawer interfaces to diverge a bit if needed.\n\ninterface ProviderProps {\n  children: ReactNode;\n}\n\n// Define this outside of the rendered component to avoid eslint error.\nconst dummyChild = (_props: unknown) => <div />;\n\nexport function ModalProvider({ children }: ProviderProps) {\n  const [isOpen, setIsOpen] = useState(false);\n  const [modalProps, setProps] = useState<OpenModalProps>({\n    // Create some dummy initial props for the modal. These will get\n    // overwritten when openModal() is used.\n    component: dummyChild,\n  });\n\n  const state = useMemo(\n    () => ({\n      openModal: (props: OpenModalProps) => {\n        setProps(props);\n\n        // Ensure isOpen starts as false and then async set it to true.\n        // This ensures the modal is added first before isOpen is set to\n        // true which fixes an issue around initial opening animation/transition.\n        setIsOpen(false);\n        setTimeout(() => {\n          setIsOpen(true);\n        });\n      },\n    }),\n    []\n  );\n\n  return (\n    <ModalContext.Provider value={state}>\n      {modalProps.component({\n        isOpen,\n        onClose: () => setIsOpen(false),\n      })}\n      {children}\n    </ModalContext.Provider>\n  );\n}\n\nexport const useModal = (): ModalState => {\n  const context = useContext(ModalContext);\n\n  if (!context) {\n    throw new Error(\"useModal must be used within a ModalProvider\");\n  }\n\n  return context;\n};\n","import { createContext } from \"react\";\nimport { PatientFormData } from \"../../content/forms/actions/patients\";\nimport { Tag } from \"@/fhir/types\";\n\nexport type PatientState = {\n  patientResourceID?: string;\n  patientID?: string;\n  systemURL?: string;\n  tags?: Tag[];\n  onPatientSave?: (data: PatientFormData) => Promise<void>;\n  onResourceSave?: (data: fhir4.Resource, action: \"create\" | \"update\") => void;\n};\n\nexport const PatientContext = createContext<PatientState | undefined>(undefined);\n","import { createContext } from \"react\";\n\nexport type CTWToken = {\n  accessToken: string;\n  expiresAt: number; // Timestamp in ms.\n};\n\nexport interface AuthenticationContextValue {\n  getAuthToken: () => Promise<string>;\n}\n\nexport const AuthenticationContext = createContext<AuthenticationContextValue>({\n  getAuthToken: () => Promise.resolve(\"\"),\n});\n","import { useContext } from \"react\";\nimport { AuthenticationContext, AuthenticationContextValue } from \"./context\";\n\nexport function useGetAuthToken(): AuthenticationContextValue[\"getAuthToken\"] {\n  const context = useContext(AuthenticationContext);\n  return context.getAuthToken;\n}\n","import Client from \"fhir-kit-client\";\nimport { createContext } from \"react\";\nimport { Env } from \"./types\";\nimport { OnResourceSaveCallback } from \"@/fhir/action-helper\";\n\nexport type FeatureFlags = {\n  enableViewFhirButton?: boolean;\n  patientRequestForm?: boolean;\n  // In the standalone app, we want to open the CCDA in a new tab. It's hopeful in the future the ZAP could be able to\n  // open in a new tab as well.\n  openCCDAInNewTab?: boolean;\n};\n\nexport type CTWState = {\n  env: Env;\n  builderId?: string;\n  headers?: HeadersInit;\n  featureFlags?: FeatureFlags;\n  onResourceSave?: OnResourceSaveCallback;\n  resourceSaveHeaders?: Record<string, string>;\n  allowSmallBreakpointCCDAViewer?: boolean;\n};\n\nexport type CTWRequestContext = {\n  env: Env;\n  headers?: HeadersInit;\n  authToken: string;\n  // The user's builder ID.\n  builderId: string;\n  userType: string | undefined;\n  // The optional builder ID used in case the user is impersonating a builder.\n  contextBuilderId: string | undefined;\n  fhirClient: Client;\n  fhirWriteBackClient: Client;\n  fetchFromFqs: (\n    url: string,\n    options: RequestInit,\n  ) => Promise<{ data: unknown; headers: Response[\"headers\"] }>;\n  onResourceSave: OnResourceSaveCallback;\n  resourceSaveHeaders?: Record<string, string>;\n};\n\nexport const CTWStateContext = createContext<CTWState | undefined>(undefined);\n","import { Env } from \"@/components/core/providers/types\";\n\nexport const getZusApiBaseUrl = (env: Env) =>\n  env === \"production\" ? `https://api.zusapi.com` : `https://api.${env}.zusapi.com`;\n\nexport const getZusServiceUrl = (env: Env, service: string) => {\n  if (env === \"phi-test\" && [\"fqs\", \"patient-history\"].includes(service)) {\n    return `https://${service}.phitest.zusapi.com`;\n  }\n  return env === \"production\"\n    ? `https://${service}.zusapi.com`\n    : `https://${service}.${env}.zusapi.com`;\n};\n\nexport const getZapIFrameUrl = (env: Env) =>\n  env === \"production\" ? \"https://zap.zushealth.com\" : `https://zap.${env}.zushealth.com`;\n\nexport const getZusProxyApiBaseUrl = (env: Env) => {\n  const { VITE_LOCAL_EHR_HOOKS_URL } = import.meta.env;\n  if (VITE_LOCAL_EHR_HOOKS_URL) {\n    // This environment variable is only used locally. It allows the UI to talk\n    // to a locally hosted ehr-data-integration service.\n    return VITE_LOCAL_EHR_HOOKS_URL;\n  }\n  return env === \"production\"\n    ? `https://ehr-hooks.zusapi.com/proxy`\n    : `https://ehr-hooks.${env}.zusapi.com/proxy`;\n};\n\nexport const getZusFhirBaseUrl = (env: Env) => `${getZusApiBaseUrl(env)}/fhir`;\n\nexport const getZusFhirWriteBackBaseUrl = (env: Env) => `${getZusProxyApiBaseUrl(env)}/fhir`;\n\nexport const getFormsConditionsUrl = (env: Env) =>\n  `${getZusApiBaseUrl(env)}/forms-data/terminology/conditions`;\n\nexport const getFormsMedicationsUrl = (env: Env) =>\n  `${getZusApiBaseUrl(env)}/forms-data/terminology/dosages`;\n\nexport const getCTWBaseUrl = (env: string) => {\n  if (window.location.hostname === \"localhost\") {\n    // Locally we just want to send to 3000. This provides 2 outcomes:\n    // - If CTW is running locally on 3000, we can test with to dev Datadog\n    // - Else, the requests fail silently\n    return import.meta.env.VITE_LOCAL_METRICS_URL || \"http://localhost:3000\";\n  }\n\n  return [\"prod\", \"production\"].includes(env)\n    ? `https://app.zushealth.com`\n    : `https://app.${env}.zushealth.com`;\n};\n\nexport const getLensBuilderId = (env: Env) => {\n  switch (env) {\n    case \"dev\":\n      return \"bc1c791a-581c-4117-8b17-f9c59f39caf8\";\n    case \"phitest\":\n      return \"186d5446-46ec-4beb-8699-9e42903a3dd2\";\n    case \"production\":\n      return \"5e0f86eb-bb0b-4543-8489-262fcbf661da\";\n    case \"sandbox\":\n      return \"d8ab3e86-7ff2-482d-bbed-b30df2dd7ec7\";\n    default:\n      throw new Error(\"Unknown environment\");\n  }\n};\n","export class RequestError extends Error {\n  statusCode: number;\n\n  statusText: string;\n\n  requestInfo: Response;\n\n  stackTrace: string | undefined;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor(response: Response, ...params: any[]) {\n    super(...params);\n\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, RequestError);\n      this.stackTrace = this.stack;\n    }\n\n    this.name = \"RequestError\";\n    this.statusCode = response.status;\n    this.statusText = response.statusText;\n    this.requestInfo = response;\n  }\n}\n","import { Query, QueryKey } from \"@tanstack/react-query\";\nimport { RequestError } from \"./error\";\n\nexport class ReactQueryError extends Error {\n  queryKey: QueryKey;\n\n  stackTrace: string | undefined;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor(query: Query, ...params: any[]) {\n    super(...params);\n\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, RequestError);\n      this.stackTrace = this.stack;\n    }\n\n    this.name = \"RequestError\";\n    this.queryKey = query.queryKey;\n  }\n}\n","const SESSION_INACTIVE_TIME_MS = 1000 * 60 * 60; // 1 hour\nconst SESSION_TIMESTAMP_KEY = \"zus:sessionLastActiveTimestamp\";\nconst SESSION_USER_ID_KEY = \"zus:sessionUserId\";\n\nexport class Session {\n  static isActive() {\n    const timestampStr = localStorage.getItem(SESSION_TIMESTAMP_KEY);\n    if (timestampStr) {\n      const lastActiveTimestamp = parseInt(timestampStr, 10);\n      const now = new Date().getTime();\n      return now - SESSION_INACTIVE_TIME_MS < lastActiveTimestamp;\n    }\n    return false;\n  }\n\n  static setSessionLastActiveTimestamp() {\n    localStorage.setItem(SESSION_TIMESTAMP_KEY, new Date().getTime().toString());\n  }\n\n  static clearSessionLastActiveTimestamp() {\n    localStorage.removeItem(SESSION_TIMESTAMP_KEY);\n  }\n\n  /**\n   * Sets the session user id. If the user id is already set and not of the\n   * same value, the active session will be cleared.\n   */\n  static setSessionUserId(userId: string) {\n    const sessionUserId = localStorage.getItem(SESSION_USER_ID_KEY);\n    if (sessionUserId !== userId) {\n      Session.clearSession();\n      localStorage.setItem(SESSION_USER_ID_KEY, userId);\n    }\n  }\n\n  static clearSession() {\n    localStorage.removeItem(SESSION_USER_ID_KEY);\n    localStorage.removeItem(SESSION_TIMESTAMP_KEY);\n  }\n}\n","export function isOperationOutcome(response: unknown): response is fhir4.OperationOutcome {\n  if (typeof response === \"object\" && response !== null) {\n    return \"issue\" in response;\n  }\n  return false;\n}\n","/** Used to map aliases to their real names. */\nexports.aliasToReal = {\n\n  // Lodash aliases.\n  'each': 'forEach',\n  'eachRight': 'forEachRight',\n  'entries': 'toPairs',\n  'entriesIn': 'toPairsIn',\n  'extend': 'assignIn',\n  'extendAll': 'assignInAll',\n  'extendAllWith': 'assignInAllWith',\n  'extendWith': 'assignInWith',\n  'first': 'head',\n\n  // Methods that are curried variants of others.\n  'conforms': 'conformsTo',\n  'matches': 'isMatch',\n  'property': 'get',\n\n  // Ramda aliases.\n  '__': 'placeholder',\n  'F': 'stubFalse',\n  'T': 'stubTrue',\n  'all': 'every',\n  'allPass': 'overEvery',\n  'always': 'constant',\n  'any': 'some',\n  'anyPass': 'overSome',\n  'apply': 'spread',\n  'assoc': 'set',\n  'assocPath': 'set',\n  'complement': 'negate',\n  'compose': 'flowRight',\n  'contains': 'includes',\n  'dissoc': 'unset',\n  'dissocPath': 'unset',\n  'dropLast': 'dropRight',\n  'dropLastWhile': 'dropRightWhile',\n  'equals': 'isEqual',\n  'identical': 'eq',\n  'indexBy': 'keyBy',\n  'init': 'initial',\n  'invertObj': 'invert',\n  'juxt': 'over',\n  'omitAll': 'omit',\n  'nAry': 'ary',\n  'path': 'get',\n  'pathEq': 'matchesProperty',\n  'pathOr': 'getOr',\n  'paths': 'at',\n  'pickAll': 'pick',\n  'pipe': 'flow',\n  'pluck': 'map',\n  'prop': 'get',\n  'propEq': 'matchesProperty',\n  'propOr': 'getOr',\n  'props': 'at',\n  'symmetricDifference': 'xor',\n  'symmetricDifferenceBy': 'xorBy',\n  'symmetricDifferenceWith': 'xorWith',\n  'takeLast': 'takeRight',\n  'takeLastWhile': 'takeRightWhile',\n  'unapply': 'rest',\n  'unnest': 'flatten',\n  'useWith': 'overArgs',\n  'where': 'conformsTo',\n  'whereEq': 'isMatch',\n  'zipObj': 'zipObject'\n};\n\n/** Used to map ary to method names. */\nexports.aryMethod = {\n  '1': [\n    'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',\n    'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',\n    'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',\n    'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',\n    'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',\n    'uniqueId', 'words', 'zipAll'\n  ],\n  '2': [\n    'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',\n    'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',\n    'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',\n    'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',\n    'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',\n    'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',\n    'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',\n    'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',\n    'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',\n    'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',\n    'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',\n    'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',\n    'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',\n    'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',\n    'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',\n    'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',\n    'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',\n    'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',\n    'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',\n    'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',\n    'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',\n    'zipObjectDeep'\n  ],\n  '3': [\n    'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',\n    'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',\n    'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',\n    'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',\n    'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',\n    'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',\n    'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',\n    'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',\n    'xorWith', 'zipWith'\n  ],\n  '4': [\n    'fill', 'setWith', 'updateWith'\n  ]\n};\n\n/** Used to map ary to rearg configs. */\nexports.aryRearg = {\n  '2': [1, 0],\n  '3': [2, 0, 1],\n  '4': [3, 2, 0, 1]\n};\n\n/** Used to map method names to their iteratee ary. */\nexports.iterateeAry = {\n  'dropRightWhile': 1,\n  'dropWhile': 1,\n  'every': 1,\n  'filter': 1,\n  'find': 1,\n  'findFrom': 1,\n  'findIndex': 1,\n  'findIndexFrom': 1,\n  'findKey': 1,\n  'findLast': 1,\n  'findLastFrom': 1,\n  'findLastIndex': 1,\n  'findLastIndexFrom': 1,\n  'findLastKey': 1,\n  'flatMap': 1,\n  'flatMapDeep': 1,\n  'flatMapDepth': 1,\n  'forEach': 1,\n  'forEachRight': 1,\n  'forIn': 1,\n  'forInRight': 1,\n  'forOwn': 1,\n  'forOwnRight': 1,\n  'map': 1,\n  'mapKeys': 1,\n  'mapValues': 1,\n  'partition': 1,\n  'reduce': 2,\n  'reduceRight': 2,\n  'reject': 1,\n  'remove': 1,\n  'some': 1,\n  'takeRightWhile': 1,\n  'takeWhile': 1,\n  'times': 1,\n  'transform': 2\n};\n\n/** Used to map method names to iteratee rearg configs. */\nexports.iterateeRearg = {\n  'mapKeys': [1],\n  'reduceRight': [1, 0]\n};\n\n/** Used to map method names to rearg configs. */\nexports.methodRearg = {\n  'assignInAllWith': [1, 0],\n  'assignInWith': [1, 2, 0],\n  'assignAllWith': [1, 0],\n  'assignWith': [1, 2, 0],\n  'differenceBy': [1, 2, 0],\n  'differenceWith': [1, 2, 0],\n  'getOr': [2, 1, 0],\n  'intersectionBy': [1, 2, 0],\n  'intersectionWith': [1, 2, 0],\n  'isEqualWith': [1, 2, 0],\n  'isMatchWith': [2, 1, 0],\n  'mergeAllWith': [1, 0],\n  'mergeWith': [1, 2, 0],\n  'padChars': [2, 1, 0],\n  'padCharsEnd': [2, 1, 0],\n  'padCharsStart': [2, 1, 0],\n  'pullAllBy': [2, 1, 0],\n  'pullAllWith': [2, 1, 0],\n  'rangeStep': [1, 2, 0],\n  'rangeStepRight': [1, 2, 0],\n  'setWith': [3, 1, 2, 0],\n  'sortedIndexBy': [2, 1, 0],\n  'sortedLastIndexBy': [2, 1, 0],\n  'unionBy': [1, 2, 0],\n  'unionWith': [1, 2, 0],\n  'updateWith': [3, 1, 2, 0],\n  'xorBy': [1, 2, 0],\n  'xorWith': [1, 2, 0],\n  'zipWith': [1, 2, 0]\n};\n\n/** Used to map method names to spread configs. */\nexports.methodSpread = {\n  'assignAll': { 'start': 0 },\n  'assignAllWith': { 'start': 0 },\n  'assignInAll': { 'start': 0 },\n  'assignInAllWith': { 'start': 0 },\n  'defaultsAll': { 'start': 0 },\n  'defaultsDeepAll': { 'start': 0 },\n  'invokeArgs': { 'start': 2 },\n  'invokeArgsMap': { 'start': 2 },\n  'mergeAll': { 'start': 0 },\n  'mergeAllWith': { 'start': 0 },\n  'partial': { 'start': 1 },\n  'partialRight': { 'start': 1 },\n  'without': { 'start': 1 },\n  'zipAll': { 'start': 0 }\n};\n\n/** Used to identify methods which mutate arrays or objects. */\nexports.mutate = {\n  'array': {\n    'fill': true,\n    'pull': true,\n    'pullAll': true,\n    'pullAllBy': true,\n    'pullAllWith': true,\n    'pullAt': true,\n    'remove': true,\n    'reverse': true\n  },\n  'object': {\n    'assign': true,\n    'assignAll': true,\n    'assignAllWith': true,\n    'assignIn': true,\n    'assignInAll': true,\n    'assignInAllWith': true,\n    'assignInWith': true,\n    'assignWith': true,\n    'defaults': true,\n    'defaultsAll': true,\n    'defaultsDeep': true,\n    'defaultsDeepAll': true,\n    'merge': true,\n    'mergeAll': true,\n    'mergeAllWith': true,\n    'mergeWith': true,\n  },\n  'set': {\n    'set': true,\n    'setWith': true,\n    'unset': true,\n    'update': true,\n    'updateWith': true\n  }\n};\n\n/** Used to map real names to their aliases. */\nexports.realToAlias = (function() {\n  var hasOwnProperty = Object.prototype.hasOwnProperty,\n      object = exports.aliasToReal,\n      result = {};\n\n  for (var key in object) {\n    var value = object[key];\n    if (hasOwnProperty.call(result, value)) {\n      result[value].push(key);\n    } else {\n      result[value] = [key];\n    }\n  }\n  return result;\n}());\n\n/** Used to map method names to other names. */\nexports.remap = {\n  'assignAll': 'assign',\n  'assignAllWith': 'assignWith',\n  'assignInAll': 'assignIn',\n  'assignInAllWith': 'assignInWith',\n  'curryN': 'curry',\n  'curryRightN': 'curryRight',\n  'defaultsAll': 'defaults',\n  'defaultsDeepAll': 'defaultsDeep',\n  'findFrom': 'find',\n  'findIndexFrom': 'findIndex',\n  'findLastFrom': 'findLast',\n  'findLastIndexFrom': 'findLastIndex',\n  'getOr': 'get',\n  'includesFrom': 'includes',\n  'indexOfFrom': 'indexOf',\n  'invokeArgs': 'invoke',\n  'invokeArgsMap': 'invokeMap',\n  'lastIndexOfFrom': 'lastIndexOf',\n  'mergeAll': 'merge',\n  'mergeAllWith': 'mergeWith',\n  'padChars': 'pad',\n  'padCharsEnd': 'padEnd',\n  'padCharsStart': 'padStart',\n  'propertyOf': 'get',\n  'rangeStep': 'range',\n  'rangeStepRight': 'rangeRight',\n  'restFrom': 'rest',\n  'spreadFrom': 'spread',\n  'trimChars': 'trim',\n  'trimCharsEnd': 'trimEnd',\n  'trimCharsStart': 'trimStart',\n  'zipAll': 'zip'\n};\n\n/** Used to track methods that skip fixing their arity. */\nexports.skipFixed = {\n  'castArray': true,\n  'flow': true,\n  'flowRight': true,\n  'iteratee': true,\n  'mixin': true,\n  'rearg': true,\n  'runInContext': true\n};\n\n/** Used to track methods that skip rearranging arguments. */\nexports.skipRearg = {\n  'add': true,\n  'assign': true,\n  'assignIn': true,\n  'bind': true,\n  'bindKey': true,\n  'concat': true,\n  'difference': true,\n  'divide': true,\n  'eq': true,\n  'gt': true,\n  'gte': true,\n  'isEqual': true,\n  'lt': true,\n  'lte': true,\n  'matchesProperty': true,\n  'merge': true,\n  'multiply': true,\n  'overArgs': true,\n  'partial': true,\n  'partialRight': true,\n  'propertyOf': true,\n  'random': true,\n  'range': true,\n  'rangeRight': true,\n  'subtract': true,\n  'zip': true,\n  'zipObject': true,\n  'zipObjectDeep': true\n};\n","/**\n * The default argument placeholder value for methods.\n *\n * @type {Object}\n */\nmodule.exports = {};\n","var mapping = require('./_mapping'),\n    fallbackHolder = require('./placeholder');\n\n/** Built-in value reference. */\nvar push = Array.prototype.push;\n\n/**\n * Creates a function, with an arity of `n`, that invokes `func` with the\n * arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} n The arity of the new function.\n * @returns {Function} Returns the new function.\n */\nfunction baseArity(func, n) {\n  return n == 2\n    ? function(a, b) { return func.apply(undefined, arguments); }\n    : function(a) { return func.apply(undefined, arguments); };\n}\n\n/**\n * Creates a function that invokes `func`, with up to `n` arguments, ignoring\n * any additional arguments.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @param {number} n The arity cap.\n * @returns {Function} Returns the new function.\n */\nfunction baseAry(func, n) {\n  return n == 2\n    ? function(a, b) { return func(a, b); }\n    : function(a) { return func(a); };\n}\n\n/**\n * Creates a clone of `array`.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the cloned array.\n */\nfunction cloneArray(array) {\n  var length = array ? array.length : 0,\n      result = Array(length);\n\n  while (length--) {\n    result[length] = array[length];\n  }\n  return result;\n}\n\n/**\n * Creates a function that clones a given object using the assignment `func`.\n *\n * @private\n * @param {Function} func The assignment function.\n * @returns {Function} Returns the new cloner function.\n */\nfunction createCloner(func) {\n  return function(object) {\n    return func({}, object);\n  };\n}\n\n/**\n * A specialized version of `_.spread` which flattens the spread array into\n * the arguments of the invoked `func`.\n *\n * @private\n * @param {Function} func The function to spread arguments over.\n * @param {number} start The start position of the spread.\n * @returns {Function} Returns the new function.\n */\nfunction flatSpread(func, start) {\n  return function() {\n    var length = arguments.length,\n        lastIndex = length - 1,\n        args = Array(length);\n\n    while (length--) {\n      args[length] = arguments[length];\n    }\n    var array = args[start],\n        otherArgs = args.slice(0, start);\n\n    if (array) {\n      push.apply(otherArgs, array);\n    }\n    if (start != lastIndex) {\n      push.apply(otherArgs, args.slice(start + 1));\n    }\n    return func.apply(this, otherArgs);\n  };\n}\n\n/**\n * Creates a function that wraps `func` and uses `cloner` to clone the first\n * argument it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} cloner The function to clone arguments.\n * @returns {Function} Returns the new immutable function.\n */\nfunction wrapImmutable(func, cloner) {\n  return function() {\n    var length = arguments.length;\n    if (!length) {\n      return;\n    }\n    var args = Array(length);\n    while (length--) {\n      args[length] = arguments[length];\n    }\n    var result = args[0] = cloner.apply(undefined, args);\n    func.apply(undefined, args);\n    return result;\n  };\n}\n\n/**\n * The base implementation of `convert` which accepts a `util` object of methods\n * required to perform conversions.\n *\n * @param {Object} util The util object.\n * @param {string} name The name of the function to convert.\n * @param {Function} func The function to convert.\n * @param {Object} [options] The options object.\n * @param {boolean} [options.cap=true] Specify capping iteratee arguments.\n * @param {boolean} [options.curry=true] Specify currying.\n * @param {boolean} [options.fixed=true] Specify fixed arity.\n * @param {boolean} [options.immutable=true] Specify immutable operations.\n * @param {boolean} [options.rearg=true] Specify rearranging arguments.\n * @returns {Function|Object} Returns the converted function or object.\n */\nfunction baseConvert(util, name, func, options) {\n  var isLib = typeof name == 'function',\n      isObj = name === Object(name);\n\n  if (isObj) {\n    options = func;\n    func = name;\n    name = undefined;\n  }\n  if (func == null) {\n    throw new TypeError;\n  }\n  options || (options = {});\n\n  var config = {\n    'cap': 'cap' in options ? options.cap : true,\n    'curry': 'curry' in options ? options.curry : true,\n    'fixed': 'fixed' in options ? options.fixed : true,\n    'immutable': 'immutable' in options ? options.immutable : true,\n    'rearg': 'rearg' in options ? options.rearg : true\n  };\n\n  var defaultHolder = isLib ? func : fallbackHolder,\n      forceCurry = ('curry' in options) && options.curry,\n      forceFixed = ('fixed' in options) && options.fixed,\n      forceRearg = ('rearg' in options) && options.rearg,\n      pristine = isLib ? func.runInContext() : undefined;\n\n  var helpers = isLib ? func : {\n    'ary': util.ary,\n    'assign': util.assign,\n    'clone': util.clone,\n    'curry': util.curry,\n    'forEach': util.forEach,\n    'isArray': util.isArray,\n    'isError': util.isError,\n    'isFunction': util.isFunction,\n    'isWeakMap': util.isWeakMap,\n    'iteratee': util.iteratee,\n    'keys': util.keys,\n    'rearg': util.rearg,\n    'toInteger': util.toInteger,\n    'toPath': util.toPath\n  };\n\n  var ary = helpers.ary,\n      assign = helpers.assign,\n      clone = helpers.clone,\n      curry = helpers.curry,\n      each = helpers.forEach,\n      isArray = helpers.isArray,\n      isError = helpers.isError,\n      isFunction = helpers.isFunction,\n      isWeakMap = helpers.isWeakMap,\n      keys = helpers.keys,\n      rearg = helpers.rearg,\n      toInteger = helpers.toInteger,\n      toPath = helpers.toPath;\n\n  var aryMethodKeys = keys(mapping.aryMethod);\n\n  var wrappers = {\n    'castArray': function(castArray) {\n      return function() {\n        var value = arguments[0];\n        return isArray(value)\n          ? castArray(cloneArray(value))\n          : castArray.apply(undefined, arguments);\n      };\n    },\n    'iteratee': function(iteratee) {\n      return function() {\n        var func = arguments[0],\n            arity = arguments[1],\n            result = iteratee(func, arity),\n            length = result.length;\n\n        if (config.cap && typeof arity == 'number') {\n          arity = arity > 2 ? (arity - 2) : 1;\n          return (length && length <= arity) ? result : baseAry(result, arity);\n        }\n        return result;\n      };\n    },\n    'mixin': function(mixin) {\n      return function(source) {\n        var func = this;\n        if (!isFunction(func)) {\n          return mixin(func, Object(source));\n        }\n        var pairs = [];\n        each(keys(source), function(key) {\n          if (isFunction(source[key])) {\n            pairs.push([key, func.prototype[key]]);\n          }\n        });\n\n        mixin(func, Object(source));\n\n        each(pairs, function(pair) {\n          var value = pair[1];\n          if (isFunction(value)) {\n            func.prototype[pair[0]] = value;\n          } else {\n            delete func.prototype[pair[0]];\n          }\n        });\n        return func;\n      };\n    },\n    'nthArg': function(nthArg) {\n      return function(n) {\n        var arity = n < 0 ? 1 : (toInteger(n) + 1);\n        return curry(nthArg(n), arity);\n      };\n    },\n    'rearg': function(rearg) {\n      return function(func, indexes) {\n        var arity = indexes ? indexes.length : 0;\n        return curry(rearg(func, indexes), arity);\n      };\n    },\n    'runInContext': function(runInContext) {\n      return function(context) {\n        return baseConvert(util, runInContext(context), options);\n      };\n    }\n  };\n\n  /*--------------------------------------------------------------------------*/\n\n  /**\n   * Casts `func` to a function with an arity capped iteratee if needed.\n   *\n   * @private\n   * @param {string} name The name of the function to inspect.\n   * @param {Function} func The function to inspect.\n   * @returns {Function} Returns the cast function.\n   */\n  function castCap(name, func) {\n    if (config.cap) {\n      var indexes = mapping.iterateeRearg[name];\n      if (indexes) {\n        return iterateeRearg(func, indexes);\n      }\n      var n = !isLib && mapping.iterateeAry[name];\n      if (n) {\n        return iterateeAry(func, n);\n      }\n    }\n    return func;\n  }\n\n  /**\n   * Casts `func` to a curried function if needed.\n   *\n   * @private\n   * @param {string} name The name of the function to inspect.\n   * @param {Function} func The function to inspect.\n   * @param {number} n The arity of `func`.\n   * @returns {Function} Returns the cast function.\n   */\n  function castCurry(name, func, n) {\n    return (forceCurry || (config.curry && n > 1))\n      ? curry(func, n)\n      : func;\n  }\n\n  /**\n   * Casts `func` to a fixed arity function if needed.\n   *\n   * @private\n   * @param {string} name The name of the function to inspect.\n   * @param {Function} func The function to inspect.\n   * @param {number} n The arity cap.\n   * @returns {Function} Returns the cast function.\n   */\n  function castFixed(name, func, n) {\n    if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {\n      var data = mapping.methodSpread[name],\n          start = data && data.start;\n\n      return start  === undefined ? ary(func, n) : flatSpread(func, start);\n    }\n    return func;\n  }\n\n  /**\n   * Casts `func` to an rearged function if needed.\n   *\n   * @private\n   * @param {string} name The name of the function to inspect.\n   * @param {Function} func The function to inspect.\n   * @param {number} n The arity of `func`.\n   * @returns {Function} Returns the cast function.\n   */\n  function castRearg(name, func, n) {\n    return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))\n      ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])\n      : func;\n  }\n\n  /**\n   * Creates a clone of `object` by `path`.\n   *\n   * @private\n   * @param {Object} object The object to clone.\n   * @param {Array|string} path The path to clone by.\n   * @returns {Object} Returns the cloned object.\n   */\n  function cloneByPath(object, path) {\n    path = toPath(path);\n\n    var index = -1,\n        length = path.length,\n        lastIndex = length - 1,\n        result = clone(Object(object)),\n        nested = result;\n\n    while (nested != null && ++index < length) {\n      var key = path[index],\n          value = nested[key];\n\n      if (value != null &&\n          !(isFunction(value) || isError(value) || isWeakMap(value))) {\n        nested[key] = clone(index == lastIndex ? value : Object(value));\n      }\n      nested = nested[key];\n    }\n    return result;\n  }\n\n  /**\n   * Converts `lodash` to an immutable auto-curried iteratee-first data-last\n   * version with conversion `options` applied.\n   *\n   * @param {Object} [options] The options object. See `baseConvert` for more details.\n   * @returns {Function} Returns the converted `lodash`.\n   */\n  function convertLib(options) {\n    return _.runInContext.convert(options)(undefined);\n  }\n\n  /**\n   * Create a converter function for `func` of `name`.\n   *\n   * @param {string} name The name of the function to convert.\n   * @param {Function} func The function to convert.\n   * @returns {Function} Returns the new converter function.\n   */\n  function createConverter(name, func) {\n    var realName = mapping.aliasToReal[name] || name,\n        methodName = mapping.remap[realName] || realName,\n        oldOptions = options;\n\n    return function(options) {\n      var newUtil = isLib ? pristine : helpers,\n          newFunc = isLib ? pristine[methodName] : func,\n          newOptions = assign(assign({}, oldOptions), options);\n\n      return baseConvert(newUtil, realName, newFunc, newOptions);\n    };\n  }\n\n  /**\n   * Creates a function that wraps `func` to invoke its iteratee, with up to `n`\n   * arguments, ignoring any additional arguments.\n   *\n   * @private\n   * @param {Function} func The function to cap iteratee arguments for.\n   * @param {number} n The arity cap.\n   * @returns {Function} Returns the new function.\n   */\n  function iterateeAry(func, n) {\n    return overArg(func, function(func) {\n      return typeof func == 'function' ? baseAry(func, n) : func;\n    });\n  }\n\n  /**\n   * Creates a function that wraps `func` to invoke its iteratee with arguments\n   * arranged according to the specified `indexes` where the argument value at\n   * the first index is provided as the first argument, the argument value at\n   * the second index is provided as the second argument, and so on.\n   *\n   * @private\n   * @param {Function} func The function to rearrange iteratee arguments for.\n   * @param {number[]} indexes The arranged argument indexes.\n   * @returns {Function} Returns the new function.\n   */\n  function iterateeRearg(func, indexes) {\n    return overArg(func, function(func) {\n      var n = indexes.length;\n      return baseArity(rearg(baseAry(func, n), indexes), n);\n    });\n  }\n\n  /**\n   * Creates a function that invokes `func` with its first argument transformed.\n   *\n   * @private\n   * @param {Function} func The function to wrap.\n   * @param {Function} transform The argument transform.\n   * @returns {Function} Returns the new function.\n   */\n  function overArg(func, transform) {\n    return function() {\n      var length = arguments.length;\n      if (!length) {\n        return func();\n      }\n      var args = Array(length);\n      while (length--) {\n        args[length] = arguments[length];\n      }\n      var index = config.rearg ? 0 : (length - 1);\n      args[index] = transform(args[index]);\n      return func.apply(undefined, args);\n    };\n  }\n\n  /**\n   * Creates a function that wraps `func` and applys the conversions\n   * rules by `name`.\n   *\n   * @private\n   * @param {string} name The name of the function to wrap.\n   * @param {Function} func The function to wrap.\n   * @returns {Function} Returns the converted function.\n   */\n  function wrap(name, func, placeholder) {\n    var result,\n        realName = mapping.aliasToReal[name] || name,\n        wrapped = func,\n        wrapper = wrappers[realName];\n\n    if (wrapper) {\n      wrapped = wrapper(func);\n    }\n    else if (config.immutable) {\n      if (mapping.mutate.array[realName]) {\n        wrapped = wrapImmutable(func, cloneArray);\n      }\n      else if (mapping.mutate.object[realName]) {\n        wrapped = wrapImmutable(func, createCloner(func));\n      }\n      else if (mapping.mutate.set[realName]) {\n        wrapped = wrapImmutable(func, cloneByPath);\n      }\n    }\n    each(aryMethodKeys, function(aryKey) {\n      each(mapping.aryMethod[aryKey], function(otherName) {\n        if (realName == otherName) {\n          var data = mapping.methodSpread[realName],\n              afterRearg = data && data.afterRearg;\n\n          result = afterRearg\n            ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)\n            : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);\n\n          result = castCap(realName, result);\n          result = castCurry(realName, result, aryKey);\n          return false;\n        }\n      });\n      return !result;\n    });\n\n    result || (result = wrapped);\n    if (result == func) {\n      result = forceCurry ? curry(result, 1) : function() {\n        return func.apply(this, arguments);\n      };\n    }\n    result.convert = createConverter(realName, func);\n    result.placeholder = func.placeholder = placeholder;\n\n    return result;\n  }\n\n  /*--------------------------------------------------------------------------*/\n\n  if (!isObj) {\n    return wrap(name, func, defaultHolder);\n  }\n  var _ = func;\n\n  // Convert methods by ary cap.\n  var pairs = [];\n  each(aryMethodKeys, function(aryKey) {\n    each(mapping.aryMethod[aryKey], function(key) {\n      var func = _[mapping.remap[key] || key];\n      if (func) {\n        pairs.push([key, wrap(key, func, _)]);\n      }\n    });\n  });\n\n  // Convert remaining methods.\n  each(keys(_), function(key) {\n    var func = _[key];\n    if (typeof func == 'function') {\n      var length = pairs.length;\n      while (length--) {\n        if (pairs[length][0] == key) {\n          return;\n        }\n      }\n      func.convert = createConverter(key, func);\n      pairs.push([key, func]);\n    }\n  });\n\n  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.\n  each(pairs, function(pair) {\n    _[pair[0]] = pair[1];\n  });\n\n  _.convert = convertLib;\n  _.placeholder = _;\n\n  // Assign aliases.\n  each(keys(_), function(key) {\n    each(mapping.realToAlias[key] || [], function(alias) {\n      _[alias] = _[key];\n    });\n  });\n\n  return _;\n}\n\nmodule.exports = baseConvert;\n","var createWrap = require('./_createWrap');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_ARY_FLAG = 128;\n\n/**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\nfunction ary(func, n, guard) {\n  n = guard ? undefined : n;\n  n = (func && n == null) ? func.length : n;\n  return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n}\n\nmodule.exports = ary;\n","var baseGetTag = require('./_baseGetTag'),\n    isObjectLike = require('./isObjectLike'),\n    isPlainObject = require('./isPlainObject');\n\n/** `Object#toString` result references. */\nvar domExcTag = '[object DOMException]',\n    errorTag = '[object Error]';\n\n/**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\nfunction isError(value) {\n  if (!isObjectLike(value)) {\n    return false;\n  }\n  var tag = baseGetTag(value);\n  return tag == errorTag || tag == domExcTag ||\n    (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n}\n\nmodule.exports = isError;\n","var getTag = require('./_getTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar weakMapTag = '[object WeakMap]';\n\n/**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\nfunction isWeakMap(value) {\n  return isObjectLike(value) && getTag(value) == weakMapTag;\n}\n\nmodule.exports = isWeakMap;\n","var baseClone = require('./_baseClone'),\n    baseIteratee = require('./_baseIteratee');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1;\n\n/**\n * Creates a function that invokes `func` with the arguments of the created\n * function. If `func` is a property name, the created function returns the\n * property value for a given element. If `func` is an array or object, the\n * created function returns `true` for elements that contain the equivalent\n * source properties, otherwise it returns `false`.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Util\n * @param {*} [func=_.identity] The value to convert to a callback.\n * @returns {Function} Returns the callback.\n * @example\n *\n * var users = [\n *   { 'user': 'barney', 'age': 36, 'active': true },\n *   { 'user': 'fred',   'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));\n * // => [{ 'user': 'barney', 'age': 36, 'active': true }]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, _.iteratee(['user', 'fred']));\n * // => [{ 'user': 'fred', 'age': 40 }]\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, _.iteratee('user'));\n * // => ['barney', 'fred']\n *\n * // Create custom iteratee shorthands.\n * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {\n *   return !_.isRegExp(func) ? iteratee(func) : function(string) {\n *     return func.test(string);\n *   };\n * });\n *\n * _.filter(['abc', 'def'], /ef/);\n * // => ['def']\n */\nfunction iteratee(func) {\n  return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));\n}\n\nmodule.exports = iteratee;\n","var flatten = require('./flatten'),\n    overRest = require('./_overRest'),\n    setToString = require('./_setToString');\n\n/**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\nfunction flatRest(func) {\n  return setToString(overRest(func, undefined, flatten), func + '');\n}\n\nmodule.exports = flatRest;\n","var createWrap = require('./_createWrap'),\n    flatRest = require('./_flatRest');\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_REARG_FLAG = 256;\n\n/**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n *   return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\nvar rearg = flatRest(function(func, indexes) {\n  return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n});\n\nmodule.exports = rearg;\n","var arrayMap = require('./_arrayMap'),\n    copyArray = require('./_copyArray'),\n    isArray = require('./isArray'),\n    isSymbol = require('./isSymbol'),\n    stringToPath = require('./_stringToPath'),\n    toKey = require('./_toKey'),\n    toString = require('./toString');\n\n/**\n * Converts `value` to a property path array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Util\n * @param {*} value The value to convert.\n * @returns {Array} Returns the new property path array.\n * @example\n *\n * _.toPath('a.b.c');\n * // => ['a', 'b', 'c']\n *\n * _.toPath('a[0].b.c');\n * // => ['a', '0', 'b', 'c']\n */\nfunction toPath(value) {\n  if (isArray(value)) {\n    return arrayMap(value, toKey);\n  }\n  return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n}\n\nmodule.exports = toPath;\n","module.exports = {\n  'ary': require('../ary'),\n  'assign': require('../_baseAssign'),\n  'clone': require('../clone'),\n  'curry': require('../curry'),\n  'forEach': require('../_arrayEach'),\n  'isArray': require('../isArray'),\n  'isError': require('../isError'),\n  'isFunction': require('../isFunction'),\n  'isWeakMap': require('../isWeakMap'),\n  'iteratee': require('../iteratee'),\n  'keys': require('../_baseKeys'),\n  'rearg': require('../rearg'),\n  'toInteger': require('../toInteger'),\n  'toPath': require('../toPath')\n};\n","var baseConvert = require('./_baseConvert'),\n    util = require('./_util');\n\n/**\n * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last\n * version with conversion `options` applied. If `name` is an object its methods\n * will be converted.\n *\n * @param {string} name The name of the function to wrap.\n * @param {Function} [func] The function to wrap.\n * @param {Object} [options] The options object. See `baseConvert` for more details.\n * @returns {Function|Object} Returns the converted function or object.\n */\nfunction convert(name, func, options) {\n  return baseConvert(util, name, func, options);\n}\n\nmodule.exports = convert;\n","module.exports = {\n  'cap': false,\n  'curry': false,\n  'fixed': false,\n  'immutable': false,\n  'rearg': false\n};\n","var convert = require('./convert'),\n    func = convert('capitalize', require('../capitalize'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('chunk', require('../chunk'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('cloneDeep', require('../cloneDeep'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('compact', require('../compact'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('concat', require('../concat'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('filter', require('../filter'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('find', require('../find'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('get', require('../get'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('groupBy', require('../groupBy'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('intersectionWith', require('../intersectionWith'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('isEqual', require('../isEqual'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('isFunction', require('../isFunction'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('keys', require('../keys'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('last', require('../last'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('map', require('../map'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('mapValues', require('../mapValues'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var baseGet = require('./_baseGet'),\n    baseSlice = require('./_baseSlice');\n\n/**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\nfunction parent(object, path) {\n  return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n}\n\nmodule.exports = parent;\n","var castPath = require('./_castPath'),\n    last = require('./last'),\n    parent = require('./_parent'),\n    toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\nfunction baseUnset(object, path) {\n  path = castPath(path, object);\n  object = parent(object, path);\n  return object == null || delete object[toKey(last(path))];\n}\n\nmodule.exports = baseUnset;\n","var isPlainObject = require('./isPlainObject');\n\n/**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\nfunction customOmitClone(value) {\n  return isPlainObject(value) ? undefined : value;\n}\n\nmodule.exports = customOmitClone;\n","var arrayMap = require('./_arrayMap'),\n    baseClone = require('./_baseClone'),\n    baseUnset = require('./_baseUnset'),\n    castPath = require('./_castPath'),\n    copyObject = require('./_copyObject'),\n    customOmitClone = require('./_customOmitClone'),\n    flatRest = require('./_flatRest'),\n    getAllKeysIn = require('./_getAllKeysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n    CLONE_FLAT_FLAG = 2,\n    CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\nvar omit = flatRest(function(object, paths) {\n  var result = {};\n  if (object == null) {\n    return result;\n  }\n  var isDeep = false;\n  paths = arrayMap(paths, function(path) {\n    path = castPath(path, object);\n    isDeep || (isDeep = path.length > 1);\n    return path;\n  });\n  copyObject(object, getAllKeysIn(object), result);\n  if (isDeep) {\n    result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n  }\n  var length = paths.length;\n  while (length--) {\n    baseUnset(result, paths[length]);\n  }\n  return result;\n});\n\nmodule.exports = omit;\n","var convert = require('./convert'),\n    func = convert('omit', require('../omit'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('orderBy', require('../orderBy'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('partition', require('../partition'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var basePickBy = require('./_basePickBy'),\n    hasIn = require('./hasIn');\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, paths) {\n  return basePickBy(object, paths, function(value, path) {\n    return hasIn(object, path);\n  });\n}\n\nmodule.exports = basePick;\n","var basePick = require('./_basePick'),\n    flatRest = require('./_flatRest');\n\n/**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\nvar pick = flatRest(function(object, paths) {\n  return object == null ? {} : basePick(object, paths);\n});\n\nmodule.exports = pick;\n","var convert = require('./convert'),\n    func = convert('pick', require('../pick'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var LodashWrapper = require('./_LodashWrapper'),\n    flatRest = require('./_flatRest'),\n    getData = require('./_getData'),\n    getFuncName = require('./_getFuncName'),\n    isArray = require('./isArray'),\n    isLaziable = require('./_isLaziable');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used to compose bitmasks for function metadata. */\nvar WRAP_CURRY_FLAG = 8,\n    WRAP_PARTIAL_FLAG = 32,\n    WRAP_ARY_FLAG = 128,\n    WRAP_REARG_FLAG = 256;\n\n/**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\nfunction createFlow(fromRight) {\n  return flatRest(function(funcs) {\n    var length = funcs.length,\n        index = length,\n        prereq = LodashWrapper.prototype.thru;\n\n    if (fromRight) {\n      funcs.reverse();\n    }\n    while (index--) {\n      var func = funcs[index];\n      if (typeof func != 'function') {\n        throw new TypeError(FUNC_ERROR_TEXT);\n      }\n      if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n        var wrapper = new LodashWrapper([], true);\n      }\n    }\n    index = wrapper ? index : length;\n    while (++index < length) {\n      func = funcs[index];\n\n      var funcName = getFuncName(func),\n          data = funcName == 'wrapper' ? getData(func) : undefined;\n\n      if (data && isLaziable(data[0]) &&\n            data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n            !data[4].length && data[9] == 1\n          ) {\n        wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n      } else {\n        wrapper = (func.length == 1 && isLaziable(func))\n          ? wrapper[funcName]()\n          : wrapper.thru(func);\n      }\n    }\n    return function() {\n      var args = arguments,\n          value = args[0];\n\n      if (wrapper && args.length == 1 && isArray(value)) {\n        return wrapper.plant(value).value();\n      }\n      var index = 0,\n          result = length ? funcs[index].apply(this, args) : value;\n\n      while (++index < length) {\n        result = funcs[index].call(this, result);\n      }\n      return result;\n    };\n  });\n}\n\nmodule.exports = createFlow;\n","var createFlow = require('./_createFlow');\n\n/**\n * Creates a function that returns the result of invoking the given functions\n * with the `this` binding of the created function, where each successive\n * invocation is supplied the return value of the previous.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Util\n * @param {...(Function|Function[])} [funcs] The functions to invoke.\n * @returns {Function} Returns the new composite function.\n * @see _.flowRight\n * @example\n *\n * function square(n) {\n *   return n * n;\n * }\n *\n * var addSquare = _.flow([_.add, square]);\n * addSquare(1, 2);\n * // => 9\n */\nvar flow = createFlow();\n\nmodule.exports = flow;\n","var convert = require('./convert'),\n    func = convert('flow', require('../flow'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","module.exports = require('./flow');\n","var baseClone = require('./_baseClone'),\n    baseMatchesProperty = require('./_baseMatchesProperty');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1;\n\n/**\n * Creates a function that performs a partial deep comparison between the\n * value at `path` of a given object to `srcValue`, returning `true` if the\n * object value is equivalent, else `false`.\n *\n * **Note:** Partial comparisons will match empty array and empty object\n * `srcValue` values against any array or object value, respectively. See\n * `_.isEqual` for a list of supported value comparisons.\n *\n * **Note:** Multiple values can be checked by combining several matchers\n * using `_.overSome`\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n * @example\n *\n * var objects = [\n *   { 'a': 1, 'b': 2, 'c': 3 },\n *   { 'a': 4, 'b': 5, 'c': 6 }\n * ];\n *\n * _.find(objects, _.matchesProperty('a', 4));\n * // => { 'a': 4, 'b': 5, 'c': 6 }\n *\n * // Checking for several possible values\n * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));\n * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]\n */\nfunction matchesProperty(path, srcValue) {\n  return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));\n}\n\nmodule.exports = matchesProperty;\n","var convert = require('./convert'),\n    func = convert('matchesProperty', require('../matchesProperty'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","module.exports = require('./matchesProperty');\n","var baseSet = require('./_baseSet');\n\n/**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\nfunction set(object, path, value) {\n  return object == null ? object : baseSet(object, path, value);\n}\n\nmodule.exports = set;\n","var convert = require('./convert'),\n    func = convert('set', require('../set'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('sortBy', require('../sortBy'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var baseGetTag = require('./_baseGetTag'),\n    isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar regexpTag = '[object RegExp]';\n\n/**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\nfunction baseIsRegExp(value) {\n  return isObjectLike(value) && baseGetTag(value) == regexpTag;\n}\n\nmodule.exports = baseIsRegExp;\n","var baseIsRegExp = require('./_baseIsRegExp'),\n    baseUnary = require('./_baseUnary'),\n    nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;\n\n/**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\nvar isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\nmodule.exports = isRegExp;\n","var baseToString = require('./_baseToString'),\n    castSlice = require('./_castSlice'),\n    hasUnicode = require('./_hasUnicode'),\n    isIterateeCall = require('./_isIterateeCall'),\n    isRegExp = require('./isRegExp'),\n    stringToArray = require('./_stringToArray'),\n    toString = require('./toString');\n\n/** Used as references for the maximum length and index of an array. */\nvar MAX_ARRAY_LENGTH = 4294967295;\n\n/**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\nfunction split(string, separator, limit) {\n  if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n    separator = limit = undefined;\n  }\n  limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n  if (!limit) {\n    return [];\n  }\n  string = toString(string);\n  if (string && (\n        typeof separator == 'string' ||\n        (separator != null && !isRegExp(separator))\n      )) {\n    separator = baseToString(separator);\n    if (!separator && hasUnicode(string)) {\n      return castSlice(stringToArray(string), 0, limit);\n    }\n  }\n  return string.split(separator, limit);\n}\n\nmodule.exports = split;\n","var convert = require('./convert'),\n    func = convert('split', require('../split'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var toString = require('./toString');\n\n/**\n * Converts `string`, as a whole, to lower case just like\n * [String#toLowerCase](https://mdn.io/toLowerCase).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.toLower('--Foo-Bar--');\n * // => '--foo-bar--'\n *\n * _.toLower('fooBar');\n * // => 'foobar'\n *\n * _.toLower('__FOO_BAR__');\n * // => '__foo_bar__'\n */\nfunction toLower(value) {\n  return toString(value).toLowerCase();\n}\n\nmodule.exports = toLower;\n","var convert = require('./convert'),\n    func = convert('toLower', require('../toLower'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('uniq', require('../uniq'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('uniqWith', require('../uniqWith'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","var convert = require('./convert'),\n    func = convert('values', require('../values'), require('./_falseOptions'));\n\nfunc.placeholder = require('./placeholder');\nmodule.exports = func;\n","import { formatISO, isValid, parse, parseISO } from \"date-fns\";\nimport { format, toZonedTime } from \"date-fns-tz\"\nimport { filter } from \"@/utils/nodash/fp\";\n\n// Formats a date from YYYY-MM-DD to M/D/YYYY (ie. no leading 0s).\nexport function formatDateISOToLocal(dateStr?: string, treatMidnightUTCAsDate = false): string | undefined {\n  if (!dateStr) return undefined;\n\n  // TODO: once https://zeushealth.atlassian.net/browse/DAU-288 is done we can likely remove this \n  // logic to treat midnight UTC as a date only\n  const utcDate = toZonedTime(dateStr, \"UTC\");\n  if (treatMidnightUTCAsDate && utcDate.getHours() === 0 && utcDate.getMinutes() === 0 && utcDate.getSeconds() === 0) {    \n    return format(utcDate, \"M/d/yyyy\", { timeZone: \"UTC\" });\n  }\n  return format(parseISO(dateStr), \"M/d/yyyy\");\n}\n\nexport const matchDatePattern = (dateStr: string): Date | string => {\n  const patterns = [\"P\", \"yyyyMMddHHmm\"];\n\n  // Going to try to parse all the patterns and if pattern is not recognized then will return date as is\n  for (let i = 0; i < patterns.length; i += 1) {\n    const parsedDate = parse(dateStr, patterns[i], new Date());\n    if (isValid(parsedDate)) {\n      return parsedDate;\n    }\n  }\n\n  return dateStr;\n};\n\n// Formats a date from MM/DD/YYYY to YYYY-MM-DD.\nexport function formatDateLocalToISO(dateStr?: string): string | undefined {\n  if (!dateStr) return undefined;\n\n  const date = matchDatePattern(dateStr);\n  if (date instanceof Date) {\n    return formatISO(date, { representation: \"date\" });\n  }\n\n  return date;\n}\n\n// Formats a string yyyymmdd or yyyyMMddHHmmss into MM/DD/YYYY.\nexport function formatStringToDate(dateStr?: string): string | undefined {\n  if (!dateStr) return undefined;\n\n  const month = dateStr.substring(4, 6);\n  const day = dateStr.substring(6, 8);\n  const year = dateStr.substring(0, 4);\n\n  return `${month}/${day}/${year}`;\n}\n\n// Returns the ISO string (YYYY-MM-DD) for a given date.\n// We avoid using date-fn's format method to avoid timezone issues.\nexport function dateToISO(date?: Date) {\n  if (date) {\n    return date.toISOString().split(\"T\")[0];\n  }\n\n  return undefined;\n}\n\n// Takes a phone number of any format and returns it in 555-555-5555 format.\nexport function formatPhoneNumber(phoneNumber?: string): string | undefined {\n  if (!phoneNumber) return undefined;\n\n  // Remove all non digits.\n  const cleaned = phoneNumber.replace(/\\D/g, \"\");\n\n  // Match our group of digits.\n  const match = cleaned.match(/^(\\d{3})(\\d{3})(\\d{4})$/);\n\n  // Return the new format OR the original if we don't have a match.\n  // This would happen if we didn't have the expected 10 digits.\n  return match ? `${match[1]}-${match[2]}-${match[3]}` : phoneNumber;\n}\n\n// Tries to format a date string from either YYYYMMDD or YYYYMMDDkkmmss\n// to MM/DD/YYYY kk:mm:ss.\nexport function maybeFormatDateStringToLocal(dateStr?: string): string | undefined {\n  if (dateStr && /^\\d+$/.test(dateStr) && dateStr.length >= 8) {\n    let result = \"\";\n    try {\n      result = format(parse(dateStr.substring(0, 8), \"yyyyMMdd\", new Date()), \"P\");\n      // eslint-disable-next-line no-empty\n    } catch {}\n\n    // Check if there's a time component and add it.\n    // Result will be MM/DD/YYY kk:mm:ss.\n    if (dateStr.length === 14) {\n      try {\n        result += ` ${format(parse(dateStr.substring(9, 15), \"kkmmss\", new Date()), \"kk:mm:ss\")}`;\n        // eslint-disable-next-line no-empty\n      } catch {}\n    }\n    return result;\n  }\n\n  return dateStr;\n}\n\n// Formats an age as value followed by unit, or whichever one is available.\nexport function formatAge(age: fhir4.Age): string {\n  const { value, unit } = age;\n  return compactToTruthyAndZero([value, unit]).join(\" \");\n}\n\nfunction ensureJsTimestamp(n: number) {\n  return `${n}`.length <= 11 ? n * 1000 : n;\n}\n\n// Formats a string ISO date to MM/DD/YYY.\nexport function formatISODateStringToDate(dateStr?: string | number): string | undefined {\n  if (!dateStr) return undefined;\n  const date =\n    typeof dateStr === \"number\" ? new Date(ensureJsTimestamp(dateStr)).toISOString() : dateStr;\n\n  const day = date.substring(8, 10);\n  const month = date.substring(5, 7);\n  const year = date.substring(0, 4);\n\n  return `${month}/${day}/${year}`;\n}\n\nexport function formatDate(dateStr: string | undefined, pattern: string): string | undefined {\n  if (!dateStr) return undefined;\n\n  return format(new Date(dateStr), pattern);\n}\n\nexport function formatPeriod(period: fhir4.Period) {\n  const { start, end } = period;\n  if (!start && !end) return \"\";\n\n  if (!start || !end) {\n    return formatDateISOToLocal(start ?? end) ?? \"\";\n  }\n\n  return `${formatDateISOToLocal(start)} - ${formatDateISOToLocal(end)}`;\n}\n\n// Returns the low and high value and units of a range or unknown if not available.\n// Examples:\n// \"\" # blank when both low.value and high.value don't exist\n// \"2.4 mmol/L\" # Shows single value when low or high is missing\n// \"1.2 l/L - 2.4 mmol/L\" # Shows both units if they both exist and are different\n// \"1.2 - 2.4 mmol/L\" # Shows single unit at end when one unit isn't provided\n// \"1.2 - 2.4\" # Drops units when both low.unit and high.unit are not provided\nexport function formatRange(range: fhir4.Range) {\n  const { low, high } = range;\n\n  // No values, show blank.\n  if (low?.value === undefined && high?.value === undefined) return \"\";\n\n  const unit = low?.unit ?? high?.unit;\n  const unitStr = unit ? ` ${unit}` : \"\";\n\n  // Only one value, show that value and the unit if it exists.\n  if (low?.value === undefined || high?.value === undefined) {\n    const value = low?.value ?? high?.value ?? \"\";\n    return `${value}${unitStr}`;\n  }\n\n  // Both values exist, show both values and both units if units exist and are different.\n  if (low.unit !== undefined && high.unit !== undefined && low.unit !== high.unit) {\n    return `${low.value} ${low.unit} - ${high.value} ${high.unit}`;\n  }\n\n  return `${low.value} - ${high.value}${unitStr}`;\n}\n\nexport function formatQuantity(quantity: fhir4.Quantity) {\n  const { value, unit } = quantity;\n  return compactToTruthyAndZero([value, unit]).join(\" \");\n}\n\nexport const compactToTruthyAndZero = <T>(arr: T[] | null | undefined) =>\n  filter(onlyTruthyAndZero, arr);\n\nexport function onlyTruthyAndZero(val: unknown | undefined) {\n  return val || val === 0;\n}\n","// HL7 / FHIR\n\nexport const SYSTEM_ACT_CODE = \"urn:oid:2.16.840.1.113883.5.4\";\nexport const SYSTEM_BASIC_RESOURCE_TYPE = `http://terminology.hl7.org/CodeSystem/basic-resource-type`;\nexport const SYSTEM_CONDITION_CATEGORY = `http://terminology.hl7.org/CodeSystem/condition-category`;\nexport const SYSTEM_CONDITION_CLINICAL = \"http://terminology.hl7.org/CodeSystem/condition-clinical\";\nexport const SYSTEM_CONDITION_VERIFICATION_STATUS =\n  \"http://terminology.hl7.org/CodeSystem/condition-ver-status\";\nexport const SYSTEM_DIAGNOSTIC_SERVICE_SECTION_ID = \"http://terminology.hl7.org/CodeSystem/v2-0074\";\nexport const SYSTEM_MARITAL_STATUS = \"http://terminology.hl7.org/CodeSystem/v3-MaritalStatus\";\nexport const SYSTEM_NULL_FLAVOR = \"http://terminology.hl7.org/CodeSystem/v3-NullFlavor\";\nexport const SYSTEM_PROVENANCE_ACTIVITY_TYPE =\n  \"http://terminology.hl7.org/3.1.0/CodeSystem-v3-DataOperation.html\";\nexport const SYSTEM_PROVENANCE_AGENT_TYPE =\n  \"http://terminology.hl7.org/CodeSystem/provenance-participant-type\";\nexport const SYSTEM_RELATIONSHIP = \"http://terminology.hl7.org/CodeSystem/v2-0131\";\nexport const SYSTEM_TASK_STATUS = \"https://www.hl7.org/fhir/codesystem-task-status.html\";\n\n// CODE SYSTEMS\n\nexport const SYSTEM_CCS = \"https://www.hcup-us.ahrq.gov/toolssoftware/ccsr/dxccsr.jsp\";\nexport const SYSTEM_CCI =\n  \"http://www.hcup-us.ahrq.gov/toolssoftware/chronic_icd10/chronic_icd10.jsp\";\n\nexport const SYSTEM_CPT = \"http://www.ama-assn.org/go/cpt\";\n\nexport const SYSTEM_CVX = \"http://hl7.org/fhir/sid/cvx\";\n\nexport const SYSTEM_CMS_HCC = \"http://terminology.hl7.org/CodeSystem/cmshcc\";\n\nexport const SYSTEM_ICD9 = \"http://hl7.org/fhir/sid/icd-9\";\n\nexport const SYSTEM_ICD9_CM = \"http://hl7.org/fhir/sid/icd-9-cm\";\n\nexport const SYSTEM_ICD10 = \"http://hl7.org/fhir/sid/icd-10\";\n\nexport const SYSTEM_ICD10_CM = \"http://hl7.org/fhir/sid/icd-10-cm\";\n\nexport const SYSTEM_RXNORM = \"http://www.nlm.nih.gov/research/umls/rxnorm\";\n\nexport const SYSTEM_LOINC = \"http://loinc.org\";\n\nexport const SYSTEM_NDC = \"http://hl7.org/fhir/sid/ndc\";\n\nexport const SYSTEM_SNOMED = \"http://snomed.info/sct\";\n\n// ZUS\n\nexport const SYSTEM_SUMMARY = \"https://zusapi.com/summary\";\n\nexport const SYSTEM_ZUS_BUILDER_ID = \"https://zusapi.com/builder_id\";\nexport const SYSTEM_ZUS_CREATED_AT = \"https://zusapi.com/created-at\";\nexport const SYSTEM_ZUS_LENS = \"https://zusapi.com/lens\";\nexport const SYSTEM_ZUS_SUMMARY = \"https://zusapi.com/summary\";\nexport const SYSTEM_ZUS_OWNER = \"https://zusapi.com/accesscontrol/owner\";\nexport const SYSTEM_ZUS_PRACTITIONER_ID = \"https://zusapi.com/practitioner_id\";\nexport const SYSTEM_ZUS_PROFILE_ACTION = \"https://zusapi.com/profile/action\";\nexport const SYSTEM_ZUS_THIRD_PARTY = \"https://zusapi.com/thirdparty/source\";\nexport const SYSTEM_ZUS_UNIVERSAL_ID = \"https://zusapi.com/fhir/identifier/universal-id\";\nexport const SYSTEM_ZUS_UPI_RECORD_TYPE = \"https://zusapi.com/fhir/tag/upi-record-type\";\nexport const SYSTEM_ZUS_USER_TYPE = \"https://zusapi.com/user_type\";\n\n// ENRICHMENT\n\nexport const SYSTEM_ENRICHMENT = \"https://zusapi.com/terminology/enrichment\";\n\n// LENS\nexport const LENS_EXTENSION_AGGREGATED_FROM = \"https://zusapi.com/lens/extension/aggregatedFrom\";\nexport const LENS_EXTENSION_ID = \"https://zusapi.com/lens/id\";\nexport const LENS_EXTENSION_MEDICATION_LAST_FILL_DATE =\n  \"https://zusapi.com/lens/extension/medicationLastFillDate\";\nexport const LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE =\n  \"https://zusapi.com/lens/extension/medicationLastPrescribedDate\";\nexport const LENS_EXTENSION_MEDICATION_QUANTITY =\n  \"https://zusapi.com/lens/extension/medicationQuantity\";\nexport const LENS_EXTENSION_MEDICATION_DAYS_SUPPLY =\n  \"https://zusapi.com/lens/extension/medicationDaysSupply\";\nexport const LENS_EXTENSION_MEDICATION_REFILLS =\n  \"https://zusapi.com/lens/extension/medicationRefills\";\nexport const LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER =\n  \"https://zusapi.com/lens/extension/medicationLastPrescriber\";\n\n// MISC\n\nexport const CTW_EXTENSION_LENS_AGGREGATED_FROM =\n  \"https://zusapi.com/ctw-component-library/extension/lensAggregatedFrom\";\n\n// CUSTOMERS\nexport const SYSTEM_ATHENA_PATIENT = \"https://fhir.athena.io/sid/ah-patient\";\n","// All of the possible resourceType strings.\nexport type ResourceTypeString = fhir4.FhirResource[\"resourceType\"];\n\n// Usage ResourceType<\"MedicationStatement\"> to return the fhir4.MedicationStatement type.\n// This is useful in combination with ResourceTypeString, allowing us to go\n// from the resourceType string to the actual fhir4 resource type.\nexport type ResourceType<T extends ResourceTypeString> = Extract<\n  fhir4.FhirResource,\n  { resourceType: T }\n>;\n\nexport type ResourceMap = { [key: string]: fhir4.Resource | undefined };\nexport type ResourceArrayMap = Map<string, fhir4.Resource[]>;\n\nexport type Tag = { system: string; code: string };\n\nexport function isFHIRDomainResource(resource: unknown): resource is fhir4.DomainResource {\n  return (\n    isFHIRResource(resource) &&\n    // Exclude resource types that extend \"Resource\" and not \"DomainResource\".\n    resource.resourceType !== \"Binary\" &&\n    resource.resourceType !== \"Bundle\"\n  );\n}\n\nexport function isFHIRResource(resource: unknown): resource is fhir4.FhirResource {\n  return typeof resource === \"object\" && resource !== null && \"resourceType\" in resource;\n}\n","import { Basic, Resource } from \"fhir/r4\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport {\n  CTW_EXTENSION_LENS_AGGREGATED_FROM,\n  LENS_EXTENSION_AGGREGATED_FROM,\n  SYSTEM_ENRICHMENT,\n  SYSTEM_SUMMARY,\n  SYSTEM_ZUS_CREATED_AT,\n  SYSTEM_ZUS_OWNER,\n  SYSTEM_ZUS_PROFILE_ACTION,\n  SYSTEM_ZUS_THIRD_PARTY,\n  SYSTEM_ZUS_UNIVERSAL_ID,\n} from \"../system-urls\";\nimport { isFHIRDomainResource, ResourceMap, ResourceTypeString } from \"../types\";\nimport { compact, find, orderBy, some, startCase } from \"@/utils/nodash\";\n\nexport abstract class FHIRModel<T extends fhir4.Resource> {\n  public resource: T;\n\n  // This is a string that is used to identify the type of model and\n  // allows us to use a switch statement to determine the type of model.\n  abstract readonly kind: string;\n\n  readonly includedResources?: ResourceMap;\n\n  private basicResources?: fhir4.Basic[];\n\n  private optimisticIsRead?: boolean;\n\n  private optimisticIsDismissed?: boolean;\n\n  constructor(resource: T, includedResources?: ResourceMap, basics?: fhir4.Basic[]) {\n    this.resource = resource;\n    this.includedResources = includedResources;\n    this.basicResources = basics;\n  }\n\n  // Returns the aggregated from resource ids for summary resources.\n  get aggregatedFromIds(): string[] {\n    if (isFHIRDomainResource(this.resource)) {\n      const extension = find(\n        this.resource.extension,\n        (x) =>\n          x.url === LENS_EXTENSION_AGGREGATED_FROM || x.url === CTW_EXTENSION_LENS_AGGREGATED_FROM,\n      );\n      return compact(extension?.extension?.map((e) => e.valueReference?.reference?.split(\"/\")[1]));\n    }\n    return [];\n  }\n\n  get createdAt(): string | undefined {\n    return find(this.resource.meta?.extension, { url: SYSTEM_ZUS_CREATED_AT })?.valueInstant;\n  }\n\n  get createdAtDisplay(): string | undefined {\n    return formatDateISOToLocal(this.createdAt);\n  }\n\n  get lastUpdated(): string | undefined {\n    return this.resource.meta?.lastUpdated || this.createdAt;\n  }\n\n  get id(): string {\n    return this.resource.id || \"\";\n  }\n\n  // key is used to uniquely identify rows in our resource table\n  get key(): string {\n    return this.id;\n  }\n\n  get versionId(): string {\n    return this.resource.meta?.versionId || \"\";\n  }\n\n  get isDismissed(): boolean {\n    if (this.optimisticIsDismissed !== undefined) {\n      return this.optimisticIsDismissed;\n    }\n\n    const basic = this.getLatestAction([\"archive\", \"unarchive\"]);\n    return some(basic?.code.coding, {\n      system: SYSTEM_ZUS_PROFILE_ACTION,\n      code: \"archive\",\n    });\n  }\n\n  // Special key for filtering. See utils/filters.ts.\n  get isHidden(): boolean {\n    return this.isDismissed;\n  }\n\n  // Optimistically toggle the isDismiss state.\n  // This is useful to be able to change the state of the UI\n  // without having to wait for the toggleRead API call.\n  optimisticToggleIsDismiss(): void {\n    this.optimisticIsDismissed = !this.isDismissed;\n  }\n\n  get isRead(): boolean {\n    if (this.optimisticIsRead !== undefined) {\n      return this.optimisticIsRead;\n    }\n    const basic = this.getLatestAction([\"read\", \"unread\"]);\n    return some(basic?.code.coding, {\n      system: SYSTEM_ZUS_PROFILE_ACTION,\n      code: \"read\",\n    });\n  }\n\n  // Optimistically toggle the isRead state.\n  // This is useful to be able to change the state of the UI\n  // without having to wait for the toggleRead API call.\n  optimisticToggleIsRead(): void {\n    this.optimisticIsRead = !this.isRead;\n  }\n\n  // Returns true if this resource is a summary/lens resource.\n  get isSummaryResource(): boolean {\n    return find(this.resource.meta?.tag, { system: SYSTEM_SUMMARY }) !== undefined;\n  }\n\n  get isThirdPartyData(): boolean {\n    return this.resource.meta?.tag?.some((t) => t.system === SYSTEM_ZUS_THIRD_PARTY) ?? false;\n  }\n\n  // If the data came from a third party data source then return that name\n  get thirdPartyDataSourceName(): string | undefined {\n    return this.resource.meta?.tag?.find((t) => t.system === SYSTEM_ZUS_THIRD_PARTY)?.code;\n  }\n\n  get patientUPID(): string | undefined {\n    if (isFHIRDomainResource(this.resource)) {\n      return find(this.resource.extension, { url: SYSTEM_ZUS_UNIVERSAL_ID })?.valueString;\n    }\n    return undefined;\n  }\n\n  get resourceType(): ResourceTypeString {\n    return this.resource.resourceType as ResourceTypeString;\n  }\n\n  get resourceTypeTitle(): string {\n    return startCase(this.resourceType);\n  }\n\n  abstract get title(): string;\n\n  get basics(): fhir4.Basic[] | undefined {\n    return this.basicResources;\n  }\n\n  set basics(basics: fhir4.Basic[] | undefined) {\n    this.basicResources = basics;\n  }\n\n  // Returns the latest Basic resource that has a code that matches\n  // one of profileActions.\n  // In practice, there should only be a single Basic resource, but\n  // we need to handle the case where there may be several.\n  getLatestAction(profileActions: string[]): Basic | undefined {\n    const ordered = orderBy(this.basics, \"meta.lastUpdated\", \"desc\") as Resource[];\n    return find(ordered, (resource) =>\n      some(\n        (resource as Basic).code.coding,\n        (coding) =>\n          coding.system === SYSTEM_ZUS_PROFILE_ACTION && profileActions.includes(coding.code ?? \"\"),\n      ),\n    ) as Basic | undefined;\n  }\n\n  // Returns true if this resource is enriched with additional data\n  // from Zus enrichment.\n  isEnriched(): boolean {\n    return JSON.stringify(this.resource).includes(SYSTEM_ENRICHMENT);\n  }\n\n  // Returns true if this resource is owned by the specified builder.\n  ownedByBuilder(builderId: string): boolean {\n    if (this.resource.meta?.tag?.some((tag) => tag.system === SYSTEM_ZUS_THIRD_PARTY)) {\n      return false;\n    }\n    const ownerTag = this.resource.meta?.tag?.find((tag) => tag.system === SYSTEM_ZUS_OWNER);\n    const splitTag = ownerTag?.code?.split(\"/\");\n\n    if (splitTag?.length !== 2) {\n      return false;\n    }\n    return splitTag[1] === builderId;\n  }\n\n  // Returns a string that would setup this model.\n  //   E.g. \"new ConditionModel({...resource})\"\n  // Helpful for debugging / console logging.\n  // This way we get copyable code for the model\n  // instead of \"[object Object]\".\n  toString() {\n    const modelName = this.constructor.name;\n    return `new ${modelName}(${JSON.stringify(this.resource, null, 2)}\\n)`;\n  }\n}\n","// Returns a predicate for use with lodash that will find\n// a coding with the given code within an array of CodeableConcepts.\n// E.g. find(concepts, codeableConceptPredicate(\"C\")) will find the first\n\nimport { SYSTEM_ENRICHMENT } from \"./system-urls\";\nimport { compact, filter, find, some } from \"@/utils/nodash\";\n\n/**\n  Finds the best display text for a CodeableConcept.\n \n  Priority order is:\n    1. The display of the coding with the given favoredSystemDisplay\n       (skipping enrichment extensions!).\n    2. The text of the CodeableConcept.\n    3. The display of the first coding with a display.\n    4. The code of the first coding with a code.\n */\nexport const codeableConceptLabel = (\n  concept?: fhir4.CodeableConcept,\n  favoredSystemDisplay?: string,\n): string => {\n  if (favoredSystemDisplay && concept?.coding) {\n    const coding = concept.coding.find(\n      (c) => c.system === favoredSystemDisplay && c.display && !c.extension,\n    );\n    if (coding && coding.display) {\n      return coding.display;\n    }\n  }\n\n  const firstWithDisplay = concept?.coding?.find((c) => c.display);\n  const firstWithCode = concept?.coding?.find((c) => c.code);\n  return concept?.text ?? firstWithDisplay?.display ?? firstWithCode?.code ?? \"\";\n};\n\n// Returns text if there is one, otherwise returns the first display text or an empty string.\nexport const codeableConceptTextOrDisplay = (concept?: fhir4.CodeableConcept): string => {\n  if (concept?.text) {\n    return concept.text;\n  }\n\n  const firstDisplay = compact(concept?.coding?.map((c) => c.display))[0] as string | undefined;\n  return firstDisplay ?? \"\";\n};\n\nexport function findCoding(\n  system: string,\n  concept?: fhir4.CodeableConcept,\n): fhir4.Coding | undefined {\n  return find(concept?.coding, { system });\n}\n\n// Return true if the concept has a coding with the given system and a matching code.\nexport function hasMatchingCode(\n  system: string,\n  codes: string[],\n  concept?: fhir4.CodeableConcept,\n): boolean {\n  return some(\n    concept?.coding,\n    (coding) => coding.system === system && codes.includes(coding.code ?? \"\"),\n  );\n}\n\nexport function findCodingWithEnrichment(\n  system: string,\n  concept?: fhir4.CodeableConcept,\n): fhir4.Coding | undefined {\n  return find(concept?.coding, {\n    system,\n    extension: [{ url: SYSTEM_ENRICHMENT }],\n  });\n}\n\nexport function findAllCodingsWithEnrichment(\n  system: string,\n  concept?: fhir4.CodeableConcept,\n): fhir4.Coding[] {\n  return filter(concept?.coding, {\n    system,\n    extension: [{ url: SYSTEM_ENRICHMENT }],\n  });\n}\n\nexport function findCodingWithEnrichmentValueString(\n  valueString: string,\n  concept?: fhir4.CodeableConcept,\n): fhir4.Coding | undefined {\n  return find(concept?.coding, {\n    extension: [{ url: SYSTEM_ENRICHMENT, valueString }],\n  });\n}\n\nexport type CodePreference = { system: string; checkForEnrichment?: boolean };\n\nexport const findCodingByOrderOfPreference = (\n  preferences: CodePreference[],\n  concept: fhir4.CodeableConcept | undefined,\n): fhir4.Coding | undefined => {\n  for (let i = 0; i < preferences.length; i += 1) {\n    const code = preferences[i];\n    if (code.checkForEnrichment) {\n      const coding = findCodingWithEnrichment(code.system, concept);\n      if (coding) {\n        return coding;\n      }\n    } else {\n      const coding = findCoding(code.system, concept);\n      if (coding) {\n        return coding;\n      }\n    }\n  }\n\n  return undefined;\n};\n","import { codeableConceptLabel } from \"@/fhir/codeable-concept\";\n\nexport class OperationOutcomeIssueModel {\n  public resource: fhir4.OperationOutcomeIssue;\n\n  constructor(issue: fhir4.OperationOutcomeIssue) {\n    this.resource = issue;\n  }\n\n  get display(): string {\n    return (\n      codeableConceptLabel(this.resource.details) ||\n      this.resource.diagnostics ||\n      `${this.resource.code} error`\n    );\n  }\n\n  get severity(): fhir4.OperationOutcomeIssue[\"severity\"] {\n    return this.resource.severity;\n  }\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { OperationOutcomeIssueModel } from \"./operation-outcome-issue\";\n\nexport class OperationOutcomeModel extends FHIRModel<fhir4.OperationOutcome> {\n  kind = \"OperationOutcome\" as const;\n\n  // Condense the errors into one string.\n  get display(): string {\n    const issues = this.resource.issue\n      .filter((issue) => issue.severity !== \"warning\")\n      .map((issue) => {\n        let locationError = \"\";\n        if (issue.location && issue.location.length > 0) {\n          const location = issue.location[0];\n          locationError += `${location} -- `;\n        }\n        return `${locationError}${issue.diagnostics}`;\n      });\n\n    return issues.join(\"; \");\n  }\n\n  // Get the models of each issue in this outcome.\n  get issues(): OperationOutcomeIssueModel[] {\n    return this.resource.issue.map((issue) => new OperationOutcomeIssueModel(issue));\n  }\n\n  get title() {\n    return this.display;\n  }\n}\n","import { isOperationOutcome } from \"./operation-outcome\";\nimport { OperationOutcomeModel } from \"@/fhir/models/operation-outcome\";\n\nexport type FhirError = {\n  response: {\n    status: number;\n    data: unknown;\n  };\n  config: {\n    method: string;\n    url: string;\n    headers: Record<string, string>;\n  };\n};\n\nexport function isFhirError(error: unknown): error is FhirError {\n  if (typeof error === \"object\" && error !== null) {\n    return \"response\" in error && \"config\" in error;\n  }\n  return false;\n}\n\nexport const fhirErrorResponse = (title: string, e: FhirError) => {\n  const { data, status } = e.response;\n  let errorStr = \"\";\n  if (isOperationOutcome(data)) {\n    errorStr = new OperationOutcomeModel(data).display;\n  }\n\n  return { title, status, statusText: errorStr };\n};\n","import { faCircleCheck } from \"@fortawesome/free-regular-svg-icons\";\nimport { faCircleExclamation } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { toast, ToastOptions } from \"react-toastify\";\n\nexport type ToastProps = {\n  title?: string;\n  body?: string;\n  options?: Omit<ToastOptions, \"type\" | \"containerId\" | \"className\">;\n  containerId?: string;\n  type: \"success\" | \"info\" | \"error\";\n};\n\nexport const APP_TOAST_CONTAINER_ID = \"ctw-toast-container\";\nexport const APP_TOAST_CONTAINER_DRAWER_ID = \"ctw-toast-container-drawer\";\n\nexport const drawerToastStyles = { style: { bottom: \"40px\" } };\n\nexport const notifyFromDrawer = ({ type, title, body, options }: Omit<ToastProps, \"containerId\">) =>\n  notify({ type, title, body, options, containerId: APP_TOAST_CONTAINER_DRAWER_ID });\n\nexport const notify = ({\n  type,\n  title,\n  body,\n  options,\n  containerId = APP_TOAST_CONTAINER_ID,\n}: ToastProps) => {\n  const toastOptions: ToastOptions = {\n    closeOnClick: false,\n    draggable: false,\n    // Auto close all toasts after 4 seconds, except for error toasts.\n    autoClose: type === \"error\" ? undefined : 4000,\n    containerId,\n    ...options,\n  };\n\n  const content = (\n    <div className=\"ctw-toast\">\n      {title && <div className=\"ctw-font-medium\">{title}</div>}\n      {body && <div>{body}</div>}\n    </div>\n  );\n\n  switch (type) {\n    case \"success\":\n      toast.success(content, {\n        ...toastOptions,\n        icon: <FontAwesomeIcon icon={faCircleCheck} className=\"ctw-h-5 ctw-text-success-main\" />,\n      });\n      break;\n\n    case \"info\":\n      toast.info(content, {\n        ...toastOptions,\n        icon: false,\n      });\n      break;\n\n    case \"error\":\n      toast.error(content, {\n        ...toastOptions,\n        icon: (\n          <FontAwesomeIcon icon={faCircleExclamation} className=\"ctw-h-5 ctw-text-error-main\" />\n        ),\n      });\n      break;\n\n    default:\n      // Type of \"type\" prop should prevent this from happening.\n      throw new Error(`Unknown toast type: ${type}`);\n  }\n};\n","import jwt_decode from \"jwt-decode\";\nimport { notify } from \"@/components/core/toast\";\n\nexport const AUTH_BUILDER_ID = \"https://zusapi.com/builder_id\";\nexport const AUTH_BUILDER_NAME = \"https://zusapi.com/builder_name\";\nexport const AUTH_PRACTITIONER_ID = \"https://zusapi.com/practitioner_id\";\nexport const AUTH_IS_SUPER_ORG = \"https://zusapi.com/is_super_org\";\nexport const AUTH_PERMISSION_TOKEN = \"https://zusapi.com/permissions_token\";\nexport const AUTH_EMAIL = \"https://zusapi.com/email\";\nexport const AUTH_USER_ID = \"https://zusapi.com/user_id\";\nexport const AUTH_APP_CLIENT_ID = \"https://zusapi.com/app_client_id\";\nexport const AUTH_USER_TYPE = \"https://zusapi.com/user_type\";\nexport const AUTH_PATIENT_ID = \"https://zusapi.com/patient_id\";\nexport const AUTH_AUTHENTICATED_BY = \"https://zusapi.com/authenticated_by\";\n\nexport type ZusJWT = {\n  [AUTH_BUILDER_ID]: string;\n  [AUTH_BUILDER_NAME]: string;\n  [AUTH_PRACTITIONER_ID]: string;\n  [AUTH_IS_SUPER_ORG]: string;\n  [AUTH_PERMISSION_TOKEN]: string;\n  [AUTH_EMAIL]: string;\n  [AUTH_USER_ID]: string;\n  [AUTH_APP_CLIENT_ID]: string;\n  [AUTH_USER_TYPE]: string;\n  [AUTH_PATIENT_ID]: string;\n  [AUTH_AUTHENTICATED_BY]: string;\n  iss: string;\n  sub: string;\n  aud: string[];\n  iat: number;\n  exp: number;\n  azp: string;\n  scope: string;\n};\n\nfunction getClaims(authToken: string): ZusJWT {\n  try {\n    return jwt_decode(authToken);\n  } catch {\n    return {} as ZusJWT;\n  }\n}\n\nexport function claimsUserType(authToken: string): string | undefined {\n  return getClaims(authToken)[AUTH_USER_TYPE];\n}\n\nexport function claimsBuilderId(authToken: string): string | undefined {\n  return getClaims(authToken)[AUTH_BUILDER_ID];\n}\n\nexport function claimsBuilderName(authToken: string): string | undefined {\n  return getClaims(authToken)[AUTH_BUILDER_NAME];\n}\n\nexport function claimsExp(authToken: string): number {\n  return getClaims(authToken).exp;\n}\n\nexport function claimsPractitionerId(authToken: string): string | undefined {\n  return getClaims(authToken)[AUTH_PRACTITIONER_ID];\n}\n\nexport function claimsAuthEmail(authToken: string): string | undefined {\n  return getClaims(authToken)[AUTH_EMAIL];\n}\n\nexport function hasUnexpiredToken(authToken?: string): boolean {\n  if (!authToken) {\n    return false;\n  }\n  return claimsExp(authToken) * 1000 > Date.now();\n}\n\nexport function hasValidClaimsAuthEmail(authToken: string): boolean {\n  return hasUnexpiredToken(authToken) && !!claimsAuthEmail(authToken);\n}\n\nexport function sendInvalidTokenNotification(authToken: string, toastId: string) {\n  const message = hasUnexpiredToken(authToken)\n    ? \"Only user tokens are allowed\"\n    : \"This token has expired\";\n  notify({\n    type: \"error\",\n    title: \"Warning\",\n    body: `Invalid auth token: ${message}`,\n    options: {\n      toastId,\n    }\n  });\n}\n","import { datadogLogs } from \"@datadog/browser-logs\";\nimport jwtDecode from \"jwt-decode\";\nimport { RequestError } from \"./error\";\nimport { ReactQueryError } from \"./react-query-error\";\nimport { Session } from \"./session\";\nimport packageJson from \"../../package.json\";\nimport { getCTWBaseUrl } from \"@/api/urls\";\nimport { FhirError, fhirErrorResponse } from \"@/fhir/errors\";\nimport {\n  AUTH_BUILDER_ID,\n  AUTH_BUILDER_NAME,\n  AUTH_EMAIL,\n  AUTH_IS_SUPER_ORG,\n  AUTH_PRACTITIONER_ID,\n  AUTH_USER_ID,\n  AUTH_USER_TYPE,\n  ZusJWT,\n} from \"@/utils/auth\";\nimport { compact, snakeCase } from \"@/utils/nodash\";\n\ntype TelemetryEventKey = \"zusTelemetryClick\" | \"zusTelemetryFocus\";\n\nconst prodDatadogConfig = {\n  service: \"ctw-component-library\",\n  clientToken: \"pub7f1b01887ceb412fd989f5e08cf60d9a\",\n  applicationId: \"44011d8b-3aa4-4672-9c7b-ee23ddac16b5\",\n};\nconst devDatadogConfig = {\n  service: \"ctw-component-library\",\n  clientToken: \"pub29b659b1cd402a88d57c4f8c923c1eea\",\n  applicationId: \"48fec1f8-b187-492a-afdd-e809cc6b3b82\",\n};\n\nlet origin = \"\";\nlet body: HTMLElement | undefined;\nif (typeof window !== \"undefined\") {\n  origin = window.location.origin;\n  body = window.document.body;\n}\n\nconst FLUSH_DEFERRED_TIMEOUT_MS = 200;\n// Assume local development if origin is localhost or just an IP address\nconst isLocalDevelopment = /https?:\\/\\/(localhost|\\d+\\.\\d+\\.\\d+\\.\\d+)/i.test(origin);\n// Avoid initializing telemetry or event listeners multiple times\nlet isInitialized = false;\nlet listenersHaveBeenAdded = false;\n\n/**\n * Bootstrap APM Tracing\n *\n * @description Starts up DataDog RUM and tracing. Depending on the configuration the\n * RUM client will decorate requests to allowed origins with x-datadog-trace-id\n * headers, profile the in-browser app and optionally even record sessions.\n * Visit the docs for important configuration options.\n *\n * https://docs.datadoghq.com/real_user_monitoring/browser/#configuration\n */\nexport class Telemetry {\n  private static accessToken = \"\";\n\n  private static get telemetryIsAvailable() {\n    return Boolean(this.environment && isInitialized);\n  }\n\n  private static datadogLoggingEnabled = false;\n\n  private static unauthorizedAnalyticBuffer: {\n    name: string;\n    properties: Record<string, unknown>;\n  }[] = [];\n\n  private static unauthorizedMetricBuffer: {\n    type: string;\n    metric: string;\n    value: number;\n    additionalTags: string[];\n  }[] = [];\n\n  static logger = datadogLogs.logger;\n\n  static environment = \"\";\n\n  static ehr = \"unknown\";\n\n  /**\n   * We need to normalize environment name in order to effectively use template\n   * variables on dashboards in Datadog. Otherwise, users of the dashboard would\n   * need to know to select all variations of an environment.\n   */\n  static setEnv(environment: string) {\n    this.environment = environment.toLowerCase();\n    if ([\"dev\", \"development\"].includes(this.environment)) {\n      this.environment = \"dev\";\n    }\n    if ([\"prod\", \"production\"].includes(this.environment)) {\n      this.environment = \"prod\";\n    }\n  }\n\n  static init(environment: string, ehr = \"unknown\", allowDataDogLogging = false) {\n    this.datadogLoggingEnabled = allowDataDogLogging;\n    this.setEnv(environment);\n    this.setEHR(ehr);\n\n    // Turning on Datadog Logging is conditional. However, the event handlers\n    // that explicitly send internal /report/metrics to ctw are not optional.\n    if (!this.telemetryIsAvailable && allowDataDogLogging) {\n      datadogLogs.init({\n        ...(isLocalDevelopment ? devDatadogConfig : prodDatadogConfig),\n        env: this.environment,\n        forwardConsoleLogs: [], // No console logs to datadog.\n        forwardErrorsToLogs: false,\n        site: \"datadoghq.com\",\n        version: packageJson.version,\n      });\n    }\n\n    // We need to ensure that this will run in browser context, not just server.\n    if (!listenersHaveBeenAdded && body) {\n      // We are listening to click events propagating to the document body as that\n      // is the lowest level HTMLElement we actually know will both exist at this\n      // time and which won't be removed from the DOM by React causing a small\n      // memory leak.\n      // Additionally, because we aren't listening directly to events on elements\n      // that have `data-zus-telemetry-*` attributes, we don't have the luxury of\n      // knowing whether an event triggered from inside one of these telemetry\n      // elements, so we'll have to traverse the DOM tree ourselves. To minimize\n      // this work we'll put a `depth` level and adjust it over time if needed.\n      // For example, imagine the user clicked an element with CSS selector path\n      // of \"button[data-zus-telemetry-click=\"submit\"] > span > span\". Because we\n      // are listening on body and not button, we would have to walk up 2 parent\n      // nodes of the DOM before knowing whether this event was relevant to us.\n      body.addEventListener(\"click\", (event: MouseEvent) => {\n        const { target, isTrusted } = event;\n        if (!(isTrusted && target instanceof Element)) {\n          return;\n        }\n        const htmlElement = this.closestHTMLElement(target);\n        if (htmlElement instanceof HTMLElement) {\n          this.processHTMLEvent(htmlElement, \"zusTelemetryClick\");\n        }\n      });\n      body.addEventListener(\"focusin\", (event) => {\n        const { target, isTrusted } = event;\n        if (isTrusted && target instanceof HTMLElement) {\n          this.processHTMLEvent(target, \"zusTelemetryFocus\");\n        }\n      });\n      listenersHaveBeenAdded = true;\n    }\n\n    isInitialized = true;\n    if (!this.accessToken) {\n      setTimeout(() => {\n        void this.flushUnauthorizedAnalyticBuffer();\n      }, FLUSH_DEFERRED_TIMEOUT_MS);\n    }\n  }\n\n  static setEHR(ehr: string) {\n    if (this.datadogLoggingEnabled) {\n      datadogLogs.setGlobalContextProperty(\"ehr\", ehr);\n    }\n    this.ehr = ehr;\n  }\n\n  static setBuilder(builderId?: string) {\n    if (this.datadogLoggingEnabled) {\n      datadogLogs.setGlobalContextProperty(\"builderId\", builderId);\n    }\n  }\n\n  static setPatientUPID(upid?: string) {\n    if (this.datadogLoggingEnabled) {\n      datadogLogs.setGlobalContextProperty(\"patientUPID\", upid);\n    }\n  }\n\n  static setUser(accessToken?: string) {\n    if (accessToken) {\n      this.accessToken = accessToken;\n      const user = jwtDecode(accessToken) as ZusJWT;\n      Session.setSessionUserId(user[AUTH_USER_ID]);\n      const decodedUser = {\n        id: user[AUTH_USER_ID],\n        type: user[AUTH_USER_TYPE],\n        email: user[AUTH_EMAIL],\n        practitionerId: user[AUTH_PRACTITIONER_ID],\n        builderName: user[AUTH_BUILDER_NAME],\n        builderId: user[AUTH_BUILDER_ID],\n        isSuperOrg: user[AUTH_IS_SUPER_ORG],\n      };\n\n      if (this.datadogLoggingEnabled) {\n        datadogLogs.setUser(decodedUser);\n      }\n    }\n  }\n\n  static clearUser() {\n    this.accessToken = \"\";\n    datadogLogs.setUser({});\n  }\n\n  static trackView(viewName: string) {\n    this.countMetric(`component.${viewName}.loaded`);\n  }\n\n  static logError(error: Error, overrideMessage?: string): Error {\n    if (error instanceof RequestError) {\n      this.logger.error(error.message, {\n        error: {\n          stack: error.stack,\n          statusCode: error.statusCode,\n          statusText: error.message,\n        },\n      });\n      return error;\n    }\n\n    if (error instanceof ReactQueryError) {\n      this.logger.error(error.message, {\n        error: {\n          stack: error.stack,\n          queryKey: error.queryKey[0],\n          statusText: error.message,\n        },\n      });\n      return error;\n    }\n\n    const err = new Error(overrideMessage ?? error.message);\n    this.logger.error(err.message, {\n      error: {\n        stack: error.stack,\n      },\n    });\n    return err;\n  }\n\n  static logFhirError(error: FhirError, message: string) {\n    const context = fhirErrorResponse(message, error);\n    this.logger.error(message, context);\n  }\n\n  static trackInteraction(\n    action: string,\n    metadata: Record<string, unknown> & { datadogMetricName?: string } = {},\n  ) {\n    // If `datadogMetricName` is not provided, we default to the action name.\n    // This allows us to send a different metric name to DataDog if needed.\n    const { datadogMetricName = action, ...eventMetadata } = metadata;\n    // We send an action metric to CTW\n    this.countMetric(`action.${datadogMetricName}`, 1);\n    // We report an active session to CTW\n    this.reportActiveSession().catch((error) => Telemetry.logError(error as Error));\n    this.analyticsEvent(action, eventMetadata).catch((error) => Telemetry.logError(error as Error));\n  }\n\n  /**\n   * Metrics names are alphanumeric, lowercase, seperated by only \".\" or \"_\"\n   */\n  private static normalizeMetricName(metric: string) {\n    return metric\n      .split(\".\")\n      .map(snakeCase)\n      .join(\".\")\n      .replace(/[^a-z0-9_.]/gi, \"\");\n  }\n\n  /*\n   * In dev/test environments we should skip sending any metrics\n   */\n  static shouldSkipSendingMetrics() {\n    return (\n      !this.environment ||\n      (process.env.NODE_ENV !== \"test\" && /(localhost|127\\.0\\.0\\.1)/.test(window.location.origin))\n    );\n  }\n\n  private static deferAnalyticEvent(name: string, properties: Record<string, unknown> = {}) {\n    this.unauthorizedAnalyticBuffer.push({ name, properties });\n  }\n\n  private static deferMetricEvent(\n    type: string,\n    metric: string,\n    value: number,\n    additionalTags: string[] = [],\n  ) {\n    this.unauthorizedMetricBuffer.push({ type, metric, value, additionalTags });\n  }\n\n  private static async flushUnauthorizedAnalyticBuffer(): Promise<void> {\n    if (!this.accessToken) {\n      setTimeout(() => {\n        void this.flushUnauthorizedAnalyticBuffer();\n      }, FLUSH_DEFERRED_TIMEOUT_MS);\n      return;\n    }\n\n    try {\n      if (this.unauthorizedAnalyticBuffer.length) {\n        await Promise.all(\n          this.unauthorizedAnalyticBuffer.map(({ name, properties }) =>\n            this.analyticsEvent(name, properties),\n          ),\n        );\n      }\n      if (this.unauthorizedMetricBuffer.length) {\n        await Promise.all(\n          this.unauthorizedMetricBuffer.map(({ type, metric, value, additionalTags }) =>\n            this.reportMetric(type, metric, value, additionalTags),\n          ),\n        );\n      }\n    } catch {\n      // eslint-disable-next-line no-console\n      console.warn(\"[Telemetry] Failed to flush unauthorized event buffer\");\n    }\n  }\n\n  /**\n   * Report a metric to CTW\n   */\n  static async reportMetric(\n    type: string,\n    metric: string,\n    value: number,\n    additionalTags: string[] = [],\n  ) {\n    if (this.shouldSkipSendingMetrics()) {\n      return;\n    }\n\n    if (!this.accessToken) {\n      this.deferMetricEvent(type, metric, value, additionalTags);\n      return;\n    }\n\n    let user;\n    const name = this.normalizeMetricName(metric);\n    try {\n      user = jwtDecode(this.accessToken) as ZusJWT;\n    } catch {\n      user = {};\n    }\n\n    const tags = compact([\n      \"service:ctw-component-library\",\n      `env:${this.environment}`,\n      user[AUTH_BUILDER_NAME] ? `builder_name:${user[AUTH_BUILDER_NAME]}` : undefined,\n      `user_id:${user[AUTH_USER_ID]}`,\n      `is_super:${user[AUTH_IS_SUPER_ORG] || \"false\"}`,\n      this.ehr ? `ehr:${this.ehr}` : undefined,\n      `version:${packageJson.version}`,\n      ...additionalTags,\n    ]);\n\n    await fetch(`${getCTWBaseUrl(this.environment)}/report/metric`, {\n      method: \"POST\",\n      headers: {\n        Authorization: `Bearer ${this.accessToken}`,\n      },\n      body: JSON.stringify({ name, type, tags, value }),\n      mode: \"cors\",\n    });\n  }\n\n  /**\n   * Report User analytic events\n   */\n  static async analyticsEvent(eventName: string, eventProperties: Record<string, unknown> = {}) {\n    if (this.shouldSkipSendingMetrics()) {\n      return;\n    }\n\n    if (!this.accessToken) {\n      this.deferAnalyticEvent(eventName, eventProperties);\n      return;\n    }\n\n    try {\n      const analyticEvent = {\n        event: eventName,\n        metadata: {\n          ...eventProperties,\n          ehr: this.ehr || undefined,\n          libraryVersion: packageJson.version,\n        },\n      };\n\n      await fetch(`${getCTWBaseUrl(this.environment)}/report/analytic`, {\n        method: \"POST\",\n        headers: {\n          Authorization: `Bearer ${this.accessToken}`,\n        },\n        // Base64 encode the event name and user information\n        body: JSON.stringify(analyticEvent),\n        mode: \"cors\",\n      });\n    } catch {\n      // Nothing to do here.\n    }\n  }\n\n  static countMetric(name: string, value = 1, tags: string[] = []) {\n    Telemetry.reportMetric(\"increment\", name, value, tags).catch((error) =>\n      Telemetry.logError(error as Error),\n    );\n  }\n\n  static histogramMetric(name: string, value: number, tags: string[] = []) {\n    Telemetry.reportMetric(\"histogram\", name, value, tags).catch((error) =>\n      Telemetry.logError(error as Error),\n    );\n  }\n\n  static timeMetric(metric: string, tags: string[] = []) {\n    const start = new Date().getTime();\n\n    // Callback should not return a promise or throw errors to the consumer\n    return function endTiming() {\n      const end = new Date().getTime();\n      Telemetry.reportMetric(\"timing\", metric, end - start, tags).catch((error) =>\n        Telemetry.logError(error as Error),\n      );\n    };\n  }\n\n  static reportActionSuccess(metric: string, tags: string[] = []) {\n    Telemetry.countMetric(`action.${metric}.success`, 1, tags);\n  }\n\n  static reportActionFailure(metric: string, tags: string[] = []) {\n    Telemetry.countMetric(`action.${metric}.failure`, 1, tags);\n  }\n\n  static processHTMLEvent(\n    target: HTMLElement,\n    telemetryKey: TelemetryEventKey,\n    explicitTargetName?: string,\n  ) {\n    let eventTarget: HTMLElement | null = null;\n\n    if (explicitTargetName) {\n      eventTarget = target;\n    } else {\n      let nextTarget: HTMLElement | null = target;\n      let depth = 5;\n      while (!eventTarget && depth > 0 && nextTarget) {\n        if (nextTarget.dataset[telemetryKey]) {\n          eventTarget = nextTarget;\n        }\n        nextTarget = nextTarget.parentElement;\n        depth -= 1;\n      }\n    }\n\n    const targetName = eventTarget?.dataset[telemetryKey] ?? explicitTargetName;\n    if (eventTarget && targetName) {\n      this.trackInteraction(targetName);\n    }\n  }\n\n  private static closestHTMLElement(target: Element | Node | null): HTMLElement | null {\n    if (!target || target instanceof HTMLElement) {\n      return target;\n    }\n    if (target.parentElement instanceof HTMLElement) {\n      return target.parentElement;\n    }\n    return this.closestHTMLElement(target.parentNode);\n  }\n\n  static async reportActiveSession() {\n    // Return if the session is already active or we don't need to report\n    if (Session.isActive() || this.shouldSkipSendingMetrics()) {\n      return;\n    }\n\n    try {\n      // Set last active timestamp so we don't report the same session twice\n      const user = jwtDecode(this.accessToken) as ZusJWT;\n      Session.setSessionUserId(user[AUTH_USER_ID]);\n      Session.setSessionLastActiveTimestamp();\n      await Telemetry.reportMetric(\"increment\", \"active_session\", 1, []);\n    } catch {\n      // Clear the session last active timestamp because we didn't report it\n      Session.clearSessionLastActiveTimestamp();\n    }\n  }\n}\n\n/**\n * Wrapper to time a function\n *\n * @example\n * ```\n * withTimerMetric(async (requestContext, patient) => {\n *   const data = await getData(requestContext, patient);\n *   return applyTransform(data);\n * }, \"req.data_transform\")\n * ```\n */\nexport const withTimerMetric =\n  <Args extends unknown[], Return>(\n    fn: (...args: Args) => Promise<Return>,\n    name: string,\n    tags: string[] = [],\n  ) =>\n  async (...args: Args) => {\n    let sendMetric;\n    try {\n      sendMetric = Telemetry.timeMetric(name, tags);\n      return await fn(...args);\n    } catch (e) {\n      sendMetric = undefined;\n      throw e;\n    } finally {\n      sendMetric?.();\n    }\n  };\n","import { Query, QueryCache, QueryClient } from \"@tanstack/react-query\";\nimport { RequestError } from \"./error\";\nimport { ReactQueryError } from \"./react-query-error\";\nimport { Telemetry } from \"./telemetry\";\n\nexport type UseQueryResultBasic<T> = {\n  data: T;\n  isLoading: boolean;\n};\n\nfunction logOnError(err: unknown, query: Query) {\n  const error = new ReactQueryError(query, err);\n  Telemetry.logError(error);\n}\n\nexport const queryClient = new QueryClient({\n  defaultOptions: {\n    queries: {\n      retry: false,\n      // NOTE: Stale time must be kept less than what we'd expect auth token\n      // expiration to be. This ensures that if the token expires and we go to\n      // fetch a fresh one, we don't get a stale token from react-query cache.\n      staleTime: 1000 * 30, // 30s.\n      refetchOnWindowFocus: false,\n    },\n  },\n  queryCache: new QueryCache({\n    onError: logOnError,\n  }),\n});\n\nexport const CTW_REQUEST_HEADER = { \"Zus-Request-Source\": \"component-library\" };\n\nexport type CTWRequestInit = {\n  headers?: Record<string, string>;\n} & Omit<RequestInit, \"headers\">;\n\nconst xmlTypes = [\"/xml\", \"/xhtml+xml\", \"application/xml\", \"text/xml\"];\nconst pdfTypes = [\"/pdf\"];\nconst tiffTypes = [\"/tif\", \"/tiff\"];\nconst webImageTypes = [\"/jpg\", \"/jpeg\", \"/png\", \"/apng\", \"/avif\", \"/gif\", \"/webp\", \"/svg+xml\"];\n\nexport async function ctwFetch(input: RequestInfo | URL, init?: CTWRequestInit) {\n  const headers = init?.headers ?? {};\n\n  const newInit: CTWRequestInit = init ?? {};\n  newInit.headers = {\n    ...CTW_REQUEST_HEADER,\n    ...headers,\n  };\n\n  const fetchResponse = await fetch(input, newInit);\n  await assertResponseOK(fetchResponse);\n\n  return { data: await getResponseContent(fetchResponse), headers: fetchResponse.headers };\n}\n\nexport const getResponseContent = async (response: Response) => {\n  const contentType = response.headers.get(\"content-type\");\n  if (contentType?.includes(\"json\")) {\n    return response.json();\n  }\n  if (contentType?.includes(\"text\")) {\n    return response.text();\n  }\n  if (\n    [...xmlTypes, ...pdfTypes, ...tiffTypes, ...webImageTypes].some(\n      (type) => contentType?.includes(type),\n    )\n  ) {\n    return response.blob();\n  }\n  return response.json();\n};\n\nexport async function assertResponseOK(response: Awaited<Response>) {\n  if (!response.ok) {\n    let data;\n    let errorMsg = response.statusText;\n    const contentType = response.headers.get(\"content-type\");\n    if (contentType?.includes(\"json\")) {\n      data = await response.json();\n      errorMsg = JSON.stringify(data);\n    }\n\n    // try to get error message directly from DA response\n    if (\"detail\" in data) {\n      throw new Error(data.detail);\n    }\n\n    switch (response.status) {\n      case 401:\n        throw new RequestError(response, errorMsg);\n      case 403:\n        throw new RequestError(response, errorMsg);\n      case 404:\n        throw new RequestError(response, errorMsg);\n      default:\n        throw new RequestError(response, response.statusText);\n    }\n  }\n}\n","import Client from \"fhir-kit-client\";\nimport { getZusFhirBaseUrl, getZusFhirWriteBackBaseUrl } from \"@/api/urls\";\nimport { Env } from \"@/components/core/providers/types\";\nimport { CTW_REQUEST_HEADER } from \"@/utils/request\";\n\nexport function getFhirClients(\n  env: Env,\n  accessToken: string,\n  builderId?: string,\n  resourceSaveHeaders?: Record<string, string>,\n) {\n  const customHeaders: HeadersInit = { ...CTW_REQUEST_HEADER };\n  if (builderId) {\n    customHeaders[\"Zus-Account\"] = builderId;\n  }\n\n  // fhirClient reads/writes directly to and from ODS\n  const fhirClient = new Client({\n    baseUrl: getZusFhirBaseUrl(env),\n    bearerToken: accessToken,\n    customHeaders,\n  });\n\n  const writeBackCustomHeaders = { ...customHeaders };\n  if (resourceSaveHeaders) {\n    Object.assign(writeBackCustomHeaders, resourceSaveHeaders);\n  }\n  // fhirWriteBackClient uses write-back proxy to create new FHIR resources which could also have\n  // configurations in ehr-data-integration service to additionally write out to an external source\n  const fhirWriteBackClient = new Client({\n    baseUrl: getZusFhirWriteBackBaseUrl(env),\n    bearerToken: accessToken,\n    customHeaders: writeBackCustomHeaders,\n  });\n\n  return {\n    fhirClient,\n    fhirWriteBackClient,\n  };\n}\n\n// Takes a fhir resource and returns a new one that has numerous fixes\n// to help get saves working with ODS.\n// 1. Remoes all empty arrays.\n//    This fixes an issue where ODS will complain with:\n//    \"Array cannot be empty - the property should not be present if it has no values\"\n// 2. Removes all null and undefined values.\n// 3. Removes \"resource\" from references which are added by FQS.\nexport const fixupFHIR = <T>(value: T): T =>\n  // Cast because the function that finds and omits arrays produces an unknown.\n  fixupFHIRHelper(value) as T;\n\nconst fixupFHIRHelper = (value: unknown): unknown => {\n  if (Array.isArray(value)) {\n    if (value.length === 0) {\n      return undefined;\n    }\n    return value.map(fixupFHIR);\n  }\n\n  if (value !== null && typeof value === \"object\") {\n    const newValue = value as { [key: string]: unknown };\n    Object.entries(newValue).forEach(([key, v]) => {\n      if (v === undefined || v === null) {\n        delete newValue[key];\n      } else {\n        newValue[key] = fixupFHIR(v);\n      }\n      // FQS allows fetching nested \"resource\" objects from references.\n      // We cannot pass these back when saving to ODS,\n      // so we delete them from the object here.\n      // Our simple test is if the current object has a \"reference\"\n      // and a \"resource\" object.\n      if (newValue.reference && typeof newValue.resource === \"object\") {\n        delete newValue.resource;\n      }\n    });\n    return newValue;\n  }\n\n  return value;\n};\n","// Takes a fqs graphql response and returns a new one that removes nulls and undefineds\n// and replaces aliased field names with their source field name.\n// Removes all null and undefined values.\n// Replaces aliased field names in the format '_somealias__field' with 'field'.\nexport const graphQLToFHIR = <T>(value: T): T =>\n  // Cast because the function that finds and omits arrays produces an unknown.\n  graphQLToFHIRHelper(value) as T;\n\nconst graphQLToFHIRHelper = (value: unknown): unknown => {\n  const aliasRegEx = /_[^_]+__(\\w+)/;\n  if (Array.isArray(value)) {\n    return value.map(graphQLToFHIR);\n  }\n\n  if (value !== null && typeof value === \"object\") {\n    const newValue = value as { [key: string]: unknown };\n    Object.entries(newValue).forEach(([key, v]) => {\n      if (aliasRegEx.test(key)) {\n        const match = key.match(aliasRegEx);\n        if (match) {\n          delete newValue[key];\n          newValue[match[1]] = v;\n        }\n      }\n      if (v === undefined || v === null) {\n        delete newValue[key];\n      } else {\n        newValue[key] = graphQLToFHIR(v);\n      }\n    });\n    return newValue;\n  }\n\n  return value;\n};\n","import { isValidElement, ReactNode } from \"react\";\n\nexport type AllOrNone<T> = T | { [K in keyof T]?: never };\n\nexport function isMouseEvent(e: unknown): e is MouseEvent {\n  return !!(e && typeof e === \"object\" && \"preventDefault\" in e);\n}\n\nexport const hasNumber = (str: string | number | undefined) => /\\d/.test(String(str));\n\n// Properly check if the value is an \"empty\" value.\n// This works better than lodash's isEmpty in that it properly handles\n// number and boolean types.\n// See https://medium.com/@trmaphi/lodash-isempty-value-you-might-be-using-it-the-wrong-way-d83210d7decf\nexport const isEmptyValue = (value: unknown) =>\n  value === undefined ||\n  value === null ||\n  Number.isNaN(value) ||\n  (typeof value === \"object\" && Object.keys(value).length === 0) ||\n  (typeof value === \"string\" && value.trim().length === 0);\n\nexport type DeepPartial<T> = {\n  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];\n};\n\nexport type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };\n\nexport type VoidValue = Promise<void> | void;\n\nexport function isReactNode(node: unknown): node is ReactNode {\n  return isValidElement(node);\n}\n","import { GraphQLClient, Variables } from \"graphql-request\";\nimport { graphQLToFHIR } from \"./graphql-to-fhir\";\nimport { getZusServiceUrl } from \"@/api/urls\";\nimport { Env } from \"@/components/core/providers/types\";\nimport { ResourceType, ResourceTypeString } from \"@/fhir/types\";\nimport { CTW_REQUEST_HEADER, ctwFetch } from \"@/utils/request\";\nimport { Telemetry } from \"@/utils/telemetry\";\nimport { isEmptyValue } from \"@/utils/types\";\n\nexport interface GraphqlPageInfo {\n  hasNextPage: boolean;\n  startCursor?: string;\n  endCursor?: string;\n}\n\nexport interface GraphqlConnectionNode<T> {\n  node: T;\n}\n\nexport interface GenericConnection<T extends ResourceTypeString> {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<ResourceType<T>>[];\n}\n\nexport const MAX_OBJECTS_PER_REQUEST = 500;\n\nexport const createGraphqlClient = (requestContext: { env: string; authToken: string }) => {\n  const endpoint = `${getZusServiceUrl(requestContext.env, \"fqs\")}/query`;\n  return new GraphQLClient(endpoint, {\n    errorPolicy: \"all\",\n    headers: {\n      ...CTW_REQUEST_HEADER,\n      authorization: `Bearer ${requestContext.authToken}`,\n    },\n  });\n};\n\nexport const fqsRequest = async <T>(client: GraphQLClient, query: string, variables: object) => {\n  const updatedVariables = { ...variables };\n  if (\n    \"first\" in updatedVariables &&\n    typeof updatedVariables.first === \"number\" &&\n    updatedVariables.first > MAX_OBJECTS_PER_REQUEST\n  ) {\n    updatedVariables.first = MAX_OBJECTS_PER_REQUEST;\n  }\n\n  const { data, errors } = await client.rawRequest<T>(query, updatedVariables as Variables);\n  const fhirData = graphQLToFHIR(data);\n  if (errors) {\n    errors.forEach((e) => {\n      Telemetry.logger.error(\"Error in FQS request\", undefined, e);\n    });\n\n    if (isEmptyValue(data)) {\n      throw errors;\n    }\n\n    return { data: fhirData };\n  }\n  return { data: fhirData };\n};\n\nexport function getFetchFromFqs(env: Env, accessToken: string) {\n  return (url: string, options: RequestInit) =>\n    ctwFetch(`${getZusServiceUrl(env, \"fqs\")}/${url}`, {\n      ...options,\n      headers: {\n        Authorization: `Bearer ${accessToken}`,\n        ...options.headers,\n      } as Record<string, string>,\n    });\n}\n\nexport function getResourceNodes<T extends ResourceTypeString>(\n  response: object,\n): ResourceType<T>[] {\n  const values = Object.values(response) as GenericConnection<T>[];\n\n  return values.map((x) => x.edges.map((y) => y.node)).flat();\n}\n\nexport function getHistoryResources<T extends ResourceTypeString>(\n  response: object,\n): ResourceType<T>[] {\n  const values = Object.values(response);\n\n  return values.flat();\n}\n","import { useCallback, useContext, useEffect, useRef } from \"react\";\nimport { useGetAuthToken } from \"./authentication/use-get-auth-token\";\nimport { CTWRequestContext, CTWStateContext } from \"./ctw-context\";\nimport { getFhirClients } from \"@/fhir/client\";\nimport { getFetchFromFqs } from \"@/services/fqs/client\";\nimport { claimsBuilderId, claimsUserType } from \"@/utils/auth\";\n\nexport function useCTW() {\n  const context = useContext(CTWStateContext);\n  const getAuthToken = useGetAuthToken();\n\n  // Store the contextValue in a ref so it's always up to date\n  const contextValueRef = useRef(context);\n  useEffect(() => {\n    contextValueRef.current = context;\n  }, [context]);\n\n  if (context === undefined) {\n    throw new Error(\"useCTW must be used within a CTWProvider\");\n  }\n\n  const getRequestContext = useCallback(async () => {\n    const authToken = await getAuthToken();\n    const updatedContext = contextValueRef.current || context;\n\n    const { fhirClient, fhirWriteBackClient } = getFhirClients(\n      updatedContext.env,\n      authToken,\n      updatedContext.builderId,\n      updatedContext.resourceSaveHeaders,\n    );\n    const requestContext: CTWRequestContext = {\n      authToken,\n      headers: updatedContext.headers,\n      fhirClient,\n      fhirWriteBackClient,\n      env: updatedContext.env,\n      userType: claimsUserType(authToken) ?? undefined,\n      builderId: updatedContext.builderId ?? claimsBuilderId(authToken) ?? \"\",\n      contextBuilderId: updatedContext.builderId,\n      fetchFromFqs: getFetchFromFqs(updatedContext.env, authToken),\n      onResourceSave: (resource, action, error) => {\n        if (updatedContext.onResourceSave) {\n          updatedContext.onResourceSave(resource, action, error);\n        }\n      },\n    };\n    return requestContext;\n  }, [context, getAuthToken]);\n\n  return {\n    env: context.env,\n    getRequestContext,\n    featureFlags: context.featureFlags,\n    allowSmallBreakpointCCDAViewer: context.allowSmallBreakpointCCDAViewer === true,\n  };\n}\n","import { Reference } from \"fhir/r4\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { claimsAuthEmail, claimsPractitionerId } from \"@/utils/auth\";\n\n// Use their email address as the display if no practitioner reference available.\nexport async function getUsersPractitionerReference(\n  requestContext: CTWRequestContext,\n): Promise<Reference> {\n  const practitionerId = claimsPractitionerId(requestContext.authToken);\n  if (practitionerId) {\n    return {\n      reference: `Practitioner/${practitionerId}`,\n      type: \"Practitioner\",\n    };\n  }\n  return {\n    display: claimsAuthEmail(requestContext.authToken),\n  };\n}\n","export const QUERY_KEY_AI_SEARCH = \"ai_search\";\nexport const QUERY_KEY_AUTH_TOKEN = \"auth_token\";\nexport const QUERY_KEY_BINARY = \"binary\";\nexport const QUERY_KEY_BUILDER_CONFIG = \"builder_config\";\nexport const QUERY_KEY_CARETEAM = \"patient_care_team\";\nexport const QUERY_KEY_ALLERGY_HISTORY = \"allergy_history\";\nexport const QUERY_KEY_CONDITION_HISTORY = \"condition_history\";\nexport const QUERY_KEY_MEDICATION_HISTORY = \"medication_history\";\nexport const QUERY_KEY_PATIENT_SUMMARY_CONDITIONS = \"patient_summary_conditions\";\nexport const QUERY_KEY_DATA_INDICATORS = \"patient_data_indicators\";\nexport const QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS = \"patient_diagnostic_reports\";\nexport const QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS = \"patient_summary_medications\";\nexport const QUERY_KEY_PATIENT = \"patient\";\nexport const QUERY_KEY_PATIENT_ALLERGIES = \"patient_allergies\";\nexport const QUERY_KEY_PATIENT_BUILDER_MEDICATIONS = \"patient_builder_medications\";\nexport const QUERY_KEY_BUILDER_CONDITIONS = \"builder_conditions\";\nexport const QUERY_KEY_PATIENT_DOCUMENTS = \"patient_documents\";\nexport const QUERY_KEY_PATIENT_ENCOUNTERS = \"patient_encounters\";\nexport const QUERY_KEY_PATIENT_EPISODES_OF_CARE = \"patient_episodes_of_care\";\nexport const QUERY_KEY_PATIENT_HISTORY_DETAILS = \"patient_history_details\";\nexport const QUERY_KEY_PATIENT_HISTORY_LIST = \"patient_history_list\";\nexport const QUERY_KEY_PATIENT_IMMUNIZATIONS = \"patient_immunizations\";\nexport const QUERY_KEY_PATIENT_SUBSCRIPTION = \"patient_subscription\";\nexport const QUERY_KEY_PATIENT_VITALS = \"patient_vitals\";\nexport const QUERY_KEY_PATIENTS_LIST_ODS = \"patients_list\";\nexport const QUERY_KEY_PATIENTS_LIST_FQS = \"patients_list_fqs\";\nexport const QUERY_KEY_PROVENANCE = \"provenance\";\nexport const QUERY_KEY_PATIENT_MEDICATION_DISPENSE = \"patient_medication_dispense\";\nexport const QUERY_KEY_MATCHED_PATIENTS = \"matched_patients\";\nexport const QUERY_KEY_BUILDER_PATIENTS_BY_UPID = \"builder_patients_by_upid\";\n","import { Provenance } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { createGraphqlClient } from \"../client\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { ResourceTypeString } from \"@/fhir/types\";\nimport { QUERY_KEY_PROVENANCE } from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\n\nexport async function searchProvenancesFQS(\n  requestContext: CTWRequestContext,\n  resourceType: ResourceTypeString,\n  targets: string[]\n) {\n  const targetIds = targets.map((target) => target.replace(`${resourceType}/`, \"\"));\n  const graphClient = createGraphqlClient(requestContext);\n\n  return queryClient.fetchQuery([QUERY_KEY_PROVENANCE, resourceType, targetIds], async () => {\n    const data = (await graphClient.request(\n      provenanceQueries(resourceType, targetIds)\n    )) as ProvenanceResponse;\n\n    return Object.values(data).reduce((acc, val) => {\n      acc.push(...val.ProvenanceList);\n      return acc;\n    }, [] as Provenance[]);\n  });\n}\n\ntype ProvenanceResponse = {\n  [key: string]: {\n    ProvenanceList: Provenance[];\n  };\n};\n\nfunction provenanceQueries(resourceType: ResourceTypeString, targetIds: string[]) {\n  return gql`\n    query GetProvenances() {\n      ${targetIds.map((id, index) => provenanceQuery(resourceType, id, index)).join(\"\\n\")}\n    }\n  `;\n}\n\nfunction provenanceQuery(resourceType: ResourceTypeString, targetId: string, index: number) {\n  return `\n    provenance${index}: ${resourceType}(id: \"${targetId}\") {\n      ProvenanceList(_reference: \"target\") {\n        id\n        meta {\n          tag {\n            system\n            code\n          }\n        }\n        target {\n          reference\n        }\n        entity {\n          role\n          what {\n            reference\n          }\n        }\n      }\n    }\n  `;\n}\n","import { Provenance, Resource } from \"fhir/r4\";\nimport { FHIRModel } from \"./models/fhir-model\";\nimport { getUsersPractitionerReference } from \"./practitioner\";\nimport { SYSTEM_PROVENANCE_ACTIVITY_TYPE, SYSTEM_PROVENANCE_AGENT_TYPE } from \"./system-urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { searchProvenancesFQS } from \"@/services/fqs/queries/provenances\";\nimport { claimsBuilderName } from \"@/utils/auth\";\nimport { uniq } from \"@/utils/nodash\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nconst ASSEMBLER_CODING = {\n  system: SYSTEM_PROVENANCE_AGENT_TYPE,\n  code: \"assembler\",\n  display: \"Assembler\",\n};\n\nconst CREATE_CODING = {\n  coding: [\n    {\n      system: SYSTEM_PROVENANCE_ACTIVITY_TYPE,\n      code: \"CREATE\",\n      display: \"create\",\n    },\n  ],\n};\n\nconst UPDATE_CODING = {\n  coding: [\n    {\n      system: SYSTEM_PROVENANCE_ACTIVITY_TYPE,\n      code: \"UPDATE\",\n      display: \"revise\",\n    },\n  ],\n};\n\nexport const createProvenance = async (\n  type: \"CREATE\" | \"UPDATE\",\n  resource: Resource,\n  requestContext: CTWRequestContext,\n) => {\n  const { fhirClient } = requestContext;\n  const builderName = claimsBuilderName(requestContext.authToken);\n  const versionId = parseInt(resource.meta?.versionId || \"0\", 10);\n\n  const provenance: Provenance = {\n    resourceType: \"Provenance\",\n    activity: type === \"CREATE\" ? CREATE_CODING : UPDATE_CODING,\n    agent: [\n      {\n        who: await getUsersPractitionerReference(requestContext),\n        onBehalfOf: { display: builderName },\n      },\n      {\n        type: {\n          coding: [ASSEMBLER_CODING],\n        },\n        who: { display: \"Zus Health\" },\n      },\n    ],\n    recorded: new Date().toISOString(),\n    target: [\n      {\n        reference: `${resource.resourceType}/${resource.id}/_history/${versionId}`,\n        type: resource.resourceType,\n      },\n    ],\n  };\n  try {\n    const response = fhirClient.create({\n      resourceType: \"Provenance\",\n      body: provenance,\n    });\n    Telemetry.reportActionSuccess(`${resource.resourceType}.provenance`);\n    return response;\n  } catch (e) {\n    Telemetry.reportActionFailure(`${resource.resourceType}.provenance`);\n    throw e;\n  }\n};\n\nexport async function searchProvenances<T extends fhir4.Resource>(\n  requestContext: CTWRequestContext,\n  models: FHIRModel<T>[],\n): Promise<Provenance[]> {\n  if (models.length === 0) return [];\n\n  const targets = uniq(models.map((m) => `${m.resourceType}/${m.id}`));\n\n  // Builder-scoped queries will fix the issue of FQS not supporting Practitioner provenance search.\n  if (models[0].resourceType === \"Practitioner\") {\n    return [];\n  }\n\n  return searchProvenancesFQS(requestContext, models[0].resourceType, targets);\n}\n\nexport function getBinaryIDFromProvenance(provenance?: fhir4.Provenance[]) {\n  if (provenance && provenance.length > 0) {\n    let binaryIDReference = \"\";\n    for (let i = 0; i < provenance.length; i += 1) {\n      const entity = provenance[i].entity?.find((e) => e.what.reference !== undefined);\n      if (entity && entity.what.reference) {\n        binaryIDReference = entity.what.reference;\n        break;\n      }\n    }\n    if (binaryIDReference) {\n      return binaryIDReference.split(\"/\")[1];\n    }\n  }\n  return undefined;\n}\n","export const sleep = (ms: number) =>\n  new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n","/* eslint-disable no-await-in-loop */\nimport { createGraphqlClient } from \"./client\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { get } from \"@/utils/nodash\";\nimport { sleep } from \"@/utils/sleep\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\n// We'll keep retrying until we've gone over our timeout.\nconst TIMEOUT_MS = 20_000;\n\n// Due to mutations going to ODS, there is a delay\n// before FQS has the latest fresh resource.\n// This function will poll FQS until the resource.meta.lastUpdated timestamp\n// is greater or equal to the provided lastUpdated timestamp.\nexport async function longPollFQS(\n  requestContext: CTWRequestContext,\n  resourceType: string,\n  resourceId: string,\n  lastUpdated: string,\n): Promise<boolean> {\n  const graphClient = createGraphqlClient(requestContext);\n  const query = `query GetLastUpdated {\n      ${resourceType}(id: \"${resourceId}\") {\n        meta {\n          lastUpdated\n        }\n      }\n    }`;\n\n  const targetTimestamp = Date.parse(lastUpdated);\n  let retryCount = 0;\n  let currentTimestamp = 0;\n  const startTime = Date.now();\n  do {\n    // Exponential backoff how long we wait between retries.\n    await sleep(100 * 2 ** retryCount);\n    retryCount += 1;\n    // Refetch the resource from FQS.\n    try {\n      const data = await graphClient.request(query);\n      currentTimestamp = Date.parse(String(get(data, `${resourceType}.meta.lastUpdated`)));\n    } catch {\n      // Ignore errors and retry.\n      // This can happen if we just created a new resource that isn't in FQS yet.\n    }\n  } while (\n    (Number.isNaN(currentTimestamp) || currentTimestamp < targetTimestamp) &&\n    Date.now() - startTime < TIMEOUT_MS\n  );\n\n  Telemetry.histogramMetric(`fqs.longpoll.all`, Date.now() - startTime);\n  Telemetry.histogramMetric(`fqs.longpoll.${resourceType}`, Date.now() - startTime);\n  return currentTimestamp >= targetTimestamp;\n}\n","import { Resource } from \"fhir/r4\";\nimport { fixupFHIR } from \"./client\";\nimport { isFhirError } from \"./errors\";\nimport { createProvenance } from \"./provenance\";\nimport { isFHIRDomainResource } from \"./types\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { notify } from \"@/components/core/toast\";\nimport { longPollFQS } from \"@/services/fqs/long-poll-fqs\";\nimport { cloneDeep } from \"@/utils/nodash\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\ntype ResourceSaveOperation = \"update\" | \"create\";\nexport type OnResourceSaveCallback = (\n  resource: Resource,\n  action: ResourceSaveOperation,\n  error?: Error,\n) => void;\n\nexport async function createOrEditFhirResource(\n  resource: Resource,\n  requestContext: CTWRequestContext,\n  title: string = resource.resourceType,\n) {\n  const updating = !!resource.id;\n  const { fhirClient, fhirWriteBackClient } = requestContext;\n  const resourceModified = cloneDeep(resource); // Clone to not modify the original resource.\n  let action: ResourceSaveOperation = \"create\";\n  let response: Resource | undefined;\n\n  try {\n    if (updating) {\n      action = \"update\";\n      // Use the ODS client to update a resource\n      response = await fhirClient.update({\n        resourceType: resource.resourceType,\n        id: resource.id,\n        body: fixupFHIR(resource),\n      });\n      if (!isFhirError(response)) {\n        await createProvenance(\"UPDATE\", response, requestContext);\n      }\n    } else {\n      // Utilize the FHIR write-back client for creating resources\n      response = await fhirWriteBackClient.create({\n        resourceType: resource.resourceType,\n        body: fixupFHIR(resource),\n      });\n      await createProvenance(\"CREATE\", response, requestContext);\n\n      if (!isFhirError(response)) {\n        resourceModified.id = response.id;\n      }\n    }\n    Telemetry.reportActionSuccess(`${resource.resourceType}.${action}`);\n    requestContext.onResourceSave(resourceModified, action);\n\n    // Read-Your-Writes!\n    // Wait for FQS to have the latest version of the resource.\n    // This way callers can safely refetch/invalidateQueries\n    // and be sure to get fresh data from FQS.\n    if (\n      resource.resourceType !== \"Basic\" &&\n      isFHIRDomainResource(response) &&\n      response.id &&\n      response.meta?.lastUpdated\n    ) {\n      await longPollFQS(\n        requestContext,\n        resource.resourceType,\n        response.id,\n        response.meta.lastUpdated,\n      );\n    }\n\n    return response;\n  } catch (e) {\n    Telemetry.reportActionFailure(`${resource.resourceType}.${action}`);\n    Telemetry.logError(e as Error);\n    requestContext.onResourceSave(resourceModified, action, e as Error);\n\n    if (updating) {\n      notify({\n        type: \"error\",\n        title: `Unable to update ${title}.`,\n        body: \"Please update it manually.\",\n      });\n    } else {\n      notify({\n        type: \"error\",\n        title: `Unable to import ${title} to chart.`,\n        body: \"Please add it manually. Dismiss it to no longer see it in this list.\",\n      });\n    }\n    return e;\n  }\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { formatPhoneNumber } from \"../formatters\";\n\nexport class OrganizationModel extends FHIRModel<fhir4.Organization> {\n  kind = \"Organization\" as const;\n\n  get name(): string | undefined {\n    return this.resource.name;\n  }\n\n  get phone(): string | undefined {\n    const phone = this.resource.telecom?.find((t) => t.system === \"phone\");\n    return formatPhoneNumber(phone?.value);\n  }\n\n  get title() {\n    return this.name ?? \"Unknown Organization\";\n  }\n}\n","import type { ResourceMap, ResourceType, ResourceTypeString, Tag } from \"./types\";\nimport { find } from \"@/utils/nodash\";\n\nexport type Fhir4Reference = fhir4.Reference & { resource?: fhir4.FhirResource };\n\n// Returns the referenced resource if there is one.\n// Checks both the contained resources AND any included resources map.\n// NOTE: Throws error if reference exists but we couldn't find it!\n//       See throw note below for details.\nexport function findReference<T extends ResourceTypeString>(\n  resourceType: T,\n  contained: fhir4.FhirResource[] | undefined,\n  includedResources: ResourceMap | undefined,\n  reference: Fhir4Reference | undefined,\n): ResourceType<T> | undefined {\n  if (!reference) {\n    return undefined;\n  }\n\n  if (reference.resource) {\n    return reference.resource as ResourceType<T>;\n  }\n\n  if (reference.reference?.startsWith(\"#\")) {\n    // TODO: Remove this once we no longer support ODS, as this format is specific to ODS/FHIR.\n    let found = find(contained, {\n      id: reference.reference.substring(1), // Remove preceding # when looking up contained resource.\n      resourceType,\n    }) as ResourceType<T> | undefined;\n    if (found) {\n      return found;\n    }\n\n    // FQS returns contained resources nested another level deep (e.g. as {resource: {}} vs just {}),\n    // so we need to look there for contained values.\n    found = find(contained, {\n      resource: {\n        id: reference.reference.substring(1), // Remove preceding # when looking up contained resource.\n        resourceType,\n      },\n    }) as ResourceType<T> | undefined;\n    if (found) {\n      // @ts-ignore: We need to return the unnested resource here vs the nested one.\n      return found.resource;\n    }\n    return undefined;\n  }\n\n  if (\n    reference.reference &&\n    includedResources?.[reference.reference]?.resourceType === resourceType\n  ) {\n    return includedResources[reference.reference] as ResourceType<T>;\n  }\n\n  // TIP: Are you missing a _include or _include:iterate in\n  //      the FHIR request!?\n  // Calling `findReference` implies we are intending to be able\n  // to find the reference and use it. The only reason why this\n  // wouldn't work for an existing reference is if we forgot\n  // to do a _include or _include:iterate!\n  // NOTE: It's also possible that we cannot find a reference\n  // because user does not have permission to it. This can happen\n  // in CPR where user can see a resource but not one of its references.\n  return undefined;\n}\n\nexport function referenceToId(reference?: string) {\n  return reference ? reference.split(\"/\").pop() : undefined;\n}\n\n// Returns resources that match ALL of the provided tags.\nexport function filterByTags<T extends fhir4.FhirResource>(resources: T[], tags?: Tag[]): T[] {\n  if (!tags) {\n    return resources;\n  }\n\n  return resources.filter((resource) =>\n    tags.every(\n      (tag) =>\n        resource.meta?.tag?.some(\n          (resourceTag) => resourceTag.system === tag.system && resourceTag.code === tag.code,\n        ),\n    ),\n  );\n}\n","import { differenceInYears, parseISO } from \"date-fns\";\nimport fhir4 from \"fhir/r4\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { OrganizationModel } from \"./organization\";\nimport { formatDateISOToLocal, formatPhoneNumber } from \"../formatters\";\nimport { SYSTEM_ZUS_UNIVERSAL_ID } from \"../system-urls\";\nimport { findReference } from \"@/fhir/resource-helper\";\nimport { cloneDeep, find } from \"@/utils/nodash\";\n\nexport const MaritalStatuses = [\n  { text: \"Annulled\", code: \"A\" },\n  { text: \"Divorced\", code: \"D\" },\n  { text: \"Interlocutory\", code: \"I\" },\n  { text: \"Legally Separated\", code: \"L\" },\n  { text: \"Married\", code: \"M\" },\n  { text: \"Polygamous\", code: \"P\" },\n  { text: \"Never Married\", code: \"S\" },\n  { text: \"Domestic Partner\", code: \"T\" },\n  { text: \"unmarried\", code: \"U\" },\n  { text: \"Widowed\", code: \"W\" },\n] as const;\n\nexport class PatientModel extends FHIRModel<fhir4.Patient> {\n  kind = \"Patient\" as const;\n\n  get active(): boolean | undefined {\n    return this.resource.active;\n  }\n\n  get contact(): fhir4.PatientContact[] | undefined {\n    return this.resource.contact;\n  }\n\n  get dob(): string | undefined {\n    return formatDateISOToLocal(this.resource.birthDate);\n  }\n\n  get age(): number | undefined {\n    if (!this.resource.birthDate) return undefined;\n\n    const date = parseISO(this.resource.birthDate);\n    return differenceInYears(new Date(), date);\n  }\n\n  findIdentifier(system?: string): string | undefined {\n    if (!system) return undefined;\n    return find(this.resource.identifier, { system })?.value;\n  }\n\n  get gender(): string | undefined {\n    return this.resource.gender;\n  }\n\n  get maritalStatus(): string | undefined {\n    // The code is the source of truth, look up the code\n    // in our list of statuses and return the text.\n    const code = this.resource.maritalStatus?.coding?.[0]?.code;\n    const status = MaritalStatuses.find((s) => s.code === code);\n    return status?.text;\n  }\n\n  get organization(): OrganizationModel | undefined {\n    const reference = findReference(\n      \"Organization\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.managingOrganization,\n    );\n\n    if (reference) {\n      return new OrganizationModel(reference, this.includedResources);\n    }\n\n    return undefined;\n  }\n\n  get organizationDisplayName(): string | undefined {\n    if (this.organization) {\n      return this.organization.name;\n    }\n    return this.thirdPartyDataSourceName;\n  }\n\n  get use(): fhir4.HumanName[\"use\"] | undefined {\n    return this.bestName.use;\n  }\n\n  get officialOrUsualIdentifier(): string {\n    return (\n      find(this.resource.identifier, { use: \"official\" })?.value ||\n      find(this.resource.identifier, { use: \"usual\" })?.value ||\n      \"\"\n    );\n  }\n\n  get UPID(): string | undefined {\n    return find(this.resource.identifier, {\n      system: SYSTEM_ZUS_UNIVERSAL_ID,\n    })?.value;\n  }\n\n  getPhoneNumber(use?: fhir4.ContactPoint[\"use\"]): string | undefined {\n    const predicate: fhir4.ContactPoint = { system: \"phone\" };\n    if (use) {\n      predicate.use = use;\n    }\n    const telecom = find(this.resource.telecom, predicate);\n    return formatPhoneNumber(telecom?.value);\n  }\n\n  // Gets first \"phone\" telecom.\n  get phoneNumber(): string | undefined {\n    return this.getPhoneNumber();\n  }\n\n  get email(): string | undefined {\n    return find(this.resource.telecom, { system: \"email\" })?.value;\n  }\n\n  /*\n    ADDRESS STUFF\n  */\n\n  private get bestHomeAddress(): fhir4.Address | undefined {\n    return (\n      find(this.resource.address, { use: \"home\" }) ||\n      find(this.resource.address, (address) => !address.use) // use is undefined\n    );\n  }\n\n  // Returns first home address or first address without \"use\" set.\n  // This way we return a home address if there is one, or another address\n  // but making sure not to return a work address here.\n  get homeAddress(): fhir4.Address | undefined {\n    // Clone the address so that consumers cannot modify our resource.\n    return cloneDeep(this.bestHomeAddress);\n  }\n\n  /*\n    NAME STUFF\n  */\n  // Returns the best name to use for this patient.\n  // Priority is \"official\", then \"usual\", then first name provided.\n  private get bestName(): fhir4.HumanName {\n    // If patient has ZERO names, then add one!\n    if (!this.resource.name || this.resource.name.length === 0) {\n      this.resource.name = [{ use: \"official\" }];\n    }\n\n    return (\n      find(this.resource.name, { use: \"official\" }) ||\n      find(this.resource.name, { use: \"usual\" }) ||\n      this.resource.name[0] || // We'll always have at least one!\n      {} // Make TypeScript happy.\n    );\n  }\n\n  get additionalNames(): string | undefined {\n    if (this.bestName.given && this.bestName.given.length > 1) {\n      const [, ...rest] = this.bestName.given;\n      return rest.join(\" \");\n    }\n    return undefined;\n  }\n\n  // Returns \"First Last\" which is similar to a reference display.\n  get display(): string {\n    return [this.firstName, this.lastName].filter((name) => name).join(\" \");\n  }\n\n  get firstName(): string {\n    return this.bestName.given?.[0] || \"\";\n  }\n\n  // Returns \"Last, First\" or just \"First\" or just \"Last\" or \"\" when\n  // neither are available.\n  get fullName(): string {\n    return [this.lastName, this.firstName].filter((name) => name).join(\", \");\n  }\n\n  get lastName(): string | undefined {\n    return this.bestName.family;\n  }\n\n  get nickname(): string | undefined {\n    const name = find(this.resource.name, { use: \"nickname\" });\n    return name?.given?.join(\" \");\n  }\n\n  get prefix(): string | undefined {\n    return this.bestName.prefix?.join(\" \");\n  }\n\n  get suffix(): string | undefined {\n    return this.bestName.suffix?.join(\" \");\n  }\n\n  get isTestPatient(): boolean {\n    // no security tags means not a test patient\n    if (!this.resource.meta || !this.resource.meta.security) {\n      return false;\n    }\n\n    return (\n      this.resource.meta.security.filter(\n        (secTag) =>\n          secTag.system === \"http://terminology.hl7.org/CodeSystem/v3-ActReason\" &&\n          secTag.code === \"HTEST\",\n      ).length > 0\n    );\n  }\n\n  get title() {\n    return this.display;\n  }\n}\n","import { formatAge, formatDateISOToLocal, maybeFormatDateStringToLocal } from \"./formatters\";\n\nexport function displayOnset(\n  resource: fhir4.Condition | fhir4.AllergyIntolerance\n): string | undefined {\n  if (resource.onsetAge) {\n    return formatAge(resource.onsetAge);\n  }\n\n  if (resource.onsetDateTime) {\n    return formatDateISOToLocal(resource.onsetDateTime);\n  }\n\n  if (resource.onsetPeriod) {\n    return formatDateISOToLocal(resource.onsetPeriod.start);\n  }\n\n  if (resource.onsetRange) {\n    return formatDateISOToLocal(resource.onsetRange.low?.value?.toString());\n  }\n\n  return maybeFormatDateStringToLocal(resource.onsetString);\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { findReference } from \"../resource-helper\";\nimport { SYSTEM_NDC, SYSTEM_RXNORM, SYSTEM_SNOMED } from \"../system-urls\";\nimport { codeableConceptLabel, CodePreference, findCoding } from \"@/fhir/codeable-concept\";\nimport { displayOnset } from \"@/fhir/display-onset\";\nimport { capitalize, compact, uniqWith } from \"@/utils/nodash\";\n\nexport class AllergyModel extends FHIRModel<fhir4.AllergyIntolerance> {\n  kind = \"Allergy\" as const;\n\n  get categories(): string | undefined {\n    return this.resource.category?.join(\", \");\n  }\n\n  get codeText(): string | undefined {\n    return this.resource.code?.text;\n  }\n\n  get resourceTypeTitle(): string {\n    return this.resource.resourceType.slice(0, 7);\n  }\n\n  get clinicalStatus(): string {\n    return codeableConceptLabel(this.resource.clinicalStatus);\n  }\n\n  get display(): string | undefined {\n    return capitalize(codeableConceptLabel(this.resource.code));\n  }\n\n  get lowercaseDisplay(): string {\n    return this.display?.toLocaleLowerCase() || \"\";\n  }\n\n  get manifestations(): string {\n    const manifestations: string[] = [];\n\n    this.resource.reaction?.forEach((reaction) =>\n      reaction.manifestation.forEach((manifestation) =>\n        manifestations.push(codeableConceptLabel(manifestation)),\n      ),\n    );\n\n    return manifestations.join(\", \");\n  }\n\n  get patientOrganizationName(): string | undefined {\n    const reference = findReference(\n      \"Patient\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.patient,\n    );\n\n    if (reference) {\n      return new PatientModel(reference, this.includedResources).organizationDisplayName;\n    }\n\n    return undefined;\n  }\n\n  get note(): string | undefined {\n    let concatenatedString;\n    if (this.resource.note) {\n      concatenatedString = this.resource.note.map((note) => codeableConceptLabel(note)).join(\", \");\n    }\n\n    return concatenatedString;\n  }\n\n  get severity(): string | undefined {\n    return this.resource.reaction?.[0].severity;\n  }\n\n  get knownCodings(): fhir4.Coding[] {\n    const codings = compact(\n      ALLERGY_CODE_PREFERENCE_ORDER.map((code) => findCoding(code.system, this.resource.code)),\n    );\n\n    return uniqWith(codings, (prev, next) => prev.system === next.system);\n  }\n\n  get onset(): string | undefined {\n    return displayOnset(this.resource);\n  }\n\n  get recordedDate(): string | undefined {\n    return formatDateISOToLocal(this.resource.recordedDate);\n  }\n\n  get title() {\n    return this.display ?? \"Unknown Allergy\";\n  }\n\n  get type(): string {\n    return this.resource.type ?? \"\";\n  }\n}\n\nconst ALLERGY_CODE_PREFERENCE_ORDER: CodePreference[] = [\n  { system: SYSTEM_RXNORM },\n  { system: SYSTEM_NDC },\n  { system: SYSTEM_SNOMED },\n];\n","import { FHIRModel } from \"./fhir-model\";\n\nexport class PractitionerModel extends FHIRModel<fhir4.Practitioner> {\n  kind = \"Practitioner\" as const;\n\n  get fullName(): string {\n    const firstEntryInName = this.resource.name?.[0];\n    const givenName = firstEntryInName?.given?.length ? firstEntryInName.given[0] : \"\";\n\n    return [givenName, firstEntryInName?.family].filter((n) => n).join(\" \");\n  }\n\n  get title() {\n    return this.fullName;\n  }\n}\n","type CCSChapterNameMapType = Record<string, { fullName: string; shortName: string } | undefined>;\n\nexport const CCSChapterName: CCSChapterNameMapType = {\n  INF: {\n    fullName: \"Certain Infectious and Parasitic Diseases\",\n    shortName: \"Infectious and Parasitic Diseases\",\n  },\n  NEO: { fullName: \"Neoplasms\", shortName: \"Neoplasms\" },\n  BLD: {\n    fullName:\n      \"Diseases of the Blood and Blood Forming Organs and Certain Disorders Involving the Immune Mechanism\",\n    shortName: \"Blood Diseases\",\n  },\n  END: {\n    fullName: \"Endocrine, Nutritional and Metabolic Diseases\",\n    shortName: \"Endocrine, Nutritional and Metabolic\",\n  },\n  MBD: {\n    fullName: \"Mental, Behavioral and Neurodevelopmental Disorders\",\n    shortName: \"Mental and Behavioral\",\n  },\n  NVS: {\n    fullName: \"Diseases of the Nervous System\",\n    shortName: \"Nervous System\",\n  },\n  EYE: {\n    fullName: \"Diseases of the Eye and Adnexa\",\n    shortName: \"Eye and Adnexa\",\n  },\n  EAR: {\n    fullName: \"Diseases of the Ear and Mastoid Process\",\n    shortName: \"Ear and Mastoid Process\",\n  },\n  CIR: {\n    fullName: \"Diseases of the Circulatory System\",\n    shortName: \"Circulatory System\",\n  },\n  RSP: {\n    fullName: \"Diseases of the Respiratory System\",\n    shortName: \"Respiratory System\",\n  },\n  DIG: {\n    fullName: \"Diseases of the Digestive System\",\n    shortName: \"Digestive System\",\n  },\n  SKN: {\n    fullName: \"Diseases of the Skin and Subcutaneous Tissue\",\n    shortName: \"Skin and Subcutaneous Tissue\",\n  },\n  MUS: {\n    fullName: \"Diseases of the Musculoskeletal System and Connective Tissue\",\n    shortName: \"Musculoskeletal System\",\n  },\n  GEN: {\n    fullName: \"Diseases of the Genitourinary System\",\n    shortName: \"Genitourinary System\",\n  },\n  PRG: {\n    fullName: \"Pregnancy, Childbirth and the Puerperium\",\n    shortName: \"Pregnancy & Childbirth\",\n  },\n  PNL: {\n    fullName: \"Certain Conditions Originating in the Perinatal Period\",\n    shortName: \"Perinatal Conditions\",\n  },\n  MAL: {\n    fullName: \"Congenital Malformations, Deformations and Chromosomal Abnormalities\",\n    shortName: \"Malformations and Chromosomal Abnormalities\",\n  },\n  SYM: {\n    fullName: \"Symptoms, Signs and Abnormal Clinical and Laboratory Findings\",\n    shortName: \"Clinical Findings\",\n  },\n  INJ: {\n    fullName: \"Injury, Poisoning and Certain Other Consequences of External Causes\",\n    shortName: \"External Causes Injury\",\n  },\n  EXT: {\n    fullName: \"External Causes of Morbidity\",\n    shortName: \"External Morbidity\",\n  },\n  FAC: {\n    fullName: \"Factors Influencing Health Status and Contact with Health Services\",\n    shortName: \"Health Status Influences\",\n  },\n  XXX: {\n    fullName:\n      \"Unacceptable principal diagnosis (inpatient data) or first-listed diagnosis (outpatient data)\",\n    shortName: \"Unacceptable principal diagnosis\",\n  },\n};\n","import { Condition } from \"fhir/r4\";\nimport { ConditionStatus, ConditionType } from \"../types\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { notify } from \"@/components/core/toast\";\nimport { createOrEditFhirResource } from \"@/fhir/action-helper\";\nimport { dateToISO } from \"@/fhir/formatters\";\nimport { ConditionModel } from \"@/fhir/models/condition\";\nimport { getUsersPractitionerReference } from \"@/fhir/practitioner\";\nimport {\n  SYSTEM_CCI,\n  SYSTEM_CONDITION_CATEGORY,\n  SYSTEM_CONDITION_CLINICAL,\n  SYSTEM_CONDITION_VERIFICATION_STATUS,\n} from \"@/fhir/system-urls\";\nimport { isFHIRResource } from \"@/fhir/types\";\nimport { cloneDeep, isUndefined, omitBy } from \"@/utils/nodash\";\nimport {\n  QUERY_KEY_BUILDER_CONDITIONS,\n  QUERY_KEY_PATIENT_SUMMARY_CONDITIONS,\n} from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\n\n// Sets any autofill values that apply when a user adds a condition, whether creating or confirming.\nexport function getAddConditionWithDefaults(condition: Condition): Condition {\n  return cloneDeep(condition);\n}\n\nexport const getClincalAndVerificationStatus = (status: ConditionStatus) => {\n  let verificationStatus = \"\";\n  let clinicalStatus = \"\";\n\n  switch (status) {\n    case \"Active\":\n      verificationStatus = \"confirmed\";\n      clinicalStatus = \"active\";\n      break;\n    case \"Inactive\":\n      verificationStatus = \"confirmed\";\n      clinicalStatus = \"inactive\";\n      break;\n    case \"Pending\":\n      verificationStatus = \"unconfirmed\";\n      clinicalStatus = \"active\";\n      break;\n    case \"Refuted\":\n      verificationStatus = \"refuted\";\n      clinicalStatus = \"inactive\";\n      break;\n    case \"Entered In Error\":\n      verificationStatus = \"entered-in-error\";\n      break;\n    default:\n      throw Error(\"status is should be of type ConditionStatus\");\n  }\n\n  return omitBy(\n    {\n      verificationStatus: {\n        coding: [\n          {\n            system: SYSTEM_CONDITION_VERIFICATION_STATUS,\n            code: verificationStatus,\n          },\n        ],\n      },\n      ...(clinicalStatus && {\n        clinicalStatus: {\n          coding: [{ system: SYSTEM_CONDITION_CLINICAL, code: clinicalStatus }],\n        },\n      }),\n    },\n    isUndefined,\n  );\n};\n\nexport const createOrEditCondition = async (\n  condition: ConditionModel | undefined,\n  patientID: string,\n  data: CreateOrEditConditionFormData,\n  getRequestContext: () => Promise<CTWRequestContext>,\n): Promise<unknown> => {\n  const requestContext = await getRequestContext();\n\n  // Defines the properties of the condition based on the form.\n  // The autofill values that apply to both edits and creates are here; including Practitioner, Recorder, Patient, and Recorded date.\n  const fhirCondition: fhir4.Condition = {\n    resourceType: \"Condition\",\n    id: data.id,\n    recorder: await getUsersPractitionerReference(requestContext),\n    ...getClincalAndVerificationStatus(data.status),\n    // Set category to problem list when creating a condition.\n    category:\n      data.id && condition\n        ? condition.resource.category\n        : [\n            {\n              coding: [\n                {\n                  system: SYSTEM_CONDITION_CATEGORY,\n                  code: \"problem-list-item\",\n                  display: \"Problem List Item\",\n                },\n              ],\n            },\n          ],\n    // Keep all existing codings when editing a condition.\n    code:\n      data.id && condition\n        ? condition.codings\n        : {\n            coding: [\n              {\n                system: data.condition.system,\n                code: data.condition.code,\n                display: data.condition.display,\n              },\n            ],\n            text: data.condition.display,\n          },\n    ...(data.abatement && {\n      abatementDateTime: dateToISO(data.abatement),\n    }),\n    onsetDateTime: dateToISO(data.onset),\n    recordedDate: dateToISO(new Date()),\n    subject: { type: \"Patient\", reference: `Patient/${patientID}` },\n    note: data.note ? [{ text: data.note }] : undefined,\n  };\n\n  if (data.type === \"Chronic\") {\n    fhirCondition.code?.coding?.push({\n      system: SYSTEM_CCI,\n      code: \"C\",\n      display: \"Chronic\",\n    });\n  } else if (data.type === \"Acute\") {\n    fhirCondition.code?.coding?.push({\n      system: SYSTEM_CCI,\n      code: \"A\",\n      display: \"Acute\",\n    });\n  } else if (data.type === \"Chronic and acute\") {\n    fhirCondition.code?.coding?.push({\n      system: SYSTEM_CCI,\n      code: \"B\",\n      display: \"Both\",\n    });\n  }\n\n  const response = await createOrEditFhirResource(\n    fhirCondition,\n    requestContext,\n    new ConditionModel(fhirCondition).title,\n  );\n\n  await Promise.all([\n    queryClient.invalidateQueries([QUERY_KEY_BUILDER_CONDITIONS]),\n    queryClient.invalidateQueries([QUERY_KEY_PATIENT_SUMMARY_CONDITIONS]),\n  ]);\n\n  // When adding a condition to the chart, show success notification.\n  if (!fhirCondition.id && condition && isFHIRResource(response)) {\n    notify({\n      type: \"success\",\n      title: `${condition.title} added to chart.`,\n    });\n  }\n\n  return response;\n};\n\nexport type CreateOrEditConditionFormData = {\n  id?: string;\n  status: ConditionStatus;\n  type: ConditionType;\n  condition: fhir4.Coding;\n  abatement?: Date;\n  onset: Date;\n  note?: string;\n};\n","import { Coding } from \"fhir/r4\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { PractitionerModel } from \"./practitioner\";\nimport { formatDateISOToLocal, formatStringToDate } from \"../formatters\";\nimport { CCSChapterName } from \"../mappings/ccs-chapter-names\";\nimport { findReference } from \"../resource-helper\";\nimport {\n  SYSTEM_CCI,\n  SYSTEM_CCS,\n  SYSTEM_CMS_HCC,\n  SYSTEM_CONDITION_CLINICAL,\n  SYSTEM_CONDITION_VERIFICATION_STATUS,\n  SYSTEM_ICD10,\n  SYSTEM_ICD10_CM,\n  SYSTEM_ICD9,\n  SYSTEM_ICD9_CM,\n  SYSTEM_SNOMED,\n} from \"../system-urls\";\nimport {\n  getAddConditionWithDefaults,\n  getClincalAndVerificationStatus,\n} from \"@/components/content/forms/actions/conditions\";\nimport {\n  codeableConceptLabel,\n  codeableConceptTextOrDisplay,\n  CodePreference,\n  findAllCodingsWithEnrichment,\n  findCoding,\n  findCodingByOrderOfPreference,\n  findCodingWithEnrichment,\n} from \"@/fhir/codeable-concept\";\nimport { capitalize, compact, find, intersectionWith, uniqWith } from \"@/utils/nodash\";\n\ntype VerificationStatus =\n  | \"unconfirmed\"\n  | \"provisional\"\n  | \"differential\"\n  | \"confirmed\"\n  | \"refuted\"\n  | \"entered-in-error\";\n\ntype ClinicalStatus = \"active\" | \"recurrence\" | \"relapse\" | \"inactive\" | \"remission\" | \"resolved\";\n\nconst CONDITION_CODE_PREFERENCE_ORDER: CodePreference[] = [\n  { system: SYSTEM_SNOMED, checkForEnrichment: true },\n  { system: SYSTEM_ICD10, checkForEnrichment: true },\n  { system: SYSTEM_SNOMED },\n  { system: SYSTEM_ICD10 },\n  { system: SYSTEM_ICD10_CM },\n  { system: SYSTEM_ICD9 },\n  { system: SYSTEM_ICD9_CM },\n];\n\nexport function getNewCondition(patientId: string) {\n  const newCondition: fhir4.Condition = {\n    resourceType: \"Condition\",\n    subject: {\n      type: \"Patient\",\n      reference: `Patient/${patientId}`,\n    },\n    ...getClincalAndVerificationStatus(\"Active\"),\n  };\n  return getAddConditionWithDefaults(newCondition);\n}\n\nexport class ConditionModel extends FHIRModel<fhir4.Condition> {\n  kind = \"Condition\" as const;\n\n  // Used by summary conditions to indicate that there's a matching\n  // builder condition for this summary condition.\n  public hasMatchingBuilderConditions = false;\n\n  get abatement(): string | undefined {\n    if (this.resource.abatementAge) {\n      return this.resource.abatementAge.value?.toString();\n    }\n\n    if (this.resource.abatementDateTime) {\n      return formatDateISOToLocal(this.resource.abatementDateTime);\n    }\n\n    if (this.resource.abatementPeriod) {\n      return formatDateISOToLocal(this.resource.abatementPeriod.start);\n    }\n\n    if (this.resource.abatementRange) {\n      return formatDateISOToLocal(this.resource.abatementRange.low?.value?.toString());\n    }\n\n    return this.resource.abatementString;\n  }\n\n  get active(): boolean {\n    const coding = find(this.resource.clinicalStatus?.coding, {\n      system: SYSTEM_CONDITION_CLINICAL,\n    });\n\n    return coding?.code ? [\"active\", \"recurrence\", \"relapse\"].includes(coding.code) : false;\n  }\n\n  get asserter(): string | undefined {\n    return this.resource.asserter?.display;\n  }\n\n  get bodySites(): string[] {\n    return this.resource.bodySite?.map((bodySite) => codeableConceptLabel(bodySite)) || [];\n  }\n\n  // Returns the first category text or display.\n  get category(): string {\n    return (\n      compact(\n        this.resource.category?.map((category) => codeableConceptTextOrDisplay(category)),\n      )[0] ?? \"\"\n    );\n  }\n\n  get ccsChapter(): string | undefined {\n    const code = this.ccsChapterCode;\n    if (!code) return \"Uncategorized\";\n    return CCSChapterName[code]?.shortName;\n  }\n\n  get ccsChapterCode(): string | undefined {\n    return findCoding(SYSTEM_CCS, this.resource.code)?.code?.slice(0, 3);\n  }\n\n  get ccsGrouping(): string | undefined {\n    return findCoding(SYSTEM_CCS, this.resource.code)?.display;\n  }\n\n  get clinicalStatus(): string {\n    return codeableConceptLabel(this.resource.clinicalStatus);\n  }\n\n  get clinicalStatusCode(): ClinicalStatus | undefined {\n    return find(this.resource.clinicalStatus?.coding, {\n      system: SYSTEM_CONDITION_CLINICAL,\n    })?.code as ClinicalStatus | undefined;\n  }\n\n  get codings(): fhir4.CodeableConcept | undefined {\n    return this.resource.code;\n  }\n\n  get chronic(): Coding | undefined {\n    return findCodingWithEnrichment(SYSTEM_CCI, this.resource.code);\n  }\n\n  get display(): string | undefined {\n    return capitalize(\n      findCodingByOrderOfPreference(CONDITION_CODE_PREFERENCE_ORDER, this.resource.code)?.display ??\n        codeableConceptLabel(this.resource.code),\n    );\n  }\n\n  get title() {\n    return this.display ?? \"Condition\";\n  }\n\n  get type() {\n    const type = findCoding(SYSTEM_CCI, this.resource.code)?.display || \"Unknown\";\n    return type.toLocaleLowerCase() === \"both\" ? \"Chronic and acute\" : type;\n  }\n\n  // Standardize the type display as to not end up with so many useless type categories to filter on\n  get typeDisplay() {\n    const type = findCoding(SYSTEM_CCI, this.resource.code);\n    const display = this.type;\n\n    if (\n      [\"UNK\", \"U\", \"NULL\", \"N\"].includes(type?.code ?? \"\") ||\n      /^(not applicable|unknown)/i.test(display)\n    ) {\n      return \"Unknown, not applicable\";\n    }\n\n    return display;\n  }\n\n  get encounter(): string | undefined {\n    return this.resource.encounter?.display;\n  }\n\n  get evidences(): string[] {\n    return (\n      this.resource.evidence?.map((evidence) => codeableConceptLabel(evidence.code?.[0])) || []\n    );\n  }\n\n  get hccEnrichment(): Coding | undefined {\n    return findCodingWithEnrichment(SYSTEM_CMS_HCC, this.resource.code);\n  }\n\n  get hccEnrichments(): Coding[] {\n    return findAllCodingsWithEnrichment(SYSTEM_CMS_HCC, this.resource.code);\n  }\n\n  get icd10CMEnrichments(): Coding[] {\n    return findAllCodingsWithEnrichment(SYSTEM_ICD10_CM, this.resource.code);\n  }\n\n  get icd10Code(): string | undefined {\n    return findCoding(SYSTEM_ICD10, this.resource.code)?.code;\n  }\n\n  get icd10System(): string | undefined {\n    return findCoding(SYSTEM_ICD10, this.resource.code)?.system;\n  }\n\n  get icd10Display(): string | undefined {\n    return findCoding(SYSTEM_ICD10, this.resource.code)?.display;\n  }\n\n  get isDeleted(): boolean {\n    return this.verificationStatusCode === \"entered-in-error\";\n  }\n\n  get knownCodings(): fhir4.Coding[] {\n    const codings = compact(\n      CONDITION_CODE_PREFERENCE_ORDER.map((code) => {\n        if (code.checkForEnrichment) {\n          return findCodingWithEnrichment(code.system, this.resource.code);\n        }\n        return findCoding(code.system, this.resource.code);\n      }),\n    );\n\n    // The order of the array matters here because that is how it determines which record to keep when dupes are found.\n    const dedupedBySystemCoding = uniqWith(codings, (prev, next) => prev.system === next.system);\n    return dedupedBySystemCoding;\n  }\n\n  // Returns true if any of the known codings match between\n  // this condition and the passed in condition.\n  knownCodingsMatch(condition: ConditionModel): boolean {\n    return (\n      intersectionWith(\n        this.knownCodings,\n        condition.knownCodings,\n        (a, b) => a.code === b.code && a.system === b.system,\n      ).length > 0\n    );\n  }\n\n  get notes(): string[] {\n    return this.resource.note?.map((note) => note.text) || [];\n  }\n\n  get onset(): string | undefined {\n    if (this.resource.onsetAge) {\n      return this.resource.onsetAge.value?.toString();\n    }\n\n    if (this.resource.onsetDateTime) {\n      return formatDateISOToLocal(this.resource.onsetDateTime);\n    }\n\n    if (this.resource.onsetPeriod) {\n      return formatDateISOToLocal(this.resource.onsetPeriod.start);\n    }\n\n    if (this.resource.onsetRange) {\n      return formatDateISOToLocal(this.resource.onsetRange.low?.value?.toString());\n    }\n\n    return formatStringToDate(this.resource.onsetString);\n  }\n\n  get patientOrganizationName(): string | undefined {\n    const reference = findReference(\n      \"Patient\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.subject,\n    );\n\n    if (reference) {\n      return new PatientModel(reference, this.includedResources).organizationDisplayName;\n    }\n\n    return undefined;\n  }\n\n  get preferredCoding(): fhir4.Coding | undefined {\n    return findCodingByOrderOfPreference(CONDITION_CODE_PREFERENCE_ORDER, this.resource.code);\n  }\n\n  get recordedDate(): string | undefined {\n    return formatDateISOToLocal(this.resource.recordedDate);\n  }\n\n  get recorded(): string | undefined {\n    return formatDateISOToLocal(this.resource.recordedDate);\n  }\n\n  get recorder(): string | undefined {\n    const reference = this.resource.recorder;\n\n    const practitioner = findReference(\n      \"Practitioner\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n\n    if (practitioner) {\n      return new PractitionerModel(practitioner).fullName;\n    }\n\n    return this.resource.recorder?.display;\n  }\n\n  get severity(): string {\n    return codeableConceptLabel(this.resource.severity);\n  }\n\n  get snomedCoding(): fhir4.Coding | undefined {\n    return findCoding(SYSTEM_SNOMED, this.resource.code);\n  }\n\n  get snomedCode(): string | undefined {\n    return findCoding(SYSTEM_SNOMED, this.resource.code)?.code;\n  }\n\n  get snomedDisplay(): string | undefined {\n    return findCoding(SYSTEM_SNOMED, this.resource.code)?.display;\n  }\n\n  get snomedSystem(): string | undefined {\n    return findCoding(SYSTEM_SNOMED, this.resource.code)?.system;\n  }\n\n  get stages(): string[] {\n    return (\n      this.resource.stage?.map((stage) => {\n        const summary = codeableConceptLabel(stage.summary);\n        const type = codeableConceptLabel(stage.type);\n        return `Summary: ${summary}, Type: ${type}`;\n      }) || []\n    );\n  }\n\n  get displayStatus(): ConditionStatuses {\n    function clinicalStatusMap(code: ClinicalStatus | undefined) {\n      switch (code) {\n        case \"active\":\n        case \"recurrence\":\n        case \"relapse\":\n          return \"Active\";\n        case \"inactive\":\n        case \"remission\":\n        case \"resolved\":\n          return \"Inactive\";\n        default:\n          return \"\";\n      }\n    }\n\n    function verificationStatusMap(code: VerificationStatus | undefined) {\n      switch (code) {\n        case \"confirmed\":\n          return \"confirmed\";\n        case \"unconfirmed\":\n        case \"provisional\":\n        case \"differential\":\n          return \"unconfirmed\";\n        case \"refuted\":\n          return \"refuted\";\n        case \"entered-in-error\":\n          return \"entered-in-error\";\n        default:\n          return \"\";\n      }\n    }\n\n    // What to show if lens or summary resource.\n    if (this.isSummaryResource) {\n      return clinicalStatusMap(this.clinicalStatusCode) || \"Unknown\";\n    }\n\n    const concatenation =\n      verificationStatusMap(this.verificationStatusCode) +\n      clinicalStatusMap(this.clinicalStatusCode).toLowerCase();\n\n    // What to show if patient record resource.\n    switch (concatenation) {\n      case \"unconfirmedactive\":\n        return \"Pending\";\n      case \"unconfirmedinactive\":\n      case \"refutedactive\":\n        return \"Unknown\";\n      case \"confirmedinactive\":\n        return \"Inactive\";\n      case \"confirmedactive\":\n        return \"Active\";\n      case \"refutedinactive\":\n        return \"Refuted\";\n      case \"entered-in-error\":\n        return \"Entered in Error\";\n      default:\n        return \"Unknown\";\n    }\n  }\n\n  get subjectID(): string {\n    const [, subjectID] = this.resource.subject.reference?.split(\"/\") || [];\n    return subjectID || \"\";\n  }\n\n  get verificationStatus(): string {\n    return codeableConceptLabel(this.resource.verificationStatus);\n  }\n\n  get verificationStatusCode(): VerificationStatus | undefined {\n    return find(this.resource.verificationStatus?.coding, {\n      system: SYSTEM_CONDITION_VERIFICATION_STATUS,\n    })?.code as VerificationStatus | undefined;\n  }\n}\n\nexport const conditionStatuses = [\n  \"Active\",\n  \"Inactive\",\n  \"Entered in Error\",\n  \"Pending\",\n  \"Refuted\",\n  \"Unknown\",\n] as const;\n\nexport const outsideConditionStatuses = [\"Active\", \"Inactive\", \"Unknown\"] as const;\n\nexport type ConditionStatuses =\n  | (typeof conditionStatuses)[number]\n  | (typeof outsideConditionStatuses)[number];\n","import { FHIRModel } from \"./fhir-model\";\nimport { formatDateISOToLocal, formatISODateStringToDate } from \"../formatters\";\nimport { findReference } from \"../resource-helper\";\nimport { SYSTEM_LOINC } from \"@/fhir/system-urls\";\nimport { compact } from \"@/utils/nodash\";\n\nconst ZUS_DOCUMENT_SYSTEM_IDS = [\n  \"2.16.840.1.113883.3.3126.2.3.25726.\",\n  \"2.16.840.1.113883.3.9206.2.\",\n];\nexport class DocumentModel extends FHIRModel<fhir4.DocumentReference> {\n  kind = \"Document\" as const;\n\n  get status(): string {\n    return this.resource.status;\n  }\n\n  get binaryId(): string | undefined {\n    const binaryID = this.resource.content[0].attachment.url;\n\n    if (binaryID) {\n      return binaryID.split(\"/\").pop();\n    }\n    return undefined;\n  }\n\n  get contentType(): string | undefined {\n    return this.resource.content[0].attachment.contentType;\n  }\n\n  get docStatus(): string | undefined {\n    return this.resource.docStatus;\n  }\n\n  get category(): fhir4.CodeableConcept[] {\n    return this.resource.category ?? ([] as fhir4.CodeableConcept[]);\n  }\n\n  // eslint-disable-next-line class-methods-use-this\n  get resourceTypeTitle(): string {\n    return \"Document\";\n  }\n\n  get title() {\n    if (this.resource.description) {\n      return this.resource.description;\n    }\n\n    if (this.resource.content.length > 0 && this.resource.content[0].attachment.title) {\n      return this.resource.content[0].attachment.title;\n    }\n\n    return this.loincDisplay || \"Unknown\";\n  }\n\n  get dateCreated(): string | undefined {\n    return formatISODateStringToDate(\n      this.resource.date || this.resource.content[0].attachment.creation,\n    );\n  }\n\n  get isZusDocument(): boolean {\n    return ZUS_DOCUMENT_SYSTEM_IDS.some(\n      (systemId) => this.resource.masterIdentifier?.system?.includes(systemId),\n    );\n  }\n\n  get isClinicalSummary(): boolean {\n    return this.resource.type?.coding?.some((x) => x.code === \"34133-9\") ?? false;\n  }\n\n  get contextPeriodStartDate(): string | undefined {\n    return formatDateISOToLocal(this.resource.context?.period?.start);\n  }\n\n  get contextPeriodEndDate(): string | undefined {\n    return formatDateISOToLocal(this.resource.context?.period?.end);\n  }\n\n  get encounterDate(): string | undefined {\n    if (this.isClinicalSummary) {\n      return undefined;\n    }\n\n    const start = this.contextPeriodStartDate;\n    const end = this.contextPeriodEndDate;\n\n    if (start && end && start !== end) {\n      return `${start} - ${end}`;\n    }\n\n    if (start) {\n      return start;\n    }\n\n    if (end) {\n      return end;\n    }\n\n    return undefined;\n  }\n\n  get custodian(): string | undefined {\n    const organizationName = findReference(\n      \"Organization\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.custodian,\n    )?.name;\n    return this.resource.custodian?.display || organizationName;\n  }\n\n  get loincDisplay(): string | undefined {\n    // Look for a LOINC code on the \"type\" field. It is possible that the LOINC\n    // could be found in the \"category\" list as well (our fhir seeds do this).\n    const codings = compact([this.resource.type, ...this.category]);\n    const loincCoding = codings.find(\n      (codeableConcept) =>\n        codeableConcept.coding?.some((coding) => coding.system === SYSTEM_LOINC && coding.code),\n    );\n    return loincCoding?.coding?.[0]?.display || loincCoding?.text;\n  }\n\n  get text(): string | undefined {\n    return this.resource.text?.div;\n  }\n}\n","import type { DiagnosticReportModel } from \"./diagnostic-report\";\nimport type { TrendDataMap } from \"../data-helper/diagnostic-report-trends\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { getBinaryIDFromProvenance } from \"../provenance\";\nimport { SYSTEM_CPT, SYSTEM_LOINC } from \"../system-urls\";\nimport { ResourceMap } from \"../types\";\nimport { codeableConceptLabel } from \"@/fhir/codeable-concept\";\nimport { formatDateISOToLocal, formatPeriod, formatQuantity, formatRange } from \"@/fhir/formatters\";\nimport { compact, uniq } from \"@/utils/nodash\";\n\nexport const LOINC_ANALYTES: Record<string, string> = {\n  \"17856-6\": \"a1c\",\n  \"2345-7\": \"glucose\",\n  \"4548-4\": \"a1c\",\n  \"4549-2\": \"a1c\",\n  \"18262-6\": \"Cholesterol in LDL [Mass/volume] in Serum or Plasma by Direct assay\",\n  \"13457-7\": \"Cholesterol in LDL [Mass/volume] in Serum or Plasma by Direct assay\",\n  \"2089-1\": \"Cholesterol in LDL [Mass/volume] in Serum or Plasma by Direct assay\",\n  \"39469-2\": \"Cholesterol in LDL [Mass/volume] in Serum or Plasma by Direct assay\",\n  \"46985-8\": \"Cholesterol in LDL [Mass/volume] in Serum or Plasma by Direct assay\",\n  \"2093-3\": \"Cholesterol [Mass/volume] in Serum or Plasma\",\n  \"48620-9\": \"Cholesterol [Mass/volume] in Serum or Plasma\",\n  \"35200-5\": \"Cholesterol [Mass/volume] in Serum or Plasma\",\n  \"2085-9\": \"Cholesterol in HDL [Mass/volume] in Serum or Plasma\",\n  \"2086-7\": \"Cholesterol in HDL [Mass/volume] in Serum or Plasma\",\n  \"49130-8\": \"Cholesterol in HDL [Mass/volume] in Serum or Plasma\",\n  \"9832-7\": \"Cholesterol in HDL [Mass/volume] in Serum or Plasma\",\n  \"2571-8\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"12951-0\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"3043-7\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"14927-8\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"3048-6\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"3049-4\": \"Triglyceride [Mass/volume] in Serum or Plasma\",\n  \"48643-1\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"33914-3\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"77147-7\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"50044-7\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"70969-1\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"48642-3\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"88294-4\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"88293-6\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"62238-1\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"69405-9\":\n    \"Glomerular filtration rate/1.73 sq M.predicted among blacks [Volume Rate/Area] in Serum, Plasma or Blood by Creatinine-based formula (MDRD)\",\n  \"2160-0\": \"Creatinine [Mass/volume] in Serum or Plasma\",\n  \"3094-0\": \"Urea nitrogen [Mass/volume] in Serum or Plasma\",\n  \"2823-3\": \"Potassium [Moles/volume] in Serum or Plasma\",\n  \"19123-9\": \"Magnesium [Mass/volume] in Serum or Plasma\",\n  \"3016-3\": \"Thyrotropin [Units/volume] in Serum or Plasma\",\n  \"11580-8\": \"Thyrotropin [Units/volume] in Serum or Plasma\",\n  \"3024-7\": \"Thyroxine (T4) free [Mass/volume] in Serum or Plasma\",\n  \"3040-3\": \"Lipase [Enzymatic activity/volume] in Serum or Plasma\",\n  \"2777-1\": \"Phosphate [Mass/volume] in Serum or Plasma\",\n  \"10839-9\": \"Troponin I.cardiac [Mass/volume] in Serum or Plasma\",\n};\n\nexport class ObservationModel extends FHIRModel<fhir4.Observation> {\n  kind = \"Observation\" as const;\n\n  public binaryId?: string;\n\n  public diagnosticReport?: DiagnosticReportModel;\n\n  public provenance?: fhir4.Provenance[];\n\n  private trendData?: ObservationModel[];\n\n  constructor(\n    resource: fhir4.Observation,\n    provenance?: fhir4.Provenance[],\n    includedResources?: ResourceMap,\n    basics?: fhir4.Basic[],\n  ) {\n    super(resource, includedResources, basics);\n    this.provenance = provenance;\n    this.binaryId = getBinaryIDFromProvenance(this.provenance);\n  }\n\n  get category() {\n    return codeableConceptLabel(this.resource.category?.[0]);\n  }\n\n  get display() {\n    const filteredCoding = this.resource.code.coding?.find(\n      (coding) => coding.display !== \"unknown\" && coding.display,\n    );\n\n    if (filteredCoding) {\n      return filteredCoding.display || filteredCoding.code;\n    }\n\n    return codeableConceptLabel(this.resource.code);\n  }\n\n  get effectiveStart() {\n    return formatDateISOToLocal(this.effectiveStartRaw);\n  }\n\n  get effectiveStartRaw() {\n    return this.resource.effectivePeriod?.start || this.resource.effectiveDateTime;\n  }\n\n  get identifier() {\n    return this.resource.identifier?.[0].value ?? \"\";\n  }\n\n  get performer() {\n    return this.resource.performer?.[0].display;\n  }\n\n  get value(): string {\n    if (this.resource.valueBoolean !== undefined) {\n      return this.resource.valueBoolean ? \"true\" : \"false\";\n    }\n\n    if (this.resource.valueCodeableConcept) {\n      return codeableConceptLabel(this.resource.valueCodeableConcept);\n    }\n\n    if (this.resource.valueDateTime) {\n      return this.resource.valueDateTime;\n    }\n\n    if (this.resource.valueInteger !== undefined) {\n      return String(this.resource.valueInteger);\n    }\n\n    if (this.resource.valuePeriod) {\n      return formatPeriod(this.resource.valuePeriod);\n    }\n\n    if (this.resource.valueQuantity) {\n      return formatQuantity(this.resource.valueQuantity);\n    }\n\n    if (this.resource.valueRange) {\n      return formatRange(this.resource.valueRange);\n    }\n\n    if (this.resource.valueString) {\n      return this.resource.valueString;\n    }\n\n    if (this.resource.valueTime) {\n      return this.resource.valueTime;\n    }\n\n    return \"\";\n  }\n\n  get unit() {\n    return this.resource.valueQuantity?.unit;\n  }\n\n  get valueString(): string | number | undefined {\n    return this.resource.valueString || this.resource.valueQuantity?.value;\n  }\n\n  get interpretation() {\n    const nonAcceptedValues = [\n      \"n\",\n      \"noinformation\",\n      \"normal\",\n      \"na\",\n      \"(normal)\",\n      \"unknown\",\n      \"not applicable\",\n      \"temporarily unavailable\",\n      \"nml\",\n      \"norm\",\n      \"*\",\n    ];\n\n    const interpretation = codeableConceptLabel(this.resource.interpretation?.[0]).toLowerCase();\n    if (nonAcceptedValues.includes(interpretation)) {\n      return undefined;\n    }\n\n    return interpretation;\n  }\n\n  get notes() {\n    return this.resource.note?.[0].text ?? \"\";\n  }\n\n  get referenceRange() {\n    return this.resource.referenceRange?.[0].text;\n  }\n\n  get trends() {\n    return this.trendData;\n  }\n\n  setTrends(trendDataMap: TrendDataMap) {\n    const analytes = compact(\n      this.resource.code.coding\n        ?.filter((coding) => coding.code && coding.system === SYSTEM_LOINC)\n        .map((coding) => LOINC_ANALYTES[coding.code as string]),\n    );\n\n    this.trendData = compact(uniq(analytes.flatMap((analyte) => trendDataMap[analyte])));\n  }\n\n  get acceptedInterpretations(): string {\n    switch (codeableConceptLabel(this.resource.interpretation?.[0]).toLowerCase()) {\n      case \"high\":\n      case \"low\":\n      case \"hi\":\n      case \"abn\":\n      case \"(high)\":\n      case \"(low)\":\n      case \"abnormal\":\n      case \"a\":\n      case \"l\":\n      case \"h\":\n      case \"above high normal\":\n      case \"crit\":\n      case \"below low normal\":\n      case \"high alert\":\n      case \"(abnormal)\":\n      case \"abnormal alert\":\n      case \"abnormal low\":\n      case \"abnormal high\":\n      case \"low alert\":\n      case \"pos\":\n      case \"no reference range\":\n      case \"positive\":\n      case \"(positive)\":\n      case \"(critical high)\":\n      case \"(critical low)\":\n      case \"critical high\":\n      case \"critical low\":\n      case \"c\":\n        return \"ctw-text-caution-text ctw-bg-caution-light ctw-inline-flex ctw-rounded-xl ctw-font-medium ctw-text-sm ctw-p-1 ctw-px-3\";\n      default:\n        return \"ctw-text-content-black ctw-bg-bg-light ctw-inline-flex ctw-rounded-xl ctw-leading-5 ctw-font-medium ctw-text-sm ctw-p-1 ctw-px-3\";\n    }\n  }\n\n  /**\n   * Return true if the provided diagnostic and trend combination are incorrectly coded,\n   * and therefore should not be displayed in the trends.\n   *\n   * https://zeushealth.atlassian.net/browse/CDEV-310\n   */\n  get isIncorrectlyCodedGlucose() {\n    if (this.diagnosticReport) {\n      const diagnosticFlagged = this.diagnosticReport.resource.code.coding?.some((coding) => {\n        const a1cDisplay = coding.display?.toLowerCase().indexOf(\"a1c\");\n        return (\n          (coding.system === SYSTEM_LOINC && coding.code === \"4548-4\") ||\n          (coding.system === SYSTEM_CPT && coding.code === \"83036\") ||\n          (a1cDisplay !== undefined && a1cDisplay > -1)\n        );\n      });\n      const trendFlagged = this.resource.code.coding?.some(\n        (coding) => coding.system === SYSTEM_LOINC && coding.code === \"2345-7\",\n      );\n      return diagnosticFlagged && trendFlagged;\n    }\n    return false;\n  }\n\n  get title() {\n    return this.display ?? \"Unknown Observation\";\n  }\n}\n","/* eslint-disable no-underscore-dangle */\nimport { Coding, DiagnosticReport, Observation } from \"fhir/r4\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { ObservationModel } from \"./observation\";\nimport { ResourceMap } from \"../types\";\nimport { codeableConceptLabel, findCodingByOrderOfPreference } from \"@/fhir/codeable-concept\";\nimport { formatDateISOToLocal } from \"@/fhir/formatters\";\nimport { findReference } from \"@/fhir/resource-helper\";\nimport { SYSTEM_DIAGNOSTIC_SERVICE_SECTION_ID, SYSTEM_SNOMED } from \"@/fhir/system-urls\";\nimport { find } from \"@/utils/nodash\";\n\nexport class DiagnosticReportModel extends FHIRModel<fhir4.DiagnosticReport> {\n  kind = \"DiagnosticReport\" as const;\n\n  private observationModels: ObservationModel[];\n\n  private _effectiveStart?: string;\n\n  constructor(resource: DiagnosticReport, includedResources?: ResourceMap, basics?: fhir4.Basic[]) {\n    super(resource, includedResources, basics);\n\n    this.observationModels =\n      this.resource.result?.map((result) => {\n        const reference =\n          // @ts-ignore: The FHIR spec doesn't support this customized result field that now has the\n          // observation resource and not only just a reference.\n          result.resource ||\n          findReference(\"Observation\", resource.contained, includedResources, result);\n\n        const model = new ObservationModel(reference);\n        model.diagnosticReport = this;\n\n        return model;\n      }) ?? [];\n  }\n\n  get category() {\n    const category = codeableConceptLabel(this.resource.category?.[0]) || this.reportCategory;\n    if (category) {\n      return category;\n    }\n\n    const label = codeableConceptLabel(this.resource.category?.[0]);\n    return (\n      findReference(\"Observation\", undefined, this.includedResources, this.resource.result?.[0])\n        ?.category ?? `No display value found ${label ? \" for \" : \"\"}${label}`\n    );\n  }\n\n  get coding() {\n    return (\n      standardizedLoincDisplay(this.resource.code.coding) || firstDisplay(this.resource.code.coding)\n    );\n  }\n\n  get displayName() {\n    return (\n      standardizedLoincDisplay(this.resource.code.coding)?.display ||\n      firstDisplay(this.resource.code.coding)?.display ||\n      codeableConceptLabel(this.resource.code)\n    );\n  }\n\n  get effectiveStart() {\n    if (!this._effectiveStart) {\n      this._effectiveStart =\n        formatDateISOToLocal(\n          this.resource.effectivePeriod?.start || this.resource.effectiveDateTime,\n        ) ||\n        inferStartDateFromResults(\n          this.resource.result?.map((ref) =>\n            findReference(\"Observation\", undefined, this.includedResources, ref),\n          ),\n        );\n    }\n\n    return this._effectiveStart;\n  }\n\n  get effectiveEnd() {\n    if (this.resource.effectivePeriod?.end) {\n      return formatDateISOToLocal(this.resource.effectivePeriod.end);\n    }\n    return (\n      this.effectiveStart ||\n      inferEndDateFromResults(\n        this.resource.result?.map((ref) =>\n          findReference(\"Observation\", undefined, this.includedResources, ref),\n        ),\n      ) ||\n      inferStartDateFromResults(\n        this.resource.result?.map((ref) =>\n          findReference(\"Observation\", undefined, this.includedResources, ref),\n        ),\n      )\n    );\n  }\n\n  get identifier() {\n    return this.resource.identifier?.[0].value ?? \"\";\n  }\n\n  get details() {\n    if (!this.results.length) {\n      return \"\";\n    }\n    const tResult = this.results.length > 1 ? \"results\" : \"result\";\n    let display = `${this.results.length} ${tResult}`;\n    if (this.hasTrends) {\n      display += \", result trend available\";\n    }\n    return display;\n  }\n\n  get hasTrends() {\n    return this.observations.some((o) => o.trends && o.trends.length > 1);\n  }\n\n  get performer() {\n    return this.organization?.display || this.resource.performer?.[0].display;\n  }\n\n  get organization() {\n    const performer = this.resource.performer ?? [];\n    return find(performer, { type: \"Organization\" });\n  }\n\n  get reportCategory() {\n    return (\n      findCodingByOrderOfPreference(\n        [{ system: SYSTEM_DIAGNOSTIC_SERVICE_SECTION_ID }, { system: SYSTEM_SNOMED }],\n        this.resource.code,\n      )?.display ?? codeableConceptLabel(this.resource.code)\n    );\n  }\n\n  get results() {\n    return this.resource.result ?? [];\n  }\n\n  get observations() {\n    return this.observationModels;\n  }\n\n  get title() {\n    return this.displayName;\n  }\n}\n\nexport const standardizedLoincDisplay = (coding?: Coding[]) => {\n  if (!coding) {\n    return undefined;\n  }\n\n  return coding.find(\n    (x) =>\n      x.extension &&\n      x.extension.find(\n        (ext) =>\n          ext.valueString === \"LOINC Standardization\" &&\n          ext.url === \"https://zusapi.com/terminology/enrichment\",\n      ) &&\n      x.display &&\n      x.system !== \"http://terminology.hl7.org/CodeSystem/v3-NullFlavor\",\n  );\n};\n\nexport const firstDisplay = (coding?: Coding[]): Coding | undefined => {\n  if (!coding) {\n    return undefined;\n  }\n\n  return (\n    coding\n      // filter out null flavor\n      .filter((x) => x.system !== \"http://terminology.hl7.org/CodeSystem/v3-NullFlavor\")\n      // find the first one that has a truthy display\n      .find((x) => x.display)\n  );\n};\n\nexport const filterOutFalsy = <T>(arr: (T | undefined)[] | undefined): T[] => {\n  if (!arr) {\n    return [];\n  }\n\n  // this makes me sad, but TypeScript isn't smart enough to figure this out\n  return arr.filter((x) => x) as T[];\n};\n\n// go through all possible values, grab the maximum date, or undefined\n// if nothing was found\nexport const inferStartDateFromResults = (results: (Observation | undefined)[] | undefined) =>\n  filterOutFalsy(results)\n    .map(\n      (obs) =>\n        formatDateISOToLocal(obs.effectivePeriod?.start) ||\n        formatDateISOToLocal(obs.effectiveDateTime) ||\n        formatDateISOToLocal(obs.effectiveInstant),\n    )\n    .reduce(\n      (d, min) => {\n        if (!d) {\n          return min;\n        }\n        if (!min) {\n          return d;\n        }\n        return Date.parse(d) < Date.parse(min) ? d : min;\n      },\n      undefined as unknown as string,\n    );\n\n// go through all possible values, grab the maximum date, or undefined\n// if nothing was found\nexport const inferEndDateFromResults = (results: (Observation | undefined)[] | undefined) =>\n  filterOutFalsy(results)\n    .map(\n      (obs) =>\n        formatDateISOToLocal(obs.effectivePeriod?.start) ||\n        formatDateISOToLocal(obs.effectiveDateTime) ||\n        formatDateISOToLocal(obs.effectiveInstant),\n    )\n    .reduce(\n      (d, min) => {\n        if (!d) {\n          return min;\n        }\n        if (!min) {\n          return d;\n        }\n        return Date.parse(d) > Date.parse(min) ? d : min;\n      },\n      undefined as unknown as string,\n    );\n","import type { ResourceMap } from \"./types\";\nimport { findReference } from \"./resource-helper\";\nimport { SYSTEM_ENRICHMENT, SYSTEM_RXNORM } from \"./system-urls\";\nimport { get, sortBy } from \"@/utils/nodash\";\n\nexport type Medication =\n  | fhir4.MedicationStatement\n  | fhir4.MedicationAdministration\n  | fhir4.MedicationRequest\n  | fhir4.MedicationDispense;\n\nexport type ClinicalStatus =\n  | \"active\"\n  | \"entered-in-error\"\n  | \"not-taken\"\n  | \"completed\"\n  | \"on-hold\"\n  | \"intended\"\n  | \"stopped\";\n\n// Hardcoded aliased display statuses for patient-reported statuses.\nconst medStatusDisplays: Record<ClinicalStatus, string> = {\n  active: \"Currently taking\",\n  \"entered-in-error\": \"Never taken\",\n  \"not-taken\": \"Prescribed, not taken\",\n  completed: \"No longer taking\",\n  \"on-hold\": \"On hold\",\n  intended: \"Intend to take\",\n  stopped: \"No longer taking\",\n};\n\n// Medications can have either a medicationCodeableConcept or a\n// medicationReference. This helper grabs the codeable concept\n// from wherever it exists.\nexport function getMedicationCodeableConcept(\n  medication: Medication,\n  includedResources?: ResourceMap\n): fhir4.CodeableConcept | undefined {\n  if (medication.medicationCodeableConcept) {\n    return medication.medicationCodeableConcept;\n  }\n\n  const medicationResource = findReference(\n    \"Medication\",\n    medication.contained,\n    includedResources,\n    medication.medicationReference\n  );\n\n  return medicationResource?.code;\n}\n\n// Returns the best RxNorm code for uniquely identifying a medication.\nexport function getIdentifyingRxNormCode(\n  medication: Medication,\n  includedResources?: ResourceMap\n): string | undefined {\n  return getIdentifyingRxNormCoding(medication, includedResources)?.code;\n}\n\n// Returns the best RxNorm code for uniquely identifying a medication.\nexport function getIdentifyingRxNormCoding(\n  medication: Medication,\n  includedResources?: ResourceMap\n): fhir4.Coding | undefined {\n  const codeableConcept = getMedicationCodeableConcept(medication, includedResources);\n\n  // first check to see if the med has an RxNorm coding that wasn't provided via enrichment\n  const rxNorm = codeableConcept?.coding?.find(\n    (code) =>\n      // must be an RxNorm code\n      code.system === SYSTEM_RXNORM && !code.extension?.some((e) => e.url === SYSTEM_ENRICHMENT)\n  );\n\n  if (rxNorm) {\n    return rxNorm;\n  }\n\n  // otherwise look for an RxNorm provided via the enrichment process\n  return codeableConcept?.coding?.find(\n    (code) =>\n      // must be an RxNorm code\n      code.system === SYSTEM_RXNORM &&\n      // must have no extensions\n      code.extension?.some(\n        (e) => e.url === SYSTEM_ENRICHMENT && e.valueString === \"Standardization\"\n      )\n  );\n}\n\n// Returns the best (most user friendly) display string for the medication associated with a medicationX resource\n// Prefers the \"identifying\" RxNorm code display value, if Zus was able to determine one for the medication.\n// Otherwise fall back to any display values.\nexport function getMedicationDisplayName(\n  resource: Medication,\n  includedResources?: ResourceMap\n): string {\n  const code = getIdentifyingRxNormCoding(resource, includedResources);\n  if (code?.display) {\n    return code.display;\n  }\n\n  const medCodeableConcept = getMedicationCodeableConcept(resource, includedResources);\n\n  if (medCodeableConcept?.text) {\n    return medCodeableConcept.text;\n  }\n\n  return (\n    medCodeableConcept?.coding?.find((x) => x.display)?.display ??\n    `${medCodeableConcept?.coding?.[0].code} (${medCodeableConcept?.coding?.[0].system})`\n  );\n}\n\n// Returns the organization name of any performer for the medication.\nexport function getPerformingOrganization(\n  resource: Medication,\n  includedResources?: ResourceMap\n): fhir4.Organization | undefined {\n  let reference;\n\n  switch (resource.resourceType) {\n    case \"MedicationAdministration\":\n    case \"MedicationDispense\":\n      reference = resource.performer?.[0]?.actor;\n      break;\n\n    case \"MedicationRequest\":\n      reference = resource.performer || resource.dispenseRequest?.performer;\n      break;\n\n    // MedicationStatements don't have a performer.\n    case \"MedicationStatement\":\n    default:\n      return undefined;\n  }\n\n  if (reference?.reference && reference.type === \"Organization\") {\n    return findReference(\"Organization\", resource.contained, includedResources, reference);\n  }\n\n  return undefined;\n}\n\nexport function createPatientStatusMap(\n  medications: fhir4.MedicationStatement[],\n  includedResources?: ResourceMap\n): Record<string, string> {\n  let patientMedications = medications.filter(\n    (medication) => medication.informationSource?.type === \"Patient\"\n  );\n\n  /* Sort the medications by asserted date, which we will then loop and\n     set the last instance of whatever rxCode we see as the source of truth. */\n  patientMedications = sortBy(patientMedications, (medication) =>\n    medication.dateAsserted ? medication.dateAsserted : \"\"\n  );\n\n  const rxNormStatusMap: Record<string, string> = {};\n  patientMedications.forEach((medication) => {\n    const rxNormCode = getIdentifyingRxNormCode(medication, includedResources) ?? \"\";\n    rxNormStatusMap[rxNormCode] = medication.status;\n  });\n\n  return rxNormStatusMap;\n}\n\nexport function patientStatus(status?: string): string {\n  return get(medStatusDisplays, status as string, \"\");\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport {\n  getIdentifyingRxNormCode,\n  getMedicationDisplayName,\n  getPerformingOrganization,\n} from \"@/fhir/medication\";\nimport { PractitionerModel } from \"@/fhir/models/practitioner\";\nimport { findReference } from \"@/fhir/resource-helper\";\n\nexport class MedicationDispenseModel extends FHIRModel<fhir4.MedicationDispense> {\n  kind = \"MedicationDispense\" as const;\n\n  get includedPerformer(): string | undefined {\n    const reference = this.resource.performer?.[0]?.actor;\n\n    const practitioner = findReference(\n      \"Practitioner\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n\n    if (practitioner) {\n      return new PractitionerModel(practitioner).fullName;\n    }\n    return this.resource.performer?.[0]?.actor.display;\n  }\n\n  get performer(): fhir4.Organization | undefined {\n    return getPerformingOrganization(this.resource, this.includedResources);\n  }\n\n  get performerDetails() {\n    const { performer } = this;\n    return {\n      name: performer?.name ?? \"\",\n      address: performer?.address?.[0].text ?? \"\",\n      telecom: performer?.telecom?.[0].value ?? \"\",\n    };\n  }\n\n  get status(): string {\n    return this.resource.status;\n  }\n\n  get quantityDisplay(): string | undefined {\n    const { value, unit = \"units\" } = this.resource.quantity || {};\n    return value ? `${value} ${unit}` : undefined;\n  }\n\n  get rxNorm(): string | undefined {\n    return getIdentifyingRxNormCode(this.resource, this.includedResources);\n  }\n\n  get supplied(): string | undefined {\n    const { value, unit = \"days\" } = this.resource.daysSupply || {};\n    return value ? `${value} ${unit}` : undefined;\n  }\n\n  get medicationDisplayName() {\n    return getMedicationDisplayName(this.resource, this.includedResources);\n  }\n\n  get PMARefillNotPickedUp(): string | undefined {\n    return this.resource.extension?.find(\n      (e) => e.url === \"http://surescripts.net/fhir/CodeSystem/patient-notification-types\",\n    )?.valueString;\n  }\n\n  get alertTimeStamp(): string | undefined {\n    const time = this.resource.extension?.find(\n      (e) => e.url === \"http://surescripts.net/fhir/CodeSystem/notification-generated-time\",\n    )?.valueInstant;\n\n    return formatDateISOToLocal(time);\n  }\n\n  get title() {\n    return this.medicationDisplayName;\n  }\n\n  get whenHandedOver() {\n    return formatDateISOToLocal(this.resource.whenHandedOver);\n  }\n\n  get whenPrepared() {\n    return formatDateISOToLocal(this.resource.whenPrepared);\n  }\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { getMedicationDisplayName } from \"../medication\";\nimport { formatDateISOToLocal } from \"@/fhir/formatters\";\nimport { compact } from \"@/utils/nodash/fp\";\n\nexport class MedicationAdministrationModel extends FHIRModel<fhir4.MedicationAdministration> {\n  kind = \"MedicationAdministration\" as const;\n\n  get dosageDisplay(): string {\n    const { text, dose } = this.resource.dosage || {};\n    if (text) {\n      return text;\n    }\n\n    return compact([dose?.value, dose?.unit]).join(\" \");\n  }\n\n  get dosageRoute(): string | undefined {\n    const { route } = this.resource.dosage || {};\n    return route?.text;\n  }\n\n  get effectivePeriod() {\n    const { start, end } = this.resource.effectivePeriod || {};\n\n    return {\n      start: start ? formatDateISOToLocal(start) : \"\",\n      end: end ? formatDateISOToLocal(end) : \"\",\n    };\n  }\n\n  get title() {\n    return getMedicationDisplayName(this.resource, this.includedResources);\n  }\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { getIdentifyingRxNormCode, getMedicationDisplayName } from \"../medication\";\nimport { PractitionerModel } from \"@/fhir/models/practitioner\";\nimport { findReference } from \"@/fhir/resource-helper\";\nimport { compact } from \"@/utils/nodash/fp\";\n\nexport class MedicationRequestModel extends FHIRModel<fhir4.MedicationRequest> {\n  kind = \"MedicationRequest\" as const;\n\n  get authoredOn() {\n    return formatDateISOToLocal(this.resource.authoredOn);\n  }\n\n  get includedRequester() {\n    const reference = this.resource.requester;\n\n    const practitioner = findReference(\n      \"Practitioner\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n\n    if (practitioner) {\n      return new PractitionerModel(practitioner).fullName;\n    }\n    return this.resource.requester?.display;\n  }\n\n  get medicationDisplayName() {\n    return getMedicationDisplayName(this.resource, this.includedResources);\n  }\n\n  get pharmacy() {\n    const reference = this.resource.dispenseRequest?.performer || {};\n    const organization = findReference(\n      \"Organization\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n    if (organization) {\n      const telecom = organization.telecom?.[0].value;\n      const { city, state, postalCode, text, line = [] } = organization.address?.[0] || {};\n      const cityStatePostal = compact([city, `${state} ${postalCode}`]).join(\", \");\n\n      return {\n        telecom,\n        name: organization.name,\n        address: text ?? compact([line, cityStatePostal]).join(\"\\n\"),\n      };\n    }\n    return { name: reference.display };\n  }\n\n  get rxNorm(): string | undefined {\n    return getIdentifyingRxNormCode(this.resource, this.includedResources);\n  }\n\n  get title() {\n    return this.medicationDisplayName;\n  }\n}\n","import { max } from \"date-fns\";\nimport type { Reference } from \"fhir/r4\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { codeableConceptLabel, findCodingWithEnrichmentValueString } from \"@/fhir/codeable-concept\";\nimport { dateToISO, formatDateISOToLocal } from \"@/fhir/formatters\";\nimport {\n  getIdentifyingRxNormCode,\n  getIdentifyingRxNormCoding,\n  getMedicationCodeableConcept,\n  patientStatus,\n} from \"@/fhir/medication\";\nimport { findReference } from \"@/fhir/resource-helper\";\nimport {\n  CTW_EXTENSION_LENS_AGGREGATED_FROM,\n  LENS_EXTENSION_AGGREGATED_FROM,\n  LENS_EXTENSION_MEDICATION_DAYS_SUPPLY,\n  LENS_EXTENSION_MEDICATION_LAST_FILL_DATE,\n  LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE,\n  LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER,\n  LENS_EXTENSION_MEDICATION_QUANTITY,\n  LENS_EXTENSION_MEDICATION_REFILLS,\n  SYSTEM_RXNORM,\n} from \"@/fhir/system-urls\";\nimport { capitalize, compact, find, get, toLower } from \"@/utils/nodash/fp\";\n\nexport class MedicationStatementModel extends FHIRModel<fhir4.MedicationStatement> {\n  kind = \"MedicationStatement\" as const;\n\n  readonly builderPatientRxNormStatus?: Record<string, string>;\n\n  get activeIngredient(): string | undefined {\n    const concept = getMedicationCodeableConcept(this.resource, this.includedResources);\n    const coding = findCodingWithEnrichmentValueString(\"ActiveIngredient\", concept);\n    return coding?.display;\n  }\n\n  get aggregatedFrom(): Reference[] {\n    const extension = find(\n      (x) =>\n        x.url === LENS_EXTENSION_AGGREGATED_FROM || x.url === CTW_EXTENSION_LENS_AGGREGATED_FROM,\n      this.resource.extension,\n    );\n    if (!extension?.extension) {\n      return compact(this.resource.derivedFrom);\n    }\n    return compact(extension.extension.map(get(\"valueReference\")));\n  }\n\n  get basedOn(): string | undefined {\n    return this.resource.basedOn?.[0]?.type;\n  }\n\n  get category(): string {\n    return codeableConceptLabel(this.resource.category);\n  }\n\n  get context(): string | undefined {\n    return this.resource.context?.display;\n  }\n\n  get dateAsserted(): string | undefined {\n    return formatDateISOToLocal(this.resource.dateAsserted);\n  }\n\n  set dateAsserted(dateAsserted: Date | string | undefined) {\n    if (dateAsserted instanceof Date) {\n      this.resource.dateAsserted = dateToISO(dateAsserted);\n    } else {\n      this.resource.dateAsserted = dateAsserted;\n    }\n  }\n\n  get derivedFrom(): string[] {\n    return this.resource.derivedFrom?.map(({ display }) => display || \"\") || [];\n  }\n\n  get display() {\n    return codeableConceptLabel(\n      getMedicationCodeableConcept(this.resource, this.includedResources),\n      SYSTEM_RXNORM,\n    );\n  }\n\n  get sortDisplay() {\n    return toLower(this.display);\n  }\n\n  get dosage(): string | undefined {\n    return this.resource.dosage?.[0]?.text;\n  }\n\n  get effectiveStart(): string | undefined {\n    return formatDateISOToLocal(this.resource.effectivePeriod?.start);\n  }\n\n  get identifier(): string | undefined {\n    return this.resource.identifier?.[0]?.value;\n  }\n\n  set informationSource(informationSource: Reference | undefined) {\n    this.resource.informationSource = informationSource;\n  }\n\n  get medicationReference(): string | undefined {\n    return this.resource.medicationReference?.display;\n  }\n\n  get notesDisplay(): string[] {\n    return this.resource.note?.map(({ text }) => text) || [];\n  }\n\n  get partOf(): string | undefined {\n    return this.resource.partOf?.[0]?.display;\n  }\n\n  get patientStatus(): string {\n    return patientStatus(this.builderPatientRxNormStatus?.[this.rxNorm ?? \"\"]);\n  }\n\n  // eslint-disable-next-line class-methods-use-this\n  get resourceTypeTitle(): string {\n    return \"Medication\";\n  }\n\n  get rxNorm() {\n    return getIdentifyingRxNormCode(this.resource, this.includedResources);\n  }\n\n  /**\n   * Get RxNorm coding with \"display\" defaulting to this Med-Statement label.\n   */\n  get rxNormCodeableConcept() {\n    const coding = getIdentifyingRxNormCoding(this.resource, this.includedResources);\n\n    return {\n      ...(coding ?? {}),\n      display: coding?.display ?? this.display,\n    };\n  }\n\n  get reason(): string | undefined {\n    return codeableConceptLabel(this.resource.reasonCode?.[0]);\n  }\n\n  get reasonReference(): fhir4.MedicationStatement[\"reasonReference\"] | undefined {\n    return this.resource.reasonReference;\n  }\n\n  get isInactive(): boolean {\n    return ![\"active\", \"intended\", \"unknown\"].includes(this.status);\n  }\n\n  get status() {\n    return this.resource.status;\n  }\n\n  get displayStatus() {\n    if (this.isDismissed) {\n      return \"Dismissed\";\n    }\n    return capitalize(this.resource.status);\n  }\n\n  get statusReason(): string | undefined {\n    return codeableConceptLabel(this.resource.statusReason?.[0]);\n  }\n\n  get subjectID(): string {\n    const [, subjectID] = this.resource.subject.reference?.split(\"/\") || [];\n    return subjectID || \"\";\n  }\n\n  get patient(): PatientModel | undefined {\n    const reference = findReference(\n      \"Patient\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.subject,\n    );\n\n    if (reference) {\n      return new PatientModel(reference, this.includedResources);\n    }\n\n    return undefined;\n  }\n\n  // lens extensions\n\n  get lastFillDate(): string | undefined {\n    return formatDateISOToLocal(\n      this.resource.extension?.find((x) => x.url === LENS_EXTENSION_MEDICATION_LAST_FILL_DATE)\n        ?.valueDateTime,\n    );\n  }\n\n  get quantity(): string | undefined {\n    const quantity = this.resource.extension?.find(\n      (x) => x.url === LENS_EXTENSION_MEDICATION_QUANTITY,\n    )?.valueQuantity;\n\n    if (quantity) {\n      return `${quantity.value} ${quantity.unit || \"\"}`;\n    }\n    return undefined;\n  }\n\n  get daysSupply(): string | undefined {\n    return this.resource.extension\n      ?.find((x) => x.url === LENS_EXTENSION_MEDICATION_DAYS_SUPPLY)\n      ?.valueQuantity?.value?.toString();\n  }\n\n  get refills(): string | undefined {\n    return this.resource.extension\n      ?.find((x) => x.url === LENS_EXTENSION_MEDICATION_REFILLS)\n      ?.valueUnsignedInt?.toString();\n  }\n\n  get lastPrescriber(): string | undefined {\n    const reference = this.resource.extension?.find(\n      (x) => x.url === LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER,\n    )?.valueReference;\n\n    if (!reference?.type || !reference.reference) {\n      return undefined;\n    }\n    const resource = findReference(\n      reference.type as \"Practitioner\" | \"Organization\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n    if (resource?.name) {\n      if (typeof resource.name === \"string\") {\n        return resource.name;\n      }\n      const { family, given = [] } = resource.name[0];\n      return compact([family, given[0]]).join(\", \");\n    }\n    return reference.display;\n  }\n\n  get lastPrescribedDate(): string | undefined {\n    return formatDateISOToLocal(\n      this.resource.extension?.find((x) => x.url === LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE)\n        ?.valueDateTime,\n    );\n  }\n\n  get lastActivityDate(): string | undefined {\n    const { lastPrescribedDate, lastFillDate } = this;\n    const dates = compact([lastPrescribedDate, lastFillDate]).map((x) => new Date(x));\n    if (dates.length === 0) {\n      return undefined;\n    }\n    const maxDate = max(dates);\n    return formatDateISOToLocal(maxDate.toISOString());\n  }\n\n  get title() {\n    return this.display;\n  }\n}\n","import type { Medication } from \"@/fhir/medication\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { codeableConceptLabel } from \"@/fhir/codeable-concept\";\nimport { formatDateISOToLocal } from \"@/fhir/formatters\";\nimport { getPerformingOrganization } from \"@/fhir/medication\";\nimport { MedicationAdministrationModel } from \"@/fhir/models/medication-administration\";\nimport { MedicationDispenseModel } from \"@/fhir/models/medication-dispense\";\nimport { MedicationRequestModel } from \"@/fhir/models/medication-request\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\nimport { findReference } from \"@/fhir/resource-helper\";\n\nexport class MedicationModel extends FHIRModel<Medication> {\n  kind = \"Medication\" as const;\n\n  get performer(): string | undefined {\n    return getPerformingOrganization(this.resource, this.includedResources)?.name;\n  }\n\n  get status(): string {\n    return this.resource.status;\n  }\n\n  get dosage(): string | undefined {\n    switch (this.resource.resourceType) {\n      case \"MedicationStatement\":\n        return this.resource.dosage?.[0]?.text;\n      case \"MedicationAdministration\":\n        return new MedicationAdministrationModel(this.resource, this.includedResources)\n          .dosageDisplay;\n      case \"MedicationDispense\":\n      case \"MedicationRequest\":\n        return codeableConceptLabel(this.resource.dosageInstruction?.[0]);\n      default:\n        return \"\";\n    }\n  }\n\n  get date(): string | undefined {\n    switch (this.resource.resourceType) {\n      case \"MedicationStatement\":\n        return this.resource.dateAsserted ?? this.resource.effectivePeriod?.start;\n      case \"MedicationAdministration\":\n        return this.resource.effectivePeriod?.start;\n      case \"MedicationDispense\":\n        return this.resource.whenHandedOver ?? this.resource.whenPrepared;\n      case \"MedicationRequest\":\n        return (\n          this.resource.authoredOn ??\n          this.resource.dosageInstruction?.[0].timing?.repeat?.boundsPeriod?.start\n        );\n      default:\n        return \"\";\n    }\n  }\n\n  get dateLocal(): string | undefined {\n    return formatDateISOToLocal(this.date);\n  }\n\n  get patient(): PatientModel | undefined {\n    const reference = findReference(\n      \"Patient\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.subject,\n    );\n\n    if (reference) {\n      return new PatientModel(reference, this.includedResources);\n    }\n\n    return undefined;\n  }\n\n  /**\n   * This accessor will try to get the prescriber for the underlying medication\n   * models resource. Depending on the type of fhir resource, it will delegate\n   * the work to a more specific fhir/model/*.ts class before simply grabbing\n   * the `display` property from an actor/performer/requester. If all else\n   * should fail, the accessor returns an empty string.\n   */\n  get prescriber(): string | undefined {\n    switch (this.resource.resourceType) {\n      case \"MedicationStatement\":\n        return new MedicationStatementModel(this.resource, this.includedResources).lastPrescriber;\n      case \"MedicationDispense\":\n        return new MedicationDispenseModel(this.resource, this.includedResources).includedPerformer;\n      case \"MedicationRequest\":\n        return new MedicationRequestModel(this.resource, this.includedResources).includedRequester;\n      default:\n        return undefined;\n    }\n  }\n\n  get title() {\n    switch (this.resource.resourceType) {\n      case \"MedicationStatement\":\n        return new MedicationStatementModel(this.resource, this.includedResources).title;\n      case \"MedicationAdministration\":\n        return new MedicationAdministrationModel(this.resource, this.includedResources).title;\n      case \"MedicationDispense\":\n        return new MedicationDispenseModel(this.resource, this.includedResources).title;\n      case \"MedicationRequest\":\n        return new MedicationRequestModel(this.resource, this.includedResources).title;\n      default:\n        return \"Unknown Medication\";\n    }\n  }\n}\n","export const EmptyNotes = [\n  \"not available\",\n  \"no known\",\n  \"no information\",\n  \"none\",\n  \"no reason\",\n  \"no active\",\n  \"no clinical\",\n  \"not on file\",\n  \"no data\",\n  \"no instructions\",\n  \"no medical\",\n  \"no assessment\",\n  \"no physical\",\n  \"no history\",\n  \"no review\",\n  \"no goals\",\n  \"no health\",\n  \"no discharge\",\n  \"no transcribed\",\n];\n","import { faEye, faEyeSlash } from \"@fortawesome/free-solid-svg-icons\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\n\nexport const dismissFilter: FilterItem = {\n  key: \"showHidden\", // Special key for filtering. See utils/filters.ts.\n  type: \"tag\",\n  belowDivider: true,\n  display: ({ listView }) => (listView ? \"show dismissed records\" : \"dismissed records\"),\n  icon: faEye,\n  toggleDisplay: \"hide dismissed records\",\n  toggleIcon: faEyeSlash,\n};\n","export const THIRD_PARTY_SOURCE_SYSTEM = \"https://zusapi.com/thirdparty/source\";\n\nconst isFromThirdParties = (doc: fhir4.Resource, thirdParties: string[]): boolean => {\n  const thirdPartyTag = doc.meta?.tag?.find((tag) => tag.system === THIRD_PARTY_SOURCE_SYSTEM);\n  return thirdParties.includes(thirdPartyTag?.code || \"\");\n};\n\nexport const isRenderableBinary = (doc: fhir4.Resource): boolean =>\n  isFromThirdParties(doc, [\"commonwell\", \"carequality\"]);\n","import { DocumentReference } from \"fhir/r4\";\nimport { EmptyNotes } from \"./empty-notes\";\nimport { dismissFilter } from \"../../resource/filters\";\nimport { isRenderableBinary } from \"../../resource/helpers/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { DocumentModel } from \"@/fhir/models/document\";\nimport { groupBy, isEqual, orderBy, uniqWith } from \"@/utils/nodash\";\n\nexport const ZUS_CREATION_DATE_URL = \"https://zusapi.com/created-at\";\nconst RAINBOW_CUTOVER_DATE = new Date(\"2023-03-08T05:00:00.000Z\");\n\nconst zusCreationDate = (doc: fhir4.DocumentReference) => {\n  const createExtension = doc.meta?.extension?.filter((ext) => ext.url === ZUS_CREATION_DATE_URL);\n  if (createExtension?.length !== 1 || !createExtension[0].valueInstant) {\n    return null;\n  }\n\n  return new Date(createExtension[0].valueInstant);\n};\n\nconst isViewablePreRainbow = (doc: fhir4.DocumentReference) => {\n  const creationDate = zusCreationDate(doc);\n\n  // if we cannot determine the date, default to trying to show the document\n  if (!creationDate) {\n    return true;\n  }\n  return creationDate < RAINBOW_CUTOVER_DATE;\n};\n\n// DA creates document references for sections of a CDA and the full CDA.\n// We want to filter out the sections, which share binary IDs but have a subsection of categories.\nexport const filterHighestLevelDocs = (docs: DocumentModel[]) => {\n  const highestLevelDocs: DocumentModel[] = [];\n  const documentGroups = groupBy(docs, (d) => d.binaryId);\n\n  // Identify the highest level docs, based on highest category count\n  Object.keys(documentGroups).forEach((binaryId) => {\n    if (binaryId) {\n      highestLevelDocs.push(orderBy(documentGroups[binaryId], \"category.length\", \"desc\")[0]);\n    } else {\n      // If no id, assume highest level\n      highestLevelDocs.push(...documentGroups[binaryId]);\n    }\n  });\n\n  return highestLevelDocs;\n};\n\n// DA creates document references for sections of a CDA and the full CDA.\n// Sections will have at most 1 category.\nexport function isSectionDocument(document: DocumentModel) {\n  return document.category.length < 2;\n}\n\n// We have to ask ourselves this because otherwise a document without multiple\n// categories will be filtered out because we assume it is a section from a CDA\nconst isPdfOrImage = (docRef: fhir4.DocumentReference) => {\n  const document = new DocumentModel(docRef);\n\n  return document.contentType?.startsWith(\"image/\") || document.contentType === \"application/pdf\";\n};\n\n// isEmptyClinicalNote is used to filter out empty clinical notes\n// where the note text is null or empty string or\n// is less than 500 chars and contains one of the substrings in EmptyNotes\nexport function isEmptyClinicalNote(document: DocumentModel) {\n  const noteText = document.text;\n  if (!noteText) {\n    return true;\n  }\n\n  return EmptyNotes.some(\n    (emptyNoteStr) => noteText.length < 500 && noteText.toLowerCase().includes(emptyNoteStr),\n  );\n}\n\nexport const applyDocumentFilters = (data: DocumentModel[]) => {\n  // Is not a section\n  const highestLevelDocs = filterHighestLevelDocs(data);\n  const isHighestLevelDoc = (docRef: DocumentReference) =>\n    highestLevelDocs.find((docModel) => docModel.id === docRef.id);\n\n  const documentModels = data.filter(\n    (doc) =>\n      [isHighestLevelDoc, isViewablePreRainbow, isPdfOrImage].some((fn) => fn(doc.resource)) &&\n      isRenderableBinary(doc.resource) &&\n      !doc.isZusDocument,\n  );\n\n  return uniqWith(documentModels, (a, b) => isEqual(valuesToDedupeOn(a), valuesToDedupeOn(b)));\n};\n\nconst valuesToDedupeOn = (document: DocumentModel) => [\n  document.encounterDate,\n  document.dateCreated,\n  document.custodian,\n  document.title,\n];\n\nexport function documentsFilter(): FilterItem[] {\n  return [dismissFilter];\n}\n","import type { Coding } from \"fhir/r4\";\nimport { SYSTEM_NULL_FLAVOR } from \"@/fhir/system-urls\";\n\nexport const isNullFlavorSystem = (coding: Coding | string | undefined) => {\n  if (typeof coding === \"string\") return coding === SYSTEM_NULL_FLAVOR;\n  return coding?.system === SYSTEM_NULL_FLAVOR;\n};\n\nexport const NullFlavorSystem = {\n  NI: { display: \"NoInformation\", level: 1 },\n  INV: { display: \"invalid\", level: 2 },\n  DER: { display: \"derived\", level: 3 },\n  OTH: { display: \"other\", level: 3 },\n  NINF: { display: \"negative infinity\", level: 4 },\n  PINF: { display: \"positive infinity\", level: 4 },\n  UNC: { display: \"un-encoded\", level: 3 },\n  MSK: { display: \"masked\", level: 2 },\n  NA: { display: \"not applicable\", level: 2 },\n  UNK: { display: \"unknown\", level: 2 },\n  ASKU: { display: \"asked but unknown\", level: 3 },\n  NAV: { display: \"temporarily unavailable\", level: 4 },\n  NASK: { display: \"not asked\", level: 3 },\n  NAVU: { display: \"Not available\", level: 3 },\n  QS: { display: \"Sufficient Quantity\", level: 3 },\n  TRC: { display: \"trace\", level: 3 },\n  NP: { display: \"not present\", level: 1 },\n};\n","import { Coding } from \"fhir/r4\";\nimport { DocumentModel } from \"./document\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { codeableConceptLabel } from \"../codeable-concept\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { getBinaryIDFromProvenance } from \"../provenance\";\nimport { findReference } from \"../resource-helper\";\nimport { SYSTEM_ZUS_CREATED_AT } from \"../system-urls\";\nimport { ResourceMap } from \"../types\";\nimport {\n  isEmptyClinicalNote,\n  isSectionDocument,\n} from \"@/components/content/document/helpers/filters\";\nimport { isNullFlavorSystem } from \"@/fhir/mappings/null-flavor\";\nimport { compact, flatten, uniq } from \"@/utils/nodash\";\n\nexport class EncounterModel extends FHIRModel<fhir4.Encounter> {\n  kind = \"Encounter\" as const;\n\n  public binaryId?: string;\n\n  public clinicalNotes: DocumentModel[];\n\n  public provenance: fhir4.Provenance[];\n\n  public relatedEncounter: EncounterModel | undefined;\n\n  constructor(\n    resource: fhir4.Encounter,\n    provenance: fhir4.Provenance[],\n    includedResources?: ResourceMap,\n    basics?: fhir4.Basic[],\n  ) {\n    super(resource, includedResources, basics);\n    this.provenance = provenance;\n    this.clinicalNotes = [];\n    this.provenance = provenance;\n    this.binaryId = getBinaryIDFromProvenance(this.provenance);\n  }\n\n  findAndSetNotesFrom(documentPool: DocumentModel[]) {\n    if (this.binaryId) {\n      this.clinicalNotes = documentPool.filter(\n        (d) => d.binaryId === this.binaryId && isSectionDocument(d) && !isEmptyClinicalNote(d),\n      );\n    }\n  }\n\n  get lastUpdated(): string | undefined {\n    return (\n      this.resource.meta?.lastUpdated ||\n      this.resource.meta?.extension?.find((e) => e.url === SYSTEM_ZUS_CREATED_AT)?.valueDateTime\n    );\n  }\n\n  get patient(): PatientModel | undefined {\n    const patient = findReference(\"Patient\", undefined, undefined, this.resource.subject);\n    return patient ? new PatientModel(patient) : undefined;\n  }\n\n  get class(): string | undefined {\n    const { display, code } = this.resource.class;\n    return display ?? code !== \"UNK\" ? code : undefined;\n  }\n\n  get diagnoses(): string[] | undefined {\n    return compact(uniq(this.resource.diagnosis?.map((d) => d.condition.display)));\n  }\n\n  get dischargeDisposition(): string | undefined {\n    return codeableConceptLabel(this.resource.hospitalization?.dischargeDisposition);\n  }\n\n  get isHospitalEncounter(): boolean {\n    return this.typeCodings.some((c) => c.code === \"IMP\" || c.code === \"EMER\");\n  }\n\n  get location(): string | undefined {\n    const locations = compact(this.resource.location?.map((l) => l.location.display));\n    return locations.length ? locations.join(\", \") : undefined;\n  }\n\n  get participantsDisplay(): string | undefined {\n    return this.participants?.join(\", \");\n  }\n\n  get participants(): string[] | undefined {\n    return compact(uniq(this.resource.participant?.map((p) => p.individual?.display)));\n  }\n\n  get periodEnd() {\n    return formatDateISOToLocal(this.resource.period?.end);\n  }\n\n  get periodStart() {\n    return formatDateISOToLocal(this.resource.period?.start);\n  }\n\n  get dateDisplay() {\n    if (this.periodStart !== this.periodEnd && this.periodEnd) {\n      return `${this.periodStart} - ${this.periodEnd}`;\n    }\n    return this.periodStart;\n  }\n\n  get reason(): string | undefined {\n    const reasons = compact(this.resource.reasonCode?.map((d) => codeableConceptLabel(d)));\n\n    return reasons.length ? reasons.join(\", \") : undefined;\n  }\n\n  get status() {\n    return this.resource.status;\n  }\n\n  get typeCodings(): Coding[] {\n    return compact(flatten(this.resource.type?.map((t) => t.coding)));\n  }\n\n  get typeSpecialty() {\n    const locations = compact(\n      this.resource.location?.map((l) => {\n        const location = findReference(\"Location\", undefined, undefined, l.location);\n        return location?.type?.map((t) => codeableConceptLabel(t));\n      }),\n    );\n    const uniqueLocations = uniq(flatten(locations)).filter(\n      (l) => l !== \"Not Indicated\" && l !== \"Unknown\" && l !== \"NoInformation\",\n    );\n\n    return uniqueLocations.length ? uniqueLocations.join(\", \") : undefined;\n  }\n\n  get locationPhysicalType() {\n    const locations = compact(\n      this.resource.location?.map((l) => {\n        const location = findReference(\"Location\", undefined, undefined, l.location);\n        return codeableConceptLabel(location?.physicalType);\n      }),\n    );\n\n    const uniqueLocations = uniq(locations).filter((l) => {\n      switch (l) {\n        case \"URGENT_CARE\":\n          return \"Urgent Care\";\n        case \"Not Indicated\":\n        case \"Unknown\":\n        case \"NoInformation\":\n        case \"No Information\":\n        case \"Building\":\n        case undefined:\n          return \"Unknown\";\n        default:\n          return l;\n      }\n    });\n\n    return uniqueLocations.length ? uniqueLocations[0] : \"Unknown\";\n  }\n\n  get title() {\n    return this.typeDisplay;\n  }\n\n  get typeDisplay(): string {\n    const { display: classDisplay, system: classSystem } = this.resource.class;\n    const classCode = (this.resource.class.code ?? \"\").toUpperCase();\n    const firstTypeCoding = this.resource.type?.[0]?.coding?.[0] ?? {};\n    const { text: typeText } = this.resource.type?.[0] ?? {};\n    const typeCode = (firstTypeCoding.code ?? \"\").toUpperCase();\n\n    // Grab our code and display, first from class if valid, otherwise from\n    // first type coding.\n    const isNullFlavor = isNullFlavorSystem(classSystem);\n    const code = isNullFlavor ? typeCode : classCode;\n    let display = isNullFlavor ? typeText : classDisplay;\n\n    // Optionally add expanded version of the code\n    // if code is AMB, IMP, EMER and display isn't already the expanded version.\n    const mappings: Record<string, string> = {\n      AMB: \"Ambulatory\",\n      IMP: \"Inpatient\",\n      EMER: \"Emergency\",\n    };\n    if (code && Object.keys(mappings).includes(code)) {\n      const codeDisplay = mappings[code];\n      if (!display) {\n        return codeDisplay;\n      }\n\n      if (display.toLowerCase() !== codeDisplay.toLowerCase()) {\n        display += `, ${mappings[code]}`;\n      }\n    }\n\n    return display ?? \"Unknown\";\n  }\n}\n","import { EpisodeOfCare } from \"fhir/r4\";\nimport { EncounterModel } from \"./encounter\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PatientModel } from \"./patient\";\nimport { codeableConceptLabel } from \"../codeable-concept\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { findReference } from \"../resource-helper\";\nimport { SYSTEM_ZUS_CREATED_AT } from \"../system-urls\";\nimport { ResourceMap } from \"../types\";\nimport { capitalize } from \"@/utils/nodash\";\nimport { compact, uniq } from \"@/utils/nodash/fp\";\n\nconst DISCHARGE_NARRATIVE_URL = \"https://zusapi.com/lens/extension/dischargeNarrative\";\nconst DISCHARGE_DISP_URL = \"https://zusapi.com/lens/extension/dischargeDisposition\";\nconst DISCHARGE_LOC_URL = \"https://zusapi.com/lens/extension/dischargeLocation\";\nconst ADMIT_LOC_URL = \"https://zusapi.com/lens/extension/admittingLocation\";\n\nconst findViaExtensionByURL = (r: EpisodeOfCare, url: string) =>\n  r.extension?.find((e) => e.url === url);\n\nexport class EpisodeOfCareModel extends FHIRModel<fhir4.EpisodeOfCare> {\n  kind = \"EpisodeOfCareModel\" as const;\n\n  public binaryId?: string;\n\n  public provenance: fhir4.Provenance[];\n\n  public relatedEncounters: EncounterModel[] | undefined;\n\n  constructor(\n    resource: fhir4.EpisodeOfCare,\n    provenance: fhir4.Provenance[],\n    includedResources?: ResourceMap,\n    basics?: fhir4.Basic[],\n  ) {\n    super(resource, includedResources, basics);\n    this.provenance = provenance;\n  }\n\n  get key() {\n    return this.resource.id || \"\";\n  }\n\n  get lastUpdated(): string | undefined {\n    return (\n      this.resource.meta?.lastUpdated ||\n      this.resource.meta?.extension?.find((e) => e.url === SYSTEM_ZUS_CREATED_AT)?.valueDateTime\n    );\n  }\n\n  get patient(): PatientModel | undefined {\n    const patient = findReference(\"Patient\", undefined, undefined, this.resource.patient);\n    return patient ? new PatientModel(patient) : undefined;\n  }\n\n  get diagnoses(): string[] | undefined {\n    return compact(\n      uniq(\n        this.resource.diagnosis?.map((d) => {\n          const c = findReference(\"Condition\", undefined, undefined, d.condition);\n          return c?.code?.text;\n        }),\n      ),\n    );\n  }\n\n  get class(): string | undefined {\n    const classExt = findViaExtensionByURL(\n      this.resource,\n      \"https://zusapi.com/lens/extension/encounterClass\",\n    );\n    return capitalize(classExt?.valueCoding?.display);\n  }\n\n  get classCode(): string {\n    const classExt = findViaExtensionByURL(\n      this.resource,\n      \"https://zusapi.com/lens/extension/encounterClass\",\n    );\n    return classExt?.valueCoding?.code?.toUpperCase() ?? \"\";\n  }\n\n  get dischargeDisposition(): string | undefined {\n    const dischargeExt = findViaExtensionByURL(this.resource, DISCHARGE_DISP_URL);\n    return codeableConceptLabel(dischargeExt?.valueCodeableConcept);\n  }\n\n  get location(): string | undefined {\n    const dischargeLoc = findViaExtensionByURL(this.resource, DISCHARGE_LOC_URL);\n    return dischargeLoc?.valueReference?.display || this.admittingLocation;\n  }\n\n  get admittingLocation(): string | undefined {\n    const admitLoc = findViaExtensionByURL(this.resource, ADMIT_LOC_URL);\n    return admitLoc?.valueReference?.display;\n  }\n\n  // TODO: once https://zeushealth.atlassian.net/browse/DAU-288 is done we can likely remove this \n  // logic to treat midnight UTC as a date only\n  get periodEnd() {\n    return formatDateISOToLocal(this.resource.period?.end, true);\n  }\n\n  get periodStart() {\n    return formatDateISOToLocal(this.resource.period?.start, true);\n  }\n\n  get dateDisplay() {\n    if (this.periodStart !== this.periodEnd && this.periodEnd) {\n      return `${this.periodStart} - ${this.periodEnd}`;\n    }\n    return this.periodStart;\n  }\n\n  get status() {\n    switch (this.resource.status) {\n      case \"active\":\n        return \"Active\";\n      case \"finished\":\n        return \"Discharged\";\n      default:\n        return this.resource.status;\n    }\n  }\n\n  get dischargeBinaries() {\n    const dischargeExt = findViaExtensionByURL(this.resource, DISCHARGE_NARRATIVE_URL);\n    const binaryIds = dischargeExt?.extension?.map(\n      (e) => e.valueReference?.reference?.substring(\"Binary/\".length),\n    );\n    return binaryIds || [];\n  }\n\n  get title() {\n    return `${this.dateDisplay} - ${this.class}`;\n  }\n}\n","import { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { createOrEditFhirResource } from \"@/fhir/action-helper\";\nimport { dateToISO } from \"@/fhir/formatters\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { cloneDeep } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT } from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\n\nexport type PatientFormData = {\n  lastName: string;\n  firstName: string;\n  gender: fhir4.Patient[\"gender\"];\n  dateOfBirth: Date;\n  email: string;\n  phone: string;\n  address: string;\n  city: string;\n  state: string;\n  zipCode: string;\n};\n\nexport const editPatient = async (\n  patient: PatientModel,\n  data: PatientFormData,\n  getRequestContext: () => Promise<CTWRequestContext>,\n) => {\n  const requestContext = await getRequestContext();\n  const fhirPatient = cloneDeep(patient.resource);\n\n  fhirPatient.gender = data.gender;\n  fhirPatient.birthDate = dateToISO(data.dateOfBirth);\n\n  fhirPatient.name = [\n    {\n      use: \"official\",\n      family: data.lastName,\n      given: [data.firstName],\n    },\n  ];\n\n  fhirPatient.address = [\n    {\n      line: [data.address],\n      city: data.city,\n      state: data.state,\n      postalCode: data.zipCode,\n    },\n  ];\n\n  const telecom: fhir4.ContactPoint[] = [];\n\n  if (data.phone) {\n    telecom.push({ system: \"phone\", value: data.phone });\n  }\n\n  if (data.email) {\n    telecom.push({ system: \"email\", value: data.email });\n  }\n\n  fhirPatient.telecom = telecom;\n\n  const response = await createOrEditFhirResource(\n    fhirPatient,\n    requestContext,\n    new PatientModel(fhirPatient).title,\n  );\n\n  await queryClient.invalidateQueries([QUERY_KEY_PATIENT]);\n\n  return response;\n};\n","import { createContext } from \"react\";\n\ntype TelemetryContextValue = {\n  builderId?: string;\n  enableTelemetry?: boolean;\n  ehr?: string;\n};\n\nexport const TelemetryContext = createContext<TelemetryContextValue>({});\n","import { useContext } from \"react\";\nimport { TelemetryContext } from \"./context\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function useTelemetry() {\n  return {\n    Telemetry,\n    context: useContext(TelemetryContext),\n  };\n}\n","import { useQuery } from \"@tanstack/react-query\";\nimport { CTWRequestContext } from \"./ctw-context\";\nimport { useCTW } from \"./use-ctw\";\nimport { withTimerMetric } from \"@/utils/telemetry\";\n\nexport function useQueryWithCTW<T, T2>(\n  queryKey: string,\n  keys: T2[],\n  query: (requestContext: CTWRequestContext, keys?: T2[]) => Promise<T>,\n  enabled = true,\n  staleTime: number | undefined = undefined,\n) {\n  const { getRequestContext } = useCTW();\n\n  return useQuery({\n    queryKey: [queryKey, ...keys],\n    queryFn: async () => {\n      const requestContext = await getRequestContext();\n      return query(requestContext, keys);\n    },\n    staleTime,\n    enabled,\n  });\n}\n\nexport function useTimerQueryWithCTW<T, T2>(\n  queryKey: string,\n  keys: T2[],\n  query: (requestContext: CTWRequestContext, keys?: T2[]) => Promise<T>,\n  enabled = true,\n  staleTime: number | undefined = undefined,\n) {\n  return useQueryWithCTW(\n    queryKey,\n    keys,\n    withTimerMetric(query, \"query_request_timing\", [`query_key:${queryKey}`]),\n    enabled,\n    staleTime,\n  );\n}\n","import type { ResourceMap, ResourceType, ResourceTypeString } from \"./types\";\nimport type { FhirResource } from \"fhir-kit-client\";\n\nexport const isBundle = (resource: fhir4.Resource): resource is fhir4.Bundle =>\n  resource.resourceType === \"Bundle\";\n\n// Returns an array of resource entries from bundle filtered\n// down to the specified resourceType.\nexport function getResources<T extends ResourceTypeString>(\n  bundle: FhirResource,\n  resourceType: T,\n): ResourceType<T>[] {\n  const resources: FhirResource[] = [];\n  if (isBundle(bundle)) {\n    bundle.entry?.forEach((entry) => {\n      if (entry.resource?.resourceType === resourceType) {\n        resources.push(entry.resource);\n      } else if (entry.resource?.resourceType === \"Bundle\") {\n        // Recursively search for resources in nested bundles.\n        resources.push(...getResources(entry.resource, resourceType));\n      }\n    });\n  }\n\n  return resources as ResourceType<T>[];\n}\n\n// Returns a map from resourceType/id -> resource.\nexport function bundleToResourceMap(bundle: FhirResource): ResourceMap {\n  const resources = {} as ResourceMap;\n  if (isBundle(bundle)) {\n    bundle.entry?.forEach((entry) => {\n      const { resource } = entry;\n      if (!resource) {\n        return;\n      }\n      const path = `${resource.resourceType}/${resource.id}`;\n      resources[path] = resource as fhir4.Resource;\n    });\n  }\n\n  return resources;\n}\n","import Client, { SearchParams } from \"fhir-kit-client\";\nimport { getResources } from \"./bundle\";\nimport {\n  SYSTEM_SUMMARY,\n  SYSTEM_ZUS_LENS,\n  SYSTEM_ZUS_OWNER,\n  SYSTEM_ZUS_THIRD_PARTY,\n  SYSTEM_ZUS_UNIVERSAL_ID,\n  SYSTEM_ZUS_UPI_RECORD_TYPE,\n} from \"./system-urls\";\nimport { ResourceType, ResourceTypeString } from \"./types\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { filter, mergeWith, some } from \"@/utils/nodash\";\n\nconst MAX_COUNT = 500;\n\n// Set env to true to fetch all pages from ODS.\nconst DEBUG_ODS_FETCH_ALL_PAGES = import.meta.env.VITE_DEBUG_ODS_FETCH_ALL_PAGES;\n\n// Number of entries in bundle before we stop fetching all pages.\n// This way, we don't accidentally fetch 100K resources from ODS.\nconst DEBUG_ODS_FETCH_ALL_PAGES_CUTOFF = 2500;\n\n// TODO: move this into client.ts after we are off ODS.\nexport function excludeTagsinPatientRecordSearch<T extends ResourceTypeString>(\n  resourceType: T,\n): string[] {\n  switch (resourceType) {\n    case \"Patient\":\n      return [...UPI_TAGS];\n    case \"Condition\":\n      return [...CONDITIONS_LENS_TAGS, ...SUMMARY_TAGS];\n    case \"MedicationStatement\":\n      return [...MEDICATION_LENS_TAGS, ...SUMMARY_TAGS];\n    case \"Coverage\":\n    case \"AllergyIntolerance\":\n    case \"CareTeam\":\n    case \"DocumentReference\":\n    case \"Encounter\":\n    case \"Immunization\":\n    case \"MedicationAdministration\":\n    case \"MedicationDispense\":\n    case \"MedicationRequest\":\n    default:\n      return [];\n  }\n}\n\n// Enumerating ALL of the third party tags.\nconst THIRD_PARTY_TAGS = [\n  `${SYSTEM_ZUS_THIRD_PARTY}|surescripts`,\n  `${SYSTEM_ZUS_THIRD_PARTY}|commonwell`,\n  `${SYSTEM_ZUS_THIRD_PARTY}|elation`,\n  `${SYSTEM_ZUS_THIRD_PARTY}|collective-medical`,\n  `${SYSTEM_ZUS_THIRD_PARTY}|quest`,\n];\n\n// Enumerating Medication-specific lens tags.\nconst MEDICATION_LENS_TAGS = [`${SYSTEM_ZUS_LENS}|ActiveMedications`];\n\n// Enumerating Condition-specific lens tags.\nconst CONDITIONS_LENS_TAGS = [`${SYSTEM_ZUS_LENS}|ChronicConditions`];\n\nconst UPI_TAGS = [`${SYSTEM_ZUS_UPI_RECORD_TYPE}|universal`];\n\nconst SUMMARY_TAGS = [`${SYSTEM_SUMMARY}|Common`];\n\n// ODS must be specifically configured *by resource* to support the firstparty tag.\n// This is a performance optimization to address slow queries using _tag:not.\nconst FIRST_PARTY_TAG_SUPPORTED_RESOURCES = [\n  \"Patient\",\n  \"Condition\",\n  \"Coverage\",\n  \"Encounter\",\n  \"MedicationStatement\",\n];\n\nexport type SearchReturn<T extends ResourceTypeString> = {\n  bundle: fhir4.Bundle;\n  total: number;\n  resources: ResourceType<T>[];\n};\n\n// Performs a FHIR search for the given resourceType across all resources\n// the user has access to. This can include lens and third party resources!\n// Returns {bundle: fhir4.Bundle, total: number, resources: ResourceType[]}.\n// Usage: {bundle, total, resources: tasks} =\n//          searchAllRecords(\"Task\", requestContext, searchParams)\n// NOTE: \"patientUPID\" is a special searchParam that will correctly\n//       filter down to the resources pertaining to that patient UPID.\nasync function searchAllRecords<T extends ResourceTypeString>(\n  resourceType: T,\n  requestContext: CTWRequestContext,\n  searchParams?: SearchParams,\n): Promise<SearchReturn<T>> {\n  const { patientUPID, _count, ...params } = searchParams ?? {};\n  const fetchAll = typeof _count === \"undefined\";\n  const count = fetchAll ? MAX_COUNT : _count;\n  let bundle = (await requestContext.fhirClient.search({\n    resourceType,\n    searchParams: {\n      ...params,\n      _count: count,\n      ...patientSearchParams(resourceType, patientUPID as string),\n    },\n  })) as fhir4.Bundle;\n\n  if (DEBUG_ODS_FETCH_ALL_PAGES === \"true\") {\n    bundle = await fetchAllPages(requestContext.fhirClient, bundle);\n  }\n\n  const resources = getResources(bundle, resourceType);\n  return { bundle, total: bundle.total ?? 0, resources };\n}\n\n// Like searchAllRecords, but only for resources from this builder.\nexport async function searchBuilderRecords<T extends ResourceTypeString>(\n  resourceType: T,\n  requestContext: CTWRequestContext,\n  searchParams?: SearchParams,\n): Promise<SearchReturn<T>> {\n  // TODO: Once all third party and lens data is being written to dedicated builders (ie. we are in a \"post-kludge world\")\n  // then we can remove all of this filtering by firstparty and the user's builder.\n  // The whole purpose of this code is to specifically target data that was written by the user's builder.\n  const nonBuilderTags = [\n    ...THIRD_PARTY_TAGS,\n    ...MEDICATION_LENS_TAGS,\n    ...CONDITIONS_LENS_TAGS,\n    ...SUMMARY_TAGS,\n    ...UPI_TAGS,\n  ];\n  type FirstPartyParams = {\n    firstparty?: boolean;\n    \"_tag:not\"?: string[];\n  };\n  const firstPartyParams: FirstPartyParams = {};\n\n  // Only some resources in ODS support filtering by the \"firstparty\" in order to exclude 3rd party and lens data.\n  // For other resources we'll need to keep using the _tag:not parameter which is significantly slower.\n  if (FIRST_PARTY_TAG_SUPPORTED_RESOURCES.includes(resourceType)) {\n    firstPartyParams.firstparty = true;\n  } else {\n    firstPartyParams[\"_tag:not\"] = nonBuilderTags;\n  }\n\n  const params = mergeParams(searchParams, firstPartyParams);\n  const records = await searchAllRecords(resourceType, requestContext, params);\n\n  // Filter using the user's builder ID.\n  const { entry, resources } = filterSearchReturnByBuilderId(\n    records,\n    requestContext.contextBuilderId || requestContext.builderId,\n  );\n\n  records.resources = resources;\n  records.bundle.entry = entry;\n\n  return records;\n}\n\n// Merges two sets of params into a single set,\n// taking special care to concat any arrays.\n// E.g. mergeParams({_tag: [1], foo: \"foo\"}, {_tag: [2], bar: \"bar\"})\n//   -> {_tag: [1, 2], foo: \"foo\", bar: \"bar\"}\nfunction mergeParams(params: SearchParams | undefined, params2: SearchParams): SearchParams {\n  return mergeWith(params, params2, (v, v2) =>\n    // Concat arrays otherwise return undefined to let mergeWith handle it.\n    Array.isArray(v) ? v.concat(v2) : undefined,\n  );\n}\n\n// Returns the needed search params to filter resources down to those\n// pertaining to our patientUPID.\nfunction patientSearchParams(resourceType: ResourceTypeString, patientUPID?: string): SearchParams {\n  // No search param needed when not searching for a patientUPID.\n  if (!patientUPID) {\n    return {};\n  }\n\n  const identifier = `${SYSTEM_ZUS_UNIVERSAL_ID}|${patientUPID}`;\n\n  switch (resourceType) {\n    case \"Coverage\":\n      return { \"beneficiary.identifier\": identifier };\n    case \"AllergyIntolerance\":\n    case \"CareTeam\":\n    case \"Condition\":\n    case \"DocumentReference\":\n    case \"DiagnosticReport\":\n    case \"Encounter\":\n    case \"Immunization\":\n    case \"MedicationAdministration\":\n    case \"MedicationDispense\":\n    case \"MedicationRequest\":\n    case \"MedicationStatement\":\n    case \"Observation\":\n      return { \"patient.identifier\": identifier };\n    case \"Patient\":\n      return { identifier };\n    default:\n      throw new Error(`Unhandled patient search for resource type: ${resourceType}`);\n  }\n}\n\n// Filters resources down to those owned by matchOwnerBuilderId.\n// Filters the bundle of entries down to those owned by:\n//  * mathOwnerBuilderId for search entries with mode \"match\"\n//  * includedOwnerBuilderId for search entries with mode \"include\"\nconst filterSearchReturnByBuilderId = <T extends ResourceTypeString>(\n  searchReturn: SearchReturn<T>,\n  matchOwnerBuilderId: string,\n  includedOwnerBuilderId?: string,\n) => {\n  const resources = filter(searchReturn.resources, (record) =>\n    some(record.meta?.tag, {\n      system: SYSTEM_ZUS_OWNER,\n      code: `builder/${matchOwnerBuilderId}`,\n    }),\n  );\n\n  const entry = filter(searchReturn.bundle.entry, (record) => {\n    if (record.search?.mode === \"include\") {\n      return some(record.resource?.meta?.tag, {\n        system: SYSTEM_ZUS_OWNER,\n        code: `builder/${includedOwnerBuilderId ?? matchOwnerBuilderId}`,\n      });\n    }\n    return some(record.resource?.meta?.tag, {\n      system: SYSTEM_ZUS_OWNER,\n      code: `builder/${matchOwnerBuilderId}`,\n    });\n  });\n\n  return { resources, entry };\n};\n\nasync function fetchAllPages(fhirClient: Client, bundle: fhir4.Bundle) {\n  const entries = [...(bundle.entry ?? [])];\n  let currentBundle = bundle;\n\n  while (\n    currentBundle.link?.find((link) => link.relation === \"next\")?.url &&\n    entries.length < DEBUG_ODS_FETCH_ALL_PAGES_CUTOFF\n  ) {\n    // eslint-disable-next-line no-await-in-loop\n    currentBundle = (await fhirClient.nextPage({ bundle: currentBundle })) as fhir4.Bundle;\n    entries.push(...(currentBundle.entry ?? []));\n  }\n\n  return { ...bundle, link: undefined, entry: entries, total: entries.length };\n}\n","import { gql } from \"graphql-request\";\n\nexport const fragmentBasic = gql`\n  fragment Basic on Basic {\n    id\n    resourceType\n    meta {\n      lastUpdated\n    }\n    code {\n      coding {\n        code\n        display\n        system\n      }\n    }\n    author {\n      display\n    }\n  }\n`;\n\nexport const fragmentCoding = gql`\n  fragment Coding on Coding {\n    code\n    display\n    system\n    extension {\n      url\n      valueString\n    }\n  }\n`;\n\nexport const fragmentEncounterReference = gql`\n  fragment Encounter on Encounter {\n    id\n    resourceType\n    extension {\n      url\n      valueString\n    }\n    status\n    priority {\n      text\n      coding {\n        code\n        display\n        system\n      }\n    }\n  }\n`;\n\nexport const fragmentPractitioner = gql`\n  fragment Practitioner on Practitioner {\n    id\n    resourceType\n    extension {\n      url\n      valueString\n    }\n    name {\n      family\n      given\n      prefix\n      suffix\n      text\n      use\n    }\n    qualification {\n      code {\n        text\n        coding {\n          code\n          display\n          system\n        }\n      }\n      period {\n        start\n        end\n      }\n    }\n  }\n`;\n\nexport const fragmentMedicationRequest = gql`\n  fragment MedicationRequest on MedicationRequest {\n    id\n    resourceType\n    extension {\n      url\n      valueString\n    }\n    status\n    intent\n  }\n`;\n\nexport const fragmentPatient = gql`\n  fragment Patient on Patient {\n    id\n    resourceType\n    meta {\n      extension {\n        url\n        valueString\n        valueInstant\n      }\n      tag {\n        system\n        code\n      }\n    }\n    active\n    identifier {\n      use\n      system\n      value\n    }\n    contact {\n      address {\n        city\n        country\n        district\n        line\n        period {\n          start\n          end\n        }\n        postalCode\n        state\n        text\n        type\n        use\n      }\n      gender\n      name {\n        family\n        given\n        prefix\n        suffix\n        text\n        use\n      }\n      organization {\n        display\n        identifier {\n          value\n        }\n        type\n      }\n    }\n    birthDate\n    gender\n    maritalStatus {\n      text\n      coding {\n        code\n        display\n        system\n      }\n    }\n    telecom {\n      use\n      value\n      system\n    }\n    address {\n      city\n      country\n      district\n      line\n      period {\n        start\n        end\n      }\n      postalCode\n      state\n      text\n      type\n      use\n    }\n    name {\n      family\n      given\n      prefix\n      suffix\n      text\n      use\n    }\n    managingOrganization {\n      resource {\n        ...Organization\n      }\n    }\n  }\n`;\n\nexport const fragmentReference = gql`\n  fragment Reference on Reference {\n    id\n    extension {\n      url\n      valueString\n    }\n    reference\n    type\n    identifier {\n      id\n      system\n      value\n    }\n    display\n  }\n`;\n\nexport const fragmentObservation = gql`\n  fragment Observation on Observation {\n    id\n    resourceType\n    extension {\n      url\n      valueString\n    }\n    status\n    category {\n      text\n      coding {\n        code\n        display\n        system\n        extension {\n          url\n          valueString\n        }\n      }\n    }\n    effectivePeriod {\n      start\n      end\n    }\n    effectiveDateTime\n    referenceRange {\n      text\n    }\n    code {\n      text\n      coding {\n        code\n        display\n        system\n        extension {\n          url\n          valueString\n        }\n      }\n    }\n    valueQuantity {\n      comparator\n      unit\n      value\n      system\n      code\n    }\n    valueCodeableConcept {\n      text\n      coding {\n        system\n        code\n        display\n      }\n    }\n    valueString\n    valueBoolean\n    valueInteger\n    valueRange {\n      low {\n        unit\n        value\n        system\n        code\n      }\n      high {\n        unit\n        value\n        system\n        code\n      }\n    }\n    valueRatio {\n      numerator {\n        comparator\n        unit\n        value\n        system\n        code\n      }\n      denominator {\n        unit\n        value\n        system\n        code\n      }\n    }\n    valueTime\n    valueDateTime\n    valuePeriod {\n      start\n      end\n    }\n    interpretation {\n      text\n      coding {\n        code\n        display\n        system\n        extension {\n          url\n          valueString\n        }\n      }\n    }\n  }\n`;\n\nexport const fragmentOrganization = gql`\n  fragment Organization on Organization {\n    id\n    resourceType\n    extension {\n      url\n      valueString\n    }\n    name\n    telecom {\n      system\n      value\n      period {\n        start\n        end\n      }\n    }\n    contact {\n      purpose {\n        text\n        coding {\n          code\n          display\n          system\n          extension {\n            url\n            valueString\n          }\n        }\n      }\n      name {\n        family\n        given\n        prefix\n        suffix\n        text\n        use\n      }\n      telecom {\n        system\n        value\n        period {\n          start\n          end\n        }\n      }\n      address {\n        type\n        use\n        text\n        line\n        city\n        district\n        state\n        postalCode\n        country\n        period {\n          start\n          end\n        }\n      }\n    }\n  }\n`;\n","import { Patient } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentOrganization, fragmentPatient } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface PatientConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<Patient>[];\n}\n\nexport interface PatientGraphqlResponse {\n  PatientConnection: PatientConnection;\n}\n\nexport const patientsForUPIDQuery = gql`\n  ${fragmentPatient}\n  ${fragmentOrganization}\n\n  query Patients(\n    $upid: ID!\n    $cursor: String!\n    $sort: PatientSortParams!\n    $first: Int!\n    $filter: PatientFilterParams! = {}\n  ) {\n    PatientConnection(upid: $upid, after: $cursor, sort: $sort, first: $first, filter: $filter) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          ...Patient\n        }\n      }\n    }\n  }\n`;\n\nexport const patientsForBuilderQuery = gql`\n  ${fragmentPatient}\n  ${fragmentOrganization}\n\n  query Patients(\n    $builderID: ID!\n    $cursor: String!\n    $sort: PatientSortParams!\n    $first: Int!\n    $filter: PatientFilterParams! = {}\n  ) {\n    PatientConnection(\n      builderID: $builderID\n      after: $cursor\n      sort: $sort\n      first: $first\n      filter: $filter\n    ) {\n      pageInfo {\n        hasNextPage\n        endCursor\n      }\n      edges {\n        node {\n          ...Patient\n        }\n      }\n    }\n  }\n`;\n","import { Bundle } from \"fhir/r4\";\nimport { getZusServiceUrl } from \"@/api/urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { SYSTEM_ZUS_THIRD_PARTY } from \"@/fhir/system-urls\";\nimport { ResourceType, ResourceTypeString } from \"@/fhir/types\";\nimport { ctwFetch } from \"@/utils/request\";\n\nexport type FQSRequestContext = {\n  // Added type to prevent normal CTWRequestContext from working.\n  // This forces callers to use the fqsRequestContext converter function\n  // which properly handles contextBuilderId overwrites.\n  type: \"fqs\";\n  env: string;\n  builderId: string;\n  authToken: string;\n};\n\nexport function fqsRequestContext(ctwContext: CTWRequestContext): FQSRequestContext {\n  return {\n    type: \"fqs\",\n    env: ctwContext.env,\n    builderId: ctwContext.contextBuilderId ?? ctwContext.builderId,\n    authToken: ctwContext.authToken,\n  };\n}\n\nexport async function searchRecordsFQS<T extends ResourceTypeString>(\n  context: FQSRequestContext,\n  resourceString: T,\n  params?: Record<string, string>,\n): Promise<ResourceType<T>[]> {\n  const baseUrl = `${getZusServiceUrl(context.env, \"fqs\")}/rest/`;\n  const urlParams = new URLSearchParams(params);\n\n  const { data } = await ctwFetch(`${baseUrl}/${resourceString}?${urlParams.toString()}`, {\n    method: \"GET\",\n    headers: {\n      Authorization: `Bearer ${context.authToken}`,\n    },\n  });\n\n  const resources = ((data as Bundle).entry ?? []).map((e) => e.resource) as ResourceType<T>[];\n\n  // Filter out 3rd party resources (TODO: Can remove when fully post-kludge).\n  return resources.filter(\n    (resource) => !resource.meta?.tag?.some((t) => t.system === SYSTEM_ZUS_THIRD_PARTY),\n  );\n}\n\nexport async function searchBuilderRecordsFQS<T extends ResourceTypeString>(\n  context: FQSRequestContext,\n  resourceString: T,\n  params?: Record<string, string>,\n): Promise<ResourceType<T>[]> {\n  return searchRecordsFQS(context, resourceString, {\n    ...params,\n    builderID: context.builderId,\n  });\n}\n\nexport async function fetchResource<T extends ResourceTypeString>(\n  context: FQSRequestContext,\n  resourceString: T,\n  id: string,\n) {\n  const baseUrl = `${getZusServiceUrl(context.env, \"fqs\")}/rest/`;\n  const { data } = await ctwFetch(`${baseUrl}/${resourceString}/${id}`, {\n    method: \"GET\",\n    headers: {\n      Authorization: `Bearer ${context.authToken}`,\n    },\n  });\n\n  return data as ResourceType<T>;\n}\n","import { isEmptyValue } from \"./types\";\nimport { isString, orderBy } from \"@/utils/nodash\";\nimport { get } from \"@/utils/nodash/fp\";\n\nexport type SortDir = \"asc\" | \"desc\";\n\nexport type Sort<T extends object> = {\n  dir: SortDir;\n  isDate?: boolean;\n  key: keyof T;\n};\n\ntype GetValueFunction<T> = (c: T) => unknown;\n\ntype Comparator<T> = (a: T) => unknown;\nexport function applySorts<T extends object>(records: T[], sorts: Sort<T>[]) {\n  const dateIteratee =\n    (column: keyof T): Comparator<T> =>\n    (record: T) => {\n      const value = record[column];\n      if (!isString(value) || !value) {\n        return 0;\n      }\n      return new Date(value).getTime();\n    };\n\n  // Makes a list of iteratees, where each index iteratee is preceded by an iteratee that ensures blanks go last.\n  const iteratees: (Comparator<T> | keyof T)[] = [];\n  const orders: SortDir[] = [];\n  sorts.forEach((sortEntry) => {\n    const { key, dir, isDate } = sortEntry;\n    iteratees.push((o) => isEmptyValue(o[key]), isDate ? dateIteratee(key) : key);\n    orders.push(\"asc\", dir);\n  });\n\n  return orderBy(records, iteratees, orders);\n}\n\nexport function sort<T>(\n  collection: T[],\n  getValue: GetValueFunction<T> | string,\n  order: SortDir,\n  isDate = false\n) {\n  const getValueFn = isString(getValue) ? get(getValue) : getValue;\n  if (isDate) return sortByDate(collection, getValueFn, order);\n  return orderBy(collection, getValue, order) as T[];\n}\n\nfunction sortByDate<T>(collection: T[], getValue: GetValueFunction<T>, order: \"asc\" | \"desc\") {\n  collection.sort((a, b) => {\n    const aDate = getValue(a) as string | undefined;\n    const bDate = getValue(b) as string | undefined;\n    if (!aDate && !bDate) {\n      return 0;\n    }\n    if (!aDate) {\n      return order === \"asc\" ? -1 : 1;\n    }\n    if (!bDate) {\n      return order === \"asc\" ? 1 : -1;\n    }\n\n    const dateA = new Date(aDate).getTime();\n    const dateB = new Date(bDate).getTime();\n\n    if (order === \"asc\") {\n      return dateA - dateB;\n    }\n\n    return dateB - dateA;\n  });\n  return collection;\n}\n","import { SearchParams } from \"fhir-kit-client\";\nimport { PatientModel } from \"./models\";\nimport { filterByTags } from \"./resource-helper\";\nimport { searchBuilderRecords } from \"./search-helpers\";\nimport { SYSTEM_ZUS_OWNER, SYSTEM_ZUS_UPI_RECORD_TYPE } from \"./system-urls\";\nimport { Tag } from \"./types\";\nimport { Telemetry, useTimingQueryWithPatient } from \"..\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useQueryWithCTW } from \"@/components/core/providers/use-query-with-ctw\";\nimport {\n  createGraphqlClient,\n  fqsRequest,\n  GraphqlPageInfo,\n  MAX_OBJECTS_PER_REQUEST,\n} from \"@/services/fqs/client\";\nimport {\n  PatientGraphqlResponse,\n  patientsForBuilderQuery,\n  patientsForUPIDQuery,\n} from \"@/services/fqs/queries/patients\";\nimport {\n  fetchResource,\n  fqsRequestContext,\n  searchBuilderRecordsFQS,\n} from \"@/services/fqs-rest/search-helpers\";\nimport { pickBy } from \"@/utils/nodash\";\nimport {\n  QUERY_KEY_BUILDER_PATIENTS_BY_UPID,\n  QUERY_KEY_MATCHED_PATIENTS,\n  QUERY_KEY_PATIENTS_LIST_FQS,\n} from \"@/utils/query-keys\";\nimport { sort } from \"@/utils/sort\";\nimport { hasNumber } from \"@/utils/types\";\n\n// As of 1/9/24, if all of the patients for the given UPID are inactive, getPatientsForUPIDFQS will throw an\n// unauthorized error so we return the patient used to initiate the query.\nexport function useBuilderPatientsByUPID() {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_BUILDER_PATIENTS_BY_UPID,\n    [],\n    async (requestContext: CTWRequestContext, patient: PatientModel) =>\n      getPatientsForUPIDFQS(requestContext, patient, {\n        tag: {\n          allmatch: [`${SYSTEM_ZUS_OWNER}|builder/${requestContext.builderId}`],\n        },\n      }).catch(() => [patient]),\n  );\n}\n\nexport function useMatchedPatients() {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_MATCHED_PATIENTS,\n    [],\n    async (requestContext: CTWRequestContext, patient: PatientModel) =>\n      getPatientsForUPIDFQS(requestContext, patient, {\n        tag: {\n          nonematch: [`${SYSTEM_ZUS_OWNER}|builder/${requestContext.builderId}`],\n        },\n      }),\n  );\n}\n\nexport async function getPatientsForUPIDFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  filter: Record<string, unknown> = {},\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<PatientGraphqlResponse>(graphClient, patientsForUPIDQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: MAX_OBJECTS_PER_REQUEST,\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n      filter,\n    });\n    return data.PatientConnection.edges\n      .filter(\n        (p) =>\n          !p.node.meta?.tag?.some(\n            (t) => t.system === SYSTEM_ZUS_UPI_RECORD_TYPE && t.code === \"universal\",\n          ),\n      )\n      .map((x) => new PatientModel(x.node));\n  } catch (e) {\n    throw new Error(`Failed fetching patients: ${e}`);\n  }\n}\n\n// Returns a single FHIR patient given a patientID and systemURL.\n// If multiple patients are found then it returns the last updated.\nexport async function getBuilderFhirPatientByExternalIdentifier(\n  requestContext: CTWRequestContext,\n  patientID: string,\n  systemURL: string,\n  tags?: Tag[],\n): Promise<PatientModel> {\n  const params = {\n    identifier: `${systemURL}|${patientID}`,\n    // We need to ensure that all the patients aren't third-party in the response. We have no way to paginate patients by identifier from FQS due to a bug\n    _count: \"50\",\n  };\n  let patients = await searchBuilderRecordsFQS(\n    fqsRequestContext(requestContext),\n    \"Patient\",\n    params,\n  );\n  patients = filterByTags(patients, tags);\n\n  if (patients.length === 0) {\n    throw new Error(\n      `Failed fetching patient information for patient from patientID ${patientID} with system ${systemURL}`,\n    );\n  }\n\n  // sort by lastUpdated in descending order to prefer more recent patients\n  const sortedPatients = sort(patients, \"meta.lastUpdated\", \"desc\", true);\n  // prefer patients with a name so we avoid using a stub/duplicate patient\n  const patient = sortedPatients.find((x) => (x.name?.length ?? 0) > 0) ?? sortedPatients[0];\n  const patientModel = new PatientModel(patient);\n\n  // Set the patient UPID globally so that any log events can be associated with the patient\n  Telemetry.setPatientUPID(patientModel.UPID);\n\n  return patientModel;\n}\n\nexport async function getPatientByID(\n  requestContext: CTWRequestContext,\n  patientID: string,\n): Promise<PatientModel> {\n  const response = await fetchResource(fqsRequestContext(requestContext), \"Patient\", patientID);\n\n  const patientModel = new PatientModel(response as fhir4.Patient);\n  // Set the patient UPID globally so that any log events can be associated with the patient\n  Telemetry.setPatientUPID(patientModel.UPID);\n  return patientModel;\n}\n\nexport function usePatientsListFQS(pageSize: number, cursor: string) {\n  return useQueryWithCTW(\n    QUERY_KEY_PATIENTS_LIST_FQS,\n    [pageSize, cursor],\n    getBuilderPatientsListFQS,\n  );\n}\n\ntype GetPatientsTableResultsODS = {\n  patients: PatientModel[];\n  searchParams: SearchParams;\n  total: number;\n};\n\ntype GetPatientsTableResultsFQS = {\n  patients: PatientModel[];\n  pageInfo: GraphqlPageInfo;\n};\n\nexport async function getBuilderPatientListWithSearch(\n  requestContext: CTWRequestContext,\n  paginationOptions: (number | string | undefined)[] = [],\n): Promise<Omit<GetPatientsTableResultsODS, \"total\">> {\n  const [pageSize, pageOffset, searchValue] = paginationOptions;\n  const offset = parseInt(`${pageOffset ?? \"0\"}`, 10) * parseInt(`${pageSize ?? \"1\"}`, 10);\n\n  const searchParams = pickBy({\n    _count: pageSize,\n\n    _offset: offset,\n    ...(hasNumber(searchValue) ? { identifier: searchValue } : { name: searchValue }),\n  }) as SearchParams;\n\n  try {\n    const { resources } = await searchBuilderRecords(\"Patient\", requestContext, searchParams);\n\n    return {\n      searchParams,\n      patients: resources.map((patient) => new PatientModel(patient)),\n    };\n  } catch (e) {\n    throw Error(\"Failed to fetch patients in patient search list\");\n  }\n}\n\nexport async function getBuilderPatientsListFQS(\n  requestContext: CTWRequestContext,\n  paginationOptions: (number | string | undefined)[] = [],\n): Promise<GetPatientsTableResultsFQS> {\n  const [pageSize, cursor] = paginationOptions;\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<PatientGraphqlResponse>(\n      graphClient,\n      patientsForBuilderQuery,\n      {\n        builderID: requestContext.builderId,\n        cursor,\n        first: pageSize,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          tag: {\n            nonematch: [\"https://zusapi.com/thirdparty/source\"],\n          },\n        },\n      },\n    );\n    const models = data.PatientConnection.edges.map((x) => new PatientModel(x.node));\n    return {\n      patients: models,\n      pageInfo: data.PatientConnection.pageInfo,\n    };\n  } catch (e) {\n    throw new Error(`Failed fetching patients: ${e}`);\n  }\n}\n","import { useQuery, UseQueryResult } from \"@tanstack/react-query\";\nimport { ReactNode, useCallback, useContext, useMemo } from \"react\";\nimport { CTWRequestContext } from \"./ctw-context\";\nimport { DrawerProvider } from \"./drawer-provider\";\nimport { ModalProvider } from \"./modal-provider\";\nimport { PatientContext, PatientState } from \"./patient-context\";\nimport { useCTW } from \"./use-ctw\";\nimport { editPatient, PatientFormData } from \"../../content/forms/actions/patients\";\nimport { useTelemetry } from \"@/components/core/providers/telemetry/use-telemetry\";\nimport { useTimerQueryWithCTW } from \"@/components/core/providers/use-query-with-ctw\";\nimport { PatientModel } from \"@/fhir/models/patient\";\nimport { getBuilderFhirPatientByExternalIdentifier, getPatientByID } from \"@/fhir/patient-helper\";\nimport { SYSTEM_ZUS_UNIVERSAL_ID } from \"@/fhir/system-urls\";\nimport { Tag } from \"@/fhir/types\";\nimport { QUERY_KEY_PATIENT } from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\nimport { withTimerMetric } from \"@/utils/telemetry\";\n\n// Cache patient for 5 minutes.\nconst PATIENT_STALE_TIME = 1000 * 60 * 5;\n\nexport type ThirdPartyID = {\n  patientResourceID?: never;\n  patientUPID?: never;\n  patientID: string;\n  systemURL: string;\n};\n\nexport type PatientUPIDSpecified = {\n  patientResourceID?: never;\n  patientUPID: string;\n  patientID?: never;\n  systemURL?: never;\n};\n\nexport type PatientResourceID = {\n  patientResourceID: string;\n  patientUPID?: never;\n  patientID?: never;\n  systemURL?: never;\n};\n\nexport type PatientProviderProps = {\n  children: ReactNode;\n  tags?: Tag[];\n  onPatientSave?: (data: PatientFormData) => void;\n  onResourceSave?: (data: fhir4.Resource, action: \"create\" | \"update\") => void;\n} & (ThirdPartyID | PatientUPIDSpecified | PatientResourceID);\n\nexport function PatientProvider({\n  children,\n  patientResourceID,\n  patientUPID,\n  patientID,\n  systemURL,\n  tags,\n  onPatientSave,\n  onResourceSave,\n}: PatientProviderProps) {\n  const providerState = useMemo(\n    () => ({\n      patientResourceID,\n      patientID: patientUPID || patientID,\n      systemURL: patientUPID ? SYSTEM_ZUS_UNIVERSAL_ID : systemURL,\n      tags,\n      onPatientSave,\n      onResourceSave,\n    }),\n    [patientResourceID, patientID, patientUPID, systemURL, tags, onPatientSave, onResourceSave],\n  );\n\n  return (\n    <PatientContext.Provider value={providerState as PatientState}>\n      <ModalProvider>\n        <DrawerProvider>{children}</DrawerProvider>\n      </ModalProvider>\n    </PatientContext.Provider>\n  );\n}\n\nexport function usePatientContext() {\n  const context = useContext(PatientContext);\n  if (!context) {\n    throw new Error(\"usePatient must be used within a PatientProvider\");\n  }\n\n  return context;\n}\n\nexport function usePatient(): UseQueryResult<PatientModel> {\n  const context = usePatientContext();\n\n  const { patientResourceID, patientID, systemURL, tags } = context;\n  const { getPatient } = usePatientPromise();\n\n  return useTimerQueryWithCTW(\n    QUERY_KEY_PATIENT,\n    [patientResourceID, patientID, systemURL, tags],\n    getPatient,\n    !!patientID || !!patientResourceID,\n    PATIENT_STALE_TIME,\n  );\n}\n\nexport function usePatientPromise() {\n  const { getRequestContext } = useCTW();\n  const { Telemetry } = useTelemetry();\n\n  const context = usePatientContext();\n\n  return {\n    context,\n    getPatient: useCallback(() => {\n      const { patientResourceID, patientID, systemURL, tags } = context;\n\n      return queryClient.fetchQuery(\n        [QUERY_KEY_PATIENT, patientID, systemURL, tags],\n        async () => {\n          const requestContext = await getRequestContext();\n          try {\n            if (systemURL && patientID) {\n              return await getBuilderFhirPatientByExternalIdentifier(\n                requestContext,\n                patientID,\n                systemURL,\n                tags,\n              );\n            }\n            if (patientResourceID) {\n              return await getPatientByID(requestContext, patientResourceID);\n            }\n          } catch (e) {\n            const patientIdUsed =\n              systemURL && patientID ? `${patientID}_${systemURL}` : patientResourceID;\n            // We want to be able to alert when failing to fetch patients. This metric is also used in standalone directly.\n            // The `patient_id_by` is used to track the specific patient that failed to fetch.\n            void Telemetry.reportMetric(\"increment\", \"patient_fetch_error\", 1, [\n              `patient_id_by:${patientIdUsed}`,\n            ]);\n\n            throw Error(\"Failed fetching patient\");\n          }\n          throw new Error(\"Must specify a patient ID and system URL or a patient FHIR resource ID\");\n        },\n        { staleTime: PATIENT_STALE_TIME },\n      );\n    }, [context, getRequestContext, Telemetry]),\n  };\n}\n\nexport function useHandlePatientSave(patient?: PatientModel) {\n  const { getRequestContext } = useCTW();\n  const context = usePatientContext();\n\n  const { onPatientSave } = context;\n\n  return useCallback(\n    async (data) => {\n      if (patient) {\n        if (onPatientSave) {\n          return onPatientSave(data);\n        }\n        return editPatient(patient, data, getRequestContext);\n      }\n      throw new Error(\"onPatientSave requires a patient\");\n    },\n    [onPatientSave, patient, getRequestContext],\n  );\n}\n\nexport function useQueryWithPatient<T, T2>(\n  queryKey: string,\n  keys: T2[],\n  query: (requestContext: CTWRequestContext, patient: PatientModel, keys?: T2[]) => Promise<T>,\n  enabled = true,\n) {\n  const { Telemetry } = useTelemetry();\n  const { getRequestContext } = useCTW();\n  const patientResponse = usePatient();\n\n  if (patientResponse.isSuccess && !patientResponse.data.UPID) {\n    const patientID = patientResponse.data.resource.identifier;\n    Telemetry.logger.error(\"Patient does not have a UPID\", { patientID });\n    throw new Error(`Patient with ID ${JSON.stringify(patientID)} does not have a UPID`);\n  }\n\n  return useQuery({\n    // eslint-disable-next-line @tanstack/query/exhaustive-deps\n    queryKey: [queryKey, patientResponse.data, ...keys],\n    queryFn: async () => {\n      const requestContext = await getRequestContext();\n      // Ignore eslint warning as we should always have a valid\n      // patient thanks to the enabled check.\n      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n      return query(requestContext, patientResponse.data!, keys);\n    },\n    enabled: !!patientResponse.data?.UPID && enabled,\n  });\n}\n\nexport function useTimingQueryWithPatient<T, T2>(\n  queryKey: string,\n  keys: T2[],\n  query: (requestContext: CTWRequestContext, patient: PatientModel, keys?: T2[]) => Promise<T>,\n  enabled = true,\n) {\n  return useQueryWithPatient(\n    queryKey,\n    keys,\n    withTimerMetric(query, \"query_request_timing\", [`query_key:${queryKey}`]),\n    enabled,\n  );\n}\n","import { useContext, useMemo } from \"react\";\nimport { AnalyticsContext } from \"./context\";\nimport { usePatient } from \"@/components/core/providers/patient-provider\";\nimport { useTelemetry } from \"@/components/core/providers/telemetry/use-telemetry\";\nimport { SortDir } from \"@/utils/sort\";\n\n// Tracked events indicate the effect the user initiated.\n// They don't indicate details like patient, overarching component, or cause, which belong in metadata.\nexport type Action =\n  // App-level\n  | \"logout\"\n  | \"toggle_ai_search\"\n  | \"search\"\n  | \"clear_search\"\n  // Documents\n  | \"open_source_document\"\n  | \"close_document\"\n  | \"toggle_document_section\"\n  | \"download_document\"\n  | \"add_to_record\"\n  | \"select_section\"\n  // History\n  | \"toggle_history_entry\"\n  // Notes\n  | \"toggle_note\"\n  // Drawers\n  | \"open_drawer\"\n  | \"close_drawer\"\n  // Forms\n  | \"submit_form\" // actions include \"create_resource\", \"edit_resource\"\n  | \"cancel_delete_request\"\n  | \"confirm_delete_request\"\n  | \"request_records\"\n  | \"open_diagnostic_report\"\n  // Trends\n  | \"toggle_trend\"\n  // Tables\n  | \"change_view\"\n  | \"change_filter\"\n  | \"sort\"\n  | \"open_tab\"\n  | \"empty_table\"\n  // Records\n  | \"toggle_record_archive\"\n  | \"toggle_record_read\"\n  | \"click_row\"\n  | \"change_page\"\n  // TOC Table\n  | \"view_adt_details\"\n  | \"view_adt_discharge_summary\"\n  // Overview\n  | \"see_all_of_resource\";\n\n// Properties to include in metadata if applicable,\n// beyond the default of component and patient.\nexport type TrackingMetadata = {\n  resourceType?: string;\n  target?: string; // For identical events, indicates which UI triggered it.\n  value?: string; // Value of selector\n  action?: string; // Further differentiates actions\n  dir?: SortDir;\n  datadogMetricName?: string;\n  page?: number; // Which page number the action triggered or triggured on\n};\n\nexport function useAnalytics() {\n  const analytics = useContext(AnalyticsContext);\n  const telemetry = useTelemetry();\n  const patient = usePatient();\n\n  return useMemo(\n    () => ({\n      // Helper to include patient UPID and optionally also the component name\n      // with metadata when tracking interactions\n      trackInteraction(action: Action, metadata: TrackingMetadata = {}) {\n        const eventMetadata: Record<string, unknown> = { ...metadata };\n\n        if (analytics.componentName) {\n          eventMetadata.componentName = analytics.componentName;\n        }\n        if (patient.data?.UPID) {\n          eventMetadata.upid = patient.data.UPID;\n        }\n        return telemetry.Telemetry.trackInteraction(action, eventMetadata);\n      },\n\n      analyticsEvent(action: string, eventMetadata = {}) {\n        return telemetry.Telemetry.analyticsEvent(action, eventMetadata);\n      },\n    }),\n    [analytics.componentName, patient.data?.UPID, telemetry.Telemetry],\n  );\n}\n","import { faChevronDown } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport DOMPurify from \"dompurify\";\nimport { Interweave } from \"interweave\";\nimport { ReactNode, useRef, useState } from \"react\";\nimport { DOCUMENT_HEADER_ID, TABLE_OF_CONTENT_ID } from \"../../../constants\";\nimport { fixHtml } from \"../../helpers\";\nimport { SectionType } from \"../../types\";\nimport \"../../../styles.scss\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport useHeaderOffset from \"@/hooks/use-header-offset\";\n\nexport const Section = ({ title, humanReadable, id, isEmpty }: SectionType): JSX.Element | null => {\n  if (!humanReadable) return null;\n\n  const sanitizedHtml = DOMPurify.sanitize(fixHtml(humanReadable));\n  const cleanedHtml = sanitizedHtml.replace(/Â&nbsp;/g, \" \");\n\n  return (\n    <SectionContainer\n      title={title}\n      id={id}\n      tableOfContentsId={TABLE_OF_CONTENT_ID}\n      overrideDefaultHidden={isEmpty}\n    >\n      <Interweave content={cleanedHtml} />\n    </SectionContainer>\n  );\n};\n\nexport type SectionContainerProps = {\n  children: ReactNode;\n  id: string;\n  title: string;\n  tableOfContentsId: string;\n  overrideDefaultHidden?: boolean;\n};\n\nexport const SectionContainer = ({\n  children,\n  id,\n  title,\n  tableOfContentsId,\n  overrideDefaultHidden,\n}: SectionContainerProps): JSX.Element => {\n  const [isHidden, setIsHidden] = useState(overrideDefaultHidden);\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n  const headerOffset = useHeaderOffset(tableOfContentsId);\n  const documentHeaderOffset = useHeaderOffset(DOCUMENT_HEADER_ID);\n\n  const { trackInteraction } = useAnalytics();\n\n  const handleClick = () => {\n    setIsHidden(!isHidden);\n    trackInteraction(\"toggle_document_section\", {\n      action: isHidden ? \"collapse_document_section\" : \"expand_document_section\",\n    });\n  };\n\n  return (\n    <div className=\"ctw-ccda-section-container\" id={id} ref={containerRef}>\n      <div\n        className=\"ctw-ccda-section-header-wrapper\"\n        style={{ top: breakpoints.md ? documentHeaderOffset : documentHeaderOffset + headerOffset }}\n      >\n        <button type=\"button\" className=\"ctw-ccda-section-arrow\" onClick={handleClick}>\n          <span className=\"ctw-hidden\">hide</span>\n          <FontAwesomeIcon\n            icon={faChevronDown}\n            className={cx(\"ctw-ml-auto ctw-w-4\", { \"ctw-transform ctw-rotate-[270deg]\": isHidden })}\n          />\n        </button>\n        <h3 className=\"ctw-text-sm ctw-uppercase\">{title}</h3>\n      </div>\n\n      {!isHidden && <div className=\"ctw-section-display\">{children}</div>}\n    </div>\n  );\n};\n","import xpath, { SelectedValue } from \"xpath\";\n\nexport const wrappedInDiv = (content: string): string =>\n  `<div xmlns=\"http://www.w3.org/1999/xhtml\">${content}</div>`;\n\nexport const parseNestedElement = (element: Document): string => {\n  const childNodes = xpath.select(\"child::node()\", element);\n  const names = childNodes\n    .map((itemChildNode: SelectedValue) =>\n      xpath.select1(\"string(name())\", itemChildNode as Node | undefined),\n    )\n    .filter(Boolean);\n\n  const documents = childNodes as Document[];\n\n  if (names.length !== 0) {\n    return documents.map(parseElement).join(\"\");\n  }\n  return \"\";\n};\n\nexport const parseElement = (element: Document) => {\n  const textElementToParseName = xpath.select1(\"string(name())\", element) as string;\n\n  switch (textElementToParseName) {\n    case \"br\":\n      return \"<br />\";\n    case \"caption\":\n      return parseCaptionElement(element);\n    case \"content\":\n      return parseContentElement(element);\n    case \"list\":\n      return parseListElement(element);\n    case \"paragraph\":\n      return parseParagraphElement(element);\n    case \"table\":\n      return parseTableElement(element);\n    // Text nodes have no node name\n    case \"\":\n      return parseTextNode(element);\n    default:\n      return undefined;\n  }\n};\n\nexport const parseTableElement = (tableElementXml: Document | undefined): string | undefined => {\n  if (!tableElementXml) return \"\";\n\n  const theadElementXml = xpath.select1(\"*[name()='thead']\", tableElementXml) as\n    | Document\n    | undefined;\n  const tbodyElementXml = xpath.select1(\"*[name()='tbody']\", tableElementXml) as\n    | Document\n    | undefined;\n\n  const tableContent = [];\n\n  if (theadElementXml) {\n    const parsedTheadElement = parseTheadElement(theadElementXml);\n    if (parsedTheadElement) tableContent.push(parsedTheadElement);\n  }\n\n  if (tbodyElementXml) {\n    const parsedTbodyElement = parseTbodyElement(tbodyElementXml);\n    if (parsedTbodyElement) tableContent.push(parsedTbodyElement);\n  }\n\n  if (tableContent.length > 0) return `<table>${tableContent.join(\"\")}</table>`;\n\n  return undefined;\n};\n\nexport const parseTdElement = (tdElementXml: Document | undefined): string | undefined => {\n  if (!tdElementXml) return \"\";\n\n  const nestedData = parseNestedElement(tdElementXml);\n  if (nestedData) return `<td>${nestedData}</td>`;\n\n  const tdElementText = parseTextNode(tdElementXml);\n  if (tdElementText) return `<td>${tdElementText}</td>`;\n\n  return undefined;\n};\n\nexport const parseTextNode = (textNodeXml: Document | undefined): string => {\n  if (!textNodeXml) return \"\";\n\n  return (\n    (xpath.select1(\"string()\", textNodeXml) as string)\n      .trim()\n      .replace(/</g, \"&lt;\")\n      .replace(/>/g, \"&gt;\")\n      .replace(/&/g, \"&amp;\") || \"\"\n  );\n};\n\nexport const parseParagraphElement = (\n  paragraphElementXml: Document | undefined,\n): string | undefined => {\n  if (!paragraphElementXml) return \"\";\n\n  const nestedData = parseNestedElement(paragraphElementXml);\n  if (nestedData) return `<p>${nestedData}</p>`;\n\n  const paragraphText = parseTextNode(paragraphElementXml);\n\n  if (paragraphText) return `<p>${paragraphText}</p>`;\n\n  return undefined;\n};\n\nexport const parseListElement = (listElelementXml: Document | undefined): string => {\n  if (!listElelementXml) return \"\";\n\n  const listType = xpath.select1(\"string(@listType)\", listElelementXml) as string;\n\n  const listItems = xpath.select(\"*[name()='item']\", listElelementXml) as Document[];\n\n  const parsedListItems = listItems\n    .map((listItem: Document) => {\n      const nestedData = parseNestedElement(listItem);\n      if (nestedData) return `<li>${nestedData}</li>`;\n\n      const textData = parseTextNode(listItem);\n      if (textData) return `<li>${textData}</li>`;\n\n      return undefined;\n    })\n    .join(\"\");\n\n  if (listType === \"ordered\") {\n    return `<ol>${parsedListItems}</ol>`;\n  }\n\n  return `<ul>${parsedListItems}</ul>`;\n};\n\nexport const parseContentElement = (\n  contentElementXml: Document | undefined,\n): string | undefined => {\n  if (!contentElementXml) return undefined;\n\n  const nestedData = parseNestedElement(contentElementXml);\n  if (nestedData) return nestedData;\n\n  const contentText = parseTextNode(contentElementXml);\n  if (contentText) return `<span>${contentText}</span>`;\n\n  return undefined;\n};\n\nexport const parseCaptionElement = (\n  captionElementXml: Document | undefined,\n): string | undefined => {\n  if (!captionElementXml) return undefined;\n\n  const nestedData = parseNestedElement(captionElementXml);\n  if (nestedData) return nestedData;\n\n  const captionText = parseTextNode(captionElementXml);\n  if (captionText) return `<h2>${captionText}</h2>`;\n\n  return undefined;\n};\n\nexport const parseTheadElement = (theadElementXml: Document | undefined): string | undefined => {\n  if (!theadElementXml) return \"\";\n\n  const trElementXml = xpath.select1(\"*[name()='tr']\", theadElementXml) as Document | undefined;\n\n  if (trElementXml) {\n    const parsedTrElement = parseTrElement(trElementXml);\n    if (parsedTrElement) return `<thead>${parsedTrElement}</thead>`;\n  }\n\n  return undefined;\n};\n\nexport const parseTbodyElement = (theadElementXml: Document | undefined): string | undefined => {\n  if (!theadElementXml) return \"\";\n\n  const trElementsXml = xpath.select(\"*[name()='tr']\", theadElementXml) as Document[];\n  if (trElementsXml.length > 0) {\n    const parsedTrElements = trElementsXml.map((trElementXml: Document) =>\n      parseTrElement(trElementXml),\n    );\n    if (parsedTrElements.length > 0) {\n      return `<tbody>${parsedTrElements.join(\"\")}</tbody>`;\n    }\n  }\n\n  return undefined;\n};\n\nexport const parseThElement = (thElementXml: Document | undefined): string | undefined => {\n  if (!thElementXml) return \"\";\n\n  const nestedData = parseNestedElement(thElementXml);\n  if (nestedData) return `<th>${nestedData}</th>`;\n\n  const thElementText = parseTextNode(thElementXml);\n  if (thElementText) return `<th>${thElementText}</th>`;\n\n  return undefined;\n};\n\nexport const parseTrElement = (trElementXml: Document | undefined): string | undefined => {\n  if (!trElementXml) return \"\";\n\n  const thElements = xpath.select(\"*[name()='th']\", trElementXml) as Document[];\n\n  if (thElements.length > 0) {\n    const parsedThElements = thElements.map((thElement) => parseThElement(thElement));\n    return `<tr>${parsedThElements.join(\"\")}</tr>`;\n  }\n\n  const tdElements = xpath.select(\"*[name()='td']\", trElementXml) as Document[];\n\n  if (tdElements.length > 0) {\n    const parsedTdElements = tdElements.map((tdElement) => parseTdElement(tdElement));\n    return `<tr>${parsedTdElements.join(\"\")}</tr>`;\n  }\n\n  return undefined;\n};\n","import { Narrative } from \"fhir/r4\";\nimport xpath from \"xpath\";\nimport { parseElement, wrappedInDiv } from \"./parse-elements\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getNarrativeForSection = (xmlData: Document): Narrative | undefined => {\n  const text = xpath.select1(\"*[name()='text']\", xmlData) as Document | undefined;\n  if (!text) return undefined;\n\n  const textElementsToParse = xpath.select(\"child::node()\", text) as Document[];\n\n  if (isEmpty(textElementsToParse)) return undefined;\n\n  const parsedTextElements = textElementsToParse.map(parseElement).filter(Boolean).join(\"\");\n\n  return {\n    status: \"generated\",\n    div: wrappedInDiv(parsedTextElements),\n  };\n};\n","import cx from \"classnames\";\nimport { ReactElement, ReactNode, useRef } from \"react\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\ntype ContainerProps = {\n  className?: string;\n  children?: ReactNode;\n};\n\ntype BodyContainerProps = ContainerProps & {\n  title?: string;\n  titleChildren?: ReactElement;\n};\n\ntype TitleContainerProps = ContainerProps & {\n  title?: string;\n};\n\ntype HeadingContainerProps = TitleContainerProps;\n\nexport function Wrapper({ className, children }: ContainerProps) {\n  return <div className={cx(\"ctw-container\", className)}>{children}</div>;\n}\n\nexport function StackedWrapper({ className, children, ...htmlProps }: ContainerProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n  const classNames = cx(className, {\n    \"ctw-stacked\": breakpoints.sm,\n  });\n\n  return (\n    <div className={classNames} ref={containerRef} {...htmlProps}>\n      {children}\n    </div>\n  );\n}\n\nexport function Heading({ className, title, children }: HeadingContainerProps) {\n  return (\n    <div className={cx(\"ctw-heading-container\", className)}>\n      {title && <div className=\"ctw-title\">{title}</div>}\n      {children}\n    </div>\n  );\n}\n\nexport function Title({ className, title, children }: TitleContainerProps) {\n  return (\n    <div className={cx(\"ctw-title-container\", className)}>\n      {title && <div className=\"ctw-title\">{title}</div>}\n      {children}\n    </div>\n  );\n}\n\nexport function Body({ className, title, titleChildren, children }: BodyContainerProps) {\n  const showTitleContainer = !!(title || titleChildren);\n  return (\n    <div className={cx(\"ctw-body-container\", className)}>\n      <div className=\"ctw-space-y-3\">\n        {showTitleContainer && <Title title={title}>{titleChildren}</Title>}\n        {children}\n      </div>\n    </div>\n  );\n}\n","import {\n  Component,\n  ComponentType,\n  createElement,\n  ErrorInfo,\n  ForwardedRef,\n  forwardRef,\n  ForwardRefExoticComponent,\n  PropsWithoutRef,\n  ReactNode,\n  RefAttributes,\n} from \"react\";\nimport * as CTWBox from \"@/components/core/ctw-box\";\nimport { pickBy } from \"@/utils/nodash\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\ninterface Props {\n  children?: ReactNode;\n  name?: string;\n  trackView?: boolean;\n}\n\ninterface State {\n  hasError: boolean;\n  error?: Error;\n  errorInfo?: ErrorInfo;\n}\n\n/**\n * Error Boundary for internal use.\n */\nexport class ErrorBoundary extends Component<Props, State> {\n  static getDerivedStateFromError(error: Error): State {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true, error };\n  }\n\n  state: State = {\n    hasError: false,\n  };\n\n  componentDidMount() {\n    const { props } = this;\n    if (props.name) {\n      Telemetry.logger.info(`Loaded component ${props.name}`);\n      if (props.trackView) {\n        Telemetry.trackView(props.name);\n      }\n    }\n  }\n\n  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n    const { props } = this;\n    Telemetry.countMetric(`component.${props.name}.failure`);\n    Telemetry.logger.error(\n      error.message,\n      pickBy({\n        ...errorInfo,\n        componentName: props.name,\n        error: {\n          stack: error.stack,\n        },\n      })\n    );\n  }\n\n  resetState = () => {\n    this.setState({ hasError: false });\n  };\n\n  public render() {\n    const { state, props } = this;\n\n    if (state.hasError) {\n      return (\n        <CTWBox.Wrapper>\n          <CTWBox.Body\n            title=\"Sorry, we have encountered an error.\"\n            className=\"ctw-flex ctw-items-center ctw-justify-between\"\n          >\n            <div className=\"ctw-px-5 ctw-space-y-2\">\n              <p>{state.error?.message || \"Unknown\"}</p>\n              <button\n                type=\"button\"\n                className=\"ctw-btn-primary ctw-capitalize\"\n                onClick={this.resetState}\n              >\n                Refresh component\n              </button>\n            </div>\n          </CTWBox.Body>\n        </CTWBox.Wrapper>\n      );\n    }\n\n    return props.children;\n  }\n}\n\nexport function withErrorBoundary<CProps extends object>(\n  component: ComponentType<CProps>,\n  name?: string,\n  trackView = true\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): ForwardRefExoticComponent<PropsWithoutRef<CProps> & RefAttributes<any>> {\n  const Wrapped = forwardRef<ComponentType<CProps>, CProps>(\n    (props: CProps, ref: ForwardedRef<ComponentType<CProps>>) =>\n      createElement(ErrorBoundary, { name, trackView }, createElement(component, { ...props, ref }))\n  );\n\n  // Format for display in DevTools\n  Wrapped.displayName = `withErrorBoundary(${name})`;\n\n  return Wrapped;\n}\n","import xpath from \"xpath\";\nimport { DocumentDetails } from \"./components/DocumentDetails\";\nimport { Header } from \"./components/Header/Header\";\nimport { Section, SectionContainer } from \"./components/Section/Section\";\nimport { getNarrativeForSection } from \"./helpers/sectionNarrative/get-section-narrative\";\nimport { SectionType } from \"./types\";\nimport { EmptyNotes } from \"../../document/helpers/empty-notes\";\nimport { TABLE_OF_CONTENT_ID } from \"../constants\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { PatientModel } from \"@/fhir/models\";\n\ntype CcdaViewerComponentProps = {\n  document: Document;\n  overridePatient: PatientModel | undefined;\n};\n\nconst sectionToUseSectionNarrative = [\n  \"Progress Notes\",\n  \"Patient Instructions\",\n  \"ED Notes\",\n  \"Discharge Instructions\",\n];\n\nexport const CcdaViewerComponent = ({\n  document,\n  overridePatient,\n}: CcdaViewerComponentProps): JSX.Element => {\n  const sections = xpath.select(\n    \"//*[name()='component']/*[name()='section']\",\n    document,\n  ) as Document[];\n\n  const texts: SectionType[] = sections.map((section, index) => {\n    const title = String(xpath.select1(\"string(*[name()='title'])\", section));\n    let isEmpty = false;\n    const id = `${title}-${index}`; // This way we can handle multiple sections with the same title.\n    let humanReadable = xpath.select1(`*[name()='text']`, section) as Element | null;\n\n    const textContent = humanReadable?.textContent;\n\n    // Checks if the textContent is empty or contains a substring from EmptyNotes\n    if (textContent && textContent.length < 500) {\n      isEmpty = EmptyNotes.some(\n        (emptyNoteStr) =>\n          textContent.length < 500 && textContent.toLowerCase().includes(emptyNoteStr),\n      );\n    }\n\n    if (sectionToUseSectionNarrative.includes(title)) {\n      const sectionNarrative = getNarrativeForSection(section);\n      if (!sectionNarrative) {\n        return { title, humanReadable, id, isEmpty };\n      }\n\n      humanReadable = sectionNarrative.div as unknown as Element;\n    }\n\n    return { title, humanReadable, id, isEmpty };\n  });\n\n  return (\n    <div className=\"print:ctw-min-h-full print:ctw-overflow-auto\" id=\"ccda-viewer\">\n      <Header document={document} sections={texts} overridePatient={overridePatient} />\n      <div className=\"ctw-flex ctw-flex-col\">\n        {texts.map(({ title, humanReadable, id, isEmpty }) => (\n          <Section\n            key={`el-text-${id}`}\n            title={title}\n            id={id}\n            humanReadable={humanReadable}\n            isEmpty={isEmpty}\n          />\n        ))}\n      </div>\n      <SectionContainer\n        title=\"Demographic Details\"\n        id=\"demographic-details\"\n        tableOfContentsId={TABLE_OF_CONTENT_ID}\n      >\n        <DocumentDetails document={document} />\n      </SectionContainer>\n    </div>\n  );\n};\n\nexport const CcdaViewer = withErrorBoundary(CcdaViewerComponent);\n","import { ModifiedAddress } from \"../types\";\nimport { capitalize, isArray, isEmpty } from \"@/utils/nodash\";\n\nconst addressParser = (addr: ModifiedAddress) => {\n  if (addr.text) return addr.text;\n  let result = \"\";\n\n  result += addr.use ? `${capitalize(addr.use)}: ` : \"\";\n  result += !isEmpty(addr.line) ? `${addr.line?.join(\"\\n\")}\\n` : \"\";\n  result += addr.city ? `${addr.city}, ` : \"\";\n  result += addr.state ? `${addr.state} ` : \"\";\n  result += addr.postalCode || \"\";\n  result += addr.country ? `\\n${addr.country}` : \"\";\n\n  return result;\n};\n\nexport const displayForAddress = (address: ModifiedAddress | ModifiedAddress[]): string => {\n  if (isEmpty(address)) return \"\";\n\n  if (isArray(address)) return address.map(addressParser).join(\"\\n\");\n\n  return addressParser(address);\n};\n","import { ModifiedHumanName } from \"../types\";\nimport { isArray, isEmpty } from \"@/utils/nodash\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isHumanNameArray(data: any): data is ModifiedHumanName[] {\n  return isArray(data) && data.every((name) => typeof name === \"object\");\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isStringArray(data: any): data is string[] {\n  return isArray(data) && data.every((name) => typeof name === \"string\");\n}\n\nconst nameParser = (name: ModifiedHumanName) => {\n  if (name.text) return name.text;\n  let displayName = \"\";\n  if (name.given && name.given.length > 0) {\n    displayName = name.given.join(\" \");\n    if (name.family) displayName = `${displayName} ${name.family}`;\n  }\n  if (name.prefix && name.prefix.length > 0) {\n    displayName = `${name.prefix.join(\" \")} ${displayName}`;\n  }\n  return displayName;\n};\n\nexport const displayForName = (\n  humanName: ModifiedHumanName[] | ModifiedHumanName | string | string[]\n): string => {\n  if (isEmpty(humanName)) return \"\";\n\n  if (typeof humanName === \"string\") return humanName;\n\n  if (isStringArray(humanName)) {\n    return humanName.reduce((acc, val, index) => {\n      const withNewLine = index === 0 ? \"\" : \"\\n\";\n      return `${acc}${withNewLine}${val}`;\n    }, \"\");\n  }\n\n  if (isHumanNameArray(humanName)) return humanName.map(nameParser).join(\", \");\n\n  return nameParser(humanName);\n};\n","import { ModifiedContactPoint } from \"../types\";\nimport { capitalize, isArray, isEmpty } from \"@/utils/nodash\";\n\nconst telecomParser = ({ use, system, value }: ModifiedContactPoint) => {\n  const withUse = use ? ` (${use})` : \"\";\n  const withSystem = system ? `${capitalize(system)}${withUse}:` : \"\";\n  return `${withSystem} ${value}`.trim();\n};\n\nexport const displayForTelecom = (\n  telecom: ModifiedContactPoint | ModifiedContactPoint[]\n): string => {\n  if (isEmpty(telecom)) return \"\";\n\n  if (isArray(telecom)) return telecom.map(telecomParser).join(\"\\n\");\n\n  return telecomParser(telecom);\n};\n","import xpath from \"xpath\";\nimport { displayForAddress } from \"./displayForAddress\";\nimport { ModifiedAddress } from \"../types\";\nimport { isArray, map } from \"@/utils/nodash\";\n\nexport const addressUseMap: Record<string, string> = {\n  BAD: \"bad\",\n  DIR: \"direct\",\n  H: \"home\",\n  HP: \"primary home\",\n  HV: \"vacation home\",\n  PHYS: \"physical\",\n  PST: \"postal\",\n  PUB: \"public\",\n  TMP: \"temporary\",\n  WP: \"work\",\n  CONF: \"confidential\",\n};\n\nexport const getAddress = (address: Document | Document[] | undefined): string => {\n  if (!address) return \"\";\n\n  const parser = (addressXml: Document) => {\n    const use = String(xpath.select1(\"string(@use)\", addressXml));\n\n    const addr: ModifiedAddress = {\n      line: map(xpath.select(\"*[name()='streetAddressLine']\", addressXml) as Document[], (l) =>\n        String(xpath.select(\"string(text())\", l))\n      ).filter(Boolean),\n      city: String(xpath.select(\"string(*[name()='city'])\", addressXml)),\n      state: String(xpath.select(\"string(*[name()='state'])\", addressXml)),\n      postalCode: String(xpath.select(\"string(*[name()='postalCode'])\", addressXml)),\n      country: String(xpath.select(\"string(*[name()='country'])\", addressXml)),\n      use: addressUseMap[use],\n    };\n\n    return displayForAddress(addr);\n  };\n\n  if (isArray(address)) return address.map(parser).join(\"\\n\");\n\n  return parser(address);\n};\n","import xpath from \"xpath\";\nimport { displayForTelecom } from \"./displayForTelecom\";\nimport { ModifiedContactPoint } from \"../types\";\nimport { isArray } from \"@/utils/nodash\";\n\nexport const contactPointUseMap: Record<string, string> = {\n  BAD: \"bad\",\n  CONF: \"confidential\",\n  OLD: \"old\",\n  H: \"home\",\n  HP: \"primary home\",\n  HV: \"vacation Home\",\n  TMP: \"temporary\",\n  WP: \"work\",\n  DIR: \"direct\",\n  PUB: \"public\",\n  AS: \"answering service\",\n  EC: \"emergency:\",\n  MC: \"mobile\",\n  PG: \"pager\",\n};\n\nexport const contactPointTelecomMap: Record<string, string> = {\n  tel: \"phone\",\n  mailto: \"email\",\n};\n\nexport const getTelecom = (telecom?: Document | Document[]): string => {\n  if (!telecom) return \"\";\n\n  const parser = (telecomXml: Document) => {\n    const valueFromTag = String(xpath.select1(\"string(@value)\", telecomXml));\n\n    const splitValue = valueFromTag.split(\":\");\n\n    let system;\n    let value;\n    if (splitValue.length === 2) [system, value] = splitValue;\n\n    if (splitValue.length === 1) [value] = splitValue;\n\n    if (!value) return \"\";\n\n    const backupSystem = value.includes(\"@\")\n      ? contactPointTelecomMap.mailto\n      : contactPointTelecomMap.tel;\n\n    const finalSystem = contactPointTelecomMap[system as string] || backupSystem;\n\n    const contactPoint: ModifiedContactPoint = {\n      system: finalSystem,\n      value,\n      use: contactPointUseMap[String(xpath.select1(\"string(@use)\", telecomXml))],\n    };\n    return displayForTelecom(contactPoint);\n  };\n\n  if (isArray(telecom)) return telecom.map(parser).join(\"\\n\");\n\n  return parser(telecom);\n};\n","import { getAddress } from \"./getAddress\";\nimport { getTelecom } from \"./getTelecom\";\n\nexport const getContactDetails = (\n  addressXml: Document | Document[],\n  telecomXml: Document | Document[]\n): string => {\n  const address = getAddress(addressXml);\n  const telecom = getTelecom(telecomXml);\n\n  return `${address || \"\"}${address && telecom ? \"\\n\" : \"\"}${telecom || \"\"}`;\n};\n","import xpath from \"xpath\";\nimport { displayForName } from \"./displayForName\";\nimport { ModifiedHumanName } from \"../types\";\nimport { isArray, map } from \"@/utils/nodash\";\n\nconst humanNameUseMap: Record<string, string> = {\n  A: \"Artist/Stage\",\n  ABC: \"Alphabetic\",\n  ASGN: \"Assigned\",\n  C: \"License\",\n  I: \"Indigenous/Tribal\",\n  IDE: \"Ideographic\",\n  L: \"Legal\",\n  P: \"Pseudonym\",\n  PHON: \"Phonetic\",\n  R: \"Religious\",\n  SNDX: \"Soundex\",\n  SRCH: \"Search\",\n  SYL: \"Syllabic\",\n};\n\nexport const getHumanName = (name?: Document | Document[]): string => {\n  if (!name) return \"\";\n\n  const parser = (nameXml: Document) => {\n    const patientParsedName: ModifiedHumanName = {\n      use: humanNameUseMap[String(xpath.select(\"string(@use)\", nameXml))],\n      given: map(xpath.select(\"(*[name()='given'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n      family: String(xpath.select1(\"string(*[name()='family']/text())\", nameXml)),\n      prefix: map(xpath.select(\"(*[name()='prefix'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n      suffix: map(xpath.select(\"(*[name()='suffix'])\", nameXml) as Document[], (n) =>\n        String(xpath.select1(\"string(text())\", n))\n      ),\n    };\n    return displayForName(patientParsedName);\n  };\n\n  if (isArray(name)) return name.map(parser).join(\"\\n\");\n\n  return parser(name);\n};\n","import xpath from \"xpath\";\n\nexport const getId = (id: Document | undefined): string => {\n  if (!id) return \"\";\n\n  const rootValue = String(xpath.select1(\"string(@root)\", id));\n\n  const extensionValue = String(xpath.select1(\"string(@extension)\", id));\n\n  return `${extensionValue}${extensionValue ? \" (\" : \"\"}${rootValue}${extensionValue ? \")\" : \"\"}`;\n};\n","import { isFinite } from \"@/utils/nodash\";\n\n/**\n * Estimates the index of the timezone sign counting from the end of the string and the type of the sign itself (\"-\" or \"+\")\n *\n *\n * @param date Raw date from C-CDA\n * @returns Index of the timezone signs from the end and sign timezone itself\n *\n */\nconst getIndexFromEnd = (date: string): { index: number; timezoneSign?: \"+\" | \"-\" } => {\n  const rawDate = date.replace(/:/g, \"\");\n  const plusSign = rawDate.lastIndexOf(\"+\");\n  const minusSign = rawDate.lastIndexOf(\"-\");\n\n  if (plusSign > 0) {\n    // need to subtract 1 to count the array from the end from 0 index\n    return { index: rawDate.length - plusSign - 1, timezoneSign: \"+\" };\n  }\n\n  if (minusSign > 0) {\n    // check if \"-\" sign is for timezone, it is needed to correctly parse such date 2013-02-2209\n    const signOnThreePlacesLeft = rawDate[minusSign - 3];\n    if (\n      isFinite(Number(signOnThreePlacesLeft)) ||\n      signOnThreePlacesLeft === \"T\" // needed to correctly parse such date 2013-02-22T09-05:00\n    ) {\n      // need to subtract 1 to count the array from the end from 0 index\n      return { index: rawDate.length - minusSign - 1, timezoneSign: \"-\" };\n    }\n\n    return { index: -1 };\n  }\n  return { index: -1 };\n};\n\n/**\n * Checks if fragment of the date is valid.\n *\n *\n * @param fragment Fragment of the date (year, month, day, hour, minute, second)\n * @returns True if valid, otherwise false\n *\n */\nconst isCorrectValue = (fragment: string) =>\n  fragment && fragment.length > 1 && fragment.split(\"\").every((char) => isFinite(Number(char)));\n\nconst constructISOString = ({\n  year,\n  month,\n  day,\n  hour,\n  minute,\n  second,\n  timezoneHour,\n  timezoneMinute,\n  timezoneSign,\n}: {\n  year: string;\n  month: string;\n  day: string;\n  hour: string;\n  minute: string;\n  second: string;\n  timezoneHour: string;\n  timezoneMinute: string;\n  timezoneSign: string | undefined;\n}): string => {\n  let result = \"\";\n\n  if (isCorrectValue(year)) {\n    result += year;\n    if (isCorrectValue(month)) {\n      result += `-${month}`;\n      if (isCorrectValue(day)) {\n        result += `-${day}`;\n        if (isCorrectValue(hour)) {\n          result += `T${hour}`;\n\n          if (isCorrectValue(minute)) result += `:${minute}`;\n          else result += \":00\";\n\n          if (isCorrectValue(second)) result += `:${second}`;\n          else result += \":00\";\n\n          if (timezoneSign && isCorrectValue(timezoneHour)) {\n            result += `${timezoneSign}${timezoneHour}`;\n            if (isCorrectValue(timezoneMinute)) result += `:${timezoneMinute}`;\n            else result += \":00\";\n          } else result += \"-00:00\";\n        }\n      }\n    }\n  }\n  return result;\n};\n\n/**\n * Convert a raw date from C-CDA to ISOString.\n *\n *\n * @param rawDate Raw date from C-CDA\n * @returns Date in ISOString format\n *\n */\nexport const parseToISOString = (rawDate: string): string => {\n  if (!rawDate) return \"\";\n\n  const { index, timezoneSign } = getIndexFromEnd(rawDate);\n  // delete all junk that can be in date in C-CDA document\n  let date = rawDate\n    .replace(/T/g, \"\")\n    .replace(/-/g, \"\")\n    // plus sign can be only once, no need for regexp\n    .replace(\"+\", \"\")\n    .replace(/:/g, \"\");\n\n  let timezone = \"\";\n\n  // if sign index from the end is equal to 4 (-0500) or 2 (-05) and date has at least hour it means that there is a timezone\n  if ((index === 4 || index === 2) && date.length > 9) {\n    timezone = date.substring(date.length - index);\n    date = date.substring(0, date.length - index);\n  }\n\n  const year = date.slice(0, 4);\n  const month = date.slice(4, 6);\n  const day = date.slice(6, 8);\n  const hour = date.slice(8, 10);\n  const minute = date.slice(10, 12);\n  const second = date.slice(12, 14);\n\n  const timezoneHour = timezone.slice(0, 2);\n  const timezoneMinute = timezone.slice(2);\n\n  if (!day) return \"\";\n\n  return constructISOString({\n    year,\n    month,\n    day,\n    hour,\n    minute,\n    second,\n    timezoneHour,\n    timezoneMinute,\n    timezoneSign,\n  });\n};\n","import { isBefore, isEqual } from \"date-fns\";\nimport { Period } from \"fhir/r4\";\nimport xpath from \"xpath\";\nimport { parseToISOString } from \"./parseToISOString\";\n\nexport const getPeriod = (xmlData?: Document): Period => {\n  if (!xmlData) return {};\n\n  const low = String(xpath.select1(\"string(*[name()='low']/@value)\", xmlData));\n  const high = String(xpath.select1(\"string(*[name()='high']/@value)\", xmlData));\n\n  if (!low && !high) return {};\n\n  if (low && !high) {\n    return {\n      start: parseToISOString(low),\n    };\n  }\n\n  if (!low && high) {\n    return {\n      end: parseToISOString(high),\n    };\n  }\n\n  let start = parseToISOString(low);\n  let end = parseToISOString(high);\n\n  // it indicates that at least on of the dates has minutes so both have to be parsed to iso string\n  if (start.includes(\"T\") || end.includes(\"T\")) {\n    start = parseToISOString(start);\n    end = parseToISOString(end);\n  }\n\n  if (isBefore(new Date(start), new Date(end)) || isEqual(new Date(start), new Date(end))) {\n    return { start, end };\n  }\n\n  return { start };\n};\n","import { escapeRegExp, identity, isArray } from \"@/utils/nodash\";\n\nconst replaceInXML = (\n  xmlString: string,\n  toReplace: string | string[],\n  toReplaceWith: string,\n  escape = true\n): string => {\n  if (isArray(toReplace)) {\n    return toReplace.reduce((acc, val) => replaceInXML(acc, val, toReplaceWith), xmlString);\n  }\n\n  const modify: (_: string) => string = escape ? escapeRegExp : identity;\n  return xmlString.replace(new RegExp(modify(toReplace), \"g\"), toReplaceWith);\n};\n\nconst replaceTag = (xmlString: string, oldTag: string, newTag: string) => {\n  const oldTags = [`</${oldTag}>`, `<${oldTag}>`, `</${oldTag}`, `<${oldTag}`];\n  const newTags = [`</${newTag}>`, `<${newTag}>`, `</${newTag}`, `<${newTag}`];\n\n  return oldTags.reduce(\n    (acc, _, index) => replaceInXML(acc, oldTags[index], newTags[index]),\n    xmlString\n  );\n};\n\nexport const fixHtml = (xmlData: Document): string => {\n  let fixedHtml = xmlData.toString();\n\n  // these are not needed at all\n  fixedHtml = replaceInXML(\n    fixedHtml,\n    [\n      \"<list/>\",\n      \"<item/>\",\n      \"<content/>\",\n      \"<paragraph/>\",\n      \"<section/>\",\n      \"<br/>\",\n      '<text xmlns=\"urn:hl7-org:v3\">',\n      \"<text />\",\n      \"<text/>\",\n    ],\n    \"\"\n  );\n\n  // there can be more strange attributes in C-CDA that need to be changed\n  fixedHtml = replaceInXML(fixedHtml, ' styleCode=\"(.*?)\"', \"\", false);\n\n  fixedHtml = replaceTag(fixedHtml, \"section\", \"div\");\n  fixedHtml = replaceTag(fixedHtml, \"list\", \"ul\");\n  fixedHtml = replaceTag(fixedHtml, \"item\", \"li\");\n  fixedHtml = replaceTag(fixedHtml, \"content\", \"div\");\n  fixedHtml = replaceTag(fixedHtml, \"paragraph\", \"p\");\n\n  return fixedHtml;\n};\n","import { format } from \"date-fns\";\n\nexport const formatDate = (isoDate: string | undefined, formatString = \"MMMM dd, yyyy\"): string => {\n  if (!isoDate) return \"\";\n  const [date, time = \"\"] = isoDate.split(\"T\");\n\n  return (\n    format(new Date(date), formatString) +\n    (time.split(\"\").some((char) => Number(char) > 0) ? `, ${time}` : \"\")\n  );\n};\n","type GeneralInfo = {\n  name: string;\n  contactDetails: string;\n};\n\ntype ExtendedGeneralInfo = GeneralInfo & {\n  relationship?: string;\n  time?: string;\n  functionCode?: string;\n};\n\ntype GeneralInfoWithOrg = GeneralInfo & {\n  organization: GeneralInfo;\n};\n\nexport const isGeneralInfoExist = (item: GeneralInfo | undefined): item is GeneralInfo => !!item;\n\nexport const isExtendedGeneralInfoExist = (\n  item: ExtendedGeneralInfo | undefined\n): item is ExtendedGeneralInfo => !!item;\n\nexport type { GeneralInfo, ExtendedGeneralInfo, GeneralInfoWithOrg };\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName, parseToISOString } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthenticatorData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const authenticators = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='authenticator']\",\n    document\n  ) as Document[];\n  if (isEmpty(authenticators)) return undefined;\n  return authenticators\n    .map((authenticator): ExtendedGeneralInfo | undefined => {\n      const assignedEntity = xpath.select1(\"*[name()='assignedEntity']\", authenticator) as\n        | Document\n        | undefined;\n      if (!assignedEntity) return undefined;\n      const assignedPerson = xpath.select1(\n        \"*[name()='assignedPerson']\",\n        assignedEntity\n      ) as Document;\n      const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n      const contactDetails = getContactDetails(\n        xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n        xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n      );\n\n      const time = parseToISOString(\n        String(xpath.select1(\"string(*[name()='time']/@value)\", authenticator))\n      );\n      return { name, contactDetails, time };\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","/* eslint-disable react/no-array-index-key */\nimport React from \"react\";\nimport { TableInfo } from \"../../types\";\nimport \"../../../styles.scss\";\n\ntype TdProps = {\n  dataChunk: TableInfo[];\n  indexKey: number;\n  chunkSize?: 2 | 3;\n};\nexport const BasicRow = ({ dataChunk, indexKey, chunkSize }: TdProps): JSX.Element | null => {\n  if (!dataChunk[0].value && !dataChunk[1]?.value && !dataChunk[2]?.value) {\n    return null;\n  }\n\n  let last: TableInfo | null = null;\n  let newDataChunk = dataChunk;\n  if (chunkSize === 3) {\n    newDataChunk = dataChunk.slice(0, 2);\n    [last] = dataChunk.slice(2);\n  }\n\n  return (\n    <>\n      <tr>\n        {newDataChunk.map((singleData, index) => {\n          if (!singleData.value) return null;\n          let colSpan = 1;\n          if (\n            (index === 0 && (!newDataChunk[index + 1] || !newDataChunk[index + 1].value)) ||\n            (index === 1 && (!newDataChunk[index - 1] || !newDataChunk[index - 1].value))\n          ) {\n            colSpan = 3;\n          }\n\n          return (\n            <React.Fragment\n              key={`${newDataChunk[0].label}-${String(\n                newDataChunk[0].value\n              )}-${index}-${indexKey}-${newDataChunk[1]?.label || \"\"}-${\n                newDataChunk[1]?.value || \"\"\n              }`}\n            >\n              <td\n                className=\"ctw-ccda-common-td1\"\n                rowSpan={last && last.value && index === 0 ? 2 : 1}\n              >\n                {singleData.label.replace(/:/g, \"\")}\n              </td>\n              <td\n                className=\"ctw-ccda-common-td2\"\n                colSpan={colSpan}\n                rowSpan={last && last.value && index === 0 ? 2 : 1}\n              >\n                {singleData.value}\n              </td>\n            </React.Fragment>\n          );\n        })}\n      </tr>\n      {last && last.value && (\n        <tr>\n          <td className=\"ctw-ccda-common-td1\">{last.label.replace(/:/g, \"\")}</td>\n          <td className=\"ctw-ccda-common-td2\">{last.value}</td>\n        </tr>\n      )}\n    </>\n  );\n};\n","/* eslint-disable react/no-array-index-key */\nimport React from \"react\";\nimport { TableInfo } from \"../../types\";\nimport \"../../../styles.scss\";\n\ntype TdProps = {\n  tuple: [TableInfo, TableInfo];\n  indexKey: number;\n};\nexport const TupleRow = ({ tuple, indexKey }: TdProps): JSX.Element | null => {\n  if (!tuple[0].value && !tuple[1].value) return null;\n\n  return (\n    <tr>\n      {tuple.map((singleData, index) => {\n        if (!singleData.value) return null;\n        let colSpan = 1;\n        if ((index === 0 && !tuple[1].value) || (index === 1 && !tuple[0].value)) {\n          colSpan = 3;\n        }\n\n        return (\n          <React.Fragment\n            key={`${tuple[0].label}-${tuple[0].value}-${index}-${indexKey}-${\n              tuple[1].label || \"\"\n            }-${tuple[1].value}`}\n          >\n            <td className=\"ctw-ccda-common-td1\">{singleData.label.replace(/:/g, \"\")}</td>\n            <td className=\"ctw-ccda-common-td2\" colSpan={colSpan}>\n              {singleData.value}\n            </td>\n          </React.Fragment>\n        );\n      })}\n    </tr>\n  );\n};\n","/* eslint-disable react/no-array-index-key */\nimport { BasicRow } from \"./BasicRow\";\nimport { TupleRow } from \"./TupleRow\";\nimport { TableInfo } from \"../../types\";\nimport { chunk, isArray, partition } from \"@/utils/nodash\";\nimport \"../../../styles.scss\";\n\ntype TableProps = {\n  data: (TableInfo | [TableInfo, TableInfo])[];\n  chunkSize?: 2 | 3;\n};\n\nexport const Table = ({ data, chunkSize = 2 }: TableProps): JSX.Element => {\n  const [normalEntries, tupleEntries] = partition(data, (d) => !isArray(d)) as [\n    TableInfo[],\n    [TableInfo, TableInfo][]\n  ];\n\n  const entries = chunk(normalEntries, chunkSize);\n\n  return (\n    <table className=\"ctw-ccda-common-table\">\n      <tbody>\n        {entries.map((dataChunk: TableInfo[], index) => (\n          <BasicRow\n            key={`${dataChunk[0].label}-${index}`}\n            dataChunk={dataChunk}\n            chunkSize={chunkSize}\n            indexKey={index}\n          />\n        ))}\n        {tupleEntries.map((tuple: [TableInfo, TableInfo], index) => (\n          <TupleRow\n            key={`${tuple[0].label}-${tuple[1].label}-${index}`}\n            tuple={tuple}\n            indexKey={index}\n          />\n        ))}\n      </tbody>\n    </table>\n  );\n};\n","import { getAuthenticatorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Authenticator = ({ document }: DocumentOnlyProps): JSX.Element | null => {\n  const authenticators = getAuthenticatorData(document);\n\n  if (!authenticators || isEmpty(authenticators)) return null;\n\n  const finalData = authenticators.flatMap((authenticator) => [\n    {\n      label: \"Authenticator\",\n      value: `${authenticator.name || \"Unknown\"}${\n        authenticator.time ? ` signed at ${authenticator.time}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: authenticator.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getHumanName, parseToISOString } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthor = (document: Document): Record<string, LabelValueType[]> | undefined => {\n  const authors = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='author']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(authors)) return undefined;\n\n  const result = authors.map((author): LabelValueType[] => {\n    const personName = xpath.select1(\n      \"*[name()='assignedAuthor']/*[name()='assignedPerson']/*[name()='name']\",\n      author\n    ) as Document | undefined;\n    const deviceName = xpath.select1(\n      \"*[name()='assignedAuthor']/*[name()='assignedAuthoringDevice']\",\n      author\n    ) as Document | undefined;\n\n    let name = \"\";\n\n    if (personName) name = getHumanName(personName);\n    else if (deviceName) {\n      const manufacturerModelName = String(\n        xpath.select1(\"string(*[name()='manufacturerModelName'])\", deviceName)\n      );\n      const softwareName = String(xpath.select1(\"string(*[name()='softwareName'])\", deviceName));\n\n      name = [manufacturerModelName, softwareName].filter(Boolean).join(\"; \");\n    }\n    const representedOrganizationName = String(\n      xpath.select1(\n        \"string(*[name()='assignedAuthor']/*[name()='representedOrganization']/*[name()='name'])\",\n        author\n      )\n    );\n\n    const authoredOn = parseToISOString(String(xpath.select1(\"string(*[name()='time'])\", author)));\n\n    return [\n      { label: \"Name:\", value: name },\n      { label: \"Organization:\", value: representedOrganizationName },\n      { label: \"Authored on\", value: authoredOn },\n    ];\n  });\n\n  return result.reduce((acc, val, index) => ({ ...acc, [`author${index + 1}`]: val }), {});\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { GeneralInfoWithOrg, LabelValueType } from \"../../types\";\nimport { getAuthor as getAuthorDataFromHeader } from \"../Header/data/getAuthor\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getAuthorData = (document: Document): GeneralInfoWithOrg[] | undefined => {\n  const authorXmls = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='author']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(authorXmls)) return undefined;\n\n  const authors = getAuthorDataFromHeader(document) as Record<string, LabelValueType[]>; // we can cast because we are sure that authors exist\n\n  return authorXmls.map((authorXml, index) => {\n    const assignedAuthor = xpath.select1(\"*[name()='assignedAuthor']\", authorXml) as Document;\n\n    const authorContactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", assignedAuthor) as Document[],\n      xpath.select(\"*[name()='telecom']\", assignedAuthor) as Document[]\n    );\n\n    const representedOrganization = xpath.select1(\n      \"*[name()='representedOrganization']\",\n      assignedAuthor\n    ) as Document | undefined;\n\n    const result: GeneralInfoWithOrg = {\n      name: authors[`author${index + 1}`][0].value,\n      contactDetails: authorContactDetails,\n      organization: {\n        name: authors[`author${index + 1}`][1].value,\n        contactDetails: \"\",\n      },\n    };\n\n    if (representedOrganization) {\n      const organizationContactDetails = getContactDetails(\n        xpath.select(\"*[name()='addr']\", representedOrganization) as Document[],\n        xpath.select(\"*[name()='telecom']\", representedOrganization) as Document[]\n      );\n\n      return {\n        ...result,\n        organization: {\n          ...result.organization,\n          contactDetails: organizationContactDetails,\n        },\n      };\n    }\n\n    return result;\n  });\n};\n","import { getAuthorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Author = ({ document }: DocumentOnlyProps) => {\n  const authors = getAuthorData(document);\n\n  if (!authors || isEmpty(authors)) return null;\n\n  const finalData = authors.flatMap((author) => [\n    {\n      label: \"Author\",\n      value: `${author.name || \"Unknown\"}${\n        author.organization.name ? `, Organization: ${author.organization.name}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: author.contactDetails,\n    },\n    {\n      label: \"Contact Details (Organization)\",\n      value: author.organization.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} chunkSize={3} />;\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getConsent = (document: Document): Record<string, LabelValueType[]> | undefined => {\n  const consents = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='authorization']/*[name()='consent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(consents)) return undefined;\n\n  const result = consents.map((consent) => {\n    const id = getId(xpath.select1(\"*[name()='id']\", consent) as Document);\n    const code = String(xpath.select1(\"string(*[name()='code']/@displayName)\", consent));\n    const status = String(xpath.select1(\"string(*[name()='statusCode']/@code)\", consent));\n    return [\n      { label: \"ID:\", value: id },\n      { label: \"Code:\", value: code },\n      { label: \"Status:\", value: status },\n    ];\n  });\n\n  return result.reduce((acc, order, index) => ({ ...acc, [`consent${index + 1}`]: order }), {});\n};\n","import { getConsent as getConsentDataFromHeader } from \"../Header/data/getConsent\";\n\nexport const getAuthorizationData = (document: Document) => {\n  const inFulfillmentOf = getConsentDataFromHeader(document);\n\n  return Object.values(inFulfillmentOf || {});\n};\n","import { getAuthorizationData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Authorization = ({ document }: DocumentOnlyProps) => {\n  const authorizations = getAuthorizationData(document);\n\n  if (isEmpty(authorizations)) return null;\n\n  const finalData = authorizations.flatMap((authorization) => [\n    {\n      label: \"Consent\",\n      value: `Order: ${authorization[0].value || \"Unknown\"}, ${\n        authorization[1].value || \"Unknown\"\n      }, ${authorization[2].value || \"Unknown\"}`,\n    },\n    { label: \"\", value: \"\" },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { GeneralInfo } from \"../../types\";\n\nexport const getCustodianData = (document: Document): GeneralInfo | undefined => {\n  const representedCustodianOrganization = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']\",\n    document\n  ) as Document | undefined;\n\n  if (!representedCustodianOrganization) return undefined;\n\n  const name = String(xpath.select1(\"string(*[name()='name'])\", representedCustodianOrganization));\n\n  const contactDetails = getContactDetails(\n    xpath.select1(\n      \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']/*[name()='addr']\",\n      document\n    ) as Document,\n    xpath.select1(\n      \"*[name()='ClinicalDocument']/*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']/*[name()='telecom']\",\n      document\n    ) as Document\n  );\n\n  return { name, contactDetails };\n};\n","import { getCustodianData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Custodian = ({ document }: DocumentOnlyProps) => {\n  const custodian = getCustodianData(document);\n\n  if (!custodian) return null;\n\n  const { name, contactDetails } = custodian;\n  const finalData = [\n    {\n      label: \"Custodian\",\n      value: name,\n    },\n    {\n      label: \"Contact Details\",\n      value: contactDetails,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName } from \"../../helpers\";\nimport { GeneralInfo } from \"../../types\";\n\nexport const getDataEntererData = (document: Document): GeneralInfo | undefined => {\n  const dataEnterer = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='dataEnterer']/*[name()='assignedEntity']\",\n    document\n  ) as Document | undefined;\n\n  if (!dataEnterer) return undefined;\n\n  const assignedPerson = xpath.select1(\"*[name()='assignedPerson']\", dataEnterer) as Document;\n\n  const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", dataEnterer) as Document[],\n    xpath.select(\"*[name()='telecom']\", dataEnterer) as Document[]\n  );\n\n  return { name, contactDetails };\n};\n","import { getDataEntererData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const DataEnterer = ({ document }: DocumentOnlyProps) => {\n  const dataEnterer = getDataEntererData(document);\n\n  if (!dataEnterer) return null;\n\n  const { name, contactDetails } = dataEnterer;\n  const finalData = [\n    {\n      label: \"Data Enterer\",\n      value: name,\n    },\n    {\n      label: \"Contact Details\",\n      value: contactDetails,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getId, parseToISOString } from \"../../helpers\";\n\nconst confidentialityCodeMap: Record<string, string> = {\n  N: \"normal\",\n  R: \"restricted\",\n  V: \"very restricted\",\n};\nexport const getDocumentData = (document: Document) => {\n  const id = getId(\n    xpath.select1(\"*[name()='ClinicalDocument']/*[name()='id']\", document) as Document\n  );\n\n  const effectiveTimeValue = parseToISOString(\n    String(\n      xpath.select1(\n        \"string(*[name()='ClinicalDocument']/*[name()='effectiveTime']/@value)\",\n        document\n      )\n    )\n  );\n\n  const createdOn = formatDate(effectiveTimeValue);\n\n  const version = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='versionNumber']/@value)\", document)\n  );\n  const setId = getId(\n    xpath.select1(\"*[name()='ClinicalDocument']/*[name()='setId']\", document) as Document\n  );\n  const confidentialityCode =\n    confidentialityCodeMap[\n      String(\n        xpath.select1(\n          \"string(*[name()='ClinicalDocument']/*[name()='confidentialityCode']/@code)\",\n          document\n        )\n      )\n    ];\n  const code = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='code']/@displayName)\", document)\n  );\n  const languageCode = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='languageCode']/@code)\", document)\n  );\n  return {\n    id,\n    createdOn,\n    version,\n    setId,\n    confidentialityCode,\n    code,\n    languageCode,\n  };\n};\n","import { getDocumentData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Document = ({ document }: DocumentOnlyProps) => {\n  const { id, createdOn, version, setId, confidentialityCode, code, languageCode } =\n    getDocumentData(document);\n\n  const finalData = [\n    {\n      label: \"Document\",\n      value: (\n        <>\n          <b>ID: </b>\n          {id}\n          {setId && (\n            <>\n              <br />\n              <b>Set ID: </b>\n              {setId}\n            </>\n          )}\n        </>\n      ),\n    },\n    {\n      label: \"Created on\",\n      value: createdOn,\n    },\n    {\n      label: \"Version\",\n      value: version || \"Unknown\",\n    },\n    {\n      label: \"Confidentiality\",\n      value: confidentialityCode,\n    },\n    {\n      label: \"Code\",\n      value: code,\n    },\n    {\n      label: \"Language\",\n      value: languageCode,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getHumanName, getPeriod } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getDocumentationOf = (\n  document: Document\n): Record<string, LabelValueType[]> | undefined => {\n  const serviceEvents = xpath.select(\n    \"//*[name()='documentationOf']/*[name()='serviceEvent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(serviceEvents)) return undefined;\n\n  const result = serviceEvents.map((serviceEvent) => {\n    const effectiveTime = xpath.select1(\"*[name()='effectiveTime']\", serviceEvent) as Document;\n\n    const period = getPeriod(effectiveTime);\n\n    const performerNames = xpath.select(\n      \"*[name()='performer']/*[name()='assignedEntity']/*[name()='assignedPerson']/*[name()='name']\",\n      serviceEvent\n    ) as Document[];\n\n    const performers = performerNames.map((performer) => getHumanName(performer));\n\n    return [\n      {\n        label: \"Date/Time:\",\n        value:\n          period.start || period.end\n            ? `from ${formatDate(period.start) || \"unknown\"} to ${\n                formatDate(period.end) || \"unknown\"\n              }`\n            : \"\",\n      },\n      ...performers.map((performer) => ({\n        label: \"Performer:\",\n        value: performer,\n      })),\n    ];\n  });\n\n  return result.reduce((acc, val, index) => ({ ...acc, [`documentationOf${index + 1}`]: val }), {});\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isGeneralInfoExist, LabelValueType } from \"../../types\";\nimport { getDocumentationOf as getDocumentationOfDataFromHeader } from \"../Header/data/getDocumentationOf\";\nimport { get, isEmpty } from \"@/utils/nodash\";\n\nexport const getDocumentationOfData = (\n  document: Document\n): { dateTime: string; finalPerformers: ExtendedGeneralInfo[] }[] | undefined => {\n  const serviceEventXmls = xpath.select(\n    \"//*[name()='documentationOf']/*[name()='serviceEvent']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(serviceEventXmls)) return undefined;\n\n  const documentationOfs = getDocumentationOfDataFromHeader(document) as Record<\n    string,\n    LabelValueType[]\n  >; // we can cast, it won't be undefined\n\n  return serviceEventXmls.map(\n    (serviceEventXml, index): { dateTime: string; finalPerformers: ExtendedGeneralInfo[] } => {\n      const performerXmls = xpath.select(\"*[name()='performer']\", serviceEventXml) as Document[];\n\n      const finalPerformers = performerXmls.map(\n        (performerXml, index2): ExtendedGeneralInfo | undefined => {\n          const functionCode = String(\n            xpath.select1(\"string(*[name()='functionCode']/@displayName)\", performerXml)\n          );\n          const name = get(\n            documentationOfs,\n            `documentationOf${index + 1}[${index2 + 1}].value`\n          ) as unknown as string; // rest elements are performers\n\n          const contactDetails = getContactDetails(\n            xpath.select(\"*[name()='assignedEntity']/*[name()='addr']\", performerXml) as Document[],\n            xpath.select(\n              \"*[name()='assignedEntity']/*[name()='telecom']\",\n              performerXml\n            ) as Document[]\n          );\n\n          if (!name && !functionCode && !contactDetails) return undefined;\n\n          return {\n            functionCode,\n            name,\n            contactDetails,\n          };\n        }\n      );\n\n      return {\n        dateTime: get(\n          documentationOfs,\n          `documentationOf${index + 1}[0].value`\n        ) as unknown as string, // first element is date time\n        finalPerformers: finalPerformers.filter(isGeneralInfoExist),\n      };\n    }\n  );\n};\n","import { getDocumentationOfData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const DocumentationOf = ({ document }: DocumentOnlyProps) => {\n  const documentationOfs = getDocumentationOfData(document);\n\n  if (!documentationOfs || isEmpty(documentationOfs)) return null;\n\n  const finalData = documentationOfs.flatMap((documentationOf) => [\n    { label: \"Documentation of - Date/Time\", value: documentationOf.dateTime },\n    { label: \"\", value: \"\" },\n    ...documentationOf.finalPerformers.flatMap((performer) => [\n      {\n        label: \"Performer\",\n        value: `${performer.name || \"Unknown\"}${\n          performer.functionCode ? ` - ${performer.functionCode}` : \"\"\n        }`,\n      },\n      { label: \"Contact Details\", value: performer.contactDetails },\n    ]),\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getId, getPeriod } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\n\nexport const getEncounter = (document: Document): LabelValueType[] | undefined => {\n  const encompassingEncounter = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='componentOf']/*[name()='encompassingEncounter']\",\n    document\n  ) as Document | undefined;\n\n  if (!encompassingEncounter) return undefined;\n\n  const id = getId(xpath.select1(\"*[name()='id']\", encompassingEncounter) as Document);\n\n  const type = String(\n    xpath.select1(\"string(*[name()='code']/@displayName)\", encompassingEncounter) as Document\n  );\n\n  const period = getPeriod(\n    xpath.select1(\"*[name()='effectiveTime']\", encompassingEncounter) as Document\n  );\n\n  return [\n    {\n      label: \"ID:\",\n      value: period.start || period.end || id ? id || \"Unknown\" : \"\",\n    },\n    { label: \"Type:\", value: type },\n    {\n      label: \"Date/Time:\",\n      value:\n        period.start || period.end\n          ? `from ${formatDate(period.start) || \"unknown\"} to ${\n              formatDate(period.end) || \"unknown\"\n            }`\n          : \"\",\n    },\n  ];\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../helpers\";\nimport { LabelValueType } from \"../../types\";\nimport { getEncounter } from \"../Header/data/getEncounter\";\n\nexport const getEncounterData = (document: Document) => {\n  const encompassingEncounter = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='componentOf']/*[name()='encompassingEncounter']\",\n    document\n  ) as Document | undefined;\n\n  if (!encompassingEncounter) return undefined;\n\n  const encounter = getEncounter(document) as LabelValueType[];\n\n  const dischargeDisposition = String(\n    xpath.select1(\n      \"string(*[name()='dischargeDispositionCode']/@displayName)\",\n      encompassingEncounter\n    )\n  );\n\n  const encounterLocation = getId(\n    xpath.select1(\n      \"*[name()='location']/*[name()='healthCareFacility']/*[name()='id']\",\n      encompassingEncounter\n    ) as Document\n  );\n\n  return {\n    id: encounter[0], // we now that they are returned in that order\n    type: encounter[1],\n    dateTime: encounter[2],\n    dischargeDisposition,\n    encounterLocation: encounterLocation ? `ID: ${encounterLocation}` : null,\n  };\n};\n","import { getEncounterData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const Encounter = ({ document }: DocumentOnlyProps) => {\n  const encounter = getEncounterData(document);\n\n  if (!encounter) return null;\n\n  const { dischargeDisposition, encounterLocation, id, type, dateTime } = encounter;\n\n  const finalData = [\n    {\n      label: \"Encounter\",\n      value:\n        dateTime.value || dischargeDisposition || encounterLocation || id.value ? (\n          <>\n            <b>ID: </b>\n            {id.value || \"Unknown\"}\n            {type.value && (\n              <>\n                <br />\n                <b>Type: </b>\n                {type.value}\n              </>\n            )}\n          </>\n        ) : null,\n    },\n    {\n      label: \"Date/Time\",\n      value: dateTime.value,\n    },\n    {\n      label: \"Discharge Disposition\",\n      value: dischargeDisposition,\n    },\n    {\n      label: \"Encounter Location\",\n      value: encounterLocation,\n    },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInformantData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const informants = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='informant']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(informants)) return undefined;\n\n  return informants\n    .map((informant): ExtendedGeneralInfo | undefined => {\n      const assignedEntity = xpath.select1(\"*[name()='assignedEntity']\", informant) as\n        | Document\n        | undefined;\n\n      if (assignedEntity) {\n        const assignedPerson = xpath.select1(\n          \"*[name()='assignedPerson']\",\n          assignedEntity\n        ) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n        );\n\n        return { name, contactDetails, relationship: \"\" };\n      }\n\n      const relatedEntity = xpath.select1(\"*[name()='relatedEntity']\", informant) as\n        | Document\n        | undefined;\n\n      if (relatedEntity) {\n        const relatedPerson = xpath.select1(\"*[name()='relatedPerson']\", relatedEntity) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", relatedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", relatedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", relatedEntity) as Document[]\n        );\n\n        const relationship = String(\n          xpath.select1(\"string(*[name()='code']/@displayName)\", relatedEntity)\n        ).toLowerCase();\n\n        return { name, contactDetails, relationship };\n      }\n\n      return undefined;\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","import { getInformantData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Informant = ({ document }: DocumentOnlyProps) => {\n  const informants = getInformantData(document);\n\n  if (!informants || isEmpty(informants)) return null;\n\n  const finalData = informants.flatMap((informant) => [\n    {\n      label: \"Informant\",\n      value: `${informant.name || \"Unknown\"}${\n        informant.relationship ? ` - ${informant.relationship}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: informant.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getHumanName, getId } from \"../../helpers\";\nimport { InformationRecipient } from \"../../types/InformationRecipient\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInformationRecipientData = (\n  document: Document\n): InformationRecipient[] | undefined => {\n  const intendedRecipients = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='informationRecipient']/*[name()='intendedRecipient']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(intendedRecipients)) return undefined;\n\n  return intendedRecipients.map((intendedRecipient) => {\n    let informationRecipientName = \"\";\n    const informationRecipient = xpath.select1(\n      \"*[name()='informationRecipient']\",\n      intendedRecipient\n    ) as Document | undefined;\n\n    if (informationRecipient) {\n      informationRecipientName = getHumanName(\n        xpath.select1(\"*[name()='name']\", informationRecipient) as Document\n      );\n    }\n\n    const ids = (xpath.select(\"*[name()='id']\", intendedRecipient) as Document[])\n      .map(getId)\n      .join(\", \");\n\n    let receivedOrganizationName = \"\";\n    const receivedOrganization = xpath.select1(\n      \"*[name()='receivedOrganization']\",\n      intendedRecipient\n    ) as Document | undefined;\n    if (receivedOrganization) {\n      receivedOrganizationName = String(\n        xpath.select1(\"string(*[name()='name']/node())\", receivedOrganization)\n      );\n    }\n\n    return {\n      name: informationRecipientName,\n      id: ids,\n      organization: receivedOrganizationName,\n    };\n  });\n};\n","import { getInformationRecipientData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const InformationRecipient = ({ document }: DocumentOnlyProps) => {\n  const informationRecipients = getInformationRecipientData(document);\n\n  if (!informationRecipients || isEmpty(informationRecipients)) return null;\n\n  const finalData = informationRecipients.flatMap((informationRecipient) => [\n    {\n      label: \"Information Recipient\",\n      value: informationRecipient.name ?? \"Unnamed\",\n    },\n    {\n      label: \"ID\",\n      value: informationRecipient.id,\n    },\n    {\n      label: \"Organization\",\n      value: informationRecipient.organization,\n    },\n  ]);\n\n  return <Table data={finalData} chunkSize={3} />;\n};\n","import xpath from \"xpath\";\nimport { getId } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getInFulfillmentOf = (\n  document: Document\n): Record<string, LabelValueType[]> | undefined => {\n  const orderXmls = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='inFulfillmentOf']/*[name()='order']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(orderXmls)) return undefined;\n\n  const orders = orderXmls.map((orderXml) => {\n    const id = getId(xpath.select1(\"*[name()='id']\", orderXml) as Document);\n    const code = String(xpath.select1(\"string(*[name()='code']/@displayName)\", orderXml));\n\n    return [\n      { label: \"Order ID:\", value: id },\n      { label: \"Code:\", value: code },\n    ];\n  });\n\n  return orders.reduce(\n    (acc, order, index) => ({ ...acc, [`inFulfillmentOf${index + 1}`]: order }),\n    {}\n  );\n};\n","import { getInFulfillmentOf as getInFulfillmentOfDataFromHeader } from \"../Header/data/getInFulfillmentOf\";\n\nexport const getInFulfillmentOfData = (document: Document) => {\n  const inFulfillmentOf = getInFulfillmentOfDataFromHeader(document);\n\n  return Object.values(inFulfillmentOf || {});\n};\n","import { getInFulfillmentOfData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const InFulfillmentOf = ({ document }: DocumentOnlyProps) => {\n  const inFulfillmentOfs = getInFulfillmentOfData(document);\n\n  if (isEmpty(inFulfillmentOfs)) return null;\n\n  const finalData = inFulfillmentOfs.flatMap((inFulfillmentOf) => [\n    {\n      label: \"In Fulfillment Of\",\n      value: `Order: ${inFulfillmentOf[0].value || \"Unknown\"}, ${\n        // [0] is id\n        inFulfillmentOf[1].value || \"Unknown\" // [1] is code\n      }`,\n    },\n    { label: \"\", value: \"\" },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { formatDate, getContactDetails, getHumanName, parseToISOString } from \"../../helpers\";\nimport { ExtendedGeneralInfo } from \"../../types\";\n\nexport const getLegalAuthenticatorData = (document: Document): ExtendedGeneralInfo | undefined => {\n  const legalAuthenticator = xpath.select1(\n    \"*[name()='ClinicalDocument']/*[name()='legalAuthenticator']\",\n    document\n  ) as Document | undefined;\n\n  if (!legalAuthenticator) return undefined;\n\n  const assignedEntity = xpath.select1(\n    \"*[name()='assignedEntity']\",\n    legalAuthenticator\n  ) as Document;\n\n  const assignedPerson = xpath.select1(\"*[name()='assignedPerson']\", assignedEntity) as Document;\n\n  const name = getHumanName(xpath.select(\"*[name()='name']\", assignedPerson) as Document[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", assignedEntity) as Document[],\n    xpath.select(\"*[name()='telecom']\", assignedEntity) as Document[]\n  );\n\n  const time = formatDate(\n    parseToISOString(String(xpath.select1(\"string(*[name()='time']/@value)\", legalAuthenticator)))\n  );\n\n  return { name, contactDetails, time };\n};\n","import { getLegalAuthenticatorData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\n\nexport const LegalAuthenticator = ({ document }: DocumentOnlyProps) => {\n  const legalAuthenticator = getLegalAuthenticatorData(document);\n\n  if (!legalAuthenticator) return null;\n\n  const { name, time, contactDetails } = legalAuthenticator;\n\n  const withSignedAt = time ? ` signed at ${time}` : \"\";\n  const finalData = [\n    {\n      label: \"Legal Authenticator\",\n      value: `${name}${withSignedAt}`,\n    },\n    { label: \"Contact Details\", value: contactDetails },\n  ];\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getContactDetails, getHumanName, getPeriod } from \"../../helpers\";\nimport { ExtendedGeneralInfo, isExtendedGeneralInfoExist } from \"../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getParticipantData = (document: Document): ExtendedGeneralInfo[] | undefined => {\n  const participants = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='participant']\",\n    document\n  ) as Document[];\n\n  if (isEmpty(participants)) return undefined;\n\n  return participants\n    .map((participant): ExtendedGeneralInfo | undefined => {\n      const associatedEntity = xpath.select1(\"*[name()='associatedEntity']\", participant) as\n        | Document\n        | undefined;\n\n      if (associatedEntity) {\n        const associatedPerson = xpath.select1(\n          \"*[name()='associatedPerson']\",\n          associatedEntity\n        ) as Document;\n\n        const name = getHumanName(xpath.select(\"*[name()='name']\", associatedPerson) as Document[]);\n\n        const contactDetails = getContactDetails(\n          xpath.select(\"*[name()='addr']\", associatedEntity) as Document[],\n          xpath.select(\"*[name()='telecom']\", associatedEntity) as Document[]\n        );\n\n        const time = xpath.select1(\"*[name()='time']\", participant) as Document;\n\n        const period = getPeriod(time);\n\n        const relationship = String(\n          xpath.select1(\"string(*[name()='code']/@displayName)\", associatedEntity)\n        ).toLowerCase();\n\n        return {\n          name,\n          contactDetails,\n          time: `from ${period.start} to ${period.end}`,\n          relationship,\n        };\n      }\n\n      return undefined;\n    })\n    .filter(isExtendedGeneralInfoExist);\n};\n","import { getParticipantData } from \"./data\";\nimport { DocumentOnlyProps } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const Participant = ({ document }: DocumentOnlyProps) => {\n  const participants = getParticipantData(document);\n\n  if (!participants || isEmpty(participants)) return null;\n\n  const finalData = participants.flatMap((participant) => [\n    {\n      label: \"Participant\",\n      value: `${participant.name}${\n        participant.relationship ? ` - ${participant.relationship}` : \"\"\n      }`,\n    },\n    {\n      label: \"Contact Details\",\n      value: participant.contactDetails,\n    },\n  ]);\n\n  return <Table data={finalData} />;\n};\n","import xpath from \"xpath\";\nimport { getAddress } from \"../../../helpers\";\n\nexport const getBirthPlace = (patient: Document): string => {\n  const birthPlace = xpath.select1(\n    \"*[name()='birthplace']/*[name()='place']/*[name()='addr']\",\n    patient\n  ) as Document | undefined;\n\n  if (!birthPlace) return \"\";\n\n  return getAddress(birthPlace);\n};\n","import xpath from \"xpath\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getEthnicity = (patient: Document): string => {\n  const ethnicGroup = xpath.select1(\"*[name()='ethnicGroupCode']\", patient) as Document | undefined;\n\n  if (ethnicGroup) {\n    return String(xpath.select1(\"string(@displayName)\", ethnicGroup));\n  }\n\n  const detailedEthnicGroup = xpath.select(\n    \"*[name()='sdtc:ethnicGroupCode']\",\n    patient\n  ) as Document[];\n\n  if (isEmpty(detailedEthnicGroup)) return \"\";\n\n  return String(xpath.select1(\"string(@displayName)\", detailedEthnicGroup[0]));\n};\n","import xpath from \"xpath\";\nimport { getHumanName } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getGuardian = (patientRole: Document): LabelValueType[] | undefined => {\n  const guardians = xpath.select(\n    \"*[name()='patient']/*[name()='guardian']\",\n    patientRole\n  ) as Document[];\n\n  if (isEmpty(guardians)) return undefined;\n\n  return guardians.map((guardian) => {\n    const guardianPerson = xpath.select1(\"*[name()='guardianPerson']\", guardian) as Document;\n\n    const relationship = String(xpath.select1(\"string(*[name()='code']/@displayName)\", guardian));\n    const name = getHumanName(xpath.select(\"*[name()='name']\", guardianPerson) as Document[]);\n\n    const withRelationship = relationship ? ` - ${relationship}` : \"\";\n    return {\n      label: \"\",\n      value: `${name}${withRelationship}`,\n    };\n  });\n};\n","import xpath from \"xpath\";\nimport { getContactDetails } from \"../../../helpers\";\nimport { GeneralInfo, LabelValueType } from \"../../../types\";\nimport { getGuardian as getGuardianFromHeader } from \"../../Header/data/getGuardian\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getGuardian = (patientRole: Document): GeneralInfo[] | undefined => {\n  const guardians = xpath.select(\n    \"//*[name()='patientRole']/*[name()='patient']/*[name()='guardian']\",\n    document\n  ) as Document[] | undefined;\n\n  if (!guardians || isEmpty(guardians)) return undefined;\n\n  const guardianNames = getGuardianFromHeader(patientRole) as LabelValueType[];\n\n  return guardians.map((guardian, index) => {\n    const contactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", guardian) as Document[],\n      xpath.select(\"*[name()='telecom']\", guardian) as Document[]\n    );\n\n    return { name: guardianNames[index].value, contactDetails };\n  });\n};\n","import xpath from \"xpath\";\n\nexport const getLanguage = (patient: Document): string => {\n  const languages = xpath.select(\"*[name()='languageCommunication']\", patient) as Document[];\n\n  return languages.reduce((acc, language, index) => {\n    const languageCode = String(xpath.select1(\"string(*[name()='languageCode']/@code)\", language));\n    if (!languageCode) return acc;\n\n    const preferred = String(xpath.select1(\"string(*[name()='preferenceInd']/@value)\", language));\n\n    const withNewLine = index === 0 ? \"\" : \"\\n\";\n    const withPreferred = preferred !== \"\" ? `, preferred: ${preferred}` : \"\";\n    return `${acc}${withNewLine}${languageCode}${withPreferred}`;\n  }, \"\");\n};\n","import xpath from \"xpath\";\n\nexport const getMaritalStatus = (patient: Document): string =>\n  String(xpath.select1(\"string(*[name()='maritalStatusCode']/@displayName)\", patient));\n","import xpath from \"xpath\";\nimport { displayForName, getContactDetails, getId } from \"../../../helpers\";\nimport { GeneralInfo } from \"../../../types\";\n\nexport const getProviderOrganization = (patientRole: Document): GeneralInfo => {\n  const providerOrganization = xpath.select1(\"*[name()='providerOrganization']\", patientRole) as\n    | Document\n    | undefined;\n\n  const custodian = xpath.select1(\n    \"//*[name()='custodian']/*[name()='assignedCustodian']/*[name()='representedCustodianOrganization']\",\n    patientRole\n  ) as Document | undefined;\n\n  const finalProvider = providerOrganization || custodian;\n\n  if (!finalProvider) {\n    return {\n      name: \"\",\n      contactDetails: \"\",\n    };\n  }\n  const ids = (xpath.select(\"*[name()='id']\", finalProvider) as Document[]).map(getId).join(\", \");\n\n  const names = displayForName(xpath.select(\"string(*[name()='name'])\", finalProvider) as string[]);\n\n  const contactDetails = getContactDetails(\n    xpath.select(\"*[name()='addr']\", finalProvider) as Document[],\n    xpath.select(\"*[name()='telecom']\", finalProvider) as Document[]\n  );\n\n  const withNames = names ? `\\n${names}` : \"\";\n  return {\n    name: `${ids}${withNames}`,\n    contactDetails,\n  };\n};\n","import xpath from \"xpath\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport const getRace = (patient: Document): string => {\n  const race = xpath.select1(\"*[name()='raceCode']\", patient) as Document | undefined;\n\n  if (race) return String(xpath.select1(\"string(@displayName)\", race));\n\n  const detailedRace = xpath.select(\"*[name()='sdtc:raceCode']\", patient) as Document[];\n\n  if (isEmpty(detailedRace)) return \"\";\n\n  return String(xpath.select1(\"string(@displayName)\", detailedRace[0]));\n};\n","import xpath from \"xpath\";\n\nexport const getReligion = (patient: Document): string =>\n  String(xpath.select1(\"string(*[name()='religiousAffiliationCode']/@displayName)\", patient));\n","import { differenceInYears, format, isValid, parseISO } from \"date-fns\";\nimport xpath from \"xpath\";\nimport { getGuardian } from \"./getGuardian\";\nimport { getHumanName, getId, parseToISOString } from \"../../../helpers\";\nimport { LabelValueType } from \"../../../types\";\nimport { map } from \"@/utils/nodash\";\n\nexport const getPatient = (document: Document): Record<string, LabelValueType[] | undefined> => {\n  const patientRoles = xpath.select(\n    \"*[name()='ClinicalDocument']/*[name()='recordTarget']/*[name()='patientRole']\",\n    document\n  ) as Document[];\n\n  const result = patientRoles.map(\n    (\n      patientRole\n    ): {\n      patient: LabelValueType[];\n      guardian: LabelValueType[] | undefined;\n    } => {\n      const patient = xpath.select1(\"*[name()='patient']\", patientRole) as Document;\n\n      const patientName = getHumanName(xpath.select1(\"*[name()='name']\", patient) as Document);\n\n      const patientIds = (xpath.select(\"*[name()='id']\", patientRole) as Document[])\n        .map(getId)\n        .join(\", \");\n\n      const administrativeGenderCode = String(\n        xpath.select1(\"string(*[name()='administrativeGenderCode']/@displayName)\", patient)\n      );\n\n      const birthTime = parseISO(\n        parseToISOString(String(xpath.select1(\"string(*[name()='birthTime']/@value)\", patient)))\n      );\n\n      const deceasedTime = parseISO(\n        parseToISOString(\n          String(xpath.select1(\"string(*[name()='sdtc:deceasedTime']/@value)\", patient))\n        )\n      );\n\n      const deceasedInd =\n        String(xpath.select1(\"string(*[name()='sdtc:deceasedInd']/@value)\", patient)) === \"true\";\n\n      const withDeceased = deceasedInd\n        ? \"deceased\"\n        : differenceInYears(isValid(deceasedTime) ? deceasedTime : new Date(), birthTime);\n      const dateOfBirth = `${format(birthTime, \"MMMM dd, yyyy\")} (${withDeceased}${\n        deceasedInd ? \"\" : \" yr\"\n      }${isValid(deceasedTime) ? \" - deceased\" : \"\"})`;\n\n      const guardian = getGuardian(patientRole);\n\n      return {\n        patient: [\n          { label: \"Name:\", value: patientName },\n          {\n            label: \"ID:\",\n            value: patientIds,\n          },\n          {\n            label: \"Date of birth:\",\n            value: dateOfBirth,\n          },\n          { label: \"Gender:\", value: administrativeGenderCode },\n        ],\n        guardian,\n      };\n    }\n  );\n\n  return map(result, (res) => [res.patient, res.guardian]).reduce(\n    (acc, val, index) => ({\n      ...acc,\n      [`patient${index + 1}`]: val[0],\n      [`guardian${index + 1}`]: val[1],\n    }),\n    {}\n  );\n};\n","import xpath from \"xpath\";\nimport { getBirthPlace } from \"./getBirthPlace\";\nimport { getEthnicity } from \"./getEthnicity\";\nimport { getGuardian } from \"./getGuardian\";\nimport { getLanguage } from \"./getLanguage\";\nimport { getMaritalStatus } from \"./getMaritalStatus\";\nimport { getProviderOrganization } from \"./getProviderOrganization\";\nimport { getRace } from \"./getRace\";\nimport { getReligion } from \"./getReligion\";\nimport { getContactDetails } from \"../../../helpers\";\nimport { getPatient as getPatientDataFromHeader } from \"../../Header/data/getPatient\";\nimport { camelCase, isEmpty } from \"@/utils/nodash\";\n\nexport const getPatientData = (document: Document) => {\n  const patientRoles = xpath.select(\"//*[name()='patientRole']\", document) as\n    | Document[]\n    | undefined;\n\n  if (!patientRoles || isEmpty(patientRoles)) return undefined;\n\n  const dataFromHeader = getPatientDataFromHeader(document);\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const patients: any = Object.entries(dataFromHeader).reduce(\n    (result, [key, value]) => ({\n      ...result,\n      [key]: value?.reduce(\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        (valueAsObject: any, data: { label: string; value: string }) => ({\n          ...valueAsObject,\n          [camelCase(data.label)]: data.value,\n        }),\n        {}\n      ),\n    }),\n    {}\n  );\n\n  return patientRoles.map((patientRole, index) => {\n    const patient = xpath.select1(\"*[name()='patient']\", patientRole) as Document;\n\n    const race = getRace(patient);\n    const ethnicity = getEthnicity(patient);\n\n    const contactDetails = getContactDetails(\n      xpath.select(\"*[name()='addr']\", patientRole) as Document[],\n      xpath.select(\"*[name()='telecom']\", patientRole) as Document[]\n    );\n\n    const language = getLanguage(patient);\n\n    const providerOrganization = getProviderOrganization(patientRole);\n\n    const guardian = getGuardian(patientRole);\n\n    const maritalStatus = getMaritalStatus(patient);\n    const religion = getReligion(patient);\n    const birthPlace = getBirthPlace(patient);\n\n    return {\n      name: patients[`patient${index + 1}`].name,\n      contactDetails,\n      dateOfBirth: patients[`patient${index + 1}`].dateOfBirth,\n      gender: patients[`patient${index + 1}`].gender,\n      race,\n      ethnicity,\n      patientId: patients[`patient${index + 1}`].id,\n      language,\n      maritalStatus,\n      religion,\n      birthPlace,\n      guardian: guardian || [],\n      providerOrganization: providerOrganization.name,\n      providerOrganizationContactDetails: providerOrganization.contactDetails,\n    };\n  });\n};\n","import { getPatientData } from \"./data\";\nimport { DocumentOnlyProps, TableInfo } from \"../../types\";\nimport { Table } from \"../Table/Table\";\nimport { isArray, isEmpty } from \"@/utils/nodash\";\n\nexport const Patient = ({ document }: DocumentOnlyProps): JSX.Element | null => {\n  const patients = getPatientData(document);\n\n  if (!patients || isEmpty(patients)) return null;\n\n  return (\n    <>\n      {patients.map((patient) => {\n        const finalData: ([TableInfo, TableInfo] | TableInfo)[] = [\n          { label: \"Patient\", value: patient.name },\n          { label: \"Contact Details\", value: patient.contactDetails },\n\n          { label: \"Date Of Birth\", value: patient.dateOfBirth },\n          { label: \"Gender\", value: patient.gender },\n\n          { label: \"Race\", value: patient.race },\n          { label: \"Ethnicity\", value: patient.ethnicity },\n\n          { label: \"Patient ID\", value: patient.patientId },\n          { label: \"Language\", value: patient.language },\n\n          { label: \"Marital Status\", value: patient.maritalStatus },\n          { label: \"Religion\", value: patient.religion },\n\n          { label: \"Birth Place\", value: patient.birthPlace },\n\n          ...(patient.guardian.map((guardian) => [\n            { label: \"Guardian\", value: guardian.name },\n            { label: \"Contact Details\", value: guardian.contactDetails },\n          ]) as [TableInfo, TableInfo][]), // ts does not understand, we must explicitly state it is ok\n\n          [\n            {\n              label: \"Provider Organization\",\n              value: patient.providerOrganization,\n            },\n            {\n              label: \"Contact Details (Organization)\",\n              value: patient.providerOrganizationContactDetails,\n            },\n          ],\n        ];\n\n        return (\n          <Table\n            key={`${patient.patientId}-${patient.name}-${patient.dateOfBirth}`}\n            data={finalData.filter((d) => isArray(d) || d.value)}\n          />\n        );\n      })}\n    </>\n  );\n};\n","import { Authenticator } from \"./Authenticator/Authenticator\";\nimport { Author } from \"./Author/Author\";\nimport { Authorization } from \"./Authorization/Authorization\";\nimport { Custodian } from \"./Custodian/Custodian\";\nimport { DataEnterer } from \"./DataEnterer/DataEnterer\";\nimport { Document } from \"./Document/Document\";\nimport { DocumentationOf } from \"./DocumentationOf/DocumentationOf\";\nimport { Encounter } from \"./Encounter/Encounter\";\nimport { Informant } from \"./Informant/Informant\";\nimport { InformationRecipient } from \"./InformationRecipient/InformationRecipient\";\nimport { InFulfillmentOf } from \"./InFulfillmentOf/InFulfillmentOf\";\nimport { LegalAuthenticator } from \"./LegalAuthenticator/LegalAuthenticator\";\nimport { Participant } from \"./Participant/Participant\";\nimport { Patient } from \"./Patient/Patient\";\nimport { DocumentOnlyProps } from \"../types\";\nimport \"../../styles.scss\";\n\nexport const DocumentDetails = ({ document }: DocumentOnlyProps) => (\n  <div className=\"ctw-ccda-document-details\">\n    <Document document={document} />\n    <Custodian document={document} />\n    <Patient document={document} />\n    <Author document={document} />\n    <DataEnterer document={document} />\n    <Informant document={document} />\n    <InformationRecipient document={document} />\n    <LegalAuthenticator document={document} />\n    <Authenticator document={document} />\n    <Participant document={document} />\n    <DocumentationOf document={document} />\n    <InFulfillmentOf document={document} />\n    <Authorization document={document} />\n    <Encounter document={document} />\n  </div>\n);\n","import xpath from \"xpath\";\nimport { formatDate, parseToISOString } from \"../../../helpers\";\n\nexport const getTitle = (document: Document): string => {\n  const title = String(\n    xpath.select1(\"string(*[name()='ClinicalDocument']/*[name()='title']/text())\", document)\n  );\n\n  const effectiveTime = parseToISOString(\n    String(\n      xpath.select1(\n        \"string(*[name()='ClinicalDocument']/*[name()='effectiveTime']/@value)\",\n        document\n      )\n    )\n  );\n\n  const date = formatDate(effectiveTime);\n\n  return `${title} (${date})`;\n};\n","import { getAuthor } from \"./getAuthor\";\nimport { getConsent } from \"./getConsent\";\nimport { getDocumentationOf } from \"./getDocumentationOf\";\nimport { getEncounter } from \"./getEncounter\";\nimport { getInFulfillmentOf } from \"./getInFulfillmentOf\";\nimport { getPatient } from \"./getPatient\";\nimport { getTitle } from \"./getTitle\";\nimport { LabelValueType } from \"../../../types\";\n\nexport const getHeaderData = (\n  document: Document\n): { title: string; labelTypeData: Record<string, LabelValueType[]> } => {\n  const title = getTitle(document);\n  const patient = getPatient(document);\n  const documentationOf = getDocumentationOf(document);\n  const author = getAuthor(document);\n  const encounter = getEncounter(document);\n  const inFulfillmentOf = getInFulfillmentOf(document);\n  const consents = getConsent(document);\n\n  return {\n    title,\n    labelTypeData: {\n      ...patient,\n      ...(consents || {}),\n      ...(documentationOf || {}),\n      ...(author || {}),\n      encounter: encounter || [],\n      ...(inFulfillmentOf || {}),\n    },\n  };\n};\n","/* eslint-disable react/no-array-index-key */\nimport cx from \"classnames\";\nimport { ReactNode } from \"react\";\nimport { getHeaderData } from \"./data\";\nimport { DocumentOnlyProps, LabelValueType } from \"../../types\";\nimport { isEmpty, map, startCase } from \"@/utils/nodash\";\nimport \"../../../styles.scss\";\n\ntype HeaderProps = DocumentOnlyProps & { children?: ReactNode };\n\nexport const Header = ({ document, children }: HeaderProps): JSX.Element => {\n  const { title, labelTypeData } = getHeaderData(document);\n\n  return (\n    <div className=\"ctw-ccda-header-container ctw-space-y-4\">\n      <div className=\"ctw-flex ctw-w-full ctw-space-x-0 ct\">\n        <div className=\"ctw-w-fit ctw-basis-1/2\">{children}</div>\n        <div\n          className={cx(\"ctw-ccda-header-title ctw-w-fit\", {\n            \"ctw-self-center\": !children,\n            \"ctw-basis-1/2\": !!children,\n          })}\n        >\n          <h2 className=\"ctw-text-base ctw-text-right ctw-leading-none\">{title}</h2>\n        </div>\n      </div>\n\n      <table className=\"ctw-ccda-common-table\">\n        <tbody>\n          {map(labelTypeData, (arrayOfData: LabelValueType[] | undefined, key: string) => {\n            if (!arrayOfData) return null;\n\n            const filteredData = arrayOfData.filter((data) => data.value);\n            if (isEmpty(filteredData)) return null;\n            return (\n              <tr key={key}>\n                <td className=\"ctw-ccda-common-td1\">{startCase(key.replace(/\\d/g, \"\"))}</td>\n                <td className=\"ctw-ccda-common-td2\">\n                  {filteredData.map((data: LabelValueType, index) => (\n                    <span key={`${key}-${index}`}>\n                      {data.label && <b>{data.label} </b>}\n                      {data.value}\n                    </span>\n                  ))}\n                </td>\n              </tr>\n            );\n          })}\n        </tbody>\n      </table>\n    </div>\n  );\n};\n","import DOMPurify from \"dompurify\";\nimport { Interweave } from \"interweave\";\nimport { useState } from \"react\";\nimport { fixHtml } from \"../../helpers\";\nimport { SectionType } from \"../../types\";\nimport \"../../../styles.scss\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\n\nexport const Section = ({\n  title,\n  humanReadable,\n}: Omit<SectionType, \"code\">): JSX.Element | null => {\n  const [isOpen, setIsOpen] = useState(true);\n  const { trackInteraction } = useAnalytics();\n\n  if (!humanReadable) return null;\n\n  const handleClick = () => {\n    setIsOpen(!isOpen);\n    trackInteraction(\"toggle_document_section\", {\n      action: isOpen ? \"collapse_document_section\" : \"expand_document_section\",\n    });\n  };\n  return (\n    <div className=\"ctw-ccda-section-container\">\n      <div className=\"ctw-ccda-section-header-wrapper\">\n        <button type=\"button\" className=\"ctw-ccda-section-arrow\" onClick={handleClick}>\n          {isOpen ? \"▼\" : \"▶\"}\n        </button>\n        <h3>{title}</h3>\n      </div>\n      {isOpen && (\n        <div className=\"ctw-ccda-section-wrapper\">\n          <Interweave content={DOMPurify.sanitize(fixHtml(humanReadable))} />\n        </div>\n      )}\n    </div>\n  );\n};\n","import { ReactNode } from \"react\";\nimport xpath from \"xpath\";\nimport { DocumentDetails } from \"./components/DocumentDetails\";\nimport { Header } from \"./components/Header/Header\";\nimport { Section } from \"./components/Section/Section\";\nimport { SectionType } from \"./types\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\n\ntype CccdaViewerComponentProps = {\n  document: Document;\n  children?: ReactNode;\n};\n\nexport const CcdaViewerComponent = ({\n  document,\n  children,\n}: CccdaViewerComponentProps): JSX.Element => {\n  const sections = xpath.select(\n    \"//*[name()='component']/*[name()='section']\",\n    document,\n  ) as Document[];\n\n  const texts: SectionType[] = sections.map((section) => {\n    const title = String(xpath.select1(\"string(*[name()='title'])\", section));\n    const humanReadable = xpath.select1(\"*[name()='text']\", section) as Document;\n\n    const code = String(xpath.select1(\"string(*[name()='code']/@code)\", section));\n\n    return { title, humanReadable, code };\n  });\n\n  return (\n    <div className=\"print:ctw-min-h-full print:ctw-overflow-auto\">\n      <Header document={document}>{children}</Header>\n      <DocumentDetails document={document} />\n      {texts.map(({ title, humanReadable, code }) => (\n        <Section key={`el-text-${code}`} title={title} humanReadable={humanReadable} />\n      ))}\n    </div>\n  );\n};\n\nexport const CcdaViewer = withErrorBoundary(CcdaViewerComponent);\n","import UTIF from \"utif\";\n\nexport function tiffToPNG(\n  arrayBuffer: ArrayBuffer,\n  page = 0,\n): {\n  dataUrl: string;\n  description: string;\n  pageCount: number;\n} {\n  const imageFileDirectory = UTIF.decode(arrayBuffer);\n  if (imageFileDirectory.length <= page) {\n    throw new Error(\"Tiff page number requested is out of bounds\");\n  }\n  const imageFileDirectoryPage = imageFileDirectory[page];\n  // t270 is where an IFD indexes any description of the image\n  if (!(\"t270\" in imageFileDirectoryPage && Array.isArray(imageFileDirectoryPage.t270))) {\n    imageFileDirectoryPage.t270 = [\"\"]; // Set a default description\n  }\n  UTIF.decodeImage(arrayBuffer, imageFileDirectoryPage);\n  const rgba = UTIF.toRGBA8(imageFileDirectory[0]); // Uint8Array with RGBA pixels\n\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = imageFileDirectoryPage.width;\n  canvas.height = imageFileDirectoryPage.height;\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) {\n    throw new Error(\"Could not get 2d context\");\n  }\n\n  const img = ctx.createImageData(canvas.width, canvas.height);\n  img.data.set(rgba);\n  ctx.putImageData(img, 0, 0);\n\n  return {\n    dataUrl: canvas.toDataURL(),\n    description: `${imageFileDirectoryPage.t270[0]}`,\n    pageCount: imageFileDirectory.length,\n  };\n}\n","import * as React from \"react\";\n\nfunction ChevronLeftIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ChevronLeftIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction ChevronRightIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ChevronRightIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction ExclamationCircleIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ExclamationCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction ExclamationIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(ExclamationIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction FireIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M12.395 2.553a1 1 0 00-1.45-.385c-.345.23-.614.558-.822.88-.214.33-.403.713-.57 1.116-.334.804-.614 1.768-.84 2.734a31.365 31.365 0 00-.613 3.58 2.64 2.64 0 01-.945-1.067c-.328-.68-.398-1.534-.398-2.654A1 1 0 005.05 6.05 6.981 6.981 0 003 11a7 7 0 1011.95-4.95c-.592-.591-.98-.985-1.348-1.467-.363-.476-.724-1.063-1.207-2.03zM12.12 15.12A3 3 0 017 13s.879.5 2.5.5c0-1 .5-4 1.25-4.5.5 1 .786 1.293 1.371 1.879A2.99 2.99 0 0113 13a2.99 2.99 0 01-.879 2.121z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(FireIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction LockClosedIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(LockClosedIcon);\nexport default ForwardRef;","import * as React from \"react\";\n\nfunction SearchIcon(props, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    ref: svgRef\n  }, props), /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z\",\n    clipRule: \"evenodd\"\n  }));\n}\n\nconst ForwardRef = React.forwardRef(SearchIcon);\nexport default ForwardRef;","import { ExclamationCircleIcon, ExclamationIcon } from \"@heroicons/react/solid\";\nimport cx from \"classnames\";\nimport { ReactNode } from \"react\";\n\nexport type AlertType = \"caution\" | \"error\";\n\nexport type AlertProps = {\n  header: string;\n  children?: ReactNode;\n  className?: string;\n};\n\nexport const ErrorAlert = ({ header, children, className }: AlertProps) => (\n  <div className={cx(\"ctw-alert-bg ctw-rounded-md ctw-bg-error-bg\", className)}>\n    <ExclamationCircleIcon className=\"ctw-h-5 ctw-flex-none ctw-text-error-icon\" />\n    <div className=\"ctw-space-y-2\">\n      <div className=\"ctw-font-medium ctw-text-error-text\">{header}</div>\n      {children && <div className=\"ctw-text-error-message\">{children}</div>}\n    </div>\n  </div>\n);\n\nexport const CautionAlert = ({ header, children, className }: AlertProps) => (\n  <div className={cx(\"ctw-alert-bg ctw-rounded-md ctw-bg-caution-bg\", className)}>\n    <ExclamationIcon className=\"ctw-h-5 ctw-flex-none ctw-text-caution-icon\" />\n    <div className=\"ctw-space-y-2\">\n      <div className=\"ctw-font-medium ctw-text-caution-text\">{header}</div>\n      {children && <div className=\"ctw-text-caution-text\">{children}</div>}\n    </div>\n  </div>\n);\n","export function FileIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      width=\"20\"\n      height=\"20\"\n      viewBox=\"3.75 1.5 12.5 17.5\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      className={className}\n    >\n      <path\n        d=\"M6 2H11V6C11 6.5625 11.4375 7 12 7H16V16C16 17.125 15.0938 18 14 18H6C4.875 18 4 17.125 4 16V4C4 2.90625 4.875 2 6 2ZM12 2L16 6H12V2ZM7.5 10C7.21875 10 7 10.25 7 10.5C7 10.7812 7.21875 11 7.5 11H12.5C12.75 11 13 10.7812 13 10.5C13 10.25 12.75 10 12.5 10H7.5ZM7.5 12C7.21875 12 7 12.25 7 12.5C7 12.7812 7.21875 13 7.5 13H12.5C12.75 13 13 12.7812 13 12.5C13 12.25 12.75 12 12.5 12H7.5ZM7.5 14C7.21875 14 7 14.25 7 14.5C7 14.7812 7.21875 15 7.5 15H12.5C12.75 15 13 14.7812 13 14.5C13 14.25 12.75 14 12.5 14H7.5Z\"\n      />\n    </svg>\n  );\n}\n","export function ImageIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      width=\"20\"\n      height=\"20\"\n      viewBox=\"3.75 1.5 12.5 17.5\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      className={className}\n    >\n      <path\n        d=\"M6 2H11V6C11 6.5625 11.4375 7 12 7H16V16C16 17.125 15.0938 18 14 18H6C4.875 18 4 17.125 4 16V4C4 2.90625 4.875 2 6 2ZM12 2L16 6H12V2ZM8 10C8 9.46875 7.53125 9 7 9C6.4375 9 6 9.46875 6 10C6 10.5625 6.4375 11 7 11C7.53125 11 8 10.5625 8 10ZM10.75 11V11.0312C10.5625 11.0312 10.4062 11.0938 10.3125 11.2188L8.8125 13.4375L8.40625 12.75C8.3125 12.5938 8.15625 12.5 8 12.5C7.8125 12.5 7.65625 12.5938 7.5625 12.75L6.0625 15.25C5.96875 15.4062 5.96875 15.5938 6.0625 15.75C6.125 15.9062 6.3125 16 6.5 16H8H9.5H10.75H13.5C13.6875 16 13.8438 15.9062 13.9375 15.75C14 15.5938 14 15.375 13.9062 15.2188L11.1562 11.2188C11.0625 11.0938 10.9062 11 10.75 11Z\"\n      />\n    </svg>\n  );\n}\n","export function PdfIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      width=\"20\"\n      height=\"20\"\n      viewBox=\"3.75 1.5 12.5 17.5\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      className={className}\n    >\n      <path\n        d=\"M6 2H11V6C11 6.5625 11.4375 7 12 7H16V16C16 17.125 15.0938 18 14 18H6C4.875 18 4 17.125 4 16V4C4 2.90625 4.875 2 6 2ZM12 2L16 6H12V2ZM6 9C5.71875 9 5.5 9.25 5.5 9.5V12V13.5C5.5 13.7812 5.71875 14 6 14C6.25 14 6.5 13.7812 6.5 13.5V12.5H6.75C7.6875 12.5 8.5 11.7188 8.5 10.75C8.5 9.8125 7.6875 9 6.75 9H6ZM6.75 11.5H6.5V10H6.75C7.15625 10 7.5 10.3438 7.5 10.75C7.5 11.1875 7.15625 11.5 6.75 11.5ZM9 9.5V13.5C9 13.7812 9.21875 14 9.5 14H10.25C11.0625 14 11.75 13.3438 11.75 12.5V10.5C11.75 9.6875 11.0625 9 10.25 9H9.5C9.21875 9 9 9.25 9 9.5ZM10 13V10H10.25C10.5 10 10.75 10.25 10.75 10.5V12.5C10.75 12.7812 10.5 13 10.25 13H10ZM13 9C12.7188 9 12.5 9.25 12.5 9.5V11.5V13.5C12.5 13.7812 12.7188 14 13 14C13.25 14 13.5 13.7812 13.5 13.5V12H14.5C14.75 12 15 11.7812 15 11.5C15 11.25 14.75 11 14.5 11H13.5V10H14.5C14.75 10 15 9.78125 15 9.5C15 9.25 14.75 9 14.5 9H13Z\"\n      />\n    </svg>\n  );\n}\n","import { FileIcon } from \"@/components/core/icons/file\";\nimport { ImageIcon } from \"@/components/core/icons/image\";\nimport { PdfIcon } from \"@/components/core/icons/pdf\";\n\ntype ContentTypeIconProps = {\n  className?: string;\n  contentType: string;\n};\n\nconst IMAGE_RE = /^image\\//i;\nconst PDF_RE = /^application\\/.*(pdf|fdf)$/i;\n\nexport function ContentTypeIcon({\n  contentType,\n  className = \"ctw-fill-current ctw-w-4 ctw-h-4\",\n}: ContentTypeIconProps) {\n  if (IMAGE_RE.test(contentType)) {\n    return <ImageIcon className={className} />;\n  }\n  if (PDF_RE.test(contentType)) {\n    return <PdfIcon className={className} />;\n  }\n  return <FileIcon className={className} />;\n}\n","import cx from \"classnames\";\n\nexport type SpinnerProps = {\n  className?: string;\n  size?: number;\n};\n\nexport const Spinner = ({ className }: SpinnerProps) => (\n  <svg\n    className={cx(`ctw-inline ctw-h-4 ctw-w-4 ctw-animate-spin`, className)}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    fill=\"none\"\n    viewBox=\"0 0 24 24\"\n  >\n    <circle\n      className=\"ctw-opacity-25\"\n      cx=\"12\"\n      cy=\"12\"\n      r=\"10\"\n      stroke=\"currentColor\"\n      strokeWidth=\"4\"\n    />\n    <path\n      className=\"ctw-opacity-75\"\n      fill=\"currentColor\"\n      d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n    />\n  </svg>\n);\n","import cx from \"classnames\";\nimport { Spinner } from \"@/components/core/spinner\";\n\nexport type LoadingProps = {\n  className?: string;\n  iconClass?: string;\n  message?: string;\n};\n\nexport const Loading = ({\n  className = \"ctw-text-sm\",\n  iconClass,\n  message = \"Loading...\",\n}: LoadingProps) => (\n  <div className={cx(\"ctw-space-x-2 ctw-flex ctw-items-center  ctw-m-auto\", className)}>\n    <Spinner className={iconClass} />\n    {message && <span className=\"ctw-italic\">{message}</span>}\n  </div>\n);\n","import { FlagProvider, UnleashClient, useUnleashContext } from \"@unleash/proxy-client-react\";\nimport jwtDecode from \"jwt-decode\";\nimport { createContext, ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { useGetAuthToken } from \"./authentication/use-get-auth-token\";\nimport { Env } from \"./types\";\n\n// Map our env to the unleash environment, defaulting to \"development\".\n// NOTE: these keys are hardcoded in https://github.com/zeus-health/aws-base/blame/8eb18e694f5c94b70f15559254ce10027e74f4b4/unleash/scripts/create_secrets.sh#L33-L39\n// so they could change without notice. INFRA-729 will create these in AWS secrets for all\n// accounts but for now it is safe to store these in GitHub\nexport const getUnleashProxyForEnv = (env: Env) => {\n  switch (env) {\n    case \"production\":\n      return {\n        url: \"https://unleash-proxy-prod.zusapi.com/proxy\",\n        clientKey: \"MDE0NDU5NTQtNEIyNC00RUVGLUI4NDUtRTE3QjYyMUQ3NTAzCg==\",\n      };\n    case \"phi-test\":\n    case \"sandbox\":\n      return {\n        url: \"https://unleash-proxy.zusapi.com/proxy\",\n        clientKey: \"Q0QwNUIxODgtQkFEMC00MTA2LUIwRDEtRDgwQ0FFRDBBMzBCCg==\",\n      };\n    case \"dev\":\n    default:\n      return {\n        url: \"https://unleash-proxy-dev.zusapi.com/proxy\",\n        clientKey: \"NTk3QkM3RTItMTU4Qi00NDYwLTlFQjQtNjMyQ0ZFMENBNkY1Cg==\",\n      };\n  }\n};\n\nexport const getUnleashContext = (zusToken: string) => {\n  const decoded = jwtDecode(zusToken) as { [key: string]: string };\n  // For some reason unleash proxy does not like localhost appearing\n  // in the query params and will return 403's.\n  // As a work around, we replace localhost with local.\n  const hostname = window.location.hostname.replace(\"localhost\", \"local\");\n\n  return {\n    userId: decoded[\"https://zusapi.com/user_id\"],\n    properties: {\n      builderId: decoded[\"https://zusapi.com/builder_id\"],\n      builderName: decoded[\"https://zusapi.com/builder_name\"],\n      userType: decoded[\"https://zusapi.com/user_type\"],\n      email: decoded[\"https://zusapi.com/email\"],\n      hostname,\n    },\n  };\n};\n\nexport const FeatureFlagContext = createContext({\n  unleashClientFailed: false,\n});\n\nexport type FeatureFlagProviderProps = {\n  env: Env;\n  children: ReactNode;\n};\n\nexport function FeatureFlagProvider({ env, children }: FeatureFlagProviderProps) {\n  const unleashClient = useMemo(\n    () =>\n      new UnleashClient({\n        ...getUnleashProxyForEnv(env),\n        refreshInterval: 15, // (in seconds)\n        appName: \"ctw-component-library\",\n        context: {},\n      }),\n    [env],\n  );\n\n  return (\n    <FlagProvider unleashClient={unleashClient} startClient={false}>\n      <FeatureFlagProviderComponent unleashClient={unleashClient}>\n        {children}\n      </FeatureFlagProviderComponent>\n    </FlagProvider>\n  );\n}\n\ntype FeatureFlagProviderComponentProps = {\n  children: ReactNode;\n  unleashClient: UnleashClient;\n};\n\n// Component responsible for fetching the auth token and updating the Unleash context once the auth token has been fetched.\n// This needs to be a child of `FlagProvider` in order to have access to the Unleash context.\nconst FeatureFlagProviderComponent = ({\n  unleashClient,\n  children,\n}: FeatureFlagProviderComponentProps) => {\n  const updateContext = useUnleashContext();\n  const authTokenPromise = useGetAuthToken();\n  const [authToken, setAuthToken] = useState<string>();\n  const [unleashClientStarted, setUnleashClientStarted] = useState<boolean>();\n  const [unleashClientFailed, setUnleashClientFailed] = useState<boolean>();\n\n  // fetch the auth token\n  useEffect(() => {\n    void (async function fetchData() {\n      setAuthToken(await authTokenPromise());\n    })();\n  }, [authTokenPromise]);\n\n  // configure the unleash client\n  useEffect(() => {\n    if (authToken && !unleashClientStarted) {\n      void (async function run() {\n        unleashClient.on(\"error\", () => {\n          setUnleashClientFailed(true);\n        });\n        await updateContext(getUnleashContext(authToken));\n        await unleashClient.start();\n        setUnleashClientStarted(true);\n      })();\n    }\n  }, [authToken, unleashClient, unleashClientStarted, updateContext]);\n\n  const context = useMemo(\n    () => ({\n      unleashClientFailed: !!unleashClientFailed,\n    }),\n    [unleashClientFailed],\n  );\n\n  return <FeatureFlagContext.Provider value={context}>{children}</FeatureFlagContext.Provider>;\n};\n","import { useFlagsStatus, useUnleashClient } from \"@unleash/proxy-client-react\";\nimport { useContext } from \"react\";\nimport { FeatureFlagContext } from \"@/components/core/providers/feature-flag-provider\";\n\nexport type FeatureToggle = {\n  enabled?: boolean | undefined;\n  ready: boolean;\n  errorGettingToggles?: boolean;\n};\n\nexport function useFeatureToggle(name: string): FeatureToggle {\n  const client = useUnleashClient();\n  const status = useFlagsStatus();\n  const { unleashClientFailed } = useContext(FeatureFlagContext);\n\n  if (unleashClientFailed || status.flagsError) {\n    return { ready: true, errorGettingToggles: true };\n  }\n\n  if (!status.flagsReady && !status.flagsError) {\n    return { ready: false };\n  }\n\n  return { ready: true, enabled: client.isEnabled(name) };\n}\n","import { faPrint } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { Viewer } from \"@react-pdf-viewer/core\";\nimport { DOMParser } from \"@xmldom/xmldom\";\nimport { MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useReactToPrint } from \"react-to-print\";\nimport xpath from \"xpath\";\nimport { CcdaViewer } from \"./ccda-viewer\";\nimport { CcdaViewer as CCDAViewerOriginal } from \"./ccda_viewer\";\nimport { tiffToPNG } from \"@/components/content/CCDA/tiff-to-png\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { ContentTypeIcon } from \"@/components/core/icons/content-type-icon\";\nimport { Loading } from \"@/components/core/loading\";\nimport \"@react-pdf-viewer/core/lib/styles/index.css\";\nimport \"./styles.scss\";\nimport \"./new-ccda-styles.scss\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\n\nconst xmlTypes = [\"/xml\", \"/xhtml+xml\", \"application/xml\", \"text/xml\"];\nconst pdfTypes = [\"/pdf\"];\nconst tiffTypes = [\"/tif\", \"/tiff\"];\nconst webImageTypes = [\"/jpg\", \"/jpeg\", \"/png\", \"/apng\", \"/avif\", \"/gif\", \"/webp\", \"/svg+xml\"];\n\nconst isSpecificContentType = (extensions: string[], contentType: string) =>\n  extensions.some((extension) => contentType.includes(extension));\n\ninterface BinaryFieldProps {\n  data: string;\n  blob: Blob;\n  contentType: string;\n  fileName: string | undefined;\n  showPrintBtn?: boolean;\n  onClose?: () => void;\n  overridePatient?: PatientModel | undefined;\n}\n\nexport const BinaryField = ({\n  data,\n  blob,\n  contentType,\n  fileName,\n  showPrintBtn = true,\n  overridePatient,\n}: BinaryFieldProps) => {\n  const showNewCCDAViewer = useFeatureToggle(\"ctw-ccda-viewer\");\n  const [arrayBuffer, setArrayBuffer] = useState<ArrayBuffer>();\n\n  useEffect(() => {\n    if (isSpecificContentType(tiffTypes, contentType)) {\n      // Convert blob to an array buffer, which is used only for tiff files atm.\n      void (async () => {\n        setArrayBuffer(await blob.arrayBuffer());\n      })();\n    }\n  }, [blob, contentType]);\n\n  const ccdaDoc = useMemo(() => {\n    if (isSpecificContentType(tiffTypes, contentType)) {\n      return <PreviewTiffImg data={arrayBuffer} />;\n    }\n\n    if (isSpecificContentType(webImageTypes, contentType)) {\n      const url = URL.createObjectURL(blob);\n      return (\n        <img\n          src={url}\n          alt=\"\"\n          className=\"ctw-h-full ctw-max-h-[95vh] ctw-w-auto ctw-object-contain\"\n        />\n      );\n    }\n\n    if (contentType.includes(\"/pdf\")) {\n      return <PreviewPdf data={blob} />;\n    }\n\n    if (isSpecificContentType(xmlTypes, contentType)) {\n      const xmlDocument = new DOMParser({\n        locator: {},\n        errorHandler: () => null,\n      }).parseFromString(data, contentType);\n      if (xpath.select1(\"//*[name()='patientRole']\", xmlDocument)) {\n        return xmlDocument;\n      }\n    }\n\n    return undefined;\n  }, [contentType, data, arrayBuffer, blob]);\n\n  const downloadAndPrintButtons = (\n    <DownloadAndPrintButtons\n      showPrintBtn={showPrintBtn}\n      fileName={fileName}\n      contentType={contentType}\n      blob={blob}\n    />\n  );\n\n  if (!showNewCCDAViewer.enabled) {\n    return (\n      <OriginalCCDAViewer\n        ccdaDoc={ccdaDoc}\n        contentType={contentType}\n        downloadAndPrintButtons={downloadAndPrintButtons}\n        data={data}\n      />\n    );\n  }\n\n  return (\n    <>\n      {ccdaDoc && isSpecificContentType(xmlTypes, contentType) ? (\n        <CcdaViewer document={ccdaDoc as Document} overridePatient={overridePatient} />\n      ) : (\n        <div className=\"ctw-space-y-4 ctw-w-full\">\n          <div\n            className={\n              ccdaDoc\n                ? \"ctw-flex ctw-flex-col ctw-p-4 ctw-items-center\"\n                : \"ctw-ccda-base64-binary-text\"\n            }\n          >\n            {ccdaDoc ?? data}\n          </div>\n        </div>\n      )}\n    </>\n  );\n};\n\ntype OriginalCCDAViewerProps = {\n  ccdaDoc: Document | JSX.Element | undefined;\n  contentType: string;\n  downloadAndPrintButtons: JSX.Element;\n  data: string;\n};\n\nconst OriginalCCDAViewer = ({\n  ccdaDoc,\n  contentType,\n  downloadAndPrintButtons,\n  data,\n}: OriginalCCDAViewerProps) => (\n  <div className=\"ctw-ccda-container ccda-modal-old\">\n    {ccdaDoc && isSpecificContentType(xmlTypes, contentType) ? (\n      <CCDAViewerOriginal document={ccdaDoc as Document}>\n        {downloadAndPrintButtons}\n      </CCDAViewerOriginal>\n    ) : (\n      <div className=\"ctw-space-y-4\">\n        {downloadAndPrintButtons}\n        <div className={ccdaDoc ? \"\" : \"ctw-ccda-base64-binary-text\"}>{ccdaDoc ?? data}</div>\n      </div>\n    )}\n  </div>\n);\n\nexport type DownloadButtonsProps = {\n  fileName: string | undefined;\n  contentType: string;\n  blob: Blob;\n  handlePrint: ReturnType<typeof useReactToPrint>;\n  contentToPrint: React.MutableRefObject<null>;\n};\n\nfunction DownloadAndPrintButtons({\n  showPrintBtn,\n  fileName,\n  contentType,\n  blob,\n}: {\n  showPrintBtn: boolean;\n  fileName: string | undefined;\n  contentType: string;\n  blob: Blob;\n}) {\n  const ref = useRef<HTMLAnchorElement>(null);\n  const [fileUrl, setFileUrl] = useState<string>();\n  const [fileTitle, setFileTitle] = useState<string>();\n  const downloadDocument = useCallback(\n    (event: MouseEvent<HTMLButtonElement>) => {\n      // Don't want the click event to bubble up to the parent element (the anchor tag).\n      event.stopPropagation();\n      // Clean up any previously created file.\n      if (fileUrl) {\n        URL.revokeObjectURL(fileUrl);\n      }\n      setFileUrl(URL.createObjectURL(blob));\n      setFileTitle(fileName);\n      ref.current?.click();\n    },\n    [blob, fileName, fileUrl],\n  );\n\n  let fileType = \"Document\";\n  if (isSpecificContentType(xmlTypes, contentType)) {\n    fileType = \"XML\";\n  }\n  if (isSpecificContentType(pdfTypes, contentType)) {\n    fileType = \"PDF\";\n  }\n  if (isSpecificContentType([...tiffTypes, ...webImageTypes], contentType)) {\n    fileType = \"Image\";\n  }\n\n  return (\n    <div className=\"flex ctw-justify-items-start ctw-space-x-6 ctw-ml-0 print:ctw-hidden\">\n      <a aria-label=\"Download\" href={fileUrl} ref={ref} download={fileTitle}>\n        <button\n          type=\"button\"\n          className=\"ctw-btn-clear ctw-link ctw-flex ctw-items-center ctw-space-x-2\"\n          onClick={downloadDocument}\n        >\n          <ContentTypeIcon contentType={contentType} className=\"ctw-w-4 ctw-h-4\" />\n          <span>Download {fileType}</span>\n        </button>\n      </a>\n\n      {showPrintBtn && (\n        <button\n          type=\"button\"\n          className=\"ctw-btn-clear ctw-link ctw-items-center ctw-space-x-2 ctw-flex\"\n          onClick={() => window.print()}\n        >\n          <FontAwesomeIcon icon={faPrint} className=\"ctw-h-3\" />\n          <span>Print</span>\n        </button>\n      )}\n    </div>\n  );\n}\n\nfunction PreviewTiffImg({ data }: { data?: ArrayBuffer }) {\n  if (!data) {\n    return <Loading />;\n  }\n\n  const { dataUrl, description } = tiffToPNG(data);\n  return (\n    <>\n      <img src={dataUrl} alt={description} className=\"ctw-h-full ctw-max-h-[95vh] ctw-w-auto\" />\n      <p className=\"ctw-text-sm ctw-text-content-lighter ctw-leading-relaxed\">{description}</p>\n    </>\n  );\n}\n\nfunction PreviewPdf({ data }: { data: Blob }) {\n  try {\n    const url = URL.createObjectURL(data);\n    return (\n      <div className=\"ctw-pdf-viewer ctw-min-w-full ctw-w-[450px] sm:ctw-w-[645px] md:ctw-w-[750px] lg:ctw-w-[960px]\">\n        <Viewer fileUrl={url} />\n      </div>\n    );\n  } catch (e) {\n    // eslint-disable-next-line no-console\n    console.warn(e);\n    return (\n      <ErrorAlert header=\"Error loading PDF\">\n        Unable to preview this PDF file in the web browser.\n      </ErrorAlert>\n    );\n  }\n}\n\nexport function downloadBlob(blob: Blob, fileName?: string) {\n  const fileUrl = URL.createObjectURL(blob);\n  const tempLink = document.createElement(\"a\");\n  tempLink.href = fileUrl;\n\n  tempLink.download = fileName || \"\";\n  document.body.appendChild(tempLink);\n\n  tempLink.click();\n\n  document.body.removeChild(tempLink);\n\n  setTimeout(() => {\n    URL.revokeObjectURL(fileUrl);\n  }, 100);\n}\n","import { ReactNode } from \"react\";\nimport { DocumentHeader } from \"./ccda-viewer/components/Header/Header\";\nimport { PatientModel } from \"@/fhir/models\";\n\nexport const CCDAModalBase = ({\n  children,\n  onClose,\n  actions,\n  patient,\n}: {\n  children: ReactNode;\n  onClose?: () => void;\n  actions?: ReactNode;\n  patient?: PatientModel;\n}) => (\n  <div className=\"ctw-text-lg ctw-w-full\">\n    <DocumentHeader onClose={onClose} actions={actions} overridePatient={patient} />\n    {children}\n  </div>\n);\n","export const base64toBlob = (data: string, type = \"application/pdf\") => {\n  const bytes = atob(data);\n  let { length } = data;\n  const out = new Uint8Array(length);\n\n  while (length) {\n    length -= 1;\n    out[length] = bytes.charCodeAt(length);\n  }\n\n  return new Blob([out], { type });\n};\n","import { Provenance } from \"fhir/r4\";\nimport { base64toBlob } from \"@/components/content/CCDA/base64toBlob\";\nimport { isRenderableBinary } from \"@/components/content/resource/helpers/filters\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { find, some } from \"@/utils/nodash\";\nimport { QUERY_KEY_BINARY } from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\nimport { withTimerMetric } from \"@/utils/telemetry\";\n\n// Get the binary ID from provenance, if document is renderable\nexport function getBinaryId(provenances: Provenance[], targetId: string): string | undefined {\n  for (let i = 0; i < provenances.length; i += 1) {\n    const provenance = provenances[i];\n\n    const hasTarget = some(provenance.target, (t) => t.reference?.includes(targetId));\n\n    if (hasTarget && isRenderableBinary(provenance)) {\n      const source = find(provenance.entity, { role: \"source\" });\n      if (source?.what.reference) {\n        // Return the ID portion of the reference.\n        return source.what.reference.split(\"/\")[1];\n      }\n    }\n  }\n\n  return undefined;\n}\n\nasync function blobToBase64(blob: Blob): Promise<string> {\n  const reader = new FileReader();\n\n  return new Promise((resolve, reject) => {\n    reader.readAsDataURL(blob);\n\n    reader.onload = () => {\n      const base64String = reader.result?.toString().split(\",\")[1] ?? \"\"; // Remove data: prefix\n      const binaryString = atob(base64String);\n      const bytes = new Uint8Array(binaryString.length);\n      for (let i = 0; i < binaryString.length; i += 1) {\n        bytes[i] = binaryString.charCodeAt(i);\n      }\n      const text = new TextDecoder().decode(bytes);\n      resolve(text);\n    };\n\n    reader.onerror = (error) => {\n      reject(error);\n    };\n  });\n}\n\nexport type BinaryData = fhir4.Binary & {\n  blob: Blob;\n};\n\nasync function getBinaryDocumentReq(\n  requestContext: CTWRequestContext,\n  binaryId: string,\n): Promise<BinaryData> {\n  return queryClient.fetchQuery([QUERY_KEY_BINARY, binaryId], async () => {\n    const { data, headers } = await requestContext.fetchFromFqs(`Binary/${binaryId}`, {\n      method: \"GET\",\n    });\n\n    if (data instanceof Blob) {\n      // The Smile response is a base64 string but FQS returns a blob.\n      // The blob can easily convert to base64 string, but is flaky converting\n      // back from base64 blob because we strip off any header information the\n      // blob had when converting to base64 decoded string. So we add `blob` to\n      // the BinaryData object so that we have it later as-is.\n\n      return {\n        blob: data,\n        data: await blobToBase64(data),\n        contentType: headers.get(\"Content-Type\") || \"unknown\",\n        resourceType: \"Binary\",\n      };\n    }\n\n    // fall back to asking ODS for the binary\n    // Remove this once FQS is backfilled + dekludge is completed\n    const based64binary = (await requestContext.fhirClient.read({\n      resourceType: \"Binary\",\n      id: binaryId,\n    })) as fhir4.Binary;\n\n    const decodedData = atob(based64binary.data || \"\");\n\n    return {\n      resourceType: \"Binary\",\n      contentType: based64binary.contentType,\n      data: decodedData,\n      blob: base64toBlob(decodedData, based64binary.contentType),\n    };\n  });\n}\n\nexport const getBinaryDocument = withTimerMetric(getBinaryDocumentReq, \"query_request_timing\", [\n  `query_key:${QUERY_KEY_BINARY}`,\n]);\n","import { faPrint } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { MouseEvent, useCallback, useEffect, useRef, useState } from \"react\";\nimport { useReactToPrint } from \"react-to-print\";\nimport { BinaryField, downloadBlob, DownloadButtonsProps } from \"./binary-field\";\nimport { CCDAModalBase } from \"./ccda-modal-base\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { ContentTypeIcon } from \"@/components/core/icons/content-type-icon\";\nimport { Loading } from \"@/components/core/loading\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { BinaryData, getBinaryDocument } from \"@/fhir/binaries\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\n\ntype ViewDocumentProps = {\n  binaryId: string;\n  fileName: string | undefined;\n  showPrintBtn?: boolean;\n  onClose?: () => void;\n  patient?: PatientModel | undefined;\n};\n\nexport const ViewDocument = ({\n  binaryId,\n  fileName,\n  showPrintBtn = false,\n  onClose,\n  patient,\n}: ViewDocumentProps) => {\n  const [rawBinary, setRawBinary] = useState<BinaryData>();\n  const [isLoading, setIsLoading] = useState(true);\n  const { getRequestContext } = useCTW();\n  const showNewCCDAViewer = useFeatureToggle(\"ctw-ccda-viewer\");\n\n  useEffect(() => {\n    async function load() {\n      // Reset loading and rawBinary every time the binaryId changes.\n      setIsLoading(true);\n      setRawBinary(undefined);\n\n      // Load the binary!\n      const requestContext = await getRequestContext();\n      const data = await getBinaryDocument(requestContext, binaryId);\n      setRawBinary(data);\n      setIsLoading(false);\n    }\n    void load();\n  }, [getRequestContext, binaryId]);\n\n  return showNewCCDAViewer.enabled ? (\n    <BinaryContent\n      isLoading={isLoading}\n      rawBinary={rawBinary}\n      fileName={fileName}\n      showPrintBtn={showPrintBtn}\n      onClose={onClose}\n      patient={patient}\n    />\n  ) : (\n    <OldBinaryContent\n      isLoading={isLoading}\n      rawBinary={rawBinary}\n      fileName={fileName}\n      showPrintBtn={showPrintBtn}\n      onClose={onClose}\n    />\n  );\n};\n\nconst BinaryContent = ({\n  isLoading,\n  rawBinary,\n  fileName,\n  showPrintBtn,\n  onClose,\n  patient,\n}: {\n  isLoading: boolean;\n  rawBinary: BinaryData | undefined;\n  fileName: string | undefined;\n  showPrintBtn?: boolean;\n  onClose?: () => void;\n  patient: PatientModel | undefined;\n}) => {\n  const contentToPrint = useRef(null);\n  const handlePrint = useReactToPrint({\n    documentTitle: fileName,\n    removeAfterPrint: true,\n  });\n\n  if (isLoading) {\n    return (\n      <CCDAModalBase onClose={onClose} patient={patient}>\n        <Loading className=\"ctw-p-12 ctw-flex ctw-justify-center\" />\n      </CCDAModalBase>\n    );\n  }\n\n  if (!rawBinary?.data) {\n    return (\n      <CCDAModalBase onClose={onClose} patient={patient}>\n        <ErrorAlert header=\"Unable to view document\" className=\"ctw-justify-center\">\n          The document could not be loaded.\n        </ErrorAlert>\n      </CCDAModalBase>\n    );\n  }\n\n  const downloadButton = (\n    <DownloadButtons\n      fileName={fileName}\n      contentType={rawBinary.contentType}\n      blob={rawBinary.blob}\n      handlePrint={handlePrint}\n      contentToPrint={contentToPrint}\n    />\n  );\n\n  return (\n    <div\n      className=\"ctw-ccda-container ctw-new-ccda-styles\"\n      ref={contentToPrint}\n      data-testid=\"ccda-viewer\"\n    >\n      <CCDAModalBase onClose={onClose} actions={downloadButton} patient={patient}>\n        <BinaryField\n          data={rawBinary.data}\n          blob={rawBinary.blob}\n          contentType={rawBinary.contentType}\n          fileName={fileName}\n          showPrintBtn={showPrintBtn}\n          onClose={onClose}\n          overridePatient={patient}\n        />\n      </CCDAModalBase>\n    </div>\n  );\n};\n\nconst OldBinaryContent = ({\n  isLoading,\n  rawBinary,\n  fileName,\n  showPrintBtn,\n  onClose,\n}: {\n  isLoading: boolean;\n  rawBinary: BinaryData | undefined;\n  fileName: string | undefined;\n  showPrintBtn?: boolean;\n  onClose?: () => void;\n}) => {\n  if (isLoading) {\n    return <Loading className=\"ctw-p-12 ctw-flex ctw-justify-center\" />;\n  }\n\n  if (!rawBinary?.data) {\n    return (\n      <ErrorAlert header=\"Unable to view document\" className=\"ctw-justify-center\">\n        The document could not be loaded.\n      </ErrorAlert>\n    );\n  }\n  return (\n    <div className=\"ctw-ccda-container ctw-ccda-modal-old\">\n      <BinaryField\n        data={rawBinary.data}\n        blob={rawBinary.blob}\n        contentType={rawBinary.contentType}\n        fileName={fileName}\n        showPrintBtn={showPrintBtn}\n        onClose={onClose}\n      />\n    </div>\n  );\n};\n\nfunction DownloadButtons({\n  fileName,\n  contentType,\n  blob,\n  handlePrint,\n  contentToPrint,\n}: DownloadButtonsProps) {\n  const downloadDocument = useCallback(\n    (event: MouseEvent<HTMLButtonElement>) => {\n      // Don't want the click event to bubble up to the parent element (the anchor tag).\n      event.stopPropagation();\n      // Use the helper function to download the blob.\n      downloadBlob(blob, fileName);\n    },\n    [blob, fileName],\n  );\n\n  return (\n    <div className=\"ctw-flex ctw-justify-items-start ctw-space-x-2 ctw-ml-0 print:ctw-hidden \">\n      <button\n        aria-label=\"Download\"\n        type=\"button\"\n        className=\"ctw-btn-clear ctw-link ctw-flex ctw-items-center ctw-space-x-2\"\n        onClick={downloadDocument}\n      >\n        <ContentTypeIcon contentType={contentType} className=\"ctw-w-5 ctw-h-5 ctw-fill-white\" />\n      </button>\n\n      <button\n        aria-label=\"Print\"\n        type=\"button\"\n        className=\"ctw-btn-clear ctw-link ctw-items-center\"\n        onClick={() => {\n          handlePrint(null, () => contentToPrint.current);\n        }}\n      >\n        <FontAwesomeIcon icon={faPrint} className=\"ctw-h-4 ctw-w-4 ctw-text-white\" />\n      </button>\n    </div>\n  );\n}\n","import { dismissFilter } from \"../../resource/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\n\nexport function allergyFilter(): FilterItem[] {\n  return [dismissFilter];\n}\n","import { AllergyIntolerance } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport {\n  fragmentBasic,\n  fragmentCoding,\n  fragmentEncounterReference,\n  fragmentOrganization,\n  fragmentPatient,\n  fragmentPractitioner,\n} from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface AllergyIntoleranceConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<AllergyIntoleranceWithBasics>[];\n}\n\nexport type AllergyIntoleranceWithBasics = AllergyIntolerance & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface AllergyGraphqlResponse {\n  AllergyIntoleranceConnection: AllergyIntoleranceConnection;\n}\n\nexport const allergyQuery = gql`\n  ${fragmentCoding}\n  ${fragmentOrganization}\n  ${fragmentPatient}\n  ${fragmentEncounterReference}\n  ${fragmentPractitioner}\n  ${fragmentBasic}\n  query Allergies(\n    $upid: ID!\n    $cursor: String!\n    $sort: AllergyIntoleranceSortParams!\n    $filter: AllergyIntoleranceFilterParams! = {}\n    $first: Int!\n  ) {\n    AllergyIntoleranceConnection(\n      upid: $upid\n      after: $cursor\n      sort: $sort\n      filter: $filter\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          BasicList(_reference: \"subject\") {\n            ...Basic\n          }\n          meta {\n            tag {\n              system\n              code\n              display\n            }\n          }\n          clinicalStatus {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          extension {\n            url\n            valueString\n          }\n          verificationStatus {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          type\n          category\n          criticality\n          code {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          patient {\n            reference\n            resource {\n              ... on Patient {\n                ...Patient\n                managingOrganization {\n                  resource {\n                    ... on Organization {\n                      name\n                    }\n                  }\n                }\n              }\n            }\n          }\n          encounter {\n            reference\n            resource {\n              ...Encounter\n            }\n          }\n          onsetDateTime\n          onsetAge {\n            value\n            unit\n            system\n            code\n          }\n          onsetPeriod {\n            start\n            end\n          }\n          recordedDate\n          recorder {\n            reference\n            resource {\n              ...Practitioner\n            }\n          }\n          lastOccurrence\n          note {\n            text\n            time\n          }\n          reaction {\n            substance {\n              text\n              coding {\n                ...Coding\n              }\n            }\n            manifestation {\n              text\n              coding {\n                ...Coding\n              }\n            }\n            onset\n            severity\n            note {\n              text\n              time\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n","import {\n  fragmentBasic,\n  fragmentCoding,\n  fragmentOrganization,\n  fragmentPatient,\n  fragmentPractitioner,\n} from \"../fragments\";\n\nconst subjectFragment = `subject {\n      reference\n      resource {\n        ... on Patient {\n          ...Patient\n          managingOrganization {\n            resource {\n              ... on Organization {\n                name\n              }\n            }\n          }\n        }\n      }\n    }`;\n\nexport const fragmentCondition = `  \n    ${fragmentCoding}\n    ${fragmentPatient}\n    ${fragmentOrganization}\n    ${fragmentBasic}\n    ${fragmentPractitioner}\n    fragment Condition on Condition {\n      id\n      resourceType\n      BasicList(_reference: \"subject\") {\n        ...Basic\n      }\n      meta {\n        tag {\n          system\n          code\n        }\n        versionId\n      }\n      extension {\n        url\n        valueString\n        extension {\n          url\n          valueReference {\n            id\n            type\n            reference\n          }\n        }\n      }\n      ${subjectFragment}\n      abatementAge {\n        value\n      }\n      abatementDateTime\n      abatementPeriod {\n        start\n      }\n      abatementRange {\n        low {\n          value\n        }\n      }\n      abatementString\n      clinicalStatus {\n        coding {\n          ...Coding\n        }\n      }\n      asserter {\n        display\n      }\n      bodySite {\n        text\n        coding {\n          ...Coding\n        }\n      }\n      category {\n        text\n        coding {\n          ...Coding\n        }\n      }\n      code {\n        coding {\n          ...Coding\n        }\n      }\n      encounter {\n        display\n      }\n      evidence {\n        code {\n          coding {\n            ...Coding\n          }\n        }\n      }\n      verificationStatus {\n        coding {\n          ...Coding\n        }\n      }\n      note {\n        text\n      }\n      onsetAge {\n        value\n      }\n      onsetDateTime\n      onsetPeriod {\n        start\n      }\n      onsetRange {\n        low {\n          value\n        }\n      }\n      onsetString\n      recordedDate\n      recorder {\n        display\n        reference\n        resource {\n          ...Practitioner\n        }\n      }\n      severity {\n        coding {\n          ...Coding\n        }\n      }\n      stage {\n        summary {\n          coding {\n            ...Coding\n          }\n        }\n        type {\n          coding {\n            ...Coding\n          }\n        }\n      }\n    }\n  `;\n","import { Condition } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentCondition } from \"./fragments/condition\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface ConditionConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<ConditionWithBasics>[];\n}\n\nexport type ConditionWithBasics = Condition & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface ConditionGraphqlResponse {\n  ConditionConnection: ConditionConnection;\n}\n\nexport const conditionsQuery = gql`\n  ${fragmentCondition}\n  query Conditions(\n    $upid: ID!\n    $cursor: String!\n    $filter: ConditionFilterParams! = {}\n    $sort: ConditionSortParams!\n    $first: Int!\n  ) {\n    ConditionConnection(upid: $upid, after: $cursor, filter: $filter, sort: $sort, first: $first) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          ...Condition\n        }\n      }\n    }\n  }\n`;\n","import { HistoryEntryProps } from \"./helpers/history-entry\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport {\n  useTimingQueryWithPatient,\n} from \"@/components/core/providers/patient-provider\";\nimport { getBinaryId } from \"@/fhir/binaries\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { searchProvenances } from \"@/fhir/provenance\";\nimport { excludeTagsinPatientRecordSearch } from \"@/fhir/search-helpers\";\nimport { ResourceType, ResourceTypeString } from \"@/fhir/types\";\nimport { createGraphqlClient, getResourceNodes } from \"@/services/fqs/client\";\nimport { allergyQuery } from \"@/services/fqs/queries/allergies\";\nimport { conditionsQuery } from \"@/services/fqs/queries/conditions\";\nimport { isEqual, orderBy, uniqWith } from \"@/utils/nodash\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport type UseHistoryProps<T extends ResourceTypeString, M extends FHIRModel<ResourceType<T>>> = {\n  resourceType: T;\n  model: M;\n  queryKey: string;\n  valuesToDedupeOn: (m: M) => unknown;\n  getHistoryEntry: (m: M) => HistoryEntryProps;\n  getFiltersFQS?: (m: M) => object | undefined;\n  clientSideFiltersFQS?: (model: M, resources: ResourceType<T>[]) => ResourceType<T>[];\n};\n\nexport function useHistory<T extends ResourceTypeString, M extends FHIRModel<ResourceType<T>>>({\n  resourceType,\n  model,\n  queryKey,\n  valuesToDedupeOn,\n  getHistoryEntry,\n  getFiltersFQS,\n  clientSideFiltersFQS,\n}: UseHistoryProps<T, M>) {\n  return useTimingQueryWithPatient(\n    queryKey,\n    [model],\n    async (requestContext, patient) =>\n      fetchResourcesFQS(\n        resourceType,\n        model,\n        requestContext,\n        patient,\n        valuesToDedupeOn,\n        getHistoryEntry,\n        clientSideFiltersFQS,\n        getFiltersFQS?.(model),\n      ),\n    true,\n  );\n}\n\nexport function dedupeHistory<T extends fhir4.Resource, M extends FHIRModel<T>>(\n  resources: M[],\n  valuesToDedupeOn: (m: M) => unknown,\n) {\n  // We sort by isEnriched because we want enriched records to be preferred in uniqWith function.\n  const enrichedFirst = orderBy(resources, [\"isEnriched\"], \"desc\");\n\n  return uniqWith(enrichedFirst, (a, b) => isEqual(valuesToDedupeOn(a), valuesToDedupeOn(b)));\n}\n\nfunction getResourceFQSQuery(resourceType: ResourceTypeString) {\n  switch (resourceType) {\n    case \"Condition\":\n      return conditionsQuery;\n    case \"AllergyIntolerance\":\n      return allergyQuery;\n    default:\n      throw new Error(`Resource type to FQS query not implemented yet for ${resourceType}`);\n  }\n}\n\nasync function fetchResourcesFQS<\n  T extends ResourceTypeString,\n  M extends FHIRModel<ResourceType<T>>,\n>(\n  resourceType: T,\n  model: M,\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  valuesToDedupeOn: (m: M) => unknown,\n  getHistoryEntry: (m: M) => HistoryEntryProps,\n  clientSideFiltersFQS?: (model: M, resources: ResourceType<T>[]) => ResourceType<T>[],\n  filter?: object | undefined,\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n\n    const resources =\n      filter || clientSideFiltersFQS\n        ? getResourceNodes<T>(\n            await graphClient.request(getResourceFQSQuery(resourceType), {\n              upid: patient.UPID,\n              cursor: \"\",\n              first: 1000,\n              sort: {\n                lastUpdated: \"DESC\",\n              },\n              filter,\n            }),\n          )\n        : [model.resource];\n\n    let filteredResources = filterLensAndSummary(resources, resourceType);\n\n    if (clientSideFiltersFQS) {\n      filteredResources = clientSideFiltersFQS(model, filteredResources);\n    }\n\n    const constructor = model.constructor as new (r: ResourceType<T>) => M;\n    const models = filteredResources.map((c) => new constructor(c));\n\n    const entries = dedupeHistory(models, valuesToDedupeOn).map(getHistoryEntry);\n\n    // Fetch provenances and add binaryId to each entry.\n    const provenances = await searchProvenances(requestContext, models);\n    entries.forEach((entry) => {\n      // eslint-disable-next-line no-param-reassign\n      entry.binaryId = getBinaryId(provenances, entry.id);\n    });\n\n    return entries;\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching ${resourceType} history for patient via FQS: ${patient.UPID}}`,\n    );\n  }\n}\n\nexport function filterLensAndSummary<T extends ResourceTypeString>(\n  resources: ResourceType<T>[],\n  resourceType: T,\n) {\n  // filter out anything we don't want\n  return resources.filter((resource) => {\n    // no tags are allowed through (should be an edge case)\n    if (!resource.meta || !resource.meta.tag) {\n      return true;\n    }\n\n    const hasExcludableTag =\n      resource.meta.tag.filter((tag) =>\n        excludeTagsinPatientRecordSearch(resourceType).includes(`${tag.system}|${tag.code}`),\n      ).length > 0;\n\n    return !hasExcludableTag;\n  });\n}\n","import { AllergyIntolerance } from \"fhir/r4\";\nimport { HistoryEntryProps } from \"../../resource/helpers/history-entry\";\nimport { useHistory } from \"../../resource/history\";\nimport { AllergyModel } from \"@/fhir/models/allergies\";\nimport { capitalize } from \"@/utils/nodash\";\nimport { QUERY_KEY_ALLERGY_HISTORY } from \"@/utils/query-keys\";\n\nexport function useAllergiesHistory(allergy: AllergyModel) {\n  return useHistory({\n    resourceType: \"AllergyIntolerance\",\n    model: allergy,\n    queryKey: QUERY_KEY_ALLERGY_HISTORY,\n    valuesToDedupeOn,\n    getHistoryEntry,\n    clientSideFiltersFQS,\n  });\n}\n\nfunction clientSideFiltersFQS(model: AllergyModel, allergies: AllergyIntolerance[]) {\n  const tokens = model.knownCodings.map((coding) => `${coding.system}|${coding.code}`);\n  return allergies.filter((allergy) => {\n    const modelTokens = allergy.code?.coding?.map((coding) => `${coding.system}|${coding.code}`);\n    // Sometimes data doesn't have known codings, so we also match on the code.text making sure that it is not blank.\n    const matchingCodeDisplay = model.codeText && allergy.code?.text === model.codeText;\n    const matchingSystemCode = modelTokens?.some((token) => tokens.includes(token));\n    return matchingSystemCode || matchingCodeDisplay;\n  });\n}\n\nfunction getHistoryEntry(allergy: AllergyModel): HistoryEntryProps {\n  const detailData = [\n    { label: \"Status\", value: allergy.clinicalStatus },\n    { label: \"Type\", value: capitalize(allergy.type) },\n    { label: \"Onset\", value: allergy.onset },\n    { label: \"Reaction\", value: capitalize(allergy.manifestations) },\n    { label: \"Severity\", value: capitalize(allergy.severity) },\n    { label: \"Note\", value: allergy.note },\n  ];\n\n  return {\n    id: allergy.id,\n    date: allergy.recordedDate,\n    versionId: allergy.versionId,\n    title: allergy.patientOrganizationName,\n    details: detailData,\n  };\n}\n\nconst valuesToDedupeOn = (allergy: AllergyModel) => [\n  allergy.recordedDate,\n  allergy.patientOrganizationName,\n  allergy.clinicalStatus,\n  allergy.onset,\n  allergy.manifestations,\n  allergy.severity,\n  allergy.note,\n  allergy.knownCodings.map((coding) => [coding.system, coding.code]),\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { AllergyModel } from \"@/fhir/models/allergies\";\n\nexport const defaultAllergySort: SortOption<AllergyModel> = {\n  display: \"Date (New to Old)\",\n  sorts: [{ key: \"recordedDate\", dir: \"desc\", isDate: true }],\n};\n\nexport const allergySortOptions: SortOption<AllergyModel>[] = [\n  defaultAllergySort,\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"recordedDate\", dir: \"asc\", isDate: true }],\n  },\n  {\n    display: \"Name (A-Z)\",\n    sorts: [{ key: \"lowercaseDisplay\", dir: \"asc\" }],\n  },\n  {\n    display: \"Name (Z-A)\",\n    sorts: [{ key: \"lowercaseDisplay\", dir: \"desc\" }],\n  },\n];\n","import parse from \"html-react-parser\";\nimport React, {ReactElement, ReactNode, useEffect, useState} from \"react\";\nimport { cloneDeep } from \"@/utils/nodash\";\n\nimport \"./note-style.scss\";\n\nexport type DetailEntry = {\n  label?: string;\n  value: ReactNode;\n  transposeTables?: boolean;\n};\n\nexport type DetailsProps = {\n  hideEmpty?: boolean;\n  details: DetailEntry[];\n  documentButton?: ReactNode;\n};\n\nconst MIN_SOURCE_COLUMNS_IN_NOTE_TO_TRANSPOSE = 3;\nconst MAX_DEPTH_FIND_TABLE_TO_TRANSPOSE = 6;\n\nexport const recursivelyTransposeTables = (node: ReactNode, curDepth: number): ReactNode => {\n  if (!node || curDepth >= MAX_DEPTH_FIND_TABLE_TO_TRANSPOSE) {\n    return node;\n  }\n\n  // if this doesn't have a props then skip it\n  if (node instanceof Boolean || node instanceof String) {\n    return node;\n  }\n\n  // is this node a table?\n  if ((node as ReactElement).type === \"table\") {\n    const tbl = node as ReactElement;\n    return transposeTable(tbl);\n  }\n\n  const props = Object.hasOwn(node as object, \"props\")\n    ? (node as { props: Record<string, unknown> }).props\n    : {};\n\n  // if there are contents, then it's a big 'ol string of html we need to parse\n  if (props.content) {\n    // try to render it\n    const el = parse(props.content as string, {});\n    return recursivelyTransposeTables(el, curDepth + 1);\n  }\n\n  if (!props.children) {\n    return node;\n  }\n\n  const children = Array.isArray(props.children)\n    ? (props.children as ReactElement[])\n    : ([props.children] as ReactElement[]);\n\n  const newChildren = (children as ReactElement[]).map((child) =>\n    recursivelyTransposeTables(child, curDepth + 1)\n  );\n  const newNode = cloneDeep(node);\n\n  if (!(newNode as ReactElement).props) {\n    return node;\n  }\n\n  // react doesn't want arrays of one; rather, it wants either an object or\n  // an array of 2 or more children\n  if (newChildren.length === 1 && newChildren[0]) {\n    // eslint-disable-next-line prefer-destructuring\n    (newNode as ReactElement).props.children = newChildren[0];\n  } else {\n    (newNode as ReactElement).props.children = newChildren;\n  }\n  return newNode;\n};\n\nconst transposeTable = (tbl: ReactElement): ReactElement => {\n  // if there's no children, then return with original tbl\n  if (!Array.isArray(tbl.props?.children)) {\n    return tbl;\n  }\n\n  // find the thead, otherwise skip\n  const theads = (tbl.props.children as ReactElement[]).filter((child) => child.type === \"thead\");\n  if (theads.length !== 1) {\n    return tbl;\n  }\n  const thead = theads[0];\n\n  // find the tbody, otherwise skip\n  const tbodies = (tbl.props.children as ReactElement[]).filter((child) => child.type === \"tbody\");\n  if (tbodies.length !== 1) {\n    return tbl;\n  }\n  const tbody = tbodies[0];\n\n  // if there's less than the max number of cols, return the original table\n  let headerRows = [] as ReactElement[];\n  if (Array.isArray(thead.props.children)) {\n    headerRows = thead.props.children as ReactElement[];\n  } else if (\n    thead.props.children.type === \"tr\" &&\n    Array.isArray(thead.props.children.props.children)\n  ) {\n    headerRows = thead.props.children.props.children as ReactElement[];\n  } else {\n    headerRows = [thead.props.children.props.children] as ReactElement[];\n  }\n\n  if (headerRows.length < MIN_SOURCE_COLUMNS_IN_NOTE_TO_TRANSPOSE) {\n    return tbl;\n  }\n\n  const dataRows = Array.isArray(tbody.props.children)\n    ? (tbody.props.children as ReactElement[])\n    : ([tbody.props.children] as ReactElement[]);\n  if (!dataRows.length) {\n    return tbl;\n  }\n\n  const newRows = dataRows.reduce((acc, dataRow, rowIdx) => {\n    // now for each cell in the data row\n    const dataCells = Array.isArray(dataRow.props.children)\n      ? (dataRow.props.children as ReactElement[])\n      : ([dataRow.props.children] as ReactElement[]);\n\n    const newDivs = dataCells.reduce((accRow, dataCell, cellIdx) => {\n      const headerRow = headerRows[cellIdx];\n\n      return [\n        ...accRow,\n        // eslint-disable-next-line react/no-array-index-key\n        <div key={`cell-${rowIdx}-${cellIdx}`}>\n          <p className=\"ctw-font-medium\">{headerRow.props.children}</p>\n          <p>{dataCell.props.children}</p>\n        </div>,\n      ];\n    }, [] as ReactElement[]);\n\n    // add an extra div we need to separate data rows\n    if (dataRows.length - 1 > rowIdx) {\n      newDivs.push(\n        <div\n          // eslint-disable-next-line react/no-array-index-key\n          key={`transpose-separator-${rowIdx}`}\n          className=\"ctw-note-transposed-row-separator\"\n        />\n      );\n    }\n\n    return [...acc, ...newDivs];\n  }, [] as ReactElement[]);\n\n  return <div className=\"ctw-note-transposed\">{newRows}</div>;\n};\n\nexport const DetailsCard = ({ details, hideEmpty = true, documentButton }: DetailsProps) => {\n  const [transposedValues, setTransposedValues] = useState(\n    details.map(() => <div>Loading Note...</div>) as ReactNode[]\n  );\n\n  // transposing the tables can take 1-2 seconds, so wrapping in an useEffect to\n  // prevent the screen from freezing\n  useEffect(() => {\n    const newlyTransposedValues = details.map((detail) =>\n      detail.transposeTables ? recursivelyTransposeTables(detail.value, 0) : detail.value\n    );\n    setTransposedValues(newlyTransposedValues);\n  }, [details]);\n\n  return (\n    <div className=\"ctw-rounded-lg ctw-bg-bg-lighter\">\n      <dl className=\"ctw-m-0 ctw-space-y-2 ctw-px-2 ctw-py-6 sm:ctw-px-4\">\n        <div className=\"ctw-flex ctw-justify-between ctw-space-x-2 ctw-text-sm ctw-uppercase ctw-text-content-light\">\n          <div className=\"ctw-title-container\">Details</div>\n          <div className=\"ctw-flex\">{documentButton}</div>\n        </div>\n        {transposedValues.length > 0 &&\n          details.map(({ label, value }, idx) => {\n            // if we want to hide empty rows and the value is falsy and the value\n            // is not zero, then hide it\n            if (hideEmpty && !value && value !== 0) {\n              // eslint-disable-next-line react/no-array-index-key\n              return <div key={idx} />;\n            }\n\n            const valueWithTransposedTables = transposedValues[idx];\n            if (!label) {\n              return (\n                // eslint-disable-next-line react/no-array-index-key\n                <div key={idx} className=\"ctw-text-gray-900 ctw-flex ctw-items-baseline\">\n                  <div className=\"ctw-m-0 ctw-w-full\">{valueWithTransposedTables}</div>\n                </div>\n              );\n            }\n            return (\n              <div key={label} className=\"ctw-text-gray-900 ctw-flex ctw-items-baseline\">\n                <dt className=\"ctw-w-1/3 ctw-flex-shrink-0 ctw-font-medium\">{label}</dt>\n                <dd className=\"ctw-m-0 ctw-w-full\">{valueWithTransposedTables}</dd>\n              </div>\n            );\n          })}\n      </dl>\n    </div>\n  );\n};\n","import { Dialog, Transition } from \"@headlessui/react\";\nimport cx from \"classnames\";\nimport { Fragment, ReactNode } from \"react\";\n\ntype BaseModalProps = {\n  isOpen: boolean;\n  onAfterClosed?: () => void;\n  children: ReactNode;\n  className?: string;\n  id?: string;\n};\n\ntype ModalWithCloseOnEscapeOrBackdrop = BaseModalProps & {\n  closeOnEscapeOrBackdrop: true;\n  onClose: () => void;\n};\n\ntype ModalWithoutCloseOnEscapeOrBackdrop = BaseModalProps & {\n  closeOnEscapeOrBackdrop?: false;\n  onClose?: () => void;\n};\n\nexport type ModalProps = ModalWithCloseOnEscapeOrBackdrop | ModalWithoutCloseOnEscapeOrBackdrop;\n\nexport const Modal = ({\n  isOpen,\n  onAfterClosed,\n  children,\n  className,\n  id,\n  closeOnEscapeOrBackdrop = false,\n  onClose,\n}: ModalProps) => (\n  <Transition appear show={isOpen} as={Fragment}>\n    <Dialog\n      as=\"div\"\n      // change to ctw-z-modal and ctw-z-drawer in main.scss (and make sure the value of z is modal > drawer)\n      className=\"ctw-relative ctw-z-[10100]\"\n      onClose={() => {\n        if (closeOnEscapeOrBackdrop) {\n          onClose?.();\n        }\n      }}\n    >\n      <Transition.Child\n        as={Fragment}\n        enter=\"ctw-ease-out ctw-duration-300\"\n        enterFrom=\"ctw-opacity-0\"\n        enterTo=\"ctw-opacity-100\"\n        leave=\"ctw-ease-in ctw-duration-200\"\n        leaveFrom=\"ctw-opacity-100\"\n        leaveTo=\"ctw-opacity-0\"\n        afterLeave={onAfterClosed}\n      >\n        <div className=\"ctw-fixed ctw-inset-0  ctw-transition-opacity\">\n          <div className=\"ctw-h-full ctw-w-full ctw-bg-content-light ctw-opacity-75\" />\n        </div>\n      </Transition.Child>\n\n      <div className=\"ctw-fixed ctw-inset-0 ctw-overflow-auto\" id={id}>\n        <div className=\"ctw-min-h-full ctw-items-center ctw-p-10 max-lg:ctw-p-4 max-sm:ctw-p-0\">\n          <Transition.Child\n            as={Fragment}\n            enter=\"ctw-ease-out ctw-duration-300\"\n            enterFrom=\"ctw-opacity-0 ctw-scale-95\"\n            enterTo=\"ctw-opacity-100 ctw-scale-100\"\n            leave=\"ctw-ease-in ctw-duration-200\"\n            leaveFrom=\"ctw-opacity-100 ctw-scale-100\"\n            leaveTo=\"ctw-opacity-0 ctw-scale-95\"\n          >\n            <Dialog.Panel\n              className={cx(\n                \"ctw-mr-auto ctw-ml-auto ctw-min-w-fit ctw-max-w-lg ctw-transform ctw-rounded-lg ctw-bg-white ctw-px-10 ctw-py-10 ctw-shadow-xl\",\n                className,\n              )}\n            >\n              <div className=\"ctw-flex ctw-h-full ctw-flex-col ctw-space-y-6\">{children}</div>\n            </Dialog.Panel>\n          </Transition.Child>\n        </div>\n      </div>\n    </Dialog>\n  </Transition>\n);\n","import { XIcon } from \"@heroicons/react/outline\";\nimport { CTW_MODAL_ID } from \"./constants\";\nimport { ViewDocument } from \"@/components/content/CCDA/view-document\";\nimport { Modal, ModalProps } from \"@/components/core/modal\";\nimport { useModal } from \"@/components/core/providers/modal-provider\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\nimport { PatientModel, useAnalytics } from \"@/index\";\n\nexport function useCCDAModal(patient?: PatientModel) {\n  const { openModal } = useModal();\n  const showNewCCDAViewer = useFeatureToggle(\"ctw-ccda-viewer\");\n\n  return (binaryId: string, title: string) => {\n    openModal({\n      component: (props) =>\n        showNewCCDAViewer.enabled ? (\n          <CCDAModal fileName={title} binaryId={binaryId} patient={patient} {...props} />\n        ) : (\n          <CCDAModalOld fileName={title} binaryId={binaryId} {...props} />\n        ),\n    });\n  };\n}\n\ntype CCDAModalProps = {\n  binaryId: string;\n  fileName: string | undefined;\n  onClose: () => void;\n  patient: PatientModel | undefined;\n} & Omit<ModalProps, \"title\" | \"children\">;\n\nconst CCDAModalOld = ({\n  binaryId,\n  fileName,\n  onClose,\n  ...modalProps\n}: Omit<CCDAModalProps, \"patient\">) => {\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <Modal {...modalProps} closeOnEscapeOrBackdrop={false}>\n      <div className=\"ctw-flex ctw-w-full ctw-space-x-4\">\n        <ViewDocument binaryId={binaryId} fileName={fileName} onClose={onClose} />\n\n        <div className=\"ctw-ml-3 ctw-flex ctw-h-7 ctw-items-center\">\n          <button\n            type=\"button\"\n            aria-label=\"close\"\n            onClick={() => {\n              onClose();\n              trackInteraction(\"close_document\");\n            }}\n            className=\"ctw-btn-clear\"\n          >\n            <span className=\"ctw-sr-only\">Close panel</span>\n            <XIcon className=\"ctw-h-6 ctw-w-6\" aria-hidden=\"true\" />\n          </button>\n        </div>\n      </div>\n    </Modal>\n  );\n};\n\nconst CCDAModal = ({ binaryId, fileName, onClose, patient, ...modalProps }: CCDAModalProps) => (\n  <Modal\n    {...modalProps}\n    onClose={onClose}\n    closeOnEscapeOrBackdrop\n    id={CTW_MODAL_ID}\n    className=\"!ctw-py-0 !ctw-px-0 !ctw-min-w-full ctw-max-w-3xl\"\n  >\n    <div className=\"ctw-w-full ctw-items-center\">\n      <ViewDocument patient={patient} binaryId={binaryId} fileName={fileName} onClose={onClose} />\n    </div>\n  </Modal>\n);\n","import { useCallback, useState } from \"react\";\nimport { base64toBlob } from \"@/components/content/CCDA/base64toBlob\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { getBinaryDocument } from \"@/fhir/binaries\";\n\ntype UseDownloadBinary = {\n  downloadBinaryById: (binaryId: string, filename: string) => void;\n  isDownloading: boolean;\n  error?: string;\n};\n\nexport function useDownloadBinary (): UseDownloadBinary {\n  const [isDownloading, setIsDownloading] = useState(false);\n  const [error, setError] = useState<string>();\n  const { getRequestContext } = useCTW();\n\n  const downloadBinaryById = useCallback((binaryId: string, filename: string) => {\n    setIsDownloading(true);\n    setError(undefined);\n\n    const fetchAndDownloadBinary = async () => {\n      let link: HTMLAnchorElement | null = null;\n      try {\n        const requestContext = await getRequestContext();\n        const binary = await getBinaryDocument(requestContext, binaryId);\n        // Create a new Blob from the decoded data\n        let blob: Blob;\n        try {\n          // This method seems to work for pdfs but not for xml. So rather than\n          // try to pre-determine which content types use which method, lets just\n          // attempt to use the base64toBlob we took from FHIRPlace and fallback to\n          // using the new Blob constructor directly.\n          blob = base64toBlob(binary.data ?? \"\", binary.contentType);\n        } catch (e) {\n          blob = new Blob([binary.data ?? \"\"], { type: binary.contentType });\n        }\n\n        // Create a link element, use it to download the file and then remove it\n        link = document.createElement('a');\n        link.href = window.URL.createObjectURL(blob);\n        link.download = filename;\n\n        // Append link to the body\n        document.body.appendChild(link);\n\n        // Trigger download with click\n        link.click();\n      } catch (e) {\n        setError(e instanceof Error ? e.message : `${e}`);\n        // eslint-disable-next-line no-console\n        console.error(`Error downloading binary file: ${e}`);\n      } finally {\n        setIsDownloading(false);\n        // Clean up and remove the link\n        link?.parentNode?.removeChild(link);\n      }\n    }\n\n    void fetchAndDownloadBinary();\n  }, [getRequestContext]);\n\n  return { downloadBinaryById, isDownloading, error };\n}\n","import { faExternalLinkAlt } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { useEffect, useState } from \"react\";\nimport { useCCDAModal } from \"@/components/content/CCDA/modal-ccda\";\nimport { useDownloadBinary } from \"@/components/content/CCDA/use-download-binary\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { ContentTypeIcon } from \"@/components/core/icons/content-type-icon\";\nimport { Loading } from \"@/components/core/loading\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\n\nexport type ResponsiveDocumentButtonProps = Partial<{\n  binaryId: string;\n  contentType?: string;\n  documentTitle: string;\n  forceInModel?: boolean;\n  showIcon: boolean;\n  telemetryTarget: string;\n  text?: string;\n}>;\n\nconst MAX_CCDA_VIEWER_WIDTH = 460;\n\nexport const ResponsiveSourceDocumentLink = ({\n  binaryId,\n  contentType = \"\",\n  documentTitle = \"Source Document\",\n  forceInModel = false,\n  text = \"Source Document\",\n  telemetryTarget = \"none\",\n  showIcon = true,\n}: ResponsiveDocumentButtonProps) => {\n  const openCCDAModal = useCCDAModal();\n  const { allowSmallBreakpointCCDAViewer, featureFlags } = useCTW();\n  const { trackInteraction } = useAnalytics();\n  const { downloadBinaryById, error, isDownloading } = useDownloadBinary();\n  const [width, setWidth] = useState(window.innerWidth);\n\n  useEffect(() => {\n    window.addEventListener(\"resize\", () => setWidth(window.innerWidth));\n  }, []);\n\n  if (!binaryId) {\n    return null;\n  }\n\n  const isDownloadBtn = !allowSmallBreakpointCCDAViewer && width < MAX_CCDA_VIEWER_WIDTH;\n  const downloadText = isDownloadBtn && !isDownloading ? \"Download\" : \"\";\n  const showOpenInNewTab = !isDownloadBtn && !forceInModel && featureFlags?.openCCDAInNewTab;\n\n  return (\n    <>\n      {error && <ErrorAlert header={error} />}\n      {showOpenInNewTab ? (\n        <a\n          aria-label=\"Open in new tab\"\n          href={`/ccda/${binaryId}`}\n          className=\"ctw-btn-clear ctw-link ctw-flex ctw-items-center ctw-space-x-2\"\n          rel=\"noopener noreferrer\"\n          target=\"_blank\"\n        >\n          <FontAwesomeIcon icon={faExternalLinkAlt} className=\"ctw-h-3\" />\n          <span className=\"ctw-normal-case\">{text}</span>\n        </a>\n      ) : (\n        <button\n          type=\"button\"\n          className=\"ctw-btn-clear ctw-link ctw-flex ctw-items-center ctw-space-x-2\"\n          disabled={isDownloading}\n          onClick={() => {\n            if (isDownloadBtn) {\n              downloadBinaryById(binaryId, documentTitle);\n              trackInteraction(\"download_document\", { target: telemetryTarget });\n            } else {\n              openCCDAModal(binaryId, documentTitle);\n              trackInteraction(\"open_source_document\", { target: telemetryTarget });\n            }\n          }}\n        >\n          {showIcon && (\n            <ContentTypeIcon contentType={contentType} />\n          )}\n          <span className=\"ctw-block\">\n            {!isDownloading ? downloadText : <Loading className=\"ctw-h-3\" message=\"Downloading\" />}{\" \"}\n            {text}\n          </span>\n        </button>\n      )}\n    </>\n  );\n};\n","import { faFileLines } from \"@fortawesome/free-regular-svg-icons\";\nimport { faChevronRight } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useState } from \"react\";\nimport { DetailEntry, DetailsCard } from \"./details-card\";\nimport { ResponsiveSourceDocumentLink } from \"@/components/content/CCDA/responsive-source-document-link\";\nimport {\n  TrackingMetadata,\n  useAnalytics,\n} from \"@/components/core/providers/analytics/use-analytics\";\n\nexport type HistoryEntryProps = {\n  binaryId?: string;\n  date?: string;\n  details: DetailEntry[];\n  hideEmpty?: boolean;\n  id: string;\n  subtitle?: string;\n  title?: string;\n  versionId?: string;\n};\n\ntype Props = HistoryEntryProps & { resourceTypeTitle: string; trackingMetadata?: TrackingMetadata };\n\nexport const HistoryEntry = ({\n  binaryId,\n  date,\n  details,\n  hideEmpty,\n  subtitle,\n  title,\n  resourceTypeTitle,\n}: Props) => {\n  const [isDetailShown, setIsDetailShown] = useState(false);\n\n  return (\n    <div className=\"ctw-space-y-1\">\n      <DetailSummary\n        date={date}\n        title={title}\n        subtitle={subtitle}\n        isDetailShown={isDetailShown}\n        setIsDetailShown={setIsDetailShown}\n        hasDocument={!!binaryId}\n      />\n      {isDetailShown && (\n        <DetailsCard\n          details={details}\n          hideEmpty={hideEmpty}\n          documentButton={\n            <ResponsiveSourceDocumentLink\n              binaryId={binaryId}\n              documentTitle={resourceTypeTitle}\n              telemetryTarget=\"history_entry\"\n            />\n          }\n        />\n      )}\n    </div>\n  );\n};\n\nconst DetailSummary = ({\n  date,\n  title,\n  subtitle,\n  isDetailShown,\n  hasDocument = false,\n  setIsDetailShown,\n}: {\n  date?: string;\n  title?: string;\n  subtitle?: string;\n  isDetailShown: boolean;\n  hasDocument?: boolean;\n  setIsDetailShown: React.Dispatch<React.SetStateAction<boolean>>;\n}) => {\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <button\n      type=\"button\"\n      aria-label=\"details\"\n      onClick={() => {\n        setIsDetailShown(!isDetailShown);\n        trackInteraction(\"toggle_history_entry\", {\n          action: isDetailShown ? \"collapse_history_entry\" : \"expand_history_entry\",\n        });\n      }}\n      className=\"ctw-btn-clean\"\n    >\n      <div className=\"ctw-flex ctw-items-center ctw-justify-between ctw-rounded-lg ctw-bg-bg-white ctw-p-3 ctw-text-left ctw-outline ctw-outline-1 ctw-outline-bg-dark\">\n        <div className=\"ctw-flex ctw-space-x-3\">\n          <div className=\"ctw-min-w-[5rem]\">\n            {date ?? <span className=\"ctw-text-content-lighter\">Unknown</span>}\n          </div>\n          {(title || subtitle) && (\n            <div>\n              <div className=\"ctw-font-semibold ctw-text-content-black\">{title}</div>\n              <div className=\"ctw-text-content-light\">{subtitle}</div>\n            </div>\n          )}\n          {/* Show unknown in the title spot if we don't have one AND if we aren't already\n            showing \"Unknown\" in the date spot. */}\n          {!title && !subtitle && date && <div className=\"ctw-text-content-lighter\">Unknown</div>}\n        </div>\n        <div className=\"ctw-flex ctw-items-center ctw-space-x-3\">\n          {hasDocument && (\n            <FontAwesomeIcon icon={faFileLines} className=\"ctw-h-5 ctw-text-content-light\" />\n          )}\n          <div className=\"ctw-justify-right ctw-flex\">\n            <FontAwesomeIcon\n              icon={faChevronRight}\n              className={cx(\"ctw-h-3 ctw-w-3 ctw-text-content-lighter\", {\n                \"ctw-rotate-90\": isDetailShown,\n              })}\n            />\n          </div>\n        </div>\n      </div>\n    </button>\n  );\n};\n","import { useState } from \"react\";\nimport { HistoryEntry, HistoryEntryProps } from \"./history-entry\";\nimport { Loading } from \"@/components/core/loading\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { orderBy } from \"@/utils/nodash\";\nimport { UseQueryResultBasic } from \"@/utils/request\";\n\nexport type HistoryEntries = HistoryEntryProps[];\n\nexport type HistoryProps<M> = {\n  limit?: number;\n  getHistory?: (model: M) => UseQueryResultBasic<HistoryEntries | undefined>;\n  model: M;\n};\n\nconst DEFAULT_HISTORY_PAGE_LIMIT = 20;\n\nexport function History<T extends fhir4.Resource, M extends FHIRModel<T>>({\n  limit = DEFAULT_HISTORY_PAGE_LIMIT,\n  getHistory,\n  model,\n}: HistoryProps<M>) {\n  const history = getHistory && getHistory(model);\n  const entries: HistoryEntries = history?.data ?? [];\n  const [showAll, setShowAll] = useState(!limit || entries.length <= limit);\n  const { resourceTypeTitle } = model;\n\n  // Sort entries by:\n  //  1. date descending\n  //  2. has a source document (binaryId present or not)\n  //  3. title ascending\n  //  4. subtitle ascending\n  //  5. versionId descending (this is to ensure consistent ordering)\n  const sortedEntries = orderBy(\n    entries,\n    [\n      // Convert the date string to a Date object so that it sorts correctly.\n      (e) => (e.date ? new Date(e.date) : \"\"), // desc\n      // We want to promote entries with a source document to the top.\n      (e) => !!e.binaryId, // desc\n      \"title\", // asc\n      \"subtitle\", // asc\n      \"versionId\", // desc\n    ],\n    [\"desc\", \"desc\", \"asc\", \"asc\", \"desc\"]\n  );\n\n  const displayedEntries = showAll || !limit ? sortedEntries : sortedEntries.slice(0, limit);\n\n  return history && history.isLoading ? (\n    <Loading message=\"Loading history...\" />\n  ) : (\n    <div className=\"ctw-space-y-4\">\n      <div className=\"ctw-text-lg ctw-font-semibold\">History</div>\n      {displayedEntries.map((entry, idx) => (\n        // We can have multiple items with the same condition id\n        // eslint-disable-next-line react/no-array-index-key\n        <div key={`${entry.id}-${idx}`}>\n          <HistoryEntry\n            id={entry.id}\n            date={entry.date}\n            title={entry.title}\n            subtitle={entry.subtitle}\n            details={entry.details}\n            hideEmpty={entry.hideEmpty}\n            binaryId={entry.binaryId}\n            resourceTypeTitle={resourceTypeTitle}\n          />\n        </div>\n      ))}\n      {!showAll && (\n        <div className=\"ctw-text-center\">\n          <button type=\"button\" className=\"ctw-btn-primary\" onClick={() => setShowAll(true)}>\n            {/* We know limit must be set if showAll is false. */}\n            {/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */}\n            Load {sortedEntries.length - limit!} More\n          </button>\n        </div>\n      )}\n    </div>\n  );\n}\n","import { Basic } from \"fhir/r4\";\nimport { FhirResource } from \"fhir-kit-client\";\nimport { createOrEditFhirResource } from \"./action-helper\";\nimport { FHIRModel } from \"./models/fhir-model\";\nimport { getUsersPractitionerReference } from \"./practitioner\";\nimport { SYSTEM_BASIC_RESOURCE_TYPE, SYSTEM_ZUS_PROFILE_ACTION } from \"./system-urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport async function recordProfileAction<T extends fhir4.Resource>(\n  existingBasic: Basic | undefined,\n  model: FHIRModel<T>,\n  requestContext: CTWRequestContext,\n  profileAction: string\n) {\n  if (!model.id) {\n    throw new Error(`Tried to ${profileAction} a resource that hasn't been created yet.`);\n  }\n\n  if (model.ownedByBuilder(requestContext.builderId)) {\n    throw new Error(`Tried to ${profileAction} a patient record resource.`);\n  }\n\n  const basic: fhir4.Basic = {\n    resourceType: \"Basic\",\n    id: existingBasic?.id,\n    code: {\n      coding: [\n        {\n          system: SYSTEM_BASIC_RESOURCE_TYPE,\n          code: \"adminact\",\n          display: \"Administrative Activity\",\n        },\n        {\n          system: SYSTEM_ZUS_PROFILE_ACTION,\n          code: profileAction,\n        },\n      ],\n    },\n    subject: {\n      reference: `${model.resourceType}/${model.id}`,\n      type: model.resourceType,\n    },\n    author: await getUsersPractitionerReference(requestContext),\n  };\n\n  const response = (await createOrEditFhirResource(basic, requestContext)) as FhirResource;\n\n  if (!response.id) {\n    Telemetry.reportActionFailure(profileAction);\n    throw new Error(`Failed to ${profileAction} resource with id of ${model.id}`);\n  } else {\n    Telemetry.reportActionSuccess(profileAction);\n  }\n}\n\nexport async function toggleDismiss<T extends fhir4.Resource>(\n  model: FHIRModel<T>,\n  requestContext: CTWRequestContext\n) {\n  const existingBasic = model.getLatestAction([\"archive\", \"unarchive\"]);\n  const profileAction = model.isDismissed ? \"unarchive\" : \"archive\";\n  model.optimisticToggleIsDismiss();\n  await recordProfileAction(existingBasic, model, requestContext, profileAction);\n}\n\nexport async function toggleRead<T extends fhir4.Resource>(\n  model: FHIRModel<T>,\n  requestContext: CTWRequestContext\n) {\n  const existingBasic = model.getLatestAction([\"read\", \"unread\"]);\n  const profileAction = model.isRead ? \"unread\" : \"read\";\n  model.optimisticToggleIsRead();\n  await recordProfileAction(existingBasic, model, requestContext, profileAction);\n}\n","import { useCallback, useState } from \"react\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { notify } from \"@/components/core/toast\";\nimport { toggleDismiss } from \"@/fhir/basic\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\ninterface UseToggleDismissResult {\n  /**\n   * Function to call to toggle the archive status of the FHIR model\n   */\n  toggleDismiss: (model: FHIRModel<fhir4.Resource>) => Promise<void>;\n\n  /**\n   * True when `toggleArchive` is called\n   */\n  isLoading: boolean;\n}\n\n/**\n * This hook is toggles the dismiss status for the specified FHIR model.\n */\nexport function useToggleDismiss(): UseToggleDismissResult {\n  const { getRequestContext } = useCTW();\n\n  const [isLoading, setIsLoading] = useState<boolean>(false);\n\n  const handleToggleDismiss = useCallback(async (model: FHIRModel<fhir4.Resource>) => {\n    setIsLoading(true);\n    await toggleDismiss(model, await getRequestContext());\n    notify({\n      type: \"info\",\n      title: `${model.title} ${model.isDismissed ? \"dismissed\" : \"restored\"}.`,\n    });\n    setIsLoading(false);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return {\n    toggleDismiss: handleToggleDismiss,\n    isLoading,\n  };\n}\n","import { useCallback, useState } from \"react\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { toggleRead } from \"@/fhir/basic\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\ninterface UseToggleReadResult {\n  /**\n   * Function to call to toggle the read status of the FHIR model\n   */\n  toggleRead: (model: FHIRModel<fhir4.Resource>) => Promise<void>;\n\n  /**\n   * True when `toggleRead` is called\n   */\n  isLoading: boolean;\n}\n\n/**\n * This hook toggles the read status for the specified FHIR model.\n */\nexport function useToggleRead(): UseToggleReadResult {\n  const { getRequestContext } = useCTW();\n\n  const [isLoading, setIsLoading] = useState<boolean>(false);\n\n  const handleToggleRead = useCallback(async (model: FHIRModel<fhir4.Resource>) => {\n    const requestContext = await getRequestContext();\n    // In production we want to avoid non-builder users from inadvertantly marking records as read\n    // In lower environments this is allowed for demos/testing\n    if (requestContext.env === \"production\" && requestContext.userType !== \"builder\") {\n      return;\n    }\n    setIsLoading(true);\n    await toggleRead(model, await getRequestContext());\n    setIsLoading(false);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return {\n    toggleRead: handleToggleRead,\n    isLoading,\n  };\n}\n","import { IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport { Menu } from \"@headlessui/react\";\nimport * as RadixDropdownMenu from \"@radix-ui/react-dropdown-menu\";\nimport cx from \"classnames\";\nimport { ReactNode, useState } from \"react\";\nimport \"./dropdown-action-menu.scss\";\n\nexport type MenuItem = {\n  action: () => void;\n  className?: string;\n  icon?: IconDefinition;\n  name: string;\n};\n\nexport type OptionsItem = {\n  key: string;\n  name: string;\n  display?: ReactNode;\n  disabled?: boolean;\n  isSelected?: boolean;\n};\n\nexport type DropdownMenuSimpleProps = {\n  buttonClassName?: cx.Argument;\n  children: ReactNode;\n  items: OptionsItem[];\n  onItemSelect: (clickedItem: { key: string; name: string; value: boolean }) => void;\n  isOpen?: boolean;\n} & Partial<Pick<RadixDropdownMenu.MenuContentProps, \"align\" | \"side\">>;\n\nexport function DropdownMenuSimple({\n  children,\n  items,\n  onItemSelect,\n  buttonClassName,\n  isOpen,\n  side,\n  align = \"start\",\n}: DropdownMenuSimpleProps) {\n  const [isMenuOpen, setIsMenuOpen] = useState(isOpen);\n  return (\n    <Menu>\n      <RadixDropdownMenu.Root\n        modal={false}\n        open={isMenuOpen}\n        onOpenChange={(e) => setIsMenuOpen(e)}\n      >\n        <RadixDropdownMenu.Trigger className={cx(buttonClassName)} aria-label=\"dropdown\">\n          {children}\n        </RadixDropdownMenu.Trigger>\n        <RadixDropdownMenu.Content\n          align={align}\n          side={side}\n          // Prevent focus from closing menu, this fixes\n          // an issue with interactive testing where a \"click\"\n          // would fire twice, once for the mousedown and\n          // again for focus on the button being clicked.\n          onFocusOutside={(event) => event.preventDefault()}\n          className=\"ctw-dropdown-action-menu ctw-bg-bg-white\"\n          collisionPadding={10}\n        >\n          {items.map((menuItem) => (\n            <RadixDropdownMenu.Item\n              key={menuItem.key}\n              className={cx(\"ctw-dropdown-action-menu-item ctw-bg-bg-white\")}\n              onClick={() => {\n                if (!menuItem.disabled) {\n                  onItemSelect({\n                    key: menuItem.key,\n                    name: menuItem.name,\n                    value: !menuItem.isSelected,\n                  });\n                }\n              }}\n            >\n              <div\n                className={cx(\"ctw-flex ctw-w-full ctw-justify-between\", {\n                  \"ctw-text-content-lighter\": menuItem.disabled,\n                  \"!ctw-text-content-black\": !menuItem.disabled,\n                })}\n              >\n                {menuItem.display ? menuItem.display : menuItem.name}\n              </div>\n            </RadixDropdownMenu.Item>\n          ))}\n        </RadixDropdownMenu.Content>\n      </RadixDropdownMenu.Root>\n    </Menu>\n  );\n}\n","import { useEffect, useState } from \"react\";\nimport { CTWRequestContext } from \"./ctw-context\";\nimport { useCTW } from \"./use-ctw\";\n\nexport function useRequestContext() {\n  const { getRequestContext } = useCTW();\n  const [requestContext, setRequestContext] = useState<CTWRequestContext>();\n\n  useEffect(() => {\n    let isMounted = true;\n    async function load() {\n      const ctx = await getRequestContext();\n      if (isMounted) {\n        setRequestContext(ctx);\n      }\n    }\n\n    void load();\n    return () => {\n      isMounted = false;\n    };\n  }, [getRequestContext]);\n\n  return requestContext;\n}\n","import { useEffect, useState } from \"react\";\nimport { useCTW } from \"./use-ctw\";\n\nexport function useUserBuilderId() {\n  const { getRequestContext } = useCTW();\n  const [userBuilderId, setUserBuilderId] = useState(\"\");\n\n  useEffect(() => {\n    async function load() {\n      const requestContext = await getRequestContext();\n      setUserBuilderId(requestContext.builderId);\n    }\n\n    void load();\n  }, [getRequestContext]);\n\n  return userBuilderId;\n}\n","\"use strict\";\nexports.__esModule = true;\nexports.sharedRoot = void 0;\nexports.sharedRoot = {\n    fontFamily: 'Menlo, Monaco, \"Courier New\", monospace',\n    fontFeatureSettings: '\"liga\" 0, \"calt\" 0',\n    lineHeight: '1.5em',\n    whiteSpace: 'pre',\n    margin: 0\n};\n","\"use strict\";\nexports.__esModule = true;\nvar __shared__1 = require(\"./__shared__\");\nexports[\"default\"] = {\n    styles: {\n        root: Object.assign({}, __shared__1.sharedRoot, { backgroundColor: '#f8f8f8' }),\n        attribute: { color: '#333' },\n        unquotedAttribute: { color: '#333' },\n        string: { color: '#de1044' },\n        nil: { color: '#008080' },\n        number: { color: '#008080' },\n        boolean: { color: '#008080' },\n        punctuation: { color: '#333' }\n    }\n};\n","import { createContext } from \"react\";\n\nexport const ToastContext = createContext(undefined);\n","import { ReactNode } from \"react\";\nimport { ToastContainer, Zoom } from \"react-toastify\";\nimport { ToastContext } from \"./toast-context\";\nimport { APP_TOAST_CONTAINER_ID } from \"../toast\";\n\nimport \"react-toastify/dist/ReactToastify.css\";\nimport \"../toast.scss\";\n\ninterface ProviderProps {\n  children: ReactNode;\n  containerId?: string;\n}\n\nexport function ToastProvider({ children, containerId }: ProviderProps) {\n  return (\n    <ToastContext.Provider value={undefined}>\n      <ToastContainer\n        position=\"bottom-left\"\n        autoClose={40000}\n        hideProgressBar\n        closeOnClick\n        rtl={false}\n        limit={1}\n        transition={Zoom}\n        pauseOnFocusLoss\n        pauseOnHover\n        theme=\"colored\"\n        enableMultiContainer\n        containerId={containerId || APP_TOAST_CONTAINER_ID}\n      />\n      {children}\n    </ToastContext.Provider>\n  );\n}\n","import \"./drawer.scss\";\n\nimport { Dialog, Transition } from \"@headlessui/react\";\nimport cx from \"classnames\";\nimport type { ReactNode } from \"react\";\nimport { Fragment, useRef } from \"react\";\nimport { ToastProvider } from \"./providers/toast-provider\";\nimport { APP_TOAST_CONTAINER_DRAWER_ID } from \"./toast\";\nimport {\n  TrackingMetadata,\n  useAnalytics,\n} from \"@/components/core/providers/analytics/use-analytics\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\nexport type DrawerProps = {\n  className?: string;\n  children: ReactNode;\n  isOpen: boolean;\n  onOpen?: () => void;\n  onAfterOpen?: () => void;\n  onClose: () => void;\n  /** Called after drawer closing animation has ended. Use this for\n   * any cleanup that would affect the content displayed in the drawer.\n   */\n  onAfterClosed?: () => void;\n  /** Shows a simple footer with a single \"Close\" button. */\n  showCloseFooter?: boolean;\n  /** Prevent drawer from closing on ESC or background click. */\n  disableCloseOnBlur?: boolean;\n  title: string;\n  trackingMetadata?: TrackingMetadata;\n};\n\nconst transitionClasses = \"ctw-transform ctw-transition ctw-ease-in-out ctw-duration-300\";\n\n/**\n * Drawer is a side-panel that slides in/out from the right.\n * It has a title section at top and displays children below.\n *\n * `Drawer.Body` & `Drawer.Footer` can be used as children to create\n * a scrollable body section with a fixed footer.\n */\nexport function Drawer({\n  isOpen,\n  onClose,\n  onAfterClosed,\n  onOpen,\n  onAfterOpen,\n  children,\n  className,\n  showCloseFooter,\n  title,\n  disableCloseOnBlur = false,\n}: DrawerProps) {\n  return (\n    <Transition.Root show={isOpen} as={Fragment}>\n      <Dialog\n        as=\"div\"\n        className={cx(\"ctw-drawer ctw-relative ctw-z-[10000]\", className)}\n        onClose={() => {\n          if (!disableCloseOnBlur) {\n            onClose();\n          }\n          /* otherwise do not close on esc or backdrop click  */\n        }}\n      >\n        <Transition.Child\n          as={Fragment}\n          enter={transitionClasses}\n          enterFrom=\"ctw-opacity-0\"\n          enterTo=\"ctw-opacity-100\"\n          leave={transitionClasses}\n          leaveFrom=\"ctw-opacity-100\"\n          leaveTo=\"ctw-opacity-0\"\n          afterLeave={onAfterClosed}\n          beforeEnter={onOpen}\n          afterEnter={onAfterOpen}\n        >\n          <div className=\"ctw-fixed ctw-inset-0  ctw-transition-opacity\">\n            <div className=\"ctw-h-full ctw-w-full ctw-bg-content-light ctw-opacity-75\" />\n          </div>\n        </Transition.Child>\n        <DrawerContent onClose={onClose} showCloseFooter={showCloseFooter} title={title}>\n          <ToastProvider containerId={APP_TOAST_CONTAINER_DRAWER_ID}>{children}</ToastProvider>\n        </DrawerContent>\n      </Dialog>\n    </Transition.Root>\n  );\n}\n\n// DrawerContent is the actual content of the drawer. It is separated out from the\n// Drawer component itself because the `ref` doesn't work properly when it is created\n// in the same component as the Transition.Root.\nfunction DrawerContent({\n  children,\n  onClose,\n  showCloseFooter,\n  title,\n}: Pick<DrawerProps, \"children\" | \"onClose\" | \"showCloseFooter\" | \"title\">) {\n  const { trackInteraction } = useAnalytics();\n  const ref = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(ref);\n\n  return (\n    <div ref={ref} className=\"ctw-fixed ctw-inset-0 ctw-overflow-hidden\">\n      <div className=\"ctw-absolute ctw-inset-0 ctw-overflow-hidden\">\n        <div\n          className={cx(\n            \"ctw-pointer-events-none ctw-fixed ctw-inset-y-0 ctw-right-0 ctw-flex ctw-max-w-full\",\n            {\n              \"ctw-pl-10\": !breakpoints.sm,\n            },\n          )}\n        >\n          <Transition.Child\n            as={Fragment}\n            enter={transitionClasses}\n            enterFrom=\"ctw-translate-x-full\"\n            enterTo=\"ctw-translate-x-0\"\n            leave={transitionClasses}\n            leaveFrom=\"ctw-translate-x-0\"\n            leaveTo=\"ctw-translate-x-full\"\n          >\n            <Dialog.Panel className=\"ctw-pointer-events-auto ctw-w-screen ctw-max-w-xl\">\n              <div className=\"ctw-flex ctw-h-full ctw-flex-col ctw-bg-white ctw-shadow-xl\">\n                <div\n                  className={cx(\n                    \"ctw-flex ctw-h-14 ctw-flex-shrink-0 ctw-items-center ctw-justify-between ctw-border-0 ctw-border-b ctw-border-solid ctw-border-content-lighter\",\n                    breakpoints.sm ? \"ctw-px-3\" : \"ctw-px-6\",\n                  )}\n                >\n                  <Dialog.Title\n                    className={cx(\"ctw-pl-2 ctw-text-lg ctw-font-semibold ctw-text-content-black\")}\n                  >\n                    {title}\n                  </Dialog.Title>\n                </div>\n\n                {children}\n                {showCloseFooter && (\n                  <Drawer.Footer>\n                    <Drawer.CloseButton\n                      label=\"Close\"\n                      onClose={() => {\n                        onClose();\n                        trackInteraction(\"close_drawer\", {\n                          target: \"footer_close_icon\",\n                        });\n                      }}\n                    />\n                  </Drawer.Footer>\n                )}\n              </div>\n            </Dialog.Panel>\n          </Transition.Child>\n        </div>\n      </div>\n    </div>\n  );\n}\nconst DrawerFooter = ({ children }: { children: ReactNode }) => {\n  const ref = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(ref);\n  return (\n    <div\n      ref={ref}\n      className={cx(\"ctw-footer ctw-border-default ctw-border-t\", {\n        \"ctw-p-6\": !breakpoints.sm,\n        \"ctw-p-3\": breakpoints.sm,\n      })}\n    >\n      {children}\n    </div>\n  );\n};\n\nconst DrawerCloseButton = ({ label, onClose }: { label: string; onClose: () => void }) => (\n  <button type=\"button\" className=\"ctw-btn-clear !ctw-px-4 !ctw-py-2\" onClick={onClose}>\n    {label}\n  </button>\n);\n\nconst DrawerBody = ({ children }: { children: ReactNode }) => {\n  const ref = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(ref);\n\n  return (\n    <div\n      ref={ref}\n      className={cx(\"ctw-flex ctw-h-full ctw-flex-col ctw-overflow-y-auto\", {\n        \"ctw-p-6\": !breakpoints.sm,\n        \"ctw-p-3\": breakpoints.sm,\n      })}\n    >\n      {children}\n    </div>\n  );\n};\n\nDrawer.Body = DrawerBody;\nDrawer.Footer = DrawerFooter;\nDrawer.CloseButton = DrawerCloseButton;\n","import { FireIcon } from \"@heroicons/react/solid\";\nimport cx from \"classnames\";\nimport { ReactJason } from \"react-jason\";\nimport github from \"react-jason/themes/github\";\nimport { Drawer } from \"./drawer\";\nimport { useDrawer } from \"./providers/drawer-provider\";\nimport \"./view-fhir.scss\";\n\nexport type ViewFHIRProps = {\n  name?: string;\n  resource: fhir4.Resource;\n};\n\nexport function useFHIRDrawer() {\n  const { openDrawer } = useDrawer();\n\n  return (name: string, resource: fhir4.Resource) => {\n    openDrawer({\n      component: (props) => <FHIRDrawer name={name} resource={resource} {...props} />,\n      trackingMetadata: { action: \"view_fhir\" },\n    });\n  };\n}\n\nexport function ViewFHIR({ name = \"View FHIR\", resource }: ViewFHIRProps) {\n  const openDrawer = useFHIRDrawer();\n\n  return (\n    <button\n      type=\"button\"\n      aria-label={name}\n      className=\"ctw-btn-default\"\n      onClick={() => {\n        openDrawer(name, resource);\n      }}\n    >\n      <span className=\"ctw-relative ctw-inline-block ctw-w-4 ctw-pr-4 ctw-align-middle\">\n        <FireIcon className=\"ctw-absolute -ctw-top-2.5 ctw-left-0 ctw-h-4\" />\n      </span>\n    </button>\n  );\n}\n\ntype FHIRDrawerProps = {\n  name: string;\n  className?: string;\n  resource: fhir4.Resource;\n  isOpen: boolean;\n  onClose: () => void;\n};\n\nfunction FHIRDrawer({ resource, isOpen, onClose, className, name }: FHIRDrawerProps) {\n  return (\n    <Drawer\n      className={cx(className, \"ctw-view-fhir\")}\n      title={name}\n      isOpen={isOpen}\n      onClose={onClose}\n      showCloseFooter\n    >\n      <Drawer.Body>\n        <div className=\"ctw-text-sm react-json-pre-wrapper\">\n          <ReactJason value={resource} theme={github} />\n        </div>\n      </Drawer.Body>\n    </Drawer>\n  );\n}\n","const consoleLogger = {\n  type: 'logger',\n  log(args) {\n    this.output('log', args);\n  },\n  warn(args) {\n    this.output('warn', args);\n  },\n  error(args) {\n    this.output('error', args);\n  },\n  output(type, args) {\n    if (console && console[type]) console[type].apply(console, args);\n  }\n};\nclass Logger {\n  constructor(concreteLogger) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    this.init(concreteLogger, options);\n  }\n  init(concreteLogger) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    this.prefix = options.prefix || 'i18next:';\n    this.logger = concreteLogger || consoleLogger;\n    this.options = options;\n    this.debug = options.debug;\n  }\n  log() {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n    return this.forward(args, 'log', '', true);\n  }\n  warn() {\n    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      args[_key2] = arguments[_key2];\n    }\n    return this.forward(args, 'warn', '', true);\n  }\n  error() {\n    for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n      args[_key3] = arguments[_key3];\n    }\n    return this.forward(args, 'error', '');\n  }\n  deprecate() {\n    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n      args[_key4] = arguments[_key4];\n    }\n    return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n  }\n  forward(args, lvl, prefix, debugOnly) {\n    if (debugOnly && !this.debug) return null;\n    if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`;\n    return this.logger[lvl](args);\n  }\n  create(moduleName) {\n    return new Logger(this.logger, {\n      ...{\n        prefix: `${this.prefix}:${moduleName}:`\n      },\n      ...this.options\n    });\n  }\n  clone(options) {\n    options = options || this.options;\n    options.prefix = options.prefix || this.prefix;\n    return new Logger(this.logger, options);\n  }\n}\nvar baseLogger = new Logger();\n\nclass EventEmitter {\n  constructor() {\n    this.observers = {};\n  }\n  on(events, listener) {\n    events.split(' ').forEach(event => {\n      this.observers[event] = this.observers[event] || [];\n      this.observers[event].push(listener);\n    });\n    return this;\n  }\n  off(event, listener) {\n    if (!this.observers[event]) return;\n    if (!listener) {\n      delete this.observers[event];\n      return;\n    }\n    this.observers[event] = this.observers[event].filter(l => l !== listener);\n  }\n  emit(event) {\n    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      args[_key - 1] = arguments[_key];\n    }\n    if (this.observers[event]) {\n      const cloned = [].concat(this.observers[event]);\n      cloned.forEach(observer => {\n        observer(...args);\n      });\n    }\n    if (this.observers['*']) {\n      const cloned = [].concat(this.observers['*']);\n      cloned.forEach(observer => {\n        observer.apply(observer, [event, ...args]);\n      });\n    }\n  }\n}\n\nfunction defer() {\n  let res;\n  let rej;\n  const promise = new Promise((resolve, reject) => {\n    res = resolve;\n    rej = reject;\n  });\n  promise.resolve = res;\n  promise.reject = rej;\n  return promise;\n}\nfunction makeString(object) {\n  if (object == null) return '';\n  return '' + object;\n}\nfunction copy(a, s, t) {\n  a.forEach(m => {\n    if (s[m]) t[m] = s[m];\n  });\n}\nfunction getLastOfPath(object, path, Empty) {\n  function cleanKey(key) {\n    return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;\n  }\n  function canNotTraverseDeeper() {\n    return !object || typeof object === 'string';\n  }\n  const stack = typeof path !== 'string' ? [].concat(path) : path.split('.');\n  while (stack.length > 1) {\n    if (canNotTraverseDeeper()) return {};\n    const key = cleanKey(stack.shift());\n    if (!object[key] && Empty) object[key] = new Empty();\n    if (Object.prototype.hasOwnProperty.call(object, key)) {\n      object = object[key];\n    } else {\n      object = {};\n    }\n  }\n  if (canNotTraverseDeeper()) return {};\n  return {\n    obj: object,\n    k: cleanKey(stack.shift())\n  };\n}\nfunction setPath(object, path, newValue) {\n  const {\n    obj,\n    k\n  } = getLastOfPath(object, path, Object);\n  obj[k] = newValue;\n}\nfunction pushPath(object, path, newValue, concat) {\n  const {\n    obj,\n    k\n  } = getLastOfPath(object, path, Object);\n  obj[k] = obj[k] || [];\n  if (concat) obj[k] = obj[k].concat(newValue);\n  if (!concat) obj[k].push(newValue);\n}\nfunction getPath(object, path) {\n  const {\n    obj,\n    k\n  } = getLastOfPath(object, path);\n  if (!obj) return undefined;\n  return obj[k];\n}\nfunction getPathWithDefaults(data, defaultData, key) {\n  const value = getPath(data, key);\n  if (value !== undefined) {\n    return value;\n  }\n  return getPath(defaultData, key);\n}\nfunction deepExtend(target, source, overwrite) {\n  for (const prop in source) {\n    if (prop !== '__proto__' && prop !== 'constructor') {\n      if (prop in target) {\n        if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {\n          if (overwrite) target[prop] = source[prop];\n        } else {\n          deepExtend(target[prop], source[prop], overwrite);\n        }\n      } else {\n        target[prop] = source[prop];\n      }\n    }\n  }\n  return target;\n}\nfunction regexEscape(str) {\n  return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\n}\nvar _entityMap = {\n  '&': '&amp;',\n  '<': '&lt;',\n  '>': '&gt;',\n  '\"': '&quot;',\n  \"'\": '&#39;',\n  '/': '&#x2F;'\n};\nfunction escape(data) {\n  if (typeof data === 'string') {\n    return data.replace(/[&<>\"'\\/]/g, s => _entityMap[s]);\n  }\n  return data;\n}\nconst chars = [' ', ',', '?', '!', ';'];\nfunction looksLikeObjectPath(key, nsSeparator, keySeparator) {\n  nsSeparator = nsSeparator || '';\n  keySeparator = keySeparator || '';\n  const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);\n  if (possibleChars.length === 0) return true;\n  const r = new RegExp(`(${possibleChars.map(c => c === '?' ? '\\\\?' : c).join('|')})`);\n  let matched = !r.test(key);\n  if (!matched) {\n    const ki = key.indexOf(keySeparator);\n    if (ki > 0 && !r.test(key.substring(0, ki))) {\n      matched = true;\n    }\n  }\n  return matched;\n}\nfunction deepFind(obj, path) {\n  let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';\n  if (!obj) return undefined;\n  if (obj[path]) return obj[path];\n  const paths = path.split(keySeparator);\n  let current = obj;\n  for (let i = 0; i < paths.length; ++i) {\n    if (!current) return undefined;\n    if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {\n      return undefined;\n    }\n    if (current[paths[i]] === undefined) {\n      let j = 2;\n      let p = paths.slice(i, i + j).join(keySeparator);\n      let mix = current[p];\n      while (mix === undefined && paths.length > i + j) {\n        j++;\n        p = paths.slice(i, i + j).join(keySeparator);\n        mix = current[p];\n      }\n      if (mix === undefined) return undefined;\n      if (mix === null) return null;\n      if (path.endsWith(p)) {\n        if (typeof mix === 'string') return mix;\n        if (p && typeof mix[p] === 'string') return mix[p];\n      }\n      const joinedPath = paths.slice(i + j).join(keySeparator);\n      if (joinedPath) return deepFind(mix, joinedPath, keySeparator);\n      return undefined;\n    }\n    current = current[paths[i]];\n  }\n  return current;\n}\nfunction getCleanedCode(code) {\n  if (code && code.indexOf('_') > 0) return code.replace('_', '-');\n  return code;\n}\n\nclass ResourceStore extends EventEmitter {\n  constructor(data) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n      ns: ['translation'],\n      defaultNS: 'translation'\n    };\n    super();\n    this.data = data || {};\n    this.options = options;\n    if (this.options.keySeparator === undefined) {\n      this.options.keySeparator = '.';\n    }\n    if (this.options.ignoreJSONStructure === undefined) {\n      this.options.ignoreJSONStructure = true;\n    }\n  }\n  addNamespaces(ns) {\n    if (this.options.ns.indexOf(ns) < 0) {\n      this.options.ns.push(ns);\n    }\n  }\n  removeNamespaces(ns) {\n    const index = this.options.ns.indexOf(ns);\n    if (index > -1) {\n      this.options.ns.splice(index, 1);\n    }\n  }\n  getResource(lng, ns, key) {\n    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n    const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n    let path = [lng, ns];\n    if (key && typeof key !== 'string') path = path.concat(key);\n    if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);\n    if (lng.indexOf('.') > -1) {\n      path = lng.split('.');\n    }\n    const result = getPath(this.data, path);\n    if (result || !ignoreJSONStructure || typeof key !== 'string') return result;\n    return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);\n  }\n  addResource(lng, ns, key, value) {\n    let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {\n      silent: false\n    };\n    const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n    let path = [lng, ns];\n    if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n    if (lng.indexOf('.') > -1) {\n      path = lng.split('.');\n      value = ns;\n      ns = path[1];\n    }\n    this.addNamespaces(ns);\n    setPath(this.data, path, value);\n    if (!options.silent) this.emit('added', lng, ns, key, value);\n  }\n  addResources(lng, ns, resources) {\n    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {\n      silent: false\n    };\n    for (const m in resources) {\n      if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {\n        silent: true\n      });\n    }\n    if (!options.silent) this.emit('added', lng, ns, resources);\n  }\n  addResourceBundle(lng, ns, resources, deep, overwrite) {\n    let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {\n      silent: false\n    };\n    let path = [lng, ns];\n    if (lng.indexOf('.') > -1) {\n      path = lng.split('.');\n      deep = resources;\n      resources = ns;\n      ns = path[1];\n    }\n    this.addNamespaces(ns);\n    let pack = getPath(this.data, path) || {};\n    if (deep) {\n      deepExtend(pack, resources, overwrite);\n    } else {\n      pack = {\n        ...pack,\n        ...resources\n      };\n    }\n    setPath(this.data, path, pack);\n    if (!options.silent) this.emit('added', lng, ns, resources);\n  }\n  removeResourceBundle(lng, ns) {\n    if (this.hasResourceBundle(lng, ns)) {\n      delete this.data[lng][ns];\n    }\n    this.removeNamespaces(ns);\n    this.emit('removed', lng, ns);\n  }\n  hasResourceBundle(lng, ns) {\n    return this.getResource(lng, ns) !== undefined;\n  }\n  getResourceBundle(lng, ns) {\n    if (!ns) ns = this.options.defaultNS;\n    if (this.options.compatibilityAPI === 'v1') return {\n      ...{},\n      ...this.getResource(lng, ns)\n    };\n    return this.getResource(lng, ns);\n  }\n  getDataByLanguage(lng) {\n    return this.data[lng];\n  }\n  hasLanguageSomeTranslations(lng) {\n    const data = this.getDataByLanguage(lng);\n    const n = data && Object.keys(data) || [];\n    return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);\n  }\n  toJSON() {\n    return this.data;\n  }\n}\n\nvar postProcessor = {\n  processors: {},\n  addPostProcessor(module) {\n    this.processors[module.name] = module;\n  },\n  handle(processors, value, key, options, translator) {\n    processors.forEach(processor => {\n      if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);\n    });\n    return value;\n  }\n};\n\nconst checkedLoadedFor = {};\nclass Translator extends EventEmitter {\n  constructor(services) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    super();\n    copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);\n    this.options = options;\n    if (this.options.keySeparator === undefined) {\n      this.options.keySeparator = '.';\n    }\n    this.logger = baseLogger.create('translator');\n  }\n  changeLanguage(lng) {\n    if (lng) this.language = lng;\n  }\n  exists(key) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n      interpolation: {}\n    };\n    if (key === undefined || key === null) {\n      return false;\n    }\n    const resolved = this.resolve(key, options);\n    return resolved && resolved.res !== undefined;\n  }\n  extractFromKey(key, options) {\n    let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;\n    if (nsSeparator === undefined) nsSeparator = ':';\n    const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n    let namespaces = options.ns || this.options.defaultNS || [];\n    const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;\n    const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);\n    if (wouldCheckForNsInKey && !seemsNaturalLanguage) {\n      const m = key.match(this.interpolator.nestingRegexp);\n      if (m && m.length > 0) {\n        return {\n          key,\n          namespaces\n        };\n      }\n      const parts = key.split(nsSeparator);\n      if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n      key = parts.join(keySeparator);\n    }\n    if (typeof namespaces === 'string') namespaces = [namespaces];\n    return {\n      key,\n      namespaces\n    };\n  }\n  translate(keys, options, lastKey) {\n    if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {\n      options = this.options.overloadTranslationOptionHandler(arguments);\n    }\n    if (typeof options === 'object') options = {\n      ...options\n    };\n    if (!options) options = {};\n    if (keys === undefined || keys === null) return '';\n    if (!Array.isArray(keys)) keys = [String(keys)];\n    const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;\n    const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n    const {\n      key,\n      namespaces\n    } = this.extractFromKey(keys[keys.length - 1], options);\n    const namespace = namespaces[namespaces.length - 1];\n    const lng = options.lng || this.language;\n    const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n    if (lng && lng.toLowerCase() === 'cimode') {\n      if (appendNamespaceToCIMode) {\n        const nsSeparator = options.nsSeparator || this.options.nsSeparator;\n        if (returnDetails) {\n          return {\n            res: `${namespace}${nsSeparator}${key}`,\n            usedKey: key,\n            exactUsedKey: key,\n            usedLng: lng,\n            usedNS: namespace,\n            usedParams: this.getUsedParamsDetails(options)\n          };\n        }\n        return `${namespace}${nsSeparator}${key}`;\n      }\n      if (returnDetails) {\n        return {\n          res: key,\n          usedKey: key,\n          exactUsedKey: key,\n          usedLng: lng,\n          usedNS: namespace,\n          usedParams: this.getUsedParamsDetails(options)\n        };\n      }\n      return key;\n    }\n    const resolved = this.resolve(keys, options);\n    let res = resolved && resolved.res;\n    const resUsedKey = resolved && resolved.usedKey || key;\n    const resExactUsedKey = resolved && resolved.exactUsedKey || key;\n    const resType = Object.prototype.toString.apply(res);\n    const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n    const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;\n    const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n    const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';\n    if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {\n      if (!options.returnObjects && !this.options.returnObjects) {\n        if (!this.options.returnedObjectHandler) {\n          this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n        }\n        const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {\n          ...options,\n          ns: namespaces\n        }) : `key '${key} (${this.language})' returned an object instead of string.`;\n        if (returnDetails) {\n          resolved.res = r;\n          resolved.usedParams = this.getUsedParamsDetails(options);\n          return resolved;\n        }\n        return r;\n      }\n      if (keySeparator) {\n        const resTypeIsArray = resType === '[object Array]';\n        const copy = resTypeIsArray ? [] : {};\n        const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n        for (const m in res) {\n          if (Object.prototype.hasOwnProperty.call(res, m)) {\n            const deepKey = `${newKeyToUse}${keySeparator}${m}`;\n            copy[m] = this.translate(deepKey, {\n              ...options,\n              ...{\n                joinArrays: false,\n                ns: namespaces\n              }\n            });\n            if (copy[m] === deepKey) copy[m] = res[m];\n          }\n        }\n        res = copy;\n      }\n    } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {\n      res = res.join(joinArrays);\n      if (res) res = this.extendTranslation(res, keys, options, lastKey);\n    } else {\n      let usedDefault = false;\n      let usedKey = false;\n      const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n      const hasDefaultValue = Translator.hasDefaultValue(options);\n      const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';\n      const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {\n        ordinal: false\n      }) : '';\n      const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;\n      if (!this.isValidLookup(res) && hasDefaultValue) {\n        usedDefault = true;\n        res = defaultValue;\n      }\n      if (!this.isValidLookup(res)) {\n        usedKey = true;\n        res = key;\n      }\n      const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;\n      const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;\n      const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n      if (usedKey || usedDefault || updateMissing) {\n        this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n        if (keySeparator) {\n          const fk = this.resolve(key, {\n            ...options,\n            keySeparator: false\n          });\n          if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n        }\n        let lngs = [];\n        const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);\n        if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n          for (let i = 0; i < fallbackLngs.length; i++) {\n            lngs.push(fallbackLngs[i]);\n          }\n        } else if (this.options.saveMissingTo === 'all') {\n          lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);\n        } else {\n          lngs.push(options.lng || this.language);\n        }\n        const send = (l, k, specificDefaultValue) => {\n          const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;\n          if (this.options.missingKeyHandler) {\n            this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);\n          } else if (this.backendConnector && this.backendConnector.saveMissing) {\n            this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);\n          }\n          this.emit('missingKey', l, namespace, k, res);\n        };\n        if (this.options.saveMissing) {\n          if (this.options.saveMissingPlurals && needsPluralHandling) {\n            lngs.forEach(language => {\n              this.pluralResolver.getSuffixes(language, options).forEach(suffix => {\n                send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);\n              });\n            });\n          } else {\n            send(lngs, key, defaultValue);\n          }\n        }\n      }\n      res = this.extendTranslation(res, keys, options, resolved, lastKey);\n      if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;\n      if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {\n        if (this.options.compatibilityAPI !== 'v1') {\n          res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);\n        } else {\n          res = this.options.parseMissingKeyHandler(res);\n        }\n      }\n    }\n    if (returnDetails) {\n      resolved.res = res;\n      resolved.usedParams = this.getUsedParamsDetails(options);\n      return resolved;\n    }\n    return res;\n  }\n  extendTranslation(res, key, options, resolved, lastKey) {\n    var _this = this;\n    if (this.i18nFormat && this.i18nFormat.parse) {\n      res = this.i18nFormat.parse(res, {\n        ...this.options.interpolation.defaultVariables,\n        ...options\n      }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n        resolved\n      });\n    } else if (!options.skipInterpolation) {\n      if (options.interpolation) this.interpolator.init({\n        ...options,\n        ...{\n          interpolation: {\n            ...this.options.interpolation,\n            ...options.interpolation\n          }\n        }\n      });\n      const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);\n      let nestBef;\n      if (skipOnVariables) {\n        const nb = res.match(this.interpolator.nestingRegexp);\n        nestBef = nb && nb.length;\n      }\n      let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;\n      if (this.options.interpolation.defaultVariables) data = {\n        ...this.options.interpolation.defaultVariables,\n        ...data\n      };\n      res = this.interpolator.interpolate(res, data, options.lng || this.language, options);\n      if (skipOnVariables) {\n        const na = res.match(this.interpolator.nestingRegexp);\n        const nestAft = na && na.length;\n        if (nestBef < nestAft) options.nest = false;\n      }\n      if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;\n      if (options.nest !== false) res = this.interpolator.nest(res, function () {\n        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n          args[_key] = arguments[_key];\n        }\n        if (lastKey && lastKey[0] === args[0] && !options.context) {\n          _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);\n          return null;\n        }\n        return _this.translate(...args, key);\n      }, options);\n      if (options.interpolation) this.interpolator.reset();\n    }\n    const postProcess = options.postProcess || this.options.postProcess;\n    const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;\n    if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {\n      res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {\n        i18nResolved: {\n          ...resolved,\n          usedParams: this.getUsedParamsDetails(options)\n        },\n        ...options\n      } : options, this);\n    }\n    return res;\n  }\n  resolve(keys) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    let found;\n    let usedKey;\n    let exactUsedKey;\n    let usedLng;\n    let usedNS;\n    if (typeof keys === 'string') keys = [keys];\n    keys.forEach(k => {\n      if (this.isValidLookup(found)) return;\n      const extracted = this.extractFromKey(k, options);\n      const key = extracted.key;\n      usedKey = key;\n      let namespaces = extracted.namespaces;\n      if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);\n      const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n      const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();\n      const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';\n      const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);\n      namespaces.forEach(ns => {\n        if (this.isValidLookup(found)) return;\n        usedNS = ns;\n        if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {\n          checkedLoadedFor[`${codes[0]}-${ns}`] = true;\n          this.logger.warn(`key \"${usedKey}\" for languages \"${codes.join(', ')}\" won't get resolved as namespace \"${usedNS}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n        }\n        codes.forEach(code => {\n          if (this.isValidLookup(found)) return;\n          usedLng = code;\n          const finalKeys = [key];\n          if (this.i18nFormat && this.i18nFormat.addLookupKeys) {\n            this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);\n          } else {\n            let pluralSuffix;\n            if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);\n            const zeroSuffix = `${this.options.pluralSeparator}zero`;\n            const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;\n            if (needsPluralHandling) {\n              finalKeys.push(key + pluralSuffix);\n              if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n                finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n              }\n              if (needsZeroSuffixLookup) {\n                finalKeys.push(key + zeroSuffix);\n              }\n            }\n            if (needsContextHandling) {\n              const contextKey = `${key}${this.options.contextSeparator}${options.context}`;\n              finalKeys.push(contextKey);\n              if (needsPluralHandling) {\n                finalKeys.push(contextKey + pluralSuffix);\n                if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n                  finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n                }\n                if (needsZeroSuffixLookup) {\n                  finalKeys.push(contextKey + zeroSuffix);\n                }\n              }\n            }\n          }\n          let possibleKey;\n          while (possibleKey = finalKeys.pop()) {\n            if (!this.isValidLookup(found)) {\n              exactUsedKey = possibleKey;\n              found = this.getResource(code, ns, possibleKey, options);\n            }\n          }\n        });\n      });\n    });\n    return {\n      res: found,\n      usedKey,\n      exactUsedKey,\n      usedLng,\n      usedNS\n    };\n  }\n  isValidLookup(res) {\n    return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n  }\n  getResource(code, ns, key) {\n    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n    return this.resourceStore.getResource(code, ns, key, options);\n  }\n  getUsedParamsDetails() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];\n    const useOptionsReplaceForData = options.replace && typeof options.replace !== 'string';\n    let data = useOptionsReplaceForData ? options.replace : options;\n    if (useOptionsReplaceForData && typeof options.count !== 'undefined') {\n      data.count = options.count;\n    }\n    if (this.options.interpolation.defaultVariables) {\n      data = {\n        ...this.options.interpolation.defaultVariables,\n        ...data\n      };\n    }\n    if (!useOptionsReplaceForData) {\n      data = {\n        ...data\n      };\n      for (const key of optionsKeys) {\n        delete data[key];\n      }\n    }\n    return data;\n  }\n  static hasDefaultValue(options) {\n    const prefix = 'defaultValue';\n    for (const option in options) {\n      if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n\nfunction capitalize(string) {\n  return string.charAt(0).toUpperCase() + string.slice(1);\n}\nclass LanguageUtil {\n  constructor(options) {\n    this.options = options;\n    this.supportedLngs = this.options.supportedLngs || false;\n    this.logger = baseLogger.create('languageUtils');\n  }\n  getScriptPartFromCode(code) {\n    code = getCleanedCode(code);\n    if (!code || code.indexOf('-') < 0) return null;\n    const p = code.split('-');\n    if (p.length === 2) return null;\n    p.pop();\n    if (p[p.length - 1].toLowerCase() === 'x') return null;\n    return this.formatLanguageCode(p.join('-'));\n  }\n  getLanguagePartFromCode(code) {\n    code = getCleanedCode(code);\n    if (!code || code.indexOf('-') < 0) return code;\n    const p = code.split('-');\n    return this.formatLanguageCode(p[0]);\n  }\n  formatLanguageCode(code) {\n    if (typeof code === 'string' && code.indexOf('-') > -1) {\n      const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];\n      let p = code.split('-');\n      if (this.options.lowerCaseLng) {\n        p = p.map(part => part.toLowerCase());\n      } else if (p.length === 2) {\n        p[0] = p[0].toLowerCase();\n        p[1] = p[1].toUpperCase();\n        if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n      } else if (p.length === 3) {\n        p[0] = p[0].toLowerCase();\n        if (p[1].length === 2) p[1] = p[1].toUpperCase();\n        if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();\n        if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n        if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());\n      }\n      return p.join('-');\n    }\n    return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n  }\n  isSupportedCode(code) {\n    if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n      code = this.getLanguagePartFromCode(code);\n    }\n    return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n  }\n  getBestMatchFromCodes(codes) {\n    if (!codes) return null;\n    let found;\n    codes.forEach(code => {\n      if (found) return;\n      const cleanedLng = this.formatLanguageCode(code);\n      if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;\n    });\n    if (!found && this.options.supportedLngs) {\n      codes.forEach(code => {\n        if (found) return;\n        const lngOnly = this.getLanguagePartFromCode(code);\n        if (this.isSupportedCode(lngOnly)) return found = lngOnly;\n        found = this.options.supportedLngs.find(supportedLng => {\n          if (supportedLng === lngOnly) return supportedLng;\n          if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;\n          if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;\n        });\n      });\n    }\n    if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n    return found;\n  }\n  getFallbackCodes(fallbacks, code) {\n    if (!fallbacks) return [];\n    if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n    if (typeof fallbacks === 'string') fallbacks = [fallbacks];\n    if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;\n    if (!code) return fallbacks.default || [];\n    let found = fallbacks[code];\n    if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n    if (!found) found = fallbacks[this.formatLanguageCode(code)];\n    if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n    if (!found) found = fallbacks.default;\n    return found || [];\n  }\n  toResolveHierarchy(code, fallbackCode) {\n    const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);\n    const codes = [];\n    const addCode = c => {\n      if (!c) return;\n      if (this.isSupportedCode(c)) {\n        codes.push(c);\n      } else {\n        this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);\n      }\n    };\n    if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {\n      if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n      if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n      if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n    } else if (typeof code === 'string') {\n      addCode(this.formatLanguageCode(code));\n    }\n    fallbackCodes.forEach(fc => {\n      if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));\n    });\n    return codes;\n  }\n}\n\nlet sets = [{\n  lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],\n  nr: [1, 2],\n  fc: 1\n}, {\n  lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],\n  nr: [1, 2],\n  fc: 2\n}, {\n  lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],\n  nr: [1],\n  fc: 3\n}, {\n  lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],\n  nr: [1, 2, 5],\n  fc: 4\n}, {\n  lngs: ['ar'],\n  nr: [0, 1, 2, 3, 11, 100],\n  fc: 5\n}, {\n  lngs: ['cs', 'sk'],\n  nr: [1, 2, 5],\n  fc: 6\n}, {\n  lngs: ['csb', 'pl'],\n  nr: [1, 2, 5],\n  fc: 7\n}, {\n  lngs: ['cy'],\n  nr: [1, 2, 3, 8],\n  fc: 8\n}, {\n  lngs: ['fr'],\n  nr: [1, 2],\n  fc: 9\n}, {\n  lngs: ['ga'],\n  nr: [1, 2, 3, 7, 11],\n  fc: 10\n}, {\n  lngs: ['gd'],\n  nr: [1, 2, 3, 20],\n  fc: 11\n}, {\n  lngs: ['is'],\n  nr: [1, 2],\n  fc: 12\n}, {\n  lngs: ['jv'],\n  nr: [0, 1],\n  fc: 13\n}, {\n  lngs: ['kw'],\n  nr: [1, 2, 3, 4],\n  fc: 14\n}, {\n  lngs: ['lt'],\n  nr: [1, 2, 10],\n  fc: 15\n}, {\n  lngs: ['lv'],\n  nr: [1, 2, 0],\n  fc: 16\n}, {\n  lngs: ['mk'],\n  nr: [1, 2],\n  fc: 17\n}, {\n  lngs: ['mnk'],\n  nr: [0, 1, 2],\n  fc: 18\n}, {\n  lngs: ['mt'],\n  nr: [1, 2, 11, 20],\n  fc: 19\n}, {\n  lngs: ['or'],\n  nr: [2, 1],\n  fc: 2\n}, {\n  lngs: ['ro'],\n  nr: [1, 2, 20],\n  fc: 20\n}, {\n  lngs: ['sl'],\n  nr: [5, 1, 2, 3],\n  fc: 21\n}, {\n  lngs: ['he', 'iw'],\n  nr: [1, 2, 20, 21],\n  fc: 22\n}];\nlet _rulesPluralsTypes = {\n  1: function (n) {\n    return Number(n > 1);\n  },\n  2: function (n) {\n    return Number(n != 1);\n  },\n  3: function (n) {\n    return 0;\n  },\n  4: function (n) {\n    return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n  },\n  5: function (n) {\n    return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);\n  },\n  6: function (n) {\n    return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);\n  },\n  7: function (n) {\n    return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n  },\n  8: function (n) {\n    return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);\n  },\n  9: function (n) {\n    return Number(n >= 2);\n  },\n  10: function (n) {\n    return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);\n  },\n  11: function (n) {\n    return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);\n  },\n  12: function (n) {\n    return Number(n % 10 != 1 || n % 100 == 11);\n  },\n  13: function (n) {\n    return Number(n !== 0);\n  },\n  14: function (n) {\n    return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);\n  },\n  15: function (n) {\n    return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n  },\n  16: function (n) {\n    return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);\n  },\n  17: function (n) {\n    return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);\n  },\n  18: function (n) {\n    return Number(n == 0 ? 0 : n == 1 ? 1 : 2);\n  },\n  19: function (n) {\n    return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);\n  },\n  20: function (n) {\n    return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);\n  },\n  21: function (n) {\n    return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);\n  },\n  22: function (n) {\n    return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);\n  }\n};\nconst nonIntlVersions = ['v1', 'v2', 'v3'];\nconst intlVersions = ['v4'];\nconst suffixesOrder = {\n  zero: 0,\n  one: 1,\n  two: 2,\n  few: 3,\n  many: 4,\n  other: 5\n};\nfunction createRules() {\n  const rules = {};\n  sets.forEach(set => {\n    set.lngs.forEach(l => {\n      rules[l] = {\n        numbers: set.nr,\n        plurals: _rulesPluralsTypes[set.fc]\n      };\n    });\n  });\n  return rules;\n}\nclass PluralResolver {\n  constructor(languageUtils) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    this.languageUtils = languageUtils;\n    this.options = options;\n    this.logger = baseLogger.create('pluralResolver');\n    if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {\n      this.options.compatibilityJSON = 'v3';\n      this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');\n    }\n    this.rules = createRules();\n  }\n  addRule(lng, obj) {\n    this.rules[lng] = obj;\n  }\n  getRule(code) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    if (this.shouldUseIntlApi()) {\n      try {\n        return new Intl.PluralRules(getCleanedCode(code), {\n          type: options.ordinal ? 'ordinal' : 'cardinal'\n        });\n      } catch {\n        return;\n      }\n    }\n    return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];\n  }\n  needsPlural(code) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    const rule = this.getRule(code, options);\n    if (this.shouldUseIntlApi()) {\n      return rule && rule.resolvedOptions().pluralCategories.length > 1;\n    }\n    return rule && rule.numbers.length > 1;\n  }\n  getPluralFormsOfKey(code, key) {\n    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);\n  }\n  getSuffixes(code) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    const rule = this.getRule(code, options);\n    if (!rule) {\n      return [];\n    }\n    if (this.shouldUseIntlApi()) {\n      return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);\n    }\n    return rule.numbers.map(number => this.getSuffix(code, number, options));\n  }\n  getSuffix(code, count) {\n    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    const rule = this.getRule(code, options);\n    if (rule) {\n      if (this.shouldUseIntlApi()) {\n        return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;\n      }\n      return this.getSuffixRetroCompatible(rule, count);\n    }\n    this.logger.warn(`no plural rule found for: ${code}`);\n    return '';\n  }\n  getSuffixRetroCompatible(rule, count) {\n    const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));\n    let suffix = rule.numbers[idx];\n    if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n      if (suffix === 2) {\n        suffix = 'plural';\n      } else if (suffix === 1) {\n        suffix = '';\n      }\n    }\n    const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();\n    if (this.options.compatibilityJSON === 'v1') {\n      if (suffix === 1) return '';\n      if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;\n      return returnSuffix();\n    } else if (this.options.compatibilityJSON === 'v2') {\n      return returnSuffix();\n    } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n      return returnSuffix();\n    }\n    return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();\n  }\n  shouldUseIntlApi() {\n    return !nonIntlVersions.includes(this.options.compatibilityJSON);\n  }\n}\n\nfunction deepFindWithDefaults(data, defaultData, key) {\n  let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';\n  let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n  let path = getPathWithDefaults(data, defaultData, key);\n  if (!path && ignoreJSONStructure && typeof key === 'string') {\n    path = deepFind(data, key, keySeparator);\n    if (path === undefined) path = deepFind(defaultData, key, keySeparator);\n  }\n  return path;\n}\nclass Interpolator {\n  constructor() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    this.logger = baseLogger.create('interpolator');\n    this.options = options;\n    this.format = options.interpolation && options.interpolation.format || (value => value);\n    this.init(options);\n  }\n  init() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    if (!options.interpolation) options.interpolation = {\n      escapeValue: true\n    };\n    const iOpts = options.interpolation;\n    this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;\n    this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;\n    this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;\n    this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';\n    this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';\n    this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';\n    this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';\n    this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';\n    this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');\n    this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');\n    this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';\n    this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;\n    this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;\n    this.resetRegExp();\n  }\n  reset() {\n    if (this.options) this.init(this.options);\n  }\n  resetRegExp() {\n    const regexpStr = `${this.prefix}(.+?)${this.suffix}`;\n    this.regexp = new RegExp(regexpStr, 'g');\n    const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;\n    this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');\n    const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;\n    this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');\n  }\n  interpolate(str, data, lng, options) {\n    let match;\n    let value;\n    let replaces;\n    const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n    function regexSafe(val) {\n      return val.replace(/\\$/g, '$$$$');\n    }\n    const handleFormat = key => {\n      if (key.indexOf(this.formatSeparator) < 0) {\n        const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);\n        return this.alwaysFormat ? this.format(path, undefined, lng, {\n          ...options,\n          ...data,\n          interpolationkey: key\n        }) : path;\n      }\n      const p = key.split(this.formatSeparator);\n      const k = p.shift().trim();\n      const f = p.join(this.formatSeparator).trim();\n      return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {\n        ...options,\n        ...data,\n        interpolationkey: k\n      });\n    };\n    this.resetRegExp();\n    const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;\n    const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;\n    const todos = [{\n      regex: this.regexpUnescape,\n      safeValue: val => regexSafe(val)\n    }, {\n      regex: this.regexp,\n      safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)\n    }];\n    todos.forEach(todo => {\n      replaces = 0;\n      while (match = todo.regex.exec(str)) {\n        const matchedVar = match[1].trim();\n        value = handleFormat(matchedVar);\n        if (value === undefined) {\n          if (typeof missingInterpolationHandler === 'function') {\n            const temp = missingInterpolationHandler(str, match, options);\n            value = typeof temp === 'string' ? temp : '';\n          } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {\n            value = '';\n          } else if (skipOnVariables) {\n            value = match[0];\n            continue;\n          } else {\n            this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);\n            value = '';\n          }\n        } else if (typeof value !== 'string' && !this.useRawValueToEscape) {\n          value = makeString(value);\n        }\n        const safeValue = todo.safeValue(value);\n        str = str.replace(match[0], safeValue);\n        if (skipOnVariables) {\n          todo.regex.lastIndex += value.length;\n          todo.regex.lastIndex -= match[0].length;\n        } else {\n          todo.regex.lastIndex = 0;\n        }\n        replaces++;\n        if (replaces >= this.maxReplaces) {\n          break;\n        }\n      }\n    });\n    return str;\n  }\n  nest(str, fc) {\n    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    let match;\n    let value;\n    let clonedOptions;\n    function handleHasOptions(key, inheritedOptions) {\n      const sep = this.nestingOptionsSeparator;\n      if (key.indexOf(sep) < 0) return key;\n      const c = key.split(new RegExp(`${sep}[ ]*{`));\n      let optionsString = `{${c[1]}`;\n      key = c[0];\n      optionsString = this.interpolate(optionsString, clonedOptions);\n      const matchedSingleQuotes = optionsString.match(/'/g);\n      const matchedDoubleQuotes = optionsString.match(/\"/g);\n      if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {\n        optionsString = optionsString.replace(/'/g, '\"');\n      }\n      try {\n        clonedOptions = JSON.parse(optionsString);\n        if (inheritedOptions) clonedOptions = {\n          ...inheritedOptions,\n          ...clonedOptions\n        };\n      } catch (e) {\n        this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);\n        return `${key}${sep}${optionsString}`;\n      }\n      delete clonedOptions.defaultValue;\n      return key;\n    }\n    while (match = this.nestingRegexp.exec(str)) {\n      let formatters = [];\n      clonedOptions = {\n        ...options\n      };\n      clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;\n      clonedOptions.applyPostProcessor = false;\n      delete clonedOptions.defaultValue;\n      let doReduce = false;\n      if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {\n        const r = match[1].split(this.formatSeparator).map(elem => elem.trim());\n        match[1] = r.shift();\n        formatters = r;\n        doReduce = true;\n      }\n      value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n      if (value && match[0] === str && typeof value !== 'string') return value;\n      if (typeof value !== 'string') value = makeString(value);\n      if (!value) {\n        this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);\n        value = '';\n      }\n      if (doReduce) {\n        value = formatters.reduce((v, f) => this.format(v, f, options.lng, {\n          ...options,\n          interpolationkey: match[1].trim()\n        }), value.trim());\n      }\n      str = str.replace(match[0], value);\n      this.regexp.lastIndex = 0;\n    }\n    return str;\n  }\n}\n\nfunction parseFormatStr(formatStr) {\n  let formatName = formatStr.toLowerCase().trim();\n  const formatOptions = {};\n  if (formatStr.indexOf('(') > -1) {\n    const p = formatStr.split('(');\n    formatName = p[0].toLowerCase().trim();\n    const optStr = p[1].substring(0, p[1].length - 1);\n    if (formatName === 'currency' && optStr.indexOf(':') < 0) {\n      if (!formatOptions.currency) formatOptions.currency = optStr.trim();\n    } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {\n      if (!formatOptions.range) formatOptions.range = optStr.trim();\n    } else {\n      const opts = optStr.split(';');\n      opts.forEach(opt => {\n        if (!opt) return;\n        const [key, ...rest] = opt.split(':');\n        const val = rest.join(':').trim().replace(/^'+|'+$/g, '');\n        if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;\n        if (val === 'false') formatOptions[key.trim()] = false;\n        if (val === 'true') formatOptions[key.trim()] = true;\n        if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);\n      });\n    }\n  }\n  return {\n    formatName,\n    formatOptions\n  };\n}\nfunction createCachedFormatter(fn) {\n  const cache = {};\n  return function invokeFormatter(val, lng, options) {\n    const key = lng + JSON.stringify(options);\n    let formatter = cache[key];\n    if (!formatter) {\n      formatter = fn(getCleanedCode(lng), options);\n      cache[key] = formatter;\n    }\n    return formatter(val);\n  };\n}\nclass Formatter {\n  constructor() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    this.logger = baseLogger.create('formatter');\n    this.options = options;\n    this.formats = {\n      number: createCachedFormatter((lng, opt) => {\n        const formatter = new Intl.NumberFormat(lng, {\n          ...opt\n        });\n        return val => formatter.format(val);\n      }),\n      currency: createCachedFormatter((lng, opt) => {\n        const formatter = new Intl.NumberFormat(lng, {\n          ...opt,\n          style: 'currency'\n        });\n        return val => formatter.format(val);\n      }),\n      datetime: createCachedFormatter((lng, opt) => {\n        const formatter = new Intl.DateTimeFormat(lng, {\n          ...opt\n        });\n        return val => formatter.format(val);\n      }),\n      relativetime: createCachedFormatter((lng, opt) => {\n        const formatter = new Intl.RelativeTimeFormat(lng, {\n          ...opt\n        });\n        return val => formatter.format(val, opt.range || 'day');\n      }),\n      list: createCachedFormatter((lng, opt) => {\n        const formatter = new Intl.ListFormat(lng, {\n          ...opt\n        });\n        return val => formatter.format(val);\n      })\n    };\n    this.init(options);\n  }\n  init(services) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n      interpolation: {}\n    };\n    const iOpts = options.interpolation;\n    this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';\n  }\n  add(name, fc) {\n    this.formats[name.toLowerCase().trim()] = fc;\n  }\n  addCached(name, fc) {\n    this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);\n  }\n  format(value, format, lng) {\n    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    const formats = format.split(this.formatSeparator);\n    const result = formats.reduce((mem, f) => {\n      const {\n        formatName,\n        formatOptions\n      } = parseFormatStr(f);\n      if (this.formats[formatName]) {\n        let formatted = mem;\n        try {\n          const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};\n          const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;\n          formatted = this.formats[formatName](mem, l, {\n            ...formatOptions,\n            ...options,\n            ...valOptions\n          });\n        } catch (error) {\n          this.logger.warn(error);\n        }\n        return formatted;\n      } else {\n        this.logger.warn(`there was no format function for ${formatName}`);\n      }\n      return mem;\n    }, value);\n    return result;\n  }\n}\n\nfunction removePending(q, name) {\n  if (q.pending[name] !== undefined) {\n    delete q.pending[name];\n    q.pendingCount--;\n  }\n}\nclass Connector extends EventEmitter {\n  constructor(backend, store, services) {\n    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    super();\n    this.backend = backend;\n    this.store = store;\n    this.services = services;\n    this.languageUtils = services.languageUtils;\n    this.options = options;\n    this.logger = baseLogger.create('backendConnector');\n    this.waitingReads = [];\n    this.maxParallelReads = options.maxParallelReads || 10;\n    this.readingCalls = 0;\n    this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;\n    this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;\n    this.state = {};\n    this.queue = [];\n    if (this.backend && this.backend.init) {\n      this.backend.init(services, options.backend, options);\n    }\n  }\n  queueLoad(languages, namespaces, options, callback) {\n    const toLoad = {};\n    const pending = {};\n    const toLoadLanguages = {};\n    const toLoadNamespaces = {};\n    languages.forEach(lng => {\n      let hasAllNamespaces = true;\n      namespaces.forEach(ns => {\n        const name = `${lng}|${ns}`;\n        if (!options.reload && this.store.hasResourceBundle(lng, ns)) {\n          this.state[name] = 2;\n        } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {\n          if (pending[name] === undefined) pending[name] = true;\n        } else {\n          this.state[name] = 1;\n          hasAllNamespaces = false;\n          if (pending[name] === undefined) pending[name] = true;\n          if (toLoad[name] === undefined) toLoad[name] = true;\n          if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;\n        }\n      });\n      if (!hasAllNamespaces) toLoadLanguages[lng] = true;\n    });\n    if (Object.keys(toLoad).length || Object.keys(pending).length) {\n      this.queue.push({\n        pending,\n        pendingCount: Object.keys(pending).length,\n        loaded: {},\n        errors: [],\n        callback\n      });\n    }\n    return {\n      toLoad: Object.keys(toLoad),\n      pending: Object.keys(pending),\n      toLoadLanguages: Object.keys(toLoadLanguages),\n      toLoadNamespaces: Object.keys(toLoadNamespaces)\n    };\n  }\n  loaded(name, err, data) {\n    const s = name.split('|');\n    const lng = s[0];\n    const ns = s[1];\n    if (err) this.emit('failedLoading', lng, ns, err);\n    if (data) {\n      this.store.addResourceBundle(lng, ns, data);\n    }\n    this.state[name] = err ? -1 : 2;\n    const loaded = {};\n    this.queue.forEach(q => {\n      pushPath(q.loaded, [lng], ns);\n      removePending(q, name);\n      if (err) q.errors.push(err);\n      if (q.pendingCount === 0 && !q.done) {\n        Object.keys(q.loaded).forEach(l => {\n          if (!loaded[l]) loaded[l] = {};\n          const loadedKeys = q.loaded[l];\n          if (loadedKeys.length) {\n            loadedKeys.forEach(n => {\n              if (loaded[l][n] === undefined) loaded[l][n] = true;\n            });\n          }\n        });\n        q.done = true;\n        if (q.errors.length) {\n          q.callback(q.errors);\n        } else {\n          q.callback();\n        }\n      }\n    });\n    this.emit('loaded', loaded);\n    this.queue = this.queue.filter(q => !q.done);\n  }\n  read(lng, ns, fcName) {\n    let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n    let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;\n    let callback = arguments.length > 5 ? arguments[5] : undefined;\n    if (!lng.length) return callback(null, {});\n    if (this.readingCalls >= this.maxParallelReads) {\n      this.waitingReads.push({\n        lng,\n        ns,\n        fcName,\n        tried,\n        wait,\n        callback\n      });\n      return;\n    }\n    this.readingCalls++;\n    const resolver = (err, data) => {\n      this.readingCalls--;\n      if (this.waitingReads.length > 0) {\n        const next = this.waitingReads.shift();\n        this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);\n      }\n      if (err && data && tried < this.maxRetries) {\n        setTimeout(() => {\n          this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);\n        }, wait);\n        return;\n      }\n      callback(err, data);\n    };\n    const fc = this.backend[fcName].bind(this.backend);\n    if (fc.length === 2) {\n      try {\n        const r = fc(lng, ns);\n        if (r && typeof r.then === 'function') {\n          r.then(data => resolver(null, data)).catch(resolver);\n        } else {\n          resolver(null, r);\n        }\n      } catch (err) {\n        resolver(err);\n      }\n      return;\n    }\n    return fc(lng, ns, resolver);\n  }\n  prepareLoading(languages, namespaces) {\n    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    let callback = arguments.length > 3 ? arguments[3] : undefined;\n    if (!this.backend) {\n      this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n      return callback && callback();\n    }\n    if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);\n    if (typeof namespaces === 'string') namespaces = [namespaces];\n    const toLoad = this.queueLoad(languages, namespaces, options, callback);\n    if (!toLoad.toLoad.length) {\n      if (!toLoad.pending.length) callback();\n      return null;\n    }\n    toLoad.toLoad.forEach(name => {\n      this.loadOne(name);\n    });\n  }\n  load(languages, namespaces, callback) {\n    this.prepareLoading(languages, namespaces, {}, callback);\n  }\n  reload(languages, namespaces, callback) {\n    this.prepareLoading(languages, namespaces, {\n      reload: true\n    }, callback);\n  }\n  loadOne(name) {\n    let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n    const s = name.split('|');\n    const lng = s[0];\n    const ns = s[1];\n    this.read(lng, ns, 'read', undefined, undefined, (err, data) => {\n      if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);\n      if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);\n      this.loaded(name, err, data);\n    });\n  }\n  saveMissing(languages, namespace, key, fallbackValue, isUpdate) {\n    let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};\n    let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};\n    if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {\n      this.logger.warn(`did not save key \"${key}\" as the namespace \"${namespace}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n      return;\n    }\n    if (key === undefined || key === null || key === '') return;\n    if (this.backend && this.backend.create) {\n      const opts = {\n        ...options,\n        isUpdate\n      };\n      const fc = this.backend.create.bind(this.backend);\n      if (fc.length < 6) {\n        try {\n          let r;\n          if (fc.length === 5) {\n            r = fc(languages, namespace, key, fallbackValue, opts);\n          } else {\n            r = fc(languages, namespace, key, fallbackValue);\n          }\n          if (r && typeof r.then === 'function') {\n            r.then(data => clb(null, data)).catch(clb);\n          } else {\n            clb(null, r);\n          }\n        } catch (err) {\n          clb(err);\n        }\n      } else {\n        fc(languages, namespace, key, fallbackValue, clb, opts);\n      }\n    }\n    if (!languages || !languages[0]) return;\n    this.store.addResource(languages[0], namespace, key, fallbackValue);\n  }\n}\n\nfunction get() {\n  return {\n    debug: false,\n    initImmediate: true,\n    ns: ['translation'],\n    defaultNS: ['translation'],\n    fallbackLng: ['dev'],\n    fallbackNS: false,\n    supportedLngs: false,\n    nonExplicitSupportedLngs: false,\n    load: 'all',\n    preload: false,\n    simplifyPluralSuffix: true,\n    keySeparator: '.',\n    nsSeparator: ':',\n    pluralSeparator: '_',\n    contextSeparator: '_',\n    partialBundledLanguages: false,\n    saveMissing: false,\n    updateMissing: false,\n    saveMissingTo: 'fallback',\n    saveMissingPlurals: true,\n    missingKeyHandler: false,\n    missingInterpolationHandler: false,\n    postProcess: false,\n    postProcessPassResolved: false,\n    returnNull: false,\n    returnEmptyString: true,\n    returnObjects: false,\n    joinArrays: false,\n    returnedObjectHandler: false,\n    parseMissingKeyHandler: false,\n    appendNamespaceToMissingKey: false,\n    appendNamespaceToCIMode: false,\n    overloadTranslationOptionHandler: function handle(args) {\n      let ret = {};\n      if (typeof args[1] === 'object') ret = args[1];\n      if (typeof args[1] === 'string') ret.defaultValue = args[1];\n      if (typeof args[2] === 'string') ret.tDescription = args[2];\n      if (typeof args[2] === 'object' || typeof args[3] === 'object') {\n        const options = args[3] || args[2];\n        Object.keys(options).forEach(key => {\n          ret[key] = options[key];\n        });\n      }\n      return ret;\n    },\n    interpolation: {\n      escapeValue: true,\n      format: (value, format, lng, options) => value,\n      prefix: '{{',\n      suffix: '}}',\n      formatSeparator: ',',\n      unescapePrefix: '-',\n      nestingPrefix: '$t(',\n      nestingSuffix: ')',\n      nestingOptionsSeparator: ',',\n      maxReplaces: 1000,\n      skipOnVariables: true\n    }\n  };\n}\nfunction transformOptions(options) {\n  if (typeof options.ns === 'string') options.ns = [options.ns];\n  if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];\n  if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];\n  if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {\n    options.supportedLngs = options.supportedLngs.concat(['cimode']);\n  }\n  return options;\n}\n\nfunction noop() {}\nfunction bindMemberFunctions(inst) {\n  const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));\n  mems.forEach(mem => {\n    if (typeof inst[mem] === 'function') {\n      inst[mem] = inst[mem].bind(inst);\n    }\n  });\n}\nclass I18n extends EventEmitter {\n  constructor() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    let callback = arguments.length > 1 ? arguments[1] : undefined;\n    super();\n    this.options = transformOptions(options);\n    this.services = {};\n    this.logger = baseLogger;\n    this.modules = {\n      external: []\n    };\n    bindMemberFunctions(this);\n    if (callback && !this.isInitialized && !options.isClone) {\n      if (!this.options.initImmediate) {\n        this.init(options, callback);\n        return this;\n      }\n      setTimeout(() => {\n        this.init(options, callback);\n      }, 0);\n    }\n  }\n  init() {\n    var _this = this;\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    let callback = arguments.length > 1 ? arguments[1] : undefined;\n    if (typeof options === 'function') {\n      callback = options;\n      options = {};\n    }\n    if (!options.defaultNS && options.defaultNS !== false && options.ns) {\n      if (typeof options.ns === 'string') {\n        options.defaultNS = options.ns;\n      } else if (options.ns.indexOf('translation') < 0) {\n        options.defaultNS = options.ns[0];\n      }\n    }\n    const defOpts = get();\n    this.options = {\n      ...defOpts,\n      ...this.options,\n      ...transformOptions(options)\n    };\n    if (this.options.compatibilityAPI !== 'v1') {\n      this.options.interpolation = {\n        ...defOpts.interpolation,\n        ...this.options.interpolation\n      };\n    }\n    if (options.keySeparator !== undefined) {\n      this.options.userDefinedKeySeparator = options.keySeparator;\n    }\n    if (options.nsSeparator !== undefined) {\n      this.options.userDefinedNsSeparator = options.nsSeparator;\n    }\n    function createClassOnDemand(ClassOrObject) {\n      if (!ClassOrObject) return null;\n      if (typeof ClassOrObject === 'function') return new ClassOrObject();\n      return ClassOrObject;\n    }\n    if (!this.options.isClone) {\n      if (this.modules.logger) {\n        baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n      } else {\n        baseLogger.init(null, this.options);\n      }\n      let formatter;\n      if (this.modules.formatter) {\n        formatter = this.modules.formatter;\n      } else if (typeof Intl !== 'undefined') {\n        formatter = Formatter;\n      }\n      const lu = new LanguageUtil(this.options);\n      this.store = new ResourceStore(this.options.resources, this.options);\n      const s = this.services;\n      s.logger = baseLogger;\n      s.resourceStore = this.store;\n      s.languageUtils = lu;\n      s.pluralResolver = new PluralResolver(lu, {\n        prepend: this.options.pluralSeparator,\n        compatibilityJSON: this.options.compatibilityJSON,\n        simplifyPluralSuffix: this.options.simplifyPluralSuffix\n      });\n      if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {\n        s.formatter = createClassOnDemand(formatter);\n        s.formatter.init(s, this.options);\n        this.options.interpolation.format = s.formatter.format.bind(s.formatter);\n      }\n      s.interpolator = new Interpolator(this.options);\n      s.utils = {\n        hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n      };\n      s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n      s.backendConnector.on('*', function (event) {\n        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n          args[_key - 1] = arguments[_key];\n        }\n        _this.emit(event, ...args);\n      });\n      if (this.modules.languageDetector) {\n        s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n        if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);\n      }\n      if (this.modules.i18nFormat) {\n        s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n        if (s.i18nFormat.init) s.i18nFormat.init(this);\n      }\n      this.translator = new Translator(this.services, this.options);\n      this.translator.on('*', function (event) {\n        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n          args[_key2 - 1] = arguments[_key2];\n        }\n        _this.emit(event, ...args);\n      });\n      this.modules.external.forEach(m => {\n        if (m.init) m.init(this);\n      });\n    }\n    this.format = this.options.interpolation.format;\n    if (!callback) callback = noop;\n    if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n      const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n      if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n    }\n    if (!this.services.languageDetector && !this.options.lng) {\n      this.logger.warn('init: no languageDetector is used and no lng is defined');\n    }\n    const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n    storeApi.forEach(fcName => {\n      this[fcName] = function () {\n        return _this.store[fcName](...arguments);\n      };\n    });\n    const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n    storeApiChained.forEach(fcName => {\n      this[fcName] = function () {\n        _this.store[fcName](...arguments);\n        return _this;\n      };\n    });\n    const deferred = defer();\n    const load = () => {\n      const finish = (err, t) => {\n        if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');\n        this.isInitialized = true;\n        if (!this.options.isClone) this.logger.log('initialized', this.options);\n        this.emit('initialized', this.options);\n        deferred.resolve(t);\n        callback(err, t);\n      };\n      if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));\n      this.changeLanguage(this.options.lng, finish);\n    };\n    if (this.options.resources || !this.options.initImmediate) {\n      load();\n    } else {\n      setTimeout(load, 0);\n    }\n    return deferred;\n  }\n  loadResources(language) {\n    let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n    let usedCallback = callback;\n    const usedLng = typeof language === 'string' ? language : this.language;\n    if (typeof language === 'function') usedCallback = language;\n    if (!this.options.resources || this.options.partialBundledLanguages) {\n      if (usedLng && usedLng.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();\n      const toLoad = [];\n      const append = lng => {\n        if (!lng) return;\n        if (lng === 'cimode') return;\n        const lngs = this.services.languageUtils.toResolveHierarchy(lng);\n        lngs.forEach(l => {\n          if (l === 'cimode') return;\n          if (toLoad.indexOf(l) < 0) toLoad.push(l);\n        });\n      };\n      if (!usedLng) {\n        const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n        fallbacks.forEach(l => append(l));\n      } else {\n        append(usedLng);\n      }\n      if (this.options.preload) {\n        this.options.preload.forEach(l => append(l));\n      }\n      this.services.backendConnector.load(toLoad, this.options.ns, e => {\n        if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);\n        usedCallback(e);\n      });\n    } else {\n      usedCallback(null);\n    }\n  }\n  reloadResources(lngs, ns, callback) {\n    const deferred = defer();\n    if (!lngs) lngs = this.languages;\n    if (!ns) ns = this.options.ns;\n    if (!callback) callback = noop;\n    this.services.backendConnector.reload(lngs, ns, err => {\n      deferred.resolve();\n      callback(err);\n    });\n    return deferred;\n  }\n  use(module) {\n    if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n    if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n    if (module.type === 'backend') {\n      this.modules.backend = module;\n    }\n    if (module.type === 'logger' || module.log && module.warn && module.error) {\n      this.modules.logger = module;\n    }\n    if (module.type === 'languageDetector') {\n      this.modules.languageDetector = module;\n    }\n    if (module.type === 'i18nFormat') {\n      this.modules.i18nFormat = module;\n    }\n    if (module.type === 'postProcessor') {\n      postProcessor.addPostProcessor(module);\n    }\n    if (module.type === 'formatter') {\n      this.modules.formatter = module;\n    }\n    if (module.type === '3rdParty') {\n      this.modules.external.push(module);\n    }\n    return this;\n  }\n  setResolvedLanguage(l) {\n    if (!l || !this.languages) return;\n    if (['cimode', 'dev'].indexOf(l) > -1) return;\n    for (let li = 0; li < this.languages.length; li++) {\n      const lngInLngs = this.languages[li];\n      if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;\n      if (this.store.hasLanguageSomeTranslations(lngInLngs)) {\n        this.resolvedLanguage = lngInLngs;\n        break;\n      }\n    }\n  }\n  changeLanguage(lng, callback) {\n    var _this2 = this;\n    this.isLanguageChangingTo = lng;\n    const deferred = defer();\n    this.emit('languageChanging', lng);\n    const setLngProps = l => {\n      this.language = l;\n      this.languages = this.services.languageUtils.toResolveHierarchy(l);\n      this.resolvedLanguage = undefined;\n      this.setResolvedLanguage(l);\n    };\n    const done = (err, l) => {\n      if (l) {\n        setLngProps(l);\n        this.translator.changeLanguage(l);\n        this.isLanguageChangingTo = undefined;\n        this.emit('languageChanged', l);\n        this.logger.log('languageChanged', l);\n      } else {\n        this.isLanguageChangingTo = undefined;\n      }\n      deferred.resolve(function () {\n        return _this2.t(...arguments);\n      });\n      if (callback) callback(err, function () {\n        return _this2.t(...arguments);\n      });\n    };\n    const setLng = lngs => {\n      if (!lng && !lngs && this.services.languageDetector) lngs = [];\n      const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);\n      if (l) {\n        if (!this.language) {\n          setLngProps(l);\n        }\n        if (!this.translator.language) this.translator.changeLanguage(l);\n        if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);\n      }\n      this.loadResources(l, err => {\n        done(err, l);\n      });\n    };\n    if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n      setLng(this.services.languageDetector.detect());\n    } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n      if (this.services.languageDetector.detect.length === 0) {\n        this.services.languageDetector.detect().then(setLng);\n      } else {\n        this.services.languageDetector.detect(setLng);\n      }\n    } else {\n      setLng(lng);\n    }\n    return deferred;\n  }\n  getFixedT(lng, ns, keyPrefix) {\n    var _this3 = this;\n    const fixedT = function (key, opts) {\n      let options;\n      if (typeof opts !== 'object') {\n        for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n          rest[_key3 - 2] = arguments[_key3];\n        }\n        options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n      } else {\n        options = {\n          ...opts\n        };\n      }\n      options.lng = options.lng || fixedT.lng;\n      options.lngs = options.lngs || fixedT.lngs;\n      options.ns = options.ns || fixedT.ns;\n      options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;\n      const keySeparator = _this3.options.keySeparator || '.';\n      let resultKey;\n      if (options.keyPrefix && Array.isArray(key)) {\n        resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);\n      } else {\n        resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;\n      }\n      return _this3.t(resultKey, options);\n    };\n    if (typeof lng === 'string') {\n      fixedT.lng = lng;\n    } else {\n      fixedT.lngs = lng;\n    }\n    fixedT.ns = ns;\n    fixedT.keyPrefix = keyPrefix;\n    return fixedT;\n  }\n  t() {\n    return this.translator && this.translator.translate(...arguments);\n  }\n  exists() {\n    return this.translator && this.translator.exists(...arguments);\n  }\n  setDefaultNamespace(ns) {\n    this.options.defaultNS = ns;\n  }\n  hasLoadedNamespace(ns) {\n    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    if (!this.isInitialized) {\n      this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n      return false;\n    }\n    if (!this.languages || !this.languages.length) {\n      this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n      return false;\n    }\n    const lng = options.lng || this.resolvedLanguage || this.languages[0];\n    const fallbackLng = this.options ? this.options.fallbackLng : false;\n    const lastLng = this.languages[this.languages.length - 1];\n    if (lng.toLowerCase() === 'cimode') return true;\n    const loadNotPending = (l, n) => {\n      const loadState = this.services.backendConnector.state[`${l}|${n}`];\n      return loadState === -1 || loadState === 2;\n    };\n    if (options.precheck) {\n      const preResult = options.precheck(this, loadNotPending);\n      if (preResult !== undefined) return preResult;\n    }\n    if (this.hasResourceBundle(lng, ns)) return true;\n    if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;\n    if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n    return false;\n  }\n  loadNamespaces(ns, callback) {\n    const deferred = defer();\n    if (!this.options.ns) {\n      if (callback) callback();\n      return Promise.resolve();\n    }\n    if (typeof ns === 'string') ns = [ns];\n    ns.forEach(n => {\n      if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);\n    });\n    this.loadResources(err => {\n      deferred.resolve();\n      if (callback) callback(err);\n    });\n    return deferred;\n  }\n  loadLanguages(lngs, callback) {\n    const deferred = defer();\n    if (typeof lngs === 'string') lngs = [lngs];\n    const preloaded = this.options.preload || [];\n    const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0);\n    if (!newLngs.length) {\n      if (callback) callback();\n      return Promise.resolve();\n    }\n    this.options.preload = preloaded.concat(newLngs);\n    this.loadResources(err => {\n      deferred.resolve();\n      if (callback) callback(err);\n    });\n    return deferred;\n  }\n  dir(lng) {\n    if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);\n    if (!lng) return 'rtl';\n    const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];\n    const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());\n    return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';\n  }\n  static createInstance() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    let callback = arguments.length > 1 ? arguments[1] : undefined;\n    return new I18n(options, callback);\n  }\n  cloneInstance() {\n    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n    const forkResourceStore = options.forkResourceStore;\n    if (forkResourceStore) delete options.forkResourceStore;\n    const mergedOptions = {\n      ...this.options,\n      ...options,\n      ...{\n        isClone: true\n      }\n    };\n    const clone = new I18n(mergedOptions);\n    if (options.debug !== undefined || options.prefix !== undefined) {\n      clone.logger = clone.logger.clone(options);\n    }\n    const membersToCopy = ['store', 'services', 'language'];\n    membersToCopy.forEach(m => {\n      clone[m] = this[m];\n    });\n    clone.services = {\n      ...this.services\n    };\n    clone.services.utils = {\n      hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n    };\n    if (forkResourceStore) {\n      clone.store = new ResourceStore(this.store.data, mergedOptions);\n      clone.services.resourceStore = clone.store;\n    }\n    clone.translator = new Translator(clone.services, mergedOptions);\n    clone.translator.on('*', function (event) {\n      for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n        args[_key4 - 1] = arguments[_key4];\n      }\n      clone.emit(event, ...args);\n    });\n    clone.init(mergedOptions, callback);\n    clone.translator.options = mergedOptions;\n    clone.translator.backendConnector.services.utils = {\n      hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n    };\n    return clone;\n  }\n  toJSON() {\n    return {\n      options: this.options,\n      store: this.store,\n      language: this.language,\n      languages: this.languages,\n      resolvedLanguage: this.resolvedLanguage\n    };\n  }\n}\nconst instance = I18n.createInstance();\ninstance.createInstance = I18n.createInstance;\n\nconst createInstance = instance.createInstance;\nconst dir = instance.dir;\nconst init = instance.init;\nconst loadResources = instance.loadResources;\nconst reloadResources = instance.reloadResources;\nconst use = instance.use;\nconst changeLanguage = instance.changeLanguage;\nconst getFixedT = instance.getFixedT;\nconst t = instance.t;\nconst exists = instance.exists;\nconst setDefaultNamespace = instance.setDefaultNamespace;\nconst hasLoadedNamespace = instance.hasLoadedNamespace;\nconst loadNamespaces = instance.loadNamespaces;\nconst loadLanguages = instance.loadLanguages;\n\nexport { changeLanguage, createInstance, instance as default, dir, exists, getFixedT, hasLoadedNamespace, init, loadLanguages, loadNamespaces, loadResources, reloadResources, setDefaultNamespace, t, use };\n","export function warn() {\n  if (console && console.warn) {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n    if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`;\n    console.warn(...args);\n  }\n}\nconst alreadyWarned = {};\nexport function warnOnce() {\n  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n    args[_key2] = arguments[_key2];\n  }\n  if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;\n  if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();\n  warn(...args);\n}\nconst loadedClb = (i18n, cb) => () => {\n  if (i18n.isInitialized) {\n    cb();\n  } else {\n    const initialized = () => {\n      setTimeout(() => {\n        i18n.off('initialized', initialized);\n      }, 0);\n      cb();\n    };\n    i18n.on('initialized', initialized);\n  }\n};\nexport function loadNamespaces(i18n, ns, cb) {\n  i18n.loadNamespaces(ns, loadedClb(i18n, cb));\n}\nexport function loadLanguages(i18n, lng, ns, cb) {\n  if (typeof ns === 'string') ns = [ns];\n  ns.forEach(n => {\n    if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);\n  });\n  i18n.loadLanguages(lng, loadedClb(i18n, cb));\n}\nfunction oldI18nextHasLoadedNamespace(ns, i18n) {\n  let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n  const lng = i18n.languages[0];\n  const fallbackLng = i18n.options ? i18n.options.fallbackLng : false;\n  const lastLng = i18n.languages[i18n.languages.length - 1];\n  if (lng.toLowerCase() === 'cimode') return true;\n  const loadNotPending = (l, n) => {\n    const loadState = i18n.services.backendConnector.state[`${l}|${n}`];\n    return loadState === -1 || loadState === 2;\n  };\n  if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;\n  if (i18n.hasResourceBundle(lng, ns)) return true;\n  if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;\n  if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n  return false;\n}\nexport function hasLoadedNamespace(ns, i18n) {\n  let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n  if (!i18n.languages || !i18n.languages.length) {\n    warnOnce('i18n.languages were undefined or empty', i18n.languages);\n    return true;\n  }\n  const isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;\n  if (!isNewerI18next) {\n    return oldI18nextHasLoadedNamespace(ns, i18n, options);\n  }\n  return i18n.hasLoadedNamespace(ns, {\n    lng: options.lng,\n    precheck: (i18nInstance, loadNotPending) => {\n      if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;\n    }\n  });\n}\nexport function getDisplayName(Component) {\n  return Component.displayName || Component.name || (typeof Component === 'string' && Component.length > 0 ? Component : 'Unknown');\n}","const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;\nconst htmlEntities = {\n  '&amp;': '&',\n  '&#38;': '&',\n  '&lt;': '<',\n  '&#60;': '<',\n  '&gt;': '>',\n  '&#62;': '>',\n  '&apos;': \"'\",\n  '&#39;': \"'\",\n  '&quot;': '\"',\n  '&#34;': '\"',\n  '&nbsp;': ' ',\n  '&#160;': ' ',\n  '&copy;': '©',\n  '&#169;': '©',\n  '&reg;': '®',\n  '&#174;': '®',\n  '&hellip;': '…',\n  '&#8230;': '…',\n  '&#x2F;': '/',\n  '&#47;': '/'\n};\nconst unescapeHtmlEntity = m => htmlEntities[m];\nexport const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);","import { unescape } from './unescape.js';\nlet defaultOptions = {\n  bindI18n: 'languageChanged',\n  bindI18nStore: '',\n  transEmptyNodeValue: '',\n  transSupportBasicHtmlNodes: true,\n  transWrapTextNodes: '',\n  transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],\n  useSuspense: true,\n  unescape\n};\nexport function setDefaults() {\n  let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n  defaultOptions = {\n    ...defaultOptions,\n    ...options\n  };\n}\nexport function getDefaults() {\n  return defaultOptions;\n}","let i18nInstance;\nexport function setI18n(instance) {\n  i18nInstance = instance;\n}\nexport function getI18n() {\n  return i18nInstance;\n}","import { setDefaults } from './defaults.js';\nimport { setI18n } from './i18nInstance.js';\nexport const initReactI18next = {\n  type: '3rdParty',\n  init(instance) {\n    setDefaults(instance.options.react);\n    setI18n(instance);\n  }\n};","import { createContext } from 'react';\nimport { getDefaults, setDefaults } from './defaults.js';\nimport { getI18n, setI18n } from './i18nInstance.js';\nimport { initReactI18next } from './initReactI18next.js';\nexport { getDefaults, setDefaults, getI18n, setI18n, initReactI18next };\nexport const I18nContext = createContext();\nexport class ReportNamespaces {\n  constructor() {\n    this.usedNamespaces = {};\n  }\n  addUsedNamespaces(namespaces) {\n    namespaces.forEach(ns => {\n      if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;\n    });\n  }\n  getUsedNamespaces() {\n    return Object.keys(this.usedNamespaces);\n  }\n}\nexport function composeInitialProps(ForComponent) {\n  return ctx => new Promise(resolve => {\n    const i18nInitialProps = getInitialProps();\n    if (ForComponent.getInitialProps) {\n      ForComponent.getInitialProps(ctx).then(componentsInitialProps => {\n        resolve({\n          ...componentsInitialProps,\n          ...i18nInitialProps\n        });\n      });\n    } else {\n      resolve(i18nInitialProps);\n    }\n  });\n}\nexport function getInitialProps() {\n  const i18n = getI18n();\n  const namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : [];\n  const ret = {};\n  const initialI18nStore = {};\n  i18n.languages.forEach(l => {\n    initialI18nStore[l] = {};\n    namespaces.forEach(ns => {\n      initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};\n    });\n  });\n  ret.initialI18nStore = initialI18nStore;\n  ret.initialLanguage = i18n.language;\n  return ret;\n}","import { useState, useEffect, useContext, useRef } from 'react';\nimport { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context.js';\nimport { warnOnce, loadNamespaces, loadLanguages, hasLoadedNamespace } from './utils.js';\nconst usePrevious = (value, ignore) => {\n  const ref = useRef();\n  useEffect(() => {\n    ref.current = ignore ? ref.current : value;\n  }, [value, ignore]);\n  return ref.current;\n};\nexport function useTranslation(ns) {\n  let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n  const {\n    i18n: i18nFromProps\n  } = props;\n  const {\n    i18n: i18nFromContext,\n    defaultNS: defaultNSFromContext\n  } = useContext(I18nContext) || {};\n  const i18n = i18nFromProps || i18nFromContext || getI18n();\n  if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();\n  if (!i18n) {\n    warnOnce('You will need to pass in an i18next instance by using initReactI18next');\n    const notReadyT = (k, optsOrDefaultValue) => {\n      if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;\n      if (optsOrDefaultValue && typeof optsOrDefaultValue === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue;\n      return Array.isArray(k) ? k[k.length - 1] : k;\n    };\n    const retNotReady = [notReadyT, {}, false];\n    retNotReady.t = notReadyT;\n    retNotReady.i18n = {};\n    retNotReady.ready = false;\n    return retNotReady;\n  }\n  if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');\n  const i18nOptions = {\n    ...getDefaults(),\n    ...i18n.options.react,\n    ...props\n  };\n  const {\n    useSuspense,\n    keyPrefix\n  } = i18nOptions;\n  let namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;\n  namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];\n  if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);\n  const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));\n  function getT() {\n    return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n  }\n  const [t, setT] = useState(getT);\n  let joinedNS = namespaces.join();\n  if (props.lng) joinedNS = `${props.lng}${joinedNS}`;\n  const previousJoinedNS = usePrevious(joinedNS);\n  const isMounted = useRef(true);\n  useEffect(() => {\n    const {\n      bindI18n,\n      bindI18nStore\n    } = i18nOptions;\n    isMounted.current = true;\n    if (!ready && !useSuspense) {\n      if (props.lng) {\n        loadLanguages(i18n, props.lng, namespaces, () => {\n          if (isMounted.current) setT(getT);\n        });\n      } else {\n        loadNamespaces(i18n, namespaces, () => {\n          if (isMounted.current) setT(getT);\n        });\n      }\n    }\n    if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {\n      setT(getT);\n    }\n    function boundReset() {\n      if (isMounted.current) setT(getT);\n    }\n    if (bindI18n && i18n) i18n.on(bindI18n, boundReset);\n    if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);\n    return () => {\n      isMounted.current = false;\n      if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset));\n      if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));\n    };\n  }, [i18n, joinedNS]);\n  const isInitial = useRef(true);\n  useEffect(() => {\n    if (isMounted.current && !isInitial.current) {\n      setT(getT);\n    }\n    isInitial.current = false;\n  }, [i18n, keyPrefix]);\n  const ret = [t, i18n, ready];\n  ret.t = t;\n  ret.i18n = i18n;\n  ret.ready = ready;\n  if (ready) return ret;\n  if (!ready && !useSuspense) return ret;\n  throw new Promise(resolve => {\n    if (props.lng) {\n      loadLanguages(i18n, props.lng, namespaces, () => resolve());\n    } else {\n      loadNamespaces(i18n, namespaces, () => resolve());\n    }\n  });\n}","import i18n from \"i18next\";\nimport { initReactI18next, useTranslation } from \"react-i18next\";\nimport { DeepPartial } from \"@/utils/types\";\n\nexport const useBaseTranslations = () => useTranslation([\"main\", \"glossary\"]);\n\nexport const resources = {\n  en: {\n    glossary: {\n      condition_one: \"condition\",\n      condition_other: \"conditions\",\n    },\n    main: {\n      \"resource.add\": \"Add {{resource}}\",\n      \"resource.edit\": \"Edit {{resource}}\",\n      \"resource.history.heading\": \"{{resource}} history\",\n      \"resource.history.loading\": \"Loading {{resource}} history...\",\n      \"resource.remove.body\":\n        \"This will remove {{resourceName}} from this patient's {{resource}} list.\",\n      \"resource.remove.heading\": \"Remove this {{resource}}?\",\n      \"resource.unnamed\": \"unnamed {{resource}}\",\n      \"resourceTable.add\": \"Add\",\n      \"resourceTable.preview\": \"Open\",\n      \"resourceTable.read\": \"Mark as Viewed\",\n      \"resourceTable.unread\": \"Mark as New\",\n      \"resourceTable.dismiss\": \"Dismiss\",\n      \"resourceTable.restore\": \"Restore\",\n      \"zap.tabs.medicationsOutside\": \"medications\",\n      \"zap.tabs.conditions\": \"$t(glossary:condition_other) list\",\n      \"zap.tabs.conditionsOutside\": \"outside $t(glossary:condition_other)\",\n      \"zap.tabs.conditionsAll\": \"$t(glossary:condition_other)\",\n      commonwell: \"EHR Network\",\n      surescripts: \"Pharmacy Data\",\n      bamboo: \"ADT\",\n      collective: \"ADT\",\n      quest: \"Labs\",\n    },\n  },\n};\n\nexport type Locals = DeepPartial<typeof resources>;\n\nvoid i18n\n  .use(initReactI18next) // passes i18n down to react-i18next\n  .init({\n    ns: [\"glossary\", \"main\"],\n    returnNull: false,\n    defaultNS: [\"main\", \"glossary\"],\n    resources,\n    lng: \"en\", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources\n    interpolation: {\n      escapeValue: false, // react already safes from xss\n    },\n  });\n\nexport default i18n;\n","import { faChevronDown, faChevronUp } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { Resource } from \"fhir/r4\";\nimport { useState } from \"react\";\nimport { useToggleDismiss } from \"../hooks/use-toggle-dismiss\";\nimport { useToggleRead } from \"../hooks/use-toggle-read\";\nimport { DropdownMenuSimple } from \"@/components/core/dropdown-menu-simple\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { useRequestContext } from \"@/components/core/providers/use-request-context\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { Spinner } from \"@/components/core/spinner\";\nimport { RowActionsProps, TableProps } from \"@/components/core/table/table\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ViewFHIR } from \"@/components/core/view-fhir\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { useBaseTranslations } from \"@/i18n\";\n\nexport type AdditionalResourceActionsProps<T extends MinRecordItem> = {\n  rowActions?: (r: T) => TableProps<T>[\"rowActions\"];\n  enableDismissAndReadActions?: boolean;\n  // Will adjust the way the dropdown menu appears if the content will be rendered in a footer\n  isInFooter?: boolean;\n  queryKey?: string;\n};\n\nexport const useAdditionalResourceActions = <T extends Resource, M extends FHIRModel<T>>({\n  rowActions,\n  enableDismissAndReadActions,\n  isInFooter = false,\n}: AdditionalResourceActionsProps<M>) => {\n  const { featureFlags } = useCTW();\n  const [selectedAction, setSelectedAction] = useState(\"card\");\n  const dismissAndReadActions = useDismissAndReadActions(enableDismissAndReadActions);\n\n  return ({ record, onSuccess, stacked = false }: RowActionsProps<M>) => {\n    const extraActions = dismissAndReadActions(record) ?? [];\n    const actions = rowActions?.(record) ?? [];\n    const combinedActions = [...extraActions, ...actions];\n    if (!combinedActions.length && !featureFlags?.enableViewFhirButton) return null;\n\n    if (stacked) {\n      return (\n        <div className=\"ctw-flex ctw-space-x-2\">\n          {featureFlags?.enableViewFhirButton && <ViewFHIR resource={record.resource} />}\n          {combinedActions.length > 0 && (\n            <DropdownMenuSimple\n              align=\"end\"\n              buttonClassName={cx(\"ctw-bg-transparent ctw-border-none ctw-bg-blue ctw-p-0\")}\n              onItemSelect={(item) => {\n                const selectedOption = combinedActions.filter(\n                  (action) => action.text === item.key,\n                )[0];\n                setSelectedAction(selectedOption.text);\n                setTimeout(() => {\n                  // This is a hack to make sure the dropdown menu closes before the action is executed to avoid\n                  // react state updates on unmounted components\n                  void selectedOption.onClick(record, onSuccess);\n                }, 1);\n              }}\n              items={combinedActions.map((item) => ({\n                key: item.text,\n                name: item.text,\n                display: item.render?.({ record, onSuccess, stacked }) ?? item.text,\n                isSelected: selectedAction === item.text,\n                disabled: item.disabled,\n              }))}\n            >\n              <div className=\"ctw-btn-primary ctw-flex ctw-items-center ctw-space-x-2 !ctw-py-0 ctw-font-normal\">\n                <span className=\"!ctw-border-r-1 ctw-mr-1.5 ctw-divide-bg-light ctw-border-0 ctw-border-solid ctw-py-2 ctw-pr-4 !ctw-text-white\">\n                  select action\n                </span>\n                <FontAwesomeIcon\n                  icon={isInFooter ? faChevronUp : faChevronDown}\n                  className=\"ctw-w-2 !ctw-text-white\"\n                />\n              </div>\n            </DropdownMenuSimple>\n          )}\n        </div>\n      );\n    }\n\n    return (\n      <div className=\"ctw-flex ctw-space-x-2\">\n        {featureFlags?.enableViewFhirButton && <ViewFHIR resource={record.resource} />}\n        {combinedActions.map(({ text, testId, onClick, disabled = false, className, render }) => (\n          <button\n            key={text}\n            type=\"button\"\n            disabled={disabled}\n            className={cx(className, \"ctw-row-action\")}\n            data-testid={testId}\n            onClick={() => {\n              void onClick(record, onSuccess);\n            }}\n          >\n            {render?.({ record, onSuccess, stacked }) ?? text}\n          </button>\n        ))}\n      </div>\n    );\n  };\n};\n\nfunction useDismissAndReadActions(enableDismissAndReadActions = false) {\n  const userBuilderId = useUserBuilderId();\n  const { t } = useBaseTranslations();\n  const requestContext = useRequestContext();\n  const { trackInteraction } = useAnalytics();\n\n  const { isLoading: isToggleDismissLoading, toggleDismiss } = useToggleDismiss();\n  const { isLoading: isToggleReadLoading, toggleRead } = useToggleRead();\n  return (record: FHIRModel<Resource>): RowActionsConfigProp<FHIRModel<Resource>> => {\n    const archiveLabel = record.isDismissed\n      ? t(\"resourceTable.restore\")\n      : t(\"resourceTable.dismiss\");\n\n    const readLabel = record.isRead ? t(\"resourceTable.unread\") : t(\"resourceTable.read\");\n\n    // In production, we want to avoid non-builder users from inadvertently marking records as read\n    // In lower environments this is allowed for demos/testing\n    const disableReadButton =\n      requestContext?.env === \"production\" && requestContext.userType !== \"builder\";\n    if (!enableDismissAndReadActions || record.ownedByBuilder(userBuilderId)) {\n      return [];\n    }\n    return [\n      {\n        className: \"ctw-btn-default\",\n        disabled: isToggleDismissLoading || isToggleReadLoading,\n        text: archiveLabel,\n        // eslint-disable-next-line @typescript-eslint/no-misused-promises\n        onClick: async () => {\n          trackInteraction(\"toggle_record_archive\", {\n            action: record.isDismissed ? \"restore\" : \"dismiss\",\n          });\n          await toggleDismiss(record);\n          if (!record.isRead) {\n            await toggleRead(record);\n          }\n        },\n        render() {\n          return (\n            <div className=\"ctw-flex\">\n              {isToggleDismissLoading && <Spinner className=\"ctw-mx-4 ctw-align-middle\" />}\n              {!isToggleDismissLoading && archiveLabel}\n            </div>\n          );\n        },\n      },\n      {\n        className: \"ctw-btn-default\",\n        disabled: disableReadButton || isToggleDismissLoading || isToggleReadLoading,\n        text: readLabel,\n        // eslint-disable-next-line @typescript-eslint/no-misused-promises\n        onClick: async () => {\n          if (record.isRead) {\n            trackInteraction(\"toggle_record_read\", { action: \"mark_as_unread\" });\n          } else {\n            trackInteraction(\"toggle_record_read\", { action: \"mark_as_read\" });\n          }\n          await toggleRead(record);\n        },\n        render() {\n          return (\n            <div className=\"ctw-flex\">\n              {isToggleReadLoading && <Spinner className=\"ctw-mx-4 ctw-align-middle\" />}\n              {!isToggleReadLoading && readLabel}\n            </div>\n          );\n        },\n      },\n    ];\n  };\n}\n","import { MinRecordItem, TableColumn } from \"./table-helpers\";\n\nexport type TableColGroupProps<T extends MinRecordItem> = {\n  columns: TableColumn<T>[];\n};\n\nexport const TableColGroup = <T extends MinRecordItem>({ columns }: TableColGroupProps<T>) => (\n  <colgroup>\n    {columns.map((column, index) => (\n      <col\n        key={column.title ?? index}\n        className={column.className}\n        width={column.widthPercent ? `${column.widthPercent}%` : undefined}\n        style={{\n          minWidth: column.minWidth,\n          width: column.width,\n        }}\n      />\n    ))}\n  </colgroup>\n);\n","import { MinRecordItem, TableColumn } from \"./table-helpers\";\n\nexport type TableHeadProps<T extends MinRecordItem> = {\n  columns: TableColumn<T>[];\n};\n\nexport const TableHead = <T extends MinRecordItem>({ columns }: TableHeadProps<T>) => (\n  <thead>\n    <tr>\n      {columns.map((column, index) => (\n        <th className=\"ctw-group\" key={column.title ?? index} scope=\"col\">\n          <div className=\"ctw-flex ctw-items-center ctw-space-x-2\">\n            <div>{column.title}</div>\n          </div>\n        </th>\n      ))}\n    </tr>\n  </thead>\n);\n","import cx from \"classnames\";\nimport { ReactNode } from \"react\";\nimport { MinRecordItem, TableColumn } from \"./table-helpers\";\n\ntype TableColumnProps<T extends MinRecordItem> = {\n  column: TableColumn<T>;\n  record: T;\n};\n\nexport const TableDataCell = <T extends MinRecordItem>({\n  column,\n  record,\n}: TableColumnProps<T>): JSX.Element => {\n  const value = column.dataIndex ? (record[column.dataIndex] as unknown as ReactNode) : undefined;\n\n  return (\n    <td\n      className={cx(\n        \"ctw-text-content-black\",\n        column.className,\n        // Added ctw-break-words because AbdominalReallyLongWordThatShouldBReakButDoeskadjlkajflkajsf doesn't wrap correclty without it.\n        \"ctw-hyphens-auto ctw-break-words\"\n      )}\n    >\n      {column.render ? column.render(record) : value}\n    </td>\n  );\n};\n","import { ReactNode } from \"react\";\n\nexport const TableFullLengthRow = ({\n  children,\n  colSpan,\n}: {\n  children: ReactNode;\n  colSpan: number;\n}) => (\n  <tr>\n    <td className=\"ctw-table-full-length-row\" colSpan={colSpan}>\n      {children}\n    </td>\n  </tr>\n);\n","import { Spinner } from \"./spinner\";\n\n// Shows centered loading message and spinner with some padding.\nexport function LoadingTable() {\n  return (\n    <div className=\"ctw-flex ctw-justify-center ctw-items-center ctw-space-x-2 ctw-py-9 ctw-px-4\">\n      <span>Loading...</span>\n      <Spinner />\n    </div>\n  );\n}\n","import cx from \"classnames\";\nimport { FunctionComponent, ReactElement } from \"react\";\nimport { TableDataCell } from \"./table-data-cell\";\nimport { TableFullLengthRow } from \"./table-full-length-row\";\nimport { MinRecordItem, TableColumn } from \"./table-helpers\";\nimport { LoadingTable } from \"../loading-table\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { RowActionsProps } from \"@/components/core/table/table\";\nimport { isFunction } from \"@/utils/nodash\";\nimport { VoidValue } from \"@/utils/types\";\n\nexport type RowActionsProp<T extends MinRecordItem> = FunctionComponent<RowActionsProps<T>>;\n\nexport type RowActionsConfigProp<T extends MinRecordItem> =\n  | {\n      text: string;\n      onClick: (record: T, onSuccess?: () => void) => VoidValue;\n      className: cx.Argument;\n      disabled?: boolean;\n      testId?: string;\n      render?: RowActionsProp<T>;\n    }[]\n  | undefined;\n\nexport type TableRowsProps<T extends MinRecordItem> = {\n  RowActions?: RowActionsProp<T>;\n  rowActions?: RowActionsConfigProp<T>;\n  columns: TableColumn<T>[];\n  emptyMessage: string | ReactElement;\n  getRowClassName?: (record: T) => cx.Argument;\n  handleRowClick?: (record: T) => void;\n  canClickRow?: (record: T) => boolean;\n  isLoading: boolean;\n  records: T[];\n  stacked: boolean;\n};\n\nexport const TableRows = <T extends MinRecordItem>({\n  records,\n  columns,\n  isLoading,\n  emptyMessage,\n  handleRowClick,\n  canClickRow = () => true,\n  RowActions,\n  getRowClassName,\n  stacked,\n}: TableRowsProps<T>) => {\n  const { trackInteraction } = useAnalytics();\n\n  if (isLoading) {\n    return (\n      <TableFullLengthRow colSpan={columns.length}>\n        <LoadingTable />\n      </TableFullLengthRow>\n    );\n  }\n\n  if (records.length === 0) {\n    return (\n      <TableFullLengthRow colSpan={columns.length}>\n        <span className=\"ctw-empty-message -ctw-mt-3.5 sm:ctw-mt-0\">{emptyMessage}</span>\n      </TableFullLengthRow>\n    );\n  }\n\n  return (\n    <>\n      {records.map((record) => (\n        <tr\n          // ctw-mx-px fixes bug where side borders disappear on hover when stacked.\n          className={cx(\n            \"ctw-group ctw-relative ctw-mx-px\",\n            isFunction(getRowClassName) ? getRowClassName(record) : \"\",\n            {\n              \"ctw-cursor-pointer hover:ctw-bg-bg-lighter\":\n                isFunction(handleRowClick) && canClickRow(record),\n            },\n          )}\n          key={record.key}\n          onClick={({ target }) => {\n            // This is for the case where a user clicks area near the button (but not on), we do not want have the onRowClick handler trigger as that will cause confusion to the user.\n            if (target instanceof HTMLElement && target.querySelectorAll(\"button\").length) {\n              return;\n            }\n\n            if (handleRowClick) {\n              handleRowClick(record);\n              trackInteraction(\"click_row\");\n            }\n          }}\n        >\n          {columns.map((column, index) => (\n            <TableDataCell\n              key={`${record.key}_${column.title ?? index}`}\n              column={column}\n              record={record}\n            />\n          ))}\n          {RowActions && (\n            // Add onClick here to prevent clicks from propagating to\n            // the to the tr's onClick for onRowClick.\n            // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events\n            <td\n              aria-label=\"row-actions\"\n              className=\"ctw-table-row-actions group-hover:ctw-visible\"\n              onClick={(event) => event.stopPropagation()}\n            >\n              <RowActions record={record} stacked={stacked} />\n            </td>\n          )}\n        </tr>\n      ))}\n    </>\n  );\n};\n","export const DEFAULT_PAGE_SIZE = 10;\n\nexport type ExpandListProps = {\n  total: number;\n  count: number;\n  changeCount: (amount: number) => void;\n};\n\nexport const ExpandList = ({ total, count, changeCount }: ExpandListProps) => {\n  const allShown = count >= total || total === 0;\n  const hasPages = total > DEFAULT_PAGE_SIZE;\n\n  return (\n    <div className=\"ctw-pagination !ctw-mt-1 sm:!ctw-mt-2\">\n      <div className=\"ctw-text-gray-600 ctw-text-sm\">\n        Showing <span className=\"ctw-font-medium\">{Math.min(count, total)}</span> of{\" \"}\n        <span className=\"ctw-font-medium\">{total}</span> records\n      </div>\n\n      {(!allShown || hasPages) && (\n        <div className=\"ctw-leading-5\">\n          {!allShown && (\n            <button\n              type=\"button\"\n              className=\"ctw-btn-clear ctw-link ctw-whitespace-nowrap\"\n              onClick={() => changeCount(total)}\n            >\n              Show All\n            </button>\n          )}\n\n          {allShown && hasPages && (\n            <button\n              type=\"button\"\n              className=\"ctw-btn-clear ctw-link ctw-whitespace-nowrap\"\n              onClick={() => changeCount(DEFAULT_PAGE_SIZE)}\n            >\n              Clear\n            </button>\n          )}\n        </div>\n      )}\n    </div>\n  );\n};\n","import \"./table.scss\";\n\nimport cx from \"classnames\";\nimport { ReactElement, ReactNode, useEffect, useRef, useState } from \"react\";\nimport { TableColGroup } from \"./table-colgroup\";\nimport { TableHead } from \"./table-head\";\nimport { MinRecordItem, TableColumn } from \"./table-helpers\";\nimport { TableRows, TableRowsProps } from \"./table-rows\";\nimport { DEFAULT_PAGE_SIZE, ExpandList } from \"../pagination/expand-list\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\nexport type RowActionsProps<T extends MinRecordItem> = {\n  record: T;\n  onSuccess?: () => void;\n  stacked?: boolean;\n};\n\nexport type TableProps<T extends MinRecordItem> = {\n  children?: ReactNode;\n  className?: cx.Argument;\n  columns: TableColumn<T>[];\n  /** Displayed when we have 0 records. */\n  emptyMessage?: string | ReactElement;\n  hidePagination?: boolean;\n  isLoading?: boolean;\n  pageSize?: number;\n  records: T[];\n  showTableHead?: boolean;\n  stacked?: boolean;\n} & Pick<\n  TableRowsProps<T>,\n  \"handleRowClick\" | \"canClickRow\" | \"RowActions\" | \"rowActions\" | \"getRowClassName\"\n>;\n\nexport type TableBaseProps<T extends MinRecordItem> = Omit<TableProps<T>, \"records\" | \"columns\">;\n\nexport const Table = <T extends MinRecordItem>({\n  className,\n  columns,\n  records,\n  isLoading = false,\n  emptyMessage: message = \"No records found\",\n  showTableHead = true,\n  stacked,\n  handleRowClick,\n  canClickRow,\n  RowActions,\n  getRowClassName,\n  hidePagination = false,\n  pageSize = DEFAULT_PAGE_SIZE,\n  children,\n}: TableProps<T>) => {\n  const tableRef = useRef<HTMLTableElement>(null);\n  const scrollContainerRef = useRef<HTMLDivElement>(null);\n  const [showLeftShadow, setShowLeftShadow] = useState(false);\n  const [showRightShadow, setShowRightShadow] = useState(false);\n  const [count, setCount] = useState(pageSize);\n  const breakpoints = useBreakpoints(tableRef);\n\n  const updateShadows = () => {\n    const container = scrollContainerRef.current;\n    const table = tableRef.current;\n    if (container && table) {\n      setShowLeftShadow(container.scrollLeft > 0);\n      const rightSide = container.scrollLeft + container.clientWidth;\n      setShowRightShadow(rightSide < table.clientWidth);\n    }\n  };\n\n  useEffect(() => {\n    const container = scrollContainerRef.current;\n\n    // Update right away.\n    updateShadows();\n\n    // Update on scroll or resize events.\n    container?.addEventListener(\"scroll\", updateShadows);\n    window.addEventListener(\"resize\", updateShadows);\n\n    return () => {\n      container?.removeEventListener(\"scroll\", updateShadows);\n      window.removeEventListener(\"resize\", updateShadows);\n    };\n  }, [scrollContainerRef, isLoading]);\n\n  const hasData = !isLoading && records.length > 0;\n\n  // useeffect to set the count to the default page size when the records change\n  useEffect(() => {\n    if (hidePagination && hasData) {\n      setCount(records.length);\n    } else {\n      setCount(pageSize);\n    }\n  }, [records, pageSize, hidePagination, hasData]);\n\n  return (\n    <div\n      className={cx(\"ctw-scrollable-pass-through-height ctw-space-y-4\", {\n        \"ctw-table-stacked\": stacked,\n      })}\n    >\n      <div\n        className={cx(\"ctw-table-container ctw-scrollable-pass-through-height\", className, {\n          \"ctw-table-scroll-left-shadow\": showLeftShadow,\n          \"ctw-table-scroll-right-shadow\": showRightShadow,\n        })}\n      >\n        <div className={cx(\"ctw-scrollbar ctw-scrollable-content\")} ref={scrollContainerRef}>\n          <table ref={tableRef}>\n            {hasData && <TableColGroup columns={columns} />}\n            {showTableHead && hasData && <TableHead columns={columns} />}\n            <tbody className={cx({ \"ctw-h-[7rem]\": records.length === 0 })}>\n              <TableRows\n                getRowClassName={getRowClassName}\n                records={records.slice(0, count)}\n                handleRowClick={handleRowClick}\n                canClickRow={canClickRow}\n                RowActions={RowActions}\n                columns={columns}\n                isLoading={isLoading}\n                emptyMessage={message}\n                stacked={breakpoints.sm}\n              />\n            </tbody>\n          </table>\n        </div>\n      </div>\n      {!hidePagination && !isLoading && (\n        <ExpandList total={records.length} count={count} changeCount={setCount} />\n      )}\n      {children}\n    </div>\n  );\n};\n","import cx from \"classnames\";\nimport { ReactElement, ReactNode, useRef } from \"react\";\nimport { useAdditionalResourceActions } from \"./use-additional-resource-actions\";\nimport { useToggleRead } from \"../hooks/use-toggle-read\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { Table, TableProps } from \"@/components/core/table/table\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport \"./resource-table.scss\";\n\nexport type ResourceTableProps<T extends MinRecordItem> = {\n  className?: string;\n  columns: TableProps<T>[\"columns\"];\n  data: T[];\n  emptyMessage?: string | ReactElement;\n  isLoading?: boolean;\n  onRowClick?: TableProps<T>[\"handleRowClick\"];\n  rowActions?: (r: T) => TableProps<T>[\"rowActions\"];\n  showTableHead?: boolean;\n  enableDismissAndReadActions?: boolean;\n  hidePagination?: boolean;\n  children?: ReactNode;\n  queryKey?: string;\n};\n\nexport const ResourceTable = <T extends fhir4.Resource, M extends FHIRModel<T>>({\n  className,\n  columns,\n  data,\n  emptyMessage,\n  isLoading = false,\n  onRowClick,\n  rowActions,\n  showTableHead,\n  enableDismissAndReadActions,\n  hidePagination = false,\n  children,\n  queryKey,\n}: ResourceTableProps<M>) => {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n  const userBuilderId = useUserBuilderId();\n\n  const shouldShowTableHead = typeof showTableHead === \"boolean\" ? showTableHead : !breakpoints.sm;\n\n  const { toggleRead } = useToggleRead();\n\n  // Create the RowActions react node\n  const RowActionsWithAdditions = useAdditionalResourceActions({\n    rowActions,\n    enableDismissAndReadActions,\n    queryKey,\n  });\n\n  const onRowClickWithRead = onRowClick\n    ? async (record: M) => {\n        if (\n          !record.isRead &&\n          enableDismissAndReadActions &&\n          !record.ownedByBuilder(userBuilderId)\n        ) {\n          void toggleRead(record);\n        }\n        onRowClick(record);\n      }\n    : undefined;\n\n  return (\n    <div\n      ref={containerRef}\n      className={cx(className, \"ctw-scrollable-pass-through-height ctw-resource-table\")}\n    >\n      <Table\n        getRowClassName={(record) => ({\n          \"ctw-tr-dismissed\": record.isDismissed,\n          \"ctw-tr-unread\":\n            enableDismissAndReadActions && !record.ownedByBuilder(userBuilderId) && !record.isRead,\n        })}\n        showTableHead={shouldShowTableHead}\n        stacked={breakpoints.sm}\n        emptyMessage={emptyMessage}\n        isLoading={isLoading}\n        records={data}\n        RowActions={RowActionsWithAdditions}\n        columns={columns}\n        handleRowClick={onRowClickWithRead}\n        hidePagination={hidePagination}\n      >\n        {children}\n      </Table>\n    </div>\n  );\n};\n","import { usePatient } from \"@/components/core/providers/patient-provider\";\n\nexport function usePatientError () {\n  const patient = usePatient();\n\n  if (!patient.isLoading) {\n    if (\n      patient.error &&\n      typeof patient.error === \"object\" &&\n      \"status\" in patient.error &&\n      patient.error.status === 401\n    ) {\n      return {\n        authError: true,\n      }\n    }\n\n    if (!patient.data) {\n      return {\n        notFoundError: true,\n      }\n    }\n  }\n\n  return {}\n}\n","export const NoAuthIcon = ({ className }: { className?: string }) => (\n  <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 60 60\" fill=\"none\" className={className}>\n    <path\n      fillRule=\"evenodd\"\n      clipRule=\"evenodd\"\n      d=\"M11.5108 15.3194V20.4258H9.80861C5.97877 20.4258 3 23.511 3 27.2344V50.2135C3 54.0433 5.97877 57.0221 9.80861 57.0221H30.0649C27.5176 54.0467 25.9791 50.1821 25.9791 45.9581C25.9791 36.5574 33.5999 28.9366 43.0006 28.9366C45.7557 28.9366 48.3579 29.5912 50.6603 30.7533V27.2344C50.6603 23.511 47.5751 20.4258 43.8517 20.4258H42.1495V15.3194C42.1495 6.91499 35.2345 0 26.8301 0C18.3194 0 11.5108 6.91499 11.5108 15.3194ZM18.3194 20.4258V15.3194C18.3194 10.6385 22.0428 6.80861 26.8301 6.80861C31.5111 6.80861 35.3409 10.6385 35.3409 15.3194V20.4258H18.3194Z\"\n      fill=\"#9CA3AF\"\n    />\n    <path\n      fillRule=\"evenodd\"\n      clipRule=\"evenodd\"\n      d=\"M28.5323 45.6744C28.5323 37.8926 34.9351 31.4898 42.8154 31.4898C50.5972 31.4898 57 37.8926 57 45.6744C57 53.5548 50.5972 59.859 42.8154 59.859C34.9351 59.859 28.5323 53.5548 28.5323 45.6744ZM49.0191 42.5203C49.6102 41.9293 49.6102 40.8457 49.0191 40.2547C48.4281 39.6637 47.3446 39.6637 46.7535 40.2547L43.2074 43.8994L39.5627 40.2547C38.9717 39.6637 37.8882 39.6637 37.2971 40.2547C36.7061 40.8457 36.7061 41.9293 37.2971 42.5203L40.9418 46.0665L37.2971 49.7111C36.7061 50.3022 36.7061 51.3857 37.2971 51.9767C37.8882 52.5677 38.9717 52.5677 39.5627 51.9767L43.2074 48.3321L46.7535 51.9767C47.3446 52.5677 48.4281 52.5677 49.0191 51.9767C49.6102 51.3857 49.6102 50.3022 49.0191 49.7111L45.3745 46.0665L49.0191 42.5203Z\"\n      fill=\"#9CA3AF\"\n    />\n  </svg>\n);\n","import { NoAuthIcon } from \"./icons/no-auth-icon\";\n\nexport const AuthError = () => (\n  <div className=\"ctw-space-y-6\">\n    <div className=\"ctw-flex ctw-justify-center\">\n      <NoAuthIcon className=\"ctw-h-16\" />\n    </div>\n    <div className=\"ctw-space-y-3 ctw-text-center ctw-text-base\">\n      <div className=\"ctw-text-xl ctw-font-medium\">Not authorized</div>\n      <div>\n        Your account does not have access to this feature.\n        <br />\n        For further assistance, contact{\" \"}\n        <a href=\"mailto:support@zushealth.com\" className=\"ctw-text-content-black\">\n          support@zushealth.com\n        </a>\n        .\n      </div>\n      <div className=\"ctw-text-xs ctw-text-content-light\">HTTP ERROR 401</div>\n    </div>\n  </div>\n);\n","import { ResourceTable, ResourceTableProps } from \"./resource-table\";\nimport { usePatientError } from \"@/components/content/hooks/use-patient-error\";\nimport { AuthError } from \"@/components/core/auth-error\";\nimport { usePatient } from \"@/components/core/providers/patient-provider\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport \"./resource-table.scss\";\n\nexport const PatientResourceTable = <T extends fhir4.Resource, M extends FHIRModel<T>>({\n  className,\n  columns,\n  data,\n  emptyMessage,\n  isLoading = false,\n  onRowClick,\n  rowActions,\n  showTableHead,\n  enableDismissAndReadActions,\n  hidePagination = false,\n  queryKey,\n}: ResourceTableProps<M>) => {\n  const patient = usePatient();\n  const { authError, notFoundError } = usePatientError();\n\n  // Use correct empty message when there are auth errors or failure fetching patient data.\n  let emptyMessage2 = emptyMessage;\n  if (authError) {\n    emptyMessage2 = <AuthError />;\n  } else if (notFoundError) {\n    emptyMessage2 = <div className=\"ctw-space-y-4\">Patient not found.</div>;\n  }\n\n  // We're loading, if our patient is loading OR\n  // if we have our patient data but the passed in isLoading is true.\n  // We have to check for patient.data because most queries are only\n  // enabled when we have a patient UPID, without one, those queries\n  // will stay in the loading state forever.\n  const isLoading2 = patient.isLoading || (!!patient.data && isLoading);\n\n  return (\n    <ResourceTable\n      className={className}\n      columns={columns}\n      data={data}\n      emptyMessage={emptyMessage2}\n      isLoading={isLoading2}\n      onRowClick={onRowClick}\n      showTableHead={showTableHead}\n      rowActions={rowActions}\n      enableDismissAndReadActions={enableDismissAndReadActions}\n      hidePagination={hidePagination}\n      queryKey={queryKey}\n    />\n  );\n};\n","import { useContext } from \"react\";\nimport { ThemeContext } from \"./context\";\n\nexport function useCtwThemeRef(): React.RefObject<HTMLDivElement> {\n  const context = useContext(ThemeContext);\n  return context.ctwThemeRef;\n}\n","import cx from \"classnames\";\nimport { ReactNode, useEffect, useState } from \"react\";\nimport { useAdditionalResourceActions } from \"./use-additional-resource-actions\";\nimport { ResponsiveSourceDocumentLink } from \"@/components/content/CCDA/responsive-source-document-link\";\nimport { DetailsCard, DetailsProps } from \"@/components/content/resource/helpers/details-card\";\nimport { Drawer } from \"@/components/core/drawer\";\nimport { Loading } from \"@/components/core/loading\";\nimport { TrackingMetadata } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useDrawer } from \"@/components/core/providers/drawer-provider\";\nimport { useCtwThemeRef } from \"@/components/core/providers/theme/use-ctw-theme-ref\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { getBinaryId } from \"@/fhir/binaries\";\nimport { DocumentModel } from \"@/fhir/models/document\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { searchProvenances } from \"@/fhir/provenance\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\nexport type UseResourceDetailsDrawerProps<T extends fhir4.Resource, M extends FHIRModel<T>> = Pick<\n  ResourceDetailsDrawerProps<T, M>,\n  | \"header\"\n  | \"subHeader\"\n  | \"getSourceDocument\"\n  | \"details\"\n  | \"rowActions\"\n  | \"enableDismissAndReadActions\"\n  | \"renderChild\"\n  | \"queryKey\"\n>;\n\nexport function useResourceDetailsDrawer<T extends fhir4.Resource, M extends FHIRModel<T>>(\n  props: UseResourceDetailsDrawerProps<T, M>,\n) {\n  const { openDrawer } = useDrawer();\n\n  return (model: M, trackingMetadata?: TrackingMetadata) => {\n    openDrawer({\n      component: (drawerProps) => (\n        <ResourceDetailsDrawer model={model} {...props} {...drawerProps} />\n      ),\n      trackingMetadata: { resourceType: model.resourceType, ...trackingMetadata },\n    });\n  };\n}\n\ntype ResourceDetailsDrawerProps<T extends fhir4.Resource, M extends FHIRModel<T>> = {\n  className?: string;\n  details: (model: M) => DetailsProps[\"details\"];\n  getSourceDocument?: boolean;\n  header: (model: M) => ReactNode;\n  isOpen: boolean;\n  model: M;\n  onClose: () => void;\n  rowActions?: (model: M) => RowActionsConfigProp<M>;\n  enableDismissAndReadActions?: boolean;\n  subHeader?: (model: M) => ReactNode;\n  renderChild?: (model: M) => ReactNode;\n  queryKey?: string;\n};\n\nfunction ResourceDetailsDrawer<T extends fhir4.Resource, M extends FHIRModel<T>>({\n  className,\n  details,\n  getSourceDocument,\n  header,\n  isOpen,\n  model,\n  onClose,\n  rowActions,\n  enableDismissAndReadActions,\n  subHeader,\n  renderChild,\n  queryKey,\n}: ResourceDetailsDrawerProps<T, M>) {\n  const ctwThemeRef = useCtwThemeRef();\n  const [isLoading, setIsLoading] = useState(false);\n  const [binaryId, setBinaryId] = useState<string>();\n  const { getRequestContext } = useCTW();\n  const breakpoints = useBreakpoints(ctwThemeRef);\n\n  // We optionally look for any associated binary CCDAs\n  // if getSourceDocument is true.\n  useEffect(() => {\n    async function load() {\n      setIsLoading(true);\n      const requestContext = await getRequestContext();\n      const provenances = await searchProvenances(requestContext, [model]);\n      setBinaryId(getBinaryId(provenances, model.id));\n      setIsLoading(false);\n    }\n\n    if (model instanceof DocumentModel) {\n      // Special handling for document models which already have a binaryID.\n      setBinaryId(model.binaryId);\n    } else if (getSourceDocument) {\n      void load();\n    }\n  }, [getSourceDocument, model, getRequestContext]);\n\n  const rowActionsWithAdditions = useAdditionalResourceActions({\n    rowActions,\n    enableDismissAndReadActions,\n    isInFooter: true,\n    queryKey,\n  });\n\n  // We call rowActions right away so we'll know if it returns null and thus we should\n  // hide our footer.\n  const actions = rowActionsWithAdditions({\n    record: model,\n    onSuccess: onClose,\n    stacked: breakpoints.xs,\n  });\n  return (\n    <Drawer className={className} title={model.resourceTypeTitle} isOpen={isOpen} onClose={onClose}>\n      <Drawer.Body>\n        <div className=\"ctw-space-y-6\">\n          <div className=\"ctw-space-y-2 ctw-px-2\">\n            <div className={cx(breakpoints.xs ? \"ctw-text-2xl\" : \"ctw-text-3xl\")}>\n              {header(model)}\n            </div>\n            {subHeader && <div>{subHeader(model)}</div>}\n          </div>\n\n          {isLoading ? (\n            <Loading message=\"Loading data...\" />\n          ) : (\n            <DetailsCard\n              details={details(model)}\n              documentButton={\n                <ResponsiveSourceDocumentLink\n                  contentType={model instanceof DocumentModel ? model.contentType : \"\"}\n                  binaryId={binaryId}\n                  forceInModel={model instanceof DocumentModel && !model.contentType?.includes(\"xml\")}\n                  documentTitle={model.resourceTypeTitle}\n                  telemetryTarget=\"resource_details_drawer\"\n                />\n              }\n            />\n          )}\n          {renderChild && renderChild(model)}\n        </div>\n      </Drawer.Body>\n      <Drawer.Footer>\n        <div className=\"ctw-flex ctw-justify-between\">\n          <Drawer.CloseButton onClose={onClose} label=\"Close\" />\n          {actions}\n        </div>\n      </Drawer.Footer>\n    </Drawer>\n  );\n}\n","import { IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { ReactNode } from \"react\";\n\nexport type MenuItemProps = {\n  children: ReactNode;\n  icon?: IconDefinition;\n};\n\nexport function MenuItem({ children, icon }: MenuItemProps) {\n  return (\n    <div className=\"ctw-flex ctw-items-center ctw-space-x-3\">\n      {icon && (\n        <FontAwesomeIcon\n          icon={icon}\n          // The 2px bottom margin helps vertically center icon with text.\n          // This issue comes up as text and icons have different whitespace\n          // and visually look different when vertically\n          // centered normally (ctw-items-center).\n          className=\"ctw-mb-[2px] ctw-w-4 ctw-text-content-lighter\"\n        />\n      )}\n      <div>{children}</div>\n    </div>\n  );\n}\n","import { faCheck, IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { Menu } from \"@headlessui/react\";\nimport * as RadixDropdownMenu from \"@radix-ui/react-dropdown-menu\";\nimport cx from \"classnames\";\nimport { ReactNode, useState } from \"react\";\nimport { MenuItem } from \"./menu/menu-item\";\nimport { useCtwThemeRef } from \"./providers/theme/use-ctw-theme-ref\";\nimport \"./dropdown-action-menu.scss\";\n\nexport type MenuItem = {\n  action: () => void;\n  className?: string;\n  icon?: IconDefinition;\n  name: string;\n};\n\nexport type OptionsItem = {\n  key: string;\n  name: string;\n  display?: ReactNode;\n  isSelected?: boolean;\n};\nexport type DropDownMenuItemType = \"checkbox\" | \"select\";\n\nexport type DropdownMenuProps = {\n  buttonClassName?: cx.Argument;\n  children: ReactNode;\n  items: OptionsItem[];\n  onItemSelect: (clickedItem: { key: string; name: string; value: boolean }) => void;\n  type?: DropDownMenuItemType;\n  customOptionRender?: (optionsItem: OptionsItem) => JSX.Element;\n  pinnedActions?: MenuItem[];\n  isOpen?: boolean;\n  container?: HTMLDivElement | null;\n};\n\nexport function DropdownMenuAction({\n  children,\n  items,\n  onItemSelect,\n  type,\n  buttonClassName,\n  pinnedActions = [],\n  isOpen,\n}: DropdownMenuProps) {\n  const ctwThemeRef = useCtwThemeRef();\n  const [isMenuOpen, setIsMenuOpen] = useState(isOpen);\n  return (\n    <Menu>\n      <RadixDropdownMenu.Root\n        modal={false}\n        open={isMenuOpen}\n        onOpenChange={(e) => setIsMenuOpen(e)}\n      >\n        <RadixDropdownMenu.Trigger className={cx(buttonClassName)} aria-label=\"dropdown\">\n          {children}\n        </RadixDropdownMenu.Trigger>\n        <RadixDropdownMenu.Portal container={ctwThemeRef.current}>\n          <RadixDropdownMenu.Content\n            align=\"start\"\n            // Prevent focus from closing menu, this fixes\n            // an issue with interactive testing where a \"click\"\n            // would fire twice, once for the mousedown and\n            // again for focus on the button being clicked.\n            onFocusOutside={(event) => event.preventDefault()}\n            className=\"ctw-dropdown-action-menu ctw-bg-bg-white\"\n            collisionPadding={10}\n          >\n            {items.map((menuItem) => (\n              <RadixDropdownMenu.Item\n                key={menuItem.key}\n                className={cx(\"ctw-dropdown-action-menu-item ctw-bg-bg-white\")}\n                onClick={(e) => {\n                  if (type === \"checkbox\") {\n                    e.preventDefault();\n                  }\n\n                  onItemSelect({\n                    key: menuItem.key,\n                    name: menuItem.name,\n                    value: !menuItem.isSelected,\n                  });\n                }}\n              >\n                <RenderCorrectFieldType\n                  inputType={type}\n                  menuItem={menuItem}\n                  onClick={onItemSelect}\n                />\n              </RadixDropdownMenu.Item>\n            ))}\n\n            {pinnedActions.length > 0 && (\n              <>\n                <RadixDropdownMenu.Separator className=\"ctw-dropdown-separator\" />\n                {pinnedActions.map((menuItem) => (\n                  <RadixDropdownMenu.Item\n                    onClick={() => menuItem.action()}\n                    key={menuItem.name}\n                    className={cx(menuItem.className, \"ctw-dropdown-action-menu-item\")}\n                  >\n                    <MenuItem icon={menuItem.icon}>{menuItem.name}</MenuItem>\n                  </RadixDropdownMenu.Item>\n                ))}\n              </>\n            )}\n          </RadixDropdownMenu.Content>\n        </RadixDropdownMenu.Portal>\n      </RadixDropdownMenu.Root>\n    </Menu>\n  );\n}\n\nexport type RenderCorrectFieldTypeProps = {\n  inputType?: DropDownMenuItemType;\n  menuItem: OptionsItem;\n  onClick: (clickedItem: { key: string; name: string; value: boolean }) => void;\n};\n\nconst RenderCorrectFieldType = ({ inputType, menuItem, onClick }: RenderCorrectFieldTypeProps) => {\n  switch (inputType) {\n    case \"checkbox\":\n      return (\n        <div>\n          <label\n            htmlFor={menuItem.name}\n            className=\"ctw-flex ctw-cursor-pointer ctw-items-center ctw-space-x-3\"\n          >\n            <input\n              type=\"checkbox\"\n              className=\"ctw-m-0 ctw-mb-px ctw-w-4\"\n              name={menuItem.name}\n              onClick={(e) => {\n                onClick({\n                  key: menuItem.key,\n                  name: menuItem.name,\n                  value: !menuItem.isSelected,\n                });\n                e.stopPropagation();\n              }}\n              checked={!!menuItem.isSelected}\n              onChange={(e) => {\n                e.stopPropagation();\n              }}\n            />\n            {menuItem.display ? menuItem.display : <span>{menuItem.name}</span>}\n          </label>\n        </div>\n      );\n    case \"select\":\n      return (\n        <div className=\"ctw-flex ctw-w-full ctw-justify-between\">\n          <span className={cx({ \"ctw-font-semibold\": menuItem.isSelected })}>\n            {menuItem.display ? menuItem.display : menuItem.name}\n          </span>\n          {menuItem.isSelected && (\n            <FontAwesomeIcon\n              icon={faCheck}\n              className=\"ctw-inline-block ctw-h-4 ctw-stroke-0 ctw-align-middle ctw-text-primary-dark\"\n            />\n          )}\n        </div>\n      );\n    default:\n      return <div>{menuItem.name}</div>;\n  }\n};\n","import { faChevronDown } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useState } from \"react\";\nimport { DropdownMenuAction } from \"@/components/core/dropdown-action-menu\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { FilterEntry } from \"@/utils/filters\";\n\nexport type ViewOption<T extends object> = {\n  display: string;\n  filters: FilterEntry<T>[];\n};\n\nexport type ViewButtonProps<T extends object> = {\n  className?: cx.Argument;\n  defaultView?: string;\n  onChange: (view: ViewOption<T>) => void;\n  options: ViewOption<T>[];\n};\n\nexport const ViewButton = <T extends object>({\n  className,\n  defaultView,\n  onChange,\n  options,\n}: ViewButtonProps<T>) => {\n  const defaultViewOption = options.find((o) => o.display === defaultView) ?? options[0];\n  const [selected, setSelected] = useState<ViewOption<T>>(defaultViewOption);\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <DropdownMenuAction\n      type=\"select\"\n      buttonClassName={cx(className, \"ctw-bg-transparent ctw-border-none ctw-p-0\")}\n      onItemSelect={(item) => {\n        const selectedOption = options.filter((option) => option.display === item.key)[0];\n        onChange(selectedOption);\n        setSelected(selectedOption);\n        trackInteraction(\"change_view\", { value: selectedOption.display });\n      }}\n      items={options.map((option) => ({\n        key: option.display,\n        name: option.display,\n        isSelected: selected.display === option.display,\n      }))}\n    >\n      <div className=\"ctw-btn-default ctw-flex ctw-items-center ctw-space-x-2\">\n        <span className=\"ctw-mr-1.5 ctw-w-full ctw-font-normal\">{selected.display}</span>\n        <FontAwesomeIcon icon={faChevronDown} className=\"ctw-ml-auto ctw-w-2\" />\n      </div>\n    </DropdownMenuAction>\n  );\n};\n","import type { FilterItem } from \"./filter-bar-types\";\nimport { FilterChangeEvent, FilterValuesRecord } from \"./filter-bar-types\";\nimport { ListBoxOptionStatus } from \"../list-box/list-box\";\nimport { isFunction, set } from \"@/utils/nodash/fp\";\n\nexport function displayFilterItem({ display }: FilterItem, status: ListBoxOptionStatus) {\n  return <>{isFunction(display) ? display(status) : display}</>;\n}\n\n// Create onChange event from current <FilterBar /> state\nexport function filterChangeEvent(\n  filters: FilterItem[],\n  activeFilterKeys: string[],\n  activeFilterValues: FilterValuesRecord\n): FilterChangeEvent {\n  return activeFilterKeys.reduce((acc, key) => {\n    const filter = filters.find((item) => item.key === key) as FilterItem;\n    return {\n      ...acc,\n      [filter.key]: {\n        key: filter.key,\n        type: filter.type,\n        selected: filter.type === \"tag\" ? true : activeFilterValues[filter.key],\n        ...(filter.type === \"checkbox\" && filter.predicate\n          ? { predicate: filter.predicate }\n          : null),\n      },\n    };\n  }, {});\n}\n\n// Convert a FilterChangeEvent into FilterValuesRecord (setting default state)\nexport function filterChangeEventToValuesRecord(state: FilterChangeEvent): FilterValuesRecord {\n  return Object.keys(state).reduce((acc, key) => {\n    const filterState = state[key];\n    if (typeof filterState !== \"undefined\") {\n      const { type } = filterState;\n      if (type === \"tag\") {\n        return set(key, [], acc);\n      }\n      return set(key, filterState.selected, acc);\n    }\n    return acc;\n  }, {});\n}\n","import { faChevronDown, faTrash } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { DropdownMenuAction } from \"@/components/core/dropdown-action-menu\";\nimport { FilterOptionCheckbox, FilterValues } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { displayFilterItem } from \"@/components/core/filter-bar/filter-bar-utils\";\nimport { isString, orderBy } from \"@/utils/nodash\";\nimport { compact } from \"@/utils/nodash/fp\";\n\ntype FilterBarCheckboxPillProps = {\n  filter: FilterOptionCheckbox;\n  filterValues: FilterValues;\n  isOpen: boolean;\n  onChange: (key: string, isSelected: boolean) => void;\n  onRemove?: () => void;\n};\n\nconst buttonClassName =\n  \"ctw-flex ctw-items-center ctw-max-w-[15rem] ctw-space-x-2 ctw-capitalize ctw-text-content-black ctw-bg-bg-dark ctw-text-sm ctw-rounded ctw-py-2 ctw-px-3 ctw-relative ctw-cursor-pointer ctw-border-0 ctw-border-transparent ctw-whitespace-nowrap ctw-mb-2 ctw-mr-2\";\n\nexport function FilterBarCheckboxPill({\n  filter,\n  filterValues,\n  isOpen,\n  onRemove,\n  onChange,\n}: FilterBarCheckboxPillProps) {\n  const selected = filterValues ?? [];\n  const items = orderBy(\n    filter.values.map((item) => ({\n      key: isString(item) ? item : item.key,\n      name: isString(item) ? item : item.name,\n      display: isString(item) ? undefined : item.display,\n      isSelected: selected.includes(isString(item) ? item : item.key),\n    })),\n    [\"display\", \"name\"],\n    [\"asc\", \"asc\"],\n  );\n\n  const selectedItems = items\n    .filter((item) => item.isSelected)\n    .map((item) => item.display || item.name || item.key);\n\n  return (\n    <DropdownMenuAction\n      isOpen={isOpen}\n      items={items}\n      type=\"checkbox\"\n      pinnedActions={compact([\n        onRemove\n          ? {\n              icon: faTrash,\n              name: \"Remove Filter\",\n              action: onRemove,\n            }\n          : null,\n      ])}\n      buttonClassName={cx(filter.className, buttonClassName)}\n      onItemSelect={(item) => onChange(item.key, item.value)}\n    >\n      <div className=\"ctw-truncate ctw-font-medium ctw-text-content-black\">\n        {displayFilterItem(filter, { active: true })}\n        {selectedItems.length > 0 && (\n          <span className=\"ctw-font-normal\">: {selectedItems.join(\", \")}</span>\n        )}\n      </div>\n      <FontAwesomeIcon icon={faChevronDown} className=\"ctw-w-2\" />\n    </DropdownMenuAction>\n  );\n}\n","import { faCheck, faChevronDown, IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { Listbox } from \"@headlessui/react\";\nimport cx from \"classnames\";\nimport { forwardRef, Fragment, useEffect, useState } from \"react\";\nimport type { ReactNode, Ref } from \"react\";\nimport { MenuItem } from \"../menu/menu-item\";\nimport { FilterOptionSelect } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { isFunction } from \"@/utils/nodash\";\nimport \"./list-box.scss\";\n\ntype ListBoxItem = {\n  className?: cx.Argument;\n  divider?: false;\n  display: string | ((status: ListBoxOptionStatus) => ReactNode);\n  icon?: IconDefinition;\n  key: string;\n};\n\nexport type MinListBoxItem = ListBoxItem | { divider: true };\n\nexport type ListBoxProps = {\n  btnClassName?: cx.Argument;\n  children?: ReactNode;\n  className?: cx.Argument;\n  defaultIndex?: number;\n  selectedIndex?: number;\n  items: MinListBoxItem[];\n  onChange: (index: number, item: ListBoxItem) => void;\n  optionsClassName?: cx.Argument;\n  useBasicStyles?: boolean;\n};\n\nexport type ListBoxOptionStatus = {\n  active?: boolean;\n  filter?: FilterOptionSelect;\n  listView?: boolean;\n  selected?: boolean;\n};\n\nexport const ListBox = forwardRef(\n  (\n    {\n      useBasicStyles = false,\n      btnClassName,\n      children,\n      className,\n      optionsClassName,\n      items,\n      defaultIndex = 0,\n      selectedIndex,\n      onChange,\n    }: ListBoxProps,\n    ref: Ref<HTMLDivElement>,\n  ) => {\n    const [selectedTabIndex, setSelectedTabIndex] = useState(defaultIndex);\n    const selectedItem = items[selectedTabIndex] ?? {\n      display: \"Choose a selection\",\n    };\n\n    useEffect(() => {\n      if (selectedIndex === undefined) return;\n      setSelectedTabIndex(selectedIndex);\n    }, [selectedIndex]);\n\n    return (\n      <div className={cx(className, \"ctw-relative ctw-inline-block\")} ref={ref}>\n        <Listbox\n          value={selectedTabIndex}\n          onChange={(index: number) => {\n            const item = items[index];\n            if (item.divider) return;\n            onChange(index, item);\n            setSelectedTabIndex(index);\n          }}\n        >\n          <Listbox.Button\n            className={cx(\n              btnClassName,\n              !useBasicStyles && \"focus-visible:ctw-outline-primary-dark\",\n              \"ctw-relative ctw-cursor-pointer ctw-justify-between ctw-space-x-2 ctw-border-0 ctw-border-transparent\",\n            )}\n          >\n            {children || renderDisplay(selectedItem, { listView: false })}\n            {!useBasicStyles && <FontAwesomeIcon icon={faChevronDown} className=\"ctw-h-4\" />}\n          </Listbox.Button>\n          <Listbox.Options className={cx(optionsClassName, \"ctw-list-box\")}>\n            {items.map((item, index) => {\n              if (item.divider) {\n                return <div key=\"divider\" className=\"ctw-border-top\" />;\n              }\n\n              return (\n                <Listbox.Option key={item.key} value={index} as={Fragment}>\n                  {({ active, selected }) => (\n                    <li\n                      className={cx(\n                        \"ctw-flex ctw-cursor-pointer ctw-justify-between ctw-px-3 ctw-py-2\",\n                        \"hover:ctw-bg-bg-lighter\",\n                        item.className,\n                        {\n                          \"ctw-text-medium\": active || selected,\n                          \"ctw-text-content-black\": !(active || selected),\n                          \"ctw-bg-bg-lighter\": active,\n                        },\n                      )}\n                    >\n                      <span\n                        className={cx(\"ctw-inline-flex ctw-whitespace-nowrap ctw-align-middle\", {\n                          \"ctw-font-semibold\": selected && !useBasicStyles,\n                        })}\n                      >\n                        {renderDisplay(item, {\n                          active,\n                          selected,\n                          listView: true,\n                        })}\n                      </span>\n                      {!useBasicStyles && selected && !item.key.startsWith(\"_\") && (\n                        <span className=\"ctw-inline-flex ctw-pb-0.5\">\n                          <FontAwesomeIcon\n                            icon={faCheck}\n                            className=\"ctw-inline-block ctw-h-4 ctw-stroke-0 ctw-align-middle ctw-text-primary-dark\"\n                          />\n                        </span>\n                      )}\n                    </li>\n                  )}\n                </Listbox.Option>\n              );\n            })}\n          </Listbox.Options>\n        </Listbox>\n      </div>\n    );\n  },\n);\n\n// A helper function to render items for both the ListBox button and options.\nfunction renderDisplay<T extends MinListBoxItem>(item: T, status: ListBoxOptionStatus) {\n  if (item.divider) return null;\n  return (\n    <MenuItem icon={item.icon}>\n      {isFunction(item.display) ? item.display(status) : item.display}\n    </MenuItem>\n  );\n}\n","import { faTrash, IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport cx from \"classnames\";\nimport { ReactNode } from \"react\";\nimport { MenuItem } from \"../../menu/menu-item\";\nimport { FilterOptionSelect, FilterValues } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { ListBox, ListBoxOptionStatus } from \"@/components/core/list-box/list-box\";\nimport { isString } from \"@/utils/nodash\";\nimport { isFunction } from \"@/utils/nodash/fp\";\n\ntype FilterBarSelectPillProps = {\n  filter: FilterOptionSelect;\n  filterValues: FilterValues;\n  onChange: (key: string, isSelected: boolean) => void;\n  onRemove: () => void;\n};\n\nconst buttonClassName =\n  \"ctw-flex ctw-items-center ctw-capitalize ctw-text-content-black ctw-bg-bg-dark ctw-text-sm ctw-rounded ctw-py-2 ctw-px-3 ctw-relative ctw-cursor-pointer ctw-border-0 ctw-border-transparent ctw-whitespace-nowrap ctw-mb-2 ctw-mr-2\";\nconst renderDisplay = (display: string | ((status: ListBoxOptionStatus) => string | ReactNode)) =>\n  isFunction(display) ? display({ active: false }) : display;\nconst builtInButton = (name: string, key: string, icon: IconDefinition) => ({\n  key,\n  display: ({ listView, filter }: ListBoxOptionStatus) =>\n    listView ? <MenuItem icon={icon}>{name}</MenuItem> : filter && renderDisplay(filter.display),\n});\nconst removeButton = builtInButton(\"remove filter\", \"_remove\", faTrash);\n\nexport function FilterBarSelectPill({\n  filter,\n  filterValues,\n  onChange,\n  onRemove,\n}: FilterBarSelectPillProps) {\n  const filterNames = filter.values.map((value) => (isString(value) ? value : value.name)).sort();\n  const items = [...filterNames, removeButton];\n  const selectedIndex = typeof filterValues === \"string\" ? items.indexOf(filterValues) : -1;\n\n  return (\n    <ListBox\n      selectedIndex={selectedIndex}\n      defaultIndex={items.length - 1} // clear index\n      btnClassName={buttonClassName}\n      optionsClassName=\"ctw-capitalize\"\n      items={items.map((item) => ({\n        // eslint-disable-next-line react/no-unstable-nested-components\n        display: ({ listView }: ListBoxOptionStatus) => {\n          if (item === removeButton) {\n            return item.display({ listView, filter });\n          }\n          return listView ? (\n            <span className=\"ctw-whitespace-nowrap\">{item}</span>\n          ) : (\n            <div className=\"ctw-truncate ctw-font-medium ctw-text-content-black\">\n              {renderDisplay(filter.display)}\n              <span className=\"ctw-font-normal\">: {item}</span>\n            </div>\n          );\n        },\n        key: isString(item) ? item : item.key,\n        className: cx(\"ctw-capitalize\", {\n          \"ctw-border ctw-capitalize ctw-border-solid ctw-border-divider-light ctw-border-0 ctw-border-t\":\n            item === removeButton,\n        }),\n      }))}\n      onChange={(index, item) => {\n        if (item.key === \"_remove\") {\n          onRemove();\n        } else if (item.key === \"_reset\") {\n          onChange(\"\", false);\n        } else {\n          onChange(item.key, true);\n        }\n      }}\n    />\n  );\n}\n","import { faX } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { displayFilterItem } from \"@/components/core/filter-bar/filter-bar-utils\";\n\ntype FilterBarTagPillProps = {\n  filter: FilterItem;\n  onRemove: () => void;\n};\n\nconst buttonClassName =\n  \"ctw-flex ctw-items-center ctw-max-w-[15rem] ctw-capitalize ctw-text-content-black ctw-bg-bg-dark ctw-text-sm ctw-rounded ctw-py-2 ctw-px-3 ctw-relative ctw-cursor-pointer ctw-border-0 ctw-border-transparent ctw-whitespace-nowrap ctw-mb-2 ctw-mr-2\";\n\nexport function FilterBarTagPill({ filter, onRemove }: FilterBarTagPillProps) {\n  return (\n    <button\n      key={filter.key}\n      type=\"button\"\n      className={cx(buttonClassName, filter.className, \"ctw-space-x-2\")}\n      onClick={onRemove}\n    >\n      <div>{displayFilterItem(filter, { active: true })}</div>\n      <FontAwesomeIcon icon={faX} className=\"ctw-w-2 ctw-text-content-light\" />\n    </button>\n  );\n}\n","import type { FilterItem, FilterValues } from \"./filter-bar-types\";\nimport { FilterBarCheckboxPill } from \"./filter-bar-pills/checkbox-pill\";\nimport { FilterBarSelectPill } from \"./filter-bar-pills/select-pill\";\nimport { FilterBarTagPill } from \"./filter-bar-pills/tag-pill\";\n\ntype FilterBarPillProps = {\n  onRemove: (key: string) => void;\n  filter: FilterItem;\n  filterValues: FilterValues;\n  isOpen: boolean;\n  updateSelectedFilterValues: (valueKey: string, isSelected: boolean) => void;\n};\n\n/**\n * Filter pill component that can render any pill type. It abstracts the various\n * pill types (located in ./filter-bar-pills folder). In practice this component\n * will only be used by the FilterBar component.\n */\nexport function FilterBarPill({\n  onRemove,\n  filter,\n  filterValues,\n  isOpen,\n  updateSelectedFilterValues,\n}: FilterBarPillProps) {\n  const handleRemove = () => onRemove(filter.key);\n  switch (filter.type) {\n    case \"tag\":\n      return <FilterBarTagPill filter={filter} onRemove={handleRemove} />;\n    case \"select\":\n      return (\n        <FilterBarSelectPill\n          filter={filter}\n          filterValues={filterValues}\n          onRemove={handleRemove}\n          onChange={updateSelectedFilterValues}\n        />\n      );\n    case \"checkbox\":\n      return (\n        <FilterBarCheckboxPill\n          isOpen={isOpen}\n          filter={filter}\n          filterValues={filterValues}\n          onRemove={handleRemove}\n          onChange={updateSelectedFilterValues}\n        />\n      );\n    default:\n      throw new Error(\"ActiveFilterItem has invalid filter type\");\n  }\n}\n","import type { FilterBarProps, FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { faPlus, faRefresh, faTrash } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useEffect, useState } from \"react\";\nimport { filterChangeEvent, filterChangeEventToValuesRecord } from \"./filter-bar-utils\";\nimport { FilterBarPill } from \"@/components/core/filter-bar/filter-bar-pills\";\nimport { ListBox, MinListBoxItem } from \"@/components/core/list-box/list-box\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { omit, partition, uniq } from \"@/utils/nodash/fp\";\nimport { isEmptyValue } from \"@/utils/types\";\n\nconst INTERNAL_KEYS = [\"_remove\", \"_reset\"];\nconst removeInternalKeys = (keys: string[]) => keys.filter((key) => !INTERNAL_KEYS.includes(key));\n\n/**\n * FilterBar - A configurable filter bar with base menu and pills to control\n * which filters are active.\n *\n * Use the defaultState param to pre-set filters on mount.\n *\n * example:\n * ```\n * <FilterBar\n *   defaultState={{\n *     \"furry-things\": {\n *       type: \"checkbox\",\n *       selected: [\"cats\", \"dogs\", \"dice\"],\n *     },\n *    \"who-called-shotgun\": {\n *       type: \"select\",\n *       selected: \"Kristen\",\n *     },\n *     dismissed: {\n *       type: \"tag\",\n *       selected: true,\n *     },\n *   }}\n *   filters={filters}\n *   onChange={handleOnChange}\n * />\n * ```\n */\nexport const FilterBar = ({\n  className,\n  onChange,\n  filters,\n  defaultFilters = {},\n  selected,\n}: FilterBarProps) => {\n  const [recentlyAdded, setRecentlyAdded] = useState<string>();\n  const { trackInteraction } = useAnalytics();\n\n  useEffect(() => {\n    // Validating that the \"_remove\" filter is never passed in from parent\n    if (filters.some(({ key }) => INTERNAL_KEYS.includes(key))) {\n      throw new Error(`Filters should not use keys ${INTERNAL_KEYS.join(\", \")}`);\n    }\n  }, [filters]);\n\n  const activeFilterKeys = Object.keys(selected);\n  const activeFilterValues = filterChangeEventToValuesRecord(selected);\n\n  const clearAllFilters = () => {\n    onChange({});\n    trackInteraction(\"change_filter\", { action: \"clear\" });\n  };\n\n  const resetAllFilters = () => {\n    const initialState = filterChangeEventToValuesRecord(defaultFilters);\n    onChange(filterChangeEvent(filters, Object.keys(initialState), initialState));\n    trackInteraction(\"change_filter\", { action: \"reset\" });\n  };\n\n  // Add or remove a filter from the activated filters list\n  const toggleFilter = (key: string) => {\n    const remove = activeFilterKeys.includes(key);\n\n    if (!remove) {\n      setRecentlyAdded(key);\n    }\n    const updatedKeys = removeInternalKeys(\n      remove ? activeFilterKeys.filter((k) => k !== key) : uniq(activeFilterKeys.concat(key)),\n    );\n\n    // Finally we fire off a change event\n    onChange(filterChangeEvent(filters, updatedKeys, activeFilterValues));\n    trackInteraction(\"change_filter\", { action: remove ? \"deselect\" : \"select\", value: key });\n  };\n\n  // The update function for checkbox and select pills to call on change\n  const updateSelectedFilter = (key: string, valueKey: string, isSelected: boolean) => {\n    let activeValues;\n    const filter = filters.find((item) => item.key === key);\n    const values = activeFilterValues[key] ?? [];\n    if (isSelected) {\n      activeValues = {\n        ...activeFilterValues,\n        [key]: filter?.type === \"checkbox\" ? uniq(values.concat(valueKey)) : valueKey,\n      };\n    } else if (Array.isArray(values)) {\n      activeValues = {\n        ...activeFilterValues,\n        [key]: values.filter((k) => k !== valueKey),\n      };\n    } else {\n      // Edge case, if not selected and values not array, just remove key\n      activeValues = omit(key, activeFilterValues);\n    }\n    onChange(filterChangeEvent(filters, activeFilterKeys, activeValues));\n  };\n\n  const toFilterMenuItem = (filter: FilterItem): MinListBoxItem => {\n    const isActive = activeFilterKeys.includes(filter.key);\n    return {\n      display: isActive && filter.toggleDisplay ? filter.toggleDisplay : filter.display,\n      icon: isActive && filter.toggleIcon ? filter.toggleIcon : filter.icon,\n      key: filter.key,\n      className: cx(\"ctw-capitalize\", filter.className),\n    };\n  };\n\n  // Split the filters up by which are active (selected) or inactive (main menu)\n  const [activeFilters, inactiveFilters] = partition(\n    ({ key }) => activeFilterKeys.includes(key),\n    filters,\n  );\n\n  const activeFiltersWithToggle = activeFilters.filter((f) => f.toggleDisplay);\n\n  const [aboveDivider, belowDivider] = partition(\n    (filter) => !filter.belowDivider,\n    [...inactiveFilters, ...activeFiltersWithToggle],\n  );\n\n  if (!isEmptyValue(defaultFilters)) {\n    belowDivider.push({\n      display: \"reset filters\",\n      icon: faRefresh,\n      key: \"_reset\",\n      type: \"tag\",\n    });\n  }\n  belowDivider.push({\n    display: \"remove all filters\",\n    icon: faTrash,\n    key: \"_remove\",\n    type: \"tag\",\n  });\n\n  // Add a divider only if there are both items above\n  // and below the divider.\n  const maybeDivider: { divider: true }[] =\n    aboveDivider.length && belowDivider.length ? [{ divider: true }] : [];\n\n  const menuItems: MinListBoxItem[] = [\n    ...aboveDivider.map(toFilterMenuItem),\n    ...maybeDivider,\n    ...belowDivider.map(toFilterMenuItem),\n  ];\n\n  return (\n    <div\n      className={cx(\n        className,\n        \"ctw-items-left ctw-relative ctw-flex ctw-flex-col ctw-flex-wrap sm:ctw-flex-row sm:ctw-items-center\",\n      )}\n    >\n      {activeFilters.map((filter) => (\n        <FilterBarPill\n          isOpen={recentlyAdded === filter.key}\n          key={filter.key}\n          filter={filter}\n          filterValues={activeFilterValues[filter.key]}\n          onRemove={toggleFilter}\n          updateSelectedFilterValues={(valueKey: string, isSelected: boolean) =>\n            updateSelectedFilter(filter.key, valueKey, isSelected)\n          }\n        />\n      ))}\n\n      <ListBox\n        useBasicStyles\n        btnClassName=\"!ctw-text-content-light ctw-btn-clear !ctw-font-normal\"\n        // Add a right margin that's equal to the min-width of the dropdown-action-menu, minus the width of the \"add filters\" div (88px)\n        className=\"ctw-mr-[calc(15rem-88px)]\"\n        items={menuItems}\n        onChange={(_index, item) => {\n          switch (item.key) {\n            case \"_remove\":\n              return clearAllFilters();\n            case \"_reset\":\n              return resetAllFilters();\n            default:\n              return toggleFilter(item.key);\n          }\n        }}\n      >\n        {/* ctw-flex and ctw-items-center fixes a brief issue in CTW\n            where the icon is not inlined until the FontAwesome\n            styles load */}\n        <div className=\"ctw-mb-2 ctw-flex ctw-items-center ctw-space-x-1 ctw-p-2\">\n          <FontAwesomeIcon icon={faPlus} className=\"ctw-w-4\" />\n          <span>Add Filters</span>\n        </div>\n      </ListBox>\n    </div>\n  );\n};\n","import { faChevronDown } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useState } from \"react\";\nimport { DropdownMenuAction } from \"@/components/core/dropdown-action-menu\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { Sort } from \"@/utils/sort\";\n\nexport type SortOption<T extends object> = {\n  display: string;\n  sorts: Sort<T>[];\n};\n\nexport type SortButtonProps<T extends object> = {\n  className?: cx.Argument;\n  defaultSort: SortOption<T>;\n  onChange: (sort: SortOption<T>) => void;\n  options: SortOption<T>[];\n};\n\nexport const SortButton = <T extends object>({\n  className,\n  defaultSort,\n  onChange,\n  options,\n}: SortButtonProps<T>) => {\n  const [selected, setSelected] = useState<SortOption<T>>(defaultSort);\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <DropdownMenuAction\n      type=\"select\"\n      buttonClassName={cx(className, \"ctw-bg-transparent ctw-border-none ctw-p-0\")}\n      onItemSelect={(item) => {\n        const selectedOption = options.filter((option) => option.display === item.key)[0];\n        onChange(selectedOption);\n        trackInteraction(\"sort\", {\n          value: item.key,\n          dir: selectedOption.sorts[0].dir,\n        });\n        setSelected(selectedOption);\n      }}\n      items={options.map((option) => ({\n        key: option.display,\n        name: option.display,\n        isSelected: selected.display === option.display,\n      }))}\n    >\n      <div className=\"ctw-btn-default ctw-flex ctw-items-center ctw-space-x-2\">\n        <span className=\"ctw-mr-1.5 ctw-w-full\">\n          Sort: <span className=\"ctw-font-normal\">{selected.display}</span>\n        </span>\n        <FontAwesomeIcon icon={faChevronDown} className=\"ctw-ml-auto ctw-w-2\" />\n      </div>\n    </DropdownMenuAction>\n  );\n};\n","import cx from \"classnames\";\nimport { ReactNode } from \"react\";\nimport { ViewButton, ViewButtonProps } from \"./helpers/view-button\";\nimport { FilterBar } from \"@/components/core/filter-bar/filter-bar\";\nimport { FilterBarProps } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { SortButton, SortButtonProps } from \"@/components/core/sort-button/sort-button\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\n\nexport type ResourceTableActionsProps<T extends MinRecordItem> = {\n  action?: ReactNode;\n  className?: string;\n  filterOptions?: FilterBarProps;\n  sortOptions?: SortButtonProps<T>;\n  viewOptions?: ViewButtonProps<T>;\n};\n\nexport const ResourceTableActions = <T extends MinRecordItem>({\n  action,\n  className,\n  filterOptions,\n  sortOptions,\n  viewOptions,\n}: ResourceTableActionsProps<T>) => {\n  const isEmpty = !viewOptions && !sortOptions && !filterOptions && !action;\n  if (isEmpty) {\n    return null;\n  }\n\n  return (\n    <div\n      className={cx(\n        className,\n        \"ctw-flex ctw-flex-col-reverse ctw-items-start ctw-justify-items-end ctw-pt-2 sm:ctw-flex-row sm:ctw-pt-1.5\",\n      )}\n    >\n      <div className=\"ctw-flex ctw-w-full ctw-flex-col ctw-flex-wrap ctw-gap-x-2 sm:ctw-flex-row\">\n        {viewOptions && (\n          <ViewButton\n            className={cx(viewOptions.className, \"ctw-mb-2\")}\n            defaultView={viewOptions.defaultView}\n            onChange={viewOptions.onChange}\n            options={viewOptions.options}\n          />\n        )}\n        {sortOptions && (\n          <SortButton\n            className={cx(sortOptions.className, \"ctw-mb-2\")}\n            defaultSort={sortOptions.defaultSort}\n            onChange={sortOptions.onChange}\n            options={sortOptions.options}\n          />\n        )}\n        {filterOptions && filterOptions.filters.length > 0 && <FilterBar {...filterOptions} />}\n      </div>\n      <div className=\"ctw-mb-2 ctw-ml-0 ctw-w-full ctw-whitespace-nowrap ctw-px-2 sm:ctw-mb-0 sm:ctw-ml-auto sm:ctw-w-auto\">\n        {action}\n      </div>\n    </div>\n  );\n};\n","import cx from \"classnames\";\n\nexport type BadgeColor = \"primary\" | \"info\" | \"notification\";\n\nexport type BadgeProps = {\n  className?: string;\n  color: BadgeColor;\n  text: string;\n  size?: \"sm\" | \"xs\";\n  noFlex?: boolean;\n};\n\nexport const Badge = ({ className, color, text, noFlex = false, size = \"sm\" }: BadgeProps) => {\n  const colorClasses = {\n    primary: \"ctw-bg-primary-light ctw-text-primary-main\",\n    info: \"ctw-bg-info-light !ctw-text-info-text\",\n    notification: \"ctw-bg-notification-light ctw-text-notification-main\",\n  }[color];\n\n  const sizeClasses = {\n    xs: \"ctw-text-xs ctw-px-1.5 ctw-py-0.5\",\n    sm: \"ctw-text-xs ctw-px-2 ctw-leading-5\",\n  }[size];\n\n  return (\n    <span\n      className={cx(\n        className,\n        colorClasses,\n        sizeClasses,\n        \"ctw-rounded-full ctw-whitespace-nowrap !ctw-font-medium hover:!ctw-no-underline\",\n        !noFlex && \"ctw-inline-flex\",\n      )}\n    >\n      {text}\n    </span>\n  );\n};\n","import * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\nimport type { ReactNode } from \"react\";\nimport \"./tooltip.scss\";\n\ntype TooltipProps = {\n  children: ReactNode;\n  content?: string;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n};\n\nexport function Tooltip({\n  children,\n  content,\n  open,\n  defaultOpen,\n  onOpenChange,\n  ...props\n}: TooltipProps) {\n  if (!content) return <>{children}</>;\n\n  return (\n    // Wrap in parent div, this fixes issue where parent's\n    // may set space classes that would affect our position.\n    <div className=\"ctw-tooltip-wrapper\">\n      <TooltipPrimitive.Provider>\n        <TooltipPrimitive.Root\n          delayDuration={0}\n          open={open}\n          defaultOpen={defaultOpen}\n          onOpenChange={onOpenChange}\n        >\n          <TooltipPrimitive.Trigger asChild>\n            <div className=\"ctw-cursor-pointer ctw-inline\">{children}</div>\n          </TooltipPrimitive.Trigger>\n\n          <TooltipPrimitive.Content\n            side=\"bottom\"\n            align=\"center\"\n            className=\"ctw-max-w-[193px] ctw-rounded ctw-bg-icon-default ctw-p-2 ctw-text-sm ctw-text-center ctw-text-white ctw-TooltipContent\"\n            {...props}\n          >\n            {content}\n            <TooltipPrimitive.Arrow className=\"ctw-fill-icon-default\" />\n          </TooltipPrimitive.Content>\n        </TooltipPrimitive.Root>\n      </TooltipPrimitive.Provider>\n    </div>\n  );\n}\n","import { IconProp } from \"@fortawesome/fontawesome-svg-core\";\nimport { faCircleCheck } from \"@fortawesome/free-regular-svg-icons\";\nimport { faFileImage, faFileLines, faFilePdf } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useTelemetry } from \"../../../core/providers/telemetry/use-telemetry\";\nimport { Badge } from \"@/components/core/badge\";\nimport { Tooltip } from \"@/components/core/tooltip\";\n\nexport type ResourceTitleColumnProps = {\n  title?: string | JSX.Element;\n  subTitle?: string | JSX.Element;\n  capitalizeTitle?: boolean;\n  className?: string;\n  renderIcon?: React.ReactNode; // Function returning a React node\n};\n\nexport const ResourceTitleColumn = ({\n  title,\n  subTitle,\n  className,\n  renderIcon, // Add the renderIcon prop to be used within the component\n}: ResourceTitleColumnProps) => (\n  <div className={className}>\n    <div className=\"ctw-flex ctw-justify-between ctw-space-x-1.5\">\n      <div className=\"ctw-font-medium group-hover:ctw-underline\">{title}</div>\n      <div className=\"ctw-flex ctw-flex-nowrap ctw-space-x-2\">{renderIcon}</div>\n    </div>\n    {subTitle ? <div>{subTitle}</div> : null}\n  </div>\n);\n\n// The function to render the FontAwesome icon used for ownedByBuilder\nexport const RenderOwnedByBuilderIcon = (ownedByBuilder: boolean) =>\n  ownedByBuilder && (\n    <Tooltip content=\"Synced with record\">\n      <FontAwesomeIcon\n        className=\"ctw-text-content-light ctw-w-[14px] ctw-h-[14px]\"\n        icon={faCircleCheck}\n      />\n    </Tooltip>\n  );\n\n// The function to render the FontAwesome icon used for info badge\nexport const RenderInfoBadge = (infoBadge?: string, infoBadgeClassName?: string) =>\n  infoBadge && (\n    <div data-testid=\"indicator\" className={cx(infoBadgeClassName)}>\n      <Badge color=\"info\" text={infoBadge} size=\"xs\" noFlex />\n    </div>\n  );\n\nexport const RenderDocBadge = (contentType?: string) => {\n  const { Telemetry } = useTelemetry();\n  let icon: IconProp | undefined;\n  let toolTipText = \"\";\n\n  switch (contentType) {\n    case \"text/html\":\n    case \"application/xml\":\n      icon = faFileLines;\n      toolTipText = \"CDA Document\";\n      break;\n    case \"application/pdf\":\n      icon = faFilePdf;\n      toolTipText = \"PDF Document\";\n      break;\n    case \"image/png\":\n    case \"image/jpeg\":\n    case \"image/tiff\":\n      icon = faFileImage;\n      toolTipText = \"Image (PNG, JPG, TIFF)\";\n      break;\n    default:\n      icon = undefined; // No file icon if no specific type is matched\n      if (contentType) {\n        Telemetry.logger.warn(`No icon for content type: ${contentType}`);\n      }\n      break;\n  }\n\n  return (\n    icon && (\n      <Tooltip content={toolTipText}>\n        <FontAwesomeIcon className=\"ctw-text-content-light ctw-w-[14px] ctw-h-[14px]\" icon={icon} />\n      </Tooltip>\n    )\n  );\n};\n","import {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { AllergyModel } from \"@/fhir/models/allergies\";\nimport { capitalize } from \"@/utils/nodash\";\n\nexport const patientAllergiesColumns = (builderId: string) => {\n  const allergyColumns: TableColumn<AllergyModel>[] = [\n    {\n      title: \"Name\",\n      render: (allergy) => (\n        <ResourceTitleColumn\n          title={allergy.display}\n          renderIcon={RenderOwnedByBuilderIcon(allergy.ownedByBuilder(builderId))}\n        />\n      ),\n    },\n    {\n      title: \"Last Updated\",\n      render: (allergy) => (\n        <div>\n          <div>{allergy.recordedDate}</div>\n          <div>{allergy.patientOrganizationName}</div>\n        </div>\n      ),\n    },\n    {\n      title: \"Details\",\n      render: (allergy) => (\n        <div>\n          {!!allergy.manifestations && allergy.manifestations !== \"unknown\" && (\n            <div>Reaction: {capitalize(allergy.manifestations)}</div>\n          )}\n        </div>\n      ),\n    },\n  ];\n\n  return allergyColumns;\n};\n","export const RefreshIcon = ({ className }: { className?: string }) => (\n  <svg\n    width=\"60\"\n    height=\"60\"\n    viewBox=\"0 0 60 60\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      fillRule=\"evenodd\"\n      clipRule=\"evenodd\"\n      d=\"M26.75 8.5C15.0139 8.5 5.5 18.0139 5.5 29.75C5.5 41.486 15.0139 51 26.75 51C36.8532 51 45.3095 43.9493 47.4671 34.5H44.6876C43.6438 34.5 42.7098 33.8514 42.3451 32.8733C41.9805 31.8952 42.2619 30.7935 43.051 30.1102L49.1132 24.8602C50.0526 24.0466 51.447 24.0466 52.3864 24.8602L58.4486 30.1102C59.2377 30.7935 59.5191 31.8952 59.1545 32.8733C58.7898 33.8514 57.8558 34.5 56.812 34.5H53.0795C50.8381 47.0077 39.9026 56.5 26.75 56.5C11.9764 56.5 0 44.5236 0 29.75C0 14.9764 11.9764 3 26.75 3C33.9573 3 40.5038 5.85401 45.3115 10.4877C46.405 11.5417 46.4371 13.2826 45.3831 14.3761C44.3291 15.4697 42.5882 15.5017 41.4947 14.4478C37.6708 10.7622 32.4774 8.5 26.75 8.5Z\"\n      fill=\"#9CA3AF\"\n    />\n    <path\n      d=\"M26.25 16.75C27.6307 16.75 28.75 17.8693 28.75 19.25V29.7145L36.0178 36.9822C36.9941 37.9585 36.9941 39.5415 36.0178 40.5178C35.0415 41.4941 33.4585 41.4941 32.4822 40.5178L24.4822 32.5178C24.0134 32.0489 23.75 31.413 23.75 30.75V19.25C23.75 17.8693 24.8693 16.75 26.25 16.75Z\"\n      fill=\"#9CA3AF\"\n    />\n  </svg>\n);\n","import { z } from \"zod\";\n\n// Should match all valid formats.\n// See https://stackoverflow.com/a/56450924/1652396\nexport const phoneNumberRegex = /^(\\+\\d{1,2}\\s?)?1?-?\\.?\\s?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$/;\n\nexport const zipCodeRegex = /^\\d{5}(-\\d{4})?$/;\n\nexport function getStateEnum(requiredError: string) {\n  return z.enum(\n    [\n      \"AL\",\n      \"AK\",\n      \"AZ\",\n      \"AR\",\n      \"CA\",\n      \"CO\",\n      \"CT\",\n      \"DE\",\n      \"DC\",\n      \"FL\",\n      \"GA\",\n      \"HI\",\n      \"ID\",\n      \"IL\",\n      \"IN\",\n      \"IA\",\n      \"KS\",\n      \"KY\",\n      \"LA\",\n      \"ME\",\n      \"MD\",\n      \"MA\",\n      \"MI\",\n      \"MN\",\n      \"MS\",\n      \"MO\",\n      \"MT\",\n      \"NE\",\n      \"NV\",\n      \"NH\",\n      \"NJ\",\n      \"NM\",\n      \"NY\",\n      \"NC\",\n      \"ND\",\n      \"OH\",\n      \"OK\",\n      \"OR\",\n      \"PA\",\n      \"RI\",\n      \"SC\",\n      \"SD\",\n      \"TN\",\n      \"TX\",\n      \"UT\",\n      \"VT\",\n      \"VA\",\n      \"WA\",\n      \"WV\",\n      \"WI\",\n      \"WY\",\n    ],\n    { required_error: requiredError }\n  );\n}\n\nexport function stateCode(state?: string): string {\n  if (!state) return \"\";\n\n  const states: Record<string, string> = {\n    alabama: \"AL\",\n    alaska: \"AK\",\n    arizona: \"AZ\",\n    arkansas: \"AR\",\n    california: \"CA\",\n    colorado: \"CO\",\n    connecticut: \"CT\",\n    delaware: \"DE\",\n    florida: \"FL\",\n    georgia: \"GA\",\n    hawaii: \"HI\",\n    idaho: \"ID\",\n    illinois: \"IL\",\n    indiana: \"IN\",\n    iowa: \"IA\",\n    kansas: \"KS\",\n    kentucky: \"KY\",\n    louisiana: \"LA\",\n    maine: \"ME\",\n    maryland: \"MD\",\n    massachusetts: \"MA\",\n    michigan: \"MI\",\n    minnesota: \"MN\",\n    mississippi: \"MS\",\n    missouri: \"MO\",\n    montana: \"MT\",\n    nebraska: \"NE\",\n    nevada: \"NV\",\n    \"new hampshire\": \"NH\",\n    \"new jersey\": \"NJ\",\n    \"new mexico\": \"NM\",\n    \"new york\": \"NY\",\n    \"north carolina\": \"NC\",\n    \"north dakota\": \"ND\",\n    ohio: \"OH\",\n    oklahoma: \"OK\",\n    oregon: \"OR\",\n    pennsylvania: \"PA\",\n    \"rhode island\": \"RI\",\n    \"south carolina\": \"SC\",\n    \"south dakota\": \"SD\",\n    tennessee: \"TN\",\n    texas: \"TX\",\n    utah: \"UT\",\n    vermont: \"VT\",\n    virginia: \"VA\",\n    washington: \"WA\",\n    \"west virginia\": \"WV\",\n    wisconsin: \"WI\",\n    wyoming: \"WY\",\n  };\n\n  return states[state.toLowerCase()] || state.toUpperCase();\n}\n","import { z } from \"zod\";\nimport { getStateEnum, phoneNumberRegex, stateCode, zipCodeRegex } from \"./validations\";\nimport { FormEntry } from \"@/components/core/form/drawer-form-with-fields\";\nimport { PatientModel } from \"@/fhir/models\";\n\nexport const getRequestData = (\n  patient: PatientModel | undefined,\n  includePatientDemographicsForm: boolean\n): FormEntry[] => [\n  {\n    label: \"treating-provider\",\n    render: () => (\n      <div className=\"ctw-font-medium\">Who is the treating provider for this patient?</div>\n    ),\n  },\n  {\n    label: \"Practitioner Name\",\n    field: \"name\",\n    value: \"\",\n    readonly: false,\n  },\n  {\n    label: \"NPI\",\n    field: \"npi\",\n    value: \"\",\n    readonly: false,\n  },\n  [\n    {\n      label: \"Zus patient ID\",\n      hidden: true,\n      field: \"id\",\n      value: patient?.id ?? \"\",\n      readonly: true,\n    },\n    {\n      label: \"Role\",\n      field: \"role\",\n      value: \"Medical practitioner (SNOMED 158965000)\",\n      hidden: true,\n    },\n  ],\n  ...(!includePatientDemographicsForm\n    ? []\n    : [\n        {\n          label: \"patient-information\",\n          render: () => (\n            <div>\n              <div className=\"ctw-font-medium\">\n                Is the patient information below correct and up-to-date?\n              </div>\n              <div>Complete as many fields as possible to increase matching results.</div>\n            </div>\n          ),\n        },\n        {\n          label: \"First Name\",\n          field: \"firstName\",\n          value: patient?.firstName ?? \"\",\n          readonly: false,\n        },\n        {\n          label: \"Last Name\",\n          field: \"lastName\",\n          value: patient?.lastName ?? \"\",\n          readonly: false,\n        },\n        [\n          {\n            label: \"Date of Birth\",\n            field: \"dateOfBirth\",\n            value: patient?.dob ?? \"\",\n            readonly: false,\n          },\n          {\n            label: \"Gender\",\n            field: \"gender\",\n            value: patient?.gender ?? \"\",\n            readonly: false,\n          },\n        ],\n        {\n          label: \"Address\",\n          field: \"address\",\n          value: patient?.homeAddress?.line?.join(\", \") ?? \"\",\n          readonly: false,\n        },\n        {\n          label: \"City\",\n          field: \"city\",\n          value: patient?.homeAddress?.city ?? \"\",\n          readonly: false,\n        },\n        [\n          {\n            label: \"State\",\n            field: \"state\",\n            value: stateCode(patient?.homeAddress?.state),\n            readonly: false,\n          },\n          {\n            label: \"Zip\",\n            field: \"zipCode\",\n            value: patient?.homeAddress?.postalCode ?? \"\",\n            readonly: false,\n          },\n        ],\n        {\n          label: \"Phone\",\n          field: \"phone\",\n          value: patient?.phoneNumber ?? \"\",\n          readonly: false,\n        },\n        {\n          label: \"Email\",\n          field: \"email\",\n          value: patient?.email ?? \"\",\n          readonly: false,\n        },\n      ]),\n];\n\nexport const requestHistorySchema = z.object({\n  name: z.string({\n    required_error: \"Practitioner name must be specified.\",\n  }),\n  npi: z\n    .string({\n      required_error: \"NPI must be specified.\",\n    })\n    .length(10),\n  role: z.enum([\"Medical practitioner (SNOMED 158965000)\"]).optional(),\n  id: z.string().optional(), // patient id (hidden field on form)\n});\n\nexport const savePatientAndRequestHistorySchema = requestHistorySchema.merge(\n  z.object({\n    firstName: z.string({\n      required_error: \"First name must be specified.\",\n    }),\n    lastName: z.string({\n      required_error: \"Last name must be specified.\",\n    }),\n    dateOfBirth: z\n      .date()\n      .min(new Date(\"1900\"), { message: \"Date of birth is invalid.\" })\n      .max(new Date(), { message: \"Date of birth cannot be a future date.\" }),\n    gender: z.enum([\"-\", \"male\", \"female\", \"other\", \"unknown\"]),\n    address: z.string({\n      required_error: \"Address must be specified.\",\n    }),\n    city: z.string({\n      required_error: \"City must be specified.\",\n    }),\n    state: getStateEnum(\"State must be specified.\"),\n    zipCode: z\n      .string({\n        required_error: \"Zip code must be specified.\",\n      })\n      .regex(zipCodeRegex, {\n        message: \"Zip code is invalid.\",\n      }),\n    phone: z.string().regex(phoneNumberRegex, { message: \"Phone number is invalid.\" }).optional(),\n    email: z.string().email({ message: \"Email address is invalid.\" }).optional(),\n  })\n);\n","import cx from \"classnames\";\nimport { Spinner } from \"../../core/spinner\";\n\nexport type SaveButtonProps = {\n  submitting: boolean;\n};\n\nexport const SaveButton = ({ submitting }: SaveButtonProps) => (\n  <button\n    type=\"submit\"\n    disabled={submitting}\n    className={cx(\"ctw-btn-primary ctw-save-button ctw-w-28 ctw-whitespace-nowrap\")}\n  >\n    {submitting ? \"Saving...\" : \"Save\"}\n    {submitting && <Spinner className=\"ctw-ml-2 ctw-text-white\" />}\n  </button>\n);\n","import { OperationOutcomeModel } from \"..\";\nimport { FhirError, fhirErrorResponse, isFhirError } from \"@/fhir/errors\";\nimport { isOperationOutcome } from \"@/fhir/operation-outcome\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function isError(error: unknown): error is Error {\n  if (typeof error === \"object\" && error !== null) {\n    return \"message\" in error;\n  }\n  return false;\n}\n\nexport function errorMessage(error: unknown): string {\n  return isError(error) ? error.message.split(\":\")[0] : \"An unknown error occurred\";\n}\n\nexport const errorResponse = (title: string, e?: FhirError | Error | unknown) => {\n  if (isFhirError(e)) {\n    Telemetry.logFhirError(e, title);\n    throw fhirErrorResponse(title, e);\n  }\n\n  if (isError(e)) {\n    Telemetry.logError(e as Error, `${title}: ${e.message}`);\n    return { ...{ title }, ...{ statusText: e.message } };\n  }\n  Telemetry.logError(new Error(title));\n  return { title };\n};\n\nexport const getFormResponseErrors = (response: unknown) => {\n  let requestErrors: string[] = [];\n  let responseIsSuccess = true;\n\n  if (isFhirError(response) && isOperationOutcome(response.response.data)) {\n    requestErrors = new OperationOutcomeModel(response.response.data).issues\n      .filter((issue) => issue.severity !== \"warning\")\n      .map((issue) => issue.display);\n    responseIsSuccess = false;\n  } else if (response instanceof Error) {\n    requestErrors = [response.message];\n    responseIsSuccess = false;\n  }\n  return { requestErrors, responseIsSuccess };\n};\n","/* eslint-disable */\n/* Disabling eslint because we got this code from the remix helper and ported over to work in a SPA env. */\nimport { ActionReturn } from \"@/components/content/forms/types\";\nimport Zod, {\n  z,\n  ZodArray,\n  ZodBoolean,\n  ZodDate,\n  ZodDefault,\n  ZodEffects,\n  ZodEnum,\n  ZodLiteral,\n  ZodNativeEnum,\n  ZodNumber,\n  ZodObject,\n  ZodOptional,\n  ZodString,\n  ZodTypeAny,\n  ZodUnknown,\n} from \"zod\";\nimport { FormFieldOption, FormFieldType } from \"..\";\n\nexport type AnyZodSchema = Zod.AnyZodObject | ZodEffects<any, any, any>;\n\nexport function parseParams(o: any, schema: any, key: string, value: any) {\n  // find actual shape definition for this key\n  let shape = schema;\n\n  while (shape instanceof ZodObject || shape instanceof ZodEffects) {\n    shape =\n      shape instanceof ZodObject\n        ? shape.shape\n        : shape instanceof ZodEffects\n        ? shape._def.schema\n        : null;\n    if (shape === null) {\n      throw new Error(`Could not find shape for key ${key}`);\n    }\n  }\n\n  if (key.includes(\".\")) {\n    let [parentProp, ...rest] = key.split(\".\");\n    o[parentProp] = o[parentProp] ?? {};\n    parseParams(o[parentProp], shape[parentProp], rest.join(\".\"), value);\n    return;\n  }\n  if (key.includes(\"[]\")) {\n    key = key.replace(\"[]\", \"\");\n  }\n  const def = shape[key];\n  if (def) {\n    processDef(def, o, key, value as string);\n  }\n}\n\nexport function processDef(def: ZodTypeAny, o: any, key: string, value: string) {\n  let parsedValue: any;\n  if (def instanceof ZodString || def instanceof ZodLiteral) {\n    parsedValue = value;\n  } else if (def instanceof ZodNumber) {\n    const num = Number(value);\n    parsedValue = isNaN(num) ? value : num;\n  } else if (def instanceof ZodDate) {\n    const date = Date.parse(value);\n    parsedValue = isNaN(date) ? value : new Date(date);\n  } else if (def instanceof ZodBoolean) {\n    parsedValue = value === \"true\" ? true : value === \"false\" ? false : Boolean(value);\n  } else if (def instanceof ZodNativeEnum || def instanceof ZodEnum) {\n    parsedValue = value;\n  } else if (def instanceof ZodOptional || def instanceof ZodDefault) {\n    // def._def.innerType is the same as ZodOptional's .unwrap(), which unfortunately doesn't exist on ZodDefault\n    processDef(def._def.innerType, o, key, value);\n    // return here to prevent overwriting the result of the recursive call\n    return;\n  } else if (def instanceof ZodArray) {\n    if (o[key] === undefined) {\n      o[key] = [];\n    }\n    processDef(def.element, o, key, value);\n    // return here since recursive call will add to array\n    return;\n  } else if (def instanceof ZodEffects) {\n    processDef(def._def.schema, o, key, value);\n    return;\n  } else if (def instanceof ZodObject) {\n    const parsedJson = JSON.parse(value);\n    parsedValue = parsedJson;\n    Object.entries(def.shape).forEach(([key, _]) => {\n      if (!parsedValue[key]) {\n        delete parsedJson[key];\n      }\n    });\n  } else if (def instanceof ZodUnknown) {\n    parsedValue = JSON.parse(value);\n  } else {\n    throw new Error(`Unexpected type ${def._def.typeName} for key ${key}`);\n  }\n  if (Array.isArray(o[key])) {\n    o[key].push(parsedValue);\n  } else {\n    o[key] = parsedValue;\n  }\n}\n\nexport function isIterable(maybeIterable: unknown): maybeIterable is Iterable<unknown> {\n  return Symbol.iterator in Object(maybeIterable);\n}\n\nexport function getParamsInternal<T>(\n  params: URLSearchParams | FormData | Record<string, string | undefined>,\n  schema: any\n): ActionReturn<T> {\n  // @ts-ignore\n  let o: any = {};\n  let entries: [string, unknown][];\n  if (isIterable(params)) {\n    entries = Array.from(params);\n  } else {\n    entries = Object.entries(params);\n  }\n\n  for (const [key, value] of entries) {\n    // infer an empty param as if it wasn't defined in the first place\n    if (value === \"\") {\n      continue;\n    }\n    parseParams(o, schema, key, value);\n  }\n\n  const result = schema.safeParse(o);\n  if (result.success) {\n    return { success: true, data: result.data as T, errors: undefined };\n  }\n  const errors: { [key: string]: string[] } = {};\n\n  result.error.issues.forEach((issue: any) => {\n    const { message, path } = issue;\n    const key = path[0];\n    if (!errors.hasOwnProperty(key)) {\n      errors[key] = [message];\n    } else {\n      errors[key] = [...errors[key], message];\n    }\n  });\n\n  return { success: false, data: undefined, errors };\n}\n\nexport async function getFormData<T extends AnyZodSchema>(data: FormData, schema: T) {\n  type ParamsType = z.infer<T>;\n  return getParamsInternal<ParamsType>(data, schema);\n}\n\nfunction getOptions(\n  schema: Zod.AnyZodObject,\n  entry: Readonly<FormFieldType>\n): readonly FormFieldOption[] | undefined {\n  if (entry.options) {\n    return entry.options;\n  }\n\n  const zodField = schema.shape[entry.field];\n\n  return (zodField?.options || zodField?.unwrap?.().options)?.map((option: any) => ({\n    label: option,\n    value: option,\n  }));\n}\n\nexport const isOptional = (schema: Zod.AnyZodObject, field: string): boolean =>\n  schema.shape[field] instanceof Zod.ZodOptional;\n\nexport type InputPropType = {\n  name: string;\n  type: string;\n  required?: boolean;\n  \"aria-required\"?: boolean;\n  min?: number;\n  max?: number;\n  minLength?: number;\n  maxLength?: number;\n  options?: readonly FormFieldOption[] | undefined;\n};\n\nexport function useFormInputProps(zodThing: AnyZodSchema) {\n  const schema = zodThing instanceof ZodEffects ? zodThing._def.schema : zodThing;\n  const { shape } = schema;\n  return function (entry: Readonly<FormFieldType>, options: any = {}) {\n    const def = shape[entry.field];\n    if (!def) {\n      throw new Error(`no such key: ${entry.field}`);\n    }\n    return getInputProps(entry, schema, def);\n  };\n}\n\nexport function getInputProps(\n  entry: Readonly<FormFieldType>,\n  schema: any,\n  def: ZodTypeAny\n): InputPropType {\n  let type = \"text\";\n  let min;\n  let max;\n  let minLength;\n  let maxLength;\n  const options = getOptions(schema, entry);\n  if (def instanceof ZodString) {\n    if (def.isEmail) {\n      type = \"email\";\n    } else if (def.isURL) {\n      type = \"url\";\n    }\n    minLength = def.minLength ?? undefined;\n    maxLength = def.maxLength ?? undefined;\n\n    const check: any = def._def.checks.find((c) => c.kind === \"regex\");\n  } else if (def instanceof ZodNumber) {\n    type = \"number\";\n    min = def.minValue ?? undefined;\n    max = def.maxValue ?? undefined;\n  } else if (def instanceof ZodBoolean) {\n    type = \"checkbox\";\n  } else if (def instanceof ZodDate || def._def.innerType instanceof ZodDate) {\n    type = \"date\";\n  } else if (def instanceof ZodArray) {\n    return getInputProps(entry, schema, def.element);\n  }\n\n  const inputProps: InputPropType = {\n    name: entry.field,\n    type,\n    options,\n  };\n\n  if (!(def instanceof ZodOptional)) {\n    inputProps[\"aria-required\"] = true;\n  }\n  if (min) inputProps.min = min;\n  if (max) inputProps.max = max;\n  if (minLength && Number.isFinite(minLength)) inputProps.minLength = minLength;\n  if (maxLength && Number.isFinite(maxLength)) inputProps.maxLength = maxLength;\n  return inputProps;\n}\n","import { ReactNode, useState } from \"react\";\nimport { Drawer, DrawerProps } from \"../drawer\";\nimport { SaveButton } from \"@/components/content/forms/save-button\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { getFormResponseErrors } from \"@/utils/errors\";\nimport { AnyZodSchema, getFormData } from \"@/utils/form-helper\";\nimport { isEmpty } from \"@/utils/nodash\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport type FormErrors = Record<string, string[]>;\ntype InputError = Record<string, string[]>;\n\nexport type DrawerFormProps<T> = {\n  action: (data: T, getRequestContext: () => Promise<CTWRequestContext>) => Promise<unknown>;\n  schema: AnyZodSchema;\n  errorHeader?: string;\n  children: (submitting: boolean, errors?: FormErrors) => ReactNode;\n} & Omit<DrawerProps, \"children\">;\n\nexport const DrawerForm = <T,>({\n  action,\n  onClose,\n  children,\n  schema,\n  errorHeader = \"There was an error with your submission\",\n  ...drawerProps\n}: DrawerFormProps<T>) => {\n  const [isSubmitting, setIsSubmitting] = useState(false);\n  const [errors, setErrors] = useState<{\n    formErrors?: FormErrors;\n    requestErrors?: string[];\n  }>();\n  const { getRequestContext } = useCTW();\n  const { trackInteraction } = useAnalytics();\n\n  const reset = () => {\n    setErrors({});\n    setIsSubmitting(false);\n  };\n\n  const onFormSubmit = async (event: React.FormEvent) => {\n    event.preventDefault();\n    setErrors({});\n    setIsSubmitting(true);\n    const form = event.target;\n\n    const inputs = Array.from((event.target as HTMLElement).querySelectorAll(\"input\"));\n\n    const inputErrors: InputError = {};\n\n    inputs.forEach((input) => {\n      if (!input.checkValidity()) {\n        inputErrors[input.name] = [`The value is not valid for ${input.name}`];\n      }\n    });\n\n    if (!isEmpty(inputErrors)) {\n      setErrors({ formErrors: inputErrors });\n      setIsSubmitting(false);\n      return;\n    }\n\n    const data = new FormData(form as HTMLFormElement);\n\n    // Validation that occurs before the request.\n    const formResult = await getFormData(data, schema);\n    if (!formResult.success) {\n      // eslint-disable-next-line no-console\n      console.error(\"There was an error processing form data. formResult:\", formResult);\n      setErrors({\n        formErrors: formResult.errors,\n        requestErrors: undefined,\n      });\n      setIsSubmitting(false);\n      return;\n    }\n\n    let response;\n    let responseIsSuccess = true;\n    let requestErrors;\n    try {\n      response = await action(formResult.data, getRequestContext);\n    } catch (e) {\n      Telemetry.logError(e as Error);\n      responseIsSuccess = false;\n      requestErrors = [];\n    }\n\n    if (response) {\n      const formResponseErrors = getFormResponseErrors(response);\n      responseIsSuccess = formResponseErrors.responseIsSuccess;\n      requestErrors = formResponseErrors.requestErrors;\n    }\n\n    // Setting any errors from the response to the form.\n    if (!responseIsSuccess) {\n      setErrors({\n        formErrors: undefined,\n        requestErrors,\n      });\n      setIsSubmitting(false);\n    } else {\n      setIsSubmitting(false);\n      onClose();\n    }\n  };\n\n  return (\n    <Drawer {...drawerProps} onClose={onClose} onAfterClosed={reset} disableCloseOnBlur>\n      <form\n        className=\"ctw-flex ctw-h-full ctw-flex-col ctw-overflow-y-auto\"\n        onSubmit={(event) => {\n          void onFormSubmit(event);\n          trackInteraction(\"submit_form\");\n        }}\n        noValidate // Removes the browser tooltip functionality.\n      >\n        <Drawer.Body>\n          <div className=\"ctw-space-y-4\">\n            {errors?.requestErrors && (\n              <ErrorAlert header={errorHeader}>\n                {errors.requestErrors.length === 1 ? (\n                  errors.requestErrors[0]\n                ) : (\n                  <ul className=\"ctw-m-0 ctw-list-disc ctw-px-4\">\n                    {errors.requestErrors.map((error) => (\n                      <li>{error}</li>\n                    ))}\n                  </ul>\n                )}\n              </ErrorAlert>\n            )}\n            {children(isSubmitting, errors?.formErrors)}\n          </div>\n        </Drawer.Body>\n        <Drawer.Footer>\n          <div className=\"ctw-flex ctw-items-center ctw-justify-between\">\n            <Drawer.CloseButton label=\"Cancel\" onClose={onClose} />\n            <div className=\"ctw-flex ctw-items-center ctw-space-x-3\">\n              {(errors?.requestErrors || errors?.formErrors) && (\n                <div className=\"ctw-text-sm ctw-font-medium ctw-text-error-text\">\n                  There was an error with your submission\n                </div>\n              )}\n              <SaveButton submitting={isSubmitting} />\n            </div>\n          </div>\n        </Drawer.Footer>\n      </form>\n    </Drawer>\n  );\n};\n","import { ExclamationCircleIcon, LockClosedIcon } from \"@heroicons/react/solid\";\nimport cx from \"classnames\";\nimport type { InputHTMLAttributes } from \"react\";\nimport { FormFieldOption } from \"@/components/core/form/drawer-form-with-fields\";\nimport { formatDateLocalToISO } from \"@/fhir/formatters\";\nimport { startCase } from \"@/utils/nodash\";\n\nexport type FormFieldProps = {\n  errors?: string[];\n  options?: readonly FormFieldOption[];\n  lines?: number;\n  defaultValue?: string | string[];\n  readonly?: boolean;\n  render?: (\n    readonly: boolean | undefined,\n    props: InputHTMLAttributes<HTMLInputElement>\n  ) => JSX.Element;\n} & InputHTMLAttributes<HTMLInputElement> & { name: string };\n\nexport const FormField = ({\n  errors,\n  options,\n  lines,\n  defaultValue,\n  readonly,\n  hidden,\n  render,\n  ...inputProps\n}: FormFieldProps) => {\n  // We display dates in MM/DD/YYYY format, but date input fields\n  // expect it to be in YYYY-MM-DD format.\n\n  const value =\n    inputProps.type === \"date\" ? formatDateLocalToISO(defaultValue as string) : defaultValue;\n\n  const getFieldComponent = () => {\n    if (render) {\n      return render(readonly, { ...inputProps, defaultValue, hidden });\n    }\n\n    if (options) {\n      return (\n        <select\n          data-testid={`form-field-${inputProps.name}`}\n          className={cx({ \"ctw-error\": errors }, \"ctw-listbox-button ctw-w-full\")}\n          name={inputProps.name}\n          id={inputProps.name}\n          disabled={inputProps.disabled}\n          defaultValue={value}\n        >\n          {!options.some((option) => option.value === defaultValue) && (\n            <option value={defaultValue} disabled>\n              Select one\n            </option>\n          )}\n          {options.map((option) => (\n            <option value={option.value} key={option.value}>\n              {startCase(option.label)}\n            </option>\n          ))}\n        </select>\n      );\n    }\n    if (lines) {\n      return (\n        <textarea\n          data-testid={`form-field-${inputProps.name}`}\n          rows={lines}\n          className={cx(\n            { \"ctw-error\": errors },\n            \"ctw-listbox-textarea ctw-w-full ctw-whitespace-pre-wrap\"\n          )}\n          defaultValue={value}\n          disabled={inputProps.disabled}\n          readOnly={readonly}\n          name={inputProps.name}\n          id={inputProps.name}\n        />\n      );\n    }\n    return (\n      <input\n        data-testid={`form-field-${inputProps.name}`}\n        {...inputProps}\n        id={inputProps.name}\n        type={inputProps.type}\n        className={cx({ \"ctw-error\": errors }, \"ctw-listbox-input ctw-w-full\")}\n        readOnly={readonly}\n        // Only set defaultValue prop if there is a value.\n        // This fixes an issue where partially filled dates\n        // would get reset when saving and showing errors as the defaultValue could\n        // be undefined and the input gets reset to that (empty).\n        {...(value ? { defaultValue: value } : {})}\n      />\n    );\n  };\n\n  if (render && hidden) {\n    return render(readonly, {\n      ...inputProps,\n      defaultValue,\n      hidden,\n    });\n  }\n\n  if (hidden) {\n    return (\n      <input\n        data-testid={`form-field-${inputProps.name}`}\n        {...inputProps}\n        defaultValue={value}\n        hidden={hidden}\n      />\n    );\n  }\n\n  return (\n    <>\n      <div className=\"ctw-relative\">\n        {getFieldComponent()}\n        {readonly && (\n          <LockClosedIcon className=\"ctw-absolute ctw-right-3 ctw-top-1/2 ctw-h-4 ctw-w-4 ctw--translate-y-1/2 ctw-transform ctw-fill-content-lighter\" />\n        )}\n        {errors && (\n          <div className=\"ctw-pointer-events-none ctw-absolute ctw-right-0 ctw-top-2 ctw-pr-4\">\n            <ExclamationCircleIcon\n              className=\"ctw-h-5 ctw-w-5 ctw-text-error-main\"\n              aria-hidden=\"true\"\n            />\n          </div>\n        )}\n      </div>\n\n      {errors && (\n        <div className=\"ctw-text-xs ctw-italic ctw-text-error-text\">\n          {errors.length > 1\n            ? errors.map((error) => <div key={error}>&bull; {error}</div>)\n            : errors[0]}\n        </div>\n      )}\n    </>\n  );\n};\n","export const FormFieldLabel = ({\n  label,\n  required,\n  name,\n}: {\n  label: string;\n  name: string;\n  required: boolean | undefined;\n}) => (\n  <div className=\"ctw-flex ctw-items-center ctw-justify-between\">\n    <label htmlFor={name} className=\"ctw-capitalize\">\n      {label}\n    </label>\n    {!required && (\n      <span className=\"ctw-right-0 ctw-inline-block ctw-text-xs ctw-text-content-light\">\n        Optional\n      </span>\n    )}\n    {required && (\n      <>\n        <div className=\"ctw-flex-grow ctw-text-icon-default\">*</div>\n      </>\n    )}\n  </div>\n);\n","import cx from \"classnames\";\nimport { Fragment, InputHTMLAttributes, ReactNode } from \"react\";\nimport { DrawerForm, DrawerFormProps, FormErrors } from \"./drawer-form\";\nimport { FormField } from \"@/components/content/forms/form-field\";\nimport { FormFieldLabel } from \"@/components/content/forms/form-field-label\";\nimport { AnyZodSchema, InputPropType, useFormInputProps } from \"@/utils/form-helper\";\nimport { isArray } from \"@/utils/nodash\";\n\nexport interface FormFieldOption {\n  label: string;\n  value: string;\n}\n\nexport type FormFieldType = {\n  label: string;\n  field: string;\n  value?: string | string[];\n  lines?: number;\n  readonly?: boolean;\n  hidden?: boolean;\n  render?: (\n    readOnly: boolean | undefined,\n    inputProps: InputHTMLAttributes<HTMLInputElement>,\n  ) => JSX.Element;\n  options?: readonly FormFieldOption[];\n};\n\nexport type FormContentType = {\n  field?: never;\n  value?: never;\n  lines?: never;\n  readonly?: never;\n  hidden?: never;\n  render: () => JSX.Element;\n  label: string;\n};\n\nexport type FormEntry = FormFieldType | FormContentType | FormFieldType[];\n\nexport type DrawerFormWithFieldsProps<T> = {\n  title: string;\n  header?: ReactNode;\n  data?: FormEntry[];\n} & Pick<\n  DrawerFormProps<T>,\n  \"onClose\" | \"isOpen\" | \"action\" | \"schema\" | \"trackingMetadata\" | \"errorHeader\"\n>;\n\nexport const DrawerFormWithFields = <T,>({\n  title,\n  header,\n  data = [],\n  schema,\n  action,\n  ...drawerFormProps\n}: DrawerFormWithFieldsProps<T>) => {\n  const inputProps = useFormInputProps(schema);\n\n  return (\n    <DrawerForm title={title} action={action} schema={schema} {...drawerFormProps}>\n      {(submitting, errors) => (\n        <div className=\"ctw-space-y-4\">\n          {header}\n          <div className=\"ctw-space-y-6\">\n            {data.map((entry) => {\n              if (isArray(entry)) {\n                return (\n                  <FormFieldEntries\n                    recordList={entry}\n                    errors={errors}\n                    submitting={submitting}\n                    schema={schema}\n                    key={entry[0].label}\n                  />\n                );\n              }\n\n              const { label, field, value, lines, readonly, hidden, render } = entry;\n\n              if (!field) {\n                return <FormField key={label} readonly={readonly} render={render} name={label} />;\n              }\n\n              const props = inputProps(entry, schema);\n\n              if (hidden) {\n                return (\n                  <FormField\n                    {...props}\n                    key={label}\n                    lines={lines}\n                    disabled={submitting}\n                    readonly={readonly}\n                    defaultValue={value}\n                    errors={errors?.[field]}\n                    hidden={hidden}\n                    render={render}\n                  />\n                );\n              }\n\n              return (\n                <FormFieldEntry\n                  key={entry.label}\n                  entry={entry}\n                  errors={errors}\n                  props={props}\n                  submitting={submitting}\n                />\n              );\n            })}\n          </div>\n        </div>\n      )}\n    </DrawerForm>\n  );\n};\n\nexport type FormFieldEntries = {\n  recordList: FormFieldType[];\n  errors: FormErrors | undefined;\n  submitting: boolean;\n  schema: AnyZodSchema;\n};\n\nconst FormFieldEntries = ({ recordList, errors, submitting, schema }: FormFieldEntries) => {\n  const inputProps = useFormInputProps(schema);\n\n  return (\n    <div className=\"ctw-flex ctw-space-x-3\">\n      {recordList.map((record) => (\n        <Fragment key={record.label}>\n          <FormFieldEntry\n            entry={record}\n            props={inputProps(record, schema)}\n            submitting={submitting}\n            errors={errors}\n          />\n        </Fragment>\n      ))}\n    </div>\n  );\n};\n\nexport type FormFieldEntry = {\n  entry: FormFieldType;\n  errors: FormErrors | undefined;\n  props: InputPropType;\n  submitting: boolean;\n};\n\nconst FormFieldEntry = ({ entry, errors, props, submitting }: FormFieldEntry) => {\n  const { label, value, field, lines, readonly, hidden, render } = entry;\n  const fieldErrors = errors?.[field];\n\n  return (\n    <div\n      key={label}\n      className={cx({\n        \"ctw-flex ctw-grow ctw-basis-0 ctw-flex-col ctw-space-y-1.5 ctw-text-sm ctw-font-medium ctw-text-content-black\":\n          !hidden,\n      })}\n    >\n      {!hidden && (\n        <FormFieldLabel label={label} name={props.name} required={props[\"aria-required\"]} />\n      )}\n      <FormField\n        {...props}\n        key={label}\n        lines={lines}\n        disabled={submitting}\n        readonly={readonly}\n        defaultValue={value}\n        errors={fieldErrors}\n        hidden={hidden}\n        render={render}\n        data-zus-telemetry-focus={label}\n      />\n    </div>\n  );\n};\n","import { getZusApiBaseUrl } from \"./urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { ctwFetch } from \"@/utils/request\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport type PatientHistoryResponseError = {\n  // TODO: Can code be a list of status codes? Do we have that type defined anywhere.\n  code: number;\n  title: string;\n  details: string;\n};\n\nexport const schedulePatientHistory = async (\n  requestContext: CTWRequestContext,\n  resultData: { id: string; npi: string; role: string; name: string },\n) => {\n  const endpointUrl = `${getZusApiBaseUrl(\n    requestContext.env,\n    // If patientID is empty, just pass any non-identifying string in url.\n  )}/patient-history/jobs`;\n\n  const body = {\n    data: {\n      type: \"patient-history/jobs\",\n      attributes: {\n        requestConsent: true,\n        practitioner: {\n          npi: resultData.npi,\n          name: resultData.name,\n          role: resultData.role.toLocaleLowerCase(),\n        },\n      },\n      relationships: {\n        patient: {\n          data: { type: \"fhir/Patient\", id: resultData.id },\n        },\n      },\n    },\n  };\n\n  try {\n    const { data } = await ctwFetch(endpointUrl, {\n      method: \"POST\",\n      headers: {\n        Authorization: `Bearer ${requestContext.authToken}`,\n        ...(requestContext.contextBuilderId && {\n          \"Zus-Account\": requestContext.contextBuilderId,\n        }),\n      },\n      body: JSON.stringify(body),\n    });\n\n    return await data;\n  } catch (e) {\n    const err = e as Error;\n    const errorMessage = `Error requesting patient history.`;\n    Telemetry.logError(err, errorMessage);\n    return new Error(err.message);\n  }\n};\n","import { Dispatch, SetStateAction } from \"react\";\nimport { PatientFormData } from \"./forms/actions/patients\";\nimport {\n  getRequestData,\n  requestHistorySchema,\n  savePatientAndRequestHistorySchema,\n} from \"./forms/schemas/request-history-schema\";\nimport {\n  DrawerFormWithFields,\n  DrawerFormWithFieldsProps,\n} from \"../core/form/drawer-form-with-fields\";\nimport { CTWRequestContext } from \"../core/providers/ctw-context\";\nimport { useHandlePatientSave } from \"../core/providers/patient-provider\";\nimport { PatientHistoryResponseError, schedulePatientHistory } from \"@/api/patient-history\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { getFormResponseErrors } from \"@/utils/errors\";\nimport { QUERY_KEY_PATIENT_HISTORY_DETAILS } from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\ntype PatientHistoryRequestDrawer<T> = Pick<\n  DrawerFormWithFieldsProps<T>,\n  \"isOpen\" | \"onClose\" | \"header\"\n> & {\n  includePatientDemographicsForm?: boolean;\n  patient?: PatientModel;\n  setClinicalHistoryExists: Dispatch<SetStateAction<boolean | undefined>>;\n};\n\nexport type ScheduleHistoryFormData = {\n  npi: string;\n  name: string;\n  role: string;\n  id: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport const PatientHistoryRequestDrawer = <T,>({\n  patient,\n  header,\n  isOpen,\n  onClose,\n  setClinicalHistoryExists,\n  includePatientDemographicsForm = true,\n}: PatientHistoryRequestDrawer<T>) => {\n  const onPatientSave = useHandlePatientSave(patient);\n\n  const onScheduleHistory = async (\n    data: ScheduleHistoryFormData,\n    getRequestContext: () => Promise<CTWRequestContext>,\n  ) => {\n    const requestContext = await getRequestContext();\n    const patientHistoryResponse = await schedulePatientHistory(requestContext, data);\n\n    if (\"errors\" in patientHistoryResponse) {\n      const requestErrors = [\n        patientHistoryResponse.errors.map((err: PatientHistoryResponseError) => err.details),\n      ];\n      return new Error(requestErrors.join(\", \"));\n    }\n\n    await queryClient.invalidateQueries([QUERY_KEY_PATIENT_HISTORY_DETAILS]);\n\n    // patientHistoryResponse has succeeded at this point and should remove empty request history state.\n    setClinicalHistoryExists(true);\n\n    return patientHistoryResponse;\n  };\n\n  const onPatientSaveAndScheduleHistory = async (\n    data: PatientFormData & ScheduleHistoryFormData,\n    getRequestContext: () => Promise<CTWRequestContext>,\n  ) => {\n    try {\n      await onPatientSave(data);\n      return onScheduleHistory(data, getRequestContext);\n    } catch (e) {\n      const { requestErrors, responseIsSuccess } = getFormResponseErrors(e);\n      if (!responseIsSuccess) {\n        return new Error(requestErrors.join(\", \"));\n      }\n\n      Telemetry.logError(e as Error, \"Failed to save patient data\");\n      return new Error(\"Failed to save patient data\");\n    }\n  };\n\n  const action = includePatientDemographicsForm\n    ? onPatientSaveAndScheduleHistory\n    : onScheduleHistory;\n  const schema = includePatientDemographicsForm\n    ? savePatientAndRequestHistorySchema\n    : requestHistorySchema;\n\n  return (\n    <DrawerFormWithFields\n      header={header}\n      title=\"Request Records\"\n      errorHeader=\"Unable to request records\"\n      action={action}\n      data={getRequestData(patient, includePatientDemographicsForm)}\n      schema={schema}\n      isOpen={isOpen}\n      onClose={onClose}\n    />\n  );\n};\n","/* eslint-disable no-await-in-loop */\nimport { format } from \"date-fns\";\nimport { useEffect, useState } from \"react\";\nimport { PatientHistoryDetails } from \"./types\";\nimport { PatientHistoryRequestDrawer } from \"../patient-history-request-drawer\";\nimport { getZusServiceUrl } from \"@/api/urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useDrawer } from \"@/components/core/providers/drawer-provider\";\nimport {\n  usePatient,\n  usePatientPromise,\n  useTimingQueryWithPatient,\n} from \"@/components/core/providers/patient-provider\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { useBuilderPatientsByUPID } from \"@/fhir/patient-helper\";\nimport { PatientHistoryJobResponse } from \"@/services/patient-history/patient-history-types\";\nimport { hasUnexpiredToken } from \"@/utils/auth\";\nimport { omitBy } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_HISTORY_DETAILS } from \"@/utils/query-keys\";\nimport { ctwFetch } from \"@/utils/request\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientHistory(includePatientDemographicsForm?: boolean) {\n  const { openDrawer } = useDrawer();\n  const { getPatient } = usePatientPromise();\n  const details = usePatientHistoryDetails();\n\n  return {\n    openHistoryRequestDrawer: async () => {\n      let patient: PatientModel | undefined;\n      try {\n        patient = await getPatient();\n      } catch {\n        patient = undefined;\n      }\n      openDrawer({\n        component: (props) => (\n          <PatientHistoryRequestDrawer\n            includePatientDemographicsForm={includePatientDemographicsForm}\n            setClinicalHistoryExists={() => {}}\n            header={\n              <div className=\"ctw-pt-0 ctw-text-base\">\n                Request records from outside provider networks. To enable automatic updates, reach\n                out to your admin.\n              </div>\n            }\n            patient={patient}\n            {...props}\n          />\n        ),\n        trackingMetadata: { action: \"patient_history\" },\n      });\n    },\n    isLoading: details.isLoading,\n    isError: details.isError,\n    details: details.data ?? {},\n  };\n}\n\nexport type GetBuilderRefreshHistoryMessagesParams = {\n  requestContext: CTWRequestContext;\n  count?: number;\n  offset?: number;\n  patientId?: string;\n  status?: string;\n  excludeFutureJobs?: boolean;\n};\n\nexport async function getBuilderRefreshHistoryMessages({\n  requestContext,\n  count = 50,\n  offset = 0,\n  patientId,\n  status,\n  excludeFutureJobs,\n}: GetBuilderRefreshHistoryMessagesParams) {\n  const baseUrl = new URL(`${getZusServiceUrl(requestContext.env, \"patient-history\")}/jobs?`);\n\n  const paramsObj = omitBy(\n    {\n      \"page[count]\": String(count),\n      \"page[offset]\": String(offset * count),\n      \"filter[builder-id]\": requestContext.contextBuilderId\n        ? `${requestContext.contextBuilderId}`\n        : \"\",\n      \"filter[patient-id]\": patientId ? `${patientId}` : \"\",\n      \"filter[status]\": status ? `${status}` : \"\",\n      ...(!!excludeFutureJobs && { \"filter[targetDate][until]\": format(Date.now(), \"yyyy-MM-dd\") }),\n    },\n    (value) => !value,\n  );\n\n  const params = new URLSearchParams([...Object.entries(paramsObj)]).toString();\n  const endpointUrl = new URL(`${baseUrl}${decodeURIComponent(params)}`);\n\n  if (!hasUnexpiredToken(requestContext.authToken)) {\n    throw Error(\"Unable to make patient history request with expired token\");\n  }\n\n  const { data } = await ctwFetch(endpointUrl.href, {\n    headers: {\n      Authorization: `Bearer ${requestContext.authToken}`,\n      ...(requestContext.contextBuilderId && {\n        \"Zus-Account\": requestContext.contextBuilderId,\n      }),\n    },\n  });\n\n  return data;\n}\n\nasync function getPatientHistoryDetails(\n  requestContext: CTWRequestContext,\n  patients: PatientModel[],\n): Promise<PatientHistoryDetails> {\n  const details: PatientHistoryDetails = {};\n  const requests = patients.map(async ({ id }) =>\n    // iterate over each patient and get the patient history details\n    getBuilderRefreshHistoryMessages({\n      requestContext,\n      patientId: id,\n    }),\n  );\n  const responses = (await Promise.all(requests)) as PatientHistoryJobResponse[];\n\n  const jobs = responses.flatMap((response) => response.data);\n\n  jobs.forEach((job) => {\n    // This is necessary because targetDate was not introduced until May 2023 and it was not backfilled\n    const targetDate = new Date(\n      job.attributes.targetDate ?? Number(job.attributes.lastUpdatedAt) * 1000,\n    );\n    // eslint-disable-next-line default-case\n    switch (job.attributes.jobStatus) {\n      case \"queued\":\n      case \"scheduled\": {\n        if (!details.nextScheduledAt || targetDate < details.nextScheduledAt) {\n          details.nextScheduledAt = targetDate;\n        }\n        break;\n      }\n      case \"done\":\n      case \"error\": {\n        if (!details.latestCompleted || targetDate > details.latestCompleted.targetDate) {\n          details.latestCompleted = {\n            job,\n            targetDate,\n          };\n        }\n        break;\n      }\n      case \"in_progress\": {\n        if (!details.latestInProgress || targetDate > details.latestInProgress.targetDate) {\n          details.latestInProgress = {\n            job,\n            targetDate,\n          };\n        }\n        break;\n      }\n    }\n  });\n\n  return details;\n}\n\nexport function usePatientHistoryDetails() {\n  const patients = useBuilderPatientsByUPID();\n\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_HISTORY_DETAILS,\n    [patients.data],\n    async (requestContext: CTWRequestContext, patient: PatientModel) =>\n      getPatientHistoryDetails(requestContext, patients.data ?? [patient]),\n    !!patients.data,\n  );\n}\n\nexport function useIsFetchingHistory() {\n  const [isFetching, setIsFetching] = useState(true);\n  const [isPolling, setIsPolling] = useState(false);\n  const { getRequestContext } = useCTW();\n  const patient = usePatient();\n  useEffect(() => {\n    async function poll() {\n      if (patient.data && !isPolling) {\n        setIsPolling(true);\n        const requestContext = await getRequestContext();\n        await pollPatientHistory(requestContext, patient.data.id);\n        setIsFetching(false);\n      }\n    }\n    void poll();\n  }, [getRequestContext, patient, isPolling]);\n  return isFetching;\n}\n\nasync function pollPatientHistory(requestContext: CTWRequestContext, patientId: string) {\n  try {\n    let isDone = false;\n    do {\n      await sleep(1_000); // poll every 1 sec\n      const response = (await getBuilderRefreshHistoryMessages({\n        requestContext,\n        patientId,\n      })) as PatientHistoryJobResponse;\n\n      isDone = response.data[0]?.attributes.providers.every(\n        (provider) =>\n          provider.status === \"error\" ||\n          provider.status === \"done\" ||\n          provider.status === \"done_with_info\",\n      );\n    } while (!isDone);\n  } catch (e) {\n    Telemetry.logError(e as Error, \"Failed to poll for patient history details\");\n    throw new Error(`Failed fetching patient history details for patient: ${e}`);\n  }\n}\n\nfunction sleep(ms: number) {\n  return new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n}\n","import cx from \"classnames\";\nimport { usePatientHistory } from \"./use-patient-history\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\n\ntype RequestRecordsButtonProps = {\n  className?: cx.Argument;\n  includePatientDemographicsForm?: boolean;\n  displayText?: string;\n};\n\nexport const RequestRecordsButton = withErrorBoundary(\n  ({\n    className,\n    includePatientDemographicsForm,\n    displayText = \"Request Records\",\n  }: RequestRecordsButtonProps) => {\n    const { openHistoryRequestDrawer } = usePatientHistory(includePatientDemographicsForm);\n    const { trackInteraction } = useAnalytics();\n\n    return (\n      <button\n        type=\"button\"\n        // Add line-height (leading) to increase the clickable area.\n        className={cx(\"ctw-btn-clear ctw-link ctw-text-sm !ctw-leading-5\", className)}\n        onClick={() => {\n          void openHistoryRequestDrawer();\n          trackInteraction(\"request_records\");\n        }}\n      >\n        {displayText}\n      </button>\n    );\n  },\n  \"RequestRecordsButton\",\n  false,\n);\n","import { faInbox, faMagnifyingGlass } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { RefreshIcon } from \"./icons/refresh\";\nimport { LoadingTable } from \"./loading-table\";\nimport { useAnalytics } from \"./providers/analytics/use-analytics\";\nimport { usePatient } from \"./providers/patient-provider\";\nimport { Spinner } from \"./spinner\";\nimport { RequestRecordsButton } from \"../content/patient-history/request-records-button\";\nimport {\n  useIsFetchingHistory,\n  usePatientHistory,\n} from \"../content/patient-history/use-patient-history\";\nimport { formatISODateStringToDate } from \"@/fhir/formatters\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\n\nexport type EmptyTableProps = {\n  resourceName: string;\n  hasZeroFilteredRecords: boolean;\n};\n\nexport const EmptyPatientTable = (props: EmptyTableProps) => {\n  const patientHistory = usePatientHistory();\n  const patient = usePatient();\n  const showRequestRecordsFormToggle = useFeatureToggle(\"ctw-patient-history-form\").enabled;\n\n  if (patient.isLoading || patientHistory.isLoading) {\n    return <LoadingTable />;\n  }\n\n  const isTestPatient = !!patient.data?.isTestPatient;\n  const { latestInProgress, latestCompleted, nextScheduledAt } = patientHistory.details;\n\n  // If there was a previously completed or current in progress job, then we consider a request to have been made\n  const requestMade = !!latestCompleted || !!latestInProgress;\n\n  if (latestInProgress && !latestCompleted) {\n    return <EmptyTableFetchingHistory {...props} />;\n  }\n\n  if (isTestPatient && !requestMade) {\n    return (\n      <div className=\"ctw-text-center ctw-text-xl ctw-font-medium\">\n        This is a test patient with no records requested.\n      </div>\n    );\n  }\n\n  if (!requestMade) {\n    return (\n      <div className=\"ctw-space-y-3\">\n        <div className=\"ctw-space-y-6\">\n          <div className=\"ctw-flex ctw-justify-center\">\n            <RefreshIcon className=\"ctw-h-16 ctw-text-icon-light\" />\n          </div>\n          <div className=\"ctw-text-center ctw-text-xl ctw-font-medium\">\n            {nextScheduledAt\n              ? `Next scheduled request ${formatISODateStringToDate(nextScheduledAt.toISOString())}`\n              : \"Records not requested yet\"}\n          </div>\n        </div>\n        {showRequestRecordsFormToggle && (\n          <div className=\"ctw-flex ctw-justify-center\">\n            <RequestRecordsButton displayText=\"Request records now\" />\n          </div>\n        )}\n      </div>\n    );\n  }\n\n  return <EmptyTableNoneFound {...props} />;\n};\n\nexport function EmptyTableNoneFound({ resourceName, hasZeroFilteredRecords }: EmptyTableProps) {\n  let icon = faInbox;\n  let errorText = `No ${resourceName}`;\n  let subText = \"We didn't find any records for this patient.\";\n  const { trackInteraction } = useAnalytics();\n\n  trackInteraction(\"empty_table\");\n  if (hasZeroFilteredRecords) {\n    icon = faMagnifyingGlass;\n    errorText = `No matching ${resourceName} found`;\n    subText = \"Try changing the filters.\";\n  }\n  return (\n    <div className=\"ctw-space-y-3\">\n      <div className=\"ctw-space-y-6\">\n        <div className=\"ctw-flex ctw-justify-center\">\n          <FontAwesomeIcon icon={icon} className=\"ctw-h-16 ctw-text-icon-light\" />\n        </div>\n        <div className=\"ctw-text-center ctw-text-xl ctw-font-medium\">{errorText}</div>\n      </div>\n      <div className=\"ctw-text-center ctw-text-base ctw-font-normal\">{subText}</div>\n    </div>\n  );\n}\n\nfunction EmptyTableFetchingHistory(props: EmptyTableProps) {\n  const isLoadingPatientHistory = useIsFetchingHistory();\n  if (isLoadingPatientHistory) {\n    return (\n      <div className=\"ctw-space-y-3\">\n        <div className=\"ctw-space-y-6\">\n          <div className=\"ctw-flex ctw-justify-center\">\n            <Spinner className=\"ctw-h-12 ctw-w-12 ctw-text-icon-light\" />\n          </div>\n          <div className=\"ctw-text-center ctw-text-xl ctw-font-medium\">Retrieving records now</div>\n        </div>\n        <div className=\"ctw-text-center ctw-text-base ctw-font-normal\">\n          Check back in a few minutes.\n        </div>\n      </div>\n    );\n  }\n  return <EmptyTableNoneFound {...props} />;\n}\n","import { PropsWithChildren, useMemo } from \"react\";\nimport { AnalyticsContext } from \"./context\";\n\ntype TelemetryProviderProps = {\n  componentName?: string;\n};\n\nexport function AnalyticsProvider({\n  children,\n  componentName,\n}: PropsWithChildren<TelemetryProviderProps>) {\n  const contextValue = useMemo(\n    () => ({\n      componentName,\n    }),\n    [componentName]\n  );\n\n  return <AnalyticsContext.Provider value={contextValue}>{children}</AnalyticsContext.Provider>;\n}\n","import { AllergyModel } from \"@/fhir/models/allergies\";\nimport { orderBy, uniqBy } from \"@/utils/nodash\";\nimport { sort } from \"@/utils/sort\";\n\nexport const applyAllergyFilters = (allergyModel: AllergyModel[], builderId: string) => {\n  const sortedByDate = sort(allergyModel, \"recordedDate\", \"desc\", true);\n  // Bump builder owned allergies to the front, so uniqBy favors them!\n  const builderOwnedFirst = orderBy(sortedByDate, (a) => a.ownedByBuilder(builderId), \"desc\");\n  return uniqBy(builderOwnedFirst, \"lowercaseDisplay\");\n};\n","import { AllergyModel, PatientModel } from \"./models\";\nimport { applyAllergyFilters } from \"@/components/content/allergies/helpers/allergies-filter\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useTimingQueryWithPatient } from \"@/components/core/providers/patient-provider\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport { AllergyGraphqlResponse, allergyQuery } from \"@/services/fqs/queries/allergies\";\nimport { QUERY_KEY_PATIENT_ALLERGIES } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientAllergies(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_ALLERGIES,\n    [],\n    getAllergyIntoleranceFromFQS,\n    enabled,\n  );\n}\n\nasync function getAllergyIntoleranceFromFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<AllergyGraphqlResponse>(graphClient, allergyQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 1000,\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n    });\n    const models = data.AllergyIntoleranceConnection.edges.map(\n      (x) => new AllergyModel(x.node, undefined, x.node.BasicList),\n    );\n    const results = applyAllergyFilters(models, requestContext.builderId);\n    if (results.length === 0) {\n      Telemetry.countMetric(\"req.count.allergies.none\", 1);\n    }\n    Telemetry.histogramMetric(\"req.count.allergies\", results.length);\n    return results;\n  } catch (e) {\n    throw new Error(`Failed fetching allergies information for patient ${patient.UPID}`);\n  }\n}\n\nexport async function getAllergyIntolerancesById(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  ids: string[],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<AllergyGraphqlResponse>(graphClient, allergyQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 500,\n      filter: {\n        ids: {\n          anymatch: ids,\n        },\n      },\n      sort: {},\n    });\n    return data.AllergyIntoleranceConnection.edges.map((x) => new AllergyModel(x.node));\n  } catch (e) {\n    throw new Error(`Failed fetching allergies by ID for patient ${patient.UPID}`);\n  }\n}\n","import { Filter } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { compact, find, isArray, uniq } from \"@/utils/nodash/\";\n\nexport type FilterFunc<T extends object> = (data: T[]) => T[];\nexport type FilterEntry<T extends object> = Filter | FilterFunc<T>;\n\n// By default filters out entries with isHidden set to true\n// Unless showHidden filter is present.\nexport const filterHidden = <T extends object>(data: T[], filters?: (Filter | FilterFunc<T>)[]) => {\n  if (!filters) return data;\n\n  const filterItems = filters.filter((f) => typeof f !== \"function\") as Filter[];\n  const showHidden = find(filterItems, { key: \"showHidden\" })?.selected;\n\n  return data.filter((entry) => {\n    const isHidden = Boolean(entry[\"isHidden\" as keyof T]);\n\n    return showHidden || !isHidden;\n  });\n};\n\nexport const applyFilters = <T extends object>(data: T[], filters?: (Filter | FilterFunc<T>)[]) => {\n  if (!filters) return data;\n  const filterFuncs = filters.filter((f) => typeof f === \"function\") as FilterFunc<T>[];\n  const filterItems = filters.filter((f) => typeof f !== \"function\") as Filter[];\n\n  const filteredData = filterFuncs.reduce((acc, filterFunc) => filterFunc(acc), data);\n\n  return filteredData.filter((entry) =>\n    Object.entries(filterItems).every(([_, filterItem]) => {\n      const targetFilter = String(entry[filterItem.key as keyof T]);\n\n      switch (filterItem.type) {\n        case \"checkbox\":\n          if (isArray(filterItem.selected)) {\n            if (filterItem.predicate) {\n              if (filterItem.selected.length === 0) {\n                return true;\n              }\n              return filterItem.predicate(filterItem.selected, entry);\n            }\n            const filteredList = filterItem.selected.filter((item) =>\n              compact(uniq(data.map((c) => c[filterItem.key as keyof T]))).includes(\n                item as T[keyof T],\n              ),\n            );\n            return filteredList.includes(targetFilter);\n          }\n          break;\n        case \"select\":\n          return targetFilter === filterItem.selected;\n        case \"tag\":\n        default:\n      }\n      return true;\n    }),\n  );\n};\n\nexport function uniqueValues<T extends object>(data: T[], key: keyof T): string[] {\n  return compact(uniq(data.map((d) => String(d[key]))));\n}\n","export function saveToLocalStorage<T extends Record<string, unknown>>(\n  cacheKey: string | undefined,\n  data: T,\n) {\n  if (!cacheKey || typeof window === \"undefined\") {\n    return;\n  }\n\n  localStorage.setItem(cacheKey, JSON.stringify(data));\n}\n\nexport function getDefaultsFromLocalStorage<T extends Record<string, unknown>>(\n  cacheKey: string | undefined,\n  defaults: T,\n): T {\n  if (!cacheKey || typeof window === \"undefined\") {\n    return defaults;\n  }\n\n  const cache = localStorage.getItem(cacheKey);\n  if (!cache) {\n    return defaults;\n  }\n\n  try {\n    const cachedDefaults = JSON.parse(cache);\n    return { ...defaults, ...cachedDefaults };\n  } catch (e) {\n    return defaults;\n  }\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport { ViewOption } from \"@/components/content/resource/helpers/view-button\";\nimport {\n  FilterChangeEvent,\n  FilterOptionCheckbox,\n} from \"@/components/core/filter-bar/filter-bar-types\";\nimport { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { applyFilters, filterHidden } from \"@/utils/filters\";\nimport { getDefaultsFromLocalStorage, saveToLocalStorage } from \"@/utils/local-storage\";\nimport { compact } from \"@/utils/nodash\";\nimport { applySorts } from \"@/utils/sort\";\nimport { AllOrNone } from \"@/utils/types\";\n\nexport type PredicateMap = Record<string, FilterOptionCheckbox[\"predicate\"]>;\n\nexport type UseFilteredSortedDataProps<T extends object> = {\n  cacheKey?: string;\n  records?: T[];\n  defaultSort: SortOption<T>;\n  filterPredicates?: PredicateMap;\n  defaultFilters?: FilterChangeEvent;\n} & AllOrNone<{\n  defaultView: string;\n  viewOptions: ViewOption<T>[];\n}>;\n\n// Note: This hook all arguments except records are are stable and will not change.\n// This allows us to skip some of the dependencies in the useEffects.\nexport function useFilteredSortedData<T extends object>({\n  cacheKey,\n  filterPredicates,\n  defaultFilters: originalDefaultFilters,\n  defaultSort: originalDefaultSort,\n  defaultView: originalDefaultView,\n  viewOptions,\n  records,\n}: UseFilteredSortedDataProps<T>) {\n  const { defaultView, defaultSort, defaultFilters } = useMemo(\n    () => getDefaults(originalDefaultSort, cacheKey, originalDefaultView, originalDefaultFilters),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [],\n  );\n\n  const [viewOption, setViewOption] = useState(defaultView);\n  const [filters, setFilters] = useState(defaultFilters ?? {});\n  const [sortOption, setSortOption] = useState(defaultSort);\n  const [data, setData] = useState(records ?? []);\n\n  function setViewOptionCached(view: ViewOption<T>) {\n    setViewOption(view.display);\n    setDefaults(cacheKey, view.display, sortOption, filters);\n  }\n\n  function setFiltersCached(filters2: FilterChangeEvent) {\n    verifyFilter(filters2, filterPredicates);\n    setFilters(filters2);\n    setDefaults(cacheKey, viewOption, sortOption, filters2);\n  }\n\n  function setSortOptionCached(sort: SortOption<T>) {\n    setSortOption(sort);\n    setDefaults(cacheKey, viewOption, sort, filters);\n  }\n\n  useEffect(() => {\n    // First we filter out hidden records, then we apply the filters, followed last\n    // by filtering out the viewOptions. ViewOptions are last to support \"5 most recent\"\n    // vitals view.\n    const filterValues = fixupFilters(filters, filterPredicates);\n    let filteredData = filterHidden(records ?? [], filterValues);\n    filteredData = applyFilters(filteredData, filterValues);\n    const view = viewOptions?.find((option) => option.display === viewOption);\n    filteredData = applyFilters(filteredData, view?.filters ?? []);\n\n    const filteredAndSortedData = applySorts(filteredData, sortOption.sorts);\n    setData(filteredAndSortedData);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [filters, sortOption, records, viewOption]);\n\n  return {\n    setFilters: setFiltersCached,\n    setSort: setSortOptionCached,\n    defaultSort,\n    viewOption,\n    setViewOption: setViewOptionCached,\n    defaultView,\n    data,\n    filters,\n    sortOption,\n  };\n}\n\nfunction getDefaults<T extends object>(\n  defaultSort: SortOption<T>,\n  cacheKey?: string,\n  defaultView?: string,\n  defaultFilters?: FilterChangeEvent,\n): {\n  defaultView?: string;\n  defaultSort: SortOption<T>;\n  defaultFilters?: FilterChangeEvent;\n} {\n  const originals = { defaultView, defaultSort, defaultFilters };\n  return getDefaultsFromLocalStorage(cacheKey, originals);\n}\n\nfunction setDefaults<T extends object>(\n  cacheKey?: string,\n  defaultView?: string,\n  defaultSort?: SortOption<T>,\n  defaultFilters?: FilterChangeEvent,\n) {\n  saveToLocalStorage(cacheKey, { defaultView, defaultSort, defaultFilters });\n}\n\n// We need to fixup the filters to ensure that the predicate is set correctly.\n// Saving to cache drops predicates as they are functions (not serializeable).\n// So, we lookup the predicate from the filterPredicates map and set it on the filter.\nfunction fixupFilters(filters?: FilterChangeEvent, filterPredicates?: PredicateMap) {\n  const filterValues = compact(Object.values(filters ?? {}));\n  if (filters) {\n    filterValues.forEach((filter) => {\n      if (filter.type === \"checkbox\" && filterPredicates?.[filter.key]) {\n        // eslint-disable-next-line no-param-reassign\n        filter.predicate = filterPredicates[filter.key];\n      }\n    });\n  }\n\n  return filterValues;\n}\n\n// Throw a runtime error if we are filtering on a checkbox filter with a predicate\n// and that predicate is not in the filterPredicates map.\n// This error should help guard developers from setting up predicate based\n// filters without passing them in via filterPredicates.\n// This is needed to ensure cache works correctly with predicate based filters.\nfunction verifyFilter(filters2: FilterChangeEvent, filterPredicates?: PredicateMap) {\n  const values = compact(Object.values(filters2));\n  const missingPredicateMap = values\n    .filter((filter) => filter.type === \"checkbox\" && filter.predicate)\n    .filter((filter) => !filterPredicates?.[filter.key]);\n  if (missingPredicateMap.length > 0) {\n    throw new Error(\n      `Missing predicate map for filters: ${missingPredicateMap\n        .map((filter) => filter.key)\n        .join(\",\")}`,\n    );\n  }\n}\n","import cx from \"classnames\";\nimport { allergyFilter } from \"./helpers/filters\";\nimport { useAllergiesHistory } from \"./helpers/history\";\nimport { allergySortOptions, defaultAllergySort } from \"./helpers/sort\";\nimport { History } from \"../resource/helpers/history\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { useResourceDetailsDrawer } from \"../resource/resource-details-drawer\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { patientAllergiesColumns } from \"@/components/content/allergies/helpers/column\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientAllergies } from \"@/fhir/allergies\";\nimport { AllergyModel } from \"@/fhir/models/allergies\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { capitalize } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_ALLERGIES } from \"@/utils/query-keys\";\n\nexport type PatientAllergiesProps = {\n  className?: string;\n};\n\nexport const allergyHistory = (m: AllergyModel) => (\n  <History getHistory={useAllergiesHistory} model={m} />\n);\n\nfunction PatientAllergiesComponent({ className }: PatientAllergiesProps) {\n  const patientAllergiesQuery = usePatientAllergies();\n\n  const { data, filters, setFilters, setSort, defaultSort } = useFilteredSortedData({\n    cacheKey: \"patient-allergies\",\n    defaultSort: defaultAllergySort,\n    records: patientAllergiesQuery.data,\n  });\n\n  const userBuilderId = useUserBuilderId();\n  const isEmptyQuery = patientAllergiesQuery.data?.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openDetails = useResourceDetailsDrawer({\n    header: (m) => capitalize(m.display),\n    details: allergyData,\n    renderChild: allergyHistory,\n    getSourceDocument: true,\n    enableDismissAndReadActions: true,\n    queryKey: QUERY_KEY_PATIENT_ALLERGIES,\n  });\n\n  return (\n    <AnalyticsProvider componentName=\"PatientAllergies\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: allergyFilter(),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: allergySortOptions,\n            onChange: setSort,\n          }}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={patientAllergiesQuery.isLoading}\n          data={data}\n          columns={patientAllergiesColumns(userBuilderId)}\n          onRowClick={openDetails}\n          enableDismissAndReadActions\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"allergies\"\n            />\n          }\n          queryKey={QUERY_KEY_PATIENT_ALLERGIES}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientAllergies = withErrorBoundary(PatientAllergiesComponent, \"PatientAllergies\");\n\nexport const allergyData = (allergy: AllergyModel) => [\n  { label: \"Recorded Date\", value: allergy.recordedDate },\n  { label: \"Recording Organization\", value: allergy.patientOrganizationName },\n  { label: \"Status\", value: allergy.clinicalStatus },\n  { label: \"Type\", value: capitalize(allergy.type) },\n  { label: \"Onset\", value: allergy.onset },\n  { label: \"Reaction\", value: capitalize(allergy.manifestations) },\n  { label: \"Severity\", value: capitalize(allergy.severity) },\n  { label: \"Note\", value: allergy.note },\n];\n","import { Badge } from \"./badge\";\n\nexport type UnreadNotificationIconProps = {\n  className?: string;\n  text?: string;\n};\n\nexport const UnreadNotificationIcon = ({\n  className = \"ctw-fill-notification-icon\",\n  text,\n}: UnreadNotificationIconProps) =>\n  text ? (\n    <Badge text={text} className={className} color=\"notification\" />\n  ) : (\n    <svg height={10} className={className} viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n      <circle cx=\"5\" cy=\"5\" r=\"5\" />\n    </svg>\n  );\n","import { useUserBuilderId } from \"./providers/user-builder-id\";\nimport { UnreadNotificationIcon } from \"./unread-notification-icon\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\nexport type UnreadNotificationProps = {\n  className?: string;\n  data: FHIRModel<fhir4.Resource>[] | undefined;\n};\n\nexport const UnreadNotification = ({ className, data }: UnreadNotificationProps) => {\n  const userBuilderId = useUserBuilderId();\n\n  const unreadOutsideRecords =\n    data?.filter(\n      (record) => !record.isDismissed && !record.isRead && !record.ownedByBuilder(userBuilderId)\n    ) ?? [];\n\n  if (unreadOutsideRecords.length > 0) {\n    return <UnreadNotificationIcon className={className} />;\n  }\n  return null;\n};\n","import { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { usePatientAllergies } from \"@/fhir/allergies\";\n\nexport type UnreadAllergiesNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadAllergiesNotification = ({ className }: UnreadAllergiesNotificationProps) => {\n  const query = usePatientAllergies();\n  return <UnreadNotification className={className} data={query.data} />;\n};\n","import { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { CareTeamPractitionerModel } from \"@/fhir/models/careteam-practitioner\";\n\nexport const patientCareTeamColumns: TableColumn<CareTeamPractitionerModel>[] = [\n  {\n    widthPercent: 30,\n    minWidth: 150,\n    title: \"Provider\",\n    render: (careTeam) => (\n      <>\n        <div>{careTeam.practitionerName}</div>\n        <div>{careTeam.managingOrganization}</div>\n      </>\n    ),\n  },\n  {\n    widthPercent: 20,\n    minWidth: 150,\n    title: \"Role\",\n    render: (careTeam) => <div>{careTeam.role}</div>,\n  },\n  {\n    widthPercent: 30,\n    minWidth: 150,\n    title: \"Specialty\",\n    render: (careTeam) => <div>{careTeam.specialty}</div>,\n  },\n  {\n    widthPercent: 20,\n    minWidth: 150,\n    title: \"Last Updated\",\n    render: (careTeam) => <div>{careTeam.effectiveStartDate}</div>,\n  },\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { CareTeamPractitionerModel } from \"@/fhir/models/careteam-practitioner\";\n\nexport const careTeamSortOptions: SortOption<CareTeamPractitionerModel>[] = [\n  {\n    display: \"Provider (A-Z)\",\n    sorts: [{ key: \"practitionerName\", dir: \"asc\" }],\n  },\n  {\n    display: \"Provider (Z-A)\",\n    sorts: [{ key: \"practitionerName\", dir: \"desc\" }],\n  },\n  {\n    display: \"Last Updated (Old to New)\",\n    sorts: [\n      { key: \"effectiveStartDate\", dir: \"asc\", isDate: true },\n      { key: \"practitionerName\", dir: \"asc\" },\n    ],\n  },\n  {\n    display: \"Last Updated (New To Old)\",\n    sorts: [\n      { key: \"effectiveStartDate\", dir: \"desc\", isDate: true },\n      { key: \"practitionerName\", dir: \"asc\" },\n    ],\n  },\n];\n\nexport const defaultCareTeamSort = careTeamSortOptions[3];\n","import { differenceInDays } from \"date-fns\";\nimport { ViewOption } from \"./view-button\";\n\n// Return data within \"days\" or that don't have a date if allowNullDates is true.\nfunction dateFilter<T extends object>(field: keyof T, days: number, allowNullDates: boolean) {\n  return (data: T[]) => data.filter((d) => datePredicate(d, field, days, allowNullDates));\n}\n\nexport function datePredicate<T extends object>(\n  d: T,\n  field: keyof T,\n  days: number,\n  allowNullDates: boolean,\n): boolean {\n  return (\n    (allowNullDates && !d[field]) ||\n    differenceInDays(new Date(), new Date(String(d[field]))) <= days\n  );\n}\n\nexport function getDateRangeView<T extends object>(\n  field: Extract<keyof T, string>,\n  allowNullDates = true,\n) {\n  const viewOptions: ViewOption<T>[] = [\n    {\n      display: \"Past 7 days\",\n      filters: [dateFilter<T>(field, 7, allowNullDates)],\n    },\n    {\n      display: \"Past 30 days\",\n      filters: [dateFilter<T>(field, 30, allowNullDates)],\n    },\n    {\n      display: \"Past 3 months\",\n      filters: [dateFilter<T>(field, 90, allowNullDates)],\n    },\n    {\n      display: \"Past 6 months\",\n      filters: [dateFilter<T>(field, 180, allowNullDates)],\n    },\n    {\n      display: \"Past year\",\n      filters: [dateFilter<T>(field, 365, allowNullDates)],\n    },\n    {\n      display: \"All time\",\n      filters: [],\n    },\n  ];\n  return {\n    viewOptions,\n    past7days: viewOptions[0],\n    past30days: viewOptions[1],\n    past3months: viewOptions[2],\n    past6Months: viewOptions[3],\n    pastYear: viewOptions[4],\n    allTime: viewOptions[5],\n  };\n}\n","import { FHIRModel } from \"./fhir-model\";\nimport { PractitionerModel } from \"./practitioner\";\nimport { codeableConceptLabel } from \"../codeable-concept\";\nimport { formatDateISOToLocal, formatPhoneNumber } from \"../formatters\";\nimport { findReference } from \"../resource-helper\";\nimport { find } from \"@/utils/nodash\";\n\nexport class CareTeamModel extends FHIRModel<fhir4.CareTeam> {\n  kind = \"CareTeam\" as const;\n\n  get categoryDisplay() {\n    return codeableConceptLabel(this.resource.category ? this.resource.category[0] : undefined);\n  }\n\n  get status() {\n    return this.resource.status;\n  }\n\n  get periodStart() {\n    return formatDateISOToLocal(this.resource.period?.start);\n  }\n\n  get periodEnd() {\n    return this.resource.period?.end;\n  }\n\n  get particpants() {\n    return this.resource.participant;\n  }\n\n  get phone(): string | undefined {\n    const phone = this.resource.telecom?.find((t) => t.system === \"phone\");\n    return formatPhoneNumber(phone?.value);\n  }\n\n  get managingOrganization() {\n    return find(this.resource.participant, \"onBehalfOf\")?.onBehalfOf?.display;\n  }\n\n  get role() {\n    return codeableConceptLabel(this.resource.participant?.[0].role?.[0]);\n  }\n\n  get practitionerQualification() {\n    const reference = this.resource.participant?.[0]?.member;\n\n    const practitioner = findReference(\n      \"Practitioner\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n\n    if (practitioner) {\n      return codeableConceptLabel(\n        new PractitionerModel(practitioner).resource.qualification?.[0].code,\n      );\n    }\n    return undefined;\n  }\n\n  get title() {\n    return `${this.managingOrganization ?? \"Unknown\"} - ${this.role}`;\n  }\n\n  getPractitionerByID(reference: fhir4.Reference | undefined) {\n    return findReference(\n      \"Practitioner\",\n      this.resource.contained,\n      this.includedResources,\n      reference,\n    );\n  }\n}\n","import { CareTeamModel } from \"./careteam\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { PractitionerModel } from \"./practitioner\";\n\nexport class CareTeamPractitionerModel extends FHIRModel<fhir4.Practitioner> {\n  kind = \"CareTeamPractitioner\" as const;\n\n  constructor(careTeam: CareTeamModel, practitioner: fhir4.Practitioner) {\n    super(practitioner);\n    this.careTeam = careTeam;\n  }\n\n  careTeam: CareTeamModel;\n\n  get key() {\n    return `${this.careTeam.id}_${this.id}`;\n  }\n\n  get practitionerName() {\n    return new PractitionerModel(this.resource).fullName;\n  }\n\n  get effectiveStartDate() {\n    return this.careTeam.periodStart;\n  }\n\n  get managingOrganization() {\n    return this.careTeam.managingOrganization;\n  }\n\n  get role() {\n    return this.careTeam.role;\n  }\n\n  get specialty() {\n    return this.careTeam.practitionerQualification;\n  }\n\n  get status() {\n    return this.careTeam.status;\n  }\n\n  get title() {\n    return this.practitionerName;\n  }\n}\n","import { CareTeam } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentCoding, fragmentPractitioner } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface CareTeamConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<CareTeam>[];\n}\n\nexport interface CareTeamGraphqlResponse {\n  CareTeamConnection: CareTeamConnection;\n}\n\nexport const careTeamsQuery = gql`\n  ${fragmentCoding}\n  ${fragmentPractitioner}\n  query CareTeams($upid: ID!, $cursor: String!, $sort: CareTeamSortParams!, $first: Int!) {\n    CareTeamConnection(upid: $upid, after: $cursor, sort: $sort, first: $first) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          meta {\n            extension {\n              url\n              valueInstant\n            }\n            tag {\n              system\n              code\n            }\n            versionId\n          }\n          extension {\n            url\n            valueString\n          }\n          status\n          category {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          name\n          period {\n            start\n            end\n          }\n          participant {\n            role {\n              text\n              coding {\n                ...Coding\n              }\n            }\n            member {\n              reference\n              resource {\n                ...Practitioner\n              }\n            }\n            onBehalfOf {\n              reference\n            }\n          }\n          reasonCode {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          telecom {\n            system\n            value\n            use\n            period {\n              start\n              end\n            }\n          }\n          note {\n            text\n          }\n        }\n      }\n    }\n  }\n`;\n","import { CareTeamModel } from \"./models/careteam\";\nimport { CareTeamPractitionerModel } from \"./models/careteam-practitioner\";\nimport { CTWRequestContext, PatientModel, useTimingQueryWithPatient } from \"..\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport { CareTeamGraphqlResponse, careTeamsQuery } from \"@/services/fqs/queries/care-teams\";\nimport { isEqual, orderBy, uniqWith } from \"@/utils/nodash\";\nimport { QUERY_KEY_CARETEAM } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientCareTeamMembers() {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_CARETEAM,\n    [],\n    getCareTeamMembersFromFQS,\n  );\n}\n\nasync function getCareTeamMembersFromFQS(requestContext: CTWRequestContext, patient: PatientModel) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<CareTeamGraphqlResponse>(graphClient, careTeamsQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 1000,\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n    });\n\n    const nodes = data.CareTeamConnection.edges.map((x) => x.node);\n    const results = getFilteredCareTeamMembers(nodes);\n\n    if (results.length === 0) {\n      Telemetry.countMetric(\"req.count.care_teams.none\", 1);\n    }\n    Telemetry.histogramMetric(\"req.count.care_teams\", results.length);\n    return results;\n  } catch (e) {\n    throw new Error(`Failed fetching care teams information for patient: ${e}`);\n  }\n}\n\nexport const getFilteredCareTeamMembers = (data: fhir4.CareTeam[]) => {\n  const careTeams = data.map((careteam) => new CareTeamModel(careteam));\n\n  const careTeamMembers: CareTeamPractitionerModel[] = [];\n  careTeams.forEach(\n    (careTeam) =>\n      careTeam.resource.participant?.forEach((participant) => {\n        const practitioner = careTeam.getPractitionerByID(participant.member);\n        if (practitioner?.id && participant.member?.reference) {\n          careTeamMembers.push(new CareTeamPractitionerModel(careTeam, practitioner));\n        }\n      }),\n  );\n\n  const filteredCareTeamMembers = careTeamMembers.filter((ct) => ct.practitionerName);\n\n  const sortedCareTeamPractitionerModels = orderBy(\n    filteredCareTeamMembers,\n    [\"effectiveStartDate\", \"id\"],\n    [\"desc\", \"desc\"],\n  );\n\n  return uniqWith(sortedCareTeamPractitionerModels, (a, b) =>\n    isEqual(valuesToDedupeOn(a), valuesToDedupeOn(b)),\n  );\n};\n\nconst valuesToDedupeOn = (careTeam: CareTeamPractitionerModel) => [\n  careTeam.practitionerName.toLocaleUpperCase(),\n];\n","import cx from \"classnames\";\nimport { useRef } from \"react\";\nimport { patientCareTeamColumns } from \"./helpers/columns\";\nimport { careTeamSortOptions, defaultCareTeamSort } from \"./helpers/sorts\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { useResourceDetailsDrawer } from \"../resource/resource-details-drawer\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { usePatientCareTeamMembers } from \"@/fhir/care-team\";\nimport { CareTeamPractitionerModel } from \"@/fhir/models/careteam-practitioner\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_CARETEAM } from \"@/utils/query-keys\";\n\nexport type PatientCareTeamProps = {\n  className?: string;\n};\n\nexport type CareTeamDetailsDrawerProps = {\n  className?: string;\n  careteam: CareTeamPractitionerModel;\n  isOpen: boolean;\n  onClose: () => void;\n};\n\nexport function PatientCareTeam({ className }: PatientCareTeamProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n\n  const patientCareTeamQuery = usePatientCareTeamMembers();\n  const { viewOptions, allTime } =\n    getDateRangeView<CareTeamPractitionerModel>(\"effectiveStartDate\");\n\n  const { data, setSort, setViewOption, defaultSort, defaultView } = useFilteredSortedData({\n    cacheKey: \"patient-careteam\",\n    defaultSort: defaultCareTeamSort,\n    viewOptions,\n    records: patientCareTeamQuery.data,\n    defaultView: allTime.display,\n  });\n\n  const openDetails = useResourceDetailsDrawer({\n    header: (m) => m.practitionerName,\n    details: careTeamData,\n    queryKey: QUERY_KEY_CARETEAM,\n  });\n\n  const isEmptyQuery = patientCareTeamQuery.data && patientCareTeamQuery.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  return (\n    <AnalyticsProvider componentName=\"PatientCareTeam\">\n      <div ref={containerRef} className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          sortOptions={{\n            defaultSort,\n            options: careTeamSortOptions,\n            onChange: setSort,\n          }}\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n        />\n        <PatientResourceTable\n          isLoading={patientCareTeamQuery.isLoading}\n          data={data}\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"documents\"\n            />\n          }\n          columns={patientCareTeamColumns}\n          onRowClick={openDetails}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const careTeamData = (careTeamPractitioner: CareTeamPractitionerModel) => [\n  { label: \"Organization\", value: careTeamPractitioner.managingOrganization },\n  { label: \"Care Team\", value: careTeamPractitioner.careTeam.categoryDisplay },\n  { label: \"Phone\", value: careTeamPractitioner.careTeam.phone },\n  { label: \"Role\", value: careTeamPractitioner.role },\n  { label: \"Specialty\", value: careTeamPractitioner.specialty },\n  { label: \"Member Since\", value: careTeamPractitioner.effectiveStartDate },\n];\n","import { ConditionModel } from \"@/fhir/models/condition\";\n\ntype ConditionHeaderProp = {\n  condition: ConditionModel;\n};\n\nexport const ConditionHeader = ({ condition }: ConditionHeaderProp) => (\n  <div>\n    <div className=\"ctw-text-2xl\">\n      {condition.display} ({condition.preferredCoding?.code})\n    </div>\n    <div className=\"ctw-text-sm\">{condition.ccsChapter}</div>\n  </div>\n);\n","import { Combobox } from \"@headlessui/react\";\nimport { SearchIcon } from \"@heroicons/react/outline\";\nimport cx from \"classnames\";\nimport { ChangeEvent, Fragment, useMemo, useState } from \"react\";\nimport { debounce, isEmpty, isObject } from \"@/utils/nodash\";\nimport { isMouseEvent, VoidValue } from \"@/utils/types\";\n\nexport type ComboxboxFieldOption = {\n  value: unknown;\n  label: string;\n  key?: string;\n};\n\nexport type ComboboxFieldProps<T> = {\n  options: ComboxboxFieldOption[];\n  isLoading: boolean;\n  name: string;\n  defaultValue?: T;\n  defaultSearchTerm?: string;\n  onSearchChange: (searchTerm: string) => VoidValue;\n  readonly: boolean | undefined;\n  enableSearchIcon?: boolean;\n  onCustomSelectChange?: (e: unknown) => VoidValue;\n  renderCustomOption?: (e: unknown) => JSX.Element;\n  placeholder?: string;\n};\n\nexport const ComboboxField = <T,>({\n  options,\n  isLoading,\n  name,\n  defaultValue = {} as T,\n  defaultSearchTerm = \"\",\n  onSearchChange,\n  readonly,\n  enableSearchIcon = false,\n  onCustomSelectChange,\n  renderCustomOption,\n  placeholder = \"Type to search\",\n}: ComboboxFieldProps<T>) => {\n  const [searchTerm, setSearchTerm] = useState(defaultSearchTerm || \"\");\n  const [inputValue, setInputValue] = useState<unknown>({});\n  const inputState = isEmpty(inputValue) ? defaultValue : inputValue;\n\n  // Check if inputState is an object to determine if we should JSON.stringify.\n  const inputValueParsed = isObject(inputState) ? JSON.stringify(inputState) : inputState;\n\n  // Delay handle search input so that we don't fire a bunch of events until the user has had time to type.\n  const debouncedSearchInputChange = useMemo(() => {\n    const handleSearchInputChange = (e: ChangeEvent<HTMLInputElement>) => {\n      const newSearchTerm = e.target.value;\n      if (newSearchTerm.length > 1) {\n        void onSearchChange(newSearchTerm);\n      }\n\n      // Skip if search term has not changed.\n      if (newSearchTerm !== searchTerm) {\n        setSearchTerm(newSearchTerm);\n      }\n      if (options.filter((item) => item.label === newSearchTerm).length === 0) {\n        setInputValue({});\n      }\n    };\n\n    return debounce(handleSearchInputChange, 300);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [onSearchChange]);\n\n  const onSelectChange = (e: unknown) => {\n    const option = e as ComboxboxFieldOption;\n    setSearchTerm(option.label);\n    setInputValue(option.value);\n    void onCustomSelectChange?.(option.value);\n  };\n\n  return (\n    <Combobox onChange={onSelectChange} value={searchTerm} disabled={readonly}>\n      {({ open }) => (\n        <div className=\"ctw-relative ctw-text-left\">\n          <Combobox.Button\n            as=\"div\"\n            onClick={(e: unknown) => {\n              if (open || searchTerm.length === 0) {\n                if (isMouseEvent(e)) {\n                  e.preventDefault();\n                }\n              }\n            }}\n          >\n            <div className=\"ctw-relative\">\n              {enableSearchIcon && (\n                <div className=\"ctw-search-icon-wrapper\">\n                  <SearchIcon className=\"ctw-search-icon\" />\n                </div>\n              )}\n              <Combobox.Input\n                className={cx(`ctw-listbox-input ctw-w-full`, {\n                  \"ctw-pl-10\": enableSearchIcon,\n                })}\n                onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {\n                  if (e.key === \"Enter\" && (options.length === 0 || isLoading)) {\n                    e.preventDefault();\n                  }\n                }}\n                onChange={(e) => {\n                  // Due to debounce, we have to persist the event.\n                  // https://reactjs.org/docs/legacy-event-pooling.html\n                  e.persist();\n                  debouncedSearchInputChange(e);\n                }}\n                placeholder={placeholder}\n              />\n            </div>\n          </Combobox.Button>\n\n          <input hidden name={name} value={inputValueParsed as string} readOnly />\n          <Combobox.Options className=\"ctw-listbox ctw-absolute ctw-z-10 ctw-m-0 ctw-mt-1 ctw-max-h-60 ctw-w-full ctw-list-none ctw-overflow-auto ctw-rounded-md ctw-bg-white ctw-p-0 ctw-py-1 ctw-text-base ctw-shadow-lg ctw-ring-1 ctw-ring-opacity-5 focus:ctw-outline-none sm:ctw-text-sm\">\n            <ComboboxOptions\n              options={options}\n              query={searchTerm}\n              isLoading={isLoading}\n              renderCustomOption={renderCustomOption}\n            />\n          </Combobox.Options>\n        </div>\n      )}\n    </Combobox>\n  );\n};\n\ntype RenderCorrectOptionsProps = {\n  isLoading: boolean;\n  options: ComboxboxFieldOption[];\n  query: string;\n  renderCustomOption?: (e: unknown) => JSX.Element;\n};\n\nconst ComboboxOptions = ({\n  options,\n  query,\n  isLoading,\n  renderCustomOption,\n}: RenderCorrectOptionsProps) => {\n  if (query.length === 0) {\n    return <ComboboxOption option={{ value: \"\", label: \"Type to search\" }} />;\n  }\n\n  if (isLoading) {\n    return <ComboboxOption option={{ value: \"\", label: \"Loading...\" }} />;\n  }\n\n  if (query.length < 2) {\n    return <ComboboxOption option={{ value: \"\", label: \"Please type at least two characters\" }} />;\n  }\n\n  if (options.length === 0) {\n    return (\n      <ComboboxOption\n        option={{\n          value: ``,\n          label: `No results found for search term '${query}'`,\n        }}\n      />\n    );\n  }\n\n  return (\n    <>\n      {options.map((option, index) =>\n        renderCustomOption ? (\n          <Fragment key={option.key ?? `option-${index}`}>{renderCustomOption(option)} </Fragment>\n        ) : (\n          <ComboboxOption option={option} key={option.key ?? `option-${index}`} />\n        ),\n      )}\n    </>\n  );\n};\n\nconst ComboboxOption = ({ option }: { option: ComboxboxFieldOption }) => (\n  <Combobox.Option\n    value={option}\n    className={({ active }) =>\n      `ctw-relative ctw-cursor-default ctw-select-none ctw-py-2 ctw-pl-4 ctw-pr-4 ${\n        active ? \"ctw-bg-primary-light ctw-text-primary-dark\" : \"ctw-text-content-black\"\n      }`\n    }\n  >\n    {option.label}\n  </Combobox.Option>\n);\n","import { getFormsConditionsUrl } from \"./urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { ctwFetch } from \"@/utils/request\";\n\nexport const getAutoCompleteConditions = async (\n  requestContext: CTWRequestContext,\n  searchTerm: string,\n) => {\n  const { authToken, contextBuilderId } = requestContext;\n  const { data } = await ctwFetch(\n    `${getFormsConditionsUrl(requestContext.env)}?display=${searchTerm}`,\n    {\n      headers: {\n        Authorization: `Bearer ${authToken}`,\n        ...(contextBuilderId && { \"Zus-Account\": contextBuilderId }),\n      },\n    },\n  );\n  return data.conditionsList;\n};\n","import { InputHTMLAttributes, useState } from \"react\";\nimport { ComboboxField, ComboxboxFieldOption } from \"../../core/form/combobox-field\";\nimport { getAutoCompleteConditions } from \"@/api/autocomplete-conditions\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\n\nexport type AutoCompleteComboboxProps = {\n  defaultCoding?: fhir4.Coding;\n  readonly: boolean | undefined;\n} & InputHTMLAttributes<HTMLInputElement>;\n\nexport const ConditionsAutoComplete = ({\n  defaultCoding,\n  readonly,\n  ...inputProps\n}: AutoCompleteComboboxProps) => {\n  const { getRequestContext } = useCTW();\n  const [isLoading, setIsLoading] = useState(false);\n  const [options, setOptions] = useState<ComboxboxFieldOption[]>();\n\n  const handleSearchChange = async (query: string) => {\n    setIsLoading(true);\n    const requestContext = await getRequestContext();\n    const conditions = await getAutoCompleteConditions(requestContext, query);\n\n    if (conditions) {\n      setOptions(\n        conditions.map((item: fhir4.Coding) => ({\n          value: item,\n          label: item.display,\n        })) as ComboxboxFieldOption[],\n      );\n    }\n\n    setIsLoading(false);\n  };\n\n  return (\n    <ComboboxField\n      options={options || []}\n      isLoading={isLoading}\n      name={`${inputProps.name}`}\n      defaultSearchTerm={inputProps.defaultValue as string}\n      readonly={readonly}\n      onSearchChange={handleSearchChange}\n      defaultValue={defaultCoding}\n    />\n  );\n};\n","import type { FormEntry } from \"../../../core/form/drawer-form-with-fields\";\nimport Zod, { RefinementCtx, z } from \"zod\";\nimport { ConditionsAutoComplete } from \"../conditions-autocomplete\";\nimport { ConditionModel } from \"@/fhir/models/condition\";\nimport i18next from \"@/i18n\";\n\nexport const getAddConditionData = ({ condition }: { condition: ConditionModel }): FormEntry[] => [\n  {\n    label: i18next.t(\"glossary:condition_one\"),\n    field: \"condition\",\n    value: condition.display,\n    readonly: false,\n    render: (readonly: boolean | undefined, inputProps) => (\n      <ConditionsAutoComplete\n        readonly={readonly}\n        {...inputProps}\n        defaultCoding={condition.preferredCoding ?? {}}\n      />\n    ),\n  },\n  ...sharedFields(condition),\n];\n\nexport const getEditingPatientConditionData = ({\n  condition,\n}: {\n  condition: ConditionModel;\n}): FormEntry[] => [\n  {\n    label: \"id\",\n    value: condition.id,\n    field: \"id\",\n    readonly: true,\n    hidden: true,\n  },\n\n  ...sharedFields(condition),\n];\n\nconst sharedFields = (condition: ConditionModel) => [\n  {\n    label: \"subject\",\n    value: condition.subjectID,\n    field: \"subjectID\",\n    readonly: true,\n    hidden: true,\n  },\n  {\n    label: \"Status\",\n    value: condition.displayStatus === \"Unknown\" ? \"Select One\" : condition.displayStatus,\n    field: \"status\",\n  },\n  {\n    label: \"Type\",\n    value: condition.type,\n    field: \"type\",\n  },\n  {\n    label: \"Onset\",\n    value: condition.onset,\n    field: \"onset\",\n  },\n  {\n    label: \"Abatement\",\n    value: condition.abatement,\n    field: \"abatement\",\n  },\n  {\n    label: \"Note\",\n    value: condition.notes,\n    lines: 3,\n    field: \"note\",\n  },\n];\n\nconst conditionSchema = z.object({\n  id: z.string().optional(),\n  subjectID: z.string({\n    required_error: \"Condition subjectID must be specified.\",\n  }),\n  status: z.enum([\"Active\", \"Pending\", \"Inactive\", \"Refuted\", \"Entered In Error\"]),\n  type: z.enum([\"Chronic\", \"Acute\", \"Chronic and acute\", \"Unknown\"]),\n  onset: z.date().max(new Date(), { message: \"Onset cannot be a future date.\" }).optional(),\n  abatement: z.date().max(new Date(), { message: \"Abatement cannot be a future date.\" }).optional(),\n  note: z.string().optional(),\n});\n\nexport const conditionRefinement = (\n  condition: Zod.infer<typeof conditionSchema>,\n  ctx: RefinementCtx,\n) => {\n  if (condition.abatement && condition.status !== \"Inactive\") {\n    ctx.addIssue({\n      code: Zod.ZodIssueCode.custom,\n      message: \"Status must be inactive.\",\n      path: [\"abatement\"],\n    });\n  }\n  if (condition.abatement && condition.onset && condition.abatement < condition.onset) {\n    ctx.addIssue({\n      code: Zod.ZodIssueCode.custom,\n      message: \"Abatement date must be after onset date.\",\n      path: [\"abatement\"],\n    });\n  }\n};\n\nexport const conditionEditSchema = conditionSchema.superRefine((condition, refinementCtx) =>\n  conditionRefinement(condition, refinementCtx),\n);\n\nexport const conditionAddSchema = conditionSchema\n  .extend({\n    condition: z.object({\n      code: z.string({\n        required_error: \"Please choose a condition.\",\n      }),\n      // These are technically required but we mark them\n      // as optional to avoid duplicative error messages.\n      // The condition autocomplete will set us up so that\n      // all three of these values are set.\n      display: z.string().optional(),\n      system: z.string().optional(),\n    }),\n  })\n  .superRefine((condition, refinementCtx) => conditionRefinement(condition, refinementCtx));\n","import { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { ErrorAlert } from \"./alert\";\nimport { Modal, ModalProps } from \"./modal\";\nimport { Spinner } from \"./spinner\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useTelemetry } from \"@/components/core/providers/telemetry/use-telemetry\";\n\nexport type ModalConfirmDeleteProps = {\n  title: string;\n  resourceName: string;\n  onDelete: () => Promise<void>;\n  onClose: () => void;\n} & Omit<ModalProps, \"title\" | \"children\" | \"onAfterClosed\">;\n\nexport const ModalConfirmDelete = ({\n  title,\n  resourceName,\n  onDelete,\n  onClose,\n  ...modalProps\n}: ModalConfirmDeleteProps) => {\n  const [alert, setAlert] = useState<string>();\n  const [isDeleting, setIsDeleting] = useState(false);\n  const { t } = useTranslation();\n  const { trackInteraction } = useAnalytics();\n  const { Telemetry } = useTelemetry();\n\n  const onConfirm = async () => {\n    try {\n      setIsDeleting(true);\n      await onDelete();\n      setIsDeleting(false);\n      onClose();\n    } catch (e) {\n      Telemetry.logError(e as Error);\n      setIsDeleting(false);\n      setAlert(`Something went wrong. Please try again.`);\n      throw e;\n    }\n  };\n\n  return (\n    <Modal\n      onAfterClosed={() => setAlert(undefined)}\n      {...modalProps}\n      closeOnEscapeOrBackdrop={false}\n    >\n      {alert && <ErrorAlert header={alert} />}\n      <div className=\"ctw-items-left ctw-flex ctw-h-full ctw-flex-col ctw-space-y-2 ctw-overflow-y-auto\">\n        <span className=\"ctw-text-left ctw-text-lg ctw-font-medium ctw-text-content-black\">\n          {t(\"resource.remove.heading\", { resource: title, resourceName })}\n        </span>\n        <span className=\"ctw-subtext ctw-max-w-sm ctw-text-left ctw-text-content-light\">\n          {t(\"resource.remove.body\", { resource: title, resourceName })}\n        </span>\n      </div>\n      <div className=\"ctw-flex ctw-w-full ctw-space-x-4\">\n        <button\n          type=\"button\"\n          onClick={() => {\n            onClose();\n            trackInteraction(\"cancel_delete_request\");\n          }}\n          className=\"ctw-btn-default ctw-flex-1\"\n        >\n          Cancel\n        </button>\n        <button\n          type=\"button\"\n          disabled={isDeleting}\n          onClick={() => {\n            void onConfirm();\n            trackInteraction(\"confirm_delete_request\");\n          }}\n          className=\"ctw-btn-primary ctw-save-button ctw-flex-1\"\n        >\n          {isDeleting ? \"Removing...\" : \"Remove\"}\n          {isDeleting && <Spinner className=\"ctw-ml-2 ctw-text-white\" />}\n        </button>\n      </div>\n    </Modal>\n  );\n};\n","import { DomainResource } from \"fhir/r4\";\nimport { SYSTEM_ZUS_OWNER } from \"@/fhir/system-urls\";\nimport { filter, some } from \"@/utils/nodash\";\n\nexport const filterResourcesByBuilderId = <T extends DomainResource>(\n  resources: T[],\n  builderId: string\n) => filter(resources, (record) =>\n  some(record.meta?.tag, {\n    system: SYSTEM_ZUS_OWNER,\n    code: `builder/${builderId}`,\n  })\n);\n","import { isAfter, subYears } from \"date-fns\";\nimport { FhirResource } from \"fhir-kit-client\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { filterResourcesByBuilderId } from \"./common\";\nimport { PatientModel, useTimingQueryWithPatient } from \"..\";\nimport { getLensBuilderId } from \"@/api/urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { createOrEditFhirResource } from \"@/fhir/action-helper\";\nimport { ConditionModel } from \"@/fhir/models/condition\";\nimport {\n  SYSTEM_CONDITION_VERIFICATION_STATUS,\n  SYSTEM_SUMMARY,\n  SYSTEM_ZUS_OWNER,\n  SYSTEM_ZUS_THIRD_PARTY,\n} from \"@/fhir/system-urls\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport {\n  ConditionGraphqlResponse,\n  conditionsQuery,\n  ConditionWithBasics,\n} from \"@/services/fqs/queries/conditions\";\nimport { cloneDeep, orderBy } from \"@/utils/nodash\";\nimport {\n  QUERY_KEY_BUILDER_CONDITIONS,\n  QUERY_KEY_PATIENT_SUMMARY_CONDITIONS,\n} from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientBuilderConditions(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_BUILDER_CONDITIONS,\n    [],\n    fetchPatientBuilderConditionsFQS,\n    enabled,\n  );\n}\n\nfunction usePatientSummaryConditions(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_SUMMARY_CONDITIONS,\n    [],\n    fetchPatientSummaryConditionsFQS,\n    enabled,\n  );\n}\n\n// TODO - once Canvas is no longer using the Patient Conditions Outside component, we can remove this\nexport function usePatientConditionsOutside() {\n  const [conditions, setConditions] = useState<ConditionModel[]>([]);\n  const builderConditionsQuery = usePatientBuilderConditions();\n  const summaryConditionsQuery = usePatientSummaryConditions();\n\n  useEffect(() => {\n    const builderConditions = builderConditionsQuery.data ?? [];\n    const outsideConditions = filterOutsideConditions(\n      summaryConditionsQuery.data ?? [],\n      builderConditions,\n    );\n    setConditions(outsideConditions);\n  }, [builderConditionsQuery.data, summaryConditionsQuery.data]);\n\n  const isLoading = builderConditionsQuery.isLoading || summaryConditionsQuery.isLoading;\n  const isError = builderConditionsQuery.isError || summaryConditionsQuery.isError;\n  const isFetching = builderConditionsQuery.isFetching || summaryConditionsQuery.isFetching;\n\n  return {\n    isLoading,\n    isError,\n    isFetching,\n    data: conditions,\n  };\n}\n\n// Filter out conditions that we never want to display\nexport function filterUndesirableConditions(conditions: ConditionModel[]) {\n  const outdatedThreshold = subYears(new Date(), 5);\n\n  return conditions\n    .filter((condition) => ![\"FAC\", \"XXX\"].includes(condition.ccsChapterCode ?? \"\")) // Filter out summaries where CCS Category code starts with FAC or XXX.\n    .filter(\n      // Filter out low quality conditions\n      (condition) =>\n        condition.ccsChapterCode !== \"SYM\" ||\n        ![\"A\", \"U\", \"N\"].includes(condition.chronic?.code ?? \"\") ||\n        isAfter(new Date(condition.recordedDate ?? \"\"), outdatedThreshold),\n    );\n}\n\nexport function usePatientConditionsAll(enabled = true) {\n  const builderConditionsQuery = usePatientBuilderConditions(enabled);\n  const summaryConditionsQuery = usePatientSummaryConditions(enabled);\n\n  const conditions = useMemo(() => {\n    const summaries = associateSummaryWithBuilderConditions(\n      summaryConditionsQuery.data ?? [],\n      builderConditionsQuery.data ?? [],\n    );\n    return filterUndesirableConditions(summaries);\n  }, [builderConditionsQuery.data, summaryConditionsQuery.data]);\n\n  const isLoading = builderConditionsQuery.isLoading || summaryConditionsQuery.isLoading;\n  const isError = builderConditionsQuery.isError || summaryConditionsQuery.isError;\n  const isFetching = builderConditionsQuery.isFetching || summaryConditionsQuery.isFetching;\n\n  return {\n    isLoading,\n    isError,\n    isFetching,\n    data: conditions,\n  };\n}\n\nconst associateSummaryWithBuilderConditions = (\n  summaryConditions: ConditionModel[],\n  builderConditions: ConditionModel[],\n) => {\n  const summaries = cloneDeep(summaryConditions);\n\n  const builderConditionsById = builderConditions.reduce(\n    (acc, condition) => {\n      acc[condition.id] = condition;\n      return acc;\n    },\n    {} as Record<string, ConditionModel | undefined>,\n  );\n\n  summaries.forEach((summary) => {\n    const hasMatch =\n      // Check if aggregated from ids match any builder ids.\n      summary.aggregatedFromIds.some((id) => builderConditionsById[id]) ||\n      // Fallback to checking if any known codings match any builder conditions.\n      // This is useful for when a condition has been recently created but lens hasn't been\n      // updated yet.\n      builderConditions.some((builderCondition) => summary.knownCodingsMatch(builderCondition));\n    // eslint-disable-next-line no-param-reassign\n    summary.hasMatchingBuilderConditions = hasMatch;\n  });\n\n  return summaries;\n};\n\nfunction setupConditionModelsWithFQS(conditionResources: ConditionWithBasics[]): ConditionModel[] {\n  return conditionResources.map((c) => new ConditionModel(c, undefined, c.BasicList));\n}\n\nfunction filterAndSort(conditions: ConditionModel[]): ConditionModel[] {\n  return orderBy(\n    conditions.filter((condition) => condition.resource.asserter?.type !== \"Patient\"),\n    [\"resource.recordedDate\", \"display\"],\n    [\"desc\"],\n  );\n}\n\nexport const deleteCondition = async (\n  resource: fhir4.Condition,\n  requestContext: CTWRequestContext,\n) => {\n  if (!resource.id) {\n    throw new Error(\"Tried to edit a resource that hasn't been created yet.\");\n  }\n\n  const clonedResource = cloneDeep(resource);\n\n  clonedResource.verificationStatus = {\n    coding: [\n      {\n        code: \"entered-in-error\",\n        system: SYSTEM_CONDITION_VERIFICATION_STATUS,\n      },\n    ],\n  };\n  // We have to delete clinical status because it can't be present if verification is 'entered-in-error'\n  delete clonedResource.clinicalStatus;\n\n  const response = (await createOrEditFhirResource(\n    clonedResource,\n    requestContext,\n    new ConditionModel(clonedResource).title,\n  )) as FhirResource;\n\n  if (!response.id) {\n    Telemetry.reportActionFailure(\"delete_condition\");\n    throw new Error(`Failed to edit resource with id of ${resource.id}`);\n  } else {\n    Telemetry.reportActionSuccess(\"delete_condition\");\n  }\n\n  await queryClient.invalidateQueries([QUERY_KEY_BUILDER_CONDITIONS]);\n};\n\n// Filter out summary conditions so that they only include relevant outside conditions where:\n//  1. CCS Category code starts with FAC or XXX.\n//  2. There is an existing builder-owned condition with a matching known code\n//     AND (the outside condition is older than the builder condition OR they\n//     have the same status). That is - the builder already knows about this condition in its current state.\nexport const filterOutsideConditions = (\n  summaryConditions: ConditionModel[],\n  builderConditions: ConditionModel[],\n): ConditionModel[] =>\n  filterUndesirableConditions(summaryConditions).filter(\n    (outsideCondition) =>\n      !builderConditions.some((builderCondition) => {\n        const otherRecordedDate = outsideCondition.resource.recordedDate;\n        const patientRecordedDate = builderCondition.resource.recordedDate;\n        const isMatch = outsideCondition.knownCodingsMatch(builderCondition);\n        const isEnteredInError = builderCondition.verificationStatus === \"entered-in-error\";\n\n        const isOlder =\n          !otherRecordedDate || (patientRecordedDate && otherRecordedDate <= patientRecordedDate);\n        const hasSameStatus = outsideCondition.clinicalStatus === builderCondition.clinicalStatus;\n\n        return isMatch && !isEnteredInError && (isOlder || hasSameStatus);\n      }),\n  );\n\nasync function fetchPatientBuilderConditionsFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<ConditionGraphqlResponse>(graphClient, conditionsQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 1000,\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n      filter: {\n        tag: {\n          nonematch: [SYSTEM_SUMMARY, `${SYSTEM_ZUS_THIRD_PARTY}`],\n          // TODO: There's a bug in FQS that doesn't allow filtering with nonematch AND allmatch.\n          // Uncomment the line below once https://zeushealth.atlassian.net/browse/DRT-249 is resolved.\n          // allmatch: [`${SYSTEM_ZUS_OWNER}|builder/${requestContext.builderId}`],\n        },\n      },\n    });\n    let nodes = data.ConditionConnection.edges.map((x) => x.node);\n    // TODO: No longer needed once https://zeushealth.atlassian.net/browse/DRT-249 is resolved.\n    nodes = filterResourcesByBuilderId(\n      nodes,\n      requestContext.contextBuilderId || requestContext.builderId,\n    );\n    let conditions = setupConditionModelsWithFQS(nodes);\n    conditions = filterAndSort(conditions);\n    Telemetry.histogramMetric(`req.count.builder_conditions`, conditions.length);\n    return conditions;\n  } catch (e) {\n    throw Telemetry.logError(e as Error, `Failed fetching conditions for patient: ${patient.UPID}`);\n  }\n}\n\nexport async function fetchConditionsByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  ids: string[],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<ConditionGraphqlResponse>(graphClient, conditionsQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 500,\n      sort: {},\n      filter: {\n        ids: {\n          anymatch: ids,\n        },\n      },\n    });\n    const nodes = data.ConditionConnection.edges.map((x) => x.node);\n    return setupConditionModelsWithFQS(nodes);\n  } catch (e) {\n    throw Telemetry.logError(e as Error, `Failed fetching conditions for patient: ${patient.UPID}`);\n  }\n}\n\nasync function fetchPatientSummaryConditionsFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<ConditionGraphqlResponse>(graphClient, conditionsQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 1000,\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n      filter: {\n        tag: {\n          allmatch: [\n            SYSTEM_SUMMARY,\n            `${SYSTEM_ZUS_OWNER}|builder/${getLensBuilderId(requestContext.env)}`,\n          ],\n        },\n      },\n    });\n    const nodes = data.ConditionConnection.edges.map((x) => x.node);\n    const conditions = setupConditionModelsWithFQS(nodes);\n    const results = filterAndSort(conditions);\n    if (results.length === 0) {\n      Telemetry.countMetric(\"req.count.summary_conditions.none\", 1);\n    }\n    Telemetry.histogramMetric(\"req.count.summary_conditions\", results.length);\n    return results;\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching conditions outside for patient: ${patient.UPID}`,\n    );\n  }\n}\n","import { ConditionHeader } from \"./condition-header\";\nimport { createOrEditCondition, getAddConditionWithDefaults } from \"../../forms/actions/conditions\";\nimport {\n  conditionAddSchema,\n  conditionEditSchema,\n  getAddConditionData,\n  getEditingPatientConditionData,\n} from \"../../forms/schemas/condition-schema\";\nimport { DrawerFormWithFields } from \"@/components/core/form/drawer-form-with-fields\";\nimport { ModalConfirmDelete } from \"@/components/core/modal-confirm-delete\";\nimport { useDrawer } from \"@/components/core/providers/drawer-provider\";\nimport { useModal } from \"@/components/core/providers/modal-provider\";\nimport { usePatient } from \"@/components/core/providers/patient-provider\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { getNewCondition } from \"@/fhir/models/condition\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { deleteCondition } from \"@/services/conditions\";\nimport { curry } from \"@/utils/nodash\";\n\nexport function useAddConditionForm() {\n  const { t } = useBaseTranslations();\n  const { openDrawer } = useDrawer();\n  const patientResponse = usePatient();\n  const patientId = patientResponse.data?.id ?? \"\";\n\n  return (referenceCondition?: ConditionModel) => {\n    const condition = new ConditionModel(\n      referenceCondition\n        ? getAddConditionWithDefaults(referenceCondition.resource)\n        : getNewCondition(patientId),\n    );\n\n    openDrawer({\n      component: (props) => (\n        <DrawerFormWithFields\n          title={t(\"resource.add\", { resource: t(\"glossary:condition_one\") })}\n          schema={conditionAddSchema}\n          errorHeader=\"Unable to add condition to chart\"\n          action={curry(createOrEditCondition)(condition, patientId)}\n          data={getAddConditionData({ condition })}\n          trackingMetadata={{ action: \"create_resource\", resourceType: \"condition\" }}\n          {...props}\n        />\n      ),\n    });\n  };\n}\n\nexport function useEditConditionForm() {\n  const { t } = useBaseTranslations();\n  const { openDrawer } = useDrawer();\n  const patientResponse = usePatient();\n  const patientId = patientResponse.data?.id ?? \"\";\n\n  return (condition: ConditionModel) => {\n    openDrawer({\n      component: (props) => (\n        <DrawerFormWithFields\n          title={t(\"resource.edit\", { resource: t(\"glossary:condition_one\") })}\n          header={<ConditionHeader condition={condition} />}\n          schema={conditionEditSchema}\n          errorHeader=\"Unable to edit condition in chart\"\n          action={curry(createOrEditCondition)(condition, patientId)}\n          data={getEditingPatientConditionData({ condition })}\n          {...props}\n          trackingMetadata={{ action: \"edit_resource\", resourceType: \"condition\" }}\n        />\n      ),\n    });\n  };\n}\n\nexport function useConfirmDeleteCondition() {\n  const { t } = useBaseTranslations();\n  const { openModal } = useModal();\n  const { getRequestContext } = useCTW();\n\n  return (condition: ConditionModel, onDelete?: (condition: ConditionModel) => void) => {\n    const name =\n      condition.display ??\n      t(\"resource.unnamed\", {\n        resource: t(\"glossary:condition_one\"),\n      });\n\n    openModal({\n      component: (props) => (\n        <ModalConfirmDelete\n          title={t(\"glossary:condition_one\")}\n          resourceName={name}\n          onDelete={async () => {\n            const requestContext = await getRequestContext();\n            await deleteCondition(condition.resource, requestContext);\n            onDelete?.(condition);\n          }}\n          {...props}\n        />\n      ),\n    });\n  };\n}\n","import { faInfoCircle } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport {\n  RenderInfoBadge,\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { Tooltip } from \"@/components/core/tooltip\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nconst fixedColumns = \"ctw-w-[27rem] @[1024px]:ctw-w-[30rem] ctw-text-sm ctw-hidden -ctw-ml-2 \";\n\nexport const conditionsColumnGroupedClassNames = {\n  builderOwned: \"ctw-text-sm ctw-w-[1.5rem] ctw-max-w-[1.5rem] ctw-min-w-[1.5rem]\",\n  displayName: \"ctw-w-full ctw-flex-grow ctw-text-sm\",\n  latestDiagnosis: [fixedColumns, \"@[640px]:ctw-block @[640px]:ctw-ml-0\"],\n  onset: [fixedColumns, \"@[1024px]:ctw-block @[1024px]:ctw-ml-0\"],\n  type: [fixedColumns, \"ctw-text-ellipsis @[768px]:ctw-block @[768px]:ctw-ml-0\"],\n};\n\nexport const patientConditionsColumnsGrouped = [\n  {\n    className: conditionsColumnGroupedClassNames.builderOwned,\n  },\n  {\n    className: conditionsColumnGroupedClassNames.displayName,\n    title: \"Name\",\n  },\n  {\n    className: conditionsColumnGroupedClassNames.latestDiagnosis,\n    title: \"Latest Diagnosis\",\n  },\n  {\n    className: conditionsColumnGroupedClassNames.onset,\n    render: () => (\n      <div className=\"ctw-flex ctw-w-full ctw-justify-start ctw-space-x-2\">\n        <div>Onset Date</div>\n        <div className=\"ctw-flex-grow ctw-content-start\">\n          <Tooltip content=\"Earliest known onset or documented date\">\n            <FontAwesomeIcon\n              icon={faInfoCircle}\n              className=\"ctw-w-4 ctw-h-4 ctw-text-content-lighter\"\n            />\n          </Tooltip>\n        </div>\n      </div>\n    ),\n  },\n  {\n    className: conditionsColumnGroupedClassNames.type,\n    title: \"Type\",\n  },\n];\n\nexport const patientConditionsColumns: TableColumn<ConditionModel>[] = [\n  {\n    title: \"Name\",\n    widthPercent: 40,\n    minWidth: 320,\n    render: (condition) => (\n      <div>\n        <div className=\"ctw-font-medium group-hover:ctw-underline\">{condition.display}</div>\n        <div className=\"ctw-pc-chapter\">{condition.ccsChapter}</div>\n      </div>\n    ),\n  },\n  {\n    title: \"Last Updated\",\n    minWidth: 128,\n    render: (condition) => (\n      <div>\n        <div>{condition.recordedDate}</div>\n        <div>{condition.recorder}</div>\n      </div>\n    ),\n  },\n  {\n    title: \"Details\",\n    widthPercent: 40,\n    minWidth: 132,\n    render: (condition) => {\n      const onsetText = condition.isSummaryResource ? \"Earliest known onset:\" : \"Onset:\";\n\n      return (\n        <div className=\"ctw-pc-onset-notes\">\n          {condition.onset && (\n            <div>\n              {onsetText} {condition.onset}\n            </div>\n          )}\n          <div className=\"ctw-pc-notes\">{condition.notes.join(\" \")}</div>\n        </div>\n      );\n    },\n  },\n];\n\nexport const patientConditionsAllColumns = (): TableColumn<ConditionModel>[] => [\n  {\n    title: \"Name\",\n    widthPercent: 40,\n    minWidth: 320,\n    render: (condition) => (\n      <ResourceTitleColumn\n        title={condition.display}\n        subTitle={condition.ccsChapter}\n        renderIcon={\n          <>\n            {RenderInfoBadge(\n              !isEmpty(condition.hccEnrichment) ? \"HCC\" : undefined,\n              // ctw-mr-[3.75rem] ensures that the HCC indicator lines up to the right of where builder check mark would be\n              !condition.hasMatchingBuilderConditions ? \"ctw-mr-[3.75rem]\" : undefined,\n            )}\n            {RenderOwnedByBuilderIcon(condition.hasMatchingBuilderConditions)}\n          </>\n        }\n      />\n    ),\n  },\n  {\n    title: \"Last Updated\",\n    minWidth: 200,\n    render: (condition) => (\n      <div>\n        <div>{condition.recordedDate}</div>\n        <div>{condition.recorder}</div>\n      </div>\n    ),\n  },\n  {\n    title: \"Details\",\n    minWidth: 132,\n    render: (condition) => {\n      const onsetText = condition.isSummaryResource ? \"Earliest known onset:\" : \"Onset:\";\n\n      return (\n        <div className=\"ctw-pc-onset-notes\">\n          <div>Type: {condition.typeDisplay}</div>\n          {condition.onset && (\n            <div>\n              {onsetText} {condition.onset}\n            </div>\n          )}\n          <div className=\"ctw-pc-notes\">{condition.notes.join(\" \")}</div>\n        </div>\n      );\n    },\n  },\n];\n","type NotesListProps = {\n  notes: string[];\n};\n\nexport const NotesList = ({ notes }: NotesListProps) => (\n  <div className=\"ctw-flex ctw-flex-col ctw-space-y-4\">\n    {notes.map((note, i) => (\n      // eslint-disable-next-line react/no-array-index-key\n      <div key={note + i}>\n        <div>{note}</div>\n      </div>\n    ))}\n  </div>\n);\n","import { HistoryEntryProps } from \"../../resource/helpers/history-entry\";\nimport { useHistory } from \"../../resource/history\";\nimport { NotesList } from \"@/components/core/notes-list\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { capitalize, startCase } from \"@/utils/nodash\";\nimport { QUERY_KEY_CONDITION_HISTORY } from \"@/utils/query-keys\";\n\nexport function useConditionHistory(condition: ConditionModel) {\n  return useHistory({\n    resourceType: \"Condition\",\n    model: condition,\n    queryKey: QUERY_KEY_CONDITION_HISTORY,\n    valuesToDedupeOn,\n    getFiltersFQS,\n    getHistoryEntry,\n  });\n}\n\nfunction getFiltersFQS(condition: ConditionModel) {\n  const tokens = condition.knownCodings.map((coding) => `${coding.system}|${coding.code}`);\n\n  if (tokens.length > 0) {\n    return {\n      code: { anymatch: tokens },\n    };\n  }\n\n  return undefined;\n}\n\nfunction getHistoryEntry(condition: ConditionModel): HistoryEntryProps {\n  const detailData = [\n    {\n      label: \"Recorder\",\n      value: condition.recorder,\n    },\n    {\n      label: \"Clinical Status\",\n      value: capitalize(condition.clinicalStatus),\n    },\n    {\n      label: \"Verification Status\",\n      value: capitalize(condition.verificationStatus),\n    },\n    {\n      label: \"Category\",\n      value: startCase(condition.category),\n    },\n    {\n      label: \"Note\",\n      value: condition.notes.length !== 0 && <NotesList notes={condition.notes} />,\n    },\n    {\n      label: \"Recorded Code(s)\",\n      value: (\n        <div className=\"ctw-space-y-1\">\n          {condition.knownCodings.map((coding) => (\n            <div key={`${coding.system}-${coding.code}`}>{coding.display}</div>\n          ))}\n        </div>\n      ),\n    },\n    {\n      label: \"Onset Date\",\n      value: condition.onset,\n    },\n    {\n      label: \"Abatement Date\",\n      value: condition.abatement,\n    },\n    {\n      label: \"Encounter\",\n      value: condition.encounter,\n    },\n  ];\n\n  return {\n    id: condition.id,\n    date: condition.recordedDate,\n    versionId: condition.versionId,\n    title: condition.patientOrganizationName,\n    details: detailData,\n  };\n}\n\nconst valuesToDedupeOn = (condition: ConditionModel) => [\n  condition.recorder,\n  condition.clinicalStatus,\n  condition.verificationStatus,\n  condition.recordedDate,\n  condition.notes,\n  condition.category,\n  condition.onset,\n  condition.abatement,\n  condition.encounter,\n  condition.knownCodings.map((coding) => [coding.system, coding.code]),\n];\n","export type CodingListProps = {\n  codings: fhir4.Coding[];\n};\n\nexport const CodingList = ({ codings }: CodingListProps) => (\n  <div className=\"ctw-flex ctw-flex-col ctw-space-y-4\">\n    {codings.map((coding) => (\n      <div key={`${coding.system}-${coding.code}`} className=\"ctw-space-x-1\">\n        <span className=\"ctw-font-semibold\">{coding.code}</span>\n        <span>{coding.display}</span>\n      </div>\n    ))}\n  </div>\n);\n","import { useConditionHistory } from \"./history\";\nimport { History } from \"../../resource/helpers/history\";\nimport { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { CodingList } from \"@/components/core/coding-list\";\nimport { NotesList } from \"@/components/core/notes-list\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { capitalize } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_SUMMARY_CONDITIONS } from \"@/utils/query-keys\";\n\nconst conditionHistory = (m: ConditionModel) => (\n  <History getHistory={useConditionHistory} model={m} />\n);\n\nexport const useConditionDetailsDrawer = ({\n  rowActions,\n  enableDismissAndReadActions,\n}: {\n  rowActions?: (c: ConditionModel) => RowActionsConfigProp<ConditionModel>;\n  enableDismissAndReadActions?: boolean;\n}) =>\n  useResourceDetailsDrawer({\n    header: (condition: ConditionModel) => condition.display,\n    subHeader: (condition: ConditionModel) => condition.ccsChapter,\n    getSourceDocument: true,\n    details: (condition: ConditionModel) => [\n      { label: \"Latest Diagnosis\", value: condition.recordedDate },\n      { label: \"Recorder\", value: condition.recorder },\n      {\n        label: \"Provider Organization\",\n        value: condition.patientOrganizationName,\n      },\n      { label: \"Onset Date\", value: condition.onset },\n      { label: \"Type\", value: capitalize(condition.type) },\n      { label: \"Status\", value: capitalize(condition.displayStatus) },\n      { label: \"Abatement Date\", value: condition.abatement },\n      {\n        label: \"ICD-10\",\n        value: condition.icd10CMEnrichments.length ? (\n          <CodingList codings={condition.icd10CMEnrichments} />\n        ) : null,\n      },\n      {\n        label: \"HCC\",\n        value: condition.hccEnrichments.length ? (\n          <CodingList codings={condition.hccEnrichments} />\n        ) : null,\n      },\n      {\n        label: \"Note\",\n        value: condition.notes.length !== 0 && <NotesList notes={condition.notes} />,\n      },\n    ],\n    rowActions,\n    renderChild: conditionHistory,\n    enableDismissAndReadActions,\n    queryKey: QUERY_KEY_PATIENT_SUMMARY_CONDITIONS,\n  });\n","import { faClock } from \"@fortawesome/free-regular-svg-icons\";\nimport { faClipboardCheck, faClipboardList } from \"@fortawesome/free-solid-svg-icons\";\nimport { ConditionViewOptions } from \"./views\";\nimport { dismissFilter } from \"../../resource/filters\";\nimport { FilterChangeEvent, FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport {\n  ConditionStatuses,\n  conditionStatuses,\n  outsideConditionStatuses,\n} from \"@/fhir/models/condition\";\nimport { uniqueValues } from \"@/utils/filters\";\nimport { intersectionWith } from \"@/utils/nodash/fp\";\n\nexport function conditionFilters(\n  conditions: ConditionModel[],\n  includeDismiss: boolean,\n  showAllStatuses: boolean,\n  onlyShowOptionsForStatus?: ConditionViewOptions,\n): FilterItem[] {\n  const filters: FilterItem[] = [];\n  if (includeDismiss) {\n    filters.push(dismissFilter);\n  }\n\n  let statusesToShow: ConditionStatuses[] = showAllStatuses\n    ? [...conditionStatuses.filter((status) => status !== \"Entered in Error\")]\n    : [...outsideConditionStatuses];\n\n  if (onlyShowOptionsForStatus) {\n    switch (onlyShowOptionsForStatus) {\n      case \"Current\":\n        statusesToShow = intersectionWith((a, b) => a === b, statusesToShow, [\n          \"Active\",\n          \"Pending\",\n          \"Unknown\",\n        ]);\n        break;\n      case \"Past\":\n        statusesToShow = intersectionWith((a, b) => a === b, statusesToShow, [\n          \"Inactive\",\n          \"Refuted\",\n        ]);\n        break;\n      default:\n        break;\n    }\n  }\n\n  filters.push(\n    {\n      key: \"displayStatus\",\n      type: \"checkbox\",\n      icon: faClipboardCheck,\n      display: \"Status\",\n      // Create new array as these other ones are readonly.\n      values: statusesToShow,\n    },\n    {\n      key: \"ccsChapter\",\n      type: \"checkbox\",\n      icon: faClipboardList,\n      display: \"Category\",\n      values: uniqueValues(conditions, \"ccsChapter\"),\n    },\n    {\n      key: \"typeDisplay\",\n      type: \"checkbox\",\n      icon: faClock,\n      display: \"Type\",\n      values: uniqueValues(conditions, \"typeDisplay\").sort((a, b) => {\n        // We have to sort these filters in a specific order. Acute, Chronic, Chronic and Acute...\n        const scores: Record<string, number | undefined> = {\n          acute: 4,\n          chronic: 3,\n          \"chronic and acute\": 2,\n        };\n        const aScore = scores[a.toLowerCase()] ?? 0;\n        const bScore = scores[b.toLowerCase()] ?? 0;\n        if (aScore > bScore) {\n          return -1;\n        }\n        if (bScore > aScore) {\n          return 1;\n        }\n        return 0;\n      }),\n    },\n  );\n\n  return filters;\n}\n\nexport const defaultConditionFilters: FilterChangeEvent = {\n  displayStatus: {\n    key: \"displayStatus\",\n    selected: [\"Active\", \"Pending\", \"Unknown\"],\n    type: \"checkbox\",\n  },\n};\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { ConditionModel } from \"@/fhir/models\";\n\nexport const lastUpdatedMostRecentConditionSort: SortOption<ConditionModel> = {\n  display: \"Last Diagnosed (New to Old)\",\n  sorts: [{ key: \"recordedDate\", dir: \"desc\", isDate: true }],\n};\n\nexport const nameAzConditionSort: SortOption<ConditionModel> = {\n  display: \"Name (A-Z)\",\n  sorts: [{ key: \"display\", dir: \"asc\" }],\n}\n\nexport const conditionSortOptions: SortOption<ConditionModel>[] = [\n  nameAzConditionSort,\n  {\n    display: \"Name (Z-A)\",\n    sorts: [{ key: \"display\", dir: \"desc\" }],\n  },\n  {\n    display: \"Category (A-Z)\",\n    sorts: [{ key: \"ccsChapter\", dir: \"asc\" }],\n  },\n  {\n    display: \"Category (Z-A)\",\n    sorts: [{ key: \"ccsChapter\", dir: \"desc\" }],\n  },\n  {\n    display: \"Type (A-Z)\",\n    sorts: [{ key: \"typeDisplay\", dir: \"asc\" }],\n  },\n  {\n    display: \"Type (Z-A)\",\n    sorts: [{ key: \"typeDisplay\", dir: \"desc\" }],\n  },\n  {\n    display: \"Last Diagnosed (Old to New)\",\n    sorts: [{ key: \"recordedDate\", dir: \"asc\", isDate: true }],\n  },\n  lastUpdatedMostRecentConditionSort,\n];\n\nexport const groupedConditionSortOptions: SortOption<ConditionModel>[] = conditionSortOptions.filter(\n  (sort) => sort.sorts[0].key !== \"ccsChapter\",\n);\n","import { ViewOption } from \"../../resource/helpers/view-button\";\nimport { ConditionModel, ConditionStatuses } from \"@/fhir/models/condition\";\n\n// Filter for clinicalStatus and/or verificationStatus\nfunction statusFilter(statuses: ConditionStatuses[]) {\n  return (data: ConditionModel[]) => data.filter((c) => statuses.includes(c.displayStatus));\n}\n\nexport type ConditionViewOptions = \"Current\" | \"Past\" | \"All\";\n\nconst viewOptions: ViewOption<ConditionModel>[] = [\n  {\n    display: \"Current\",\n    filters: [statusFilter([\"Active\", \"Pending\", \"Unknown\"])],\n  },\n  {\n    display: \"Past\",\n    filters: [statusFilter([\"Inactive\", \"Refuted\"])],\n  },\n  {\n    display: \"All\",\n    filters: [(data: ConditionModel[]) => data],\n  },\n];\n\nexport const statusView = {\n  viewOptions,\n  current: viewOptions[0],\n  past: viewOptions[1],\n  all: viewOptions[2],\n};\n","import \"./patient-conditions.scss\";\n\nimport cx from \"classnames\";\nimport { ReactElement } from \"react\";\nimport { patientConditionsColumns } from \"./columns\";\nimport { useConditionDetailsDrawer } from \"./details\";\nimport { conditionFilters } from \"./filters\";\nimport { conditionSortOptions, lastUpdatedMostRecentConditionSort } from \"./sorts\";\nimport { ConditionViewOptions, statusView } from \"./views\";\nimport { PatientResourceTable } from \"../../resource/patient-resource-table\";\nimport {\n  ResourceTableActions,\n  ResourceTableActionsProps,\n} from \"../../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_PATIENT_SUMMARY_CONDITIONS } from \"@/utils/query-keys\";\n\nexport type PatientConditionsTableProps = {\n  action?: ResourceTableActionsProps<ConditionModel>[\"action\"];\n  className?: string;\n  query: { data?: ConditionModel[]; isLoading: boolean };\n  outside?: boolean;\n  readOnly?: boolean;\n  rowActions?: (r: ConditionModel) => RowActionsConfigProp<ConditionModel>;\n  emptyMessage?: string | ReactElement | undefined;\n  isLoading?: boolean;\n};\n\nexport const PatientConditionsBase = ({\n  action,\n  className,\n  query,\n  outside = false,\n  rowActions,\n  emptyMessage,\n  isLoading,\n}: PatientConditionsTableProps) => {\n  const openDetailsDrawer = useConditionDetailsDrawer({ rowActions });\n\n  const { viewOptions, current } = statusView;\n\n  const {\n    data,\n    filters,\n    setFilters,\n    setSort,\n    viewOption,\n    setViewOption,\n    defaultSort,\n    defaultView,\n  } = useFilteredSortedData({\n    cacheKey: \"patient-conditions-base\",\n    defaultSort: lastUpdatedMostRecentConditionSort,\n    viewOptions,\n    records: query.data,\n    defaultView: current.display,\n  });\n\n  const isEmptyQuery = query.data?.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  let empty = emptyMessage;\n  if (emptyMessage === undefined) {\n    empty = (\n      <EmptyPatientTable\n        hasZeroFilteredRecords={hasZeroFilteredRecords}\n        resourceName=\"conditions\"\n      />\n    );\n  }\n\n  return (\n    <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n      <ResourceTableActions\n        filterOptions={{\n          onChange: setFilters,\n          filters: conditionFilters(\n            query.data ?? [],\n            outside,\n            !outside,\n            viewOption as ConditionViewOptions,\n          ),\n          selected: filters,\n        }}\n        sortOptions={{\n          defaultSort,\n          options: conditionSortOptions,\n          onChange: setSort,\n        }}\n        viewOptions={{\n          onChange: setViewOption,\n          options: viewOptions,\n          defaultView,\n        }}\n        action={action}\n      />\n      <PatientResourceTable\n        className=\"ctw-patient-conditions\"\n        columns={patientConditionsColumns}\n        data={data}\n        emptyMessage={empty}\n        isLoading={isLoading || query.isLoading}\n        onRowClick={openDetailsDrawer}\n        rowActions={rowActions}\n        queryKey={QUERY_KEY_PATIENT_SUMMARY_CONDITIONS}\n      />\n    </div>\n  );\n};\n","import cx from \"classnames\";\nimport {\n  useAddConditionForm,\n  useConfirmDeleteCondition,\n  useEditConditionForm,\n} from \"./helpers/modal-hooks\";\nimport { PatientConditionsBase } from \"./helpers/patient-conditions-base\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { usePatientBuilderConditions } from \"@/services/conditions\";\n\nexport type PatientConditionsProps = {\n  className?: cx.Argument;\n  readOnly?: boolean;\n};\n\nconst PatientConditionsComponent = ({ className, readOnly = false }: PatientConditionsProps) => {\n  const query = usePatientBuilderConditions();\n  const showAddConditionForm = useAddConditionForm();\n  const { t } = useBaseTranslations();\n  const rowActions = useRowActions();\n  const action = !readOnly && (\n    <button type=\"button\" className=\"ctw-btn-primary\" onClick={() => showAddConditionForm()}>\n      {t(\"resource.add\", { resource: t(\"glossary:condition_one\") })}\n    </button>\n  );\n\n  return (\n    <AnalyticsProvider componentName=\"PatientConditions\">\n      <PatientConditionsBase\n        action={action}\n        className={cx(className)}\n        query={query}\n        readOnly={readOnly}\n        rowActions={readOnly ? undefined : rowActions}\n      />\n    </AnalyticsProvider>\n  );\n};\n\nexport const PatientConditions = withErrorBoundary(PatientConditionsComponent, \"PatientConditions\");\n\nfunction useRowActions(): (r: ConditionModel) => RowActionsConfigProp<ConditionModel> {\n  const showEditConditionForm = useEditConditionForm();\n  const confirmDelete = useConfirmDeleteCondition();\n\n  return (record: ConditionModel): RowActionsConfigProp<ConditionModel> => [\n    {\n      text: \"Remove\",\n      className: \"ctw-btn-default\",\n      onClick: () => confirmDelete(record),\n    },\n    {\n      text: \"Edit\",\n      className: \"ctw-btn-primary\",\n      onClick: () => showEditConditionForm(record),\n    },\n  ];\n}\n","import { IconProp } from \"@fortawesome/fontawesome-svg-core\";\nimport { faAngleRight, faInfoCircle } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport type { ReactNode } from \"react\";\nimport { Loading } from \"../../core/loading\";\nimport { Tooltip } from \"../../core/tooltip\";\nimport \"./overview.scss\";\nimport { isReactNode } from \"@/utils/types\";\n\nexport const OVERVIEW_CARD_MIN_WIDTH = 320;\nexport const OVERVIEW_CARD_MIN_WIDTH_CLASS_NAME = \"ctw-min-w-[320px]\";\n\nexport type OverviewCardProps = {\n  children?: ReactNode;\n  className?: cx.Argument;\n  footerIcon?: IconProp;\n  footerOnClick?: () => void;\n  footerText?: string;\n  hideFooter?: boolean;\n  icon?: IconProp | ReactNode;\n  isLoading?: boolean;\n  noShadow?: boolean;\n  title: string;\n  tooltipText?: string;\n  titleClassName?: cx.Argument;\n  titleSize?: \"sm\" | \"base\";\n};\n\nexport const OverviewCard = ({\n  children,\n  className,\n  footerIcon,\n  footerOnClick,\n  footerText,\n  hideFooter,\n  icon,\n  isLoading,\n  noShadow,\n  title,\n  tooltipText,\n  titleClassName,\n  titleSize,\n}: OverviewCardProps) => (\n  <div\n    className={cx(\n      className,\n      OVERVIEW_CARD_MIN_WIDTH_CLASS_NAME,\n      { \"ctw-shadow\": !noShadow },\n      \"ctw-max-h-[360px] ctw-min-h-[175px] ctw-rounded-lg ctw-border ctw-border-solid ctw-border-divider-main ctw-flex-col ctw-divide-y ctw-divide-solid ctw-divide-divider-main ctw-flex\",\n    )}\n  >\n    <OverviewCardHeader\n      icon={icon}\n      title={title}\n      className={titleClassName}\n      tooltipText={tooltipText}\n      titleSize={titleSize}\n    />\n\n    {isLoading ? (\n      <OverviewCardBodyMessage message={<Loading />} />\n    ) : (\n      <OverviewCardBody>{children}</OverviewCardBody>\n    )}\n\n    {footerText && !hideFooter && (\n      <OverviewCardFooter text={footerText} onClick={footerOnClick} icon={footerIcon} />\n    )}\n  </div>\n);\n\ntype OverviewCardHeaderProps = Pick<\n  OverviewCardProps,\n  \"icon\" | \"title\" | \"tooltipText\" | \"className\" | \"titleSize\"\n>;\n\nexport const OverviewCardHeader = ({\n  icon,\n  title,\n  tooltipText,\n  className,\n  titleSize = \"base\",\n}: OverviewCardHeaderProps) => (\n  <div\n    className={cx(\n      \"ctw-rounded-t-lg ctw-flex ctw-justify-between ctw-items-center ctw-w-full ctw-py-2.5 ctw-px-3 ctw-space-x-2\",\n      className,\n    )}\n  >\n    {icon &&\n      (isReactNode(icon) ? (\n        <div>{icon}</div>\n      ) : (\n        <FontAwesomeIcon icon={icon} className=\"ctw-w-5 ctw-h-5 ctw-text-content-lighter\" />\n      ))}\n    {/* Sadly a negative margin-bottom is needed to get this more vertically centered. */}\n    <div\n      data-testid=\"overview-card-header\"\n      className={cx(\"ctw-font-medium ctw-flex-auto ctw-text-content-black -ctw-mb-0.5\", {\n        \"ctw-text-sm\": titleSize === \"sm\",\n        \"ctw-text-base\": titleSize === \"base\",\n      })}\n    >\n      {title}\n    </div>\n    {tooltipText && (\n      <div className=\"ctw-self-start\">\n        <Tooltip content={tooltipText}>\n          <FontAwesomeIcon\n            icon={faInfoCircle}\n            className=\"ctw-w-4 ctw-h-4 ctw-text-content-lighter ctw-block\"\n          />\n        </Tooltip>\n      </div>\n    )}\n  </div>\n);\n\nexport const OverviewCardBody = ({ children }: { children: React.ReactNode }) => (\n  <div\n    data-testid=\"overview-card-body\"\n    className=\"ctw-grow ctw-flex-col ctw-flex ctw-w-full ctw-py-0 ctw-overflow-y-auto ctw-text-sm ctw-scrollbar\"\n  >\n    {children}\n  </div>\n);\n\n// Helper component that renders a message in the center of the body of the card.\nexport const OverviewCardBodyMessage = ({ message }: { message?: string | React.ReactNode }) => (\n  <div className=\"ctw-grow ctw-flex ctw-text-center ctw-justify-center ctw-items-center ctw-py-2 ctw-px-3 ctw-text-sm\">\n    <div>{message}</div>\n  </div>\n);\n\nexport const OverviewCardFooter = ({\n  text,\n  onClick,\n  icon,\n}: {\n  text: string;\n  onClick?: () => void;\n  icon?: IconProp;\n}) => {\n  if (onClick) {\n    return (\n      <button type=\"button\" className=\"ctw-overview-btn-footer ctw-group\" onClick={onClick}>\n        {text}\n        <FontAwesomeIcon\n          icon={icon ?? faAngleRight}\n          className=\"ctw-text-content-lighter ctw-button-arrow ctw-w-5 ctw-h-5 ctw-opacity-0 group-hover:ctw-opacity-100\"\n        />\n      </button>\n    );\n  }\n\n  return <div className=\"ctw-overview-footer\">{text}</div>;\n};\n","import cx from \"classnames\";\nimport { ReactElement } from \"react\";\nimport { OverviewCard, OverviewCardBodyMessage, OverviewCardProps } from \"./overview-card\";\nimport { useToggleRead } from \"../hooks/use-toggle-read\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { TableProps } from \"@/components/core/table/table\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { RowActionsProp } from \"@/components/core/table/table-rows\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { isFunction } from \"@/utils/nodash\";\nimport \"./overview.scss\";\n\nexport type ResourceOverviewCardProps<T extends MinRecordItem> = {\n  children: (record: T) => ReactElement<{ record: T }>;\n  data: T[];\n  emptyMessage: string | ReactElement;\n  onRowClick: TableProps<T>[\"handleRowClick\"];\n  onSeeAllResources?: () => void;\n  trackingName: string;\n  rowClassName?: cx.Argument;\n  RowActions?: RowActionsProp<T>;\n} & Pick<\n  OverviewCardProps,\n  | \"className\"\n  | \"hideFooter\"\n  | \"footerText\"\n  | \"icon\"\n  | \"isLoading\"\n  | \"noShadow\"\n  | \"title\"\n  | \"titleClassName\"\n  | \"titleSize\"\n  | \"tooltipText\"\n>;\n\nexport const ResourceOverviewCard = <T extends fhir4.Resource, M extends FHIRModel<T>>({\n  children,\n  data = [],\n  emptyMessage,\n  onRowClick,\n  onSeeAllResources,\n  hideFooter,\n  trackingName,\n  rowClassName,\n  RowActions,\n  ...overviewCardProps\n}: ResourceOverviewCardProps<M>) => {\n  const { trackInteraction } = useAnalytics();\n  const userBuilderId = useUserBuilderId();\n  const { toggleRead } = useToggleRead();\n  const isNoFooter = hideFooter || !onSeeAllResources;\n\n  function handleRowClick(record: M) {\n    if (onRowClick) {\n      if (!record.isRead && !record.ownedByBuilder(userBuilderId)) {\n        void toggleRead(record);\n      }\n      onRowClick(record);\n      trackInteraction(\"click_row\", { target: trackingName });\n    }\n  }\n\n  return (\n    <OverviewCard\n      hideFooter={isNoFooter}\n      footerOnClick={() => {\n        trackInteraction(\"see_all_of_resource\", { target: trackingName });\n        onSeeAllResources?.();\n      }}\n      {...overviewCardProps}\n    >\n      {data.length === 0 ? (\n        <OverviewCardBodyMessage message={emptyMessage} />\n      ) : (\n        data.map((record) => (\n          <div\n            data-testid=\"resource-overview-row\"\n            className={cx(\n              \"ctw-resource-overview-row ctw-py-1.5 ctw-px-3 ctw-group ctw-relative ctw-grouped\",\n              rowClassName,\n              {\n                \"ctw-cursor-pointer hover:ctw-bg-bg-lighter\": isFunction(onRowClick),\n                \"last:ctw-rounded-b-lg\": isNoFooter,\n              },\n            )}\n            key={record.key}\n            // Needed for accessibility (eslint and sonar rules).\n            onKeyDown={(e) => {\n              if (e.key === \"Enter\") {\n                handleRowClick(record);\n              }\n            }}\n            onClick={() => handleRowClick(record)}\n          >\n            {children(record)}\n            {RowActions && (\n              // Add onClick to prevent clicks from propagating to the row.\n              // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events\n              <div\n                aria-label=\"row-actions\"\n                className=\"ctw-row-actions group-hover:ctw-visible ctw-invisible ctw-absolute ctw-group ctw-resource-overview-actions\"\n                onClick={(event) => event.stopPropagation()}\n              >\n                <RowActions record={record} />\n              </div>\n            )}\n          </div>\n        ))\n      )}\n    </OverviewCard>\n  );\n};\n","import { useMemo } from \"react\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\nexport function useGroupedBy<T extends fhir4.Resource, M extends FHIRModel<T>>(\n  groupBy: (record: M) => string,\n  data: M[] = [],\n) {\n  // Group the records using the groupBy function\n  const groupedRecords = useMemo(\n    () =>\n      data.reduce(\n        (result, record) => {\n          const groupKey = groupBy(record) as string;\n          const group = result[groupKey] ?? [];\n          return {\n            ...result,\n            [groupKey]: group.concat(record),\n          };\n        },\n        {} as Record<string, M[] | undefined>,\n      ),\n    [data, groupBy],\n  );\n\n  const sortedKeys = useMemo(\n    () => Object.keys(groupedRecords).sort((a, b) => a.localeCompare(b)),\n    [groupedRecords],\n  );\n\n  return { groupedRecords, sortedKeys };\n}\n","import cx from \"classnames\";\nimport {\n  ResourceOverviewCard,\n  ResourceOverviewCardProps,\n} from \"../overview/resource-overview-card\";\nimport { useGroupedBy } from \"@/components/content/hooks/use-grouped-by\";\nimport { useAdditionalResourceActions } from \"@/components/content/resource/use-additional-resource-actions\";\nimport { TableProps } from \"@/components/core/table/table\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\ntype ResourceTableGroupedProps<T extends MinRecordItem> = Omit<\n  ResourceOverviewCardProps<T> & {\n    columnHeaders?: {\n      className: cx.Argument;\n      title?: string;\n      render?: () => React.ReactNode;\n    }[];\n    enableDismissAndReadActions?: boolean;\n    groupBy: (record: T) => string;\n    rowActions?: (r: T) => TableProps<T>[\"rowActions\"];\n    queryKey?: string;\n  },\n  \"title\"\n>;\n\nexport const ResourceTableGrouped = <T extends fhir4.Resource, M extends FHIRModel<T>>({\n  children,\n  columnHeaders,\n  data,\n  enableDismissAndReadActions,\n  groupBy,\n  isLoading,\n  rowActions,\n  queryKey,\n  ...resourceTableProps\n}: ResourceTableGroupedProps<M>) => {\n  // Group the records using the groupBy function\n  const { groupedRecords, sortedKeys } = useGroupedBy(groupBy, data);\n  // Create the RowActions react node\n  const RowActionsWithAdditions = useAdditionalResourceActions({\n    rowActions,\n    enableDismissAndReadActions,\n    queryKey,\n  });\n\n  return (\n    <div className=\"ctw-@container\">\n      <div className=\"ctw-space-y-2\">\n        {/* Do not show column names when loading or empty */}\n        {!isLoading && (\n          <div className=\"ctw-hidden @[640px]:ctw-flex ctw-mb-2 ctw-px-3 ctw-justify-between ctw-text-left ctw-font-medium ctw-text-sm ctw-text-content-black ctw-border-b-[1px] ctw-border-b-icon-light ctw-space-x-1.5\">\n            {columnHeaders?.map((header, i) => (\n              // eslint-disable-next-line react/no-array-index-key\n              <div key={i} className={cx(header.className)}>\n                {header.render?.() || header.title}\n              </div>\n            ))}\n          </div>\n        )}\n        {sortedKeys.map((title) => (\n          <div key={title} data-testid=\"resource-table-grouped\">\n            <ResourceOverviewCard\n              className=\"!ctw-min-h-0 !ctw-min-w-0 !ctw-text-sm\"\n              data={groupedRecords[title] ?? []}\n              isLoading={isLoading}\n              noShadow\n              title={title}\n              titleSize=\"sm\"\n              RowActions={RowActionsWithAdditions}\n              {...resourceTableProps}\n            >\n              {children}\n            </ResourceOverviewCard>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n};\n","import { useCallback } from \"react\";\nimport { useAddConditionForm } from \"@/components/content/conditions/helpers/modal-hooks\";\nimport { useToggleRead } from \"@/components/content/hooks/use-toggle-read\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useBaseTranslations } from \"@/i18n\";\n\nexport function useConditionRowActions(\n  readOnly: boolean,\n): (r: ConditionModel) => RowActionsConfigProp<ConditionModel> {\n  const { t } = useBaseTranslations();\n  const showAddConditionForm = useAddConditionForm();\n  const { toggleRead } = useToggleRead();\n  const { trackInteraction } = useAnalytics();\n\n  return useCallback(\n    (record: ConditionModel): RowActionsConfigProp<ConditionModel> => {\n      if (readOnly) {\n        return [];\n      }\n\n      if (!record.hasMatchingBuilderConditions) {\n        return [\n          {\n            className: \"ctw-btn-primary\",\n            text: t(\"resourceTable.add\"),\n            onClick: () => {\n              if (!record.isRead) {\n                void toggleRead(record);\n              }\n              showAddConditionForm(record);\n              trackInteraction(\"add_to_record\");\n            },\n          },\n        ];\n      }\n\n      return [];\n    },\n    [readOnly, showAddConditionForm, t, toggleRead, trackInteraction],\n  );\n}\n","import cx from \"classnames\";\nimport { patientConditionsAllColumns } from \"./helpers/columns\";\nimport { useConditionDetailsDrawer } from \"./helpers/details\";\nimport { conditionFilters } from \"./helpers/filters\";\nimport { useAddConditionForm } from \"./helpers/modal-hooks\";\nimport { conditionSortOptions, lastUpdatedMostRecentConditionSort } from \"./helpers/sorts\";\nimport { ConditionViewOptions, statusView } from \"./helpers/views\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { useConditionRowActions } from \"@/components/content/conditions/helpers/row-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\nimport { QUERY_KEY_PATIENT_SUMMARY_CONDITIONS } from \"@/utils/query-keys\";\n\nexport type PatientConditionsAllProps = {\n  className?: cx.Argument;\n  readOnly?: boolean;\n  onlyAllowAddOutsideConditions?: boolean;\n};\n\nfunction PatientConditionsAllComponent({\n  className,\n  readOnly = false,\n  onlyAllowAddOutsideConditions = true,\n}: PatientConditionsAllProps) {\n  const { t } = useBaseTranslations();\n  const query = usePatientConditionsAll();\n  const showAddConditionForm = useAddConditionForm();\n  const rowActions = useConditionRowActions(readOnly);\n  const { viewOptions, current } = statusView;\n\n  const {\n    data,\n    filters,\n    setFilters,\n    setSort,\n    viewOption,\n    setViewOption,\n    defaultSort,\n    defaultView,\n  } = useFilteredSortedData({\n    cacheKey: \"patient-conditions-all\",\n    defaultSort: lastUpdatedMostRecentConditionSort,\n    viewOptions,\n    records: query.data,\n    defaultView: current.display,\n  });\n\n  const isEmptyQuery = query.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const empty = (\n    <EmptyPatientTable hasZeroFilteredRecords={hasZeroFilteredRecords} resourceName=\"conditions\" />\n  );\n\n  const openDetails = useConditionDetailsDrawer({\n    rowActions,\n    enableDismissAndReadActions: true,\n  });\n\n  const action = !readOnly && !onlyAllowAddOutsideConditions && (\n    <button\n      type=\"button\"\n      className=\"ctw-btn-primary ctw-flex ctw-w-full ctw-items-center\"\n      onClick={() => showAddConditionForm()}\n    >\n      <span className=\"ctw-w-full\">\n        {t(\"resource.add\", { resource: t(\"glossary:condition_one\") })}\n      </span>\n    </button>\n  );\n\n  return (\n    <AnalyticsProvider componentName=\"PatientConditionsAll\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: conditionFilters(query.data, true, true, viewOption as ConditionViewOptions),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: conditionSortOptions,\n            onChange: setSort,\n          }}\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n          action={action}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={query.isLoading}\n          data={data}\n          columns={patientConditionsAllColumns()}\n          onRowClick={openDetails}\n          rowActions={readOnly ? undefined : rowActions}\n          enableDismissAndReadActions\n          emptyMessage={empty}\n          queryKey={QUERY_KEY_PATIENT_SUMMARY_CONDITIONS}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientConditionsAll = withErrorBoundary(\n  PatientConditionsAllComponent,\n  \"PatientConditionsAll\",\n);\n","import { faCircleCheck } from \"@fortawesome/free-regular-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useConditionDetailsDrawer } from \"./helpers/details\";\nimport { ConditionViewOptions, statusView } from \"./helpers/views\";\nimport { RenderInfoBadge, ResourceTitleColumn } from \"../resource/helpers/resource-title-column\";\nimport { ResourceTableGrouped } from \"../resource/resource-table-grouped\";\nimport {\n  conditionsColumnGroupedClassNames,\n  patientConditionsColumnsGrouped,\n} from \"@/components/content/conditions/helpers/columns\";\nimport { conditionFilters } from \"@/components/content/conditions/helpers/filters\";\nimport { useAddConditionForm } from \"@/components/content/conditions/helpers/modal-hooks\";\nimport { useConditionRowActions } from \"@/components/content/conditions/helpers/row-actions\";\nimport {\n  groupedConditionSortOptions,\n  lastUpdatedMostRecentConditionSort,\n} from \"@/components/content/conditions/helpers/sorts\";\nimport { PatientConditionsAll } from \"@/components/content/conditions/patient-conditions-all\";\nimport { ResourceTableActions } from \"@/components/content/resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { Tooltip } from \"@/components/core/tooltip\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\nimport { isEmpty } from \"@/utils/nodash\";\n\nexport type PatientConditionsAllGroupedProps = {\n  readOnly?: boolean;\n  onlyAllowAddOutsideConditions?: boolean;\n  className?: cx.Argument;\n};\n\nconst PatientConditionsAllGroupedComponent = ({\n  className,\n  readOnly = false,\n  onlyAllowAddOutsideConditions = true,\n}: PatientConditionsAllGroupedProps) => {\n  const { t } = useBaseTranslations();\n  const showAddConditionForm = useAddConditionForm();\n  const rowActions = useConditionRowActions(readOnly);\n  const query = usePatientConditionsAll();\n\n  const { viewOptions, current } = statusView;\n  const {\n    data,\n    filters,\n    setFilters,\n    setSort,\n    viewOption,\n    setViewOption,\n    defaultSort,\n    defaultView,\n  } = useFilteredSortedData({\n    cacheKey: \"patient-conditions-all-grouped\",\n    defaultSort: lastUpdatedMostRecentConditionSort,\n    viewOptions,\n    records: query.data,\n    defaultView: current.display,\n  });\n\n  const isEmptyQuery = query.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openDetails = useConditionDetailsDrawer({\n    rowActions,\n    enableDismissAndReadActions: true,\n  });\n\n  const action = !readOnly && !onlyAllowAddOutsideConditions && (\n    <button\n      type=\"button\"\n      className=\"ctw-btn-primary ctw-flex ctw-w-full ctw-items-center\"\n      onClick={() => showAddConditionForm()}\n    >\n      <span className=\"ctw-w-full\">\n        {t(\"resource.add\", { resource: t(\"glossary:condition_one\") })}\n      </span>\n    </button>\n  );\n\n  return (\n    <AnalyticsProvider componentName=\"PatientConditionsAll\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: groupedConditionSortOptions,\n            onChange: setSort,\n          }}\n          filterOptions={{\n            onChange: setFilters,\n            filters: conditionFilters(query.data, true, true, viewOption as ConditionViewOptions),\n            selected: filters,\n          }}\n          action={action}\n        />\n\n        {hasZeroFilteredRecords && (\n          <div className=\"ctw-my-16\">\n            <EmptyPatientTable resourceName=\"conditions\" hasZeroFilteredRecords />\n          </div>\n        )}\n\n        {/* Wrap this separately so when we hide the table header it doesn't affect space-y */}\n        <ResourceTableGrouped\n          hideFooter\n          data={data}\n          onRowClick={openDetails}\n          isLoading={query.isLoading}\n          trackingName=\"condition\"\n          emptyMessage=\"We didn't find any condition records for this patient.\"\n          rowClassName=\"ctw-border-b ctw-border-border-lighter last:ctw-border-none\"\n          titleClassName=\"!ctw-text-sm ctw-bg-bg-light ctw-text-content-light ctw-pl-[2.5rem] ctw-pb-1 ctw-pt-2\"\n          groupBy={(record: ConditionModel) => record.ccsChapter || \"Uncategorized\"}\n          rowActions={rowActions}\n          columnHeaders={patientConditionsColumnsGrouped}\n          enableDismissAndReadActions\n        >\n          {(record: ConditionModel) => (\n            <div\n              className=\"ctw-flex ctw-justify-between ctw-text-left ctw-text-base ctw-space-x-1.5 ctw-group ctw-relative\"\n              data-testid=\"patient-conditions-all-row\"\n            >\n              <div className={cx(conditionsColumnGroupedClassNames.builderOwned)} role=\"cell\">\n                {record.hasMatchingBuilderConditions && (\n                  <Tooltip content=\"Synced with record\">\n                    <FontAwesomeIcon\n                      className=\"ctw-text-content-light ctw-w-[14px] ctw-h-[14px]\"\n                      icon={faCircleCheck}\n                    />\n                  </Tooltip>\n                )}\n              </div>\n              <div className={cx(conditionsColumnGroupedClassNames.displayName)} role=\"cell\">\n                <ResourceTitleColumn\n                  title={record.display}\n                  renderIcon={RenderInfoBadge(!isEmpty(record.hccEnrichment) ? \"HCC\" : undefined)}\n                />\n              </div>\n              <div className={cx(conditionsColumnGroupedClassNames.latestDiagnosis)} role=\"cell\">\n                <div>{record.recordedDate}</div>\n                <div>{record.recorder}</div>\n              </div>\n              <div className={cx(conditionsColumnGroupedClassNames.onset)} role=\"cell\">\n                {record.onset}\n              </div>\n              <div className={cx(conditionsColumnGroupedClassNames.type)} role=\"cell\">\n                {record.typeDisplay}\n              </div>\n            </div>\n          )}\n        </ResourceTableGrouped>\n      </div>\n    </AnalyticsProvider>\n  );\n};\n\nfunction PatientConditionsAllGroupedFeatureRelease(props: PatientConditionsAllGroupedProps) {\n  const hasConditionsGrouped = useFeatureToggle(\"ctw-conditions-grouped\");\n\n  if (hasConditionsGrouped.ready) {\n    if (hasConditionsGrouped.enabled) {\n      return <PatientConditionsAllGroupedComponent {...props} />;\n    }\n    return <PatientConditionsAll {...props} />;\n  }\n  return null;\n}\n\nexport const PatientConditionsAllGrouped = withErrorBoundary(\n  PatientConditionsAllGroupedFeatureRelease,\n  \"PatientConditionsAllGrouped\",\n);\n","import { faClock } from \"@fortawesome/free-regular-svg-icons\";\nimport { IconDefinition } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport React, { cloneElement, isValidElement, ReactElement } from \"react\";\nimport { Tooltip } from \"@/components/core/tooltip\";\nimport { formatISODateStringToDate } from \"@/fhir/formatters\";\n\ninterface PatientHistoryDetailProps {\n  text: string;\n  date?: Date;\n  className?: cx.Argument;\n}\n\ninterface PatientHistoryDetailWithTooltipProps extends PatientHistoryDetailProps {\n  icon: IconDefinition | ReactElement<{ className?: string }>;\n  tooltip?: string;\n}\n\nexport function PatientHistoryDetail(props: PatientHistoryDetailProps): React.ReactElement;\nexport function PatientHistoryDetail(\n  props: PatientHistoryDetailWithTooltipProps,\n): React.ReactElement;\nexport function PatientHistoryDetail(\n  props: PatientHistoryDetailProps | PatientHistoryDetailWithTooltipProps,\n) {\n  const { text, date, className } = props;\n  let tooltipElement = null;\n  if (isPropsWithIcon(props)) {\n    const { icon, tooltip } = props;\n    const iconElement = isValidElement(icon) ? (\n      cloneElement(icon, {\n        className: cx(\"history-request-form-icon ctw-h-4\", icon.props.className),\n      })\n    ) : (\n      <FontAwesomeIcon\n        icon={icon as IconDefinition}\n        className=\"history-request-form-icon ctw-h-4\"\n      />\n    );\n\n    tooltipElement = <Tooltip content={tooltip}>{iconElement}</Tooltip>;\n  }\n\n  return (\n    <div className={cx(\"ctw-flex ctw-items-center ctw-space-x-1\", className)}>\n      <FontAwesomeIcon icon={faClock} />\n      <span>{text}</span>\n      {date && <span>{formatISODateStringToDate(date.toISOString())}</span>}\n      {tooltipElement}\n    </div>\n  );\n}\n\nfunction isPropsWithIcon(\n  props: PatientHistoryDetailProps | PatientHistoryDetailWithTooltipProps,\n): props is PatientHistoryDetailWithTooltipProps {\n  return \"icon\" in props;\n}\n","import { format } from \"date-fns\";\nimport { PatientModel } from \"./patient\";\nimport { formatISODateStringToDate } from \"../formatters\";\nimport {\n  PatientHistoryJobProvider,\n  PatientHistoryJobProviderStatus,\n  PatientHistoryJobResponseJobData,\n} from \"@/services/patient-history/patient-history-types\";\n\nconst providerServiceOverrides = [\"ehr_network\", \"medication_history\"] as const;\nexport type ProviderServiceOverride = (typeof providerServiceOverrides)[number];\n\n\nexport const completedProviderStatus: readonly PatientHistoryJobProviderStatus[] = [\n  \"done\",\n  \"skipped\",\n];\n\nexport const failedProviderStatus: readonly PatientHistoryJobProviderStatus[] = [\n  \"error\",\n  \"done_with_info\",\n];\n\nexport type PatientHistoryJobDerivedProviderStatus =\n  | \"inProgress\"\n  | \"complete\"\n  | \"failed\"\n  | \"partiallyComplete\" // Partially complete is a combination of in-progress and complete\n  | \"completeWithErrors\";  // Complete with errors is a combination of complete and failed\n\nexport class PatientHistoryRequestModel {\n  kind = \"PatientHistory\" as const;\n\n  constructor(\n    public patient: PatientModel,\n    public historyInfo: PatientHistoryJobResponseJobData,\n  ) {}\n\n  get key() {\n    return this.historyInfo.id;\n  }\n\n  get providers() {\n    return this.historyInfo.attributes.providers;\n  }\n\n  get targetDate() {\n    // This is necessary because targetDate was not introduced until May 2023 and it was not backfilled\n    return formatISODateStringToDate(\n      this.historyInfo.attributes.targetDate ??\n        Number(this.historyInfo.attributes.lastUpdatedAt) * 1000,\n    );\n  }\n\n  get createdAt() {\n    return format(new Date(Number(this.historyInfo.attributes.createdAt) * 1000), \"M/d/yy h:mm a\");\n  }\n\n  get lastUpdatedAt() {\n    return format(\n      new Date(Number(this.historyInfo.attributes.lastUpdatedAt) * 1000),\n      \"M/d/yy h:mm a\",\n    );\n  }\n\n  static getDerivedProviderStatus(\n    providers: readonly PatientHistoryJobProvider[],\n  ): PatientHistoryJobDerivedProviderStatus {\n    const statuses = providers.map((provider) => provider.status);\n\n    if (statuses.every((status) => completedProviderStatus.includes(status))) {\n      return \"complete\";\n    }\n\n    if (statuses.every((status) => failedProviderStatus.includes(status))) {\n      return \"failed\";\n    }\n\n    if (statuses.every((status) => [...completedProviderStatus, ...failedProviderStatus].includes(status))) {\n      return \"completeWithErrors\";\n    }\n\n    if (statuses.some((status) => completedProviderStatus.includes(status))) {\n      return \"partiallyComplete\";\n    }\n\n    return \"inProgress\";\n  }\n}\n","import { useMemo } from \"react\";\nimport { usePatientHistoryDetails } from \"@/components/content/patient-history/use-patient-history\";\nimport { usePatient } from \"@/components/core/providers/patient-provider\";\nimport { PatientHistoryJobDerivedProviderStatus, PatientHistoryRequestModel } from \"@/fhir/models/patient-history\";\nimport { PatientHistoryJobStatus } from \"@/services/patient-history/patient-history-types\";\n\ntype UsePatientHistoryStatus = {\n  isLoading: boolean;\n  lastCompletedDate: Date | undefined;\n  jobStatus: PatientHistoryJobStatus | undefined;\n  derivedStatus: PatientHistoryJobDerivedProviderStatus | undefined;\n}\n\nexport function usePatientHistoryStatus (): UsePatientHistoryStatus {\n  const { isLoading, data = {} } = usePatientHistoryDetails();\n  const patient = usePatient();\n\n  return useMemo(() => {\n    const { latestCompleted, latestInProgress, nextScheduledAt } = data;\n    const hasJob = !!latestCompleted || !!latestInProgress || !!nextScheduledAt;\n\n    const { jobStatus } = latestCompleted?.job.attributes || {};\n\n    if (patient.data?.isTestPatient && !hasJob) {\n      // Not sure what this is needed for, test or otherwise, but it's in the original code\n      return {\n        jobStatus,\n        isLoading: false,\n        derivedStatus: \"complete\",\n        lastCompletedDate: new Date(),\n      }\n    }\n\n    if (latestCompleted?.job.attributes.jobStatus) {\n      return {\n        jobStatus,\n        isLoading: false,\n        derivedStatus: PatientHistoryRequestModel.getDerivedProviderStatus(\n          latestCompleted.job.attributes.providers,\n        ),\n        lastCompletedDate: latestCompleted.targetDate,\n      }\n    }\n\n    return {\n      jobStatus,\n      isLoading: patient.isLoading || isLoading,\n      derivedStatus: undefined,\n      lastCompletedDate: undefined,\n    };\n  }, [data, isLoading, patient.data?.isTestPatient, patient.isLoading])\n}\n","import { faCircleExclamation, faWarning } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { PatientHistoryDetail } from \"./patient-history-detail\";\nimport { usePatientHistoryStatus } from \"./use-patient-history-status\";\n\ntype PatientHistoryLastCompletedProps = {\n  className?: cx.Argument;\n};\n\nexport const PatientHistoryLastCompleted = ({ className }: PatientHistoryLastCompletedProps) => {\n  const { isLoading, lastCompletedDate, derivedStatus } = usePatientHistoryStatus();\n\n  if (isLoading) {\n    return null;\n  }\n\n  if (derivedStatus === \"complete\") {\n    return (\n      <PatientHistoryDetail text=\"Last Requested\" date={lastCompletedDate} className={className} />\n    );\n  }\n\n  if (derivedStatus === \"completeWithErrors\") {\n    return (\n      <PatientHistoryDetail\n        text=\"Last requested\"\n        date={lastCompletedDate}\n        className={className}\n        icon={<FontAwesomeIcon icon={faWarning} className=\"ctw-text-caution-icon\" />}\n        tooltip=\"There was an error fetching some records for this patient\"\n      />\n    );\n  }\n\n  if (derivedStatus === \"failed\") {\n    return (\n      <PatientHistoryDetail\n        text=\"Last request failed\"\n        date={lastCompletedDate}\n        className={cx(className, \"ctw-text-error-main\")}\n        icon={faCircleExclamation}\n        tooltip=\"There was an error fetching records for this patient\"\n      />\n    );\n  }\n\n  return <PatientHistoryDetail text=\"Records never requested\" />;\n};\n","import { PatientHistoryDetail } from \"./patient-history-detail\";\nimport { PatientHistoryLastCompleted } from \"./patient-history-last-completed\";\nimport { RequestRecordsButton } from \"./request-records-button\";\nimport { usePatientHistory } from \"./use-patient-history\";\nimport { RefreshIcon } from \"@/components/core/icons/refresh\";\nimport { Spinner } from \"@/components/core/spinner\";\nimport { PatientHistoryRequestModel } from \"@/fhir/models/patient-history\";\n\nexport type PatientHistoryWithActionProps = {\n  hideRequestRecords?: boolean;\n  includePatientDemographicsForm?: boolean;\n};\n\nexport const PatientHistoryWithAction = ({\n  hideRequestRecords = false,\n  includePatientDemographicsForm = false,\n}: PatientHistoryWithActionProps) => {\n  const { isError, isLoading, details } = usePatientHistory();\n\n  if (isError) {\n    return <div className=\"ctw-text-center ctw-text-sm\">Unable to load patient history</div>;\n  }\n\n  if (isLoading) {\n    return <Spinner className=\"ctw-w-full\" />;\n  }\n\n  const { latestInProgress, latestCompleted, nextScheduledAt } = details;\n  const latestInProgressStatus =\n    latestInProgress &&\n    PatientHistoryRequestModel.getDerivedProviderStatus(latestInProgress.job.attributes.providers);\n  const latestInProgressText =\n    latestInProgressStatus === \"partiallyComplete\"\n      ? \"Current request partially complete\"\n      : \"Request in-progress\";\n\n  // Only show last completed if there is one or if there isn't a latest in progress or next scheduled\n  const showLastCompleted = !!latestCompleted || (!latestInProgress && !nextScheduledAt);\n\n  return (\n    <div className=\"ctw-flex ctw-flex-col ctw-gap-1.5 ctw-text-sm ctw-text-content-light\">\n      {latestInProgress && (\n        <PatientHistoryDetail\n          text={latestInProgressText}\n          icon={<RefreshIcon className=\"ctw-flex-none ctw-w-auto\" />}\n          tooltip=\"Patient records are  being retrieved\"\n        />\n      )}\n      {!latestInProgress && nextScheduledAt && (\n        <PatientHistoryDetail text=\"Request scheduled\" date={nextScheduledAt} />\n      )}\n      {showLastCompleted && <PatientHistoryLastCompleted key=\"patient-history-last-completed\" />}\n      {!hideRequestRecords && (\n        <div>\n          <RequestRecordsButton includePatientDemographicsForm={includePatientDemographicsForm} />\n        </div>\n      )}\n    </div>\n  );\n};\n","import { useAddConditionForm } from \"./helpers/modal-hooks\";\nimport { PatientConditionsBase } from \"./helpers/patient-conditions-base\";\nimport { useToggleDismiss } from \"../hooks/use-toggle-dismiss\";\nimport { PatientHistoryWithAction } from \"../patient-history/patient-history-with-action\";\nimport { usePatientHistory } from \"../patient-history/use-patient-history\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { Spinner } from \"@/components/core/spinner\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { usePatientConditionsOutside } from \"@/services/conditions\";\n\nexport type PatientConditionsOutsideProps = {\n  className?: string;\n  hideRequestRecords?: boolean;\n  readOnly?: boolean;\n};\n\nconst PatientConditionsOutsideComponent = ({\n  className,\n  hideRequestRecords = false,\n  readOnly = false,\n}: PatientConditionsOutsideProps) => {\n  const query = usePatientConditionsOutside();\n  const patientHistoryQuery = usePatientHistory();\n  const hasNoOutsideDataAndHasNeverRequestedPatientHistory =\n    !patientHistoryQuery.details.latestCompleted && query.data.length === 0;\n\n  const rowActions = useRowActions();\n  const action = (\n    <PatientHistoryWithAction\n      hideRequestRecords={\n        hideRequestRecords || hasNoOutsideDataAndHasNeverRequestedPatientHistory || readOnly\n      }\n    />\n  );\n\n  return (\n    <AnalyticsProvider componentName=\"PatientConditionsOutside\">\n      <PatientConditionsBase\n        outside\n        action={action}\n        className={className}\n        query={query}\n        readOnly={readOnly}\n        rowActions={readOnly ? undefined : rowActions}\n        isLoading={patientHistoryQuery.isLoading}\n      />\n    </AnalyticsProvider>\n  );\n};\n\nexport const PatientConditionsOutside = withErrorBoundary(\n  PatientConditionsOutsideComponent,\n  \"PatientConditions\",\n);\n\nfunction useRowActions(): (r: ConditionModel) => RowActionsConfigProp<ConditionModel> {\n  const { t } = useBaseTranslations();\n  const showAddConditionForm = useAddConditionForm();\n  const { isLoading, toggleDismiss } = useToggleDismiss();\n\n  return (record: ConditionModel): RowActionsConfigProp<ConditionModel> => {\n    const archiveLabel = record.isDismissed\n      ? t(\"resourceTable.restore\")\n      : t(\"resourceTable.dismiss\");\n    return [\n      {\n        text: archiveLabel,\n        className: \"ctw-btn-default\",\n        onClick: async () => {\n          await toggleDismiss(record);\n        },\n        disabled: isLoading,\n        render() {\n          return (\n            <div className=\"ctw-flex\">\n              {isLoading ? <Spinner className=\"ctw-mx-4 ctw-align-middle\" /> : archiveLabel}\n            </div>\n          );\n        },\n      },\n      {\n        text: t(\"resourceTable.add\"),\n        className: \"ctw-btn-primary\",\n        disabled: isLoading,\n        onClick: () => showAddConditionForm(record),\n      },\n    ];\n  };\n}\n","import { UnreadNotificationIcon } from \"@/components/core/unread-notification-icon\";\nimport { usePatientConditionsOutside } from \"@/services/conditions\";\n\nexport const PatientConditionsOutsideBadge = () => {\n  const otherConditionsQuery = usePatientConditionsOutside();\n  const activeUnarchivedConditions = otherConditionsQuery.data.filter(\n    (condition) => condition.active && !condition.isDismissed\n  );\n\n  if (activeUnarchivedConditions.length > 0) {\n    return <UnreadNotificationIcon />;\n  }\n  return null;\n};\n","export type OverviewFilter<T> = {\n  key: string;\n  label: string;\n  description: string;\n  predicate: (r: T) => boolean;\n};\n\nexport function applyFilters<T>(data: T[], filters: { predicate: (item: T) => boolean }[]): T[] {\n  return data.filter((item) => filters.every((filter) => filter.predicate(item)));\n}\n","import cx from \"classnames\";\nimport { OverviewCard, OverviewCardBodyMessage } from \"./overview-card\";\nimport { useToggleRead } from \"../hooks/use-toggle-read\";\nimport { useGroupedBy } from \"@/components/content/hooks/use-grouped-by\";\nimport { ResourceOverviewCardProps } from \"@/components/content/overview/resource-overview-card\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { isFunction } from \"@/utils/nodash\";\n\nexport type ResourceOverviewCardGroupedProps<T extends MinRecordItem> =\n  ResourceOverviewCardProps<T> & {\n    groupBy: (record: T) => string;\n  };\n\nexport const ResourceOverviewCardGrouped = <T extends fhir4.Resource, M extends FHIRModel<T>>({\n  children,\n  data = [],\n  emptyMessage,\n  onRowClick,\n  onSeeAllResources,\n  hideFooter,\n  trackingName,\n  rowClassName,\n  groupBy,\n  ...overviewCardProps\n}: ResourceOverviewCardGroupedProps<M>) => {\n  const { trackInteraction } = useAnalytics();\n  const userBuilderId = useUserBuilderId();\n  const { toggleRead } = useToggleRead();\n  const isNoFooter = hideFooter || !onSeeAllResources;\n  // Group the records using the groupBy function\n  const { groupedRecords, sortedKeys } = useGroupedBy(groupBy, data);\n\n  function handleRowClick(record: M) {\n    if (onRowClick) {\n      if (!record.isRead && !record.ownedByBuilder(userBuilderId)) {\n        void toggleRead(record);\n      }\n      onRowClick(record);\n      trackInteraction(\"click_row\", { target: trackingName });\n    }\n  }\n\n  return (\n    <OverviewCard\n      hideFooter={isNoFooter}\n      footerOnClick={() => {\n        trackInteraction(\"see_all_of_resource\", { target: trackingName });\n        onSeeAllResources?.();\n      }}\n      {...overviewCardProps}\n    >\n      {data.length === 0 ? (\n        <OverviewCardBodyMessage message={emptyMessage} />\n      ) : (\n        sortedKeys.map((titleKey) => (\n          <div key={titleKey}>\n            <div className=\"ctw-uppercase ctw-text-xs ctw-bg-bg-light ctw-text-content-light ctw-pl-8 ctw-pb-1 ctw-pt-2\">\n              {titleKey}\n            </div>\n            {(groupedRecords[titleKey] ?? []).map((record) => (\n              <div\n                className={cx(\"ctw-py-1.5 ctw-px-2\", rowClassName, {\n                  \"ctw-cursor-pointer hover:ctw-bg-bg-lighter\": isFunction(onRowClick),\n                  \"last:ctw-rounded-b-lg\": isNoFooter,\n                })}\n                key={record.key}\n                // Needed for accessibility (eslint and sonar rules).\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\") {\n                    handleRowClick(record);\n                  }\n                }}\n                onClick={() => handleRowClick(record)}\n              >\n                {children(record)}\n              </div>\n            ))}\n          </div>\n        ))\n      )}\n    </OverviewCard>\n  );\n};\n","import { createContext } from \"react\";\nimport { ZusAggregatedProfileSubComponentPropsMap } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile\";\n\ntype ZapPropsStateContextType = {\n  props: ZusAggregatedProfileSubComponentPropsMap;\n  setProps: (props: ZusAggregatedProfileSubComponentPropsMap) => void;\n};\n\nexport const ZapPropsStateContext = createContext<ZapPropsStateContextType>({\n  props: {},\n  setProps: () => {},\n});\n","import { faCircleCheck } from \"@fortawesome/free-regular-svg-icons\";\nimport { faClipboardList } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { useContext } from \"react\";\nimport { useConditionDetailsDrawer } from \"./helpers/details\";\nimport { lastUpdatedMostRecentConditionSort } from \"./helpers/sorts\";\nimport { statusView } from \"./helpers/views\";\nimport { applyFilters, OverviewFilter } from \"../overview/filters\";\nimport { RenderInfoBadge, ResourceTitleColumn } from \"../resource/helpers/resource-title-column\";\nimport { useConditionRowActions } from \"@/components/content/conditions/helpers/row-actions\";\nimport { ResourceOverviewCardGrouped } from \"@/components/content/overview/resource-overview-card-grouped\";\nimport { ZapPropsStateContext } from \"@/components/core/providers/zap-props-state-context\";\nimport { Tooltip } from \"@/components/core/tooltip\";\nimport { formatDate } from \"@/fhir/formatters\";\nimport { ConditionModel } from \"@/fhir/models\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\nimport { isEmpty, orderBy } from \"@/utils/nodash\";\n\nexport const filters = (): OverviewFilter<ConditionModel>[] => [\n  {\n    key: \"conditions\",\n    label: \"chronic conditions or acute conditions with hcc\",\n    description: \"chronic conditions or acute conditions with hcc\",\n    predicate: (r: ConditionModel) =>\n      r.chronic?.code === \"C\" || (r.chronic?.code === \"A\" && !isEmpty(r.hccEnrichment)),\n  },\n];\n\nexport type PatientConditionOverviewProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const PatientConditionOverview = ({ onSeeAllResources }: PatientConditionOverviewProps) => {\n  const { props } = useContext(ZapPropsStateContext);\n  const { current } = statusView;\n  const rowActions = useConditionRowActions(props[\"conditions-all\"]?.readOnly ?? false);\n  const openDetails = useConditionDetailsDrawer({\n    rowActions,\n    enableDismissAndReadActions: false,\n  });\n  const { data, isLoading } = usePatientConditionsAll();\n\n  const { data: filteredData } = useFilteredSortedData({\n    defaultSort: lastUpdatedMostRecentConditionSort,\n    viewOptions: [current],\n    records: data,\n    defaultView: current.display,\n  });\n\n  const filteredSortedData = orderBy(\n    applyFilters(filteredData, filters()),\n    (d) => d.display,\n    \"asc\",\n  );\n\n  const noData = data.length === 0;\n\n  return (\n    <ResourceOverviewCardGrouped\n      groupBy={(record) => String(record.ccsChapter)}\n      onSeeAllResources={onSeeAllResources}\n      onRowClick={openDetails}\n      data={filteredSortedData}\n      emptyMessage={\n        noData\n          ? \"We didn't find any condition records for this patient.\"\n          : \"There are no chronic conditions or acute HCCs for this patient.\"\n      }\n      footerText=\"All Conditions\"\n      hideFooter={noData}\n      title=\"Conditions\"\n      tooltipText=\"Chronic Conditions and acute HCCs\"\n      isLoading={isLoading}\n      icon={faClipboardList}\n      trackingName=\"conditions_overview\"\n    >\n      {(record: ConditionModel) => (\n        <div className=\"ctw-flex ctw-justify-between ctw-text-left\">\n          <div className=\"ctw-w-[1.5rem] ctw-max-w-[1.5rem] ctw-min-w-[1.5rem] ctw-text-sm\">\n            {record.hasMatchingBuilderConditions && (\n              <Tooltip content=\"Synced with record\">\n                <FontAwesomeIcon\n                  className=\"ctw-text-content-light ctw-w-[14px] ctw-h-[14px]\"\n                  icon={faCircleCheck}\n                />\n              </Tooltip>\n            )}\n          </div>\n          <div className=\"ctw-w-full ctw-flex-grow ctw-text-sm\">\n            <ResourceTitleColumn\n              className=\"ctw-w-full\"\n              title={\n                <>\n                  {record.display}{\" \"}\n                  {record.recordedDate && (\n                    <span className=\"ctw-font-normal ctw-text-content-light ctw-text-xs ctw-whitespace-nowrap\">\n                      [Last Dx {formatDate(record.recordedDate, \"yyyy\")}]\n                    </span>\n                  )}\n                </>\n              }\n              renderIcon={RenderInfoBadge(!isEmpty(record.hccEnrichment) ? \"HCC\" : undefined)}\n            />\n          </div>\n        </div>\n      )}\n    </ResourceOverviewCardGrouped>\n  );\n};\n","import { IVariant, useFlagsStatus, useUnleashClient } from \"@unleash/proxy-client-react\";\nimport { useContext } from \"react\";\nimport { z, ZodRawShape } from \"zod\";\nimport { FeatureFlagContext } from \"@/components/core/providers/feature-flag-provider\";\n\nexport type FeatureVariant = Partial<IVariant> & {\n  ready: boolean;\n};\n\nexport function useFeatureVariant(name: string): FeatureVariant {\n  const client = useUnleashClient();\n  const status = useFlagsStatus();\n  const { unleashClientFailed } = useContext(FeatureFlagContext);\n\n  // return \"ready\" if unleash client failed to load or failed to load flags\n  if (unleashClientFailed || status.flagsError) {\n    return { ready: true };\n  }\n\n  // return \"not ready\" if flags are still being fetched\n  if (!status.flagsReady && !status.flagsError) {\n    return { ready: false };\n  }\n\n  // return \"ready\" /w a variant\n  const variant = client.getVariant(name);\n  return { ...variant, ready: true };\n}\n\nexport function processVariantPayload<K extends ZodRawShape, T extends z.ZodObject<K>>(\n  variant: FeatureVariant,\n  payloadSchema: T,\n): z.infer<T> | undefined {\n  if (\n    variant.ready &&\n    variant.enabled &&\n    variant.payload?.type === \"json\" &&\n    variant.payload.value\n  ) {\n    try {\n      const result = payloadSchema.safeParse(JSON.parse(variant.payload.value));\n      if (!result.success) {\n        // eslint-disable-next-line no-console\n        console.error(result.error);\n      } else {\n        return result.data;\n      }\n    } catch (e) {\n      // This guards the case where JSON.parse throws an error. This shouldn't happen as unleash form requires valid json.\n      // eslint-disable-next-line no-console\n      console.error(e);\n    }\n  }\n\n  return undefined;\n}\n","import { faCircleInfo, faTriangleExclamation, faXmark } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useRef, useState } from \"react\";\nimport { z } from \"zod\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport { processVariantPayload, useFeatureVariant } from \"@/hooks/use-feature-variant\";\n\n// TODO change the name of this once the alerts are off.\nconst DISMISSED_ALERTS_KEY = \"ctw-zap-alerts-dismissed\";\n\nconst THEME_TYPES = {\n  caution: {\n    icon: faTriangleExclamation,\n    iconColor: \"ctw-text-caution-icon\",\n    iconHover: \"hover:ctw-bg-caution-light\",\n    messageColor: \"ctw-text-caution-text\",\n    linkHover: \"hover:ctw-text-caution-textHover\",\n    bg: \"ctw-bg-caution-bg\",\n  },\n  info: {\n    icon: faCircleInfo,\n    iconColor: \"ctw-text-info-icon\",\n    iconHover: \"hover:ctw-bg-info-light\",\n    messageColor: \"ctw-text-info-text\",\n    linkHover: \"hover:ctw-text-info-textHover\",\n    bg: \"ctw-bg-info-bg\",\n  },\n};\n\nconst PAYLOAD_SCHEMA = z.object({\n  type: z.enum([\"caution\", \"info\"]),\n  message: z.string(),\n  link: z.string().optional(),\n});\n\nexport type AlertFeatureFlag = {\n  className?: string;\n  featureFlag: string;\n};\n\nexport function AlertFeatureFlag({ className, featureFlag }: AlertFeatureFlag) {\n  const [dismissed, setDismissed] = useState(false);\n  const ref = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(ref);\n  const featureVariant = useFeatureVariant(featureFlag);\n  const payload = processVariantPayload(featureVariant, PAYLOAD_SCHEMA);\n\n  const dismissedAlerts = getDismissedAlerts();\n\n  // Hide if there is no payload (meaning there's no alert to show).\n  // Also hide if the alert has been dismissed.\n  if (!payload || dismissedAlerts.includes(featureVariant.name) || dismissed) {\n    return null;\n  }\n\n  const theme = THEME_TYPES[payload.type];\n\n  function dismiss() {\n    dismissedAlerts.push(featureVariant.name);\n    localStorage.setItem(DISMISSED_ALERTS_KEY, JSON.stringify(dismissedAlerts));\n    setDismissed(true);\n  }\n\n  return (\n    <div\n      ref={ref}\n      className={cx(className, theme.bg, \"ctw-p-3 ctw-flex ctw-space-x-7 ctw-justify-between\")}\n    >\n      <div className=\"ctw-space-x-3 ctw-flex ctw-flex-grow\">\n        <FontAwesomeIcon\n          icon={theme.icon}\n          className={cx(theme.iconColor, \"ctw-h-5 ctw-flex-none\")}\n        />\n        <div\n          className={cx(\n            theme.messageColor,\n            \"ctw-justify-between ctw-flex ctw-flex-grow ctw-text-sm ctw-font-medium\",\n            breakpoints.sm ? \"ctw-flex-col ctw-space-y-2\" : \"ctw-space-x-3\",\n          )}\n        >\n          <div>{payload.message}</div>\n          {payload.link && (\n            <a\n              href={payload.link}\n              className={cx(theme.linkHover, \"ctw-underline ctw-whitespace-nowrap\")}\n              target=\"_blank\"\n              rel=\"noreferrer\"\n            >\n              Learn More\n            </a>\n          )}\n        </div>\n      </div>\n      <FontAwesomeIcon\n        onClick={dismiss}\n        icon={faXmark}\n        className={cx(\n          theme.iconColor,\n          theme.iconHover,\n          \"ctw-flex-none ctw-cursor-pointer ctw-w-[22px] ctw-h-[22px] -ctw-mb-0.5\", // Negative bottom margin is to prevent the height from increasing the height of the aler box.\n        )}\n      />\n    </div>\n  );\n}\n\nfunction getDismissedAlerts() {\n  try {\n    const dismissedAlerts = localStorage.getItem(DISMISSED_ALERTS_KEY);\n    return dismissedAlerts ? JSON.parse(dismissedAlerts) : [];\n  } catch (e) {\n    return [];\n  }\n}\n","export default \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iMjIiIHZpZXdCb3g9IjAgMCA0MCAyMiIgZmlsbD0ibm9uZSIKICAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N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zkuMDgyMiAxNS40ODU0IDM4Ljg3NjcgMTUuNTcwNSAzOC40MTc4IDE1LjU3MDVIMzYuODcxM0MzNi40NDggMTUuNTcwNSAzNi4yNjcxIDE1LjUzMzQgMzUuOTY1OCAxNS4zNTIyTDM1LjI4OTEgMTQuOTQwNUwzNS42MTUxIDE0LjM0NzVMMzYuNDM3IDE0LjczNDZDMzYuNjA1NSAxNC44MDczIDM2LjcyNzQgMTQuODE5NyAzNi45NDM5IDE0LjgxOTdIMzguMzA5NkMzOC41NTA3IDE0LjgxOTcgMzguNiAxNC43OTUgMzguNzU2MiAxNC42NDk1TDM5LjA0NjYgMTQuMzU4NUMzOS4xOTE4IDE0LjIxMyAzOS4yMjc0IDE0LjE0MDMgMzkuMjI3NCAxMy45NDY4VjEzLjUyMjZDMzkuMjI3NCAxMy4yMDgzIDM5LjE0MjUgMTMuMDk4NSAzOC44MDQxIDEzLjA2MjhMMzYuNTY4NSAxMi44NTY5SDM2LjU2NzFaIiBmaWxsPSIjNUM1QzVDIi8+CiAgICA8L2c+CiAgICA8ZGVmcz4KICAgICAgICA8Y2xpcFBhdGggaWQ9ImNsaXAwXzI2M180NzQ1Ij4KICAgICAgICAgICAgPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjIxIiBmaWxsPSJ3aGl0ZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAwLjUpIi8+CiAgICAgICAgPC9jbGlwUGF0aD4KICAgIDwvZGVmcz4KPC9zdmc+\"","import cx from \"classnames\";\nimport { forwardRef } from \"react\";\nimport { usePatient } from \"@/index\";\n\nexport const PatientHeader = forwardRef<HTMLDivElement, { collapse: boolean }>(\n  ({ collapse }, ref) => {\n    const patient = usePatient();\n    return (\n      <div\n        className={cx(\n          \"ctw-flex ctw-h-full ctw-text-content-black ctw-w-fit\",\n          collapse\n            ? \"ctw-px-4 ctw-py-3 ctw-space-x-1 ctw-items-end\"\n            : \"ctw-flex-col ctw-px-5 ctw-py-2 ctw-whitespace-nowrap\",\n        )}\n        ref={ref}\n        data-testid=\"ctw-zap-patient-header\"\n      >\n        <div className=\"ctw-flex ctw-font-medium\">\n          <div className=\"ctw-min-w-fit ctw-space-x-1\">\n            <span>\n              {patient.data?.firstName} {patient.data?.lastName}\n            </span>\n            {patient.data?.gender && <span>({patient.data.gender[0].toUpperCase()})</span>}\n          </div>\n        </div>\n        <div className=\"ctw-text-sm ctw-whitespace-nowrap\">\n          {patient.data?.dob && patient.data.age && `${patient.data.dob} (${patient.data.age})`}\n        </div>\n      </div>\n    );\n  },\n);\n","import { createContext } from \"react\";\nimport { ZAPTabName } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile\";\n\ntype ZapTabStateContextType = {\n  selectedZapTabIndex: number;\n  setSelectedTab: (tabName: ZAPTabName | number) => void;\n  tabOrder: ZAPTabName[];\n  setTabOrder: (tabOrder: ZAPTabName[]) => void;\n};\n\nexport const ZapTabStateContext = createContext<ZapTabStateContextType>({\n  selectedZapTabIndex: 0,\n  setSelectedTab: () => {},\n  tabOrder: [],\n  setTabOrder: () => [],\n});\n","import type { PropsWithChildren } from \"react\";\n\nexport function RenderIf(props: PropsWithChildren<{ condition: boolean }>) {\n  const { condition, children } = props;\n  return <>{condition && children}</>;\n}\n","import \"./zap-tab-group.scss\";\n\nimport { Tab } from \"@headlessui/react\";\nimport cx from \"classnames\";\nimport { ReactNode, useContext, useEffect, useRef, useState } from \"react\";\nimport { PatientHeader } from \"./patient-header\";\nimport { ListBox } from \"../../../core/list-box/list-box\";\nimport { ZapTabStateContext } from \"../../../core/providers/zap-tab-state-context\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { RenderIf } from \"@/components/core/render-if\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\nexport type TabGroupProps = {\n  children?: ReactNode;\n  className?: string;\n  content: TabGroupItem[];\n  forceHorizontalTabs?: boolean;\n  onChange?: (index: number) => void; // optional event\n  topRightContent?: ReactNode;\n};\n\nexport type TabGroupItem = {\n  display: () => string | ReactNode;\n  key: string;\n  render: (sm: boolean) => string | ReactNode;\n};\n\n/**\n * When rendered in a small breakpoint the component will change from horizontal\n * tabs to a vertical dropdown menu. If this is undesired, you may set the\n * property `forceHorizontalTabs` to true and the tabs will remain visible and\n * horizontal.\n */\nfunction ZAPTabGroupComponent({\n  children,\n  className,\n  forceHorizontalTabs = false,\n  content,\n  onChange,\n  topRightContent,\n}: TabGroupProps) {\n  // State used for responsive tab dropdown menu.\n  const topRightContentRef = useRef<HTMLDivElement>(null);\n  const topLeftContentRef = useRef<HTMLDivElement>(null);\n  const moreMenuRef = useRef<HTMLDivElement>(null);\n  const containerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(containerRef);\n  const [tabOverflowCutoff, setTabOverflowCutoff] = useState(content.length);\n  const { selectedZapTabIndex, setSelectedTab, tabOrder } = useContext(ZapTabStateContext);\n\n  const { trackInteraction } = useAnalytics();\n  // Work around for not wanting to pre-mount all tabs.\n  // https://github.com/tailwindlabs/headlessui/issues/2276#issuecomment-1456537475\n  const [shown, setShown] = useState<Record<number, boolean>>({ 0: true });\n\n  // Calculate how many tabs can fit in the container,\n  useEffect(() => {\n    // Force everything into the more menu if we are in a small breakpoint,\n    // and we are not forcing horizontal tabs.\n    if (breakpoints.sm && !forceHorizontalTabs) {\n      setTabOverflowCutoff(0);\n      return;\n    }\n\n    const container = containerRef.current;\n    if (!container) return;\n\n    // Start with the width of the container.\n    let { width } = container.getBoundingClientRect();\n\n    // Subtract the corner content if there is any.\n    if (topRightContentRef.current) {\n      width -= topRightContentRef.current.getBoundingClientRect().width;\n    }\n    if (topLeftContentRef.current) {\n      width -= topLeftContentRef.current.getBoundingClientRect().width;\n    }\n\n    // Get width of the more menu and its spacing but don't subtract it yet.\n    const moreWidth = moreMenuRef.current?.getBoundingClientRect().width ?? 0;\n\n    // Grab our tabs and keep subtracting their widths until we run out of space.\n    const tabs = Array.from(container.querySelectorAll(\"button.ctw-tab\")) as HTMLButtonElement[];\n    setTabOverflowCutoff(\n      tabs.filter((tab, index) => {\n        // Subtract the tabs width and spacing for all but the first tab.\n        width -= tab.getBoundingClientRect().width;\n\n        // All but the last tab must reserve space for the more menu.\n        if (index < tabs.length - 1) {\n          return width >= moreWidth;\n        }\n\n        // The last tab can use the remaining space and ignore more menu\n        // as we'll not show more menu if we are displaying all tabs.\n        return width >= 0;\n      }).length,\n    );\n  }, [breakpoints, forceHorizontalTabs]); // Recalculate when the breakpoint changes (resize observer).\n\n  useEffect(() => {\n    setShown({ ...shown, [selectedZapTabIndex]: true });\n    onClickBlur();\n    trackInteraction(\"open_tab\", { value: tabOrder[selectedZapTabIndex] });\n    if (onChange) {\n      onChange(selectedZapTabIndex);\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [selectedZapTabIndex]);\n\n  const handleOnChange = (index: number) => {\n    setSelectedTab(index);\n    setShown({ ...shown, [index]: true });\n    if (onChange) {\n      onChange(index);\n    }\n  };\n\n  const showTopRightContent = !!topRightContent;\n  const shownContent = content.slice(tabOverflowCutoff);\n\n  return (\n    <div\n      ref={containerRef}\n      className={cx(className, \"ctw-zap-tab-group ctw-scrollable-pass-through-height ctw-w-full\")}\n    >\n      <Tab.Group selectedIndex={selectedZapTabIndex} onChange={handleOnChange}>\n        <div\n          className={cx(\n            \"ctw-flex ctw-border-b ctw-border-divider-main\",\n            tabOverflowCutoff === 0 ? \"ctw-flex-col\" : \"ctw-items-end\",\n          )}\n        >\n          <PatientHeader collapse={tabOverflowCutoff === 0} ref={topLeftContentRef} />\n          <div\n            className={cx(\n              \"ctw-w-full ctw-flex ctw-justify-between\",\n              \"ctw-border-divider-light ctw-border-default ctw-bg-white\",\n              tabOverflowCutoff === 0 &&\n                \"after:ctw-bg-content-black ctw-bg-white ctw-underline-light ctw-border-t ctw-border-default ctw-border-divider-light\",\n            )}\n          >\n            <Tab.List\n              className={cx(\n                \"ctw-flex\",\n                tabOverflowCutoff > 0 &&\n                  \"ctw-rounded-t-md ctw-border-t ctw-border-x ctw-border-divider-main\",\n              )}\n            >\n              {/* Renders button for each tab using \"display | display()\" */}\n              {content.map(({ key, display }, index) => (\n                <Tab\n                  key={key}\n                  onClick={() => {\n                    onClickBlur();\n                    trackInteraction(\"open_tab\", { value: key });\n                  }}\n                  className={({ selected }) =>\n                    cx(\n                      [\n                        \"ctw-tab ctw-whitespace-nowrap ctw-text-sm ctw-capitalize\",\n                        \"hover:after:ctw-bg-content-black\",\n                        \"focus-visible:ctw-outline-primary-dark focus-visible:after:ctw-bg-transparent\",\n                      ],\n                      {\n                        \"after:ctw-bg-content-black\": selected,\n                        \"ctw-text-content-light\": !selected,\n                      },\n                      { \"ctw-invisible !ctw-absolute\": index >= tabOverflowCutoff }, // Still render tab so we can derive width.\n                    )\n                  }\n                >\n                  <div className=\"ctw-divider-wrapper\">{display()}</div>\n                </Tab>\n              ))}\n\n              {/* More Button */}\n              <RenderIf condition={tabOverflowCutoff < content.length}>\n                <ListBox\n                  ref={moreMenuRef}\n                  selectedIndex={selectedZapTabIndex - tabOverflowCutoff}\n                  btnClassName={cx(\n                    \"ctw-more-tab ctw-text-sm ctw-whitespace-nowrap ctw-capitalize ctw-flex-shrink-0 ctw-h-full\",\n                    \"hover:after:ctw-bg-content-black\",\n                    {\n                      \"after:ctw-bg-content-black\": selectedZapTabIndex - tabOverflowCutoff >= 0,\n                    },\n                  )}\n                  optionsClassName={cx(\n                    \"ctw-tab-list ctw-capitalize\",\n                    !showTopRightContent && tabOverflowCutoff > 2 && \"ctw-right-0\", // Right-align dropdown if it is rightmost (and not leftmost)\n                  )}\n                  onChange={(index) => handleOnChange(index + tabOverflowCutoff)}\n                  items={shownContent}\n                >\n                  {tabOverflowCutoff !== 0 ? <span>More</span> : undefined}\n                </ListBox>\n              </RenderIf>\n            </Tab.List>\n            <div\n              className=\"ctw-px-1.5 ctw-flex ctw-flex-shrink-0 ctw-items-center ctw-whitespace-nowrap\"\n              ref={topRightContentRef}\n            >\n              {topRightContent}\n            </div>\n          </div>\n        </div>\n\n        {/* Children are always rendered and appear above the active panel */}\n        {children}\n\n        {/* Renders body of each tab using \"render()\" */}\n        <Tab.Panels className=\"ctw-scrollable-content ctw-bg-white ctw-px-4\">\n          {content.map((item, index) => (\n            <Tab.Panel\n              key={item.key}\n              className={cx(\"ctw-scrollable-pass-through-height\")}\n              // Don't unmount our tabs. This fixes an issue\n              // where ZAP filters/sort selections would get reset\n              // when switching to a new tab and back again.\n              unmount={false}\n            >\n              {shown[index] && item.render(breakpoints.sm)}\n            </Tab.Panel>\n          ))}\n        </Tab.Panels>\n      </Tab.Group>\n    </div>\n  );\n}\n\nexport const ZAPTabGroup = withErrorBoundary(ZAPTabGroupComponent, \"TabGroup\", false);\n\nfunction onClickBlur() {\n  if (typeof document !== \"undefined\") {\n    requestAnimationFrame(() => {\n      if (document.activeElement instanceof HTMLElement) {\n        document.activeElement.blur();\n      }\n    });\n  }\n}\n","import { UnreadNotificationIcon } from \"@/components/core/unread-notification-icon\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\n\nexport type UnreadConditionsNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadConditionsNotification = ({ className }: UnreadConditionsNotificationProps) => {\n  const query = usePatientConditionsAll();\n\n  const unreadOutsideRecords = query.data.filter(\n    (record) => !record.isDismissed && !record.isRead && !record.hasMatchingBuilderConditions,\n  );\n\n  if (unreadOutsideRecords.length > 0) {\n    return <UnreadNotificationIcon className={className} />;\n  }\n  return null;\n};\n","import cx from \"classnames\";\n\nexport type BetaLabelProps = {\n  className?: string;\n  hasData?: boolean;\n};\n\nexport const BetaLabel = ({ className, hasData = true }: BetaLabelProps) => (\n  <span\n    className={cx(\n      className,\n      \"ctw-relative ctw-bottom-1 ctw-break-keep ctw-text-[10px] ctw-uppercase\",\n      \"ctw-text-black\",\n      { \"ctw-text-content-lighter\": !hasData },\n    )}\n  >\n    beta\n  </span>\n);\n","// Codes taken from\n// https://docs.google.com/spreadsheets/d/18HfnrBAdwJhrZf1KS4Bb1LDpMlsXqJLGXPRZIB_pbnM\n\nexport const bpSystolicCodes = [\"8480-6\", \"8479-8\", \"8459-0\", \"8460-8\"];\n\nexport const bpDiastolicCodes = [\"8462-4\", \"8453-3\", \"8454-1\"];\n\nexport const heartRateCodes = [\"8867-4\", \"8893-0\"];\n\nexport const tempCodes = [\"8310-5\", \"8331-1\"];\n\nexport const respiratoryRateCodes = [\"9279-1\"];\n\nexport const o2Codes = [\n  \"59408-5\",\n  \"2710-2\",\n  \"2711-0\",\n  \"20564-1\",\n  \"59418-4\",\n  \"2709-4\",\n  \"59416-8\",\n  \"59408-5\",\n  \"19224-5\",\n];\n\nexport const heightCodes = [\"8302-2\", \"8306-3\", \"8301-4\", \"3138-5\"];\n\nexport const weightCodes = [\"29463-7\", \"3141-9\", \"79348-9\"];\n\nexport const bmiCodes = [\"39156-5\", \"41909-3\"];\n\nexport const headCircumferenceCodes = [\"9843-4\", \"8287-5\", \"1554118\"];\n\nexport const lmpCodes = [\"8665-2\", \"3145-0\"];\n\nexport const painCodes = [\"95627-6\", \"52500-6\", \"72514-3\"];\n\nexport const vitalLoincCodes = [\n  ...bpSystolicCodes,\n  ...bpDiastolicCodes,\n  ...heartRateCodes,\n  ...tempCodes,\n  ...respiratoryRateCodes,\n  ...o2Codes,\n  ...heightCodes,\n  ...weightCodes,\n  ...bmiCodes,\n  ...headCircumferenceCodes,\n  ...lmpCodes,\n  ...painCodes,\n];\n","import { gql } from \"graphql-request\";\nimport { GraphqlConnectionNode } from \"../client\";\nimport { ZAPTabName } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile\";\n\n// This is the current supported list of resources that can be queried for in the data indicator\nconst resourceNameMapping: Record<string, string> = {\n  \"conditions-all\": \"ConditionConnection\",\n  allergies: \"AllergyIntoleranceConnection\",\n  \"diagnostic-reports\": \"DiagnosticReportConnection\",\n  documents: \"DocumentReferenceConnection\",\n  encounters: \"EncounterConnection\",\n  immunizations: \"ImmunizationConnection\",\n  \"medications-all\": \"MedicationStatementConnection\",\n  vitals: \"ObservationConnection\",\n  sources: \"PatientConnection\",\n  \"care-team\": \"CareTeamConnection\",\n};\n\nexport function generateDataIndicatorQuery(zapTabNames: ZAPTabName[]) {\n  const activeFilters = zapTabNames\n    .map((tabName) => filters.filter((filter) => filter.tabName === tabName))\n    .filter(Boolean);\n\n  // Filter out any zap tabs that are not in the resourceNameMapping\n  const tabNames = zapTabNames.filter((resource) => resourceNameMapping[resource]);\n\n  const dataIndicatorQuery = gql`\n    query CombinedQuery(\n      $upid: ID!\n      $cursor: String!\n      $first: Int!\n      ${activeFilters\n        .map((filter) => filter.map((f) => `$${f.name}: ${f.type}!`).join(\"\\n\"))\n        .join(\"\\n\")}\n      ) {\n      ${tabNames\n        .map((resource: ZAPTabName) => {\n          const filterName = filters.find((filter) => filter.tabName === resource)?.name;\n          switch (resource) {\n            case \"sources\":\n              return generateQueryForPatientMatching(resourceNameMapping[resource], filterName);\n            default:\n              return generateQueryForGenericResource(resourceNameMapping[resource], filterName);\n          }\n        })\n        .join(\"\\n\")}\n    }\n  `;\n\n  return dataIndicatorQuery;\n}\n\nfunction generateQueryForPatientMatching(resource: string, filter?: string) {\n  return `\n    ${resource}: PatientConnection(\n      upid: $upid\n      after: $cursor\n      filter: $${filter}\n      ${filter ? `first: $PatientFirst` : \"\"}\n    ) {\n      edges {\n        node {\n          id\n          resourceType\n          meta {\n            tag {\n              system\n              code\n            }\n          }\n        }\n      }\n    }\n  `;\n}\n\nfunction generateQueryForGenericResource(resource: string, filter?: string) {\n  return `\n    ${resource}: ${resource}(\n      upid: $upid\n      after: $cursor\n      first: $first\n      ${filter ? `filter: $${filter}` : \"\"}\n    ) {\n      edges {\n        node {\n          id\n          resourceType\n        }\n      }\n    }\n  `;\n}\n\nexport type ResourceFilterKeys = Extract<ZAPTabName, \"sources\" | \"vitals\" | \"immunizations\">;\n\nconst filters: { tabName: ResourceFilterKeys; name: string; type: string }[] = [\n  { tabName: \"sources\", name: \"PatientFilter\", type: \"PatientFilterParams\" },\n  { tabName: \"sources\", name: \"PatientFirst\", type: \"Int\" },\n  { tabName: \"vitals\", name: \"ObservationFilter\", type: \"ObservationFilterParams\" },\n  { tabName: \"immunizations\", name: \"ImmunizationFilter\", type: \"ImmunizationFilterParams\" },\n];\n\ninterface Connection<T> {\n  edges: GraphqlConnectionNode<T>[];\n}\n\nexport type MinimalResourceGraphqlResponse = {\n  id: string;\n  resourceType: string;\n};\n\nexport interface DataIndicatorGraphqlResponse {\n  DiagnosticReportConnection: Connection<MinimalResourceGraphqlResponse>;\n  AllergyIntoleranceConnection: Connection<MinimalResourceGraphqlResponse>;\n  DocumentReferenceConnection: Connection<MinimalResourceGraphqlResponse>;\n  EncounterConnection: Connection<MinimalResourceGraphqlResponse>;\n  PatientConnection: Connection<MinimalResourceGraphqlResponse & { meta: fhir4.Patient[\"meta\"] }>;\n  CareTeamConnection: Connection<MinimalResourceGraphqlResponse>;\n  ObservationConnection: Connection<MinimalResourceGraphqlResponse>;\n  ConditionConnection: Connection<MinimalResourceGraphqlResponse>;\n  ImmunizationConnection: Connection<MinimalResourceGraphqlResponse>;\n  MedicationStatementConnection: Connection<MinimalResourceGraphqlResponse>;\n}\n","import { PatientModel } from \"./models\";\nimport {\n  createGraphqlClient,\n  CTWRequestContext,\n  fqsRequest,\n  MAX_OBJECTS_PER_REQUEST,\n  SYSTEM_LOINC,\n  SYSTEM_ZUS_OWNER,\n  useTimingQueryWithPatient,\n  ZAPTabName,\n} from \"..\";\nimport { vitalLoincCodes } from \"@/components/content/vitals/vital-loinc-codes\";\nimport {\n  DataIndicatorGraphqlResponse,\n  generateDataIndicatorQuery,\n} from \"@/services/fqs/queries/data-indicator\";\nimport { QUERY_KEY_DATA_INDICATORS } from \"@/utils/query-keys\";\n\nexport function useDataIndicators(\n  limit = MAX_OBJECTS_PER_REQUEST,\n  enabled = true,\n  resources: ZAPTabName[] = [],\n) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_DATA_INDICATORS,\n    [limit, resources],\n    async (requestContext, patient) => getDataIndicators(requestContext, patient, limit, resources),\n    enabled,\n  );\n}\n\nexport async function getDataIndicators(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  limit: number = MAX_OBJECTS_PER_REQUEST,\n  resources: ZAPTabName[] = [],\n) {\n  try {\n    const vitalCodes = vitalLoincCodes.map((loincCode) => `${SYSTEM_LOINC}|${loincCode}`);\n    const graphClient = createGraphqlClient(requestContext);\n    const dataIndicatorQuery = generateDataIndicatorQuery(resources);\n    const { data } = await fqsRequest<DataIndicatorGraphqlResponse>(\n      graphClient,\n      dataIndicatorQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: limit,\n        PatientFirst: MAX_OBJECTS_PER_REQUEST,\n        PatientFilter: {\n          tag: {\n            nonematch: [`${SYSTEM_ZUS_OWNER}|builder/${requestContext.builderId}`],\n          },\n        },\n        ObservationFilter: {\n          code: {\n            anymatch: vitalCodes,\n          },\n        },\n        ImmunizationFilter: {\n          status: {\n            eq: \"completed\",\n          },\n        },\n      },\n    );\n\n    return data;\n  } catch (e) {\n    throw new Error(`Failed fetching allergies by ID for patient ${patient.UPID}`);\n  }\n}\n","import { DefinedQueryObserverResult, QueryObserverLoadingErrorResult } from \"@tanstack/react-query\";\nimport cx from \"classnames\";\nimport { useContext } from \"react\";\nimport { ZAPTabName } from \"./zus-aggregated-profile/zus-aggregated-profile\";\nimport { BetaLabel } from \"../core/beta-label\";\nimport { usePatientContext } from \"../core/providers/patient-provider\";\nimport { ZapTabStateContext } from \"../core/providers/zap-tab-state-context\";\nimport { useDataIndicators } from \"@/fhir/data-indicator\";\nimport { SYSTEM_ZUS_UPI_RECORD_TYPE } from \"@/fhir/system-urls\";\nimport { DataIndicatorGraphqlResponse } from \"@/services/fqs/queries/data-indicator\";\n\nexport type ResourceHasData = {\n  className?: string;\n  resource: ZAPTabName;\n  text?: string;\n  isBeta?: boolean;\n};\n\nexport const DisplayCorrectTabLabel = ({ resource, text, isBeta }: ResourceHasData) => {\n  const recordsMap = useHasDataRecordsByResource();\n  const hasData = recordsMap.get(resource);\n\n  return (\n    <>\n      <span\n        className={cx(`ctw-capitalize ctw-text-black`, { \"ctw-text-content-lighter\": !hasData })}\n      >\n        {text}\n      </span>\n      {isBeta && <BetaLabel hasData={hasData} />}\n    </>\n  );\n};\n\n// Maps whether each ZAP resource has any unread notifications\nexport function useHasDataRecordsByResource(resources?: ZAPTabName[]): Map<ZAPTabName, boolean> {\n  const numRecordsToLookForData = 1;\n  usePatientContext(); // Require patient context\n  const { tabOrder } = useContext(ZapTabStateContext);\n  const finalResources = resources || tabOrder;\n  const query = useDataIndicators(\n    numRecordsToLookForData,\n    finalResources.length > 0,\n    finalResources,\n  );\n\n  const map = new Map<ZAPTabName, boolean>();\n  // Set all tabs to true by default so that when it is loading it will\n  // prompt the user to think that there is data.\n  // This is because we never want to incorrectly show that there is not data.\n  finalResources.forEach((zapTabName) => {\n    map.set(zapTabName, true);\n  });\n\n  if (!query.isLoading) {\n    finalResources.forEach((resource) => {\n      const data = handleResourceType(resource, query);\n      // Check if there data is available\n      if (data && data.length < 1) {\n        map.set(resource, false);\n      }\n    });\n  }\n\n  return map;\n}\n\nconst handleResourceType = (\n  resource: ZAPTabName,\n  query:\n    | DefinedQueryObserverResult<DataIndicatorGraphqlResponse, unknown>\n    | QueryObserverLoadingErrorResult<DataIndicatorGraphqlResponse, unknown>,\n) => {\n  switch (resource) {\n    case \"conditions-all\":\n      return query.data?.ConditionConnection.edges;\n    case \"allergies\":\n      return query.data?.AllergyIntoleranceConnection.edges;\n    case \"diagnostic-reports\":\n      return query.data?.DiagnosticReportConnection.edges;\n    case \"documents\":\n      return query.data?.DocumentReferenceConnection.edges;\n    case \"encounters\":\n      return query.data?.EncounterConnection.edges;\n    case \"immunizations\":\n      return query.data?.ImmunizationConnection.edges;\n    // Only gotcha here is that we don't filter out MedicationAdministration\n    case \"medications-all\":\n      return query.data?.MedicationStatementConnection.edges;\n    case \"vitals\":\n      return query.data?.ObservationConnection.edges;\n    case \"sources\":\n      return query.data?.PatientConnection.edges.filter(\n        (patient) =>\n          !patient.node.meta?.tag?.some(\n            (t) => t.system === SYSTEM_ZUS_UPI_RECORD_TYPE && t.code === \"universal\",\n          ),\n      );\n    case \"care-team\":\n      return query.data?.CareTeamConnection.edges;\n    default:\n      return [];\n  }\n};\n","import { faArrowTrendUp } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { DiagnosticReportModel } from \"@/fhir/models\";\n\nexport const patientDiagnosticReportsColumns = (\n  builderId: string,\n): TableColumn<DiagnosticReportModel>[] => [\n  {\n    title: \"Diagnostic\",\n    widthPercent: 40,\n    minWidth: 200,\n    render: (diagnostic) => (\n      <ResourceTitleColumn\n        title={diagnostic.displayName}\n        renderIcon={RenderOwnedByBuilderIcon(diagnostic.ownedByBuilder(builderId))}\n        capitalizeTitle={false}\n      />\n    ),\n  },\n  {\n    title: \"Date\",\n    dataIndex: \"effectiveStart\",\n    widthPercent: 20,\n    minWidth: 128,\n  },\n  {\n    widthPercent: 1,\n    minWidth: 32,\n    className: \"ctw-trend-indicator-cell\",\n    render: (diagnostic) =>\n      diagnostic.hasTrends ? <FontAwesomeIcon icon={faArrowTrendUp} /> : null,\n  },\n  {\n    title: \"Details\",\n    dataIndex: \"details\",\n    widthPercent: 39,\n    minWidth: 200,\n    className: \"ctw-details-cell\",\n  },\n];\n","import { dismissFilter } from \"../../resource/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\n\nexport function diagnosticReportFilter(): FilterItem[] {\n  return [dismissFilter];\n}\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { DiagnosticReportModel } from \"@/fhir/models\";\n\nexport const diagnosticReportSortOptions: SortOption<DiagnosticReportModel>[] = [\n  {\n    display: \"Date (New to Old)\",\n    sorts: [{ key: \"effectiveStart\", dir: \"desc\", isDate: true }],\n  },\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"effectiveStart\", dir: \"asc\", isDate: true }],\n  },\n  {\n    display: \"Name (A-Z)\",\n    sorts: [{ key: \"displayName\", dir: \"asc\" }],\n  },\n  {\n    display: \"Name (Z-A)\",\n    sorts: [{ key: \"displayName\", dir: \"desc\" }],\n  },\n];\n\nexport const defaultDiagnosticReportSort = diagnosticReportSortOptions[0];\n","export type BubbleIconProps = {\n  interpretation?: string;\n  result: string | number;\n  className?: string;\n};\n\nexport const BubbleIcon = ({ className, result, interpretation }: BubbleIconProps) =>\n  interpretation ? (\n    <div className={className}>\n      {result} - {interpretation}\n    </div>\n  ) : (\n    <div className={className}>{result}</div>\n  );\n","import { faArrowRight, faArrowTrendUp, faChevronRight } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport { useState } from \"react\";\nimport { BubbleIcon } from \"./bubble\";\nimport { useObservationsDetailsDrawer } from \"./drawer\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { ObservationModel } from \"@/fhir/models\";\n\nexport type ObservationTrendsProps = {\n  model: ObservationModel;\n};\n\nexport const ObservationTrends = ({ model }: ObservationTrendsProps) => {\n  const [isTrendsShown, setIsTrendsShown] = useState(false);\n  const openDiagnosticReportDetails = useObservationsDetailsDrawer();\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <AnalyticsProvider componentName=\"ObservationTrends\">\n      <div className=\"ctw-text-sm ctw-font-normal\">\n        {!model.isIncorrectlyCodedGlucose && model.trends && model.trends.length > 1 && (\n          <div className=\"ctw-pt-2\">\n            <button\n              aria-label=\"trends\"\n              className=\"ctw-btn-clear ctw-space-x-3\"\n              type=\"button\"\n              onClick={() => {\n                trackInteraction(\"toggle_trend\", {\n                  action: isTrendsShown ? \"collapse_trend\" : \"expand_trend\",\n                });\n                setIsTrendsShown(!isTrendsShown);\n              }}\n            >\n              <FontAwesomeIcon icon={faArrowTrendUp} />\n              <span>Trends</span>\n              <FontAwesomeIcon\n                icon={faChevronRight}\n                className={cx(\"ctw-h-3 ctw-w-3 ctw-pr-1\", {\n                  \"ctw-rotate-90\": isTrendsShown,\n                })}\n              />\n            </button>\n            {isTrendsShown &&\n              model.trends.map(\n                (trend) =>\n                  !trend.isIncorrectlyCodedGlucose && (\n                    <div\n                      tabIndex={0}\n                      role=\"button\"\n                      key={trend.id}\n                      className={cx(\"ctw-group/trends ctw-grid ctw-grid-cols-3 ctw-py-1 ctw-pl-4\", {\n                        \"ctw-cursor-pointer hover:ctw-bg-bg-lighter\": trend.diagnosticReport,\n                      })}\n                      onClick={() => {\n                        if (trend.diagnosticReport) {\n                          trackInteraction(\"open_diagnostic_report\", { target: \"btn\" });\n                          openDiagnosticReportDetails(trend.diagnosticReport);\n                        }\n                      }}\n                      onKeyDown={(e) => {\n                        if (e.key === \"Enter\" && trend.diagnosticReport) {\n                          trackInteraction(\"open_diagnostic_report\", { target: \"enter_key\" });\n                          openDiagnosticReportDetails(trend.diagnosticReport);\n                        }\n                      }}\n                    >\n                      <div\n                        className={cx(\"ctw-relative ctw-w-24 ctw-text-sm\", {\n                          \"ctw-font-semibold\": trend.id === model.id,\n                          \"group-hover/trends:ctw-underline\": trend.diagnosticReport,\n                        })}\n                      >\n                        {trend.effectiveStart}\n                      </div>\n                      <BubbleIcon\n                        result={trend.value}\n                        interpretation={trend.interpretation}\n                        className={cx(`${trend.acceptedInterpretations} ctw-w-fit`, {\n                          \"!ctw-font-semibold\": trend.id === model.id,\n                        })}\n                      />\n\n                      {trend.diagnosticReport && (\n                        <div className=\"ctw-justify-self-end\">\n                          <FontAwesomeIcon\n                            icon={faArrowRight}\n                            className=\"ctw-invisible ctw-pr-2 ctw-text-content-lighter group-hover/trends:ctw-visible\"\n                          />\n                        </div>\n                      )}\n                    </div>\n                  )\n              )}\n          </div>\n        )}\n      </div>\n    </AnalyticsProvider>\n  );\n};\n","import { BubbleIcon } from \"./bubble\";\nimport { ObservationTrends } from \"./trends\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { DiagnosticReportModel, ObservationModel } from \"@/fhir/models\";\nimport { capitalize } from \"@/utils/nodash\";\n\nexport const diagnosticReportColumns: TableColumn<DiagnosticReportModel>[] = [\n  {\n    title: \"Report\",\n    widthPercent: 30,\n    minWidth: 320,\n    dataIndex: \"displayName\",\n  },\n  {\n    title: \"Category\",\n    dataIndex: \"category\",\n  },\n  {\n    title: \"Started On\",\n    dataIndex: \"effectiveStart\",\n  },\n  {\n    title: \"Status\",\n    render: (model) => (\n      <div className=\"ctw-flex\">\n        <div className=\"ctw-ml-1\">\n          <div>{capitalize(model.resource.status)}</div>\n        </div>\n      </div>\n    ),\n  },\n  {\n    title: \"Observations\",\n    render: (model) => <div className=\"ctw-text-center\">{model.results.length}</div>,\n  },\n];\n\nexport const ObservationsColumns = (): TableColumn<ObservationModel>[] => [\n  {\n    title: \"Component\",\n    render: (model) => <div className=\"ctw-flex ctw-flex-wrap ctw-text-base\">{model.display}</div>,\n  },\n  {\n    title: \"Result\",\n    render: (model) => (\n      <div className=\"ctw-flex\">\n        <div className=\"ctw-text-sm ctw-font-normal\">\n          Result:{\" \"}\n          <BubbleIcon\n            interpretation={model.interpretation}\n            result={model.value}\n            className={model.acceptedInterpretations}\n          />\n        </div>\n      </div>\n    ),\n  },\n  {\n    title: \"Reference Range\",\n    render: (model) => (\n      <div className=\"ctw-flex ctw-text-sm ctw-font-normal\">\n        {model.referenceRange && (\n          <div className=\"ctw-font-normal\">\n            Reference Range: {model.referenceRange} {model.unit}\n          </div>\n        )}\n      </div>\n    ),\n  },\n  {\n    title: \"Trends\",\n    render: (model) => <ObservationTrends model={model} />,\n  },\n];\n","import { ObservationsColumns } from \"./columns\";\nimport { PatientResourceTable } from \"../../resource/patient-resource-table\";\nimport { ObservationModel } from \"@/fhir/models\";\n\nexport type ObservationsTableProps = {\n  className?: string;\n  data: ObservationModel[];\n};\n\nexport const ObservationsTable = ({ className, data }: ObservationsTableProps) => (\n  <div className={className}>\n    <div className=\"ctw-text-base ctw-font-medium ctw-uppercase ctw-text-content-black\">\n      Results\n    </div>\n    <PatientResourceTable\n      className=\"ctw-patient-observation-details\"\n      columns={ObservationsColumns()}\n      data={data}\n      emptyMessage=\"There are no observations available.\"\n      hidePagination\n    />\n  </div>\n);\n","import { useEffect, useState } from \"react\";\nimport { ResponsiveSourceDocumentLink } from \"@/components/content/CCDA/responsive-source-document-link\";\nimport { ObservationsTable } from \"@/components/content/observations/helpers/observations-table\";\nimport { DetailsCard } from \"@/components/content/resource/helpers/details-card\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { Loading } from \"@/components/core/loading\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { getBinaryId } from \"@/fhir/binaries\";\nimport { DiagnosticReportModel, ObservationModel } from \"@/fhir/models\";\nimport { searchProvenances } from \"@/fhir/provenance\";\nimport { compact } from \"@/utils/nodash\";\n\nexport type ObservationDetailsProps = {\n  diagnosticReport: DiagnosticReportModel;\n};\n\nexport const diagnosticReportData = (diagnosticReport: DiagnosticReportModel) => [\n  {\n    label: \"Effective Date\",\n    value: diagnosticReport.effectiveStart,\n  },\n  { label: \"Organization\", value: diagnosticReport.performer },\n];\n\nexport const ObservationDetailsComponent = ({ diagnosticReport }: ObservationDetailsProps) => {\n  const [observationEntries, setObservationsEntries] = useState<ObservationModel[]>([]);\n  const [isLoading, setIsLoading] = useState(false);\n  const [binaryId, setBinaryId] = useState<string>();\n  const { getRequestContext } = useCTW();\n\n  // We optionally look for any associated binary CCDAs\n  // if getSourceDocument is true.\n  useEffect(() => {\n    async function load() {\n      setIsLoading(true);\n      const requestContext = await getRequestContext();\n      const provenances = await searchProvenances(requestContext, [diagnosticReport]);\n      setBinaryId(getBinaryId(provenances, diagnosticReport.id));\n      setIsLoading(false);\n    }\n\n    void load();\n  }, [diagnosticReport, getRequestContext]);\n\n  useEffect(() => {\n    setObservationsEntries(compact(diagnosticReport.observations));\n  }, [diagnosticReport]);\n\n  return (\n    <div className=\"ctw-space-y-6\">\n      <div className=\"ctw-text-2xl\">{diagnosticReport.displayName}</div>\n\n      {isLoading ? (\n        <Loading message=\"Loading data...\" />\n      ) : (\n        <>\n          <DetailsCard\n            details={diagnosticReportData(diagnosticReport)}\n            documentButton={\n              <ResponsiveSourceDocumentLink\n                binaryId={binaryId}\n                documentTitle={diagnosticReport.resourceTypeTitle}\n                telemetryTarget=\"observation_details\"\n              />\n            }\n          />\n          <ObservationsTable data={observationEntries} />\n        </>\n      )}\n    </div>\n  );\n};\n\nexport const ObservationDetails = withErrorBoundary(ObservationDetailsComponent, \"Observations\");\n","import { useAdditionalResourceActions } from \"../../resource/use-additional-resource-actions\";\nimport { ObservationDetails } from \"@/components/content/observations/helpers/details\";\nimport { Drawer } from \"@/components/core/drawer\";\nimport { useDrawer } from \"@/components/core/providers/drawer-provider\";\nimport { DiagnosticReportModel } from \"@/fhir/models\";\n\nexport function useObservationsDetailsDrawer(enableDismissAndReadActions = true) {\n  const { openDrawer } = useDrawer();\n\n  return (diagnosticReport: DiagnosticReportModel) => {\n    openDrawer({\n      component: (props) => (\n        <ObservationsDrawer\n          diagnosticReport={diagnosticReport}\n          {...props}\n          enableDismissAndReadActions={enableDismissAndReadActions}\n        />\n      ),\n      trackingMetadata: { action: \"observations_details\" },\n    });\n  };\n}\n\nexport type ObservationsDrawerProps = {\n  className?: string;\n  diagnosticReport: DiagnosticReportModel;\n  enableDismissAndReadActions: boolean;\n  isOpen: boolean;\n  onClose: () => void;\n};\n\nfunction ObservationsDrawer({\n  className,\n  diagnosticReport,\n  enableDismissAndReadActions,\n  isOpen,\n  onClose,\n}: ObservationsDrawerProps) {\n  const ResourceActions = useAdditionalResourceActions({\n    enableDismissAndReadActions,\n  });\n\n  return (\n    <Drawer className={className} title=\"Diagnostic Report\" isOpen={isOpen} onClose={onClose}>\n      <Drawer.Body>\n        <ObservationDetails diagnosticReport={diagnosticReport} />\n      </Drawer.Body>\n      <Drawer.Footer>\n        <div className=\"ctw-flex ctw-justify-between\">\n          <Drawer.CloseButton onClose={onClose} label=\"Close\" />\n          <ResourceActions record={diagnosticReport} onSuccess={onClose} />\n        </div>\n      </Drawer.Footer>\n    </Drawer>\n  );\n}\n","import { ObservationModel } from \"../models\";\nimport { LOINC_ANALYTES } from \"../models/observation\";\nimport { SYSTEM_LOINC } from \"../system-urls\";\nimport { mapValues, uniqWith } from \"@/utils/nodash\";\n\nexport type TrendDataMap = Record<string, ObservationModel[] | undefined>;\n/**\n * Create a map from analyte to trends. This allows us to go from\n * diagnosticReport.result observations to their trends data by\n * looking up the observation's analytes.\n */\nexport const createTrendDataMap = (observations: ObservationModel[]): TrendDataMap => {\n  const trendData = observations\n    .filter((o) => {\n      if (!o.diagnosticReport) {\n        return true;\n      }\n\n      return !o.isIncorrectlyCodedGlucose;\n    })\n    // Sort here because the observations should be sorted in the drawer\n    .sort((a, b) => {\n      if (!a.effectiveStartRaw) {\n        return !b.effectiveStartRaw ? 0 : 1;\n      }\n      if (!b.effectiveStartRaw || a.effectiveStartRaw > b.effectiveStartRaw) {\n        return -1;\n      }\n      if (a.effectiveStartRaw < b.effectiveStartRaw) {\n        return 1;\n      }\n      return 0;\n    });\n\n  // Compute a map from analyte to trends\n  const trendDataMap: TrendDataMap = {};\n  trendData.forEach((o) => {\n    o.resource.code.coding?.forEach((coding) => {\n      if (coding.code && coding.system === SYSTEM_LOINC) {\n        const analyte = LOINC_ANALYTES[coding.code];\n        // Check if the analyte is in our list of analytes\n        if (analyte) {\n          if (!trendDataMap[analyte]) {\n            trendDataMap[analyte] = [];\n          }\n          trendDataMap[analyte]?.push(o);\n        }\n      }\n    });\n  });\n\n  return mapValues(trendDataMap, (v) => uniqWith(v, (a, b) => a.id === b.id));\n};\n","import { DiagnosticReport } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport {\n  fragmentBasic,\n  fragmentCoding,\n  fragmentObservation,\n  fragmentOrganization,\n  fragmentPatient,\n  fragmentPractitioner,\n} from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface DiagnosticReportConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<DiagnosticReportWithBasics>[];\n}\n\nexport type DiagnosticReportWithBasics = DiagnosticReport & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface DiagnosticReportGraphqlResponse {\n  DiagnosticReportConnection: DiagnosticReportConnection;\n}\n\nconst observationsProperties = gql`result {\n  reference\n  display\n  resource {\n    ...Observation\n  }\n}\ncontained {\n  resource {\n    ...Observation\n  }\n}`;\n\nexport const getDiagnosticReportQuery = (includeObservations: boolean) => gql`    \n  ${fragmentCoding}\n  ${fragmentOrganization}\n  ${fragmentPatient}\n  ${fragmentPractitioner}\n  ${fragmentBasic}\n  ${includeObservations ? fragmentObservation : \"\"}\n  query DiagnosticReports(\n    $upid: ID!\n    $cursor: String!\n    $sort: DiagnosticReportSortParams!\n    $filter: DiagnosticReportFilterParams!\n    $first: Int!\n  ) {\n    DiagnosticReportConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          BasicList(_reference: \"subject\") {\n            ...Basic\n          }\n          meta {\n            extension {\n              url\n              valueInstant\n            }\n          }\n          extension {\n            url\n            valueString\n          }\n          status\n          category {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          code {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          subject {\n            reference\n            resource {\n              ...Patient\n            }\n          }\n          effectiveDateTime\n          effectivePeriod {\n            start\n            end\n          }\n          issued\n          conclusion\n          performer {\n            reference\n            resource {\n              ...Practitioner\n            }\n          }\n          ${includeObservations ? observationsProperties : \"\"}\n        }\n      }\n    }\n  }\n`;\n","import { useEffect, useState } from \"react\";\nimport { createTrendDataMap } from \"./data-helper/diagnostic-report-trends\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useQueryWithPatient } from \"@/components/core/providers/patient-provider\";\nimport { DiagnosticReportModel, PatientModel } from \"@/fhir/models\";\nimport { createGraphqlClient, fqsRequest, MAX_OBJECTS_PER_REQUEST } from \"@/services/fqs/client\";\nimport {\n  DiagnosticReportGraphqlResponse,\n  getDiagnosticReportQuery,\n} from \"@/services/fqs/queries/diagnostic-reports-query\";\nimport { isEqual, uniqWith } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\n// Gets diagnostic reports for the patient with an option to include observations, though be aware that\n// including observations increases query time.\nexport function usePatientDiagnosticReports(\n  limit = MAX_OBJECTS_PER_REQUEST,\n  includeObservations = false,\n  enabled = true,\n) {\n  return useQueryWithPatient(\n    QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS,\n    [limit, includeObservations], // Only use the IDs in our key (fixes issue with ciruclar references).\n    getDiagnosticReports,\n    enabled,\n  );\n}\n\n// Gets diagnostic reports for the patient with trending data for each observation in the diagnostic report.\n// Each observation in the trend also includes a link back to its parent diagnostic report.\n// This is an expensive operation that consumes a lot of memory!\nexport function usePatientDiagnosticReportsWithTrendData(limit = MAX_OBJECTS_PER_REQUEST) {\n  const diagnosticReportsQuery = usePatientDiagnosticReports(limit, true);\n  const [diagnosticReportsWithTrends, setDiagnosticReportsWithTrends] = useState<\n    DiagnosticReportModel[]\n  >([]);\n\n  useEffect(() => {\n    const diagnosticReports = diagnosticReportsQuery.data;\n\n    if (diagnosticReportsQuery.isLoading) {\n      return;\n    }\n\n    const valuesToDedupeOn = (dr: DiagnosticReportModel) => [dr.displayName, dr.effectiveStart];\n    const uniqueDiagnosticReports = uniqWith(diagnosticReports, (a, b) =>\n      isEqual(valuesToDedupeOn(a), valuesToDedupeOn(b)),\n    );\n\n    const observations = uniqueDiagnosticReports.flatMap((dr) => dr.observations);\n    const trendDataMap = createTrendDataMap(observations);\n\n    observations.forEach((o) => {\n      o.setTrends(trendDataMap);\n    });\n\n    setDiagnosticReportsWithTrends(uniqueDiagnosticReports);\n  }, [diagnosticReportsQuery.data, diagnosticReportsQuery.isLoading]);\n\n  const { isLoading } = diagnosticReportsQuery;\n  const { isError } = diagnosticReportsQuery;\n  const { isFetching } = diagnosticReportsQuery;\n\n  return {\n    isLoading,\n    isError,\n    isFetching,\n    data: diagnosticReportsWithTrends,\n  };\n}\n\nasync function getDiagnosticReports(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  keys: (number|boolean)[] = [],\n) {\n  const [limit, includeObservations] = keys as [number, boolean];\n  try {\n    const data = await fetchDiagnosticReportsFromFQS(\n      requestContext,\n      patient,\n      limit,\n      includeObservations,\n    );\n    if (data.DiagnosticReportConnection.edges.length === 0) {\n      Telemetry.countMetric(`req.count.diagnostic_reports.none`, 1);\n    }\n    const result = data.DiagnosticReportConnection.edges.map(\n      (x) => new DiagnosticReportModel(x.node, undefined, x.node.BasicList),\n    );\n\n    Telemetry.histogramMetric(`req.count.diagnostic_reports`, result.length);\n    return result;\n  } catch (e) {\n    throw Telemetry.logError(e as Error, `Failed fetching DiagnosticReport resources`);\n  }\n}\n\nasync function fetchDiagnosticReportsFromFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  limit: number,\n  includeObservations: boolean,\n) {\n  const graphClient = createGraphqlClient(requestContext);\n  const { data } = await fqsRequest<DiagnosticReportGraphqlResponse>(\n    graphClient,\n    getDiagnosticReportQuery(includeObservations),\n    {\n      upid: patient.UPID,\n      cursor: \"\",\n      sort: {\n        lastUpdated: \"DESC\",\n      },\n      filter: {},\n      first: limit,\n    },\n  );\n  return data;\n}\n\nexport async function fetchDiagnosticReportsFromFQSById(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  ids: string[] = [],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<DiagnosticReportGraphqlResponse>(\n      graphClient,\n      getDiagnosticReportQuery(true),\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        filter: {\n          ids: {\n            anymatch: ids,\n          },\n        },\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n      },\n    );\n    return data.DiagnosticReportConnection.edges.map(\n      (x) => new DiagnosticReportModel(x.node, undefined, x.node.BasicList),\n    );\n  } catch (e) {\n    throw new Error(`Failed fetching document information for patient: ${e}`);\n  }\n}\n","import cx from \"classnames\";\nimport \"./diagnostic-reports.scss\";\nimport { patientDiagnosticReportsColumns } from \"./helpers/columns\";\nimport { diagnosticReportFilter } from \"./helpers/filters\";\nimport { defaultDiagnosticReportSort, diagnosticReportSortOptions } from \"./helpers/sorts\";\nimport { useObservationsDetailsDrawer } from \"../observations/helpers/drawer\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientDiagnosticReportsWithTrendData } from \"@/fhir/diagnostic-report\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS } from \"@/utils/query-keys\";\n\nexport type PatientDiagnosticReportsProps = {\n  className?: string;\n};\n\nfunction PatientDiagnosticReportsComponent({ className }: PatientDiagnosticReportsProps) {\n  const query = usePatientDiagnosticReportsWithTrendData();\n  const { data, filters, setFilters, setSort, defaultSort } = useFilteredSortedData({\n    cacheKey: \"patient-diagnostic-reports\",\n    defaultSort: defaultDiagnosticReportSort,\n    records: query.data,\n  });\n  const userBuilderId = useUserBuilderId();\n  const isEmptyQuery = query.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openDetails = useObservationsDetailsDrawer();\n\n  return (\n    <AnalyticsProvider componentName=\"PatientDiagnosticReports\">\n      <div\n        className={cx(className, \"ctw-scrollable-pass-through-height\", \"ctw-diagnostic-reports\")}\n      >\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: diagnosticReportFilter(),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: diagnosticReportSortOptions,\n            onChange: setSort,\n          }}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={query.isLoading}\n          data={data}\n          columns={patientDiagnosticReportsColumns(userBuilderId)}\n          onRowClick={openDetails}\n          enableDismissAndReadActions\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"diagnostics\"\n            />\n          }\n          queryKey={QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientDiagnosticReports = withErrorBoundary(\n  PatientDiagnosticReportsComponent,\n  \"PatientDiagnosticReports\",\n);\n","import { DocumentReference } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentBasic, fragmentCoding, fragmentOrganization } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface DocumentReferenceConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<DocumentReferenceWithBasics>[];\n}\n\nexport type DocumentReferenceWithBasics = DocumentReference & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface DocumentReferenceGraphqlResponse {\n  DocumentReferenceConnection: DocumentReferenceConnection;\n}\n\nexport const documentsQuery = gql`\n  ${fragmentCoding}\n  ${fragmentOrganization}\n  ${fragmentBasic}\n  query Documents(\n    $upid: ID!\n    $cursor: String!\n    $sort: DocumentReferenceSortParams!\n    $filter: DocumentReferenceFilterParams! = {}\n    $first: Int!\n  ) {\n    DocumentReferenceConnection(\n      upid: $upid\n      after: $cursor\n      sort: $sort\n      filter: $filter\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          BasicList(_reference: \"subject\") {\n            ...Basic\n          }\n          masterIdentifier {\n            system\n            use\n            value\n          }\n          meta {\n            extension {\n              url\n              valueInstant\n            }\n            tag {\n              system\n              code\n            }\n            versionId\n          }\n          extension {\n            url\n            valueString\n          }\n          status\n          docStatus\n          type {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          text {\n            id\n            div\n          }\n          category {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          date\n          custodian {\n            reference\n            resource {\n              ...Organization\n            }\n          }\n          description\n          content {\n            attachment {\n              contentType\n              language\n              data\n              url\n              size\n              hash\n              title\n              creation\n            }\n            format {\n              system\n              version\n              code\n              display\n            }\n          }\n          context {\n            period {\n              start\n              end\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n","import { useMemo } from \"react\";\nimport { PatientModel, useTimingQueryWithPatient } from \"..\";\nimport { applyDocumentFilters } from \"@/components/content/document/helpers/filters\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { DocumentModel } from \"@/fhir/models\";\nimport { createGraphqlClient, fqsRequest, MAX_OBJECTS_PER_REQUEST } from \"@/services/fqs/client\";\nimport { DocumentReferenceGraphqlResponse, documentsQuery } from \"@/services/fqs/queries/documents\";\nimport { orderBy } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_DOCUMENTS } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientTopLevelDocuments(limit = MAX_OBJECTS_PER_REQUEST, enabled = true) {\n  const { data, isError, isFetching, isLoading } = usePatientDocuments(limit, enabled);\n\n  const filteredData = useMemo(() => {\n    const filteredDocuments = orderBy(\n      applyDocumentFilters(data ?? []),\n      \"resource.content[0].attachment.creation\",\n      [\"desc\"],\n    ) as DocumentModel[];\n\n    // Telemetry logic (considering this does not produce side-effects on the UI, it's okay here)\n    if (!isFetching && !isLoading) {\n      if (filteredDocuments.length === 0) {\n        Telemetry.countMetric(\"req.count.documents.none\", 1);\n      }\n      Telemetry.histogramMetric(\"req.count.documents\", filteredDocuments.length);\n    }\n\n    return filteredDocuments;\n  }, [data, isFetching, isLoading]);\n\n  return {\n    data: filteredData,\n    isError,\n    isFetching,\n    isLoading,\n  };\n}\n\nexport function usePatientDocuments(limit = MAX_OBJECTS_PER_REQUEST, enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_DOCUMENTS,\n    [limit],\n    getDocumentsFromFQS,\n    enabled,\n  );\n}\n\nasync function getDocumentsFromFQS (requestContext: CTWRequestContext, patient: PatientModel, keys: number[] = []) {\n  try {\n    const limit = keys[0];\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<DocumentReferenceGraphqlResponse>(\n      graphClient,\n      documentsQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: limit,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n      },\n    );\n    return data.DocumentReferenceConnection.edges.map(\n      (x) => new DocumentModel(x.node, undefined, x.node.BasicList),\n    );\n  } catch (e) {\n    throw new Error(`Failed fetching document information for patient: ${e}`);\n  }\n}\n\nexport async function getDocumentsByIdFromFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  ids: string[] = [],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<DocumentReferenceGraphqlResponse>(\n      graphClient,\n      documentsQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        filter: {\n          ids: {\n            anymatch: ids,\n          },\n        },\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n      },\n    );\n    return data.DocumentReferenceConnection.edges.map((x) => new DocumentModel(x.node));\n  } catch (e) {\n    throw new Error(`Failed fetching document information for patient: ${e}`);\n  }\n}\n","import { faClipboardCheck } from \"@fortawesome/free-solid-svg-icons\";\nimport { dismissFilter } from \"../../resource/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\nimport { SYSTEM_LOINC } from \"@/fhir/system-urls\";\nimport { PredicateMap } from \"@/hooks/use-filtered-sorted-data\";\nimport { compact, mergeWith, uniq } from \"@/utils/nodash\";\n\nexport const noteTypeValues = [\n  {\n    name: \"Assessments / Plans\",\n    key: [\"51847-2\", \"18776-5\"].join(\",\"),\n  },\n  {\n    name: \"Diagnostic Narratives\",\n    key: [\"34109-9\", \"30954-2\"].join(\",\"),\n  },\n  {\n    name: \"Discharge Summary\",\n    key: \"18842-5\",\n  },\n  {\n    name: \"History of Present Illness\",\n    key: \"10164-2\",\n  },\n  {\n    name: \"Reason for Visit\",\n    key: \"29299-5\",\n  },\n];\n\nexport const encounterFilterPredicates: PredicateMap = {\n  type: (values, item) => encounterTypePredicate(values, item as EncounterModel),\n  noteType: noteTypePredicate,\n};\n\nexport function encounterFilters(encounters: EncounterModel[] | undefined): FilterItem[] {\n  const filters: FilterItem[] = [\n    dismissFilter,\n    {\n      key: \"type\",\n      type: \"checkbox\",\n      icon: faClipboardCheck,\n      predicate: encounterFilterPredicates.type,\n      display: \"Encounter Type\",\n      values: compact(uniq(encounters?.map((e) => e.typeDisplay))),\n    },\n  ];\n\n  const availableNoteTypeValues = noteTypeValues.filter(\n    (value) => encounters?.some((encounter) => noteTypePredicate([value.key], encounter)),\n  );\n  const hasOtherEncounterNoteTypes =\n    encounters &&\n    encounters.filter(\n      (encounter) => !noteTypeValues.some((value) => noteTypePredicate([value.key], encounter)),\n    ).length > 0;\n\n  if (availableNoteTypeValues.length > 0 || hasOtherEncounterNoteTypes) {\n    filters.push({\n      key: \"noteType\",\n      type: \"checkbox\",\n      icon: faClipboardCheck,\n      display: \"Note Type\",\n      predicate: encounterFilterPredicates.nodeType,\n      values: compact([\n        ...availableNoteTypeValues,\n        hasOtherEncounterNoteTypes\n          ? {\n              name: \"Other\",\n              key: \"other\",\n            }\n          : undefined,\n      ]),\n    });\n  }\n\n  return filters;\n}\n\n// Dedupes encounters by patient, periodStart, class, type, and location.\n// Merges their properties to maximize information.\nexport function dedupeAndMergeEncounters(encounters: EncounterModel[]): EncounterModel[] {\n  // Group up the encounters that need to be merged\n  const dupeGroups = new Map<string, EncounterModel[]>();\n\n  encounters.forEach((encounter, i) => {\n    const key: string = JSON.stringify({\n      upid: encounter.patientUPID,\n      periodStart: encounter.periodStart || \"\",\n      class: encounter.resource.class,\n      type: encounter.resource.type,\n      location: encounter.location || \"\",\n    });\n    const val = dupeGroups.get(key);\n\n    if (\n      !(\n        encounter.patientUPID &&\n        encounter.periodStart &&\n        encounter.resource.type &&\n        encounter.location\n      )\n    ) {\n      dupeGroups.set(key + i, [encounter]); // If it's missing values, put it in a lone group.\n    } else if (val) {\n      val.push(encounter);\n    } else {\n      dupeGroups.set(key, [encounter]);\n    }\n  });\n\n  return mergeEncounters(dupeGroups);\n}\n\nfunction mergeEncounters(dupeGroups: Map<string, EncounterModel[]>): EncounterModel[] {\n  const dedupedEncounters: EncounterModel[] = [];\n\n  dupeGroups.forEach((encs) => {\n    // If there's only one encounter in the group, no need to merge\n    if (encs.length === 1) {\n      dedupedEncounters.push(encs[0]);\n      return;\n    }\n    // Sort them to prioritize the most recently updated encounter\n    encs.sort((a, b) => {\n      const aVal = a.lastUpdated ? new Date(a.lastUpdated).valueOf() : 0;\n      const bVal = b.lastUpdated ? new Date(b.lastUpdated).valueOf() : 0;\n      return aVal - bVal;\n    });\n    const mergedEncounter: EncounterModel = encs[0];\n\n    if (encs.length > 1) {\n      const sortedEncResources = encs.map((enc) => enc.resource);\n      // Merge the encounters\n      mergedEncounter.resource = sortedEncResources.reduce((merged, curr) =>\n        mergeWith(merged, curr),\n      );\n    }\n    dedupedEncounters.push(mergedEncounter);\n  });\n\n  return dedupedEncounters;\n}\n\nexport function noteTypePredicate(values: string[], item: object): boolean {\n  if (values.length === 0) return true;\n\n  // Values can contain comma separated values, so we need to split them.\n  const parsedValues = values.flatMap((value) => value.split(\",\"));\n  const parsedAllValues = noteTypeValues.flatMap((v) => v.key.split(\",\"));\n\n  const encounter = item as EncounterModel;\n  const hasValueMatch = encounter.clinicalNotes.some((note) =>\n    note.category.some(\n      (category) =>\n        category.coding?.some(\n          (coding) =>\n            coding.system === SYSTEM_LOINC && coding.code && parsedValues.includes(coding.code),\n        ),\n    ),\n  );\n  const hasOtherMatch =\n    parsedValues.includes(\"other\") &&\n    !encounter.clinicalNotes.some((note) =>\n      note.category.some(\n        (category) =>\n          category.coding?.some(\n            (coding) =>\n              coding.system === SYSTEM_LOINC &&\n              coding.code &&\n              parsedAllValues.includes(coding.code),\n          ),\n      ),\n    );\n  return hasValueMatch || hasOtherMatch;\n}\nexport function encounterTypePredicate(values: string[], encounter: EncounterModel): boolean {\n  if (values.length === 0) return true;\n  if (encounter.typeDisplay) {\n    return values.includes(encounter.typeDisplay);\n  }\n  return false;\n}\n","import { gql } from \"graphql-request\";\nimport { fragmentCoding } from \"../fragments\";\n\nexport const fragmentCodeableConcept = gql`\n  ${fragmentCoding}\n\n  fragment CodeableConcept on CodeableConcept {\n    text\n    coding {\n      ...Coding\n    }\n  }\n`;\n","import { gql } from \"graphql-request\";\nimport { fragmentCodeableConcept } from \"./codeable-concept\";\nimport { fragmentBasic, fragmentReference } from \"../fragments\";\n\nexport const fragmentEncounter = gql`\n  ${fragmentCodeableConcept}\n  ${fragmentReference}\n  ${fragmentBasic}\n\n  fragment Encounter on Encounter {\n    id\n    resourceType\n    BasicList(_reference: \"subject\") {\n      ...Basic\n    }\n    meta {\n      tag {\n        system\n        code\n      }\n      versionId\n    }\n    extension {\n      url\n      valueString\n    }\n    status\n    class {\n      system\n      version\n      code\n      display\n    }\n    type {\n      ...CodeableConcept\n    }\n    serviceType {\n      ...CodeableConcept\n    }\n    priority {\n      ...CodeableConcept\n    }\n    diagnosis {\n      condition {\n        reference\n        display\n      }\n    }\n    participant {\n      individual {\n        reference\n        display\n      }\n      type {\n        ...CodeableConcept\n      }\n      period {\n        start\n        end\n      }\n    }\n    period {\n      start\n      end\n    }\n    ProvenanceList(_reference: \"target\") {\n      id\n      entity {\n        what {\n          ...Reference\n        }\n      }\n    }\n    length {\n      value\n      unit\n    }\n    reasonCode {\n      ...CodeableConcept\n    }\n    hospitalization {\n      dischargeDisposition {\n        ...CodeableConcept\n      }\n    }\n    location {\n      location {\n        reference\n        display\n        resource {\n          ... on Location {\n            name\n            type {\n              ...CodeableConcept\n            }\n          }\n        }\n      }\n      status\n      period {\n        start\n        end\n      }\n    }\n  }\n`;\n","import { Encounter } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentEncounter } from \"./fragments/encounter\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface EncounterConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<EncounterWithReferences>[];\n}\n\nexport type EncounterWithReferences = Encounter & {\n  ProvenanceList: fhir4.Provenance[];\n  BasicList: fhir4.Basic[];\n};\n\nexport interface EncounterGraphqlResponse {\n  EncounterConnection: EncounterConnection;\n}\n\nexport const encountersQuery = gql`\n  ${fragmentEncounter}\n  query Encounters(\n    $upid: ID!\n    $cursor: String!\n    $sort: EncounterSortParams!\n    $first: Int!\n    $filter: EncounterFilterParams! = {}\n  ) {\n    EncounterConnection(upid: $upid, after: $cursor, sort: $sort, first: $first, filter: $filter) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          ...Encounter\n        }\n      }\n    }\n  }\n`;\n","import { useEffect, useState } from \"react\";\nimport { usePatientDocuments } from \"./document\";\nimport { PatientModel } from \"./models\";\nimport { useTimingQueryWithPatient } from \"..\";\nimport { dedupeAndMergeEncounters } from \"@/components/content/encounters/helpers/filters\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { EncounterModel } from \"@/fhir/models\";\nimport { createGraphqlClient, fqsRequest, MAX_OBJECTS_PER_REQUEST } from \"@/services/fqs/client\";\nimport { EncounterGraphqlResponse, encountersQuery } from \"@/services/fqs/queries/encounters\";\nimport { QUERY_KEY_PATIENT_ENCOUNTERS } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function getEncountersFromFQS(limit: number, ids?: string[]) {\n  return async (requestContext: CTWRequestContext, patient: PatientModel) => {\n    // Skip querying for an empty set of ids.\n    // This fixes an issue with FQS where it is an error to do an anymatch with an empty array.\n    if (ids !== undefined && ids.length === 0) {\n      return [];\n    }\n\n    try {\n      const graphClient = createGraphqlClient(requestContext);\n      const { data } = await fqsRequest<EncounterGraphqlResponse>(graphClient, encountersQuery, {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: limit,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        // Optionally filter down to a specific set of encounters.\n        filter: ids\n          ? {\n              ids: { anymatch: ids },\n            }\n          : {},\n      });\n      const nodes = data.EncounterConnection.edges.map((x) => x.node);\n      const results = nodes.map(\n        (c) => new EncounterModel(c, c.ProvenanceList, undefined, c.BasicList),\n      );\n      if (results.length === 0) {\n        Telemetry.countMetric(\"req.count.encounters.none\", 1);\n      }\n      Telemetry.histogramMetric(\"req.count.encounters\", results.length);\n      return dedupeAndMergeEncounters(results);\n    } catch (e) {\n      Telemetry.logError(e as Error, \"Failed fetching encounter timeline information for patient\");\n      throw new Error(`Failed fetching encounter timeline information for patient: ${e}`);\n    }\n  };\n}\n\nexport function usePatientEncounters(limit = MAX_OBJECTS_PER_REQUEST, enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_ENCOUNTERS,\n    [limit],\n    getEncountersFromFQS(limit),\n    enabled,\n  );\n}\n\n// Gets patient encounters along with clinical notes from any documents associated with each encounter.\nexport function usePatientEncountersWithClinicalNotes(limit = MAX_OBJECTS_PER_REQUEST) {\n  const documentsQuery = usePatientDocuments();\n  const encounterQuery = usePatientEncounters(limit);\n  const [encountersWithClinicalNotes, setEncountersWithClinicalNotes] = useState<EncounterModel[]>(\n    [],\n  );\n\n  useEffect(() => {\n    const documents = documentsQuery.data ?? [];\n    const encounters = encounterQuery.data ?? [];\n\n    if (documents.length > 0) {\n      setEncountersWithClinicalNotes(\n        encounters.map((encounter) => {\n          const model = new EncounterModel(\n            encounter.resource,\n            encounter.provenance,\n            undefined,\n            encounter.basics,\n          );\n          model.findAndSetNotesFrom(documents);\n          return model;\n        }),\n      );\n    } else {\n      setEncountersWithClinicalNotes(encounters);\n    }\n  }, [documentsQuery.data, encounterQuery.data]);\n\n  const isLoading = documentsQuery.isLoading || encounterQuery.isLoading;\n  const isError = documentsQuery.isError || encounterQuery.isError;\n  const isFetching = documentsQuery.isFetching || encounterQuery.isFetching;\n\n  return {\n    isLoading,\n    isError,\n    isFetching,\n    data: encountersWithClinicalNotes,\n  };\n}\n","export const quantityLabel = (quantity?: fhir4.Quantity): string =>\n  quantity?.value ? `${quantity.value} ${quantity.unit}` : \"\";\n","import { FHIRModel } from \"./fhir-model\";\nimport { codeableConceptLabel, findCoding } from \"../codeable-concept\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { quantityLabel } from \"../quantity\";\nimport { findReference } from \"../resource-helper\";\nimport { SYSTEM_CVX } from \"../system-urls\";\nimport { capitalize } from \"@/utils/nodash\";\n\nexport class ImmunizationModel extends FHIRModel<fhir4.Immunization> {\n  kind = \"Immunization\" as const;\n\n  get description(): string | undefined {\n    return this.resource.vaccineCode.text;\n  }\n\n  get cvxCode(): string | undefined {\n    const cvxCoding = findCoding(SYSTEM_CVX, this.resource.vaccineCode);\n    return cvxCoding?.code;\n  }\n\n  // String used to define a unique instance of an immunization administered for a patient.\n  get uniqueKey(): string {\n    return `${this.cvxCode || this.description} - ${this.occurrence}`;\n  }\n\n  get doseQuantity(): string {\n    return quantityLabel(this.resource.doseQuantity);\n  }\n\n  get route(): string {\n    return codeableConceptLabel(this.resource.route);\n  }\n\n  get site(): string {\n    return codeableConceptLabel(this.resource.site);\n  }\n\n  get status(): string {\n    return capitalize(this.resource.status);\n  }\n\n  get notesDisplay(): string[] {\n    return this.resource.note?.map(({ text }) => text) || [];\n  }\n\n  get occurrence(): string | undefined {\n    if (this.resource.occurrenceDateTime) {\n      return formatDateISOToLocal(this.resource.occurrenceDateTime);\n    }\n\n    return this.resource.occurrenceString;\n  }\n\n  get managingOrganization(): string | undefined {\n    const organizationDisplay = findReference(\n      \"Patient\",\n      this.resource.contained,\n      this.includedResources,\n      this.resource.patient,\n    );\n\n    const organizationName = findReference(\n      \"Organization\",\n      this.resource.contained,\n      this.includedResources,\n      organizationDisplay?.managingOrganization,\n    )?.name;\n\n    return organizationDisplay?.managingOrganization?.display || organizationName;\n  }\n\n  get title() {\n    return this.description ?? \"Unknown Immunization\";\n  }\n}\n","import { Immunization } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentBasic, fragmentCoding, fragmentOrganization, fragmentPatient } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface ImmunizationConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<ImmunizationWithBasics>[];\n}\n\nexport type ImmunizationWithBasics = Immunization & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface ImmunizationGraphqlResponse {\n  ImmunizationConnection: ImmunizationConnection;\n}\n\nexport const immunizationsQuery = gql`\n  ${fragmentCoding}\n  ${fragmentOrganization}\n  ${fragmentPatient}\n  ${fragmentBasic}\n  query Immunizations($upid: ID!, $cursor: String!, $sort: ImmunizationSortParams!, $first: Int!) {\n    ImmunizationConnection(upid: $upid, after: $cursor, sort: $sort, first: $first) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          BasicList(_reference: \"subject\") {\n            ...Basic\n          }\n          meta {\n            tag {\n              system\n              code\n            }\n            versionId\n          }\n          extension {\n            url\n            valueString\n          }\n          status\n          statusReason {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          vaccineCode {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          patient {\n            reference\n            resource {\n              ... on Patient {\n                ...Patient\n                managingOrganization {\n                  resource {\n                    ... on Organization {\n                      name\n                    }\n                  }\n                }\n              }\n            }\n          }\n          occurrenceDateTime\n          occurrenceString\n          recorded\n          lotNumber\n          expirationDate\n        }\n      }\n    }\n  }\n`;\n","import { PatientModel } from \"./models\";\nimport { ImmunizationModel } from \"./models/immunization\";\nimport { useTimingQueryWithPatient } from \"..\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport {\n  ImmunizationGraphqlResponse,\n  immunizationsQuery,\n  ImmunizationWithBasics,\n} from \"@/services/fqs/queries/immunizations\";\nimport { orderBy, uniqBy } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_IMMUNIZATIONS } from \"@/utils/query-keys\";\nimport { sort } from \"@/utils/sort\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientImmunizations(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_IMMUNIZATIONS,\n    [],\n    getImmunizationFromFQS,\n    enabled,\n  );\n}\n\nasync function getImmunizationFromFQS(requestContext: CTWRequestContext, patient: PatientModel) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<ImmunizationGraphqlResponse>(\n      graphClient,\n      immunizationsQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n      },\n    );\n    const nodes = data.ImmunizationConnection.edges.map((x) => x.node);\n    const results = getFilteredImmunizations(nodes, requestContext.builderId);\n    if (results.length === 0) {\n      Telemetry.countMetric(\"req.count.immunizations.none\");\n    }\n    Telemetry.histogramMetric(\"req.count.immunizations\", results.length);\n    return results;\n  } catch (e) {\n    throw new Error(`Failed fetching immunization information for patient: ${e}`);\n  }\n}\n\nexport const getFilteredImmunizations = (data: ImmunizationWithBasics[], builderId: string) => {\n  const immunizations = data.map(\n    (immunization) => new ImmunizationModel(immunization, undefined, immunization.BasicList),\n  );\n\n  const sortedByDate = sort(\n    immunizations.filter((x) => x.status === \"Completed\"),\n    \"occurrence\",\n    \"desc\",\n    true,\n  );\n\n  // Bump builder owned allergies to the front, so uniqBy favors them!\n  const builderOwnedFirst = orderBy(sortedByDate, (a) => a.ownedByBuilder(builderId), \"desc\");\n  return uniqBy(builderOwnedFirst, \"uniqueKey\");\n};\n","import { MedicationAdministration } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentCoding } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface MedicationAdministrationConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<MedicationAdministration>[];\n}\n\nexport interface MedicationAdministrationGraphqlResponse {\n  MedicationAdministrationConnection: MedicationAdministrationConnection;\n}\n\nexport const medicationAdministrationQuery = gql`\n  ${fragmentCoding}\n  query MedicationAdministrations(\n    $upid: ID!\n    $cursor: String!\n    $filter: MedicationAdministrationFilterParams!\n    $sort: MedicationAdministrationSortParams!\n    $first: Int!\n  ) {\n    MedicationAdministrationConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          extension {\n            url\n            valueString\n          }\n          dosage {\n            text\n            dose {\n              value\n              unit\n            }\n            route {\n              text\n              coding {\n                ...Coding\n              }\n            }\n          }\n          effectivePeriod {\n            start\n            end\n          }\n        }\n      }\n    }\n  }\n`;\n","import { MedicationDispense } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentCoding } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface MedicationDispenseConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<MedicationDispense>[];\n}\n\nexport interface MedicationDispenseGraphqlResponse {\n  MedicationDispenseConnection: MedicationDispenseConnection;\n}\n\nexport const medicationDispenseQuery = gql`\n  ${fragmentCoding}\n  query MedicationDispenses(\n    $upid: ID!\n    $cursor: String!\n    $filter: MedicationDispenseFilterParams!\n    $sort: MedicationDispenseSortParams!\n    $first: Int!\n  ) {\n    MedicationDispenseConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          extension {\n            url\n            valueString\n            valueInstant\n          }\n          contained {\n            resource {\n              ... on Practitioner {\n                id\n                resourceType\n                name {\n                  family\n                  given\n                }\n                address {\n                  text\n                }\n                telecom {\n                  value\n                }\n              }\n              ... on Organization {\n                id\n                resourceType\n                _organization__name: name\n                telecom {\n                  value\n                }\n                address {\n                  city\n                  state\n                  postalCode\n                  text\n                  line\n                }\n              }\n            }\n          }\n          performer {\n            actor {\n              id\n              extension {\n                url\n                valueString\n              }\n              reference\n              type\n              identifier {\n                id\n                system\n                value\n              }\n              display\n              resource {\n                ... on Organization {\n                  id\n                  resourceType\n                  name\n                  telecom {\n                    value\n                  }\n                  address {\n                    city\n                    state\n                    postalCode\n                    text\n                    line\n                  }\n                }\n              }\n            }\n          }\n          status\n          quantity {\n            value\n            unit\n          }\n          medicationCodeableConcept {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          daysSupply {\n            value\n            unit\n          }\n          whenHandedOver\n          whenPrepared\n        }\n      }\n    }\n  }\n`;\n","import { MedicationRequest } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentCoding, fragmentReference } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface MedicationRequestConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<MedicationRequest>[];\n}\n\nexport interface MedicationRequestGraphqlResponse {\n  MedicationRequestConnection: MedicationRequestConnection;\n}\n\nexport const medicationRequestQuery = gql`\n  ${fragmentCoding}\n  ${fragmentReference}\n  query MedicationRequests(\n    $upid: ID!\n    $cursor: String!\n    $filter: MedicationRequestFilterParams!\n    $sort: MedicationRequestSortParams!\n    $first: Int!\n  ) {\n    MedicationRequestConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          extension {\n            url\n            valueString\n          }\n          authoredOn\n          contained {\n            resource {\n              ... on Practitioner {\n                id\n                resourceType\n                name {\n                  family\n                  given\n                }\n                address {\n                  text\n                }\n                telecom {\n                  value\n                }\n              }\n              ... on Organization {\n                id\n                resourceType\n                _organization__name: name\n                telecom {\n                  value\n                }\n                address {\n                  city\n                  state\n                  postalCode\n                  text\n                  line\n                }\n              }\n            }\n          }\n          dispenseRequest {\n            performer {\n              id\n              extension {\n                url\n                valueString\n              }\n              reference\n              type\n              identifier {\n                id\n                system\n                value\n              }\n              display\n              resource {\n                ... on Organization {\n                  id\n                  resourceType\n                  name\n                  telecom {\n                    value\n                  }\n                  address {\n                    city\n                    state\n                    postalCode\n                    text\n                    line\n                  }\n                }\n              }\n            }\n            numberOfRepeatsAllowed\n            initialFill {\n              quantity {\n                value\n                unit\n              }\n            }\n          }\n          dosageInstruction {\n            text\n            timing {\n              repeat {\n                boundsPeriod {\n                  start\n                }\n              }\n            }\n          }\n          medicationCodeableConcept {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          performer {\n            ...Reference\n          }\n          requester {\n            id\n            extension {\n              url\n              valueString\n            }\n            reference\n            type\n            identifier {\n              id\n              system\n              value\n            }\n            display\n            resource {\n              ... on Practitioner {\n                id\n                resourceType\n                name {\n                  family\n                  given\n                }\n                address {\n                  text\n                }\n                telecom {\n                  value\n                }\n              }\n            }\n          }\n          status\n        }\n      }\n    }\n  }\n`;\n","import { MedicationStatement } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentBasic, fragmentCoding, fragmentReference } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface MedicationStatementConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<MedicationStatementWithBasics>[];\n}\n\nexport type MedicationStatementWithBasics = MedicationStatement & {\n  BasicList: fhir4.Basic[];\n};\n\nexport interface MedicationStatementGraphqlResponse {\n  MedicationStatementConnection: MedicationStatementConnection;\n}\n\nexport const medicationStatementQuery = gql`\n  ${fragmentCoding}\n  ${fragmentReference}\n  ${fragmentBasic}\n  query MedicationStatements(\n    $upid: ID!\n    $cursor: String!\n    $filter: MedicationStatementFilterParams!\n    $sort: MedicationStatementSortParams!\n    $first: Int!\n  ) {\n    MedicationStatementConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          BasicList(_reference: \"subject\") {\n            ...Basic\n          }\n          meta {\n            tag {\n              system\n              code\n            }\n            versionId\n          }\n          extension {\n            url\n            extension {\n              url\n              valueReference {\n                id\n                type\n                reference\n              }\n            }\n            valueDateTime\n            valueString\n            valueReference {\n              id\n              type\n              reference\n              display\n            }\n            valueQuantity {\n              unit\n              value\n            }\n            valueUnsignedInt\n          }\n          basedOn {\n            type\n          }\n          category {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          contained {\n            resource {\n              ... on Practitioner {\n                id\n                resourceType\n                name {\n                  family\n                  given\n                }\n              }\n              ... on Organization {\n                id\n                resourceType\n                _organization__name: name\n              }\n              ... on Medication {\n                id\n                resourceType\n                code {\n                  text\n                  coding {\n                    ...Coding\n                  }\n                }\n              }\n            }\n          }\n          context {\n            display\n          }\n          dateAsserted\n          derivedFrom {\n            display\n          }\n          dosage {\n            text\n          }\n          effectivePeriod {\n            start\n          }\n          identifier {\n            value\n          }\n          informationSource {\n            type\n          }\n          medicationCodeableConcept {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          medicationReference {\n            display\n          }\n          note {\n            text\n          }\n          partOf {\n            display\n          }\n          reasonCode {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          reasonReference {\n            ...Reference\n          }\n          status\n          statusReason {\n            text\n            coding {\n              ...Coding\n            }\n          }\n          subject {\n            resource {\n              ... on Patient {\n                managingOrganization {\n                  resource {\n                    ... on Organization {\n                      name\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n","import type {\n  FhirResource,\n  MedicationAdministration,\n  MedicationDispense,\n  MedicationRequest,\n  MedicationStatement,\n} from \"fhir/r4\";\nimport { useEffect, useState } from \"react\";\nimport { bundleToResourceMap } from \"./bundle\";\nimport { getIdentifyingRxNormCode } from \"./medication\";\nimport {\n  CTW_EXTENSION_LENS_AGGREGATED_FROM,\n  LENS_EXTENSION_AGGREGATED_FROM,\n  LENS_EXTENSION_MEDICATION_DAYS_SUPPLY,\n  LENS_EXTENSION_MEDICATION_LAST_FILL_DATE,\n  LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE,\n  LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER,\n  LENS_EXTENSION_MEDICATION_QUANTITY,\n  LENS_EXTENSION_MEDICATION_REFILLS,\n  SYSTEM_SUMMARY,\n  SYSTEM_ZUS_OWNER,\n  SYSTEM_ZUS_SUMMARY,\n  SYSTEM_ZUS_THIRD_PARTY,\n} from \"./system-urls\";\nimport { ResourceMap } from \"./types\";\nimport { useTimingQueryWithPatient } from \"..\";\nimport { getLensBuilderId } from \"@/api/urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { MedicationModel } from \"@/fhir/models/medication\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\nimport { PatientModel } from \"@/fhir/models/patient\";\nimport { filterResourcesByBuilderId } from \"@/services/common\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport {\n  MedicationAdministrationGraphqlResponse,\n  medicationAdministrationQuery,\n} from \"@/services/fqs/queries/medication-administration\";\nimport {\n  MedicationDispenseGraphqlResponse,\n  medicationDispenseQuery,\n} from \"@/services/fqs/queries/medication-dispense\";\nimport {\n  MedicationRequestGraphqlResponse,\n  medicationRequestQuery,\n} from \"@/services/fqs/queries/medication-request\";\nimport {\n  MedicationStatementGraphqlResponse,\n  medicationStatementQuery,\n} from \"@/services/fqs/queries/medication-statements\";\nimport { cloneDeep, compact, groupBy, last, mapValues, sortBy, uniqWith } from \"@/utils/nodash\";\nimport {\n  filter,\n  find,\n  compact as fpCompact,\n  last as fpLast,\n  sortBy as fpSortBy,\n  get,\n  map,\n  pipe,\n  propEq,\n} from \"@/utils/nodash/fp\";\nimport { QUERY_KEY_MEDICATION_HISTORY } from \"@/utils/query-keys\";\nimport { sort } from \"@/utils/sort\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport type InformationSource =\n  | \"Patient\"\n  | \"Practitioner\"\n  | \"PractitionerRole\"\n  | \"RelatedPerson\"\n  | \"Organization\";\n\ntype MedicationFilter = {\n  status?: fhir4.MedicationStatement[\"status\"];\n  informationSource?: InformationSource;\n  informationSourceNot?: InformationSource;\n};\n\nexport type MedicationResults = {\n  bundle: fhir4.Bundle | undefined;\n  medications: fhir4.MedicationStatement[];\n  basic: fhir4.Basic[];\n};\n\nexport async function getBuilderMedicationsFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  try {\n    const searchFilters = {\n      informationSourceNot: \"Patient\", // exclude medication statements where the patient is the information source\n    } as MedicationFilter;\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationStatementGraphqlResponse>(\n      graphClient,\n      medicationStatementQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          tag: {\n            nonematch: [SYSTEM_SUMMARY, `${SYSTEM_ZUS_THIRD_PARTY}`],\n            // TODO: There's a bug in FQS that doesn't allow filtering with nonematch AND allmatch.\n            // Uncomment the line below once https://zeushealth.atlassian.net/browse/DRT-249 is resolved.\n            // allmatch: [`${SYSTEM_ZUS_OWNER}|builder/${requestContext.builderId}`],\n          },\n        },\n      },\n    );\n    let nodes = data.MedicationStatementConnection.edges.map((x) => x.node);\n    nodes = filterResourcesByBuilderId(\n      nodes,\n      requestContext.contextBuilderId || requestContext.builderId,\n    );\n    const medStatements = nodes.map((n) => new MedicationStatementModel(n, undefined, n.BasicList));\n    const models = applySearchFiltersToFQSResponse(medStatements, searchFilters, false);\n    if (models.length === 0) {\n      Telemetry.countMetric(\"req.count.builder_medications.none\", 1);\n    }\n    Telemetry.histogramMetric(\"req.count.builder_medications\", models.length);\n    return models;\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching builder medications for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nexport async function getMedicationStatementsForPatientByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  resourceIds: string[] | undefined,\n): Promise<MedicationResults> {\n  try {\n    if (resourceIds === undefined || resourceIds.length === 0) {\n      return { bundle: undefined, medications: [], basic: [] };\n    }\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationStatementGraphqlResponse>(\n      graphClient,\n      medicationStatementQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          ids: {\n            anymatch: resourceIds,\n          },\n        },\n      },\n    );\n    const nodes = data.MedicationStatementConnection.edges.map((x) => x.node);\n    return { bundle: undefined, medications: nodes, basic: [] };\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching medication statements by ID for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nexport async function getMedicationAdministrationsForPatientByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  resourceIds: string[] | undefined,\n): Promise<MedicationAdministration[]> {\n  try {\n    if (resourceIds === undefined || resourceIds.length === 0) {\n      return [];\n    }\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationAdministrationGraphqlResponse>(\n      graphClient,\n      medicationAdministrationQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          ids: {\n            anymatch: resourceIds,\n          },\n        },\n      },\n    );\n    return data.MedicationAdministrationConnection.edges.map((x) => x.node);\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching medication administrations by ID for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nexport async function getMedicationDispensesForPatientByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  resourceIds: string[] | undefined,\n): Promise<MedicationDispense[]> {\n  try {\n    if (resourceIds === undefined || resourceIds.length === 0) {\n      return [];\n    }\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationDispenseGraphqlResponse>(\n      graphClient,\n      medicationDispenseQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          ids: {\n            anymatch: resourceIds,\n          },\n        },\n      },\n    );\n\n    return data.MedicationDispenseConnection.edges.map((x) => x.node);\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching medication dispenses by ID for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nexport async function getMedicationRequestsForPatientByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  resourceIds: string[] | undefined,\n): Promise<MedicationRequest[]> {\n  try {\n    if (resourceIds === undefined || resourceIds.length === 0) {\n      return [];\n    }\n    const graphClient = createGraphqlClient(requestContext);\n\n    const { data } = await fqsRequest<MedicationRequestGraphqlResponse>(\n      graphClient,\n      medicationRequestQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          ids: {\n            anymatch: resourceIds,\n          },\n        },\n      },\n    );\n    return data.MedicationRequestConnection.edges.map((x) => x.node);\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching medication requests by ID for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nfunction applySearchFiltersToFQSResponse(\n  medicationStatements: MedicationStatementModel[],\n  searchFilters: MedicationFilter = {},\n  removeMedsWithNoRxNorm = false,\n) {\n  let medications = medicationStatements;\n  if (removeMedsWithNoRxNorm) {\n    medications = medications.filter((medication) => medication.rxNorm !== undefined);\n  }\n\n  if (searchFilters.informationSource) {\n    medications = medications.filter(\n      (medication) => medication.informationSource?.type === searchFilters.informationSource,\n    );\n  }\n\n  if (searchFilters.informationSourceNot) {\n    medications = medications.filter(\n      (medication) => medication.informationSource?.type !== searchFilters.informationSourceNot,\n    );\n  }\n\n  return medications;\n}\n\n/* Note when filtering the bundle may contain data that will no longer \nbe in the returned medications, such as medications with no RxNorm code. */\nexport async function getSummaryMedicationsFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationStatementGraphqlResponse>(\n      graphClient,\n      medicationStatementQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {\n          tag: {\n            allmatch: [\n              `${SYSTEM_ZUS_SUMMARY}|Common`,\n              `${SYSTEM_ZUS_OWNER}|builder/${getLensBuilderId(requestContext.env)}`,\n            ],\n          },\n        },\n      },\n    );\n    const nodes = data.MedicationStatementConnection.edges.map((x) => x.node);\n    if (nodes.length === 0) {\n      Telemetry.countMetric(\"req.count.summary_medications.none\", 1);\n    }\n    Telemetry.histogramMetric(\"req.count.summary_medications\", nodes.length);\n    return nodes.map((n) => new MedicationStatementModel(n, undefined, n.BasicList));\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching active medications for patient: ${patient.UPID}`,\n    );\n  }\n}\n\nexport async function getMedicationStatementsByIdFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  medicationStatementIds: string[] = [],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationStatementGraphqlResponse>(\n      graphClient,\n      medicationStatementQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        sort: {},\n        first: 500,\n        filter: {\n          ids: {\n            anymatch: medicationStatementIds,\n          },\n        },\n      },\n    );\n\n    return data.MedicationStatementConnection.edges.map(\n      (x) => new MedicationStatementModel(x.node, undefined, x.node.BasicList),\n    );\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching list of medication statements by id for patient: ${patient.UPID}`,\n    );\n  }\n}\n\n// Helper function to filter out medications missing RxNorm codes.\nexport function filterMedicationsWithNoRxNorms(\n  medications: MedicationStatement[],\n  bundle: FhirResource,\n) {\n  const resourceMap = bundleToResourceMap(bundle);\n  return medications.filter((m) => getIdentifyingRxNormCode(m, resourceMap) !== undefined);\n}\n\n// Splits medications into those that the builder already knows about (\"Provider Medications\"),\n// those that they do not know about (\"Other Provider Medications\"), and those they didn't know\n// about originally and then dismissed (\"Dismissed Other Provider Medications\").\nexport function splitMedications(\n  summarizedMedications: MedicationStatementModel[],\n  builderOwnedMedications: MedicationStatementModel[],\n) {\n  // Get active medications where there does not exist a matching builder owned record.\n  const otherProviderMedications = summarizedMedications.filter(\n    (medication) =>\n      !builderOwnedMedications.some((builderMed) => builderMed.rxNorm === medication.rxNorm),\n  );\n\n  // Get builder owned medications and splash in some data from lens meds if available.\n  const builderMedications = builderOwnedMedications.map((m) => {\n    const summarizedMed = find((a) => a.rxNorm === m.rxNorm, summarizedMedications);\n\n    if (!summarizedMed) {\n      return m;\n    }\n\n    // If we did find an active med then copy the builder med and add in the lens extensions.\n    const builderMedResource = cloneDeep(m.resource);\n\n    const LENS_MEDICATION_EXTENSIONS = [\n      LENS_EXTENSION_MEDICATION_LAST_FILL_DATE,\n      LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE,\n      LENS_EXTENSION_MEDICATION_QUANTITY,\n      LENS_EXTENSION_MEDICATION_DAYS_SUPPLY,\n      LENS_EXTENSION_MEDICATION_REFILLS,\n      LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER,\n    ];\n\n    builderMedResource.extension = summarizedMed.resource.extension?.filter((x) =>\n      LENS_MEDICATION_EXTENSIONS.includes(x.url),\n    );\n\n    const medHistory = cloneDeep(\n      find({ url: LENS_EXTENSION_AGGREGATED_FROM }, summarizedMed.resource.extension),\n    );\n    if (medHistory) {\n      // To avoid confusion about the lens extension (since \"aggregated from\" doesn't really\n      // make sense on this builder record), use a different extension URL.\n      medHistory.url = CTW_EXTENSION_LENS_AGGREGATED_FROM;\n      builderMedResource.extension?.push(medHistory);\n    }\n\n    return new MedicationStatementModel(builderMedResource, m.includedResources, m.basics);\n  });\n\n  return {\n    builderMedications,\n    otherProviderMedications,\n  };\n}\n\nexport function useMedicationHistory(medication?: fhir4.MedicationStatement) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_MEDICATION_HISTORY,\n    [medication?.id],\n    getMedicationHistoryFQS(medication),\n  );\n}\n\n/**\n * Currently MedicationStatements don't have lens data with the lastPrescriber\n * reliably populated. We are instead getting that information from the meds\n * history and reusing the `useMedicationHistory` query to avoid making extra\n * ODS requests (as the history ui and details ui are always together atm).\n */\nexport function useLastPrescriber(medication?: fhir4.MedicationStatement) {\n  const [lastPrescriber, setLastPrescriber] = useState<string | undefined>();\n  const historyQuery = useMedicationHistory(medication);\n\n  useEffect(() => {\n    const { includedResources = {}, medications = [] } = historyQuery.data || {};\n\n    if (lastPrescriber === undefined && medications.length) {\n      const prescriber = pipe(\n        // 1. Get underlying resources from the medication models.\n        map(get(\"resource\")),\n        // 2. Throw away any resources that are not MedicationRequests.\n        filter(propEq(\"resourceType\", \"MedicationRequest\")),\n        // 3. Sort by the authored on date.\n        fpSortBy((m) => Date.parse(m.authoredOn)),\n        // 4. If there are med dispense records, make them models.\n        map((mr) => new MedicationModel(mr, includedResources)),\n        // 5. Take the last (latest) from our filtered list.\n        fpLast,\n        // 6. Get the prescriber from the medication model.\n        get(\"prescriber\"),\n      )(medications);\n\n      // Fall back to a string, so we don't try to find prescriber again.\n      setLastPrescriber(prescriber || \"\");\n    }\n  }, [lastPrescriber, historyQuery.data]);\n\n  return { isLoading: historyQuery.isFetching, lastPrescriber };\n}\n\nfunction getMedicationHistoryFQS(medication?: fhir4.MedicationStatement) {\n  return async (requestContext: CTWRequestContext, patient: PatientModel) => {\n    if (!medication) {\n      return { medications: [], includedResources: {} as ResourceMap };\n    }\n    try {\n      const aggregatedFromReferences = new MedicationStatementModel(medication).aggregatedFrom;\n\n      const groups = groupBy(aggregatedFromReferences, \"type\");\n      const resources = mapValues(groups, (group) =>\n        compact(group.map((g) => last(g.reference?.split(\"/\")))),\n      );\n\n      const [\n        medicationStatementResponse,\n        medicationAdministrationResponse,\n        medicationRequestResponse,\n        medicationDispenseResponse,\n      ] = await Promise.all([\n        getMedicationStatementsForPatientByIdFQS(\n          requestContext,\n          patient,\n          resources.MedicationStatement,\n        ),\n        getMedicationAdministrationsForPatientByIdFQS(\n          requestContext,\n          patient,\n          resources.MedicationAdministration,\n        ),\n        getMedicationRequestsForPatientByIdFQS(\n          requestContext,\n          patient,\n          resources.MedicationRequest,\n        ),\n        getMedicationDispensesForPatientByIdFQS(\n          requestContext,\n          patient,\n          resources.MedicationDispense,\n        ),\n      ]);\n      let medicationResources = fpCompact([\n        ...medicationStatementResponse.medications,\n        ...medicationAdministrationResponse,\n        ...medicationRequestResponse,\n        ...medicationDispenseResponse,\n      ]).map((m) => new MedicationModel(m));\n\n      // force FQS results to be sorted by id just like ODS results to ensure both functions return the same output.\n      // TODO: Remove once the ODS code path no longer exists.\n      medicationResources = sortBy(medicationResources, (a) => a.resource.id);\n\n      const medications = sort(\n        uniqWith(\n          medicationResources,\n          (a, b) => a.date === b.date && a.resource.resourceType === b.resource.resourceType,\n        ),\n        \"date\",\n        \"desc\",\n        true,\n      );\n      return { medications, includedResources: {} as ResourceMap };\n    } catch (e) {\n      throw new Error(`Failed fetching medication history for medication ${medication.id}: ${e}`);\n    }\n  };\n}\n","import { useEffect, useState } from \"react\";\nimport { useTimingQueryWithPatient } from \"@/components/core/providers/patient-provider\";\nimport {\n  getBuilderMedicationsFQS,\n  getSummaryMedicationsFQS,\n  splitMedications,\n} from \"@/fhir/medications\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\nimport {\n  QUERY_KEY_PATIENT_BUILDER_MEDICATIONS,\n  QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n} from \"@/utils/query-keys\";\n\n// Gets patient medications for the builder, excluding meds where the information source is patient.\nexport function usePatientBuilderMedications(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_BUILDER_MEDICATIONS,\n    [],\n    getBuilderMedicationsFQS,\n    enabled,\n  );\n}\n\nexport function usePatientSummaryMedications(enabled = true) {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n    [],\n    getSummaryMedicationsFQS,\n    enabled,\n  );\n}\n\n/**\n * This hook provides all patient medication statements reconciled into two\n * categories (\"Builder Medications\" and \"Other Provider Medications\"). This is\n * useful when creating content such as the <PatientMedications /> component.\n */\nexport function useQueryAllPatientMedications(enabled = true) {\n  const [expandedBuilderMedications, setExpandedBuilderMedications] = useState<\n    MedicationStatementModel[]\n  >([]);\n  const [otherProviderMedications, setOtherProviderMedications] = useState<\n    MedicationStatementModel[]\n  >([]);\n  const [allMedications, setAllMedications] = useState<MedicationStatementModel[]>([]);\n\n  const summaryMedicationsQuery = usePatientSummaryMedications(enabled);\n  const builderMedicationsQuery = usePatientBuilderMedications(enabled);\n\n  useEffect(() => {\n    const builderMedications = builderMedicationsQuery.data ?? [];\n    let summaryMedications = (summaryMedicationsQuery.data ?? []) as MedicationStatementModel[];\n\n    // Filter out summary medications that are only aggregattedFrom MedicationAdministration\n    summaryMedications = summaryMedications.filter((medi) =>\n      medi.aggregatedFrom.some((agg) => agg.type !== \"MedicationAdministration\"),\n    );\n\n    // Split the summarized medications into those known/unknown to the builder\n    const splitData = splitMedications(summaryMedications, builderMedications);\n    setExpandedBuilderMedications(splitData.builderMedications);\n    setOtherProviderMedications(splitData.otherProviderMedications);\n    setAllMedications([...splitData.builderMedications, ...splitData.otherProviderMedications]);\n  }, [builderMedicationsQuery.data, summaryMedicationsQuery.data]);\n\n  const isLoading = builderMedicationsQuery.isLoading || summaryMedicationsQuery.isLoading;\n  const isError = builderMedicationsQuery.isError || summaryMedicationsQuery.isError;\n  const isFetching = builderMedicationsQuery.isFetching || summaryMedicationsQuery.isFetching;\n\n  return {\n    isLoading,\n    isError,\n    isFetching,\n    builderMedications: expandedBuilderMedications,\n    otherProviderMedications,\n    allMedications,\n  };\n}\n","import fhir4 from \"fhir/r4\";\nimport {\n  DEFAULT_ZAP_TABS,\n  ZAP_TAB_NAMES,\n  ZAPTabName,\n} from \"./zus-aggregated-profile/zus-aggregated-profile\";\nimport { usePatientContext } from \"../core/providers/patient-provider\";\nimport { useUserBuilderId } from \"../core/providers/user-builder-id\";\nimport { UnreadNotificationIcon } from \"../core/unread-notification-icon\";\nimport { usePatientAllergies } from \"@/fhir/allergies\";\nimport { usePatientDiagnosticReports } from \"@/fhir/diagnostic-report\";\nimport { usePatientTopLevelDocuments } from \"@/fhir/document\";\nimport { usePatientEncounters } from \"@/fhir/encounters\";\nimport { usePatientImmunizations } from \"@/fhir/immunizations\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\n\nexport const numRecordsToLookbackForUnread = 20;\n\nexport type UnreadRecordsNotificationProps = {\n  className?: string;\n  resources?: ZAPTabName[];\n  text?: string;\n};\n\nexport const UnreadRecordsNotification = ({\n  className,\n  resources = DEFAULT_ZAP_TABS,\n  text,\n}: UnreadRecordsNotificationProps) => {\n  const unreadRecordsMap = useUnreadRecordsByResource(resources);\n  const unreadStatuses = [...unreadRecordsMap.values()];\n  if (unreadStatuses.some((isUnread) => isUnread)) {\n    return <UnreadNotificationIcon className={className} text={text} />;\n  }\n\n  return null;\n};\n\n// Provides the number of ZAP resources with unread notifications\nexport function useUnreadZAPTabsCount(resources = DEFAULT_ZAP_TABS): number {\n  usePatientContext(); // Require patient context\n  const unreadRecordsMap = useUnreadRecordsByResource(resources);\n  return [...unreadRecordsMap.values()].reduce(\n    (count, hasUnread) => (hasUnread ? count + 1 : count),\n    0,\n  );\n}\n\n// Maps whether each ZAP resource has any unread notifications\nexport function useUnreadRecordsByResource(resources = DEFAULT_ZAP_TABS): Map<ZAPTabName, boolean> {\n  usePatientContext(); // Require patient context\n  const userBuilderId = useUserBuilderId();\n  const allergiesQuery = usePatientAllergies(resources.includes(\"allergies\"));\n  const conditionsQuery = usePatientConditionsAll(resources.includes(\"conditions-all\"));\n  const diagnosticReportsQuery = usePatientDiagnosticReports(\n    numRecordsToLookbackForUnread,\n    undefined,\n    resources.includes(\"diagnostic-reports\"),\n  );\n  const documentsQuery = usePatientTopLevelDocuments(\n    numRecordsToLookbackForUnread,\n    resources.includes(\"documents\"),\n  );\n  const encountersQuery = usePatientEncounters(\n    numRecordsToLookbackForUnread,\n    resources.includes(\"encounters\"),\n  );\n  const immunizationsQuery = usePatientImmunizations(resources.includes(\"immunizations\"));\n  const medicationsQuery = useQueryAllPatientMedications(resources.includes(\"medications\"));\n\n  const map = new Map<ZAPTabName, boolean>();\n  ZAP_TAB_NAMES.forEach((zapTabName) => {\n    map.set(zapTabName, false);\n  });\n\n  resources.forEach((resource) => {\n    let data: FHIRModel<fhir4.Resource>[] | undefined;\n    if (resource === \"conditions-all\") {\n      if (\n        conditionsQuery.data.some(\n          (record) => !record.isDismissed && !record.isRead && !record.hasMatchingBuilderConditions,\n        )\n      ) {\n        map.set(resource, true);\n      }\n      return;\n    }\n\n    switch (resource) {\n      case \"allergies\":\n        data = allergiesQuery.data;\n        break;\n      case \"diagnostic-reports\":\n        data = diagnosticReportsQuery.data;\n        break;\n      case \"documents\":\n        data = documentsQuery.data;\n        break;\n      case \"encounters\":\n        data = encountersQuery.data;\n        break;\n      case \"immunizations\":\n        data = immunizationsQuery.data;\n        break;\n      case \"medications-all\":\n        data = medicationsQuery.allMedications;\n        break;\n      default:\n        data = [];\n    }\n    if (\n      data?.some(\n        (record) => !record.isDismissed && !record.isRead && !record.ownedByBuilder(userBuilderId),\n      )\n    ) {\n      map.set(resource, true);\n    }\n  });\n\n  return map;\n}\n","import { numRecordsToLookbackForUnread } from \"../unread-records-notification\";\nimport { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { usePatientTopLevelDocuments } from \"@/fhir/document\";\n\nexport type UnreadDocumentsNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadDocumentsNotification = ({ className }: UnreadDocumentsNotificationProps) => {\n  const query = usePatientTopLevelDocuments(numRecordsToLookbackForUnread);\n  return <UnreadNotification className={className} data={query.data} />;\n};\n","type SimpleMoreListProps = {\n  className?: string;\n  items: string[];\n  limit: number;\n  total: number;\n  prefix?: string;\n};\n\nexport const SimpleMoreList = ({ className, items, limit, total, prefix }: SimpleMoreListProps) => {\n  const displayItems = items;\n  if (prefix) {\n    displayItems[0] = `${prefix} ${displayItems[0]}`;\n  }\n  return (\n    <div className={className}>\n      {displayItems.slice(0, limit).map((item, index) => (\n        // eslint-disable-next-line react/no-array-index-key\n        <div key={item + index}>\n          <div>{item}</div>\n        </div>\n      ))}\n      {total > limit && <div className=\"ctw-font-medium\">+ {total - limit} more</div>}\n    </div>\n  );\n};\n","import {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { SimpleMoreList } from \"@/components/core/simple-more-list\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\nimport { compact } from \"@/utils/nodash\";\n\nexport const patientEncounterColumns = (builderId: string): TableColumn<EncounterModel>[] => [\n  {\n    title: \"Date\",\n    widthPercent: 10,\n    minWidth: 120,\n    dataIndex: \"dateDisplay\",\n  },\n  {\n    title: \"Title\",\n    render: (encounter) => (\n      <ResourceTitleColumn\n        title={encounter.typeDisplay}\n        renderIcon={RenderOwnedByBuilderIcon(encounter.ownedByBuilder(builderId))}\n      />\n    ),\n  },\n  {\n    title: \"Provider\",\n    render: (encounter) => (\n      <>\n        {encounter.location && <div className=\"ctw-pb-2\">Location: {encounter.location}</div>}\n        {encounter.typeSpecialty && (\n          <div className=\"ctw-pb-2\">Speciality: {encounter.typeSpecialty}</div>\n        )}\n        {encounter.participants && encounter.participants.length > 0 && (\n          <SimpleMoreList\n            className=\"ctw-pb-2\"\n            items={encounter.participants}\n            limit={2}\n            total={encounter.participants.length}\n            prefix=\"Providers:\"\n          />\n        )}\n      </>\n    ),\n  },\n  {\n    title: \"Details\",\n    render: (encounter) => {\n      const { dischargeDisposition } = encounter;\n      const diagnoses = compact(encounter.diagnoses);\n      const notes = encounter.clinicalNotes.map((note) => note.title).sort();\n      return (\n        <div>\n          {dischargeDisposition && (\n            <div className=\"ctw-pb-2\">Discharge: {dischargeDisposition}</div>\n          )}\n          {diagnoses.length > 0 && (\n            <SimpleMoreList\n              className=\"ctw-pb-2\"\n              items={diagnoses}\n              limit={1}\n              total={diagnoses.length}\n              prefix=\"Diagnoses:\"\n            />\n          )}\n          {notes.length > 0 && (\n            <div>\n              {notes.length} note{notes.length > 1 ? \"s\" : \"\"}\n            </div>\n          )}\n        </div>\n      );\n    },\n  },\n];\n","import { faChevronRight } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport cx from \"classnames\";\nimport type { Dispatch, ReactNode, SetStateAction } from \"react\";\nimport { useState } from \"react\";\nimport { DetailEntry, DetailsCard } from \"./details-card\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\n\nexport type NotesEntryProps = {\n  details: DetailEntry[];\n  hideEmpty?: boolean;\n  id?: string;\n  summary?: ReactNode;\n  versionId?: string;\n  isDetailShownOnOpen?: boolean;\n  documentButton?: ReactNode;\n};\n\ntype Props = NotesEntryProps;\n\nexport const NotesEntry = ({\n  details,\n  hideEmpty,\n  summary,\n  isDetailShownOnOpen = false,\n  documentButton,\n}: Props) => {\n  const [isDetailShown, setIsDetailShown] = useState(isDetailShownOnOpen);\n\n  return (\n    <div className=\"ctw-space-y-1\">\n      <NoteSummary\n        summary={summary}\n        isDetailShown={isDetailShown}\n        setIsDetailShown={setIsDetailShown}\n      />\n      {isDetailShown && (\n        <DetailsCard details={details} hideEmpty={hideEmpty} documentButton={documentButton} />\n      )}\n    </div>\n  );\n};\n\nexport const NoteSummary = ({\n  summary,\n  isDetailShown,\n  setIsDetailShown,\n}: {\n  summary?: ReactNode;\n  isDetailShown: boolean;\n  setIsDetailShown: Dispatch<SetStateAction<boolean>>;\n}) => {\n  const { trackInteraction } = useAnalytics();\n  return (\n    <button\n      type=\"button\"\n      aria-label=\"details\"\n      className=\"ctw-btn-clean\"\n      onClick={() => {\n        trackInteraction(\"toggle_note\", {\n          action: isDetailShown ? \"collapse_note\" : \"expand_note\",\n        });\n        return setIsDetailShown(!isDetailShown);\n      }}\n    >\n      <div className=\"ctw-flex ctw-items-center ctw-justify-between ctw-space-x-4 ctw-rounded-lg ctw-bg-bg-white ctw-p-3 ctw-text-left ctw-outline ctw-outline-1 ctw-outline-bg-dark\">\n        <div className=\"ctw-flex ctw-grow ctw-space-x-3\">{summary}</div>\n        <div className=\"ctw-flex ctw-items-center ctw-space-x-3\">\n          <div className=\"ctw-justify-right ctw-flex\">\n            <FontAwesomeIcon\n              icon={faChevronRight}\n              className={cx(\"ctw-h-3 ctw-w-3 ctw-text-content-lighter\", {\n                \"ctw-rotate-90\": isDetailShown,\n              })}\n            />\n          </div>\n        </div>\n      </div>\n    </button>\n  );\n};\n","import DOMPurify from \"dompurify\";\nimport { Interweave } from \"interweave\";\nimport { NotesEntry } from \"./notes-entry\";\nimport { DocumentModel } from \"@/fhir/models/document\";\n\nexport type NotesProps = {\n  entries: DocumentModel[];\n  documentIdToStartOpen?: string;\n};\n\nfunction getNoteDisplay(noteText: string | undefined) {\n  if (noteText === undefined) {\n    return undefined;\n  }\n  const cleanNote = DOMPurify.sanitize(noteText);\n\n  return (\n    <div className=\"ctw-overflow-auto\">\n      <Interweave content={cleanNote} />\n    </div>\n  );\n}\n\nexport const Notes = ({ entries, documentIdToStartOpen }: NotesProps) => (\n  <div className=\"ctw-space-y-4\">\n    <div className=\"ctw-text-lg ctw-font-semibold\">Notes</div>\n    {entries.map((entry, idx) => (\n      // eslint-disable-next-line react/no-array-index-key\n      <div key={`${entry.id}-${idx}`}>\n        <NotesEntry\n          id={entry.id}\n          summary={\n            <>\n              {entry.title && (\n                <div>\n                  <div className=\"ctw-font-semibold ctw-text-content-black\">{entry.title}</div>\n                </div>\n              )}\n              {!entry.title && <div className=\"ctw-text-content-lighter\">Unknown</div>}\n            </>\n          }\n          hideEmpty={false}\n          details={[\n            {\n              value: getNoteDisplay(entry.text),\n              transposeTables: true,\n            },\n          ]}\n          isDetailShownOnOpen={entry.id === documentIdToStartOpen}\n        />\n      </div>\n    ))}\n  </div>\n);\n","import { parse, parseISO } from \"date-fns\";\n\nconst DATE_FORMATS = [\n  // 04/17/1983 3:50:00.000 PM\n  \"MM/dd/yyyy h:mm:ss.SSS aa\",\n  // 04/17/1983 15:50:00.000\n  \"MM/dd/yyyy HH:mm:ss.SSS\",\n  // 04/17/1983 3:50:00 PM\n  \"MM/dd/yyyy h:mm:ss aa\",\n  // 04/17/1983 15:50:00\n  \"MM/dd/yyyy HH:mm:ss\",\n  // 04/17/1983 3:50 PM\n  \"MM/dd/yyyy h:mm aa\",\n  // 4/17/1983 3:50 PM\n  \"M/dd/yyyy h:mm aa\",\n  // 04/17/1983 15:50\n  \"MM/dd/yyyy HH:mm\",\n  // 4/17/1983 15:50\n  \"M/dd/yyyy HH:mm\",\n  // 04/17/1983\n  \"MM/dd/yyyy\",\n];\n\nexport const parseWithoutFormat = (dateTime: string): Date | undefined => {\n  // first try ISO\n  let retval = parseISO(dateTime);\n  if (!Number.isNaN(retval.getMilliseconds())) {\n    return retval;\n  }\n\n  // next try our custom patterns that we expect\n  for (let dateFormatIdx = 0; dateFormatIdx < DATE_FORMATS.length; dateFormatIdx += 1) {\n    const dateFormat = DATE_FORMATS[dateFormatIdx];\n    retval = parse(dateTime, dateFormat, new Date());\n    if (!Number.isNaN(retval.getMilliseconds())) {\n      return retval;\n    }\n  }\n\n  return undefined;\n};\n","import { differenceInDays } from \"date-fns\";\nimport { Notes } from \"../../resource/helpers/notes\";\nimport { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\nimport { parseWithoutFormat } from \"@/utils/dates\";\nimport { orderBy } from \"@/utils/nodash\";\nimport { capitalize } from \"@/utils/nodash/fp\";\nimport { QUERY_KEY_PATIENT_ENCOUNTERS } from \"@/utils/query-keys\";\n\nexport function usePatientEncounterDetailsDrawer() {\n  return useResourceDetailsDrawer({\n    header: (m) => {\n      if (m.periodStart && m.periodEnd) {\n        const parsedStartDate = parseWithoutFormat(m.periodStart);\n        const parsedEndDate = parseWithoutFormat(m.periodEnd);\n\n        if (\n          parsedStartDate &&\n          parsedEndDate &&\n          differenceInDays(parsedStartDate, parsedEndDate) === 0\n        ) {\n          return `${m.periodStart}`;\n        }\n\n        return `${m.periodStart} - ${m.periodEnd}`;\n      }\n      if (m.periodStart) {\n        return m.periodStart;\n      }\n      if (m.periodEnd) {\n        return m.periodEnd;\n      }\n      return undefined;\n    },\n    subHeader: (m) => m.typeDisplay,\n    getSourceDocument: true,\n    details: encounterData,\n    enableDismissAndReadActions: true,\n    renderChild: (m) =>\n      m.clinicalNotes.length > 0 && <Notes entries={orderBy(m.clinicalNotes, \"title\")} />,\n    queryKey: QUERY_KEY_PATIENT_ENCOUNTERS,\n  });\n}\n\nexport const encounterData = (encounter: EncounterModel) => [\n  { label: \"Start\", value: encounter.periodStart },\n  { label: \"End\", value: encounter.periodEnd },\n  { label: \"Status\", value: capitalize(encounter.status) },\n  { label: \"Class\", value: encounter.class },\n  { label: \"Location\", value: encounter.location },\n  {\n    label: \"Providers\",\n    value: encounter.participants && encounter.participants.length > 0 && (\n      <ul className=\"ctw-m-0 ctw-list-disc ctw-pl-4\">\n        {encounter.participants.map((p) => (\n          <li key={p}>{p}</li>\n        ))}\n      </ul>\n    ),\n  },\n  { label: \"Reason\", value: encounter.reason },\n  {\n    label: \"Diagnoses\",\n    value: encounter.diagnoses && encounter.diagnoses.length > 0 && (\n      <ul className=\"ctw-m-0 ctw-list-disc ctw-pl-4\">\n        {encounter.diagnoses.map((d) => (\n          <li key={d}>{d}</li>\n        ))}\n      </ul>\n    ),\n  },\n  { label: \"Discharge Disposition\", value: encounter.dischargeDisposition },\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\n\nexport const defaultEncounterSort: SortOption<EncounterModel> = {\n  display: \"Date (New to Old)\",\n  sorts: [{ key: \"periodStart\", dir: \"desc\", isDate: true }],\n};\n\nexport const encounterSortOptions: SortOption<EncounterModel>[] = [\n  defaultEncounterSort,\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"periodStart\", dir: \"asc\", isDate: true }],\n  },\n];\n","import cx from \"classnames\";\nimport { useRef } from \"react\";\nimport { patientEncounterColumns } from \"./helpers/columns\";\nimport { encounterFilterPredicates, encounterFilters } from \"./helpers/filters\";\nimport { usePatientEncounterDetailsDrawer } from \"./helpers/modal-hooks\";\nimport { defaultEncounterSort, encounterSortOptions } from \"./helpers/sorts\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientEncountersWithClinicalNotes } from \"@/fhir/encounters\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_PATIENT_ENCOUNTERS } from \"@/utils/query-keys\";\n\nexport type PatientEncountersProps = {\n  className?: cx.Argument;\n};\n\nfunction PatientEncountersComponent({ className }: PatientEncountersProps) {\n  const userBuilderId = useUserBuilderId();\n  const encountersQuery = usePatientEncountersWithClinicalNotes();\n  const containerRef = useRef<HTMLDivElement>(null);\n  const { viewOptions, allTime } = getDateRangeView<EncounterModel>(\"periodStart\");\n  const { data, filters, setFilters, setSort, setViewOption, defaultSort, defaultView } =\n    useFilteredSortedData({\n      cacheKey: \"patient-encounters\",\n      viewOptions,\n      defaultView: allTime.display,\n      filterPredicates: encounterFilterPredicates,\n      defaultSort: defaultEncounterSort,\n      records: encountersQuery.data,\n    });\n\n  const isEmptyQuery = encountersQuery.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openEncounterDetails = usePatientEncounterDetailsDrawer();\n\n  return (\n    <AnalyticsProvider componentName=\"PatientEncounters\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")} ref={containerRef}>\n        <ResourceTableActions\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n          filterOptions={{\n            onChange: setFilters,\n            filters: encounterFilters(encountersQuery.data),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: encounterSortOptions,\n            onChange: setSort,\n          }}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={encountersQuery.isLoading}\n          columns={patientEncounterColumns(userBuilderId)}\n          data={data}\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"encounters\"\n            />\n          }\n          enableDismissAndReadActions\n          onRowClick={(e) => {\n            openEncounterDetails(e, { target: \"encounters\" });\n          }}\n          queryKey={QUERY_KEY_PATIENT_ENCOUNTERS}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientEncounters = withErrorBoundary(PatientEncountersComponent, \"PatientEncounters\");\n","import { numRecordsToLookbackForUnread } from \"../unread-records-notification\";\nimport { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { usePatientEncounters } from \"@/fhir/encounters\";\n\nexport type UnreadEncounterssNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadEncountersNotification = ({ className }: UnreadEncounterssNotificationProps) => {\n  const query = usePatientEncounters(numRecordsToLookbackForUnread);\n  return <UnreadNotification className={className} data={query.data} />;\n};\n","import { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { usePatientImmunizations } from \"@/fhir/immunizations\";\n\nexport type UnreadImmunizationsNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadImmunizationsNotification = ({\n  className,\n}: UnreadImmunizationsNotificationProps) => {\n  const query = usePatientImmunizations();\n  return <UnreadNotification className={className} data={query.data} />;\n};\n","import { faUser } from \"@fortawesome/free-solid-svg-icons\";\nimport { dismissFilter } from \"../../resource/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { uniqueValues } from \"@/utils/filters\";\n\nexport function medicationFilters(\n  medications: MedicationStatementModel[],\n  includeDismissed: boolean,\n): FilterItem[] {\n  const prescriberNames = uniqueValues(medications, \"lastPrescriber\");\n  const filters: FilterItem[] = [];\n\n  if (includeDismissed) {\n    filters.push(dismissFilter);\n  }\n\n  if (prescriberNames.length > 1) {\n    filters.push({\n      key: \"lastPrescriber\",\n      type: \"checkbox\",\n      icon: faUser,\n      values: prescriberNames,\n      display: \"prescriber\",\n    });\n  }\n\n  return filters;\n}\n","import {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\n\nexport const patientMedicationColumns: TableColumn<MedicationStatementModel>[] = [\n  {\n    title: \"Medication Name\",\n    render: (medication) => (\n      <>\n        <div className=\"ctw-font-medium group-hover:ctw-underline\">{medication.display}</div>\n        <div className=\"ctw-font-light\">{medication.dosage}</div>\n      </>\n    ),\n    widthPercent: 35,\n    minWidth: 270,\n  },\n  {\n    title: \"Dispensed\",\n    render: (medication) => (\n      <div className=\"ctw-stacked-concat\">\n        {medication.quantity && <div>{medication.quantity}</div>}\n        {medication.refills && <div>{medication.refills} refills</div>}\n      </div>\n    ),\n    widthPercent: 14,\n  },\n  {\n    title: \"Last Filled\",\n    render: (medication) =>\n      medication.lastFillDate && (\n        <div>\n          <span className=\"ctw-stacked-only\">Last Filled: </span>\n          {medication.lastFillDate}\n        </div>\n      ),\n    widthPercent: 18,\n  },\n  {\n    title: \"Last Prescribed\",\n    render: (medication) => {\n      const { lastPrescribedDate, lastPrescriber } = medication;\n\n      if (!lastPrescribedDate && !lastPrescriber) return null;\n\n      return (\n        <div className=\"ctw-stacked-concat\">\n          <span className=\"ctw-stacked-only\">Last Prescribed: </span>\n          {lastPrescribedDate && <div>{lastPrescribedDate}</div>}\n          {lastPrescriber && <div>{lastPrescriber}</div>}\n        </div>\n      );\n    },\n    widthPercent: 18,\n    minWidth: \"90px\",\n  },\n];\n\nexport const patientMedicationsAllColumns = (\n  builderId: string,\n): TableColumn<MedicationStatementModel>[] => [\n  {\n    title: \"Name\",\n    widthPercent: 40,\n    minWidth: 320,\n    render: (med) => (\n      <ResourceTitleColumn\n        title={med.display}\n        capitalizeTitle={false}\n        subTitle={med.dosage}\n        renderIcon={RenderOwnedByBuilderIcon(med.ownedByBuilder(builderId))}\n      />\n    ),\n  },\n  {\n    title: \"Dispensed\",\n    render: (medication) => (\n      <div className=\"ctw-stacked-concat\">\n        {medication.quantity && <div>{medication.quantity}</div>}\n        {medication.refills && <div>{medication.refills} refills</div>}\n      </div>\n    ),\n    widthPercent: 14,\n  },\n  {\n    title: \"Last Filled\",\n    render: (medication) =>\n      medication.lastFillDate && (\n        <div>\n          <span className=\"ctw-stacked-only\">Last Filled: </span>\n          {medication.lastFillDate}\n        </div>\n      ),\n    widthPercent: 18,\n  },\n  {\n    title: \"Last Prescribed\",\n    render: (medication) => {\n      const { lastPrescribedDate, lastPrescriber } = medication;\n\n      if (!lastPrescribedDate && !lastPrescriber) return null;\n\n      return (\n        <div className=\"ctw-stacked-concat\">\n          <span className=\"ctw-stacked-only\">Last Prescribed: </span>\n          {lastPrescribedDate && <div>{lastPrescribedDate}</div>}\n          {lastPrescriber && <div>{lastPrescriber}</div>}\n        </div>\n      );\n    },\n    widthPercent: 18,\n    minWidth: \"90px\",\n  },\n];\n","import { HistoryEntries } from \"../../resource/helpers/history\";\nimport { HistoryEntryProps } from \"@/components/content/resource/helpers/history-entry\";\nimport { useMedicationHistory } from \"@/fhir/medications\";\nimport { MedicationModel } from \"@/fhir/models/medication\";\nimport { MedicationAdministrationModel } from \"@/fhir/models/medication-administration\";\nimport { MedicationDispenseModel } from \"@/fhir/models/medication-dispense\";\nimport { MedicationRequestModel } from \"@/fhir/models/medication-request\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\nimport { capitalize, compact } from \"@/utils/nodash\";\nimport { UseQueryResultBasic } from \"@/utils/request\";\n\nexport function useMedicationHistoryEntries(\n  medication: MedicationStatementModel\n): UseQueryResultBasic<HistoryEntries | undefined> {\n  const medHistoryQuery = useMedicationHistory(medication.resource);\n  return {\n    data: medHistoryQuery.data?.medications.map(createMedicationDetailsCard),\n    isLoading: medHistoryQuery.isLoading,\n  };\n}\n\nfunction createMedicationDetailsCard(medication: MedicationModel): HistoryEntryProps {\n  if (medication.resourceType === \"MedicationStatement\") {\n    return createMedicationStatementCard(medication);\n  }\n  if (medication.resourceType === \"MedicationRequest\") {\n    return createMedicationRequestCard(medication);\n  }\n\n  if (medication.resourceType === \"MedicationDispense\") {\n    return createMedicationDispenseCard(medication);\n  }\n\n  if (medication.resourceType === \"MedicationAdministration\") {\n    return createMedicationAdminCard(medication);\n  }\n\n  throw new Error(`Unknown medication resource type \"${medication.resourceType}\"`);\n}\n\nfunction createMedicationStatementCard(medication: MedicationModel): HistoryEntryProps {\n  const resource = medication.resource as fhir4.MedicationStatement;\n  const medStatement = new MedicationStatementModel(resource, medication.includedResources);\n\n  return {\n    date: medication.dateLocal,\n    id: medication.id,\n    title: \"Medication Reviewed\",\n    hideEmpty: false,\n    subtitle: medStatement.patient?.organization?.name,\n    details: [\n      {\n        label: \"Status\",\n        value: capitalize(medStatement.displayStatus),\n      },\n      {\n        label: \"Instructions\",\n        value: medStatement.dosage,\n      },\n    ],\n  };\n}\n\nfunction createMedicationRequestCard(medication: MedicationModel): HistoryEntryProps {\n  const resource = medication.resource as fhir4.MedicationRequest;\n  const { prescriber } = medication;\n  const { name, address, telecom } = new MedicationRequestModel(\n    resource,\n    medication.includedResources\n  ).pharmacy;\n  const { numberOfRepeatsAllowed = \"\", initialFill } = resource.dispenseRequest || {};\n  const { value = \"\", unit = \"\" } = initialFill?.quantity || {};\n\n  return {\n    date: medication.dateLocal,\n    id: medication.id,\n    title: \"Prescription Ordered\",\n    subtitle: prescriber,\n    hideEmpty: false,\n    details: [\n      { label: \"Quantity\", value: [value, unit].join(\" \") },\n      {\n        label: \"Refills Allowed\",\n        value: numberOfRepeatsAllowed,\n      },\n      {\n        label: \"Instructions\",\n        value: medication.dosage,\n      },\n      { label: \"Prescriber\", value: prescriber },\n      {\n        label: \"Pharmacy\",\n        value: (\n          <>\n            {name && <div>{name}</div>}\n            {address && <div>{address}</div>}\n            {telecom && <div>T: {telecom}</div>}\n          </>\n        ),\n      },\n    ],\n  };\n}\n\nfunction createMedicationDispenseCard(medication: MedicationModel): HistoryEntryProps {\n  const resource = medication.resource as fhir4.MedicationDispense;\n  const medDispense = new MedicationDispenseModel(resource, medication.includedResources);\n\n  const { quantityDisplay, supplied, performerDetails } = medDispense;\n  const { name, address, telecom } = performerDetails;\n\n  return {\n    date: medication.dateLocal,\n    hideEmpty: false,\n    id: medication.id,\n    title: \"Medication Filled\",\n    subtitle: compact([quantityDisplay, supplied ? `${supplied} supplied` : null]).join(\", \"),\n    details: [\n      { label: \"Quantity\", value: quantityDisplay },\n      {\n        label: \"Days supply\",\n        value: supplied,\n      },\n      {\n        label: \"Pharmacy\",\n        value: (\n          <>\n            {name && <div>{name}</div>}\n            {address && <div>{address}</div>}\n            {telecom && <div>T: {telecom}</div>}\n          </>\n        ),\n      },\n    ],\n  };\n}\n\nfunction createMedicationAdminCard(medication: MedicationModel): HistoryEntryProps {\n  const resource = medication.resource as fhir4.MedicationAdministration;\n  const medAdmin = new MedicationAdministrationModel(resource, medication.includedResources);\n\n  return {\n    id: medication.id,\n    date: medication.dateLocal,\n    hideEmpty: false,\n    title: \"Medication Administered\",\n    subtitle: compact([medAdmin.dosageDisplay, medAdmin.dosageRoute]).join(\", \"),\n    details: [\n      { label: \"Dosage\", value: medAdmin.dosageDisplay },\n      {\n        label: \"Route\",\n        value: medAdmin.dosageRoute,\n      },\n      {\n        label: \"Start Date\",\n        value: medAdmin.effectivePeriod.start,\n      },\n      {\n        label: \"End Date\",\n        value: medAdmin.effectivePeriod.end,\n      },\n    ],\n  };\n}\n","export type DataListEntry = {\n  label: string;\n  value?: string | string[];\n};\n\nexport type DataListProps = {\n  title: string;\n  data: DataListEntry[];\n};\n\nexport function entryFromArray(label: string, array: string[]) {\n  return array.map((value) => ({\n    label,\n    value,\n  }));\n}\n\nexport function DataList({ title, data }: DataListProps) {\n  return (\n    <div className=\"ctw-space-y-4 ctw-rounded-lg ctw-bg-bg-lighter ctw-p-4\">\n      <h4 className=\"ctw-m-0 ctw-text-sm ctw-uppercase ctw-text-content-light\">{title}</h4>\n      <dl className=\"ctw-space-y-3\">\n        {data.map(({ label, value = \"\" }, index) => (\n          <div\n            // label is not guaranteed to be unique so append index.\n            // eslint-disable-next-line react/no-array-index-key\n            key={label + index}\n            className=\"ctw-flex ctw-items-baseline ctw-space-x-4 ctw-text-content-black\"\n          >\n            <dt className=\"ctw-w-1/3 ctw-flex-shrink-0 ctw-font-medium\">{label}</dt>\n            <dd className=\"ctw-flex-grow\">{value}</dd>\n          </div>\n        ))}\n      </dl>\n    </div>\n  );\n}\n","import { useMedicationHistoryEntries } from \"./history\";\nimport { History } from \"../../resource/helpers/history\";\nimport { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { entryFromArray } from \"@/components/core/data-list\";\nimport { Loading } from \"@/components/core/loading\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { useLastPrescriber } from \"@/fhir/medications\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS } from \"@/utils/query-keys\";\n\nconst medicationHistory = (m: MedicationStatementModel) => (\n  <History getHistory={useMedicationHistoryEntries} model={m} />\n);\n\nexport const useMedicationDetailsDrawer = ({\n  rowActions,\n  enableDismissAndReadActions,\n}: {\n  rowActions?: (m: MedicationStatementModel) => RowActionsConfigProp<MedicationStatementModel>;\n  enableDismissAndReadActions?: boolean;\n}) =>\n  useResourceDetailsDrawer({\n    header: (medication: MedicationStatementModel) => medication.display,\n    renderChild: medicationHistory,\n    details: (medication: MedicationStatementModel) => [\n      { label: \"Status\", value: medication.displayStatus },\n      { label: \"Last Fill Date\", value: medication.lastFillDate },\n      { label: \"Quantity\", value: medication.quantity },\n      { label: \"Days Supply\", value: medication.daysSupply },\n      { label: \"Refills\", value: medication.refills },\n      { label: \"Instructions\", value: medication.dosage },\n      {\n        label: \"Prescriber\",\n        value: <LastPrescriber medication={medication} />,\n      },\n      { label: \"Last Prescribed Date\", value: medication.lastPrescribedDate },\n      ...entryFromArray(\"Note\", medication.notesDisplay),\n    ],\n    rowActions,\n    enableDismissAndReadActions,\n    queryKey: QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n  });\n\nfunction LastPrescriber({ medication }: { medication: MedicationStatementModel }) {\n  const { lastPrescriber, isLoading } = useLastPrescriber(medication.resource);\n\n  if (isLoading) {\n    return <Loading className=\"ctw-text-sm ctw-h-3\" iconClass=\"!ctw-w-3 !ctw-h-3\" message=\"\" />;\n  }\n  return <span>{lastPrescriber || \"n/a\"}</span>;\n}\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\n\nexport const medicationSortOptions: SortOption<MedicationStatementModel>[] = [\n  {\n    display: \"Name (A-Z)\",\n    sorts: [{ key: \"sortDisplay\", dir: \"asc\" }],\n  },\n  {\n    display: \"Name (Z-A)\",\n    sorts: [{ key: \"sortDisplay\", dir: \"desc\" }],\n  },\n  {\n    display: \"Last Fill Date (Old to New)\",\n    sorts: [\n      { key: \"lastFillDate\", dir: \"asc\", isDate: true },\n      { key: \"lastPrescribedDate\", isDate: true, dir: \"asc\" },\n      { key: \"sortDisplay\", dir: \"asc\" },\n    ],\n  },\n  {\n    display: \"Last Fill Date (New to Old)\",\n    sorts: [\n      { key: \"lastFillDate\", dir: \"desc\", isDate: true },\n      { key: \"lastPrescribedDate\", isDate: true, dir: \"desc\" },\n      { key: \"sortDisplay\", dir: \"asc\" },\n    ],\n  },\n  {\n    display: \"Last Prescribed (Old to New)\",\n    sorts: [\n      { key: \"lastPrescribedDate\", isDate: true, dir: \"asc\" },\n      { key: \"lastPrescriber\", dir: \"asc\" },\n    ],\n  },\n  {\n    display: \"Last Prescribed (New to Old)\",\n    sorts: [\n      { key: \"lastPrescribedDate\", isDate: true, dir: \"desc\" },\n      { key: \"lastPrescriber\", dir: \"asc\" },\n    ],\n  },\n];\n\nexport const defaultMedicationSort = medicationSortOptions[3];\nexport const defaultMedicationSortOverview = medicationSortOptions[0];\n","import cx from \"classnames\";\nimport { patientMedicationColumns } from \"./columns\";\nimport { useMedicationDetailsDrawer } from \"./details\";\nimport { defaultMedicationSort, medicationSortOptions } from \"./sorts\";\nimport { ViewOption } from \"../../resource/helpers/view-button\";\nimport { PatientResourceTable } from \"../../resource/patient-resource-table\";\nimport {\n  ResourceTableActions,\n  ResourceTableActionsProps,\n} from \"../../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS } from \"@/utils/query-keys\";\nimport \"./patient-medications.scss\";\n\nexport type PatientMedicationsBaseProps = {\n  action?: ResourceTableActionsProps<MedicationStatementModel>[\"action\"];\n  className?: string;\n  query: { data?: MedicationStatementModel[]; isLoading: boolean };\n  rowActions?: (record: MedicationStatementModel) => RowActionsConfigProp<MedicationStatementModel>;\n  filters: FilterItem[];\n  defaultView: ViewOption<MedicationStatementModel>;\n  views: ViewOption<MedicationStatementModel>[];\n  onOpenHistoryDrawer?: () => void;\n};\n\nexport const PatientMedicationsBase = ({\n  action,\n  className,\n  query,\n  rowActions,\n  filters,\n  defaultView: defaultView2,\n  views,\n  onOpenHistoryDrawer,\n}: PatientMedicationsBaseProps) => {\n  const openDetailsDrawer = useMedicationDetailsDrawer({ rowActions });\n\n  const {\n    data,\n    filters: selectedFilters,\n    setFilters,\n    setSort,\n    setViewOption,\n    defaultSort,\n    defaultView,\n  } = useFilteredSortedData({\n    cacheKey: \"patient-medications-base\",\n    defaultSort: defaultMedicationSort,\n    viewOptions: views,\n    records: query.data,\n    defaultView: defaultView2.display,\n  });\n\n  const isEmptyQuery = query.data?.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  function handleRowClick(medication: MedicationStatementModel) {\n    onOpenHistoryDrawer?.();\n    openDetailsDrawer(medication);\n  }\n\n  return (\n    <div className={cx(\"ctw-scrollable-pass-through-height\", className)}>\n      <ResourceTableActions\n        viewOptions={{\n          onChange: setViewOption,\n          defaultView,\n          options: views,\n        }}\n        filterOptions={{\n          onChange: setFilters,\n          filters,\n          selected: selectedFilters,\n        }}\n        sortOptions={{\n          defaultSort,\n          options: medicationSortOptions,\n          onChange: setSort,\n        }}\n        action={action}\n      />\n\n      <PatientResourceTable\n        className=\"ctw-patient-medications\"\n        columns={patientMedicationColumns}\n        data={data}\n        emptyMessage={\n          <EmptyPatientTable\n            hasZeroFilteredRecords={hasZeroFilteredRecords}\n            resourceName=\"medications\"\n          />\n        }\n        isLoading={query.isLoading}\n        onRowClick={handleRowClick}\n        rowActions={rowActions}\n        queryKey={QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS}\n      />\n    </div>\n  );\n};\n","import { ViewOption } from \"../../resource/helpers/view-button\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\n\ntype Status = fhir4.MedicationStatement[\"status\"];\n\nconst current: Status[] = [\"active\", \"unknown\", \"on-hold\", \"intended\", \"not-taken\"];\nconst past: Status[] = [\"completed\", \"stopped\", \"entered-in-error\"];\n\nexport const medicationViews: ViewOption<MedicationStatementModel>[] = [\n  {\n    display: \"Current\",\n    filters: [{ key: \"status\", type: \"checkbox\", selected: current }],\n  },\n  {\n    display: \"Past\",\n    filters: [{ key: \"status\", type: \"checkbox\", selected: past }],\n  },\n  { display: \"All\", filters: [] },\n];\n\nexport const defaultMedicationView = medicationViews[0];\n","import { medicationFilters } from \"./helpers/filters\";\nimport { PatientMedicationsBase } from \"./helpers/patient-medications-base\";\nimport { defaultMedicationView, medicationViews } from \"./helpers/views\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\n\nexport type PatientMedicationsProps = {\n  className?: string;\n  onOpenHistoryDrawer?: () => void;\n};\n\nconst PatientMedicationsComponent = ({\n  className,\n  onOpenHistoryDrawer,\n}: PatientMedicationsProps) => {\n  const { builderMedications, isLoading } = useQueryAllPatientMedications();\n\n  return (\n    <PatientMedicationsBase\n      className={className}\n      query={{ data: builderMedications, isLoading }}\n      filters={medicationFilters(builderMedications, false)}\n      views={medicationViews}\n      defaultView={defaultMedicationView}\n      onOpenHistoryDrawer={onOpenHistoryDrawer}\n    />\n  );\n};\n\nexport const PatientMedications = withErrorBoundary(\n  PatientMedicationsComponent,\n  \"PatientMedications\"\n);\n","import { getFormsMedicationsUrl } from \"./urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\n\nexport const getAutoCompleteMedications = async (\n  requestContext: CTWRequestContext,\n  searchTerm: string\n) => {\n  const { authToken, contextBuilderId } = requestContext;\n  const response = await fetch(\n    `${getFormsMedicationsUrl(requestContext.env)}?display=${searchTerm}`,\n    {\n      headers: {\n        Authorization: `Bearer ${authToken}`,\n        ...(contextBuilderId && { \"Zus-Account\": contextBuilderId }),\n      },\n    }\n  );\n  const data = await response.json();\n  return data.data;\n};\n","import { InputHTMLAttributes, useState } from \"react\";\nimport { ComboboxField, ComboxboxFieldOption } from \"../../core/form/combobox-field\";\nimport { getAutoCompleteMedications } from \"@/api/autocomplete-medications\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\n\nexport type AutoCompleteComboboxProps = {\n  defaultCoding?: fhir4.Coding;\n  readonly: boolean | undefined;\n} & InputHTMLAttributes<HTMLInputElement>;\n\nexport const MedicationsAutoComplete = ({\n  defaultCoding,\n  readonly,\n  ...inputProps\n}: AutoCompleteComboboxProps) => {\n  const { getRequestContext } = useCTW();\n  const [isLoading, setIsLoading] = useState(false);\n  const [options, setOptions] = useState<ComboxboxFieldOption[]>();\n\n  const handleSearchChange = async (query: string) => {\n    setIsLoading(true);\n    const requestContext = await getRequestContext();\n    const medications = await getAutoCompleteMedications(requestContext, query);\n\n    if (medications) {\n      setOptions(\n        medications.map((item: fhir4.Coding) => ({\n          value: item,\n          label: item.display,\n        })) as ComboxboxFieldOption[]\n      );\n    }\n\n    setIsLoading(false);\n  };\n\n  return (\n    <ComboboxField\n      options={options || []}\n      isLoading={isLoading}\n      name={`${inputProps.name}`}\n      defaultSearchTerm={inputProps.defaultValue as string}\n      readonly={readonly}\n      onSearchChange={handleSearchChange}\n      defaultValue={defaultCoding}\n    />\n  );\n};\n","import { format } from \"date-fns\";\nimport { z } from \"zod\";\nimport { MedicationsAutoComplete } from \"../medications-autocomplete\";\nimport { FormEntry } from \"@/components/core/form/drawer-form-with-fields\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { toLower } from \"@/utils/nodash/fp\";\n\nexport const getMedicationFormData = (medication: MedicationStatementModel): FormEntry[] => [\n  {\n    label: \"Subject\",\n    value: medication.subjectID,\n    field: \"subjectID\",\n    hidden: true,\n  },\n  {\n    label: \"Date Asserted\",\n    value: format(new Date(), \"P\"),\n    field: \"dateAsserted\",\n    hidden: true,\n  },\n  {\n    label: \"Medication\",\n    field: \"medication\",\n    value: medication.display,\n    render: (readonly: boolean | undefined, inputProps) => (\n      <MedicationsAutoComplete\n        readonly={readonly}\n        {...inputProps}\n        defaultCoding={medication.rxNormCodeableConcept}\n      />\n    ),\n  },\n  {\n    label: \"Latest Status\",\n    value: toLower(medication.status),\n    field: \"status\",\n  },\n  {\n    label: \"Instructions\",\n    value: medication.dosage,\n    field: \"dosage\",\n  },\n];\n\nexport const medicationStatementSchema = z.object({\n  subjectID: z.string({ required_error: \"Patient must be specified.\" }),\n  dateAsserted: z.date({ required_error: \"Date asserted is required.\" }),\n  medication: z.object({\n    code: z.string({\n      required_error: \"Please choose a medication.\",\n    }),\n    // These are technically required but we mark them\n    // as optional to avoid duplicative error messages.\n    // The condition autocomplete will set us up so that\n    // all three of these values are set.\n    display: z.string().optional(),\n    system: z.string().optional(),\n  }),\n  dosage: z.string().optional(),\n  status: z.enum([\n    \"active\",\n    \"completed\",\n    \"entered-in-error\",\n    \"intended\",\n    \"not-taken\",\n    \"on-hold\",\n    \"stopped\",\n    \"unknown\",\n  ]),\n});\n","import { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { notify } from \"@/components/core/toast\";\nimport { createOrEditFhirResource } from \"@/fhir/action-helper\";\nimport { dateToISO } from \"@/fhir/formatters\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\nimport { SYSTEM_RXNORM } from \"@/fhir/system-urls\";\nimport { isFHIRResource } from \"@/fhir/types\";\nimport {\n  QUERY_KEY_PATIENT,\n  QUERY_KEY_PATIENT_BUILDER_MEDICATIONS,\n  QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n} from \"@/utils/query-keys\";\nimport { queryClient } from \"@/utils/request\";\n\nconst QUERY_KEYS = [\n  QUERY_KEY_PATIENT,\n  QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n  QUERY_KEY_PATIENT_BUILDER_MEDICATIONS,\n];\n\nexport type CreateMedicationStatementFormData = {\n  status: fhir4.MedicationStatement[\"status\"];\n  dateAsserted: Date;\n  subjectID: string;\n  medication: { display: string; code: string };\n  dosage: string;\n  note?: string;\n};\n\nexport const createMedicationStatement = async (\n  data: CreateMedicationStatementFormData,\n  getRequestContext: () => Promise<CTWRequestContext>,\n): Promise<unknown> => {\n  // Some fields will need to be set as they are required.\n  const fhirMedicationStatement: fhir4.MedicationStatement = {\n    resourceType: \"MedicationStatement\",\n    status: data.status,\n    dateAsserted: dateToISO(data.dateAsserted),\n    subject: { type: \"Patient\", reference: `Patient/${data.subjectID}` },\n    medicationCodeableConcept: {\n      text: data.medication.display,\n      coding: [\n        {\n          system: SYSTEM_RXNORM,\n          code: data.medication.code,\n        },\n      ],\n    },\n    ...(data.dosage && {\n      dosage: [\n        {\n          text: data.dosage,\n        },\n      ],\n    }),\n  };\n\n  const resourceModel = new MedicationStatementModel(fhirMedicationStatement);\n\n  const response = await createOrEditFhirResource(\n    resourceModel.resource,\n    await getRequestContext(),\n    resourceModel.title,\n  );\n\n  await Promise.all(QUERY_KEYS.map(async (queryKey) => queryClient.invalidateQueries([queryKey])));\n\n  if (isFHIRResource(response)) {\n    notify({\n      type: \"success\",\n      title: `${resourceModel.title} added to chart.`,\n    });\n  }\n\n  return response;\n};\n","import { format } from \"date-fns\";\nimport type { MedicationStatement } from \"fhir/r4\";\nimport { ReactElement } from \"react\";\nimport {\n  getMedicationFormData,\n  medicationStatementSchema,\n} from \"../../forms/schemas/medication-schema\";\nimport { createMedicationStatement } from \"@/components/content/forms/actions/medications\";\nimport { DrawerFormWithFields } from \"@/components/core/form/drawer-form-with-fields\";\nimport { useDrawer } from \"@/components/core/providers/drawer-provider\";\nimport { usePatient } from \"@/components/core/providers/patient-provider\";\nimport { MedicationStatementModel } from \"@/fhir/models/medication-statement\";\n\nexport function useAddMedicationForm() {\n  const { openDrawer } = useDrawer();\n\n  return (medication: MedicationStatementModel) => {\n    openDrawer({\n      trackingMetadata: { action: \"add_medication\" },\n      component: (props) => <AddNewMedDrawer medication={medication.resource} {...props} />,\n    });\n  };\n}\n\ntype Props = {\n  isOpen: boolean;\n  onClose: () => void;\n  children?: ReactElement;\n  medication?: MedicationStatement;\n};\n\nconst AddNewMedDrawer = ({ isOpen, onClose, medication }: Props) => {\n  const patient = usePatient();\n\n  const patientSubjectRef = {\n    reference: `Patient/${patient.data?.id}`,\n    display: patient.data?.display,\n  };\n\n  // Create a MedicationStatementModel that can be used to pre-populate the form appropriately.\n  let medStatementModelForFormPopulation: MedicationStatementModel;\n  // If we're starting from an existing medication, make sure the subject is set correctly\n  if (medication) {\n    medStatementModelForFormPopulation = new MedicationStatementModel({\n      ...medication,\n      subject: patientSubjectRef,\n      dateAsserted: format(new Date(), \"yyyy-MM-dd\"),\n    });\n  } else {\n    medStatementModelForFormPopulation = new MedicationStatementModel({\n      resourceType: \"MedicationStatement\",\n      status: \"active\",\n      subject: patientSubjectRef,\n      dateAsserted: format(new Date(), \"yyyy-MM-dd\"),\n    });\n  }\n\n  const createMedData = getMedicationFormData(medStatementModelForFormPopulation);\n\n  return (\n    <DrawerFormWithFields\n      title=\"Add Medication\"\n      action={createMedicationStatement}\n      errorHeader=\"Unable to add medication to chart\"\n      data={createMedData}\n      schema={medicationStatementSchema}\n      isOpen={isOpen}\n      onClose={onClose}\n    />\n  );\n};\n","import cx from \"classnames\";\nimport { useAddMedicationForm } from \"./helpers/add-new-med-drawer\";\nimport { patientMedicationsAllColumns } from \"./helpers/columns\";\nimport { useMedicationDetailsDrawer } from \"./helpers/details\";\nimport { medicationFilters } from \"./helpers/filters\";\nimport { defaultMedicationSort, medicationSortOptions } from \"./helpers/sorts\";\nimport { useToggleRead } from \"../hooks/use-toggle-read\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS } from \"@/utils/query-keys\";\n\nexport type PatientMedicationsAllProps = {\n  className?: string;\n  readOnly?: boolean;\n  onAddToRecord?: (record: MedicationStatementModel) => Promise<void> | void;\n};\n\nfunction PatientMedicationsAllComponent({\n  className,\n  readOnly,\n  onAddToRecord,\n}: PatientMedicationsAllProps) {\n  const userBuilderId = useUserBuilderId();\n  const query = useQueryAllPatientMedications();\n\n  const { viewOptions, past6Months } =\n    getDateRangeView<MedicationStatementModel>(\"lastActivityDate\");\n\n  const { data, filters, setFilters, setSort, setViewOption, defaultSort, defaultView } =\n    useFilteredSortedData({\n      cacheKey: \"patient-medications-all\",\n      defaultSort: defaultMedicationSort,\n      viewOptions,\n      defaultView: past6Months.display,\n      records: query.allMedications,\n    });\n\n  const isEmptyQuery = query.allMedications.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n  const empty = (\n    <EmptyPatientTable hasZeroFilteredRecords={hasZeroFilteredRecords} resourceName=\"medications\" />\n  );\n\n  const rowActions = useMedicationRowActions(onAddToRecord);\n\n  const openDetails = useMedicationDetailsDrawer({\n    rowActions: readOnly ? undefined : rowActions,\n    enableDismissAndReadActions: true,\n  });\n\n  return (\n    <AnalyticsProvider componentName=\"PatientMedicationsAll\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: medicationFilters(query.allMedications, true),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: medicationSortOptions,\n            onChange: setSort,\n          }}\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={query.isLoading}\n          data={data}\n          columns={patientMedicationsAllColumns(userBuilderId)}\n          onRowClick={openDetails}\n          rowActions={readOnly ? undefined : rowActions}\n          enableDismissAndReadActions\n          emptyMessage={empty}\n          queryKey={QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientMedicationsAll = withErrorBoundary(\n  PatientMedicationsAllComponent,\n  \"PatientMedicationsAll\",\n);\n\nexport function useMedicationRowActions(\n  onAddToRecord?: (record: MedicationStatementModel) => void,\n) {\n  const { t } = useBaseTranslations();\n  const userBuilderId = useUserBuilderId();\n  const showAddMedicationForm = useAddMedicationForm();\n  const { toggleRead } = useToggleRead();\n\n  return (record: MedicationStatementModel): RowActionsConfigProp<MedicationStatementModel> =>\n    record.ownedByBuilder(userBuilderId)\n      ? []\n      : [\n          {\n            text: t(\"resourceTable.add\"),\n            className: \"ctw-btn-primary\",\n            onClick: () => {\n              if (!record.isRead) {\n                void toggleRead(record);\n              }\n\n              if (onAddToRecord) {\n                onAddToRecord(record);\n              } else {\n                showAddMedicationForm(record);\n              }\n            },\n          },\n        ];\n}\n","import { useAddMedicationForm } from \"./helpers/add-new-med-drawer\";\nimport { medicationFilters } from \"./helpers/filters\";\nimport { PatientMedicationsBase } from \"./helpers/patient-medications-base\";\nimport { useToggleDismiss } from \"../hooks/use-toggle-dismiss\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { Spinner } from \"@/index\";\n\nexport type PatientMedicationsOutsideProps = {\n  className?: string;\n  onOpenHistoryDrawer?: () => void;\n  onAddToRecord?: (record: MedicationStatementModel) => Promise<void> | void;\n  readOnly?: boolean;\n};\n\nconst PatientMedicationsOutsideComponent = ({\n  className,\n  onAddToRecord,\n  readOnly = false,\n  onOpenHistoryDrawer,\n}: PatientMedicationsOutsideProps) => {\n  const { otherProviderMedications, isLoading } = useQueryAllPatientMedications();\n  const rowActions = useRowActions(onAddToRecord);\n  const { viewOptions, past6Months } =\n    getDateRangeView<MedicationStatementModel>(\"lastActivityDate\");\n\n  return (\n    <AnalyticsProvider componentName=\"PatientMedicationsOutside\">\n      <PatientMedicationsBase\n        className={className}\n        query={{ data: otherProviderMedications, isLoading }}\n        filters={medicationFilters(otherProviderMedications, true)}\n        rowActions={readOnly ? undefined : rowActions}\n        views={viewOptions}\n        defaultView={past6Months}\n        onOpenHistoryDrawer={onOpenHistoryDrawer}\n      />\n    </AnalyticsProvider>\n  );\n};\n\nexport const PatientMedicationsOutside = withErrorBoundary(\n  PatientMedicationsOutsideComponent,\n  \"PatientMedicationsOutside\",\n);\n\nfunction useRowActions(onAddToRecord?: (record: MedicationStatementModel) => void) {\n  const { t } = useBaseTranslations();\n  const { trackInteraction } = useAnalytics();\n  const showAddMedicationForm = useAddMedicationForm();\n  const { isLoading, toggleDismiss: toggleArchive } = useToggleDismiss();\n\n  return (record: MedicationStatementModel): RowActionsConfigProp<MedicationStatementModel> => {\n    const archiveLabel = record.isDismissed\n      ? t(\"resourceTable.restore\")\n      : t(\"resourceTable.dismiss\");\n    return [\n      {\n        text: archiveLabel,\n        className: \"ctw-btn-default\",\n        disabled: isLoading,\n        onClick: async () => {\n          await toggleArchive(record);\n        },\n        render() {\n          return (\n            <div className=\"ctw-flex\">\n              {isLoading && <Spinner className=\"ctw-mx-4 ctw-align-middle\" />}\n              {!isLoading && archiveLabel}\n            </div>\n          );\n        },\n      },\n      {\n        text: t(\"resourceTable.add\"),\n        className: \"ctw-btn-primary ctw-ml-1 ctw-capitalize\",\n        testId: \"add-to-record\",\n        disabled: isLoading,\n        onClick: () => {\n          if (onAddToRecord) {\n            onAddToRecord(record);\n          } else {\n            showAddMedicationForm(record);\n          }\n          trackInteraction(\"add_to_record\");\n        },\n      },\n    ];\n  };\n}\n","import { UnreadNotificationIcon } from \"@/components/core/unread-notification-icon\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\n\nexport const PatientMedicationsOutsideBadge = () => {\n  const { otherProviderMedications = [] } = useQueryAllPatientMedications();\n  const activeUnarchivedMedications = otherProviderMedications.filter(\n    (medication) => !(medication.isDismissed || medication.isInactive)\n  );\n\n  if (activeUnarchivedMedications.length > 0) {\n    return <UnreadNotificationIcon />;\n  }\n  return null;\n};\n","import { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\n\nexport type UnreadMedicationsNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadMedicationsNotification = ({\n  className,\n}: UnreadMedicationsNotificationProps) => {\n  const query = useQueryAllPatientMedications();\n  return <UnreadNotification className={className} data={query.allMedications} />;\n};\n","import { faArrowUpRightFromSquare } from \"@fortawesome/free-solid-svg-icons\";\nimport { OverviewCard, OverviewCardBodyMessage } from \"./overview-card\";\nimport { PatientHistoryWithAction } from \"../patient-history/patient-history-with-action\";\nimport ZusSVG from \"@/assets/zus-logo.svg\";\nimport { usePatientHistory } from \"@/components/content/patient-history/use-patient-history\";\n\nexport type ZusInformationCardProps = {\n  hideRequestRecords?: boolean;\n  includePatientDemographicsForm?: boolean;\n};\n\nexport const ZusInformationCard = ({\n  hideRequestRecords = false,\n  includePatientDemographicsForm,\n}: ZusInformationCardProps) => {\n  const patientHistory = usePatientHistory();\n\n  return (\n    <OverviewCard\n      icon={<img src={ZusSVG} alt=\"Zus\" className=\"ctw-h-5\" />}\n      title=\"Records Provided by Zus Health\"\n      footerIcon={faArrowUpRightFromSquare}\n      isLoading={patientHistory.isLoading}\n    >\n      {patientHistory.isError ? (\n        <OverviewCardBodyMessage message=\"Unable to load patient history information\" />\n      ) : (\n        <div className=\"ctw-space-y-3 ctw-my-3\">\n          <div className=\"ctw-px-3\">\n            <PatientHistoryWithAction\n              hideRequestRecords={hideRequestRecords}\n              includePatientDemographicsForm={includePatientDemographicsForm}\n            />\n          </div>\n\n          <div className=\"ctw-bg-divider-light ctw-h-px\" />\n\n          <div className=\"ctw-space-y-3 ctw-px-3\">\n            <a\n              href=\"https://share.hsforms.com/10NmAPiu7Qd2OXbxAHnseiwcjai8\"\n              className=\"ctw-link ctw-text-sm ctw-block\"\n              target=\"_blank\"\n              rel=\"noreferrer noopener\"\n            >\n              Share ZAP Feedback\n            </a>\n\n            <a\n              href=\"https://clinicalguide.zushealth.com/docs/getting-started\"\n              className=\"ctw-link ctw-text-sm ctw-block\"\n              target=\"_blank\"\n              rel=\"noreferrer noopener\"\n            >\n              Clinical Guide\n            </a>\n          </div>\n        </div>\n      )}\n    </OverviewCard>\n  );\n};\n","import { faFlask } from \"@fortawesome/free-solid-svg-icons\";\nimport { useEffect, useState } from \"react\";\nimport { useObservationsDetailsDrawer } from \"../observations/helpers/drawer\";\nimport { OverviewFilter } from \"../overview/filters\";\nimport { ResourceOverviewCard } from \"../overview/resource-overview-card\";\nimport {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../resource/helpers/resource-title-column\";\nimport { getCTWBaseUrl } from \"@/api/urls\";\nimport { useQueryWithCTW } from \"@/components/core/providers/use-query-with-ctw\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientDiagnosticReportsWithTrendData } from \"@/fhir/diagnostic-report\";\nimport { DiagnosticReportModel } from \"@/fhir/models\";\nimport { compact } from \"@/utils/nodash\";\n\nconst hasA1CCode = (A1CCodes: string[], r: DiagnosticReportModel) =>\n  r.coding?.code && A1CCodes.includes(r.coding.code);\n\nconst containsText = (r: DiagnosticReportModel, text: string) =>\n  r.displayName.toLowerCase().includes(text);\n\nconst cleanupA1CDisplay = (A1CCodes: string[], r: DiagnosticReportModel) => {\n  // First check that it is a 1AC display\n  if (hasA1CCode(A1CCodes, r) || containsText(r, \"a1c\")) {\n    if (hasA1CCode(A1CCodes, r)) {\n      return r.displayName;\n    }\n    return \"A1c\";\n  }\n\n  // If not an a1c display don't manipulate text\n  return r.displayName;\n};\n\nexport const getOverviewFilters = (A1CCodes: string[]): OverviewFilter<DiagnosticReportModel>[] => [\n  {\n    key: \"a1c\",\n    label: \"Filter by A1C\",\n    description: \"Contains a1c in text or if it includes an a1c code\",\n    predicate: (r: DiagnosticReportModel) => hasA1CCode(A1CCodes, r) || containsText(r, \"a1c\"),\n  },\n  {\n    key: \"cbc\",\n    label: \"Filter by CBC\",\n    description: \"Match lowercase “cbc” or “complete blood count” but not containing “cd4/cd8”\",\n    predicate: (r: DiagnosticReportModel) =>\n      /cbc(?!.*cd4\\/cd8)|complete blood count/.test(r.displayName.toLowerCase()),\n  },\n  {\n    key: \"cmp\",\n    label: \"Filter by CMP\",\n    description: \"Match lowercase “cmp” or “bmp” or “metabolic panel”\",\n    predicate: (r: DiagnosticReportModel) =>\n      [\"cmp\", \"bmp\", \"metabolic panel\"].includes(r.displayName.toLowerCase()),\n  },\n];\n\nconst useA1CCodes = () =>\n  useQueryWithCTW(\"a1cCodes\", [], async (requestContext, _) => {\n    const response = await fetch(\n      `${getCTWBaseUrl(requestContext.env)}/api/terminology/valuesets/a1c`,\n      {\n        headers: {\n          Authorization: `Bearer ${requestContext.authToken}`,\n          \"content-type\": \"application/json\",\n        },\n      },\n    );\n    return response.json();\n  });\n\ntype ValueSet = {\n  code: string;\n  display: string;\n};\n\nexport type PatientDiagnosticReportsOverviewProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const PatientDiagnosticReportsOverview = ({\n  onSeeAllResources,\n}: PatientDiagnosticReportsOverviewProps) => {\n  const [A1CCodes, setA1CCodes] = useState([]);\n  const [mergedData, setMergedData] = useState<DiagnosticReportModel[]>([]);\n  const openDetails = useObservationsDetailsDrawer(false);\n  const { data, isLoading } = usePatientDiagnosticReportsWithTrendData();\n  const userBuilderId = useUserBuilderId();\n  const useA1CCodesResponse = useA1CCodes();\n\n  useEffect(() => {\n    if (useA1CCodesResponse.data) {\n      setA1CCodes(useA1CCodesResponse.data.content.map((item: ValueSet) => item.code));\n    }\n  }, [useA1CCodesResponse.data]);\n\n  // Wait for the A1C codes to load before rendering the data\n  useEffect(() => {\n    if (A1CCodes.length > 0) {\n      const filteredData = compact(\n        getOverviewFilters(A1CCodes).flatMap((filter) => data.filter(filter.predicate)[0]),\n      );\n      setMergedData(filteredData);\n    }\n  }, [A1CCodes, data]);\n\n  const noData = data.length === 0;\n\n  return (\n    <ResourceOverviewCard\n      onSeeAllResources={onSeeAllResources}\n      onRowClick={openDetails}\n      data={mergedData}\n      emptyMessage={\n        noData\n          ? \"We didn't find any lab records for this patient.\"\n          : \"There are no metabolic or CBC panel and A1C labs for this patient.\"\n      }\n      footerText=\"All Labs\"\n      hideFooter={noData}\n      title=\"Select Labs\"\n      tooltipText=\"Most recent Metabolic or CBC Panel and A1C\"\n      isLoading={isLoading || useA1CCodesResponse.isLoading}\n      icon={faFlask}\n      trackingName=\"labs_overview\"\n    >\n      {(record: DiagnosticReportModel) => (\n        <div>\n          <ResourceTitleColumn\n            title={cleanupA1CDisplay(A1CCodes, record)}\n            renderIcon={RenderOwnedByBuilderIcon(record.ownedByBuilder(userBuilderId))}\n          />\n          <div className=\"ctw-font-normal\">Recorded: {record.effectiveStart}</div>\n        </div>\n      )}\n    </ResourceOverviewCard>\n  );\n};\n","import { faNoteSticky } from \"@fortawesome/free-regular-svg-icons\";\nimport { faCircleH } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { encounterTypePredicate } from \"./helpers/filters\";\nimport { usePatientEncounterDetailsDrawer } from \"./helpers/modal-hooks\";\nimport { defaultEncounterSort } from \"./helpers/sorts\";\nimport { applyFilters, OverviewFilter } from \"../overview/filters\";\nimport { ResourceOverviewCard } from \"../overview/resource-overview-card\";\nimport {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../resource/helpers/resource-title-column\";\nimport { datePredicate } from \"../resource/helpers/view-date-range\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientEncountersWithClinicalNotes } from \"@/fhir/encounters\";\nimport { EncounterModel } from \"@/fhir/models\";\nimport { applySorts } from \"@/utils/sort\";\n\ntype EncountersOverviewCardProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const EncountersOverviewCard = ({ onSeeAllResources }: EncountersOverviewCardProps) => {\n  const userBuilderId = useUserBuilderId();\n  const encountersQuery = usePatientEncountersWithClinicalNotes();\n  const openEncounterDetails = usePatientEncounterDetailsDrawer();\n\n  const sortedData = applySorts(encountersQuery.data, defaultEncounterSort.sorts);\n  const filteredData = applyFilters(sortedData, getEncounterOverviewFilters());\n\n  const noData = encountersQuery.data.length === 0;\n\n  return (\n    <ResourceOverviewCard\n      icon={faCircleH}\n      title=\"ED & IP Visits\"\n      data={filteredData}\n      emptyMessage={\n        noData\n          ? \"We didn't find any encounter records for this patient.\"\n          : \"There are no emergency or inpatient visits within the past year for this patient.\"\n      }\n      onRowClick={(e) => {\n        openEncounterDetails(e, { target: \"overview\" });\n      }}\n      onSeeAllResources={onSeeAllResources}\n      footerText=\"All Encounters\"\n      hideFooter={noData}\n      isLoading={encountersQuery.isLoading}\n      tooltipText=\"Emergency and inpatient visits from the past year.\"\n      trackingName=\"encounters_overview\"\n    >\n      {(e: EncounterModel) => (\n        <ResourceTitleColumn\n          title={`${e.dateDisplay} - ${e.typeDisplay}`}\n          subTitle={\n            <div className=\"ctw-space-y-0.5\">\n              {e.location && <div className=\"ctw-font-normal\">{e.location}</div>}\n              {e.clinicalNotes.length > 0 ? (\n                <div className=\"ctw-text-sm ctw-font-normal ctw-pt-1 ctw-flex ctw-space-x-1.5 ctw-items-center\">\n                  <FontAwesomeIcon\n                    className=\"ctw-w-4 ctw-text-content-lighter\"\n                    icon={faNoteSticky}\n                  />\n                  <div>\n                    {e.clinicalNotes.length} {e.clinicalNotes.length === 1 ? \"note\" : \"notes\"}\n                  </div>\n                </div>\n              ) : undefined}\n            </div>\n          }\n          renderIcon={RenderOwnedByBuilderIcon(e.ownedByBuilder(userBuilderId))}\n        />\n      )}\n    </ResourceOverviewCard>\n  );\n};\n\nconst getEncounterOverviewFilters = (): OverviewFilter<EncounterModel>[] => [\n  {\n    key: \"emergency\",\n    label: \"Filter for emergency encounters\",\n    description: \"Is an emergency or a hospitalization.\",\n    predicate: (e: EncounterModel) => encounterTypePredicate([\"Emergency\", \"Inpatient\"], e),\n  },\n  {\n    key: \"recent\",\n    label: \"Filter for recent encounters\",\n    description: \"Began within the past year.\",\n    predicate: (e: EncounterModel) => datePredicate(e, \"periodStart\", 365, false),\n  },\n];\n","import { UseQueryResult } from \"@tanstack/react-query\";\nimport { useTimerQueryWithCTW } from \"..\";\nimport { getCTWBaseUrl } from \"@/api/urls\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { merge } from \"@/utils/nodash\";\nimport { QUERY_KEY_BUILDER_CONFIG } from \"@/utils/query-keys\";\n\nconst DEFAULT_CONFIG = {\n  overviewCards: {\n    conditions: { enabled: true },\n    medications: { enabled: true },\n    diagnostics: { enabled: true },\n    encounters: { enabled: true },\n    episodesOfCare: { enabled: false },\n    vitals: { enabled: true },\n    packages: { enabled: true },\n  },\n};\n\nexport type BuilderConfig = {\n  builderId: string;\n  overviewCards?: Record<string, { enabled: boolean } | undefined>;\n  systemMRN?: string;\n};\n\nexport function useBuilderConfig(): UseQueryResult<BuilderConfig> {\n  const builderId = useUserBuilderId();\n\n  return useTimerQueryWithCTW(\n    QUERY_KEY_BUILDER_CONFIG,\n    [builderId],\n    async (requestContext) => {\n      const r = await fetch(\n        `${getCTWBaseUrl(requestContext.env)}/api/builders/${requestContext.builderId}/config`,\n        {\n          method: \"GET\",\n          headers: {\n            Authorization: `Bearer ${requestContext.authToken}`,\n          },\n          mode: \"cors\",\n        },\n      );\n\n      const config = await r.json();\n      return merge({}, DEFAULT_CONFIG, config);\n    },\n    !!builderId,\n  );\n}\n","import { PatientModel } from \"@/fhir/models\";\nimport { useBuilderConfig } from \"@/hooks/use-builder-config\";\n\nexport type PatientMRNProps = {\n  patient?: PatientModel;\n  className?: string;\n};\n\nexport function PatientInfoLine({ patient, className }: PatientMRNProps) {\n  const { data } = useBuilderConfig();\n\n  if (!patient) return null;\n\n  const mrn = patient.findIdentifier(data?.systemMRN);\n\n  return (\n    <div className={className}>\n      {patient.dob}\n      {patient.age && ` (${patient.age})`}\n      {mrn && <span>, {mrn}</span>}\n    </div>\n  );\n}\n","import { faExternalLinkAlt, faFileLines } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { useCCDAModal } from \"../CCDA/modal-ccda\";\nimport { PatientInfoLine } from \"../patients/patient-info-line\";\nimport { useResourceDetailsDrawer } from \"../resource/resource-details-drawer\";\nimport { EpisodeOfCareModel, PatientModel } from \"@/fhir/models\";\nimport { useAnalytics } from \"@/index\";\n\n/*\nDetails drawer for episode of care. Drawer will show heading based on\npatient if goToPatient is provided (hospitalizations use case), otherwise\ndrawer header will be based on the episode of care. \n*/\nexport function useEpisodeOfCareDrawer(linkToPatient = false) {\n  return useResourceDetailsDrawer({\n    header: (episodeOfCare: EpisodeOfCareModel) =>\n      linkToPatient && episodeOfCare.patient && episodeOfCare.patientUPID ? (\n        <PatientHeader\n          patient={episodeOfCare.patient}\n          patientUPID={episodeOfCare.patientUPID}\n          linkToPatient={linkToPatient}\n        />\n      ) : (\n        <EpisodeOfCareHeader episodeOfCare={episodeOfCare} />\n      ),\n    subHeader: (episodeOfCare: EpisodeOfCareModel) =>\n      linkToPatient ? <PatientInfoLine patient={episodeOfCare.patient} /> : episodeOfCare.location,\n    getSourceDocument: false,\n    details: episodeOfCareData,\n    renderChild: encountersAndNotes,\n    enableDismissAndReadActions: true,\n  });\n}\n\nconst episodeOfCareData = (toc: EpisodeOfCareModel) => [\n  { label: \"Start Date\", value: toc.periodStart },\n  { label: \"End Date\", value: toc.periodEnd },\n  { label: \"Type\", value: toc.class },\n  { label: \"Location\", value: toc.location },\n  { label: \"Diagnosis\", value: toc.diagnoses?.join(\", \") },\n  { label: \"Discharge Disposition\", value: toc.dischargeDisposition },\n];\n\nfunction encountersAndNotes(model: EpisodeOfCareModel) {\n  if (model.dischargeBinaries.length === 0) {\n    return null;\n  }\n\n  // TODO: pass patient into RelatedDocumentButton\n  const links = model.dischargeBinaries.map((binaryId) => (\n    <RelatedDocumentButton\n      key={binaryId}\n      binaryId={binaryId}\n      documentTitle=\"Encounter Summary\"\n      patient={model.patient}\n    />\n  ));\n  return (\n    <div className=\"ctw-space-y-4\">\n      <h4 className=\"ctw-text-lg ctw-font-semibold\">Documents</h4>\n      {links}\n    </div>\n  );\n}\n\nfunction RelatedDocumentButton({\n  binaryId,\n  documentTitle,\n  patient,\n}: {\n  binaryId: string | undefined;\n  documentTitle: string;\n  patient: PatientModel | undefined;\n}) {\n  const openCCDAModal = useCCDAModal(patient);\n  const { trackInteraction } = useAnalytics();\n\n  if (!binaryId) {\n    return null;\n  }\n\n  return (\n    <>\n      <button\n        type=\"button\"\n        className=\"ctw-btn-clean\"\n        onClick={() => {\n          openCCDAModal(binaryId, documentTitle);\n          trackInteraction(\"view_adt_discharge_summary\", { resourceType: \"EpisodeOfCare\" });\n        }}\n      >\n        <div className=\"ctw-flex ctw-items-center ctw-justify-between ctw-rounded-lg ctw-bg-bg-white ctw-p-3 ctw-text-left ctw-outline ctw-outline-1 ctw-outline-bg-dark\">\n          <div className=\"ctw-flex ctw-space-x-3\">\n            <div>\n              <div className=\"font-semibold ctw-text-primary-dark\">{documentTitle}</div>\n              <div className=\"text-content-light\" />\n            </div>\n          </div>\n          <FontAwesomeIcon\n            icon={faFileLines}\n            className=\"ctw-w-5 ctw-h-5 ctw-text-content-lighter ctw-justify-self-end\"\n          />\n        </div>\n      </button>\n    </>\n  );\n}\n\ntype PatientHeaderProps = {\n  patient: PatientModel;\n  patientUPID: string;\n  linkToPatient: boolean;\n};\n\nfunction PatientHeader({ patient, patientUPID, linkToPatient }: PatientHeaderProps) {\n  const { display, gender } = patient;\n\n  return (\n    <div className=\"ctw-flex ctw-justify-between\">\n      {display}\n      {gender ? ` (${gender[0].toUpperCase()})` : \"\"}\n      {linkToPatient && (\n        <a\n          aria-label=\"Open in new tab\"\n          href={`/patients/${patientUPID}`}\n          className=\"ctw-btn-clear ctw-link ctw-flex ctw-items-center ctw-space-x-2\"\n          rel=\"noopener noreferrer\"\n          target=\"_blank\"\n          tabIndex={0} // prevents the link from being focused on drawer open\n        >\n          <FontAwesomeIcon icon={faExternalLinkAlt} className=\"ctw-h-3\" />\n          <span className=\"ctw-normal-case\">Go To Profile</span>\n        </a>\n      )}\n    </div>\n  );\n}\n\nfunction EpisodeOfCareHeader({ episodeOfCare }: { episodeOfCare: EpisodeOfCareModel }) {\n  return <div className=\"ctw-flex ctw-justify-between\">{episodeOfCare.title}</div>;\n}\n","import { EpisodeOfCare } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface EpisodeOfCareConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<EpisodeOfCare>[];\n}\n\nexport interface EpisodeOfCareGraphqlResponse {\n  EpisodeOfCareConnection: EpisodeOfCareConnection;\n}\n\nexport const episodeOfCareQuery = gql`\n  query EpisodeOfCare(\n    $upid: ID!\n    $cursor: String!\n    $first: Int!\n    $filter: EpisodeOfCareFilterParams!\n  ) {\n    EpisodeOfCareConnection(upid: $upid, after: $cursor, first: $first, filter: $filter) {\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          extension {\n            url\n            extension {\n              url\n              valueReference {\n                id\n                type\n                reference\n              }\n            }\n            valueString\n            valueReference {\n              id\n              type\n              reference\n              display\n            }\n            valueCodeableConcept {\n              coding {\n                system\n                code\n                display\n              }\n              text\n            }\n            valueCoding {\n              code\n              display\n              system\n              userSelected\n              version\n            }\n          }\n          meta {\n            security {\n              system\n              code\n            }\n            tag {\n              system\n              code\n            }\n          }\n          period {\n            start\n            end\n          }\n          patient {\n            id\n            type\n            reference\n          }\n          identifier {\n            system\n            value\n            type {\n              text\n              coding {\n                system\n                code\n                display\n              }\n            }\n          }\n          status\n          diagnosis {\n            role {\n              coding {\n                system\n                code\n                display\n              }\n            }\n            condition {\n              id\n              type\n              reference\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n","import { EpisodeOfCareModel, PatientModel } from \"./models\";\nimport {\n  createGraphqlClient,\n  CTWRequestContext,\n  fqsRequest,\n  MAX_OBJECTS_PER_REQUEST,\n  Telemetry,\n  useTimingQueryWithPatient,\n} from \"..\";\nimport {\n  EpisodeOfCareGraphqlResponse,\n  episodeOfCareQuery,\n} from \"@/services/fqs/queries/episode-of-care\";\nimport { QUERY_KEY_PATIENT_EPISODES_OF_CARE } from \"@/utils/query-keys\";\n\nexport function usePatientEpisodesOfCare() {\n  return useTimingQueryWithPatient(\n    QUERY_KEY_PATIENT_EPISODES_OF_CARE,\n    [],\n    async (requestContext: CTWRequestContext, patient: PatientModel) => {\n      try {\n        const graphClient = createGraphqlClient(requestContext);\n        const { data } = await fqsRequest<EpisodeOfCareGraphqlResponse>(\n          graphClient,\n          episodeOfCareQuery,\n          {\n            upid: patient.UPID,\n            cursor: \"\",\n            first: MAX_OBJECTS_PER_REQUEST,\n            sort: {\n              lastUpdated: \"DESC\",\n            },\n            filter: {\n              tag: {\n                allmatch: [\"https://zusapi.com/summary|TransitionsOfCare\"],\n              },\n            },\n          },\n        );\n        const nodes = data.EpisodeOfCareConnection.edges.map((x) => x.node);\n        const results = nodes.map((c) => new EpisodeOfCareModel(c, []));\n        if (results.length === 0) {\n          Telemetry.countMetric(\"req.count.episodesOfCare.none\", 1);\n        }\n        Telemetry.histogramMetric(\"req.count.episodesOfCare\", results.length);\n        return results;\n      } catch (e) {\n        Telemetry.logError(e as Error, \"Failed fetching episodes of care information for patient\");\n        throw new Error(`Failed fetching episodes of care information for patient: ${e}`);\n      }\n    },\n  );\n}\n","import { faFileLines } from \"@fortawesome/free-regular-svg-icons\";\nimport { faCircleH } from \"@fortawesome/free-solid-svg-icons\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { useEpisodeOfCareDrawer } from \"./episode-of-care-drawer\";\nimport { applyFilters, OverviewFilter } from \"../overview/filters\";\nimport { ResourceOverviewCard } from \"../overview/resource-overview-card\";\nimport { ResourceTitleColumn } from \"../resource/helpers/resource-title-column\";\nimport { datePredicate } from \"../resource/helpers/view-date-range\";\nimport { usePatientEpisodesOfCare } from \"@/fhir/episode-of-care\";\nimport { EpisodeOfCareModel } from \"@/fhir/models\";\nimport { applySorts } from \"@/utils/sort\";\n\ntype EpisodeOfCaresOverviewCardProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const EpisodeOfCareOverviewCard = ({\n  onSeeAllResources,\n}: EpisodeOfCaresOverviewCardProps) => {\n  const openEpisodeOfCareDetails = useEpisodeOfCareDrawer();\n\n  const episodesOfCareQuery = usePatientEpisodesOfCare();\n  const sortedData = applySorts(episodesOfCareQuery.data ?? [], [\n    { key: \"periodStart\", dir: \"desc\", isDate: true }, // Newest first.\n  ]);\n  const filteredData = applyFilters(sortedData, getEpisodeOfCareOverviewFilters());\n  const noData = filteredData.length === 0;\n\n  return (\n    <ResourceOverviewCard\n      icon={faCircleH}\n      title=\"ED & IP Visits\"\n      data={filteredData}\n      emptyMessage={\n        noData\n          ? \"We didn't find any emergency or inpatient records for this patient.\"\n          : \"No emergency or inpatient visits found within the past year.\"\n      }\n      onRowClick={(episodeOfCare) => {\n        openEpisodeOfCareDetails(episodeOfCare);\n      }}\n      onSeeAllResources={onSeeAllResources}\n      footerText=\"All Encounters\"\n      hideFooter={noData}\n      isLoading={episodesOfCareQuery.isLoading}\n      tooltipText=\"Emergency and inpatient visits from the past year.\"\n      trackingName=\"episodes_of_care_overview\"\n    >\n      {(episodeOfCare: EpisodeOfCareModel) => {\n        const documents = episodeOfCare.dischargeBinaries;\n\n        return (\n          <ResourceTitleColumn\n            title={`${episodeOfCare.dateDisplay} - ${episodeOfCare.class}`}\n            subTitle={\n              <div className=\"ctw-space-y-0.5\">\n                {episodeOfCare.location && (\n                  <div className=\"ctw-font-normal\">{episodeOfCare.location}</div>\n                )}\n                {documents.length > 0 ? (\n                  <div className=\"ctw-text-sm ctw-font-normal ctw-pt-1 ctw-flex ctw-space-x-1.5 ctw-items-center\">\n                    <FontAwesomeIcon\n                      className=\"ctw-w-4 ctw-text-content-lighter\"\n                      icon={faFileLines}\n                    />\n                    <div>\n                      {documents.length} {documents.length === 1 ? \"document\" : \"documents\"}\n                    </div>\n                  </div>\n                ) : undefined}\n              </div>\n            }\n          />\n        );\n      }}\n    </ResourceOverviewCard>\n  );\n};\n\nconst getEpisodeOfCareOverviewFilters = (): OverviewFilter<EpisodeOfCareModel>[] => [\n  {\n    key: \"emergency\",\n    label: \"Filter for emergency episodes\",\n    description: \"Is an emergency or a hospitalization.\",\n    predicate: (episodeOfCare: EpisodeOfCareModel) =>\n      [\"EMER\", \"IMP\"].includes(episodeOfCare.classCode),\n  },\n  {\n    key: \"recent\",\n    label: \"Filter for recent episodes\",\n    description: \"Began within the past year.\",\n    predicate: (episodeOfCare: EpisodeOfCareModel) =>\n      datePredicate(episodeOfCare, \"periodStart\", 365, false),\n  },\n];\n","import { faPills } from \"@fortawesome/free-solid-svg-icons\";\nimport { useContext } from \"react\";\nimport { useMedicationDetailsDrawer } from \"./helpers/details\";\nimport { defaultMedicationSortOverview } from \"./helpers/sorts\";\nimport { useMedicationRowActions } from \"./patient-medications-all\";\nimport { ResourceOverviewCard } from \"../overview/resource-overview-card\";\nimport {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../resource/helpers/resource-title-column\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { ZapPropsStateContext } from \"@/components/core/providers/zap-props-state-context\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\nimport { groupBy, orderBy } from \"@/utils/nodash\";\nimport { values } from \"@/utils/nodash/fp\";\n\nexport type PatientMedicationOverviewProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const PatientMedicationOverview = ({\n  onSeeAllResources,\n}: PatientMedicationOverviewProps) => {\n  const userBuilderId = useUserBuilderId();\n  const query = useQueryAllPatientMedications();\n  const { props } = useContext(ZapPropsStateContext);\n  const rowActions = useMedicationRowActions(props[\"medications-all\"]?.onAddToRecord);\n  const readOnly = props[\"medications-all\"]?.readOnly ?? false;\n\n  const openDetails = useMedicationDetailsDrawer({\n    rowActions: readOnly ? undefined : rowActions,\n    enableDismissAndReadActions: false,\n  });\n\n  const { past6Months } = getDateRangeView<MedicationStatementModel>(\"lastActivityDate\", false);\n\n  const { data } = useFilteredSortedData({\n    defaultSort: defaultMedicationSortOverview, // Alphabetical\n    viewOptions: [past6Months],\n    defaultView: past6Months.display,\n    records: query.allMedications,\n  });\n\n  // Dedupe medications by active ingredient, taking the entry\n  // with the most recent lastActivityDate.\n  const dedupedData = values(\n    groupBy(data, (med: MedicationStatementModel) => med.activeIngredient),\n  ).map((meds: MedicationStatementModel[]) => orderBy(meds, \"lastActivityDate\", \"desc\")[0]);\n\n  const noData = query.allMedications.length === 0;\n\n  return (\n    <ResourceOverviewCard\n      onSeeAllResources={onSeeAllResources}\n      onRowClick={openDetails}\n      data={dedupedData}\n      emptyMessage={\n        noData\n          ? \"We didn't find any medication records for this patient.\"\n          : \"There are no medications with prescriptions or fills within the past 6 months for this patient.\"\n      }\n      footerText=\"All Medications\"\n      hideFooter={noData}\n      title=\"Medications\"\n      tooltipText=\"Medications with prescriptions or fills within the last 6 months\"\n      isLoading={query.isLoading}\n      icon={faPills}\n      trackingName=\"medications_overview\"\n    >\n      {(record: MedicationStatementModel) => (\n        <ResourceTitleColumn\n          title={record.display}\n          renderIcon={RenderOwnedByBuilderIcon(record.ownedByBuilder(userBuilderId))}\n        />\n      )}\n    </ResourceOverviewCard>\n  );\n};\n","import { EncounterModel } from \"./encounter\";\nimport { ObservationModel } from \"./observation\";\nimport { hasMatchingCode } from \"../codeable-concept\";\nimport { formatDateISOToLocal } from \"../formatters\";\nimport { SYSTEM_LOINC } from \"../system-urls\";\nimport {\n  bmiCodes,\n  bpDiastolicCodes,\n  bpSystolicCodes,\n  headCircumferenceCodes,\n  heartRateCodes,\n  heightCodes,\n  lmpCodes,\n  o2Codes,\n  painCodes,\n  respiratoryRateCodes,\n  tempCodes,\n  weightCodes,\n} from \"@/components/content/vitals/vital-loinc-codes\";\nimport { round, sum, uniq } from \"@/utils/nodash\";\nimport { sort } from \"@/utils/sort\";\n\nexport class VitalsBucket {\n  private vitals: ObservationModel[];\n\n  private encounter?: EncounterModel;\n\n  constructor(vitals: ObservationModel[], encounter?: EncounterModel) {\n    this.vitals = vitals;\n    this.encounter = encounter;\n  }\n\n  get key() {\n    return this.encounter?.id || this.vitals[0]?.id || \"\";\n  }\n\n  get date() {\n    return formatDateISOToLocal(this.dateTime);\n  }\n\n  // Our dateTime is based on the encounter date, if available, or the first vital date.\n  get dateTime() {\n    if (this.encounter) {\n      return this.encounter.resource.period?.start;\n    }\n\n    return this.vitals[0].effectiveStartRaw;\n  }\n\n  get binaryId() {\n    if (this.encounter?.binaryId) {\n      return this.encounter.binaryId;\n    }\n\n    return this.vitals.find((v) => v.binaryId)?.binaryId;\n  }\n\n  get bmi() {\n    return this.getVital(bmiCodes, { precision: 0 });\n  }\n\n  get bloodPressure() {\n    const systolic = this.getVital(bpSystolicCodes, { precision: 0 });\n    const diastolic = this.getVital(bpDiastolicCodes, { precision: 0 });\n\n    if (systolic || diastolic) {\n      return `${systolic || \"\"} / ${diastolic || \"\"}`;\n    }\n    return undefined;\n  }\n\n  get headCircumference() {\n    return this.getVital(headCircumferenceCodes, { precision: 1, unit: true });\n  }\n\n  get height() {\n    return this.getVital(heightCodes, { precision: 1, unit: true });\n  }\n\n  // Special key for filtering. See utils/filters.ts.\n  get isHidden() {\n    return !!this.encounter?.isHospitalEncounter;\n  }\n\n  get lmp() {\n    return this.getVital(lmpCodes);\n  }\n\n  get location() {\n    return this.encounter?.location;\n  }\n\n  get oxygenSaturation() {\n    return this.getVital(o2Codes, { precision: 1 });\n  }\n\n  get pain() {\n    return this.getVital(painCodes, { precision: 0 });\n  }\n\n  get pulse() {\n    return this.getVital(heartRateCodes, { precision: 0 });\n  }\n\n  get respiratoryRate() {\n    return this.getVital(respiratoryRateCodes, { precision: 0 });\n  }\n\n  get temperature() {\n    return this.getVital(tempCodes, { precision: 1, unit: true });\n  }\n\n  get typeDisplay() {\n    return this.encounter?.typeDisplay;\n  }\n\n  get weight() {\n    return this.getVital(weightCodes, { precision: 1, unit: true });\n  }\n\n  private getVital(\n    codes: string[],\n    options?: { precision?: number; unit?: boolean },\n  ): string | undefined {\n    const quantity = getVitalQuantity(this.vitals, codes);\n    if (quantity) {\n      const value = cleanUpVitalValue(quantity.value, { precision: options?.precision ?? 0 });\n      return options?.unit ? withUnit(value, quantity.unit) : String(value);\n    }\n\n    return getVitalValue(this.vitals, codes);\n  }\n}\n\n// Returns the average of the matching vitals IFF they all have the same unit.\n// Otherwise returns the most recent vital.\nfunction getVitalQuantity(vitals: ObservationModel[], codes: string[]) {\n  const matchingVitalsWithValues = vitals.filter(\n    (v) =>\n      hasMatchingCode(SYSTEM_LOINC, codes, v.resource.code) &&\n      v.resource.valueQuantity &&\n      v.resource.valueQuantity.value !== undefined,\n  );\n  if (matchingVitalsWithValues.length === 0) {\n    return undefined;\n  }\n\n  // Average them if there are multiple matching vitals with the same unit.\n  const units = matchingVitalsWithValues.map((v) => v.resource.valueQuantity?.unit);\n  if (uniq(units).length === 1) {\n    return {\n      value:\n        sum(matchingVitalsWithValues.map((v) => v.resource.valueQuantity?.value || 0)) /\n        matchingVitalsWithValues.length,\n      unit: matchingVitalsWithValues[0]?.resource.valueQuantity?.unit,\n    };\n  }\n\n  // If there are multiple matching vitals with different units, return the most recent.\n  const sorted = sort(matchingVitalsWithValues, (v) => v.effectiveStartRaw, \"desc\", true);\n  return sorted[0]?.resource.valueQuantity;\n}\n\n// Returns the most recent vitalString with a matching code.\nfunction getVitalValue(vitals: ObservationModel[], codes: string[]) {\n  const matchingVitalsWithValues = vitals.filter(\n    (v) => hasMatchingCode(SYSTEM_LOINC, codes, v.resource.code) && v.value !== \"\",\n  );\n\n  if (matchingVitalsWithValues.length === 0) {\n    return undefined;\n  }\n\n  // If there are multiple matching vitals, return the most recent.\n  const sorted = sort(matchingVitalsWithValues, (v) => v.effectiveStartRaw, \"desc\", true);\n  return sorted[0]?.value;\n}\n\nfunction withUnit(value: number | undefined, unit: string | undefined): string {\n  if (value !== undefined && unit !== undefined) {\n    return `${value} ${unit}`;\n  }\n\n  return String(value);\n}\n\nfunction cleanUpVitalValue(value: number | undefined, options: { precision: number }) {\n  if (value === undefined) {\n    return undefined;\n  }\n\n  return round(value, options.precision);\n}\n","import { Observation } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentReference } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface VitalConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<VitalWithProvenance>[];\n}\n\nexport type VitalWithProvenance = Observation & {\n  ProvenanceList: fhir4.Provenance[];\n};\n\nexport interface VitalGraphqlResponse {\n  ObservationConnection: VitalConnection;\n}\n\nexport const vitalQuery = gql`\n  ${fragmentReference}\n\n  query Vitals(\n    $upid: ID!\n    $cursor: String!\n    $sort: ObservationSortParams!\n    $filter: ObservationFilterParams!\n    $first: Int!\n  ) {\n    ObservationConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          id\n          resourceType\n          encounter {\n            reference\n          }\n          code {\n            text\n            coding {\n              code\n              display\n              system\n              extension {\n                url\n                valueString\n              }\n            }\n          }\n          effectivePeriod {\n            start\n            end\n          }\n          effectiveDateTime\n          ProvenanceList(_reference: \"target\") {\n            id\n            entity {\n              what {\n                ...Reference\n              }\n            }\n          }\n          valueQuantity {\n            comparator\n            unit\n            value\n            system\n            code\n          }\n          valueCodeableConcept {\n            text\n            coding {\n              system\n              code\n              display\n            }\n          }\n          valueString\n          valueBoolean\n          valueInteger\n          valueRange {\n            low {\n              unit\n              value\n              system\n              code\n            }\n            high {\n              unit\n              value\n              system\n              code\n            }\n          }\n          valueRatio {\n            numerator {\n              comparator\n              unit\n              value\n              system\n              code\n            }\n            denominator {\n              unit\n              value\n              system\n              code\n            }\n          }\n          valueTime\n          valueDateTime\n          valuePeriod {\n            start\n            end\n          }\n        }\n      }\n    }\n  }\n`;\n","import { getEncountersFromFQS } from \"./encounters\";\nimport { EncounterModel, ObservationModel, PatientModel } from \"./models\";\nimport { VitalsBucket } from \"./models/vitals-bucket\";\nimport { referenceToId } from \"./resource-helper\";\nimport { SYSTEM_LOINC } from \"./system-urls\";\nimport { vitalLoincCodes } from \"@/components/content/vitals/vital-loinc-codes\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useTimingQueryWithPatient } from \"@/components/core/providers/patient-provider\";\nimport { createGraphqlClient, fqsRequest, MAX_OBJECTS_PER_REQUEST } from \"@/services/fqs/client\";\nimport { VitalGraphqlResponse, vitalQuery } from \"@/services/fqs/queries/vitals\";\nimport { compact, groupBy, orderBy, uniq } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_VITALS } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\n// Returns an array of EncounterModelWithVitals, each with an array of vitals.\nexport function usePatientVitals() {\n  return useTimingQueryWithPatient(QUERY_KEY_PATIENT_VITALS, [], fetchVitals);\n}\n\n// First fetches observations for vital loinc codes.\n// Then fetches all encounters referenced by those observations.\n// Returns an array of EncounterModelWithVitals, each with an array of vitals.\nasync function fetchVitals(requestContext: CTWRequestContext, patient: PatientModel) {\n  try {\n    const vitals = await fetchVitalObservations(requestContext, patient);\n    if (vitals.length === 0) {\n      Telemetry.countMetric(\"req.count.all_vitals.none\", 1);\n      return [];\n    }\n\n    const encounters = await fetchVitalEncounters(vitals, requestContext, patient);\n\n    Telemetry.histogramMetric(`req.count.all_vitals`, vitals.length);\n    return createVitalBuckets(vitals, encounters);\n  } catch (e) {\n    throw Telemetry.logError(e as Error, `Failed fetching vitals for patient: ${patient.UPID}`);\n  }\n}\n\nasync function fetchVitalObservations(requestContext: CTWRequestContext, patient: PatientModel) {\n  const codes = vitalLoincCodes.map((loincCode) => `${SYSTEM_LOINC}|${loincCode}`); // turn loincCodes into system|code format expected by FQS\n  const graphClient = createGraphqlClient(requestContext);\n  const { data } = await fqsRequest<VitalGraphqlResponse>(graphClient, vitalQuery, {\n    upid: patient.UPID,\n    cursor: \"\",\n    first: MAX_OBJECTS_PER_REQUEST,\n    sort: {\n      lastUpdated: \"DESC\",\n    },\n    filter: {\n      code: {\n        anymatch: codes,\n      },\n    },\n  });\n\n  const vitalModels = data.ObservationConnection.edges.map(\n    ({ node }) => new ObservationModel(node, node.ProvenanceList),\n  );\n\n  // Remove vitals that don't have any value.\n  // This can help prevent blank columns appearing in our vitals table.\n  return vitalModels.filter((vital) => vital.value !== \"\");\n}\n\nfunction fetchVitalEncounters(\n  vitals: ObservationModel[],\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n) {\n  const encounterRefs = uniq(\n    vitals.map((observation) => observation.resource.encounter?.reference),\n  );\n  const encounterIds = compact(encounterRefs.map(referenceToId));\n  return getEncountersFromFQS(MAX_OBJECTS_PER_REQUEST, encounterIds)(requestContext, patient);\n}\n\n// Group all vitals by date and grab the most recent encounter for each date.\n// This way we handle a few different cases:\n// 1. Duplicate encounters for the same date. We'll add all of their vitals to a single bucket\n//    and take the average of the matching vitals thus cancelling out the duplications.\n// 2. Vitals without encounters will still be grouped by date and displayed in the UI.\n// 3. Different encounters on the same date will be displayed together, using the most recent\n//    encounter for that date.\nfunction createVitalBuckets(vitals: ObservationModel[], encounters: EncounterModel[]) {\n  const vitalsByDate = groupBy(vitals, (observation) => observation.effectiveStart);\n  const encountersByDate = groupBy(encounters, \"periodStart\");\n\n  return Object.entries(vitalsByDate).map(([date, dateVitals]) => {\n    // Grab the most recent encounter that has a type.\n    const orderedEncounters = orderBy(\n      encountersByDate[date],\n      (e) => e.resource.period?.start,\n      \"desc\",\n    );\n    const encounter =\n      orderedEncounters.find((e) => e.typeDisplay !== \"Unknown\") ?? orderedEncounters[0];\n    return new VitalsBucket(dateVitals, encounter);\n  });\n}\n","import { useMemo } from \"react\";\nimport { VitalsBucket } from \"@/fhir/models/vitals-bucket\";\nimport { usePatientVitals } from \"@/fhir/vitals\";\nimport { orderBy } from \"@/utils/nodash\";\n\ntype OverviewVitals = {\n  isLoading: boolean;\n  data: {\n    vital: string;\n    value?: string;\n    date?: string;\n  }[];\n};\n\nconst OVERVIEW_VITALS = [\n  { title: \"BP\", dataIndex: \"bloodPressure\" },\n  { title: \"HR\", dataIndex: \"pulse\" },\n  { title: \"Temp\", dataIndex: \"temperature\" },\n  { title: \"RR\", dataIndex: \"respiratoryRate\" },\n  { title: \"SpO2\", dataIndex: \"oxygenSaturation\" },\n  { title: \"Ht/Lt\", dataIndex: \"height\" },\n  { title: \"Wt\", dataIndex: \"weight\" },\n  { title: \"BMI\", dataIndex: \"bmi\" },\n  { title: \"HC\", dataIndex: \"headCircumference\" },\n  { title: \"LMP\", dataIndex: \"lmp\" },\n  { title: \"Pain\", dataIndex: \"pain\" },\n] as { title: string; dataIndex: keyof VitalsBucket }[];\n\nconst VITALS_TO_DROP_WHEN_BLANK = [\"HC\", \"LMP\", \"Pain\"];\n\nexport function usePatientVitalsOverview(): OverviewVitals {\n  const { data, isLoading } = usePatientVitals();\n\n  return useMemo(() => {\n    if (isLoading || !data?.length) {\n      return {\n        isLoading,\n        data: [],\n      };\n    }\n\n    // Get newest encounters first, so that we grab most recent vitals first.\n    const sortedBuckets = orderBy(data, (e) => e.dateTime, \"desc\");\n\n    // For each vital, find the most recent encounter that has that vital.\n    const overviewVitals = OVERVIEW_VITALS.map((vital) => {\n      const vitalBucket = sortedBuckets.find((e) => e[vital.dataIndex]);\n      const value = vitalBucket?.[vital.dataIndex] as string | undefined;\n      const date = vitalBucket?.date;\n\n      return {\n        vital: vital.title,\n        value,\n        date,\n      };\n    });\n\n    // Filter out some of our empty vitals.\n    return {\n      isLoading: false,\n      data: overviewVitals.filter(\n        (v) => !VITALS_TO_DROP_WHEN_BLANK.includes(v.vital) || v.value !== undefined,\n      ),\n    };\n  }, [data, isLoading]);\n}\n","import { faHeartPulse } from \"@fortawesome/free-solid-svg-icons\";\nimport { usePatientVitalsOverview } from \"./helpers/use-patient-overview-vitals\";\nimport { OverviewCard, OverviewCardBodyMessage } from \"../overview/overview-card\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { usePatientVitals } from \"@/fhir/vitals\";\n\nexport type PatientVitalsOverviewProps = {\n  onSeeAllResources: () => void;\n};\n\nexport const PatientVitalsOverview = ({ onSeeAllResources }: PatientVitalsOverviewProps) => {\n  const { trackInteraction } = useAnalytics();\n  const { data, isLoading } = usePatientVitals();\n  const vitals = usePatientVitalsOverview();\n\n  return (\n    <OverviewCard\n      icon={faHeartPulse}\n      isLoading={isLoading}\n      title=\"Most Recent Vitals\"\n      tooltipText=\"Displays most recent available recorded vitals\"\n      footerText=\"All Vitals\"\n      hideFooter={isLoading || data?.length === 0}\n      footerOnClick={() => {\n        trackInteraction(\"see_all_of_resource\", { target: \"vitals_overview\" });\n        onSeeAllResources();\n      }}\n    >\n      {!data || data.length === 0 ? (\n        <OverviewCardBodyMessage message=\"No vitals records found.\" />\n      ) : (\n        vitals.data.map((vital) => (\n          <div className=\"ctw-py-1.5 ctw-px-3 ctw-flex ctw-space-x-3\" key={vital.vital}>\n            <div className=\"ctw-font-medium ctw-w-14\">{vital.vital}</div>\n            <div className=\"ctw-text-right ctw-w-[7.25rem]\">{vital.value}</div>\n            <div className=\"ctw-text-right ctw-w-[5.25rem]\">\n              {vital.date ? vital.date : <span className=\"ctw-text-content-lighter\">N/A</span>}\n            </div>\n          </div>\n        ))\n      )}\n    </OverviewCard>\n  );\n};\n","import { useMemo } from \"react\";\nimport { usePatientHistoryStatus } from \"@/components/content/patient-history/use-patient-history-status\";\nimport { usePatientVitalsOverview } from \"@/components/content/vitals/helpers/use-patient-overview-vitals\";\nimport { usePatientDiagnosticReportsWithTrendData } from \"@/fhir/diagnostic-report\";\nimport { usePatientEncountersWithClinicalNotes } from \"@/fhir/encounters\";\nimport { useQueryAllPatientMedications } from \"@/hooks/use-medications\";\nimport { usePatientConditionsAll } from \"@/services/conditions\";\n\n// Provides a union of the loading and no data states for all overview cards data fetchers.\n// This way we can know whether any cards are loading and if all cards have zero data.\nexport function useOverviewCardsLoadedState() {\n  const conditionsAllQuery = usePatientConditionsAll();\n  const medicationsQuery = useQueryAllPatientMedications();\n  const diagnosticReportsQuery = usePatientDiagnosticReportsWithTrendData();\n  const encountersQuery = usePatientEncountersWithClinicalNotes();\n  const vitalsQuery = usePatientVitalsOverview();\n  const patientHistoryStatus = usePatientHistoryStatus();\n\n  const conditions = useMemo(\n    () => ({\n      isLoading: conditionsAllQuery.isLoading,\n      noData: conditionsAllQuery.data.length === 0,\n    }),\n    [conditionsAllQuery.data.length, conditionsAllQuery.isLoading],\n  );\n\n  const medications = useMemo(\n    () => ({\n      isLoading: medicationsQuery.isLoading,\n      noData: medicationsQuery.allMedications.length === 0,\n    }),\n    [medicationsQuery.allMedications.length, medicationsQuery.isLoading],\n  );\n\n  const diagnosticReports = useMemo(\n    () => ({\n      isLoading: diagnosticReportsQuery.isLoading,\n      noData: diagnosticReportsQuery.data.length === 0,\n    }),\n    [diagnosticReportsQuery.data.length, diagnosticReportsQuery.isLoading],\n  );\n\n  const encounters = useMemo(\n    () => ({\n      isLoading: encountersQuery.isLoading,\n      noData: encountersQuery.data.length === 0,\n    }),\n    [encountersQuery.data.length, encountersQuery.isLoading],\n  );\n\n  const vitals = useMemo(\n    () => ({\n      isLoading: vitalsQuery.isLoading,\n      noData: vitalsQuery.data.length === 0,\n    }),\n    [vitalsQuery.data.length, vitalsQuery.isLoading],\n  );\n\n  const patientHistory = useMemo(\n    () => ({\n      isLoading: patientHistoryStatus.isLoading,\n      noData: !patientHistoryStatus.derivedStatus && !patientHistoryStatus.lastCompletedDate,\n    }),\n    [\n      patientHistoryStatus.derivedStatus,\n      patientHistoryStatus.isLoading,\n      patientHistoryStatus.lastCompletedDate,\n    ],\n  );\n\n  return useMemo(() => {\n    const resources = [\n      conditions,\n      medications,\n      diagnosticReports,\n      encounters,\n      vitals,\n      patientHistory,\n    ];\n\n    return {\n      isLoading: resources.some((resource) => resource.isLoading),\n      noData: resources.every((resource) => resource.noData),\n    };\n  }, [conditions, diagnosticReports, encounters, medications, patientHistory, vitals]);\n}\n","import cx from \"classnames\";\nimport { useEffect, useRef, useState } from \"react\";\nimport Masonry from \"react-responsive-masonry\";\nimport { OVERVIEW_CARD_MIN_WIDTH } from \"./overview-card\";\nimport { ZusInformationCard } from \"./zus-information-card\";\nimport { PatientConditionOverview } from \"../conditions/patient-conditions-overview\";\nimport { PatientDiagnosticReportsOverview } from \"../diagnostic-reports/patient-diagnostic-reports-overview\";\nimport { EncountersOverviewCard } from \"../encounters/encounters-overview-card\";\nimport { EpisodeOfCareOverviewCard } from \"../episode-of-care/episode-of-care-overview-card\";\nimport { PatientMedicationOverview } from \"../medications/patient-medications-overview\";\nimport { PatientVitalsOverview } from \"../vitals/patient-vitals-overview\";\nimport { usePatientError } from \"@/components/content/hooks/use-patient-error\";\nimport { useOverviewCardsLoadedState } from \"@/components/content/overview/helpers/use-overview-cards-loaded-state\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport { useBuilderConfig } from \"@/hooks/use-builder-config\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\n\nexport type OverviewResources =\n  | \"conditions\"\n  | \"medications\"\n  | \"diagnostics\"\n  | \"encounters\"\n  | \"vitals\";\n\nexport type PatientOverviewProps = {\n  className?: string;\n  hideRequestRecords?: boolean;\n  includePatientDemographicsForm?: boolean;\n  onSeeAllResources: (resource: OverviewResources) => void;\n};\n\nexport const PatientOverviewComponent = ({\n  className,\n  hideRequestRecords = false,\n  includePatientDemographicsForm,\n  onSeeAllResources,\n}: PatientOverviewProps) => {\n  const ref = useRef(null);\n  const [columnsCount, setColumnsCount] = useState(1);\n  const breakpoints = useBreakpoints(ref);\n  const hasVitalFeature = useFeatureToggle(\"ctw-vitals\");\n  const cardsLoadedState = useOverviewCardsLoadedState();\n  const { notFoundError } = usePatientError();\n  const builderConfig = useBuilderConfig();\n\n  const gutterWidth = 12;\n\n  useEffect(() => {\n    // Calculate how many additional columns we can fit. We remove 1 from the width\n    // and then divide by (card width + gutter) to determine how many additional\n    // columns we can fit.\n    const additionalColumns = Math.floor(\n      (breakpoints.width - OVERVIEW_CARD_MIN_WIDTH) / (OVERVIEW_CARD_MIN_WIDTH + gutterWidth),\n    );\n    // Since we first removed 1 from the width, we need to add it back to the column count.\n    // We also ensure we have at least 1 column (fixes init bug where width is 0).\n    setColumnsCount(Math.max(1 + additionalColumns, 1));\n  }, [breakpoints]);\n\n  const tablesAreEmpty = !cardsLoadedState.isLoading && cardsLoadedState.noData;\n  if (notFoundError || tablesAreEmpty) {\n    return (\n      <div className={cx(className, \"ctw-scrollable-pass-through-height ctw-pt-8\")}>\n        <div className=\"ctw-text-center\">\n          {notFoundError ? (\n            <span className=\"ctw-font-medium\">Patient not found.</span>\n          ) : (\n            <EmptyPatientTable resourceName=\"overview\" hasZeroFilteredRecords />\n          )}\n        </div>\n      </div>\n    );\n  }\n\n  if (builderConfig.isLoading) {\n    return (\n      <div className={cx(className, \"ctw-scrollable-pass-through-height ctw-pt-8\")}>\n        <div className=\"ctw-text-center\">\n          <span className=\"ctw-font-medium\">Loading...</span>\n        </div>\n      </div>\n    );\n  }\n\n  const { overviewCards = {} } = builderConfig.data || {};\n  const cardIsEnabled = (cardName: string) => overviewCards[cardName]?.enabled !== false;\n\n  return (\n    <div className={className} ref={ref}>\n      <Masonry gutter={`${gutterWidth}px`} columnsCount={columnsCount}>\n        {cardIsEnabled(\"conditions\") && (\n          <PatientConditionOverview onSeeAllResources={() => onSeeAllResources(\"conditions\")} />\n        )}\n        {cardIsEnabled(\"medications\") && (\n          <PatientMedicationOverview onSeeAllResources={() => onSeeAllResources(\"medications\")} />\n        )}\n        {cardIsEnabled(\"diagnostics\") && (\n          <PatientDiagnosticReportsOverview\n            onSeeAllResources={() => onSeeAllResources(\"diagnostics\")}\n          />\n        )}\n        {cardIsEnabled(\"encounters\") && (\n          <EncountersOverviewCard onSeeAllResources={() => onSeeAllResources(\"encounters\")} />\n        )}\n        {cardIsEnabled(\"episodesOfCare\") && (\n          <EpisodeOfCareOverviewCard onSeeAllResources={() => onSeeAllResources(\"encounters\")} />\n        )}\n        {hasVitalFeature.enabled && cardIsEnabled(\"vitals\") && (\n          <PatientVitalsOverview onSeeAllResources={() => onSeeAllResources(\"vitals\")} />\n        )}\n        {cardIsEnabled(\"zusInformation\") && (\n          <ZusInformationCard\n            hideRequestRecords={hideRequestRecords}\n            includePatientDemographicsForm={includePatientDemographicsForm}\n          />\n        )}\n      </Masonry>\n    </div>\n  );\n};\n\nexport const PatientOverview = withErrorBoundary(PatientOverviewComponent, \"PatientOverview\");\n","import { useContext } from \"react\";\nimport { OverviewResources, PatientOverview } from \"./patient-overview\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { ZapTabStateContext } from \"@/components/core/providers/zap-tab-state-context\";\n\nexport type PatientOverviewZapProps = {\n  hideRequestRecords?: boolean;\n  includePatientDemographicsForm?: boolean;\n};\n\nexport const PatientOverviewZapComponent = ({\n  hideRequestRecords = false,\n  includePatientDemographicsForm,\n}: PatientOverviewZapProps) => {\n  const { setSelectedTab } = useContext(ZapTabStateContext);\n\n  function handleSeeAllResources(resource: OverviewResources) {\n    switch (resource) {\n      case \"conditions\":\n        setSelectedTab(\"conditions-all\");\n        break;\n      case \"medications\":\n        setSelectedTab(\"medications-all\");\n        break;\n      case \"diagnostics\":\n        setSelectedTab(\"diagnostic-reports\");\n        break;\n      case \"encounters\":\n        setSelectedTab(\"encounters\");\n        break;\n      case \"vitals\":\n        setSelectedTab(\"vitals\");\n        break;\n      default:\n    }\n  }\n\n  return (\n    <PatientOverview\n      className=\"ctw-pt-5\"\n      onSeeAllResources={handleSeeAllResources}\n      hideRequestRecords={hideRequestRecords}\n      includePatientDemographicsForm={includePatientDemographicsForm}\n    />\n  );\n};\n\nexport const PatientOverviewZap = withErrorBoundary(PatientOverviewZapComponent, \"PatientOverview\");\n","import { createContext, PropsWithChildren, useMemo } from \"react\";\n\ntype FeedbackContext = {\n  id?: string;\n};\n\nexport const FeedbackContext = createContext<FeedbackContext>({\n  id: \"\",\n});\n\nexport function FeedbackProvider({ children, id = \"\" }: PropsWithChildren<FeedbackContext>) {\n  const contextValue = useMemo(\n    () => ({\n      id,\n    }),\n    [id]\n  );\n\n  return <FeedbackContext.Provider value={contextValue}>{children}</FeedbackContext.Provider>;\n}\n","import { useContext, useState } from \"react\";\nimport { getZusServiceUrl } from \"@/api/urls\";\nimport { FeedbackContext } from \"@/components/content/patient-record-search/helpers/feedback-provider\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\n\ntype FeedbackForm = {\n  feedback: string;\n  feedbackType: string;\n};\n\ntype SubmitFeedback = {\n  submit: (data: FeedbackForm) => void;\n  isSubmitting: boolean;\n  isSubmitted: boolean;\n  isError: boolean;\n  errorMessage?: string;\n};\n\nexport const useSubmitFeedback = (name: string): SubmitFeedback => {\n  const { analyticsEvent } = useAnalytics();\n  const { id } = useContext(FeedbackContext);\n  const [isSubmitting, setIsSubmitting] = useState(false);\n  const [isSubmitted, setIsSubmitted] = useState(false);\n  const [isError, setIsError] = useState(false);\n  const [errorMessage, setErrorMessage] = useState<string | undefined>();\n  const { getRequestContext } = useCTW();\n\n  const submit = async (data: FeedbackForm) => {\n    const requestContext = await getRequestContext();\n    setIsSubmitting(true);\n    setIsError(false);\n    setErrorMessage(undefined);\n\n    try {\n      const body = JSON.stringify({\n        query_id: id,\n        feedback: data.feedback,\n        rating: data.feedbackType,\n        target: name,\n      });\n      await fetch(`${getZusServiceUrl(requestContext.env, \"search-poc\")}/feedback`, {\n        method: \"POST\",\n        body,\n        headers: {\n          Authorization: `Bearer ${requestContext.authToken}`,\n          \"Content-Type\": \"application/json\",\n          \"Zus-Account\": requestContext.builderId,\n        },\n      });\n      // Form has been submitted to the search service\n      setIsSubmitted(true);\n    } catch (e) {\n      const err = e as Error;\n      setErrorMessage(err.message);\n      setIsError(true);\n    } finally {\n      setIsSubmitting(false);\n      // We don't care about the analytics event result\n      void analyticsEvent(\"feedback\", {\n        value: \"ai_search\",\n        feedbackType: data.feedbackType,\n        target: name,\n      });\n    }\n  };\n\n  return {\n    // eslint-disable-next-line @typescript-eslint/no-misused-promises\n    submit,\n    isSubmitting,\n    isSubmitted,\n    isError,\n    errorMessage,\n  };\n};\n","import { ThumbDownIcon, ThumbUpIcon } from \"@heroicons/react/outline\";\nimport { ChangeEvent, useEffect, useState } from \"react\";\nimport { useSubmitFeedback } from \"@/components/content/patient-record-search/helpers/use-submit-feedback\";\nimport { Loading } from \"@/components/core/loading\";\n\nexport const FeedbackForm = ({ name }: { name: string }) => {\n  const [showTextInput, setShowTextInput] = useState(false);\n  const [showFinalMessage, setShowFinalMessage] = useState(false);\n  const [feedbackType, setFeedbackType] = useState(\"\");\n  const [feedback, setFeedback] = useState(\"\");\n  const { submit, isSubmitting, isSubmitted, isError, errorMessage } = useSubmitFeedback(name);\n\n  useEffect(() => {\n    let timeoutId: NodeJS.Timeout;\n    if (isSubmitted) {\n      // We only need to show the final message for a few seconds and then hide it\n      setShowFinalMessage(true);\n      timeoutId = setTimeout(() => {\n        setShowFinalMessage(false);\n      }, 2500);\n    }\n    return () => clearTimeout(timeoutId);\n  }, [isSubmitted]);\n\n  const handleThumbsDownClick = () => {\n    setFeedbackType(\"negative\");\n    setShowTextInput(true);\n  };\n\n  const handleThumbsUpClick = () => {\n    setFeedbackType(\"positive\");\n    setShowTextInput(false);\n    submit({\n      feedback: \"\",\n      feedbackType: \"positive\",\n    });\n  };\n\n  const handleTextInputChange = (event: ChangeEvent<HTMLInputElement>) => {\n    setFeedback(event.target.value);\n  };\n\n  const handleSubmit = () => {\n    submit({\n      feedback,\n      feedbackType,\n    });\n  };\n\n  const handleClear = () => {\n    setShowTextInput(false);\n    setFeedback(\"\");\n    setFeedbackType(\"\");\n    setShowFinalMessage(false);\n  };\n\n  if (isSubmitting) {\n    return (\n      <div>\n        Submitting feedback... <Loading />\n      </div>\n    );\n  }\n\n  if (isSubmitted) {\n    return showFinalMessage ? (\n      <div className=\"ctw-patient-record-search-feedback\">\n        <span>\n          {isError\n            ? `There was an error submitting your feedback; ${errorMessage}`\n            : \"Thank you for your feedback!\"}\n        </span>\n      </div>\n    ) : null;\n  }\n\n  return (\n    <div className=\"ctw-patient-record-search-feedback\">\n      {!showTextInput && (\n        <>\n          <button\n            type=\"button\"\n            className=\"ctw-btn ctw-btn-clear ctw-mr-0.5\"\n            onClick={handleThumbsUpClick}\n          >\n            <span className=\"ctw-inline-block ctw-h-4 ctw-w-4\">\n              {\" \"}\n              <ThumbUpIcon className=\"ctw-stroke-black hover:ctw-fill-primary-light hover:ctw-stroke-primary-dark\" />\n            </span>\n          </button>\n          <button\n            type=\"button\"\n            className=\"ctw-btn ctw-btn-clear ctw-mr-0.5\"\n            onClick={handleThumbsDownClick}\n          >\n            <span className=\"ctw-inline-block ctw-h-4 ctw-w-4\">\n              {\" \"}\n              <ThumbDownIcon className=\"ctw-stroke-black hover:ctw-fill-error-light hover:ctw-stroke-error-dark\" />\n            </span>\n          </button>\n        </>\n      )}\n\n      {showTextInput && (\n        <>\n          <input\n            type=\"text\"\n            placeholder=\"Please provide more feedback...\"\n            className=\"ctw-rounded-md ctw-border ctw-border-solid ctw-border-icon-light ctw-bg-bg-white ctw-px-3 ctw-py-2 ctw-pl-1.5 ctw-pr-1.5 ctw-text-sm ctw-shadow-sm\"\n            value={feedback}\n            onChange={handleTextInputChange}\n            onKeyUp={(event) => {\n              if (!event.metaKey && event.key === \"Enter\") handleSubmit();\n              if (event.key === \"Escape\") {\n                handleClear();\n              }\n            }}\n          />\n          <button type=\"button\" className=\"ctw-btn ctw-btn-primary ctw-ml-3\" onClick={handleSubmit}>\n            Submit\n          </button>\n        </>\n      )}\n    </div>\n  );\n};\n","import fhir4 from \"fhir/r4\";\nimport { FeedbackForm } from \"@/components/content/patient-record-search/helpers/feedback-form\";\nimport { Badge } from \"@/components/core/badge\";\nimport { FHIRModel } from \"@/fhir/models/fhir-model\";\n\ntype SearchResultProps<T extends FHIRModel<fhir4.Resource>> = {\n  resource: T;\n  heading?: string;\n  label: string;\n  openDetails?: (record: T) => void;\n  text?: string | JSX.Element;\n  details?: { label: string; value?: string }[];\n};\n\nexport function SearchResult<T extends FHIRModel<fhir4.Resource>>({\n  resource,\n  heading,\n  openDetails,\n  label,\n  text,\n  details,\n}: SearchResultProps<T>) {\n  return (\n    <div className=\"ctw-patient-record-search-result\">\n      <div className=\"ctw-flex ctw-items-end ctw-justify-between\">\n        <span>\n          <button\n            type=\"button\"\n            className=\"ctw-patient-record-search-result-btn\"\n            onClick={() => openDetails?.(resource)}\n          >\n            {heading}\n          </button>\n          <Badge color=\"primary\" text={label} />\n        </span>\n        <FeedbackForm name={`${resource.resourceType}/${resource.id}`} />\n      </div>\n      <div className=\"ctw-patient-record-search-text\">{text}</div>\n\n      <div className=\"ctw-patient-record-search-details\">\n        {details?.map((detail) => (\n          <div key={detail.label} data-label={detail.label}>\n            {detail.value}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n","import { isEmptyClinicalNote, isSectionDocument } from \"./filters\";\nimport { Notes } from \"../../resource/helpers/notes\";\nimport { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { usePatientDocuments } from \"@/fhir/document\";\nimport { DocumentModel } from \"@/fhir/models\";\nimport { sortBy } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_DOCUMENTS } from \"@/utils/query-keys\";\n\nexport const DocumentNotes = (document: DocumentModel) => {\n  const allDocuments = usePatientDocuments();\n  // If we're showing the detail drawer for a section document, we only want to show content from that document\n  // Otherwise show content from all clinical notes\n  const { binaryId, id } = document;\n\n  const clinicalNotes = isSectionDocument(document)\n    ? [document]\n    : sortBy(\n        allDocuments.data?.filter(\n          (d) => d.binaryId === binaryId && !isEmptyClinicalNote(d) && isSectionDocument(d),\n        ),\n        \"title\",\n      );\n\n  return <Notes entries={clinicalNotes} documentIdToStartOpen={id} />;\n};\n\nexport const useDocumentDetailsDrawer = ({\n  rowActions,\n}: {\n  rowActions?: (c: DocumentModel) => RowActionsConfigProp<DocumentModel>;\n}) =>\n  useResourceDetailsDrawer({\n    header: (m) => m.title,\n    details: documentData,\n    rowActions,\n    enableDismissAndReadActions: true,\n    renderChild: DocumentNotes,\n    queryKey: QUERY_KEY_PATIENT_DOCUMENTS,\n  });\n\nconst documentData = (document: DocumentModel) => [\n  { label: \"Encounter Date\", value: document.encounterDate },\n  { label: \"Date Retrieved\", value: document.dateCreated },\n  { label: \"Author\", value: document.custodian },\n];\n","type Span = {\n  begin: number;\n  end: number;\n};\n\nexport function getRelevantContentFromDocumentSearchResult(text: string, spans: Span[]) {\n  if (spans.length === 0) {\n    return <>{text}</>;\n  }\n  const sortedSpans = getNonOverlappingSpans(spans);\n  let idx = 0;\n  const parts: string[] = [];\n  sortedSpans.forEach((span) => {\n    parts.push(text.slice(idx, span.begin));\n    idx = span.begin;\n    parts.push(text.slice(idx, span.end));\n    idx = span.end;\n  });\n  parts.push(text.slice(idx));\n  parts[0] = parts[0].slice(parts[0].length - 100);\n  return (\n    <>\n      {spans[0].begin > 0 && <span>...</span>}\n      {parts.map((part, i) =>\n        i % 2 === 0 ? (\n          // eslint-disable-next-line react/no-array-index-key\n          <span key={i}>{part}</span>\n        ) : (\n          // eslint-disable-next-line react/no-array-index-key\n          <span key={i} className=\"ctw-font-semibold\">\n            {part}\n          </span>\n        ),\n      )}\n    </>\n  );\n}\n\nfunction getNonOverlappingSpans(spans: Span[]): Span[] {\n  if (spans.length === 0) {\n    return [];\n  }\n\n  // Sort the spans by their start indexes\n  spans.sort((a, b) => a.begin - b.begin);\n\n  const nonOverlappingSpans: Span[] = [spans[0]];\n\n  for (let i = 1; i < spans.length; i += 1) {\n    const currentSpan = spans[i];\n    const previousSpan = nonOverlappingSpans[nonOverlappingSpans.length - 1];\n\n    // Check for overlap with the previous span\n    if (currentSpan.begin <= previousSpan.end) {\n      // Update the end index of the previous span if necessary\n      if (currentSpan.end > previousSpan.end) {\n        previousSpan.end = currentSpan.end;\n      }\n    } else {\n      // No overlap, add the current span to the result array\n      nonOverlappingSpans.push(currentSpan);\n    }\n  }\n\n  return nonOverlappingSpans;\n}\n","import type { PatientRecordSearchResult } from \"@/services/patient-record-search/patient-record-search\";\nimport { SearchResult } from \"./search-result\";\nimport { allergyData, allergyHistory } from \"../../allergies/patient-allergies\";\nimport { useConditionDetailsDrawer } from \"../../conditions/helpers/details\";\nimport { useDocumentDetailsDrawer } from \"../../document/helpers/details\";\nimport { useMedicationDetailsDrawer } from \"../../medications/helpers/details\";\nimport { useObservationsDetailsDrawer } from \"../../observations/helpers/drawer\";\nimport { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { getRelevantContentFromDocumentSearchResult } from \"@/components/content/patient-record-search/helpers/relevant-content\";\nimport {\n  AllergyModel,\n  ConditionModel,\n  DiagnosticReportModel,\n  DocumentModel,\n  MedicationStatementModel,\n} from \"@/fhir/models\";\nimport { capitalize } from \"@/utils/nodash\";\n\ntype ResourceRowProps = {\n  document: PatientRecordSearchResult[\"document\"];\n};\n\nexport function SearchResultRow(props: ResourceRowProps) {\n  const { document } = props;\n  const { resource, ...result } = document;\n  const resourceType = result.metadata.resource_type;\n\n  const openConditionDetails = useConditionDetailsDrawer({});\n  const openAllergyDetails = useResourceDetailsDrawer({\n    header: (m) => capitalize(m.display),\n    details: allergyData,\n    renderChild: allergyHistory,\n    getSourceDocument: true,\n  });\n  const openDocumentDetails = useDocumentDetailsDrawer({});\n  const openMedicationDetails = useMedicationDetailsDrawer({});\n  const openDiagnosticReportDetails = useObservationsDetailsDrawer();\n\n  switch (resourceType) {\n    case \"AllergyIntolerance\": {\n      const allergy = resource as AllergyModel;\n      return (\n        <SearchResult\n          heading={allergy.display}\n          label=\"Allergy\"\n          resource={allergy}\n          openDetails={openAllergyDetails}\n          details={[\n            { label: \"Last Updated\", value: allergy.recordedDate },\n            { label: \"Reaction\", value: allergy.manifestations },\n          ]}\n        />\n      );\n    }\n    case \"Condition\": {\n      const condition = resource as ConditionModel;\n      return (\n        <SearchResult\n          heading={condition.display}\n          label=\"Condition\"\n          resource={condition}\n          openDetails={openConditionDetails}\n          details={[\n            {\n              label: \"Last Updated\",\n              value: condition.recordedDate\n                ? `${condition.recordedDate} ${condition.recorder ?? \"\"}`\n                : \"Unknown\",\n            },\n            {\n              label: \"Earliest Known Onset\",\n              value: condition.onset,\n            },\n          ]}\n        />\n      );\n    }\n\n    case \"DocumentReference\": {\n      const doc = resource as DocumentModel;\n      return (\n        <SearchResult\n          heading={doc.title}\n          label=\"Document\"\n          resource={doc}\n          openDetails={openDocumentDetails}\n          text={getRelevantContentFromDocumentSearchResult(result.page_content, result.reason.span)}\n          details={[\n            {\n              label: \"Encounter\",\n              value: doc.encounterDate,\n            },\n            {\n              label: \"Retrieved\",\n              value: doc.dateCreated,\n            },\n            {\n              label: \"Author\",\n              value: doc.custodian,\n            },\n          ]}\n        />\n      );\n    }\n\n    case \"MedicationStatement\": {\n      const medication = resource as MedicationStatementModel;\n      return (\n        <SearchResult\n          heading={medication.display}\n          label=\"Medication\"\n          resource={medication}\n          openDetails={openMedicationDetails}\n          details={[\n            {\n              label: \"Dosage\",\n              value: medication.dosage,\n            },\n            {\n              label: \"Last Filled\",\n              value: medication.lastFillDate,\n            },\n            {\n              label: \"Last Prescribed\",\n              value: medication.lastPrescribedDate\n                ? `${medication.lastPrescribedDate} ${medication.lastPrescriber}`\n                : undefined,\n            },\n          ]}\n        />\n      );\n    }\n\n    case \"DiagnosticReport\": {\n      const diagnosticReport = resource as DiagnosticReportModel;\n      return (\n        <SearchResult\n          heading={diagnosticReport.displayName}\n          label=\"Diagnostic Report\"\n          resource={diagnosticReport}\n          openDetails={openDiagnosticReportDetails}\n          details={[\n            {\n              label: \"Date\",\n              value: diagnosticReport.effectiveStart,\n            },\n            {\n              label: \"\",\n              value: diagnosticReport.details,\n            },\n          ]}\n        />\n      );\n    }\n\n    default:\n      // Unknown resource type\n      return null;\n  }\n}\n","import { Observation } from \"fhir/r4\";\nimport { gql } from \"graphql-request\";\nimport { fragmentObservation } from \"./fragments\";\nimport { GraphqlConnectionNode, GraphqlPageInfo } from \"../client\";\n\nexport interface ObservationConnection {\n  pageInfo: GraphqlPageInfo;\n  edges: GraphqlConnectionNode<Observation>[];\n}\n\nexport interface ObservationGraphqlResponse {\n  ObservationConnection: ObservationConnection;\n}\n\nexport const observationQuery = gql`\n  ${fragmentObservation}\n\n  query Observations(\n    $upid: ID!\n    $cursor: String!\n    $sort: ObservationSortParams!\n    $filter: ObservationFilterParams!\n    $first: Int!\n  ) {\n    ObservationConnection(\n      upid: $upid\n      after: $cursor\n      filter: $filter\n      sort: $sort\n      first: $first\n    ) {\n      pageInfo {\n        hasNextPage\n      }\n      edges {\n        node {\n          ...Observation\n        }\n      }\n    }\n  }\n`;\n","import { ObservationModel, PatientModel } from \"./models\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport { ObservationGraphqlResponse, observationQuery } from \"@/services/fqs/queries/observations\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport async function fetchObservationsById(\n  requestContext: CTWRequestContext,\n  patient: PatientModel,\n  ids: string[],\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<ObservationGraphqlResponse>(graphClient, observationQuery, {\n      upid: patient.UPID,\n      cursor: \"\",\n      first: 500,\n      sort: {},\n      filter: {\n        ids: {\n          anymatch: ids,\n        },\n      },\n    });\n\n    return data.ObservationConnection.edges.map(({ node }) => new ObservationModel(node));\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching observations by ID for patient: ${patient.UPID}`,\n    );\n  }\n}\n","import { UseQueryResult } from \"@tanstack/react-query\";\nimport fhir4 from \"fhir/r4\";\nimport { getZusServiceUrl } from \"@/api/urls\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { useQueryWithPatient } from \"@/components/core/providers/patient-provider\";\nimport { getAllergyIntolerancesById } from \"@/fhir/allergies\";\nimport { fetchDiagnosticReportsFromFQSById } from \"@/fhir/diagnostic-report\";\nimport { getDocumentsByIdFromFQS } from \"@/fhir/document\";\nimport { getMedicationStatementsByIdFQS } from \"@/fhir/medications\";\nimport {\n  AllergyModel,\n  ConditionModel,\n  DiagnosticReportModel,\n  MedicationStatementModel,\n  ObservationModel,\n  PatientModel,\n} from \"@/fhir/models\";\nimport { DocumentModel } from \"@/fhir/models/document\";\nimport { fetchObservationsById } from \"@/fhir/observations\";\nimport { LENS_EXTENSION_ID } from \"@/fhir/system-urls\";\nimport { fetchConditionsByIdFQS } from \"@/services/conditions\";\nimport { groupBy, keyBy, mapValues, uniq } from \"@/utils/nodash\";\nimport { QUERY_KEY_AI_SEARCH } from \"@/utils/query-keys\";\n\ntype PatientRecordSearchResourceType =\n  | \"AllergyIntolerance\"\n  | \"Condition\"\n  | \"DocumentReference\"\n  | \"MedicationStatement\"\n  | \"Observation\"\n  | \"DiagnosticReport\";\n\ntype ResourceByTypeMapping = Record<\n  PatientRecordSearchResourceType,\n  PatientRecordSearchResponseRawDocument[]\n>;\ntype ResourceIdByTypeMapping = Record<PatientRecordSearchResourceType, string[]>;\n\nexport type PatientRecordSearchResponseRawDocument = {\n  original_content?: fhir4.Resource;\n  page_content: string;\n  summary: string;\n  reason: {\n    // highlighting behavior on N spans in page_content\n    search_type: string[]; // origination of what the search engine did that surfaced this information\n    span: { begin: number; end: number }[];\n  };\n  metadata: {\n    resource_id: string;\n    resource_type: PatientRecordSearchResourceType;\n    subject: string;\n    upid: string;\n  };\n};\n\nexport type PatientRecordSearchResponseRaw = {\n  documents: PatientRecordSearchResponseRawDocument[];\n  query: string;\n  query_id: string;\n  response: string;\n  service_version: string;\n};\n\nexport type PatientRecordSearchResult = {\n  page_content: string;\n  upid: string;\n  document: PatientRecordSearchResponseRawDocument & {\n    resource?:\n      | AllergyModel\n      | ConditionModel\n      | DocumentModel\n      | MedicationStatementModel\n      | ObservationModel\n      | DiagnosticReportModel;\n  };\n};\n\nexport type PatientRecordSearchResults = {\n  id: string;\n  results: readonly PatientRecordSearchResult[];\n  query: string;\n  response: string;\n  total: number;\n};\n\nexport const EMPTY_SEARCH_RESULTS: PatientRecordSearchResults = {\n  id: \"\",\n  query: \"\",\n  response: \"\",\n  results: [] as PatientRecordSearchResult[],\n  total: 0,\n};\n\nconst EMPTY_RESOURCE_BY_TYPE_MAPPING: ResourceByTypeMapping = {\n  AllergyIntolerance: [],\n  Condition: [],\n  DocumentReference: [],\n  MedicationStatement: [],\n  DiagnosticReport: [],\n  Observation: [],\n};\n\nclass PatientRecordSearch {\n  private response: PatientRecordSearchResponseRaw;\n\n  private resources: {\n    AllergyIntolerance: Record<string, AllergyModel>;\n    Condition: Record<string, ConditionModel>;\n    DocumentReference: Record<string, DocumentModel>;\n    MedicationStatement: Record<string, MedicationStatementModel>;\n    DiagnosticReport: Record<string, DiagnosticReportModel>;\n    Observation: Record<string, ObservationModel>;\n  } = {\n    AllergyIntolerance: {},\n    Condition: {},\n    DocumentReference: {},\n    MedicationStatement: {},\n    DiagnosticReport: {},\n    Observation: {},\n  };\n\n  constructor(patientRecordSearchResponse: PatientRecordSearchResponseRaw) {\n    this.response = patientRecordSearchResponse;\n  }\n\n  get id(): string {\n    return this.response.query_id;\n  }\n\n  get results(): PatientRecordSearchResult[] {\n    return this.response.documents.map((group) => {\n      const resource = this.resources[group.metadata.resource_type][group.metadata.resource_id];\n      return {\n        upid: group.metadata.upid,\n        page_content: group.page_content,\n        document: {\n          ...group,\n          resource,\n        },\n      };\n    });\n  }\n\n  get filteredResults(): PatientRecordSearchResult[] {\n    return this.results.filter((result) => {\n      if ([\"Condition\", \"MedicationStatement\"].includes(result.document.metadata.resource_type)) {\n        const extensions = result.document.resource?.resource.extension ?? [];\n        return extensions.some(({ url }) => url === LENS_EXTENSION_ID);\n      }\n      return !!result.document.resource;\n    });\n  }\n\n  get queryString(): string {\n    return this.response.query;\n  }\n\n  get responseString(): string {\n    return this.response.response;\n  }\n\n  // Get a Map of all resource IDs from the search result by resource type\n  get resourceIds(): ResourceIdByTypeMapping {\n    const resourcesByTypePartial: Partial<ResourceByTypeMapping> = groupBy(\n      this.response.documents,\n      (r) => r.metadata.resource_type\n    );\n\n    const resourcesByType: ResourceByTypeMapping = {\n      ...EMPTY_RESOURCE_BY_TYPE_MAPPING,\n      ...resourcesByTypePartial,\n    };\n\n    return mapValues(resourcesByType, (docs) =>\n      docs.map((resource) => resource.metadata.resource_id)\n    );\n  }\n\n  // Set the resource models to their search results\n  setResources(params: {\n    allergies: AllergyModel[];\n    conditions: ConditionModel[];\n    documents: DocumentModel[];\n    medications: MedicationStatementModel[];\n    diagnosticReports: DiagnosticReportModel[];\n    observations: ObservationModel[];\n  }) {\n    this.resources.AllergyIntolerance = keyBy(params.allergies, \"id\");\n    this.resources.Condition = keyBy(params.conditions, \"id\");\n    this.resources.DocumentReference = keyBy(params.documents, \"id\");\n    this.resources.MedicationStatement = keyBy(params.medications, \"id\");\n    this.resources.DiagnosticReport = keyBy(params.diagnosticReports, \"id\");\n    this.resources.Observation = keyBy(params.observations, \"id\");\n  }\n}\n\nexport function usePatientRecordSearch(searchTerm: string): UseQueryResult<PatientRecordSearchResults> {\n  return useQueryWithPatient(\n    QUERY_KEY_AI_SEARCH,\n    [searchTerm],\n    async (requestContext: CTWRequestContext, patient: PatientModel) => {\n      // fetchResourcesById will avoid lots of boilerplate code fetching various resources from FQS.\n      const fetchResourcesById = async <T>(\n        ids: string[],\n        fn: (r: CTWRequestContext, p: PatientModel, ids: string[]) => Promise<T[]>\n      ): Promise<T[]> => (ids.length === 0 ? [] : fn(requestContext, patient, uniq(ids)));\n\n      if (searchTerm) {\n        const searchOptions = [\"keyword\"];\n\n        if (searchTerm.split(\" \").length > 2) {\n          searchOptions.push(\"semantic\");\n        }\n\n        const body = JSON.stringify({\n          query: searchTerm,\n          upid: patient.UPID,\n          include: searchOptions,\n          n_results: 30,\n          resource_types: [\n            \"AllergyIntolerance\",\n            \"Condition\",\n            \"DocumentReference\",\n            \"MedicationStatement\",\n            \"DiagnosticReport\",\n            // \"Observation\",\n          ],\n        });\n\n        const response = await fetch(\n          `${getZusServiceUrl(requestContext.env, \"search-poc\")}/search`,\n          {\n            body,\n            method: \"POST\",\n            headers: {\n              Authorization: `Bearer ${requestContext.authToken}`,\n              \"Content-Type\": \"application/json\",\n              \"Content-Length\": body.length.toString(),\n              \"Zus-Account\": requestContext.builderId,\n            },\n          }\n        );\n\n        const patientRecordSearchResult = new PatientRecordSearch(\n          (await response.json()) as PatientRecordSearchResponseRaw\n        );\n\n        const {\n          AllergyIntolerance: allergyIds,\n          Condition: conditionIds,\n          DocumentReference: documentIds,\n          MedicationStatement: medicationIds,\n          DiagnosticReport: diagnosticReportIds,\n          Observation: observationIds,\n        } = patientRecordSearchResult.resourceIds;\n\n        const allergies = await fetchResourcesById(allergyIds, getAllergyIntolerancesById);\n        const conditions = await fetchResourcesById(conditionIds, fetchConditionsByIdFQS);\n        const documents = await fetchResourcesById(documentIds, getDocumentsByIdFromFQS);\n        const medications = await fetchResourcesById(medicationIds, getMedicationStatementsByIdFQS);\n        const observations = await fetchResourcesById(observationIds, fetchObservationsById);\n        const diagnosticReports = await fetchResourcesById(\n          diagnosticReportIds,\n          fetchDiagnosticReportsFromFQSById\n        );\n\n        patientRecordSearchResult.setResources({\n          allergies,\n          conditions,\n          documents,\n          medications,\n          observations,\n          diagnosticReports,\n        });\n\n        return {\n          id: patientRecordSearchResult.id,\n          query: patientRecordSearchResult.queryString,\n          response: patientRecordSearchResult.responseString,\n          results: patientRecordSearchResult.filteredResults.sort((r) =>\n            r.document.reason.search_type.includes(\"semantic\") ? 1 : -1\n          ),\n          total: patientRecordSearchResult.filteredResults.length,\n        };\n      }\n\n      return EMPTY_SEARCH_RESULTS;\n    }\n  );\n}\n","import { XIcon } from \"@heroicons/react/outline\";\nimport { SearchIcon } from \"@heroicons/react/solid\";\nimport cx from \"classnames\";\nimport { ChangeEvent, FormEvent, useCallback, useRef, useState } from \"react\";\nimport { SearchResultRow } from \"./helpers/search-result-row\";\nimport { usePatientError } from \"@/components/content/hooks/use-patient-error\";\nimport { FeedbackProvider } from \"@/components/content/patient-record-search/helpers/feedback-provider\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { AuthError } from \"@/components/core/auth-error\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { Loading } from \"@/components/core/loading\";\nimport { DEFAULT_PAGE_SIZE, ExpandList } from \"@/components/core/pagination/expand-list\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { RenderIf } from \"@/components/core/render-if\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\nimport {\n  EMPTY_SEARCH_RESULTS,\n  PatientRecordSearchResult,\n  usePatientRecordSearch,\n} from \"@/services/patient-record-search/patient-record-search\";\nimport \"./helpers/style.scss\";\n\nexport type PatientRecordSearchProps = {\n  className?: cx.Argument;\n};\n\nfunction PatientRecordSearchComponent({ className }: PatientRecordSearchProps) {\n  const [count, setCount] = useState(DEFAULT_PAGE_SIZE);\n  const [searchTextInputValue, setSearchTextInputValue] = useState(\"\");\n  const [searchValue, setSearchValue] = useState(\"\");\n  const ref = useRef<HTMLInputElement>(null);\n  const breakpoints = useBreakpoints(ref);\n  const { authError, notFoundError } = usePatientError();\n  const {\n    data = EMPTY_SEARCH_RESULTS,\n    isFetching,\n    isLoading,\n    isError,\n  } = usePatientRecordSearch(searchValue);\n  const { trackInteraction } = useAnalytics();\n\n  const handleSubmitForm = useCallback(\n    (event: FormEvent<HTMLFormElement>) => {\n      event.preventDefault();\n      const query = searchTextInputValue.trim();\n      setSearchValue(query);\n      setCount(DEFAULT_PAGE_SIZE);\n      trackInteraction(\"search\", { action: \"patient-record-search\" });\n    },\n    [searchTextInputValue, trackInteraction],\n  );\n\n  const handleChangeInput = (event: ChangeEvent<HTMLInputElement>) => {\n    setSearchTextInputValue(event.target.value);\n  };\n\n  const clearSearch = useCallback(() => {\n    trackInteraction(\"clear_search\", { action: \"patient-record-search\" });\n    setSearchTextInputValue(\"\");\n    setSearchValue(\"\");\n  }, [trackInteraction]);\n\n  const userHasSearched = !!searchValue;\n  const hasResults = data.results.length > 0;\n\n  // Use correct empty message when there are auth errors or failure fetching patient data.\n  if (authError) {\n    return <AuthError />;\n  }\n  if (notFoundError) {\n    return <div className=\"ctw-space-y-4\">Patient not found.</div>;\n  }\n\n  return (\n    <div\n      className={cx(\n        className,\n        \"ctw-patient-record-search ctw-scrollable-pass-through-height ctw-space-x-0 ctw-space-y-2 ctw-text-base\",\n      )}\n    >\n      <form className=\"ctw-patient-record-search-input ctw-relative\" onSubmit={handleSubmitForm}>\n        <div className=\"ctw-search-icon-wrapper\">\n          <SearchIcon className=\"ctw-search-icon\" />\n        </div>\n        <input\n          ref={ref}\n          type=\"text\"\n          className=\"ctw-w-full ctw-overflow-hidden ctw-overflow-ellipsis ctw-whitespace-nowrap ctw-rounded-md ctw-border ctw-border-solid ctw-border-icon-light ctw-bg-bg-white ctw-px-3 ctw-py-2 ctw-pl-10 ctw-pr-8 ctw-text-sm ctw-shadow-sm\"\n          placeholder={\n            breakpoints.xs\n              ? \"Search patient records.\"\n              : \"Search patient conditions, medications, diagnostics, documents and allergies.\"\n          }\n          name=\"patientRecordSearch\"\n          value={searchTextInputValue}\n          onChange={handleChangeInput}\n        />\n        <button\n          aria-label=\"clear search\"\n          type=\"button\"\n          onClick={clearSearch}\n          className=\"ctw-clear-search-icon-wrapper\"\n        >\n          <XIcon className=\"ctw-clear-search-icon\" />\n        </button>\n      </form>\n\n      {isFetching || isLoading ? (\n        <div className=\"ctw-mt-3 ctw-flex ctw-justify-center ctw-space-x-1 ctw-align-middle\">\n          <Loading />\n        </div>\n      ) : (\n        <div className=\"ctw-patient-record-search-results-list ctw-scrollable-pass-through-height\">\n          <div className=\"ctw-patient-record-search-results ctw-align-left ctw-ml-0\">\n            {/* FeedbackProvider will allow all the feedback forms to get the id of the query */}\n            <FeedbackProvider id={data.id}>\n              <RenderIf condition={isError}>\n                <div className=\"ctw-w-full\">\n                  <ErrorAlert header=\"Error\">There was an error running your search.</ErrorAlert>\n                </div>\n              </RenderIf>\n\n              <RenderIf condition={userHasSearched && !hasResults && !isError}>\n                <span className=\"ctw-text-1xl ctw-text-content-dark ctw-block ctw-text-left ctw-font-medium\">\n                  Search did not find results.\n                </span>\n              </RenderIf>\n\n              {/* user has made a search and there are results */}\n              <RenderIf condition={userHasSearched && hasResults}>\n                {/* Search Results */}\n                <span className=\"ctw-text-1xl ctw-text-content-dark ctw-block ctw-text-left ctw-font-medium\">\n                  Found {data.results.length} results.\n                </span>\n                {data.results.slice(0, count).map((result: PatientRecordSearchResult, idx) => (\n                  // eslint-disable-next-line react/no-array-index-key\n                  <SearchResultRow key={idx} document={result.document} />\n                ))}\n                <div className=\"ctw-mt-5\">\n                  <ExpandList total={data.results.length} count={count} changeCount={setCount} />\n                </div>\n              </RenderIf>\n            </FeedbackProvider>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport const PatientRecordSearch = withErrorBoundary(\n  (props: PatientRecordSearchProps) => (\n    <AnalyticsProvider componentName=\"PatientRecordSearch\">\n      <PatientRecordSearchComponent {...props} />\n    </AnalyticsProvider>\n  ),\n  \"PatientRecordSearch\",\n);\n","import { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { capitalize, isEmpty } from \"@/utils/nodash\";\nimport { omit } from \"@/utils/nodash/fp\";\n\nexport const patientSourcesColumns: TableColumn<PatientModel>[] = [\n  {\n    widthPercent: 10,\n    minWidth: 128,\n    title: \"Date\",\n    render: (matchedPatient) => <div>{matchedPatient.createdAtDisplay}</div>,\n  },\n  {\n    widthPercent: 30,\n    title: \"Source\",\n    render: (matchedPatient) => (\n      <div className=\"ctw-capitalize\">{matchedPatient.organizationDisplayName}</div>\n    ),\n  },\n  {\n    widthPercent: 30,\n    title: \"Patient Details\",\n    render: (matchedPatient) => (\n      <div className=\"ctw-stacked-concat\">\n        {matchedPatient.display && <div>{matchedPatient.display}</div>}\n        {Boolean(matchedPatient.dob || matchedPatient.age || matchedPatient.gender) && <div>\n          <span>\n            {matchedPatient.dob} ({matchedPatient.age})\n          </span>\n          <span> {capitalize(matchedPatient.gender)}</span>\n        </div>}\n      </div>\n    ),\n  },\n  {\n    widthPercent: 40,\n    title: \"Contact Info\",\n    render: (matchedPatient) => (\n      <div className=\"ctw-stacked-concat\">\n        {matchedPatient.phoneNumber && <div>{matchedPatient.phoneNumber}</div>}\n        {matchedPatient.email && <div>{matchedPatient.email}</div>}\n        {matchedPatient.homeAddress?.line && <div>{matchedPatient.homeAddress.line.join(\" \")}</div>}\n        {!isEmpty(omit(\"line\", matchedPatient.homeAddress)) && <div>\n          {matchedPatient.homeAddress?.city ||\n          matchedPatient.homeAddress?.state ||\n          matchedPatient.homeAddress?.postalCode\n            ? `${matchedPatient.homeAddress.city} ${matchedPatient.homeAddress.state}, ${matchedPatient.homeAddress.postalCode}`\n            : undefined}\n        </div>}\n      </div>\n    ),\n  },\n];\n","import cx from \"classnames\";\nimport { useRef } from \"react\";\nimport { patientSourcesColumns } from \"./helpers/columns\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { Loading } from \"@/components/core/loading\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useMatchedPatients } from \"@/fhir/patient-helper\";\nimport { PatientModel, usePatient } from \"@/index\";\nimport { uniqBy } from \"@/utils/nodash\";\nimport { sort } from \"@/utils/sort\";\n\nexport type PatientSourcesProps = {\n  className?: string;\n};\n\nfunction PatientSourcesComponent({ className }: PatientSourcesProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const patient = usePatient();\n  const patientSourcesQuery = useMatchedPatients();\n  const hasNoData = patientSourcesQuery.data?.length === 0;\n\n  const dedupedData = uniqBy(\n    patientSourcesQuery.data ?? [],\n    (p: PatientModel) =>\n      [\n        p.createdAtDisplay,\n        p.organizationDisplayName,\n        p.display,\n        p.dob,\n        p.age,\n        p.gender,\n        p.phoneNumber,\n        p.email,\n        p.homeAddress,\n      ].join(\"|\"), // Stringify the array to compare its contents\n  );\n  const sortedData = sort(dedupedData, \"createdAt\", \"desc\");\n\n  if (!patient.data) {\n    return <Loading />;\n  }\n\n  return (\n    <AnalyticsProvider componentName=\"MatchedPatients\">\n      <div ref={containerRef} className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <PatientResourceTable\n          isLoading={patientSourcesQuery.isLoading}\n          data={sortedData}\n          emptyMessage={\n            <EmptyPatientTable hasZeroFilteredRecords={hasNoData} resourceName=\"patients\" />\n          }\n          columns={patientSourcesColumns}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientSources = withErrorBoundary(PatientSourcesComponent, \"MatchedPatients\");\n","import { SimpleMoreList } from \"@/components/core/simple-more-list\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { TimelineEventModel } from \"@/fhir/models/timeline-event\";\n\nexport const patientTimelineColumns: TableColumn<TimelineEventModel>[] = [\n  {\n    title: \"Date\",\n    widthPercent: 10,\n    minWidth: 120,\n    dataIndex: \"date\",\n  },\n  {\n    title: \"Type\",\n    render: (timelineEvent) => (\n      <div>\n        <div className=\"ctw-font-medium\">{timelineEvent.type}</div>\n        <div>{timelineEvent.subtype}</div>\n      </div>\n    ),\n  },\n  {\n    title: \"Actor\",\n    render: (timelineEvent) => (\n      <>\n        {timelineEvent.actorDetails.map((detail) => (\n          <div className=\"ctw-capitalize\" key={detail}>\n            {detail.toLocaleLowerCase()}\n          </div>\n        ))}\n      </>\n    ),\n  },\n  {\n    title: \"Modifiers\",\n    render: (timelineEvent) => (\n      <SimpleMoreList\n        items={timelineEvent.modifiers}\n        limit={3}\n        total={timelineEvent.modifiers.length}\n      />\n    ),\n  },\n];\n","import { faClipboardCheck } from \"@fortawesome/free-solid-svg-icons\";\nimport { FilterChangeEvent, FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { TimelineEventModel } from \"@/fhir/models/timeline-event\";\nimport { compact, isEqual, uniqWith } from \"@/utils/nodash/fp\";\n\nexport function timelineFilters(timelineEvents: TimelineEventModel[]): FilterItem[] {\n  const filters: FilterItem[] = [];\n\n  filters.push({\n    key: \"type\",\n    type: \"checkbox\",\n    icon: faClipboardCheck,\n    display: \"Type\",\n    values: compact(\n      uniqWith(\n        isEqual,\n        timelineEvents.map((te) =>\n          te.type\n            ? {\n                key: te.type,\n                name: te.type,\n              }\n            : undefined\n        )\n      )\n    ),\n  });\n\n  return filters;\n}\n\nexport const defaultTimelineFilters: FilterChangeEvent = {\n  type: {\n    key: \"type\",\n    selected: [\"Diagnostic Report\", \"Encounter\"],\n    type: \"checkbox\",\n  },\n};\n","import { useResourceDetailsDrawer } from \"../../resource/resource-details-drawer\";\nimport { CodingList } from \"@/components/core/coding-list\";\nimport { EncounterModel } from \"@/fhir/models/encounter\";\nimport { capitalize } from \"@/utils/nodash/fp\";\n\nexport function usePatientEncounterDetailsDrawer() {\n  return useResourceDetailsDrawer({\n    header: (m) => `${m.periodStart} - ${m.periodEnd}`,\n    subHeader: (m) => m.typeDisplay,\n    getSourceDocument: true,\n    details: encounterData,\n  });\n}\n\nexport const encounterData = (encounter: EncounterModel) => [\n  { label: \"Period Start\", value: encounter.periodStart },\n  { label: \"Period End\", value: encounter.periodEnd },\n  { label: \"Status\", value: capitalize(encounter.status) },\n  { label: \"Class\", value: encounter.class },\n  {\n    label: \"Type\",\n    value: encounter.typeCodings.length ? (\n      <CodingList codings={encounter.typeCodings} />\n    ) : undefined,\n  },\n  { label: \"Location\", value: encounter.location },\n  { label: \"Participants\", value: encounter.participantsDisplay },\n  { label: \"Reason\", value: encounter.reason },\n  { label: \"Diagnosis\", value: encounter.diagnoses?.join(\", \") },\n  { label: \"Discharge Disposition\", value: encounter.dischargeDisposition },\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { TimelineEventModel } from \"@/fhir/models/timeline-event\";\n\nexport const defaultTimelineSort: SortOption<TimelineEventModel> = {\n  display: \"Date (New to Old)\",\n  sorts: [{ key: \"date\", dir: \"desc\", isDate: true }],\n};\n\nexport const timelineSortOptions: SortOption<TimelineEventModel>[] = [\n  defaultTimelineSort,\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"date\", dir: \"asc\", isDate: true }],\n  },\n];\n","import { DiagnosticReportModel } from \"./diagnostic-report\";\nimport { EncounterModel } from \"./encounter\";\nimport { FHIRModel } from \"./fhir-model\";\nimport { compact } from \"@/utils/nodash\";\n\nexport type TimelineEventResource = EncounterModel | DiagnosticReportModel;\n\nexport class TimelineEventModel extends FHIRModel<TimelineEventResource> {\n  kind = \"TimelineEvent\" as const;\n\n  public model: EncounterModel | DiagnosticReportModel;\n\n  constructor(resource: TimelineEventResource) {\n    super(resource);\n    switch (resource.resourceType) {\n      case \"Encounter\":\n        this.model = resource;\n        break;\n      case \"DiagnosticReport\":\n        this.model = resource;\n        break;\n      default:\n        throw new Error(\"This resource is not in type TimelineEvent\");\n    }\n  }\n\n  get date() {\n    switch (this.model.kind) {\n      case \"Encounter\":\n        return this.model.periodStart;\n      case \"DiagnosticReport\":\n        return this.model.effectiveStart;\n      default:\n        return undefined;\n    }\n  }\n\n  get type() {\n    switch (this.model.kind) {\n      case \"Encounter\":\n        return \"Encounter\";\n      case \"DiagnosticReport\":\n        return \"Diagnostic Report\";\n      default:\n        return undefined;\n    }\n  }\n\n  get subtype() {\n    switch (this.model.kind) {\n      case \"Encounter\":\n        return this.model.typeDisplay;\n      case \"DiagnosticReport\":\n        return this.model.category;\n      default:\n        return undefined;\n    }\n  }\n\n  get actorDetails(): string[] {\n    switch (this.model.kind) {\n      case \"Encounter\":\n        return compact([this.model.participantsDisplay, this.model.location]);\n      case \"DiagnosticReport\":\n        return compact([this.model.performer]);\n      default:\n        return [];\n    }\n  }\n\n  get modifiers(): string[] {\n    switch (this.model.kind) {\n      case \"Encounter\":\n        return compact(this.model.diagnoses);\n      case \"DiagnosticReport\":\n        return [\n          this.model.results.length > 0 ? `${this.model.results.length} results available` : \"\",\n        ];\n      default:\n        return [];\n    }\n  }\n\n  get title() {\n    return `${this.date} - ${this.type}`;\n  }\n}\n","import { useEffect, useState } from \"react\";\nimport { usePatientDiagnosticReports } from \"./diagnostic-report\";\nimport { usePatientEncounters } from \"./encounters\";\nimport { TimelineEventModel } from \"./models/timeline-event\";\nimport { compact, flatten, some } from \"@/utils/nodash\";\nimport { applySorts } from \"@/utils/sort\";\n\nexport function useTimelineEvents() {\n  const [timelineEvents, setTimelineEvents] = useState<TimelineEventModel[]>();\n  const patientEncountersQuery = usePatientEncounters();\n  const diagnosticReportQuery = usePatientDiagnosticReports();\n\n  const queries = [patientEncountersQuery, diagnosticReportQuery];\n\n  useEffect(() => {\n    const models = compact(\n      flatten(queries.map((query) => query.data?.map((m) => new TimelineEventModel(m))))\n    );\n\n    setTimelineEvents(\n      applySorts(models, [\n        { dir: \"desc\", key: \"date\", isDate: true },\n        { dir: \"desc\", key: \"type\" },\n      ])\n    );\n    // Disabling because including queries will cause infinite loop\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [patientEncountersQuery.data, diagnosticReportQuery.data]);\n\n  const isLoading = some(queries, \"isLoading\");\n  const isFetching = some(queries, \"isFetching\");\n  const isError = some(queries, \"isError\");\n\n  return {\n    isFetching,\n    isLoading,\n    isError,\n    data: timelineEvents ?? [],\n  };\n}\n","import cx from \"classnames\";\nimport { useRef } from \"react\";\nimport { patientTimelineColumns } from \"./helpers/columns\";\nimport { defaultTimelineFilters, timelineFilters } from \"./helpers/filters\";\nimport { usePatientEncounterDetailsDrawer } from \"./helpers/modal-hooks\";\nimport { defaultTimelineSort, timelineSortOptions } from \"./helpers/sorts\";\nimport { useObservationsDetailsDrawer } from \"../observations/helpers/drawer\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { ResourceTable } from \"@/components/content/resource/resource-table\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { TimelineEventModel } from \"@/fhir/models/timeline-event\";\nimport { useTimelineEvents } from \"@/fhir/timeline-event\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\n\nexport type PatientTimelineProps = {\n  className?: cx.Argument;\n};\n\nexport function PatientTimeline({ className }: PatientTimelineProps) {\n  const timelineEventsQuery = useTimelineEvents();\n  const containerRef = useRef<HTMLDivElement>(null);\n  const { viewOptions, past6Months } = getDateRangeView<TimelineEventModel>(\"date\");\n\n  const { data, filters, setFilters, setSort, setViewOption, defaultSort, defaultView } =\n    useFilteredSortedData({\n      cacheKey: \"patient-timeline\",\n      viewOptions,\n      defaultView: past6Months.display,\n      defaultFilters: defaultTimelineFilters,\n      defaultSort: defaultTimelineSort,\n      records: timelineEventsQuery.data,\n    });\n\n  const isEmptyQuery = timelineEventsQuery.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openEncounterDetails = usePatientEncounterDetailsDrawer();\n  const openDiagnosticReportDetails = useObservationsDetailsDrawer();\n\n  return (\n    <AnalyticsProvider componentName=\"PatientTimeline\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")} ref={containerRef}>\n        <ResourceTableActions\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n          filterOptions={{\n            onChange: setFilters,\n            defaultFilters: defaultTimelineFilters,\n            filters: timelineFilters(timelineEventsQuery.data),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: timelineSortOptions,\n            onChange: setSort,\n          }}\n        />\n        <ResourceTable\n          showTableHead={false}\n          isLoading={timelineEventsQuery.isLoading}\n          data={data}\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"timeline records\"\n            />\n          }\n          columns={patientTimelineColumns}\n          onRowClick={(record) => {\n            switch (record.model.kind) {\n              case \"Encounter\":\n                openEncounterDetails(record.model);\n                break;\n              case \"DiagnosticReport\":\n                openDiagnosticReportDetails(record.model);\n                break;\n              default:\n            }\n          }}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n","import { faEye, faEyeSlash } from \"@fortawesome/free-solid-svg-icons\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\n\nexport const vitalFilters: FilterItem[] = [\n  {\n    key: \"showHidden\", // Special key for filtering. See utils/filters.ts.\n    type: \"tag\",\n    display: \"show hospital results\",\n    icon: faEye,\n    toggleDisplay: \"hide hospital results\",\n    toggleIcon: faEyeSlash,\n  },\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { VitalsBucket } from \"@/fhir/models/vitals-bucket\";\n\nexport const defaultVitalSort: SortOption<VitalsBucket> = {\n  display: \"Date (New to Old)\",\n  sorts: [{ key: \"dateTime\", dir: \"desc\" }],\n};\n\nexport const vitalSortOptions: SortOption<VitalsBucket>[] = [\n  defaultVitalSort,\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"dateTime\", dir: \"asc\" }],\n  },\n];\n","import { ViewOption } from \"../resource/helpers/view-button\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { VitalsBucket } from \"@/fhir/models/vitals-bucket\";\nimport { sort } from \"@/utils/sort\";\n\nconst { past30days, past3months, past6Months, pastYear, allTime } =\n  getDateRangeView<VitalsBucket>(\"date\");\n\n// Sorts the data by most recent and then takes the first 5.\n// Note: This sort happens before the sort options sorting. So\n//       the 5 most recent can still be sorted old to new.\nconst mostRecent5: ViewOption<VitalsBucket> = {\n  display: \"5 Most Recent\",\n  filters: [(data) => sort(data, \"date\", \"desc\", true).slice(0, 5)],\n};\n\nexport const vitalViewOptions = [\n  mostRecent5,\n  past30days,\n  past3months,\n  past6Months,\n  pastYear,\n  allTime,\n];\n\nexport const defaultVitalView = mostRecent5;\n","import { ResponsiveSourceDocumentLink } from \"@/components/content/CCDA/responsive-source-document-link\";\nimport { RotatedTableRows } from \"@/components/core/rotated-table/rotated-table\";\nimport { VitalsBucket } from \"@/fhir/models/vitals-bucket\";\n\nexport function getVitalRows(vitals: VitalsBucket[] = []): RotatedTableRows<VitalsBucket>[] {\n  const rows: RotatedTableRows<VitalsBucket>[] = [\n    { title: \"Vital\", dataIndex: \"date\" },\n    { title: \"Blood Pressure\", shortTitle: \"BP\", dataIndex: \"bloodPressure\" },\n    { title: \"Pulse\", shortTitle: \"HR\", dataIndex: \"pulse\" },\n    { title: \"Temperature\", shortTitle: \"Temp\", dataIndex: \"temperature\" },\n    { title: \"Respiratory Rate\", shortTitle: \"RR\", dataIndex: \"respiratoryRate\" },\n    { title: \"Oxygen Saturation\", shortTitle: \"SpO2\", dataIndex: \"oxygenSaturation\" },\n    { title: \"Height/Length\", shortTitle: \"Ht/Lt\", dataIndex: \"height\" },\n    { title: \"Weight\", shortTitle: \"Wt\", dataIndex: \"weight\" },\n    { title: \"BMI\", dataIndex: \"bmi\" },\n  ];\n\n  // Only add these if they are present in any of the vitals.\n  if (vitals.some((vital) => vital.headCircumference !== undefined)) {\n    rows.push({ title: \"Head Circumference\", shortTitle: \"HC\", dataIndex: \"headCircumference\" });\n  }\n  if (vitals.some((vital) => vital.lmp !== undefined)) {\n    rows.push({ title: \"LMP\", dataIndex: \"lmp\" });\n  }\n  if (vitals.some((vital) => vital.pain !== undefined)) {\n    rows.push({ title: \"Pain\", dataIndex: \"pain\" });\n  }\n\n  rows.push(\n    {\n      title: \"Source Document\",\n      shortTitle: \"Source Doc\",\n      render: (vitalBucket: VitalsBucket) => (\n        <ResponsiveSourceDocumentLink\n          binaryId={vitalBucket.binaryId}\n          telemetryTarget=\"vital\"\n          text=\"Source Doc\"\n          showIcon={false}\n        />\n      ),\n    },\n    { title: \"Encounter Type\", shortTitle: \"Enc Type\", dataIndex: \"typeDisplay\" },\n    { title: \"Location\", dataIndex: \"location\" },\n  );\n\n  return rows;\n}\n","import \"./rotated-table.scss\";\nimport cx from \"classnames\";\nimport { ReactElement, useRef } from \"react\";\nimport { LoadingTable } from \"../loading-table\";\nimport { DataIndexSpecified, MinRecordItem, RenderSpecified } from \"../table/table-helpers\";\nimport { useBreakpoints } from \"@/hooks/use-breakpoints\";\n\nexport type RotatedTableRows<T extends MinRecordItem> = {\n  title: string;\n  shortTitle?: string;\n} & (DataIndexSpecified<T> | RenderSpecified<T>);\n\nexport type RotatedTableProps<T extends MinRecordItem> = {\n  className?: string;\n  rows: RotatedTableRows<T>[];\n  records: T[];\n  isLoading?: boolean;\n  emptyMessage?: string | ReactElement;\n};\n\nexport const RotatedTable = <T extends MinRecordItem>({\n  className,\n  rows,\n  records,\n  isLoading = false,\n  emptyMessage: message = \"No records found\",\n}: RotatedTableProps<T>) => {\n  const tableRef = useRef<HTMLTableElement>(null);\n  const scrollContainerRef = useRef<HTMLDivElement>(null);\n  const breakpoints = useBreakpoints(tableRef);\n\n  if (isLoading) {\n    return <LoadingTable />;\n  }\n\n  if (Object.entries(records).length === 0) {\n    return <div className=\"ctw-flex ctw-justify-center\">{message}</div>;\n  }\n\n  return (\n    <div className={cx(\"ctw-scrollable-pass-through-height ctw-space-y-4\")}>\n      <div\n        ref={tableRef}\n        className={cx(\"ctw-rotated-table-container ctw-scrollable-pass-through-height\", className, {\n          \"ctw-rotated-table-small\": breakpoints.md,\n        })}\n      >\n        <div className={cx(\"ctw-scrollbar ctw-scrollable-content\")} ref={scrollContainerRef}>\n          <table>\n            <colgroup>\n              <col />\n              {records.map((record) => (\n                <col key={record.key} />\n              ))}\n            </colgroup>\n            <tbody>\n              {rows.map((row) => (\n                <tr key={row.title}>\n                  <td className=\"ctw-title-column\">\n                    {breakpoints.md ? row.shortTitle ?? row.title : row.title}\n                  </td>\n                  {records.map((record) => {\n                    if (row.dataIndex) {\n                      const value = record[row.dataIndex] as string | undefined;\n                      return (\n                        <td key={record.key}>\n                          <div className=\"ctw-flex ctw-items-center ctw-h-full\">\n                            <div title={value} className=\"ctw-rotated-table-truncate\">\n                              {value}\n                            </div>\n                          </div>\n                        </td>\n                      );\n                    }\n\n                    return (\n                      <td key={record.key}>\n                        <div className=\"ctw-flex ctw-items-center ctw-h-full\">\n                          <div className=\"ctw-rotated-table-truncate\">{row.render?.(record)}</div>\n                        </div>\n                      </td>\n                    );\n                  })}\n                </tr>\n              ))}\n            </tbody>\n          </table>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import { useEffect, useState } from \"react\";\nimport { vitalFilters } from \"./helpers/filters\";\nimport { defaultVitalSort, vitalSortOptions } from \"./sorts\";\nimport { defaultVitalView, vitalViewOptions } from \"./views\";\nimport { getVitalRows } from \"./vital-rows\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { usePatientError } from \"@/components/content/hooks/use-patient-error\";\nimport { AuthError } from \"@/components/core/auth-error\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { RotatedTable } from \"@/components/core/rotated-table/rotated-table\";\nimport { usePatientVitals } from \"@/fhir/vitals\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\n\nexport type PatientVitalsProps = {\n  className?: string;\n};\n\nexport const PatientVitals = ({ className }: PatientVitalsProps) => {\n  const vitals = usePatientVitals();\n  const [rows, setRows] = useState<ReturnType<typeof getVitalRows>>([]);\n  const { authError, notFoundError } = usePatientError();\n\n  const { data, filters, setFilters, setSort, setViewOption, defaultSort, defaultView } =\n    useFilteredSortedData({\n      cacheKey: \"patient-vitals\",\n      viewOptions: vitalViewOptions,\n      defaultSort: defaultVitalSort,\n      records: vitals.data,\n      defaultView: defaultVitalView.display,\n    });\n\n  useEffect(() => {\n    if (!vitals.isLoading) {\n      setRows(getVitalRows(vitals.data));\n    }\n  }, [vitals.data, vitals.isLoading]);\n\n  // Use correct empty message when there are auth errors or failure fetching patient data.\n  if (authError) {\n    return <AuthError />;\n  }\n  if (notFoundError) {\n    return <div className=\"ctw-space-y-4\">Patient not found.</div>;\n  }\n\n  return (\n    <AnalyticsProvider componentName=\"PatientVitals\">\n      <ResourceTableActions\n        viewOptions={{\n          onChange: setViewOption,\n          options: vitalViewOptions,\n          defaultView,\n        }}\n        filterOptions={{\n          onChange: setFilters,\n          filters: vitalFilters,\n          selected: filters,\n        }}\n        sortOptions={{\n          defaultSort,\n          options: vitalSortOptions,\n          onChange: setSort,\n        }}\n      />\n      <RotatedTable\n        className={className}\n        records={data}\n        rows={rows}\n        isLoading={vitals.isLoading}\n        emptyMessage={\n          <EmptyPatientTable\n            hasZeroFilteredRecords={vitals.data ? vitals.data.length > 0 : false}\n            resourceName=\"vitals\"\n          />\n        }\n      />\n    </AnalyticsProvider>\n  );\n};\n","import { RenderDocBadge, ResourceTitleColumn } from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { DocumentModel } from \"@/fhir/models/document\";\n\nexport const patientDocumentColumns: TableColumn<DocumentModel>[] = [\n  {\n    widthPercent: 35,\n    minWidth: 200,\n    title: \"Title\",\n    render: (document) => (\n      <ResourceTitleColumn\n        title={document.title}\n        renderIcon={RenderDocBadge(document.contentType)}\n      />\n    ),\n  },\n  {\n    widthPercent: 18,\n    minWidth: 128,\n    title: \"Encounter Date\",\n    render: (document) => document.contextPeriodStartDate ?? document.encounterDate,\n  },\n  {\n    widthPercent: 18,\n    minWidth: 128,\n    title: \"Date Retrieved\",\n    dataIndex: \"dateCreated\",\n  },\n  {\n    widthPercent: 29,\n    minWidth: 200,\n    title: \"Author\",\n    dataIndex: \"custodian\",\n  },\n];\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { DocumentModel } from \"@/fhir/models/document\";\n\nexport const documentSortOptions: SortOption<DocumentModel>[] = [\n  {\n    display: \"Name (A-Z)\",\n    sorts: [{ key: \"title\", dir: \"asc\" }],\n  },\n  {\n    display: \"Name (Z-A)\",\n    sorts: [{ key: \"title\", dir: \"desc\" }],\n  },\n  {\n    display: \"Date (Old to New)\",\n    sorts: [\n      { key: \"contextPeriodStartDate\", dir: \"asc\", isDate: true },\n      { key: \"dateCreated\", dir: \"asc\", isDate: true },\n      { key: \"title\", dir: \"asc\" },\n    ],\n  },\n  {\n    display: \"Date (New To Old)\",\n    sorts: [\n      { key: \"contextPeriodStartDate\", dir: \"desc\", isDate: true },\n      { key: \"dateCreated\", dir: \"desc\", isDate: true },\n      { key: \"title\", dir: \"asc\" },\n    ],\n  },\n];\n\nexport const defaultDocumentSort = documentSortOptions[3];\n","import cx from \"classnames\";\nimport { useRef } from \"react\";\nimport { patientDocumentColumns } from \"./helpers/columns\";\nimport { useDocumentDetailsDrawer } from \"./helpers/details\";\nimport { documentsFilter } from \"./helpers/filters\";\nimport { defaultDocumentSort, documentSortOptions } from \"./helpers/sorts\";\nimport { getDateRangeView } from \"../resource/helpers/view-date-range\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { useCCDAModal } from \"@/components/content/CCDA/modal-ccda\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { ContentTypeIcon } from \"@/components/core/icons/content-type-icon\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { RowActionsConfigProp } from \"@/components/core/table/table-rows\";\nimport { getBinaryDocument } from \"@/fhir/binaries\";\nimport { usePatientTopLevelDocuments } from \"@/fhir/document\";\nimport { DocumentModel } from \"@/fhir/models/document\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { useBaseTranslations } from \"@/i18n\";\nimport { QUERY_KEY_PATIENT_DOCUMENTS } from \"@/utils/query-keys\";\n\nexport type PatientDocumentsProps = {\n  className?: string;\n  onAddToRecord?: (document: DocumentModel, binary: fhir4.Binary) => void;\n};\n\nfunction PatientDocumentsComponent({ className, onAddToRecord }: PatientDocumentsProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n\n  const patientDocumentQuery = usePatientTopLevelDocuments();\n  const rowActions = useRowActions(onAddToRecord);\n  const { viewOptions, allTime } = getDateRangeView<DocumentModel>(\"dateCreated\");\n\n  const { data, filters, setFilters, setSort, setViewOption, defaultSort, defaultView } =\n    useFilteredSortedData({\n      cacheKey: \"patient-documents\",\n      defaultSort: defaultDocumentSort,\n      viewOptions,\n      defaultView: allTime.display,\n      records: patientDocumentQuery.data,\n    });\n\n  const isEmptyQuery = patientDocumentQuery.data.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n  const openCCDA = useCCDAModal();\n\n  return (\n    <AnalyticsProvider componentName=\"PatientDocuments\">\n      <div ref={containerRef} className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: documentsFilter(),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: documentSortOptions,\n            onChange: setSort,\n          }}\n          viewOptions={{\n            onChange: setViewOption,\n            options: viewOptions,\n            defaultView,\n          }}\n        />\n        <PatientResourceTable\n          isLoading={patientDocumentQuery.isLoading}\n          data={data}\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"documents\"\n            />\n          }\n          columns={patientDocumentColumns}\n          onRowClick={(document) => {\n            if (!document.binaryId) {\n              return;\n            }\n            openCCDA(document.binaryId, document.resourceTypeTitle);\n          }}\n          rowActions={rowActions}\n          enableDismissAndReadActions\n          queryKey={QUERY_KEY_PATIENT_DOCUMENTS}\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nconst useDocumentDrawerActions = () => {\n  const { t } = useBaseTranslations();\n  const openCCDA = useCCDAModal();\n\n  return (record: DocumentModel): RowActionsConfigProp<DocumentModel> => {\n    const actions: RowActionsConfigProp<DocumentModel> = [];\n\n    if (record.binaryId) {\n      actions.push({\n        className: \"ctw-btn-primary ctw-fill-white ctw-ml-1 ctw-capitalize\",\n        testId: \"preview-document\",\n        text: t(\"resourceTable.preview\"),\n        render: () => (\n          <span className=\"ctw-space-x-1.5\">\n            <span className=\"ctw-relative ctw-inline-block ctw-w-4 ctw-pr-4 ctw-align-middle\">\n              <ContentTypeIcon\n                contentType={record.contentType ?? \"\"}\n                className=\"ctw-absolute -ctw-top-2.5 ctw-left-0 ctw-w-4 ctw-h-4\"\n              />\n            </span>\n            <span>{t(\"resourceTable.preview\")}</span>\n          </span>\n        ),\n        onClick: async () => {\n          openCCDA(record.binaryId as string, record.resourceTypeTitle);\n        },\n      });\n    }\n\n    return actions;\n  };\n};\n\nfunction useRowActions(onAddToRecord?: (document: DocumentModel, binary: fhir4.Binary) => void) {\n  const { t } = useBaseTranslations();\n  const documentActions = useDocumentDrawerActions();\n  const { trackInteraction } = useAnalytics();\n  const { getRequestContext } = useCTW();\n  const openDetails = useDocumentDetailsDrawer({ rowActions: documentActions });\n\n  return (record: DocumentModel): RowActionsConfigProp<DocumentModel> => {\n    const { binaryId } = record;\n    const actions: RowActionsConfigProp<DocumentModel> = [];\n\n    actions.push({\n      className: \"ctw-btn-default ctw-ml-1 ctw-capitalize\",\n      testId: \"view-details\",\n      text: \"View Details\",\n      onClick: () => {\n        openDetails(record);\n      },\n    });\n\n    if (binaryId && onAddToRecord) {\n      actions.push({\n        className: \"ctw-btn-primary ctw-ml-1 ctw-capitalize\",\n        testId: \"add-to-record\",\n        text: t(\"resourceTable.add\"),\n        onClick: async () => {\n          const binary = await getBinaryDocument(await getRequestContext(), binaryId);\n          onAddToRecord(record, binary);\n          trackInteraction(\"add_to_record\");\n        },\n      });\n    }\n\n    return actions;\n  };\n}\n\nexport const PatientDocuments = withErrorBoundary(PatientDocumentsComponent, \"PatientDocuments\");\n","import {\n  RenderOwnedByBuilderIcon,\n  ResourceTitleColumn,\n} from \"../../resource/helpers/resource-title-column\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { ImmunizationModel } from \"@/fhir/models/immunization\";\n\nexport const patientImmunizationsColumns = (builderId: string) => {\n  const immunizationColumns: TableColumn<ImmunizationModel>[] = [\n    {\n      title: \"Immunization\",\n      widthPercent: 60,\n      minWidth: 320,\n      render: (immunization) => (\n        <ResourceTitleColumn\n          title={immunization.description}\n          renderIcon={RenderOwnedByBuilderIcon(immunization.ownedByBuilder(builderId))}\n        />\n      ),\n    },\n    {\n      title: \"Date Given\",\n      render: (immunization) => (\n        <div>\n          <div>{immunization.occurrence} </div>\n          <div>{immunization.managingOrganization}</div>\n        </div>\n      ),\n    },\n  ];\n\n  return immunizationColumns;\n};\n","import { dismissFilter } from \"../../resource/filters\";\nimport { FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\n\nexport function immunizationsFilter(): FilterItem[] {\n  return [dismissFilter];\n}\n","import { SortOption } from \"@/components/core/sort-button/sort-button\";\nimport { ImmunizationModel } from \"@/fhir/models/immunization\";\n\nexport const defaultImmunizationSort: SortOption<ImmunizationModel> = {\n  display: \"Immunization (A-Z)\",\n  sorts: [\n    { key: \"description\", dir: \"asc\" },\n    { key: \"occurrence\", dir: \"desc\", isDate: true },\n  ],\n};\n\nexport const immunizationSortOptions: SortOption<ImmunizationModel>[] = [\n  defaultImmunizationSort,\n  {\n    display: \"Immunization (Z-A)\",\n    sorts: [\n      { key: \"description\", dir: \"desc\" },\n      { key: \"occurrence\", dir: \"desc\", isDate: true },\n    ],\n  },\n  {\n    display: \"Date (New to Old)\",\n    sorts: [{ key: \"occurrence\", dir: \"desc\", isDate: true }],\n  },\n  {\n    display: \"Date (Old to New)\",\n    sorts: [{ key: \"occurrence\", dir: \"asc\", isDate: true }],\n  },\n];\n","import cx from \"classnames\";\nimport { patientImmunizationsColumns } from \"./helpers/columns\";\nimport { immunizationsFilter } from \"./helpers/filters\";\nimport { defaultImmunizationSort, immunizationSortOptions } from \"./helpers/sort\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { useResourceDetailsDrawer } from \"../resource/resource-details-drawer\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { entryFromArray } from \"@/components/core/data-list\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { useUserBuilderId } from \"@/components/core/providers/user-builder-id\";\nimport { usePatientImmunizations } from \"@/fhir/immunizations\";\nimport { ImmunizationModel } from \"@/fhir/models/immunization\";\nimport { useFilteredSortedData } from \"@/hooks/use-filtered-sorted-data\";\nimport { QUERY_KEY_PATIENT_IMMUNIZATIONS } from \"@/utils/query-keys\";\n\nexport type PatientImmunizationsProps = {\n  className?: string;\n};\n\nfunction PatientImmunizationsComponent({ className }: PatientImmunizationsProps) {\n  const userBuilderId = useUserBuilderId();\n  const patientImmunizationsQuery = usePatientImmunizations();\n  const { data, filters, setFilters, setSort, defaultSort } = useFilteredSortedData({\n    cacheKey: \"patient-immunizations\",\n    defaultSort: defaultImmunizationSort,\n    records: patientImmunizationsQuery.data,\n  });\n\n  const isEmptyQuery = patientImmunizationsQuery.data?.length === 0;\n  const hasZeroFilteredRecords = !isEmptyQuery && data.length === 0;\n\n  const openDetails = useResourceDetailsDrawer({\n    header: (m) => m.description,\n    details: immunizationData,\n    getSourceDocument: true,\n    enableDismissAndReadActions: true,\n    queryKey: QUERY_KEY_PATIENT_IMMUNIZATIONS,\n  });\n\n  return (\n    <AnalyticsProvider componentName=\"PatientImmunizations\">\n      <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n        <ResourceTableActions\n          filterOptions={{\n            onChange: setFilters,\n            filters: immunizationsFilter(),\n            selected: filters,\n          }}\n          sortOptions={{\n            defaultSort,\n            options: immunizationSortOptions,\n            onChange: setSort,\n          }}\n        />\n        <PatientResourceTable\n          showTableHead\n          isLoading={patientImmunizationsQuery.isLoading}\n          data={data}\n          columns={patientImmunizationsColumns(userBuilderId)}\n          onRowClick={openDetails}\n          enableDismissAndReadActions\n          queryKey={QUERY_KEY_PATIENT_IMMUNIZATIONS}\n          emptyMessage={\n            <EmptyPatientTable\n              hasZeroFilteredRecords={hasZeroFilteredRecords}\n              resourceName=\"immunizations\"\n            />\n          }\n        />\n      </div>\n    </AnalyticsProvider>\n  );\n}\n\nexport const PatientImmunizations = withErrorBoundary(\n  PatientImmunizationsComponent,\n  \"PatientImmunizations\",\n);\n\nconst immunizationData = (immunization: ImmunizationModel) => [\n  { label: \"Date Given\", value: immunization.occurrence },\n  { label: \"Provider Organization\", value: immunization.managingOrganization },\n  { label: \"Status\", value: immunization.status },\n  { label: \"Dose Quantity\", value: immunization.doseQuantity },\n  { label: \"Route\", value: immunization.route },\n  { label: \"Site\", value: immunization.site },\n  { label: \"Lot Number\", value: immunization.resource.lotNumber },\n  ...entryFromArray(\"Note\", immunization.notesDisplay),\n];\n","import { UnreadAllergiesNotification } from \"../allergies/unread-allergies-notification\";\nimport {\n  PatientConditionsAllGrouped,\n  PatientConditionsAllGroupedProps\n} from \"../conditions/patient-conditions-all-grouped\";\nimport {\n  PatientConditionsOutside,\n  PatientConditionsOutsideProps,\n} from \"../conditions/patient-conditions-outside\";\nimport { PatientConditionsOutsideBadge } from \"../conditions/patient-conditions-outside-badge\";\nimport { UnreadConditionsNotification } from \"../conditions/unread-conditions-notification\";\nimport { DisplayCorrectTabLabel } from \"../data-indicator\";\nimport {\n  PatientDiagnosticReports,\n  PatientDiagnosticReportsProps,\n} from \"../diagnostic-reports/patient-diagnostic-reports\";\nimport { UnreadDocumentsNotification } from \"../document/unread-documents-notification\";\nimport { PatientEncounters, PatientEncountersProps } from \"../encounters/patient-encounters\";\nimport { UnreadEncountersNotification } from \"../encounters/unread-encounters-notification\";\nimport { UnreadImmunizationsNotification } from \"../immunizations/unread-immunizations-notification\";\nimport { PatientMedications, PatientMedicationsProps } from \"../medications/patient-medications\";\nimport {\n  PatientMedicationsAll,\n  PatientMedicationsAllProps,\n} from \"../medications/patient-medications-all\";\nimport {\n  PatientMedicationsOutside,\n  PatientMedicationsOutsideProps,\n} from \"../medications/patient-medications-outside\";\nimport { PatientMedicationsOutsideBadge } from \"../medications/patient-medications-outside-badge\";\nimport { UnreadMedicationsNotification } from \"../medications/unread-medications-notification\";\nimport { PatientOverviewZap, PatientOverviewZapProps } from \"../overview/patient-overview-zap\";\nimport {\n  PatientRecordSearch,\n  PatientRecordSearchProps,\n} from \"../patient-record-search/patient-record-search\";\nimport { PatientSources, PatientSourcesProps } from \"../patient-sources/patient-sources\";\nimport { PatientTimeline, PatientTimelineProps } from \"../timeline/patient-timeline\";\nimport { PatientVitals, PatientVitalsProps } from \"../vitals/patient-vitals\";\nimport {\n  PatientAllergies,\n  PatientAllergiesProps,\n} from \"@/components/content/allergies/patient-allergies\";\nimport {\n  PatientCareTeam,\n  PatientCareTeamProps,\n} from \"@/components/content/care-team/patient-careteam\";\nimport {\n  PatientConditions,\n  PatientConditionsProps,\n} from \"@/components/content/conditions/patient-conditions\";\nimport {\n  PatientDocuments,\n  PatientDocumentsProps,\n} from \"@/components/content/document/patient-documents\";\nimport {\n  PatientImmunizations,\n  PatientImmunizationsProps,\n} from \"@/components/content/immunizations/patient-immunizations\";\nimport { TabGroupItem } from \"@/components/content/zus-aggregated-profile/zap-tab-group/zap-tab-group\";\nimport { ZAPTabName } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile\";\nimport { BetaLabel } from \"@/components/core/beta-label\";\nimport i18next from \"@/i18n\";\n\nexport type ZusAggregatedProfileTabs = Record<ZAPTabName, (props: object) => TabGroupItem>;\n\nexport const zusAggregatedProfileTabs = (\n  enableDataIndicators: boolean,\n): ZusAggregatedProfileTabs => ({\n  overview: (props: PatientOverviewZapProps) => ({\n    key: \"overview\",\n    display: () => <TabHelper name=\"overview\" beta />,\n    render: () => <PatientOverviewZap {...props} />,\n  }),\n  search: (props: PatientRecordSearchProps) => ({\n    key: \"search\",\n    display: () => <TabHelper name=\"search\" beta />,\n    render: () => <PatientRecordSearch className=\"ctw-pt-2\" {...props} />,\n  }),\n  conditions: (props: PatientConditionsProps = {}) => ({\n    key: \"conditions\",\n    display: () => i18next.t(\"zap.tabs.conditions\"),\n    render: () => <PatientConditions {...props} />,\n  }),\n\n  \"conditions-outside\": (props: PatientConditionsOutsideProps = {}) => ({\n    key: \"conditions-outside\",\n    display: () => (\n      <TabHelper\n        notification={<PatientConditionsOutsideBadge />}\n        name={i18next.t(\"zap.tabs.conditionsOutside\")}\n      />\n    ),\n    render: () => <PatientConditionsOutside {...props} />,\n  }),\n\n  \"conditions-all\": (props: PatientConditionsAllGroupedProps = {}) => ({\n    key: \"conditions-all\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadConditionsNotification />}\n        resource=\"conditions-all\"\n        enableDataIndicators={enableDataIndicators}\n        name={i18next.t(\"zap.tabs.conditionsAll\")}\n      />\n    ),\n    render: () => <PatientConditionsAllGrouped {...props} />,\n  }),\n\n  medications: (props: PatientMedicationsProps = {}) => ({\n    key: \"medications\",\n    display: () => \"medication list\",\n    render: () => <PatientMedications {...props} />,\n  }),\n\n  \"medications-outside\": (props: PatientMedicationsOutsideProps = {}) => ({\n    key: \"medications-outside\",\n    display: () => (\n      <TabHelper\n        notification={<PatientMedicationsOutsideBadge />}\n        name={i18next.t(\"zap.tabs.medicationsOutside\")}\n      />\n    ),\n    render: () => <PatientMedicationsOutside {...props} />,\n  }),\n\n  \"medications-all\": (props: PatientMedicationsAllProps = {}) => ({\n    key: \"medications-all\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadMedicationsNotification />}\n        resource=\"medications-all\"\n        name=\"Medications\"\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientMedicationsAll {...props} />,\n  }),\n\n  \"diagnostic-reports\": (props: PatientDiagnosticReportsProps = {}) => ({\n    key: \"diagnostic-reports\",\n    display: () => (\n      <TabHelper\n        resource=\"diagnostic-reports\"\n        name=\"diagnostics\"\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientDiagnosticReports {...props} />,\n  }),\n\n  timeline: (props: PatientTimelineProps = {}) => ({\n    key: \"timeline\",\n    display: () => (\n      <TabHelper resource=\"timeline\" name=\"timeline\" enableDataIndicators={enableDataIndicators} />\n    ),\n    render: () => <PatientTimeline {...props} />,\n  }),\n\n  encounters: (props: PatientEncountersProps = {}) => ({\n    key: \"encounters\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadEncountersNotification />}\n        resource=\"encounters\"\n        name=\"Encounters & Notes\"\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientEncounters {...props} />,\n  }),\n\n  documents: (props: PatientDocumentsProps = {}) => ({\n    key: \"documents\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadDocumentsNotification />}\n        resource=\"documents\"\n        name=\"documents\"\n        beta\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientDocuments {...props} />,\n  }),\n\n  allergies: (props: PatientAllergiesProps = {}) => ({\n    key: \"allergies\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadAllergiesNotification />}\n        resource=\"allergies\"\n        name=\"allergies\"\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientAllergies {...props} />,\n  }),\n\n  immunizations: (props: PatientImmunizationsProps = {}) => ({\n    key: \"immunizations\",\n    display: () => (\n      <TabHelper\n        notification={<UnreadImmunizationsNotification />}\n        resource=\"immunizations\"\n        name=\"immunizations\"\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientImmunizations {...props} />,\n  }),\n\n  \"care-team\": (props: PatientCareTeamProps = {}) => ({\n    key: \"care-team\",\n    display: () => (\n      <TabHelper\n        resource=\"care-team\"\n        name=\"care team\"\n        beta\n        enableDataIndicators={enableDataIndicators}\n      />\n    ),\n    render: () => <PatientCareTeam {...props} />,\n  }),\n\n  sources: (props: PatientSourcesProps = {}) => ({\n    key: \"sources\",\n    display: () => (\n      <TabHelper resource=\"sources\" name=\"sources\" enableDataIndicators={enableDataIndicators} />\n    ),\n    render: () => <PatientSources {...props} />,\n  }),\n\n  vitals: (props: PatientVitalsProps = {}) => ({\n    key: \"vitals\",\n    display: () => (\n      <TabHelper resource=\"vitals\" name=\"vitals\" beta enableDataIndicators={enableDataIndicators} />\n    ),\n    render: () => <PatientVitals {...props} />,\n  }),\n});\n\ntype TabHelperProps = {\n  beta?: boolean;\n  name: string;\n  notification?: React.ReactNode;\n  resource?: ZAPTabName;\n  enableDataIndicators?: boolean;\n};\n\nfunction TabHelper({ beta, name, notification, resource, enableDataIndicators }: TabHelperProps) {\n  return (\n    <div className=\"ctw-flex ctw-items-center ctw-space-x-3 ctw-pr-3\">\n      {notification && !enableDataIndicators && (\n        <div className=\"ctw-absolute -ctw-ml-1\">{notification}</div>\n      )}\n      <div className=\"ctw-flex ctw-items-center ctw-space-x-1 ctw-text-black\">\n        {resource && enableDataIndicators ? (\n          <DisplayCorrectTabLabel text={name} resource={resource} isBeta={beta} />\n        ) : (\n          <>\n            <span className=\"ctw-capitalize \">{name}</span>\n            {beta && <BetaLabel />}\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n","import \"./zus-aggregated-profile.scss\";\n\nimport cx from \"classnames\";\nimport { useContext, useEffect, useMemo } from \"react\";\nimport { AlertFeatureFlag } from \"../../core/alert-feature-flag\";\nimport { PatientConditionsAllGroupedProps } from \"../conditions/patient-conditions-all-grouped\";\nimport { PatientConditionsOutsideProps } from \"../conditions/patient-conditions-outside\";\nimport { PatientDiagnosticReportsProps } from \"../diagnostic-reports/patient-diagnostic-reports\";\nimport { PatientEncountersProps } from \"../encounters/patient-encounters\";\nimport { PatientMedicationsProps } from \"../medications/patient-medications\";\nimport { PatientMedicationsAllProps } from \"../medications/patient-medications-all\";\nimport { PatientMedicationsOutsideProps } from \"../medications/patient-medications-outside\";\nimport { PatientRecordSearchProps } from \"../patient-record-search/patient-record-search\";\nimport { PatientSourcesProps } from \"../patient-sources/patient-sources\";\nimport { PatientTimelineProps } from \"../timeline/patient-timeline\";\nimport { PatientVitalsProps } from \"../vitals/patient-vitals\";\nimport ZusSVG from \"@/assets/zus.svg\";\nimport { PatientAllergiesProps } from \"@/components/content/allergies/patient-allergies\";\nimport { PatientCareTeamProps } from \"@/components/content/care-team/patient-careteam\";\nimport { PatientConditionsProps } from \"@/components/content/conditions/patient-conditions\";\nimport { PatientDocumentsProps } from \"@/components/content/document/patient-documents\";\nimport { usePatientError } from \"@/components/content/hooks/use-patient-error\";\nimport { PatientImmunizationsProps } from \"@/components/content/immunizations/patient-immunizations\";\nimport { ZAPTabGroup } from \"@/components/content/zus-aggregated-profile/zap-tab-group/zap-tab-group\";\nimport { zusAggregatedProfileTabs } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile-tabs\";\nimport { AuthError } from \"@/components/core/auth-error\";\nimport { Title } from \"@/components/core/ctw-box\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { Loading } from \"@/components/core/loading\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { ZapPropsStateContext } from \"@/components/core/providers/zap-props-state-context\";\nimport { ZapTabStateContext } from \"@/components/core/providers/zap-tab-state-context\";\nimport { useFeatureToggle } from \"@/hooks/use-feature-toggle\";\nimport { intersection } from \"@/utils/nodash\";\n\nexport const ZAP_TAB_NAMES = [\n  \"allergies\",\n  \"care-team\",\n  \"conditions\",\n  \"conditions-outside\",\n  \"conditions-all\",\n  \"diagnostic-reports\",\n  \"documents\",\n  \"encounters\",\n  \"immunizations\",\n  \"medications\",\n  \"medications-outside\",\n  \"medications-all\",\n  \"search\",\n  \"timeline\",\n  \"overview\",\n  \"sources\",\n  \"vitals\",\n] as const;\n\nexport type ZAPTabName = (typeof ZAP_TAB_NAMES)[number];\n\nexport const DEFAULT_ZAP_TABS: ZAPTabName[] = [\n  \"overview\",\n  \"search\",\n  \"conditions-all\",\n  \"medications-all\",\n  \"diagnostic-reports\",\n  \"vitals\",\n  \"encounters\",\n  \"documents\",\n  \"allergies\",\n  \"immunizations\",\n  \"care-team\",\n  \"sources\",\n];\n\nexport type ZusAggregatedProfileProps = {\n  resources?: ZAPTabName[]; // TODO - would prefer to rename this to tabs\n  forceHorizontalTabs?: boolean;\n  includePatientDemographicsForm?: boolean;\n  title?: string;\n  hideTitle?: boolean;\n  removeBranding?: boolean;\n  removeRequestRecords?: boolean;\n} & ZusAggregatedProfileSubComponentProps;\n\ntype HidableRecords<T> = {\n  hideRequestRecords?: boolean;\n} & T;\n\ntype MapOfHideableTypes<MapType> = {\n  [Property in keyof MapType]: HidableRecords<MapType[Property]>;\n};\n\nexport type ZusAggregatedProfileSubComponentProps = MapOfHideableTypes<\n  Partial<{\n    allergiesProps: PatientAllergiesProps;\n    careTeamProps: PatientCareTeamProps;\n    conditionsProps: PatientConditionsProps;\n    conditionsOutsideProps: PatientConditionsOutsideProps;\n    conditionsAllProps: PatientConditionsAllGroupedProps;\n    diagnosticReportsProps: PatientDiagnosticReportsProps;\n    documentsProps: PatientDocumentsProps;\n    immunizationsProps: PatientImmunizationsProps;\n    medicationsProps: PatientMedicationsProps;\n    medicationsOutsideProps: PatientMedicationsOutsideProps;\n    medicationsAllProps: PatientMedicationsAllProps;\n    timelineProps: PatientTimelineProps;\n    encounterProps: PatientEncountersProps;\n    searchProps: PatientRecordSearchProps;\n    sourcesProps: PatientSourcesProps;\n    vitalsProps: PatientVitalsProps;\n  }>\n>;\n\nexport type ZusAggregatedProfileSubComponentPropsMap = Partial<{\n  allergies: ZusAggregatedProfileSubComponentProps[\"allergiesProps\"];\n  \"care-team\": ZusAggregatedProfileSubComponentProps[\"careTeamProps\"];\n  conditions: ZusAggregatedProfileSubComponentProps[\"conditionsProps\"];\n  \"conditions-outside\": ZusAggregatedProfileSubComponentProps[\"conditionsOutsideProps\"];\n  \"conditions-all\": ZusAggregatedProfileSubComponentProps[\"conditionsAllProps\"];\n  \"diagnostic-reports\": ZusAggregatedProfileSubComponentProps[\"diagnosticReportsProps\"];\n  documents: ZusAggregatedProfileSubComponentProps[\"documentsProps\"];\n  immunizations: ZusAggregatedProfileSubComponentProps[\"immunizationsProps\"];\n  medications: ZusAggregatedProfileSubComponentProps[\"medicationsProps\"];\n  \"medications-outside\": ZusAggregatedProfileSubComponentProps[\"medicationsOutsideProps\"];\n  \"medications-all\": ZusAggregatedProfileSubComponentProps[\"medicationsAllProps\"];\n  timeline: ZusAggregatedProfileSubComponentProps[\"timelineProps\"];\n  encounters: ZusAggregatedProfileSubComponentProps[\"encounterProps\"];\n  search: ZusAggregatedProfileSubComponentProps[\"searchProps\"];\n  sources: ZusAggregatedProfileSubComponentProps[\"sourcesProps\"];\n  overview: HidableRecords<{ includePatientDemographicsForm?: boolean }>;\n  vitals: ZusAggregatedProfileSubComponentProps[\"vitalsProps\"];\n}>;\n\nconst ZusAggregatedProfileComponent = ({\n  forceHorizontalTabs = false,\n  includePatientDemographicsForm,\n  allergiesProps,\n  careTeamProps,\n  conditionsProps,\n  conditionsOutsideProps,\n  conditionsAllProps,\n  diagnosticReportsProps,\n  documentsProps,\n  immunizationsProps,\n  medicationsProps,\n  medicationsOutsideProps,\n  medicationsAllProps,\n  timelineProps,\n  encounterProps,\n  searchProps,\n  sourcesProps,\n  vitalsProps,\n  resources = DEFAULT_ZAP_TABS,\n  hideTitle = false,\n  title = \"Outside Records\",\n  removeBranding = false,\n  removeRequestRecords = false,\n}: ZusAggregatedProfileProps) => {\n  const hasSearchFeature = useFeatureToggle(\"ctw-patient-record-search\");\n  const hasVitalFeature = useFeatureToggle(\"ctw-vitals\");\n  const showNewDataIndicators = useFeatureToggle(\"ctw-data-indicators\");\n  const hasShowRequestRecordsFeature = useFeatureToggle(\"ctw-patient-history-form\");\n  const { tabOrder, setTabOrder } = useContext(ZapTabStateContext);\n  const { setProps } = useContext(ZapPropsStateContext);\n  const { authError } = usePatientError();\n\n  // Get the configuration for each tab group by resource type\n  const subcomponentProps: ZusAggregatedProfileSubComponentPropsMap = useMemo(\n    () => ({\n      allergies: allergiesProps,\n      \"care-team\": careTeamProps,\n      conditions: conditionsProps,\n      \"conditions-outside\": conditionsOutsideProps,\n      \"conditions-all\": conditionsAllProps,\n      \"diagnostic-reports\": diagnosticReportsProps,\n      documents: documentsProps,\n      encounters: encounterProps,\n      immunizations: immunizationsProps,\n      medications: medicationsProps,\n      \"medications-outside\": medicationsOutsideProps,\n      \"medications-all\": medicationsAllProps,\n      timeline: timelineProps,\n      overview: { includePatientDemographicsForm },\n      search: searchProps,\n      sources: sourcesProps,\n      vitals: vitalsProps,\n    }),\n    [\n      allergiesProps,\n      careTeamProps,\n      conditionsProps,\n      conditionsOutsideProps,\n      conditionsAllProps,\n      diagnosticReportsProps,\n      documentsProps,\n      encounterProps,\n      immunizationsProps,\n      medicationsProps,\n      medicationsOutsideProps,\n      medicationsAllProps,\n      timelineProps,\n      includePatientDemographicsForm,\n      searchProps,\n      sourcesProps,\n      vitalsProps,\n    ],\n  );\n\n  // Set tab order here because resource tab order can be changed by the user\n  useEffect(() => {\n    // Wait until our feature toggles are ready before setting the tab order.\n    // This prevents us from setting tabOrder prematurely.\n    if (!hasSearchFeature.ready || !hasVitalFeature.ready) {\n      return;\n    }\n\n    setProps(subcomponentProps);\n\n    // Filter out tabs that are not enabled.\n    const tabs = resources.filter(\n      (tabName) =>\n        (tabName !== \"vitals\" || hasVitalFeature.enabled) &&\n        (tabName !== \"search\" || hasSearchFeature.enabled),\n    );\n\n    setTabOrder(tabs);\n  }, [\n    resources,\n    setTabOrder,\n    setProps,\n    subcomponentProps,\n    hasSearchFeature.enabled,\n    hasSearchFeature.ready,\n    hasVitalFeature.enabled,\n    hasVitalFeature.ready,\n  ]);\n\n  const showRequestRecordsButton = useMemo(\n    () => hasShowRequestRecordsFeature.enabled && !removeRequestRecords,\n    [hasShowRequestRecordsFeature.enabled, removeRequestRecords],\n  );\n\n  const tabbedContent = useMemo(\n    () =>\n      // Return tab content filtered down to our set of enabled tabs via tabOrder.\n      // This also ensures it is in the same order as tabOrder which ensures that\n      // setSelectedTab by name works correctly (tabs and content line up!).\n      intersection(tabOrder as ZAPTabName[], resources).map((tabName) => {\n        const props = subcomponentProps[tabName] ?? {};\n        props.hideRequestRecords = !showRequestRecordsButton;\n        return zusAggregatedProfileTabs(showNewDataIndicators.enabled ?? false)[tabName](props);\n      }),\n    [tabOrder, resources, subcomponentProps, showRequestRecordsButton, showNewDataIndicators],\n  );\n\n  // Use correct empty message when there are auth errors or failure fetching patient data.\n  if (authError) {\n    return <AuthError />;\n  }\n\n  if (!hasSearchFeature.ready) {\n    return <Loading />;\n  }\n\n  return (\n    <AnalyticsProvider componentName=\"ZusAggregatedProfile\">\n      <div className=\"ctw-space-y-2\">\n        <AlertFeatureFlag featureFlag=\"ctw-zap-alert\" />\n        <div className=\"ctw-zus-aggregated-profile ctw-scrollable-pass-through-height ctw-space-y-4\">\n          <ZAPTabGroup content={tabbedContent} forceHorizontalTabs={forceHorizontalTabs} />\n          {!hideTitle && (\n            <Title\n              className={cx(\n                `ctw-border-b-0 ctw-border-l-0 ctw-border-r-0 ctw-border-t-2 ctw-border-solid ctw-border-divider-light ctw-bg-zap-headerBg ctw-px-4`,\n              )}\n            >\n              <div className=\"ctw-flex ctw-items-center ctw-space-x-1 ctw-py-3\">\n                <h3 className=\"ctw-m-0 ctw-inline-block ctw-p-0  ctw-font-medium\">{title}</h3>\n                {!removeBranding && (\n                  <div className=\"ctw-flex ctw-items-center ctw-space-x-2\">\n                    <span className=\"ctw-text-sm ctw-font-light ctw-italic ctw-text-content-light\">\n                      Powered by\n                    </span>\n                    <img src={ZusSVG} alt=\"Zus\" />\n                  </div>\n                )}\n              </div>\n            </Title>\n          )}\n        </div>\n      </div>\n    </AnalyticsProvider>\n  );\n};\n\n/**\n * ZusAggregatedProfile allows developers to utilize most of the components\n * available in this library as a single customizable component with tabbed\n * navigation. Simply pass an array with the names of the desired resources\n * to include _(see below)_.\n *\n * It's possible to set a custom title for the ZusAggregatedProfile component,\n * making it a single component which can be used to create a handful of\n * different widgets within an app.\n *\n * ```\n * export const ZusMedsWidget = <ZusAggregatedProfile\n *   title=\"Medications\"\n *   resources={[\"medications\", \"medications-outside\"]}\n * />\n *\n * export const ZusProblemsWidget = <ZusAggregatedProfile\n *   title=\"Problems\"\n *   resources={[\"allergies\", \"conditions\", \"conditions-outside\"]}\n * />\n * ```\n * The complete set of available resources in the ZusAggregatedProfile are\n * \"allergies\",\n * \"care-team\",\n * \"conditions\",\n * \"conditions-outside\",\n * \"conditions-all\",\n * \"diagnostic-reports\",\n * \"documents\",\n * \"encounters\",\n * \"immunizations\",\n * \"medications\",\n * \"medications-outside\",\n * \"medications-all\",\n * \"timeline\"\n */\nexport const ZusAggregatedProfile = withErrorBoundary(\n  ZusAggregatedProfileComponent,\n  \"ZusAggregatedProfile\",\n  true,\n);\n","import { ZusAggregatedProfile } from \"../zus-aggregated-profile/zus-aggregated-profile\";\n\nexport type PatientConditionsProfileProps = {\n  hideRequestRecords?: boolean;\n  readOnly?: boolean;\n};\n\nexport const PatientConditionsProfile = ({\n  hideRequestRecords,\n  readOnly,\n}: PatientConditionsProfileProps) => (\n  <ZusAggregatedProfile\n    hideTitle\n    resources={[\"conditions\", \"conditions-outside\"]}\n    conditionsProps={{ readOnly }}\n    conditionsOutsideProps={{ hideRequestRecords, readOnly }}\n  />\n);\n","import { numRecordsToLookbackForUnread } from \"../unread-records-notification\";\nimport { UnreadNotification } from \"@/components/core/unread-notification\";\nimport { usePatientDiagnosticReports } from \"@/fhir/diagnostic-report\";\n\nexport type UnreadDiagnosticReportsNotificationProps = {\n  className?: string;\n};\n\nexport const UnreadDiagnosticReportsNotification = ({\n  className,\n}: UnreadDiagnosticReportsNotificationProps) => {\n  const query = usePatientDiagnosticReports(numRecordsToLookbackForUnread);\n  return <UnreadNotification className={className} data={query.data} />;\n};\n","import { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { MedicationDispenseModel } from \"@/fhir/models\";\n\nexport const patientMedicationDispenseColumns = () => {\n  const dispenseColumns: TableColumn<MedicationDispenseModel>[] = [\n    {\n      title: \"TimeStamp\",\n      render: (m) => m.alertTimeStamp,\n    },\n    {\n      title: \"Medication\",\n      render: (m) => m.medicationDisplayName,\n    },\n    {\n      title: \"Performer Details\",\n      render: (m) => m.performerDetails.name,\n    },\n    {\n      title: \"Last Known Fill\",\n      render: (m) => (m.whenHandedOver ? m.whenHandedOver : m.whenPrepared),\n    },\n  ];\n\n  return dispenseColumns;\n};\n","import { MedicationDispenseModel } from \"@/fhir/models\";\n\nexport const applyMedDispenseFilters = (data: fhir4.MedicationDispense[]) =>\n  data\n    .map((m) => new MedicationDispenseModel(m))\n    .filter((m) => m.PMARefillNotPickedUp === \"PMARefillNotPickedUp\");\n","import { PatientModel } from \"./models\";\nimport { CTWRequestContext, useQueryWithPatient } from \"..\";\nimport { applyMedDispenseFilters } from \"@/components/content/medication-dispense/helpers/filters\";\nimport { createGraphqlClient, fqsRequest } from \"@/services/fqs/client\";\nimport {\n  MedicationDispenseGraphqlResponse,\n  medicationDispenseQuery,\n} from \"@/services/fqs/queries/medication-dispense\";\nimport { QUERY_KEY_PATIENT_MEDICATION_DISPENSE } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function usePatientMedicationDispense() {\n  return useQueryWithPatient(\n    QUERY_KEY_PATIENT_MEDICATION_DISPENSE,\n    [],\n    getMedicationDispenseFromFQS\n  );\n}\n\nasync function getMedicationDispenseFromFQS(\n  requestContext: CTWRequestContext,\n  patient: PatientModel\n) {\n  try {\n    const graphClient = createGraphqlClient(requestContext);\n    const { data } = await fqsRequest<MedicationDispenseGraphqlResponse>(\n      graphClient,\n      medicationDispenseQuery,\n      {\n        upid: patient.UPID,\n        cursor: \"\",\n        first: 1000,\n        sort: {\n          lastUpdated: \"DESC\",\n        },\n        filter: {},\n      }\n    );\n\n    const nodes = data.MedicationDispenseConnection.edges.map((x) => x.node);\n    return applyMedDispenseFilters(nodes);\n  } catch (e) {\n    throw Telemetry.logError(\n      e as Error,\n      `Failed fetching medication dispenses for patient: ${patient.UPID}`\n    );\n  }\n}\n","import cx from \"classnames\";\nimport { patientMedicationDispenseColumns } from \"./helpers/dispense-columns\";\nimport { PatientResourceTable } from \"../resource/patient-resource-table\";\nimport { EmptyPatientTable } from \"@/components/core/empty-table\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { usePatientMedicationDispense } from \"@/fhir/medication-dispense\";\n\nexport type PatientMedDispenseProps = {\n  className?: cx.Argument;\n};\n\nfunction PatientMedDispenseComponent({ className }: PatientMedDispenseProps) {\n  const patientMedicationDispenseQuery = usePatientMedicationDispense();\n\n  const hasZeroFilteredRecords = patientMedicationDispenseQuery.data?.length === 0;\n\n  return (\n    <div className={cx(className, \"ctw-scrollable-pass-through-height\")}>\n      <PatientResourceTable\n        showTableHead\n        isLoading={patientMedicationDispenseQuery.isLoading}\n        data={patientMedicationDispenseQuery.data ?? []}\n        columns={patientMedicationDispenseColumns()}\n        emptyMessage={\n          <EmptyPatientTable\n            hasZeroFilteredRecords={hasZeroFilteredRecords}\n            resourceName=\"medicationdispense\"\n          />\n        }\n      />\n    </div>\n  );\n}\n\nexport const PatientMedicationDispense = withErrorBoundary(\n  PatientMedDispenseComponent,\n  \"PatientMedicationDispense\"\n);\n","import { PatientMedicationsProps } from \"./patient-medications\";\nimport { PatientMedicationsOutsideProps } from \"./patient-medications-outside\";\nimport {\n  ZusAggregatedProfile,\n  ZusAggregatedProfileProps,\n} from \"../zus-aggregated-profile/zus-aggregated-profile\";\n\nexport type PatientMedicationsProfileProps = Omit<ZusAggregatedProfileProps, \"resources\"> &\n  PatientMedicationsProps &\n  PatientMedicationsOutsideProps;\n\nexport const PatientMedicationsProfile = (props: PatientMedicationsProfileProps) => (\n  <ZusAggregatedProfile\n    hideTitle\n    resources={[\"medications\", \"medications-outside\"]}\n    {...props}\n    medicationsProps={props}\n    medicationsOutsideProps={props}\n  />\n);\n","export const patientHistoryJobStatuses = [\n  \"queued\",\n  \"scheduled\",\n  \"in_progress\",\n  \"done\",\n  \"error\",\n] as const;\nexport type PatientHistoryJobStatus = (typeof patientHistoryJobStatuses)[number];\n\nexport const patientHistoryJobProviderStatuses = [\n  \"initialize\",\n  \"in_progress\",\n  \"done\",\n  \"done_with_info\",\n  \"error\",\n  \"unset\",\n  \"skipped\",\n] as const;\nexport type PatientHistoryJobProviderStatus = (typeof patientHistoryJobProviderStatuses)[number];\n\nexport type PatientHistoryJobProvider = {\n  service: string;\n  status: PatientHistoryJobProviderStatus;\n};\n\nexport type PatientHistoryJobResponseJobData = {\n  type: string;\n  id: string;\n  attributes: {\n    jobStatus: PatientHistoryJobStatus;\n    practitioner: {\n      npi: string;\n      name: string;\n      role: string;\n    };\n    providers: PatientHistoryJobProvider[];\n    targetDate?: string;\n    createdAt: number;\n    lastUpdatedAt: number;\n  };\n  relationships: {\n    patient: {\n      data: { type: \"fhir/Patient\"; id: string };\n    };\n    practitioner?: {\n      data: { type: \"fhir/Practitioner\"; id: string };\n    };\n  };\n};\n\nexport type PatientHistoryJobResponse = {\n  data: PatientHistoryJobResponseJobData[];\n  links: { self: string; prev?: string; next?: string };\n};\n","import { faCalendarWeek, faHourglass } from \"@fortawesome/free-solid-svg-icons\";\nimport { FilterChangeEvent, FilterItem } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { patientHistoryJobStatuses } from \"@/services/patient-history/patient-history-types\";\n\nexport function patientHistoryFilters(): FilterItem[] {\n  const filters: FilterItem[] = [];\n\n  filters.push(\n    {\n      key: \"status\",\n      type: \"select\",\n      icon: faHourglass,\n      values: patientHistoryJobStatuses.map((status) => ({\n        key: status,\n        name: status.replaceAll(\"_\", \" \"),\n      })),\n      display: \"status\",\n    },\n    {\n      key: \"future_jobs\",\n      type: \"tag\",\n      icon: faCalendarWeek,\n      display: \"Exclude Future Jobs\",\n    }\n  );\n\n  return filters;\n}\n\nexport const defaultPatientHistoryFilters: FilterChangeEvent = {\n  future_jobs: {\n    key: \"future_jobs\",\n    selected: true,\n    type: \"tag\",\n  },\n};\n","import { getBuilderRefreshHistoryMessages } from \"./use-patient-history\";\nimport { useQueryWithCTW } from \"@/components/core/providers/use-query-with-ctw\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { PatientHistoryRequestModel } from \"@/fhir/models/patient-history\";\nimport { fqsRequestContext, searchRecordsFQS } from \"@/services/fqs-rest/search-helpers\";\nimport { PatientHistoryJobResponse } from \"@/services/patient-history/patient-history-types\";\nimport { compact, uniq } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENT_HISTORY_LIST } from \"@/utils/query-keys\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\nexport function useBuilderPatientHistoryList(\n  pageSize: number,\n  pageOffset: number,\n  status?: string,\n  excludeFutureJobs?: boolean,\n) {\n  return useQueryWithCTW(\n    QUERY_KEY_PATIENT_HISTORY_LIST,\n    [pageSize, pageOffset, status, excludeFutureJobs],\n    async (requestContext) => {\n      try {\n        const response = (await getBuilderRefreshHistoryMessages({\n          requestContext,\n          count: pageSize,\n          offset: pageOffset,\n          status,\n          excludeFutureJobs,\n        })) as PatientHistoryJobResponse;\n\n        const patientIds = uniq(\n          compact(response.data.map((job) => job.relationships.patient.data.id)),\n        );\n\n        if (!patientIds.length) {\n          return { total: 0, patients: [] };\n        }\n\n        const patientData = await searchRecordsFQS(fqsRequestContext(requestContext), \"Patient\", {\n          _id: patientIds.join(\",\"),\n        });\n\n        const patientsMap = patientData.reduce(\n          (acc, patient) => {\n            if (patient.id) {\n              acc[patient.id] = new PatientModel(patient);\n            }\n            return acc;\n          },\n          {} as Record<string, PatientModel>,\n        );\n\n        const patientHistoryPatients = response.data.map(\n          (job) =>\n            new PatientHistoryRequestModel(patientsMap[job.relationships.patient.data.id], job),\n        );\n\n        return {\n          hasNext: !!response.links.next,\n          total: response.data.length,\n          patients: patientHistoryPatients,\n        };\n      } catch (e) {\n        Telemetry.logError(e as Error, \"Failed fetching patient history patients.\");\n        throw new Error(`Failed fetching patient history patients: ${e}`);\n      }\n    },\n  );\n}\n","import cx from \"classnames\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\n\nexport type SimplePaginationProps = {\n  currentPage: number;\n  isLoading?: boolean;\n  setCurrentPage: (n: number) => void;\n  hasNext?: boolean;\n};\n\ntype PaginateButtonProps = {\n  pageToNavigateTo: number;\n  setCurrentPage: (n: number) => void;\n  children: string;\n  className?: cx.Argument;\n};\n\nexport const SimplePagination = ({\n  setCurrentPage,\n  currentPage,\n  hasNext,\n}: SimplePaginationProps) => {\n  if (hasNext || currentPage > 1) {\n    return (\n      <div className=\"ctw-simple-pagination ctw-flex ctw-justify-end ctw-space-x-3 ctw-px-6 ctw-py-3\">\n        <PaginateButton\n          pageToNavigateTo={currentPage - 1}\n          setCurrentPage={setCurrentPage}\n          className={cx({ \"ctw-invisible\": currentPage === 1 })}\n        >\n          Prev\n        </PaginateButton>\n\n        <PaginateButton\n          pageToNavigateTo={currentPage + 1}\n          setCurrentPage={setCurrentPage}\n          className={cx({ \"ctw-invisible\": !hasNext })}\n        >\n          Next\n        </PaginateButton>\n      </div>\n    );\n  }\n  return <></>;\n};\n\nconst PaginateButton = ({\n  pageToNavigateTo,\n  setCurrentPage,\n  children,\n  className,\n}: PaginateButtonProps) => {\n  const { trackInteraction } = useAnalytics();\n\n  return (\n    <button\n      type=\"button\"\n      className={cx(\"ctw-btn-default\", className)}\n      onClick={() => {\n        setCurrentPage(pageToNavigateTo);\n        trackInteraction(\"change_page\", {\n          page: pageToNavigateTo,\n        });\n      }}\n    >\n      {children}\n    </button>\n  );\n};\n","import \"./patient-history-table.scss\";\n// TODO cache filter changes.\n\nimport cx from \"classnames\";\nimport { useEffect, useState } from \"react\";\nimport { defaultPatientHistoryFilters, patientHistoryFilters } from \"./helpers/filters\";\nimport { useBuilderPatientHistoryList } from \"./use-builder-patient-history-list\";\nimport { TableOptionProps } from \"../patients/patients-table-helper\";\nimport { ResourceTableActions } from \"../resource/resource-table-actions\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { FilterChangeEvent } from \"@/components/core/filter-bar/filter-bar-types\";\nimport { SimplePagination } from \"@/components/core/pagination/simple-pagination\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { Table } from \"@/components/core/table/table\";\nimport { TableColumn } from \"@/components/core/table/table-helpers\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { PatientHistoryRequestModel } from \"@/fhir/models/patient-history\";\nimport { CTWBox } from \"@/index\";\nimport { PatientHistoryJobProviderStatus } from \"@/services/patient-history/patient-history-types\";\n\nexport type PatientsHistoryTableProps = {\n  className?: cx.Argument;\n  handleRowClick?: (row: PatientHistoryRequestModel) => void;\n  pageSize?: number;\n  title?: string;\n  includeBorder?: boolean;\n} & TableOptionProps<PatientModel>;\n\nexport const PatientHistoryTable = withErrorBoundary(\n  ({\n    className,\n    handleRowClick,\n    pageSize = 10,\n    title = \"Patient History Request\",\n    includeBorder = true,\n  }: PatientsHistoryTableProps) => {\n    const [currentPage, setCurrentPage] = useState(1);\n    const [patients, setPatients] = useState<PatientHistoryRequestModel[]>([]);\n    const [status, setStatus] = useState<string>();\n    const [excludeFutureJobs, setExcludeFutureJobs] = useState<boolean>(true);\n    const [selectedFilters, setSelectedFilters] = useState<FilterChangeEvent>(\n      defaultPatientHistoryFilters,\n    );\n\n    const {\n      data: { patients: responsePatients, total: responseTotal, hasNext } = {},\n      isLoading,\n      isFetching,\n      isError,\n    } = useBuilderPatientHistoryList(pageSize, currentPage - 1, status, excludeFutureJobs);\n\n    const onFilterChange = (e: FilterChangeEvent) => {\n      setExcludeFutureJobs(!!e.future_jobs?.selected);\n      if (e.status?.selected && typeof e.status.selected === \"string\") {\n        setStatus(e.status.selected.split(\" \").join(\"_\"));\n      } else {\n        setStatus(undefined);\n      }\n      setSelectedFilters(e);\n    };\n\n    // Here we are setting the total and patients only when we know that useQuery\n    // isn't fetching. This will prevent empty intermediate states where there\n    // is no data because the value of `usePatientsTable()` hasn't settled yet.\n    useEffect(() => {\n      if (!isFetching && responsePatients) {\n        // filter out records where a patient was not found (eg. the patient was deleted after the history request was made)\n        setPatients(responsePatients.filter((patient) => patient.patient));\n      }\n    }, [responsePatients, responseTotal, isError, isFetching]);\n\n    // This resets our state when there is an error fetching patients from ODS.\n    useEffect(() => {\n      if (isError) {\n        setPatients([]);\n      }\n    }, [isError, isFetching]);\n\n    return (\n      <AnalyticsProvider componentName=\"PatientHistoryTable\">\n        <CTWBox.StackedWrapper\n          className={cx(\n            \"ctw-patients-table-inputs\",\n            { \"ctw-patients-border\": includeBorder },\n            className,\n          )}\n        >\n          {title && <CTWBox.Heading title={title} />}\n          <ResourceTableActions\n            filterOptions={{\n              onChange: onFilterChange,\n              filters: patientHistoryFilters(),\n              defaultFilters: defaultPatientHistoryFilters,\n              selected: selectedFilters,\n            }}\n            className=\"ctw-ml-2\"\n          />\n          <div className=\"ctw-overflow-hidden\">\n            <Table\n              records={patients}\n              columns={columns}\n              pageSize={pageSize}\n              handleRowClick={handleRowClick}\n              isLoading={isLoading}\n              hidePagination\n            >\n              <SimplePagination\n                currentPage={currentPage}\n                setCurrentPage={setCurrentPage}\n                hasNext={hasNext}\n              />\n            </Table>\n          </div>\n        </CTWBox.StackedWrapper>\n      </AnalyticsProvider>\n    );\n  },\n  \"PatientsHistoryTable\",\n);\n\nconst columns: TableColumn<PatientHistoryRequestModel>[] = [\n  {\n    title: \"Last Queried\",\n    render: (data) => <div>{data.lastUpdatedAt}</div>,\n    width: \"140px\",\n  },\n  {\n    title: \"Target Date\",\n    render: (data) => <div>{data.targetDate}</div>,\n    width: \"125px\",\n  },\n  {\n    title: \"Name\",\n    render: (data) => <PatientNameColumn data={data} />,\n  },\n  {\n    title: \"Source\",\n    render: (data) => (\n      <div className=\"ctw-space-y-2\">\n        {data.providers.map(({ service }) => (\n          <div key={`${data.historyInfo.id}-${service}`}>\n            <div className=\"ctw-w-fit  ctw-py-1\tctw-capitalize\">\n              {mapSourceToSourceLabel(service)}\n            </div>\n          </div>\n        ))}\n      </div>\n    ),\n  },\n  {\n    title: \"Status\",\n    render: (data) => (\n      <div className=\"ctw-space-y-2\">\n        {data.providers.map(({ service, status }) => (\n          <div key={`${data.historyInfo.id}-${service}`}>\n            <div className=\"ctw-capitalize\">\n              <RenderCorrectStatusLabel status={status} />\n            </div>\n          </div>\n        ))}\n      </div>\n    ),\n    width: \"125px\",\n  },\n];\n\nfunction mapSourceToSourceLabel(serviceName: string) {\n  switch (serviceName) {\n    case \"commonwell\":\n      return \"EHR Network - CommonWell\";\n    case \"carequality\":\n      return \"EHR Network - Carequality\";\n    case \"surescripts\":\n      return \"Medication History - Surescripts\";\n    default:\n      return serviceName;\n  }\n}\n\nconst PatientNameColumn = ({ data }: { data: PatientHistoryRequestModel }) => (\n  <div className=\"ctw-flex ctw-items-center\">\n    <div>\n      <div className=\"ctw-flex ctw-space-x-1 ctw-font-medium\">\n        <div className=\"ctw-max-w-xs\">{data.patient.fullName}</div>\n        {data.patient.resource.gender?.[0] && (\n          <div className=\"ctw-uppercase\">({data.patient.resource.gender[0]})</div>\n        )}\n      </div>\n      <div className=\"ctw-text-content-lighter\">\n        {data.patient.dob} ({data.patient.age})\n      </div>\n    </div>\n  </div>\n);\n\nconst RenderCorrectStatusLabel = ({ status }: { status: PatientHistoryJobProviderStatus }) => {\n  switch (status) {\n    case \"initialize\":\n    case \"in_progress\":\n    case \"unset\":\n      return (\n        <StatusLabel status=\"In progress\" className=\"ctw-bg-bg-light ctw-text-content-light\" />\n      );\n    case \"done\":\n      return (\n        <StatusLabel status=\"Complete\" className=\"ctw-bg-success-light ctw-text-success-dark\" />\n      );\n    case \"error\":\n    case \"done_with_info\":\n      return <StatusLabel status=\"Failed\" className=\"ctw-bg-error-light ctw-text-error-text\" />;\n    case \"skipped\":\n      return (\n        <StatusLabel status=\"Skipped\" className=\"ctw-bg-caution-light ctw-text-caution-text\" />\n      );\n    default:\n      return <StatusLabel status={status} />;\n  }\n};\n\nconst StatusLabel = ({ status, className }: { status: string; className?: cx.Argument }) => (\n  <div className={cx(\"ctw-w-fit ctw-rounded-2xl ctw-px-3 ctw-py-1 ctw-font-medium\", className)}>\n    {status.split(\"_\").join(\" \")}\n  </div>\n);\n","import { Combobox } from \"@headlessui/react\";\nimport { useEffect, useState } from \"react\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { ComboboxField, ComboxboxFieldOption } from \"@/components/core/form/combobox-field\";\nimport { useQueryWithCTW } from \"@/components/core/providers/use-query-with-ctw\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { getBuilderPatientListWithSearch } from \"@/fhir/patient-helper\";\nimport { orderBy } from \"@/utils/nodash\";\nimport { QUERY_KEY_PATIENTS_LIST_ODS } from \"@/utils/query-keys\";\n\nexport function usePatientSearchList(\n  pageSize: number,\n  pageOffset: number,\n  searchNameValue?: string\n) {\n  return useQueryWithCTW(\n    QUERY_KEY_PATIENTS_LIST_ODS,\n    [pageSize, pageOffset, searchNameValue],\n    getBuilderPatientListWithSearch,\n    !!searchNameValue\n  );\n}\n\nexport type CustomPatientOptionValue = Omit<ComboxboxFieldOption, \"value\"> & {\n  value: PatientModel;\n};\n\nexport type PatientSearchProps = {\n  pageSize?: number;\n  onSearchClick?: (e: unknown) => void;\n};\n\nexport const PatientSearch = withErrorBoundary(\n  ({ pageSize = 250, onSearchClick }: PatientSearchProps) => {\n    const [patients, setPatients] = useState<PatientModel[]>([]);\n    const [searchValue, setSearchValue] = useState<string | undefined>();\n    const {\n      data: { patients: responsePatients } = {},\n      isFetching,\n      isError,\n    } = usePatientSearchList(pageSize, 0, searchValue);\n\n    // Here we are setting the total and patients only when we know that useQuery\n    // isn't fetching. This will prevent empty intermediate states where there\n    // is no data because the value of `usePatientsTable()` hasn't settled yet.\n    useEffect(() => {\n      if (!isFetching && responsePatients) {\n        setPatients(responsePatients);\n      }\n    }, [responsePatients, isError, isFetching]);\n\n    // This resets our state when there is an error fetching patients from ODS.\n    useEffect(() => {\n      if (isError) {\n        setPatients([]);\n      }\n    }, [isError, isFetching]);\n\n    const options = orderBy(patients, \"lastName\", \"asc\").map((patient) => ({\n      value: patient,\n      label: patient.fullName,\n      key: patient.id,\n    }));\n\n    return (\n      <ComboboxField\n        enableSearchIcon\n        options={options}\n        readonly={false}\n        isLoading={isFetching}\n        name=\"patient-search\"\n        onCustomSelectChange={onSearchClick}\n        renderCustomOption={(e) => <CustomComboBox option={e as CustomPatientOptionValue} />}\n        onSearchChange={(e) => {\n          setSearchValue(e);\n          setPatients([]);\n        }}\n        placeholder=\"Search by patient name or identifier\"\n      />\n    );\n  },\n  \"PatientsSearch\"\n);\n\nexport const CustomComboBox = ({ option }: { option: CustomPatientOptionValue }) => (\n  <Combobox.Option\n    value={option}\n    className={({ active }) =>\n      `ctw-relative ctw-flex ctw-cursor-default ctw-select-none ctw-space-x-2 ctw-py-2 ctw-pl-4 ctw-pr-4 ${\n        active ? \"ctw-bg-primary-light ctw-text-primary-dark\" : \"ctw-text-content-black\"\n      }`\n    }\n  >\n    <div className=\"ctw-space-x-1\">\n      <span className=\"ctw-font-medium\">{option.value.fullName}</span>\n      <span className=\"ctw-font-medium\">\n        {option.value.gender && `(${option.value.gender[0].toUpperCase()})`}\n      </span>\n    </div>\n    <div className=\"ctw-font-medium\">{option.value.officialOrUsualIdentifier}</div>\n    <div className=\"ctw-space-x-1\">\n      <span>{option.value.dob}</span>\n      <span>{option.value.age && `(${option.value.age})`}</span>\n    </div>\n  </Combobox.Option>\n);","import { Argument } from \"classnames\";\nimport { PatientInfoLine } from \"./patient-info-line\";\nimport { MinRecordItem } from \"@/components/core/table/table-helpers\";\nimport { PatientModel } from \"@/fhir/models\";\n\nexport type PatientNameColumnProps = {\n  patient: PatientModel;\n};\n\nexport const PatientNameColumn = ({ patient }: PatientNameColumnProps) => (\n  <div className=\"ctw-flex ctw-items-center\">\n    <div className=\"ctw-ml-4\">\n      <div className=\"ctw-flex ctw-font-medium\">\n        <div className=\"ctw-max-w-xs\">{patient.fullName}</div>\n        {patient.gender && <div className=\"ctw-uppercase\"> ({patient.gender[0]})</div>}\n      </div>\n      <PatientInfoLine patient={patient} className=\"ctw-text-content-lighter\" />\n    </div>\n  </div>\n);\n\n// Set of props that are optional configurations for the table.\nexport type TableOptionProps<T extends MinRecordItem> = {\n  getRowClasses?: (row: T) => Argument; // Adds a row hover effect and calls onClick.\n  onRowClick?: (row: T) => void;\n};\n","/* eslint-disable no-await-in-loop */\nimport { differenceInMinutes } from \"date-fns\";\nimport { useEffect, useState } from \"react\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { PatientModel } from \"@/fhir/models\";\nimport { getPatientByID } from \"@/fhir/patient-helper\";\nimport { cloneDeep, isEqual } from \"@/utils/nodash\";\nimport { sleep } from \"@/utils/sleep\";\n\n// We only poll patients that were created recently. This is a safeguard\n// to prevent constant polling in the case a UPID is never assigned.\n// This shouldn't happen in practice, but it's a good safeguard.\nconst IS_NEW_MINUTES_THRESHOLD = 10;\n\nconst REFETCH_INTERVAL_MS = 1000;\n\nexport function useUpidPolling(fetchedPatients: PatientModel[]) {\n  const { getRequestContext } = useCTW();\n  const [patients, setPatients] = useState(fetchedPatients);\n\n  useEffect(() => {\n    // Only clone the fetchedPatients if it has changed. This is to prevent\n    // unnecessary re-renders.\n    let patientsTmp = patients;\n    const fetchedPatientIds = fetchedPatients.map(patient => patient.id);\n    const patientsTmpIds = patientsTmp.map(patient => patient.id);\n    if (!isEqual(fetchedPatientIds, patientsTmpIds)) {\n      patientsTmp = cloneDeep(fetchedPatients);\n      setPatients(patientsTmp);\n    }\n\n    // We use this to safeguard our while loop below from running after we re-render or\n    // unmount this hook. This can happen when the patients table gets refreshed,\n    // for example, if the user pages the patients-table or adds a new patient.\n    let continuePolling = true;\n\n    const checkUpids = async () => {\n      const requestContext = await getRequestContext();\n      // Find patients without upids and created within last 10 minutes\n      const patientsWithoutUpid = patientsTmp.filter(\n        (patient) => !patient.UPID && isNewPatient(patient),\n      );\n\n      while (continuePolling && patientsWithoutUpid.length) {\n        const patient = patientsWithoutUpid[0];\n        const refreshedPatient = await getPatientByID(requestContext, patient.id);\n        if (refreshedPatient.UPID) {\n          // Update the underlying patient resource which now has the UPID identifier.\n          // We do this on the original patient which is referenced by patientsTmp.\n          patient.resource = refreshedPatient.resource;\n          setPatients([...patientsTmp]);\n          patientsWithoutUpid.shift();\n        } else {\n          await sleep(REFETCH_INTERVAL_MS);\n        }\n      }\n    };\n\n    void checkUpids();\n\n    return () => {\n      continuePolling = false;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [fetchedPatients, getRequestContext]);\n\n  return patients;\n}\n\n// Returns true if the patient was created within the last IS_NEW_MINUTES_THRESHOLD.\nfunction isNewPatient(patient: PatientModel) {\n  return (\n    !patient.createdAt ||\n    differenceInMinutes(new Date(), new Date(patient.createdAt)) < IS_NEW_MINUTES_THRESHOLD\n  );\n}\n","import {\n  QUERY_KEY_MEDICATION_HISTORY,\n  QUERY_KEY_PATIENT_BUILDER_MEDICATIONS,\n  QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS,\n} from \"./query-keys\";\nimport { queryClient } from \"@/utils/request\";\n\n// Invalidate all queries\nexport const invalidateQueries = () => queryClient.invalidateQueries();\n\nexport const invalidateQueriesFrom = (queryKey: unknown[]) =>\n  queryClient.invalidateQueries({ queryKey });\n\nexport function invalidateBuilderMedsQueries() {\n  return invalidateQueriesFrom([QUERY_KEY_PATIENT_BUILDER_MEDICATIONS]);\n}\n\nexport function invalidateOtherProviderMedsQueries() {\n  return invalidateQueriesFrom([QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS]);\n}\n\nexport function invalidateMedicationHistoryQueries() {\n  return invalidateQueriesFrom([QUERY_KEY_MEDICATION_HISTORY]);\n}\n\nexport function invalidateAllMedicationQueries() {\n  return Promise.all([\n    invalidateBuilderMedsQueries(),\n    invalidateOtherProviderMedsQueries(),\n    invalidateMedicationHistoryQueries(),\n  ]);\n}\n","import type { TableColumn } from \"@/components/core/table/table-helpers\";\nimport type { PatientModel } from \"@/fhir/models/patient\";\nimport cx from \"classnames\";\nimport { useState } from \"react\";\nimport { PatientNameColumn, TableOptionProps } from \"./patients-table-helper\";\nimport { useUpidPolling } from \"./use-upid-polling\";\nimport { ErrorAlert } from \"@/components/core/alert\";\nimport { Badge } from \"@/components/core/badge\";\nimport * as CTWBox from \"@/components/core/ctw-box\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { SimplePagination } from \"@/components/core/pagination/simple-pagination\";\nimport { AnalyticsProvider } from \"@/components/core/providers/analytics/analytics-provider\";\nimport { Table } from \"@/components/core/table/table\";\nimport { formatISODateStringToDate } from \"@/fhir/formatters\";\nimport { usePatientsListFQS } from \"@/fhir/patient-helper\";\nimport { invalidateQueriesFrom } from \"@/utils/invalidate-queries\";\nimport { QUERY_KEY_PATIENTS_LIST_FQS } from \"@/utils/query-keys\";\nimport \"./patients-table.scss\";\n\nexport type PatientsTableProps = {\n  className?: cx.Argument;\n  handleRowClick: (row: PatientModel) => void;\n  pageSize?: number;\n  title?: string;\n} & TableOptionProps<PatientModel>;\n\n/**\n * PatientsTable displays a paginated list of all patients for a builder. In\n * addition to having configurable page size, lazy loading and name search, the\n * component accepts an `onRowClick` prop so developers can add their own\n * logic when a row is clicked. The `onRowClick` receives the targeted\n * `PatientModel` as its sole argument, which contains the underlying FHIR\n * object as `.resource`.\n *\n */\nexport const PatientsTable = withErrorBoundary(\n  ({ className, handleRowClick, pageSize = 5, title = \"Patients\" }: PatientsTableProps) => {\n    const [currentPage, setCurrentPage] = useState(1);\n    const [cursors, setCursors] = useState<string[]>([\"\"]);\n    const { data, isLoading, isError } = usePatientsListFQS(pageSize, cursors[currentPage - 1]);\n    const patients = useUpidPolling(data?.patients ?? []);\n\n    return isError ? (\n      <ErrorAlert header=\"Error\">Could not load list of patients.</ErrorAlert>\n    ) : (\n      <AnalyticsProvider componentName=\"PatientsTable\">\n        <CTWBox.StackedWrapper\n          className={cx(\"ctw-patients-border ctw-patients-table-inputs\", className)}\n        >\n          <CTWBox.Heading title={title} />\n          <div className=\"ctw-overflow-hidden\">\n            <Table\n              canClickRow={(record) => !!record.UPID}\n              records={patients}\n              isLoading={isLoading}\n              columns={columns}\n              getRowClassName={(record) =>\n                record.UPID ? \"\" : \"ctw-bg-bg-light [&_*]:ctw-text-content-light\"\n              }\n              handleRowClick={handleRowClick}\n              pageSize={pageSize}\n              hidePagination\n            >\n              <SimplePagination\n                setCurrentPage={(p) => {\n                  const cursorIndex = p - 1;\n                  if (p > currentPage) {\n                    const newCursors = [...cursors];\n                    newCursors[cursorIndex] = data?.pageInfo.endCursor ?? \"\";\n                    setCursors(newCursors);\n                  }\n                  setCurrentPage(p);\n                }}\n                currentPage={currentPage}\n                hasNext={data?.pageInfo.hasNextPage}\n              />\n            </Table>\n          </div>\n        </CTWBox.StackedWrapper>\n      </AnalyticsProvider>\n    );\n  },\n  \"PatientsTable\",\n);\n\nconst columns: TableColumn<PatientModel>[] = [\n  {\n    title: \"Name\",\n    render: (patient) => <PatientNameColumn patient={patient} />,\n  },\n  {\n    title: \"Contact\",\n    render: ({ email, phoneNumber }) => (\n      <>\n        <div className=\"ctw-patients-table-inputs-email\">{email}</div>\n        <div className=\"ctw-patients-table-inputs-phone\">{phoneNumber}</div>\n      </>\n    ),\n  },\n  {\n    title: \"Created\",\n    render: (p) =>\n      p.UPID ? formatISODateStringToDate(p.lastUpdated) : <Badge color=\"info\" text=\"In-Progress\" />,\n  },\n];\n\nexport async function refreshPatientsTable() {\n  await invalidateQueriesFrom([QUERY_KEY_PATIENTS_LIST_FQS]);\n}\n","import { Resource } from \"fhir/r4\";\n// eslint-disable-next-line @typescript-eslint/no-restricted-imports\nimport { useEffect, useRef, useState } from \"react\";\nimport { ZusAggregatedProfileProps } from \"./zus-aggregated-profile\";\nimport { getZapIFrameUrl } from \"@/api/urls\";\nimport { withErrorBoundary } from \"@/components/core/error-boundary\";\nimport { CTWRequestContext } from \"@/components/core/providers/ctw-context\";\nimport { CTWProviderProps } from \"@/components/core/providers/ctw-provider\";\nimport {\n  PatientResourceID,\n  ThirdPartyID,\n  usePatientContext,\n} from \"@/components/core/providers/patient-provider\";\nimport { useTelemetry } from \"@/components/core/providers/telemetry/use-telemetry\";\nimport { useTheme } from \"@/components/core/providers/theme/use-theme\";\nimport { useCTW } from \"@/components/core/providers/use-ctw\";\nimport { MedicationStatementModel } from \"@/fhir/models\";\nimport { useIsomorphicLayoutEffect } from \"@/hooks/use-isomorphic-layout-effect\";\nimport { omit } from \"@/utils/nodash/fp\";\n\n// Theming for iframe which can't be handled via global tailwind theme\nexport type IFrameTheme = {\n  fontFamily?: \"Avenir\" | \"Roboto\";\n  headerSize?: string;\n  lineHeight?: string;\n  letterSpacing?: string;\n  fontWeight?: string;\n};\nexport type ZapIFrameConfig = {\n  CTWProviderProps: CTWProviderProps;\n  PatientProviderProps: ThirdPartyID | PatientResourceID;\n  ZusAggregatedProfileProps: ZusAggregatedProfileIFrameProps;\n  iframeTheme: IFrameTheme | undefined;\n};\nexport const ZapIFrameConfigMessageType = \"ZusAggregatedProfileIFrameConfig\";\nexport const ZapIFrameReadyMessageType = \"ZusAggregatedProfileIFrameReady\";\nexport const ZapOnResourceSaveMessageType = \"ZusAggregatedProfileOnResourceSave\";\nexport const ZapOnPatientSaveMessageType = \"ZusAggregatedProfileOnPatientSave\";\nexport const ZapOnAddToRecordMessageType = \"ZusAggregatedProfileOnAddToRecord\";\nexport const ZapOnConfigReceivedMessageType = \"ZusAggregatedProfileConfigReceived\";\n\nexport type ZapMessageEventData<EventType, EventPayload = undefined> = {\n  type: EventType;\n  id?: string;\n} & ({ payload: EventPayload; error?: never } | { payload?: never; error: string });\n\nexport type ZapIFrameConfigMessageEvent = ZapMessageEventData<typeof ZapIFrameConfigMessageType>;\nexport type ZapOnConfigReceivedMessageEvent = ZapMessageEventData<\n  typeof ZapOnConfigReceivedMessageType\n>;\nexport type ZapIFrameReadyMessageEvent = ZapMessageEventData<typeof ZapIFrameReadyMessageType>;\nexport type ZapOnResourceSaveMessageEvent = ZapMessageEventData<\n  typeof ZapOnResourceSaveMessageType,\n  {\n    resource: Resource;\n    action: \"create\" | \"update\";\n    error?: string;\n  }\n>;\nexport type ZapOnAddToRecordMessageEvent = ZapMessageEventData<\n  typeof ZapOnAddToRecordMessageType,\n  {\n    resource: fhir4.MedicationStatement;\n    includedResources?: Record<string, fhir4.Resource>;\n    component: \"medications-outside\" | \"medications-all\";\n  }\n>;\n\nexport type ZapMessageEvent = MessageEvent<\n  | ZapOnAddToRecordMessageEvent\n  | ZapOnConfigReceivedMessageEvent\n  | ZapOnResourceSaveMessageEvent\n  | ZapIFrameConfigMessageEvent\n  | ZapIFrameReadyMessageEvent\n>;\n\ntype ZusAggregatedProfileIFrameProps = ZusAggregatedProfileProps & {\n  overrideIframeUrl?: string;\n};\n\nconst IFRAME_MAX_LOAD_TIME_MS = 5000; // 5 seconds is a very reasonable amount of time for the iframe to load\n\nconst ZusAggregatedProfileIFrameComponent = (props: ZusAggregatedProfileIFrameProps) => {\n  const { Telemetry, context: telemetryContext } = useTelemetry();\n  const { overrideIframeUrl } = props;\n  const iframeRef = useRef<HTMLIFrameElement>(null);\n  const [hostedZapReady, setHostedZapReady] = useState(false);\n  const [preparedOnReadyListener, setPreparedOnReadyListener] = useState(false);\n  const [iframeShouldBeLoaded, setIframeShouldBeLoaded] = useState(false);\n  const [sentZapConfig, setSentZapConfig] = useState(false);\n  const [zapURL, setZapUrl] = useState<string | undefined>(overrideIframeUrl);\n  const [onAddToRecord, setOnAddToRecord] = useState<(e: ZapMessageEvent) => void>();\n  const { getRequestContext, featureFlags } = useCTW();\n  const patient = usePatientContext();\n  const theme = useTheme();\n\n  const { medicationsOutsideProps, medicationsAllProps } = props;\n\n  if (iframeShouldBeLoaded && !hostedZapReady) {\n    // It has been a reasonable amount of time since this component mounted and set the onPreparedReadyListener and we\n    // still have not heard back from the embedded iframe. This could indicate that there is either an issue downloading\n    // the embedded ZAP static files or some wonkiness in our window message event listeners. In either case, we should\n    // error here to prevent the user from waiting indefinitely and let the error boundary send component failure metrics.\n    throw new Error(\n      \"The ZAP should have connected by now. Please try to refresh the ZAP. If this error persists please contact support.\",\n    );\n  }\n\n  useEffect(() => {\n    const onAddToRecordHandler = async ({ data }: ZapMessageEvent) => {\n      if (data.type === ZapOnAddToRecordMessageType && typeof data.error !== \"string\") {\n        const medicationStatement = new MedicationStatementModel(\n          data.payload.resource,\n          data.payload.includedResources,\n        );\n        const response: Partial<ZapOnAddToRecordMessageEvent> = {\n          id: data.id,\n          type: data.type,\n        };\n        try {\n          switch (data.payload.component) {\n            case \"medications-outside\":\n              await medicationsOutsideProps?.onAddToRecord?.(medicationStatement);\n              break;\n            case \"medications-all\":\n              await medicationsAllProps?.onAddToRecord?.(medicationStatement);\n              break;\n            default:\n              response.error = `Unhandled onAddToRecord for component: ${data.payload.component}`;\n          }\n        } catch (e) {\n          response.error = e instanceof Error ? e.message : \"Unknown error\";\n        }\n        iframeRef.current?.contentWindow?.postMessage(response, String(zapURL));\n        Telemetry.logger.debug(\n          \"ZusAggregatedProfileIframe - Sent onAddToRecord message from parent frame\",\n        );\n      }\n    };\n\n    // Add this listener\n    const updatedOnAddToRecordHandler = (event: ZapMessageEvent) => {\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Receiving onAddToRecord message in parent frame\",\n      );\n      void onAddToRecordHandler(event as ZapMessageEvent);\n    };\n    // Remove previous listener if exists\n    if (onAddToRecord) {\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Removed previous onAddToRecord listener from parent frame\",\n      );\n      window.removeEventListener(\"message\", onAddToRecord);\n    }\n    window.addEventListener(\"message\", updatedOnAddToRecordHandler);\n    Telemetry.logger.debug(\n      \"ZusAggregatedProfileIframe - Added onAddToRecord listener to parent frame\",\n    );\n\n    // Set the current listener and remove it later if this effect is called again.\n    setOnAddToRecord(() => updatedOnAddToRecordHandler);\n    return () => {\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Unmounting, removing onAddToRecord listener from parent frame\",\n      );\n      window.removeEventListener(\"message\", updatedOnAddToRecordHandler);\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [\n    medicationsOutsideProps?.readOnly,\n    medicationsOutsideProps?.onAddToRecord,\n    medicationsAllProps?.readOnly,\n    medicationsAllProps?.onAddToRecord,\n    zapURL,\n  ]);\n\n  useIsomorphicLayoutEffect(() => {\n    // listener to know when iframe ZAP is ready\n    const onMessageReady = ({ data }: ZapMessageEvent) => {\n      // Handle message that iframe is ready to receive ctw config\n      if (data.type === ZapIFrameReadyMessageType) {\n        Telemetry.logger.debug(\n          \"ZusAggregatedProfileIframe - Receiving IFrameReady message in parent frame, setting hostedZapReady to true\",\n        );\n        setHostedZapReady(true);\n      }\n      // Handle message that iframe successfully received ctw config. This simply for debugging purposes.\n      if (data.type === ZapOnConfigReceivedMessageType) {\n        Telemetry.logger.debug(\n          \"ZusAggregatedProfileIframe - Receiving onConfigReceived message in parent frame\",\n        );\n      }\n    };\n    window.addEventListener(\"message\", onMessageReady);\n    Telemetry.logger.debug(\n      \"ZusAggregatedProfileIframe - Added onMessageReady listener to parent frame\",\n    );\n    setPreparedOnReadyListener(true);\n\n    const timeoutId = setTimeout(() => {\n      setIframeShouldBeLoaded(true);\n    }, IFRAME_MAX_LOAD_TIME_MS);\n\n    return () => {\n      clearTimeout(timeoutId);\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Unmounting, removing onMessageReady listener from parent frame\",\n      );\n      window.removeEventListener(\"message\", onMessageReady);\n    };\n  }, []);\n\n  useEffect(() => {\n    // set up ZAP URL and listener for resource save\n    let requestContext: CTWRequestContext | undefined;\n    void (async () => {\n      requestContext = await getRequestContext();\n      setZapUrl(overrideIframeUrl ?? getZapIFrameUrl(requestContext.env));\n    })();\n\n    const onMessageSave = ({ data }: ZapMessageEvent) => {\n      if (data.type === ZapOnResourceSaveMessageType && typeof data.error !== \"string\") {\n        Telemetry.logger.debug(\n          \"ZusAggregatedProfileIframe - Receiving onMessageSave message in parent frame\",\n        );\n        const { resource, action, error } = data.payload;\n        requestContext?.onResourceSave(resource, action, new Error(error));\n      }\n    };\n\n    window.addEventListener(\"message\", onMessageSave);\n    Telemetry.logger.debug(\n      \"ZusAggregatedProfileIframe - Added onMessageSave listener to parent frame\",\n    );\n    return () => {\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Unmounting, removing onMessageSave listener from parent frame\",\n      );\n      window.removeEventListener(\"message\", onMessageSave);\n    };\n  }, [Telemetry.logger, getRequestContext, overrideIframeUrl]);\n\n  useEffect(() => {\n    // Pass config to iframe\n    async function load() {\n      const requestContext = await getRequestContext();\n\n      //  & { locals?: Locals, enableTelemetry: boolean, ehr: string }\n      const ctwProviderProps: CTWProviderProps = {\n        authToken: requestContext.authToken,\n        env: requestContext.env,\n        builderId: requestContext.builderId,\n        featureFlags,\n        ehr: telemetryContext.ehr,\n        enableTelemetry: telemetryContext.enableTelemetry,\n        headers: requestContext.headers as Record<string, string> | undefined,\n        locals: theme.locals,\n        theme: {\n          ...theme.theme,\n          iframe: theme.iframeTheme,\n        },\n      };\n\n      const payload: ZapIFrameConfig = {\n        CTWProviderProps: ctwProviderProps,\n        PatientProviderProps:\n          typeof patient.patientResourceID === \"string\"\n            ? {\n                patientResourceID: patient.patientResourceID,\n              }\n            : {\n                patientID: patient.patientID ?? \"\",\n                systemURL: patient.systemURL ?? \"\",\n              },\n        ZusAggregatedProfileProps: {\n          ...props,\n          medicationsOutsideProps: omit(\"onAddToRecord\", medicationsOutsideProps),\n          medicationsAllProps: omit(\"onAddToRecord\", medicationsAllProps),\n        },\n        // todo: refactor this out. It is redundant with CTWProviderProps.theme.iframe but it's expected by the standalone ZAP.\n        iframeTheme: theme.iframeTheme,\n      };\n\n      iframeRef.current?.contentWindow?.postMessage(\n        { type: ZapIFrameConfigMessageType, payload },\n        zapURL as string,\n      );\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Sent ZapIFrameConfig message from parent frame\",\n      );\n      setSentZapConfig(true);\n    }\n\n    if (hostedZapReady) {\n      Telemetry.logger.debug(\n        \"ZusAggregatedProfileIframe - Hosted ZAP is ready, preparing to send config from parent frame\",\n      );\n      void load();\n    }\n  }, [\n    getRequestContext,\n    hostedZapReady,\n    iframeRef,\n    patient.patientResourceID,\n    patient.patientID,\n    patient.systemURL,\n    props,\n    medicationsAllProps,\n    medicationsOutsideProps,\n    zapURL,\n    sentZapConfig,\n    featureFlags,\n    theme.theme,\n    theme.locals,\n    telemetryContext.enableTelemetry,\n    telemetryContext.ehr,\n    theme.iframeTheme,\n    Telemetry.logger,\n  ]);\n\n  if (!zapURL || !preparedOnReadyListener) {\n    return null;\n  }\n  return (\n    <iframe\n      ref={iframeRef}\n      data-testid=\"iframe-zap\"\n      title=\"zus-aggregated-profile\"\n      height=\"100%\"\n      width=\"100%\"\n      src={`${zapURL}/v1`}\n      className=\"ctw-border-0\"\n    />\n  );\n};\n\nexport const ZusAggregatedProfileIFrame = withErrorBoundary(\n  ZusAggregatedProfileIFrameComponent,\n  \"ZusAggregatedProfileIFrame\",\n  true,\n);\n","import cx from \"classnames\";\nimport { isFunction } from \"@/utils/nodash/fp\";\nimport \"./action-list.scss\";\n\nexport type MinActionItem = {\n  complete: boolean;\n  id: string;\n  subtitle?: string;\n  title: string;\n};\n\nexport type ActionItemProps<T extends MinActionItem> = {\n  actionText?: string;\n  activeClassName?: string;\n  className?: string;\n  item: T;\n  onAction?: (i: T) => void;\n  onRowClick?: (i: T) => void;\n  onSecondaryAction?: (i: T) => void;\n  secondaryActionText?: string;\n  onUndoAction?: (i: T) => void;\n  undoActionText?: string;\n};\n\nexport type ActionListProps<T extends MinActionItem> = {\n  items: T[];\n} & Omit<ActionItemProps<T>, \"item\">;\n\n/**\n * Displays a list of action items which reflect whether they are\n * completed or not. List items marked \"active\" will show a (primary)\n * colored border to the left and when hovered will present a button\n * to take action. Use the \"onAction\" handler to mark items as \"complete\".\n *\n * Optionally the opposite can be done for inactive items if an \"onUndoAction\"\n * handler is passed in, but that is not a requirement.\n */\nexport const ActionList = <T extends MinActionItem>({\n  items,\n  className,\n  ...itemProps\n}: ActionListProps<T>) => (\n  <ul\n    className={cx(\"ctw-action-list ctw-rounded-lg\", className, {\n      \"ctw-border-0\": items.length === 0,\n      \"ctw-bg-bg-lighter\": items.length > 0,\n    })}\n  >\n    {items.map((item) => (\n      <ActionListItem key={item.id} item={item} {...itemProps} />\n    ))}\n  </ul>\n);\n\nexport const ActionListItem = <T extends MinActionItem>({\n  item,\n  onRowClick,\n  onAction = () => {},\n  onSecondaryAction,\n  secondaryActionText,\n  actionText = \"Mark Complete\",\n  undoActionText = \"Undo\",\n  onUndoAction,\n  activeClassName = \"active\",\n}: ActionItemProps<T>) => (\n  <li\n    role=\"row\"\n    className={cx(\n      \"ctw-action-list-item\",\n      \"ctw-border-lighter ctw-flex ctw-cursor-pointer ctw-p-4\",\n      {\n        [activeClassName]: !item.complete,\n        undoable: isFunction(onUndoAction),\n      }\n    )}\n    onKeyDown={(event) => {\n      // Visible, non-intercomplete elements with click handlers must have at least 1 keyboard listener\n      if (event.key === \"Enter\") {\n        event.currentTarget.click();\n      }\n    }}\n    onClick={() => onRowClick?.(item)}\n  >\n    <div className=\"ctw-action-list-item-content ctw-flex-grow\">\n      <div className=\"ctw-font-semibold\">{item.title}</div>\n      {item.subtitle && <div className=\"ctw-font-light\">{item.subtitle}</div>}\n    </div>\n    <div className=\"ctw-action-list-item-action\">\n      {!item.complete && (\n        <button\n          type=\"button\"\n          className=\"ctw-btn-primary\"\n          onClick={(event) => {\n            event.stopPropagation();\n            onAction(item);\n          }}\n        >\n          {actionText}\n        </button>\n      )}\n      {onSecondaryAction && secondaryActionText && (\n        <button\n          type=\"button\"\n          className=\"ctw-btn-primary ctw-ml-1\"\n          onClick={(event) => {\n            event.stopPropagation();\n            onSecondaryAction(item);\n          }}\n        >\n          {secondaryActionText}\n        </button>\n      )}\n      {item.complete && !!onUndoAction && (\n        <button\n          type=\"button\"\n          className=\"ctw-btn-default\"\n          onClick={(event) => {\n            event.stopPropagation();\n            onUndoAction(item);\n          }}\n        >\n          {undoActionText}\n        </button>\n      )}\n    </div>\n  </li>\n);\n","type ZusIconProps = {\n  className?: string;\n  includeZusText?: boolean;\n};\nexport const ZusIcon = ({ className, includeZusText = false }: ZusIconProps) => (\n  <svg\n    viewBox={includeZusText ? \"0 0 47 24\" : \"0 0 24 24\"}\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <title>Zus Health</title>\n    <g clip-path=\"url(#clip0_105_5210)\">\n      <path\n        d=\"M17.8781 17.222L12.2169 13.9545L16.2985 6.88471C16.3251 6.83922 16.3722 6.75608 16.2985 6.62745C16.2247 6.49882 16.1275 6.49882 16.0757 6.49882H7.91101V-0.0392151H16.0757C18.5322 -0.0392151 20.7314 1.2298 21.9596 3.35686C23.1879 5.48392 23.1879 8.02353 21.9596 10.1506L17.8781 17.2204V17.222Z\"\n        fill=\"#008051\"\n      />\n      <path\n        d=\"M15.453 24H7.36357C4.9071 24 2.70788 22.731 1.47965 20.6039C0.251413 18.4769 0.251413 15.9372 1.47965 13.8102L5.56122 6.74039L11.2208 10.0078L7.13926 17.0776C7.11259 17.1231 7.06553 17.2063 7.13926 17.3349C7.21298 17.4635 7.31024 17.4635 7.362 17.4635H15.4514V24H15.453Z\"\n        fill=\"#71B2C9\"\n      />\n      {includeZusText && (\n        <>\n          <path\n            d=\"M30.8098 10.4283C30.9211 10.4283 30.9619 10.4973 30.9619 10.5945V10.8988C30.9619 11.0369 30.976 11.12 30.838 11.3145L27.1862 16.3498H31.0874V17.1388H26.2325C26.1211 17.1388 26.0804 17.0839 26.0804 16.9867V16.6683C26.0804 16.5302 26.0662 16.4471 26.2043 16.2526L29.8294 11.2173H26.1353V10.4283H30.8113H30.8098Z\"\n            fill=\"#008051\"\n          />\n          <path\n            d=\"M38.016 10.4283H38.9698V16.2526C38.9698 16.5161 38.8866 16.6808 38.6231 16.7922L37.9313 17.0683C37.6129 17.1922 37.4749 17.2204 37.1298 17.2204H35.0137C34.4882 17.2204 34.2529 17.1232 33.9486 16.8188L33.5894 16.4596C33.216 16.0863 33.1611 15.9483 33.1611 15.3255V10.4283H34.1149V15.3537C34.1149 15.5749 34.1556 15.6581 34.3219 15.8243L34.6403 16.1428C34.8207 16.309 34.8756 16.3373 35.1517 16.3373H37.0749C37.158 16.3373 37.2411 16.3232 37.3102 16.2949L37.9329 16.0455C37.9878 16.0173 38.016 15.9906 38.016 15.9216V10.4298V10.4283Z\"\n            fill=\"#008051\"\n          />\n          <path\n            d=\"M42.471 14.1224C42.0427 14.0816 41.7102 13.9702 41.489 13.7632C41.2537 13.542 41.1298 13.1969 41.1298 12.6573V12.2149C41.1298 11.6612 41.1847 11.4824 41.558 11.1075L41.9173 10.7482C42.2357 10.4439 42.471 10.3467 42.9965 10.3467H44.4067C44.8914 10.3467 45.0984 10.389 45.431 10.5961L46.2059 11.0667L45.8325 11.7443L44.8914 11.3161C44.6984 11.233 44.5588 11.2047 44.311 11.2047H43.1078C42.8318 11.2047 42.7753 11.233 42.5965 11.3992L42.2639 11.7318C42.0976 11.8981 42.0569 11.9812 42.0569 12.2024V12.7137C42.0569 13.073 42.1541 13.1984 42.5416 13.2392L45.0733 13.4745C45.5988 13.5294 45.9031 13.6408 46.1243 13.862C46.3455 14.0831 46.4427 14.4157 46.4427 14.8863V15.3286C46.4427 15.9514 46.3878 16.0894 46.0145 16.4628L45.6553 16.822C45.351 17.1263 45.1157 17.2235 44.5902 17.2235H42.8192C42.3345 17.2235 42.1274 17.1812 41.7823 16.9741L41.0074 16.5035L41.3808 15.8259L42.322 16.2682C42.5149 16.3514 42.6545 16.3655 42.9024 16.3655H44.4663C44.7424 16.3655 44.7988 16.3373 44.9776 16.171L45.3102 15.8384C45.4765 15.6722 45.5173 15.589 45.5173 15.3679V14.8832C45.5173 14.5239 45.42 14.3984 45.0325 14.3577L42.4725 14.1224H42.471Z\"\n            fill=\"#008051\"\n          />\n        </>\n      )}\n    </g>\n    <defs>\n      <clipPath id=\"clip0_105_5210\">\n        <rect width=\"45.8039\" height=\"24\" fill=\"white\" transform=\"translate(0.598022)\" />\n      </clipPath>\n    </defs>\n  </svg>\n);\n","import { ChevronLeftIcon, ChevronRightIcon } from \"@heroicons/react/solid\";\nimport cx from \"classnames\";\nimport type { ReactNode } from \"react\";\nimport { Fragment } from \"react\";\nimport \"./pagination.scss\";\nimport { Loading } from \"@/components/core/loading\";\nimport { useAnalytics } from \"@/components/core/providers/analytics/use-analytics\";\nimport { uniq } from \"@/utils/nodash\";\n\nexport type PaginationProps = {\n  currentPage: number;\n  isLoading?: boolean;\n  pageSize: number;\n  setCurrentPage: (n: number) => void;\n  total: number;\n};\n\nexport const Pagination = ({\n  currentPage,\n  isLoading = false,\n  pageSize,\n  setCurrentPage,\n  total,\n}: PaginationProps) => {\n  const start = Math.min(total, (currentPage - 1) * pageSize + 1);\n  const finish = Math.min(currentPage * pageSize, total);\n  const pageCount = Math.ceil(total / pageSize);\n  const prevPage = Math.max(currentPage - 1, 1);\n  const nextPage = Math.min(currentPage + 1, pageCount);\n\n  // Always show the first page link and the last.\n  let pagesToShow = [1, pageCount];\n  // Always show currentPage and one before and after.\n  pagesToShow.push(currentPage - 1, currentPage, currentPage + 1);\n  // Dedupe, sort and filter away any pages that are out of range.\n  pagesToShow = uniq(\n    pagesToShow.sort((a, b) => a - b).filter((page) => page >= 1 && page <= pageCount)\n  );\n\n  return (\n    <div className=\"ctw-flex ctw-justify-between ctw-px-6 ctw-py-3\">\n      <div className=\"ctw-text-gray-600 ctw-text-sm\">\n        {isLoading ? (\n          <Loading />\n        ) : (\n          <>\n            <span className=\"ctw-font-medium\">{start}</span> to{\" \"}\n            <span className=\"ctw-font-medium\">{finish}</span> of{\" \"}\n            <span className=\"ctw-font-medium\">{total}</span> results\n          </>\n        )}\n      </div>\n\n      {pageCount > 1 && (\n        <div>\n          <nav className=\"ctw-pagination-nav\" aria-label=\"Pagination\">\n            <Page\n              page={prevPage}\n              setCurrentPage={setCurrentPage}\n              className=\"ctw-pagination-group-start ctw-hover:ctw-bg-gray-50\"\n              disabled={currentPage === 1}\n            >\n              <span className=\"ctw-sr-only\">Previous</span>\n              <ChevronLeftIcon className=\"ctw-h-5 ctw-w-5\" aria-hidden=\"true\" />\n            </Page>\n\n            {pagesToShow.map((page, index) => {\n              const prev = pagesToShow[index - 1] ?? 0;\n              const pagesSkipped = page - prev - 1;\n\n              return (\n                <Fragment key={page}>\n                  {pagesSkipped > 1 && <span className=\"ctw-pagination-ellipsis\">...</span>}\n                  {pagesSkipped === 1 && (\n                    <Page\n                      page={page - 1}\n                      setCurrentPage={setCurrentPage}\n                      currentPage={currentPage}\n                    />\n                  )}\n\n                  <Page setCurrentPage={setCurrentPage} page={page} currentPage={currentPage} />\n                </Fragment>\n              );\n            })}\n\n            <Page\n              page={nextPage}\n              setCurrentPage={setCurrentPage}\n              className=\"ctw-pagination-group-end\"\n              disabled={currentPage === pageCount}\n            >\n              <span className=\"ctw-sr-only\">Next</span>\n              <ChevronRightIcon className=\"ctw-h-5 ctw-w-5\" aria-hidden=\"true\" />\n            </Page>\n          </nav>\n        </div>\n      )}\n    </div>\n  );\n};\n\ntype PageProps = {\n  children?: ReactNode;\n  className?: cx.Argument;\n  disabled?: boolean;\n  currentPage?: number;\n  page: number;\n  setCurrentPage: (n: number) => void;\n};\n\nconst Page = ({\n  setCurrentPage,\n  page,\n  currentPage,\n  children,\n  className,\n  disabled = false,\n}: PageProps) => {\n  const { trackInteraction } = useAnalytics();\n  const active = page === currentPage;\n\n  return (\n    <button\n      type=\"button\"\n      disabled={disabled}\n      onClick={() => {\n        setCurrentPage(page);\n        trackInteraction(\"change_page\", { page });\n      }}\n      className={cx(className, \"ctw-pagination-page-btn\", { active, disabled })}\n    >\n      {children || page}\n    </button>\n  );\n};\n","import { PropsWithChildren, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { toast } from \"react-toastify\";\nimport { AuthenticationContext, CTWToken } from \"./context\";\nimport { claimsExp, hasValidClaimsAuthEmail, sendInvalidTokenNotification } from \"@/utils/auth\";\nimport { QUERY_KEY_AUTH_TOKEN } from \"@/utils/query-keys\";\nimport { ctwFetch, queryClient } from \"@/utils/request\";\n\n// We use an expiry padding to provide a buffer to prevent race conditions.\n// A race condition could happen in that we check if the token is expired,\n// it isn't, but by time we do our request(s) it has expired.\nconst EXPIRY_PADDING_MS = 60_000;\n// We track the id of the toast that we open to avoid stacking.\nconst AUTH_ERROR_TOAST_ID = \"invalid-token\";\n\nexport type AuthenticationProviderProps = {\n  headers?: Record<string, string>;\n  authToken?: string;\n  authTokenURL?: string;\n};\n\nexport function AuthenticationProvider({\n  children,\n  authToken,\n  authTokenURL,\n  headers,\n}: PropsWithChildren<AuthenticationProviderProps>) {\n  const [token, setToken] = useState<CTWToken>();\n  const [showingErrorNotice, setShowingErrorNotice] = useState(false);\n  if (!authToken && !authTokenURL) {\n    throw new Error(\"Either authToken or authTokenURL is required\");\n  }\n\n  useEffect(() => {\n    // We don't want to stack toast notifications. So we track if there is one already open with auth errors\n    const unsubscribe = toast.onChange((t) => {\n      if (t.id === AUTH_ERROR_TOAST_ID && t.status === \"removed\") {\n        setShowingErrorNotice(false);\n      }\n    });\n    return () => {\n      unsubscribe();\n    };\n  }, []);\n\n  const getAuthToken = useCallback(async () => {\n    if (authToken) {\n      if (!hasValidClaimsAuthEmail(authToken)) {\n        if (!showingErrorNotice) {\n          setShowingErrorNotice(true);\n          sendInvalidTokenNotification(authToken, AUTH_ERROR_TOAST_ID);\n        }\n        return \"\";\n      }\n      return authToken;\n    }\n\n    const newToken = await checkOrRefreshAuth(token, authTokenURL, headers);\n    if (!hasValidClaimsAuthEmail(newToken.accessToken)) {\n      if (!showingErrorNotice) {\n        setShowingErrorNotice(true);\n        sendInvalidTokenNotification(newToken.accessToken, AUTH_ERROR_TOAST_ID);\n      }\n      return \"\";\n    }\n    if (token?.accessToken !== newToken.accessToken) {\n      setToken(newToken);\n    }\n    return newToken.accessToken;\n  }, [authToken, token, authTokenURL, headers, showingErrorNotice]);\n\n  const contextValue = useMemo(\n    () => ({\n      token,\n      getAuthToken,\n    }),\n    [token, getAuthToken],\n  );\n\n  return (\n    <AuthenticationContext.Provider value={contextValue}>{children}</AuthenticationContext.Provider>\n  );\n}\n\nasync function checkOrRefreshAuth(\n  token?: CTWToken,\n  url?: string,\n  headers?: Record<string, string>,\n): Promise<CTWToken> {\n  if (!token || Date.now() >= token.expiresAt + EXPIRY_PADDING_MS) {\n    return queryClient.fetchQuery([QUERY_KEY_AUTH_TOKEN, url], async () => {\n      const { data } = await ctwFetch(url as string, { headers });\n      return {\n        accessToken: data.access_token,\n        expiresAt: claimsExp(data.access_token) * 1_000,\n      };\n    });\n  }\n  return token;\n}\n","import { PropsWithChildren, useEffect, useMemo } from \"react\";\nimport { useGetAuthToken } from \"../authentication/use-get-auth-token\";\nimport { Env } from \"../types\";\nimport { TelemetryContext } from \"@/components/core/providers/telemetry/context\";\nimport { Telemetry } from \"@/utils/telemetry\";\n\ntype TelemetryProviderProps = {\n  env: Env;\n  builderId?: string;\n  enableTelemetry?: boolean;\n  ehr?: string;\n};\n\nexport function TelemetryProvider({\n  children,\n  env,\n  builderId,\n  enableTelemetry = false,\n  ehr,\n}: PropsWithChildren<TelemetryProviderProps>) {\n  const getAuthToken = useGetAuthToken();\n  const contextValue = useMemo(\n    () => ({\n      builderId,\n      ehr,\n      enableTelemetry,\n    }),\n    [builderId, ehr, enableTelemetry]\n  );\n\n  useEffect(() => {\n    Telemetry.init(env, ehr, enableTelemetry);\n    Telemetry.setBuilder(builderId);\n    getAuthToken()\n      .then((accessToken) => Telemetry.setUser(accessToken))\n      .catch(() => Telemetry.clearUser());\n  }, [builderId, env, ehr, enableTelemetry, getAuthToken]);\n\n  return <TelemetryContext.Provider value={contextValue}>{children}</TelemetryContext.Provider>;\n}\n","import { PropsWithChildren, useEffect, useMemo, useRef, useState } from \"react\";\nimport { ThemeContext } from \"./context\";\nimport { IFrameTheme } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile-iframe\";\nimport i18next, { Locals } from \"@/i18n\";\nimport { DefaultTheme, EmptyTailwindCSSVars, mapToCSSVar, Theme } from \"@/styles/tailwind.theme\";\nimport { merge } from \"@/utils/nodash\";\n\nimport \"../../main.scss\";\n\nexport type ThemeProviderProps = {\n  theme?: Theme & { iframe?: IFrameTheme };\n  locals?: Locals;\n};\n\nexport function ThemeProvider({\n  children,\n  locals,\n  theme = {},\n}: PropsWithChildren<ThemeProviderProps>) {\n  const ctwThemeRef = useRef<HTMLDivElement>(null);\n  const [style, setStyle] = useState<string>(\"\");\n\n  // Manually compute our CSS theme string AND the\n  // fix for empty tailwind CSS vars.\n  // We have to apply this manually instead of `style={style}`\n  // as we want to use a string instead of an object where react would\n  // drop the empty variables!\n  useEffect(() => {\n    const styles = {\n      ...mapToCSSVar(theme.colors || {}),\n      ...EmptyTailwindCSSVars,\n    };\n\n    // Convert our styles into a style string.\n    setStyle(\n      Object.entries(styles)\n        .map(([key, value]) => `${key}:${value}`)\n        .join(\";\")\n    );\n  }, [ctwThemeRef, theme]);\n\n  // Manually apply our CSS theme string to the ctw-theme class.\n  useEffect(() => {\n    ctwThemeRef.current?.setAttribute(\"style\", style);\n  }, [ctwThemeRef, style]);\n\n  // Workaround for https://github.com/tailwindlabs/headlessui/discussions/666\n  // Note: We want the portal root to:\n  //    1. Be a child of body.\n  //    2. Have our theme styles.\n  useEffect(() => {\n    // Remove any existing portal root.\n    document.getElementById(\"headlessui-portal-root\")?.remove();\n\n    // Create a new portal root.\n    const el = document.createElement(\"div\");\n    el.id = \"headlessui-portal-root\";\n\n    // It needs at least one child, so that HeadlessUI doesn't remove this portal root workaround\n    // https://github.com/tailwindlabs/headlessui/blob/main/packages/@headlessui-react/src/components/portal/portal.tsx#L84\n    el.innerHTML = \"<div/>\";\n\n    // Apply our theme styles and add the portal root to the body.\n    el.setAttribute(\"style\", style);\n    document.body.appendChild(el);\n  }, [style]);\n\n  // Overwrite our i18next resources with any provided to ThemeProvider.\n  useEffect(() => {\n    if (locals) {\n      Object.entries(locals).forEach(([lang, namespaces]) => {\n        Object.entries(namespaces).forEach(([namespace, resources]) => {\n          i18next.addResourceBundle(lang, namespace, resources);\n        });\n      });\n    }\n  }, [locals]);\n\n  const contextValue = useMemo(() => {\n    const { iframe, ...tailwindTheme } = theme;\n    return {\n      // Set our context theme to our default theme merged\n      // with any of the provided theme overwrites.\n      // This way consumers of useTheme can get access to\n      // the full true theme being applied.\n      theme: merge({}, DefaultTheme, tailwindTheme),\n      iframeTheme: iframe,\n      ctwThemeRef,\n      locals,\n    };\n  }, [theme, locals, ctwThemeRef]);\n\n  return (\n    <div ref={ctwThemeRef} className=\"ctw-theme ctw-scrollable-pass-through-height\">\n      <ThemeContext.Provider value={contextValue}>{children}</ThemeContext.Provider>\n    </div>\n  );\n}\n","import { ReactNode, useMemo, useState } from \"react\";\nimport { ZapPropsStateContext } from \"./zap-props-state-context\";\n\ninterface ZapTabStateProviderProps {\n  children: ReactNode;\n}\n\nexport function ZapPropsProvider({ children }: ZapTabStateProviderProps) {\n  const [props, setProps] = useState({});\n\n  const value = useMemo(\n    () => ({\n      props,\n      setProps,\n    }),\n    [props, setProps],\n  );\n  return <ZapPropsStateContext.Provider value={value}>{children}</ZapPropsStateContext.Provider>;\n}\n","import { ReactNode, useMemo, useState } from \"react\";\nimport { ZapTabStateContext } from \"./zap-tab-state-context\";\nimport { ZAPTabName } from \"@/components/content/zus-aggregated-profile/zus-aggregated-profile\";\n\ninterface ZapTabStateProviderProps {\n  children: ReactNode;\n}\n\nexport function ZapTabStateProvider({ children }: ZapTabStateProviderProps) {\n  const [selectedZapTabIndex, setSelectedZapTabIndex] = useState(0);\n  const [tabOrder, setTabOrder] = useState<ZAPTabName[]>([]);\n\n  const value = useMemo(\n    () => ({\n      selectedZapTabIndex,\n      setSelectedTab: (tabName: number | ZAPTabName) => {\n        setSelectedZapTabIndex(typeof tabName === \"number\" ? tabName : tabOrder.indexOf(tabName));\n      },\n      tabOrder,\n      setTabOrder,\n    }),\n    [selectedZapTabIndex, setSelectedZapTabIndex, tabOrder, setTabOrder],\n  );\n  return <ZapTabStateContext.Provider value={value}>{children}</ZapTabStateContext.Provider>;\n}\n","import { Worker } from \"@react-pdf-viewer/core\";\nimport { QueryClientProvider } from \"@tanstack/react-query\";\nimport { PropsWithChildren, useEffect, useMemo } from \"react\";\nimport {\n  AuthenticationProvider,\n  AuthenticationProviderProps,\n} from \"./authentication/authentication-provider\";\nimport { CTWStateContext, FeatureFlags } from \"./ctw-context\";\nimport { FeatureFlagProvider } from \"./feature-flag-provider\";\nimport { TelemetryProvider } from \"./telemetry/telemetry-provider\";\nimport { ThemeProvider, ThemeProviderProps } from \"./theme/theme-provider\";\nimport { ToastProvider } from \"./toast-provider\";\nimport { Env } from \"./types\";\nimport { ZapPropsProvider } from \"./zap-props-provider\";\nimport { ZapTabStateProvider } from \"./zap-tab-provider\";\nimport { version } from \"../../../../package.json\";\nimport { OnResourceSaveCallback } from \"@/fhir/action-helper\";\nimport { queryClient } from \"@/utils/request\";\n\nexport type CTWProviderProps = {\n  env: Env;\n  builderId?: string;\n  enableTelemetry?: boolean;\n  ehr?: string;\n  featureFlags?: FeatureFlags;\n  onResourceSave?: OnResourceSaveCallback;\n  resourceSaveHeaders?: Record<string, string>;\n  allowSmallBreakpointCCDAViewer?: boolean;\n} & ThemeProviderProps &\n  AuthenticationProviderProps;\n\ndeclare global {\n  interface Window {\n    CTWComponentLibrary: {\n      version: string;\n    };\n  }\n}\n\n/**\n * CTWProvider is required for Zus components to operate and at least one\n * should exist in the app as an ancestor to any ctw-component-library React\n * component (we recommend CTWProvider be at the root of your project). In\n * addition to providing a client request context, the CTWProvider also allows\n * for theme configuration and opting into telemetry collection if desired.\n */\nexport function CTWProvider({\n  children,\n  env,\n  builderId,\n  enableTelemetry = false,\n  ehr,\n  featureFlags,\n  locals,\n  theme,\n  headers,\n  authToken,\n  authTokenURL,\n  onResourceSave,\n  resourceSaveHeaders,\n  allowSmallBreakpointCCDAViewer = false,\n}: PropsWithChildren<CTWProviderProps>) {\n  useEffect(() => {\n    window.CTWComponentLibrary = {\n      version,\n    };\n  }, []);\n\n  const providerState = useMemo(\n    () => ({\n      env,\n      builderId,\n      featureFlags,\n      onResourceSave,\n      resourceSaveHeaders,\n      headers,\n      allowSmallBreakpointCCDAViewer,\n    }),\n    [\n      env,\n      builderId,\n      featureFlags,\n      onResourceSave,\n      resourceSaveHeaders,\n      headers,\n      allowSmallBreakpointCCDAViewer,\n    ],\n  );\n\n  return (\n    <ThemeProvider theme={theme} locals={locals}>\n      <ToastProvider>\n        <AuthenticationProvider headers={headers} authToken={authToken} authTokenURL={authTokenURL}>\n          <FeatureFlagProvider env={env}>\n            <TelemetryProvider\n              env={env}\n              builderId={builderId}\n              ehr={ehr}\n              enableTelemetry={enableTelemetry}\n            >\n              <CTWStateContext.Provider value={providerState}>\n                <QueryClientProvider client={queryClient}>\n                  <ZapTabStateProvider>\n                    {/* https://react-pdf-viewer.dev/docs/basic-usage/ */}\n                    <Worker workerUrl=\"https://unpkg.com/pdfjs-dist@2.16.105/build/pdf.worker.min.js\">\n                      <ZapPropsProvider>\n                        {children}\n                      </ZapPropsProvider>\n                    </Worker>\n                  </ZapTabStateProvider>\n                </QueryClientProvider>\n              </CTWStateContext.Provider>\n            </TelemetryProvider>\n          </FeatureFlagProvider>\n        </AuthenticationProvider>\n      </ToastProvider>\n    </ThemeProvider>\n  );\n}\n","import { ChangeEvent } from \"react\";\nimport \"./toggle.scss\";\n\nexport type ToggleProps = {\n  name: string;\n  text: string;\n  inputProps?:\n    | {\n        value: string;\n        defaultChecked: boolean;\n      }\n    | {\n        value: string;\n        checked: boolean;\n        disabled: boolean;\n      };\n  onChange?: (event: ChangeEvent<HTMLInputElement>) => void;\n};\n\nexport const Toggle = ({ name, text, onChange, inputProps }: ToggleProps) => (\n  <div className=\"ctw-toggle\">\n    <div className=\"ctw-relative ctw-mr-2 ctw-inline-block ctw-w-10 ctw-select-none ctw-align-middle ctw-transition ctw-duration-200 ctw-ease-in\">\n      <label\n        htmlFor={name}\n        className=\"ctw-relative ctw-block ctw-h-6 ctw-cursor-pointer ctw-overflow-hidden ctw-rounded-full ctw-bg-divider-light\"\n      >\n        <input onChange={onChange} {...inputProps} type=\"checkbox\" name={name} id={name} />\n        <span className=\"ctw-toggle-span\" />\n      </label>\n    </div>\n\n    <label htmlFor={name} className=\"ctw-text-sm ctw-font-medium ctw-text-icon-default\">\n      {text}\n    </label>\n  </div>\n);\n","import { FormEvent } from \"react\";\nimport { Toggle, ToggleProps } from \"./toggle\";\n\nexport type ToggleControlProps = {\n  toggleProps: ToggleProps;\n  onFormChange: (e: FormEvent<HTMLFormElement>) => void;\n};\n\nexport const ToggleControl = ({ toggleProps, onFormChange }: ToggleControlProps) => (\n  <form onChange={onFormChange} className=\"ctw-text-end\">\n    <Toggle {...toggleProps} />\n  </form>\n);\n"],"names":["f","require$$0","g","reactJsxRuntime_production_min","h","m","n","p","q","a","k","b","d","e","l","React","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","exports","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_BLOCK_TYPE","REACT_SERVER_BLOCK_TYPE","REACT_FUNDAMENTAL_TYPE","REACT_DEBUG_TRACING_MODE_TYPE","REACT_LEGACY_HIDDEN_TYPE","symbolFor","MAYBE_ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","maybeIterator","ReactSharedInternals","error","format","_len2","args","_key2","printWarning","level","ReactDebugCurrentFrame","stack","currentlyValidatingElement","name","getComponentName","owner","describeComponentFrame","argsWithFormat","item","enableScopeAPI","isValidElementType","type","BEFORE_SLASH_RE","source","ownerName","sourceInfo","path","fileName","match","pathBeforeSlash","folderName","Resolved","refineResolvedLazyComponent","lazyComponent","getWrappedName","outerType","innerType","wrapperName","functionName","thenable","resolvedThenable","loggedTypeFailures","setCurrentlyValidatingElement","element","checkPropTypes","typeSpecs","values","location","componentName","has","typeSpecName","error$1","err","ex","ReactCurrentOwner","hasOwnProperty","RESERVED_PROPS","specialPropKeyWarningShown","specialPropRefWarningShown","didWarnAboutStringRefs","hasValidRef","config","getter","hasValidKey","warnIfStringRefCannotBeAutoConverted","self","defineKeyPropWarningGetter","props","displayName","warnAboutAccessingKey","defineRefPropWarningGetter","warnAboutAccessingRef","ReactElement","key","ref","jsxDEV","maybeKey","propName","defaultProps","ReactCurrentOwner$1","setCurrentlyValidatingElement$1","propTypesMisspellWarningShown","isValidElement","object","getDeclarationErrorAddendum","getSourceInfoErrorAddendum","lineNumber","ownerHasKeyUseWarning","getCurrentComponentErrorInfo","parentType","info","parentName","validateExplicitKey","currentComponentErrorInfo","childOwner","validateChildKeys","node","i","child","iteratorFn","iterator","step","validatePropTypes","propTypes","_name","validateFragmentProps","fragment","keys","jsxWithValidation","isStaticChildren","validType","typeString","children","jsxWithValidationStatic","jsxWithValidationDynamic","jsx","jsxs","jsxRuntimeModule","require$$1","freeGlobal","global","_freeGlobal","freeSelf","root","_root","Symbol","_Symbol","arrayMap","array","iteratee","index","length","result","_arrayMap","isArray","isArray_1","objectProto","nativeObjectToString","symToStringTag","getRawTag","value","isOwn","tag","unmasked","_getRawTag","objectToString","_objectToString","require$$2","nullTag","undefinedTag","baseGetTag","_baseGetTag","isObjectLike","isObjectLike_1","symbolTag","isSymbol","isSymbol_1","require$$3","INFINITY","symbolProto","symbolToString","baseToString","_baseToString","toString","toString_1","baseSlice","start","end","_baseSlice","castSlice","_castSlice","rsAstralRange","rsComboMarksRange","reComboHalfMarksRange","rsComboSymbolsRange","rsComboRange","rsVarRange","rsZWJ","reHasUnicode","hasUnicode","string","_hasUnicode","asciiToArray","_asciiToArray","rsAstral","rsCombo","rsFitz","rsModifier","rsNonAstral","rsRegional","rsSurrPair","reOptMod","rsOptVar","rsOptJoin","rsSeq","rsSymbol","reUnicode","unicodeToArray","_unicodeToArray","stringToArray","_stringToArray","createCaseFirst","methodName","strSymbols","chr","trailing","_createCaseFirst","upperFirst","upperFirst_1","capitalize","capitalize_1","arrayReduce","accumulator","initAccum","_arrayReduce","basePropertyOf","_basePropertyOf","deburredLetters","deburrLetter","_deburrLetter","reLatin","reComboMark","deburr","deburr_1","reAsciiWord","asciiWords","_asciiWords","reHasUnicodeWord","hasUnicodeWord","_hasUnicodeWord","rsDingbatRange","rsLowerRange","rsMathOpRange","rsNonCharRange","rsPunctuationRange","rsSpaceRange","rsUpperRange","rsBreakRange","rsApos","rsBreak","rsDigits","rsDingbat","rsLower","rsMisc","rsUpper","rsMiscLower","rsMiscUpper","rsOptContrLower","rsOptContrUpper","rsOrdLower","rsOrdUpper","rsEmoji","reUnicodeWord","unicodeWords","_unicodeWords","words","pattern","guard","words_1","reApos","createCompounder","callback","_createCompounder","camelCase","word","camelCase_1","isObject","isObject_1","objectCreate","baseCreate","proto","_baseCreate","baseLodash","_baseLodash","MAX_ARRAY_LENGTH","LazyWrapper","_LazyWrapper","LodashWrapper","chainAll","_LodashWrapper","copyArray","_copyArray","wrapperClone","wrapper","_wrapperClone","require$$4","require$$5","lodash","wrapperLodash","eq","other","eq_1","asyncTag","funcTag","genTag","proxyTag","isFunction","isFunction_1","MAX_SAFE_INTEGER","isLength","isLength_1","isArrayLike","isArrayLike_1","reIsUint","isIndex","_isIndex","isIterateeCall","_isIterateeCall","reWhitespace","trimmedEndIndex","_trimmedEndIndex","reTrimStart","baseTrim","_baseTrim","NAN","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","toNumber","isBinary","toNumber_1","MAX_INTEGER","toFinite","sign","toFinite_1","toInteger","remainder","toInteger_1","nativeCeil","nativeMax","chunk","size","resIndex","chunk_1","listCacheClear","_listCacheClear","assocIndexOf","_assocIndexOf","arrayProto","splice","listCacheDelete","data","lastIndex","_listCacheDelete","listCacheGet","_listCacheGet","listCacheHas","_listCacheHas","listCacheSet","_listCacheSet","ListCache","entries","entry","_ListCache","stackClear","_stackClear","stackDelete","_stackDelete","stackGet","_stackGet","stackHas","_stackHas","coreJsData","_coreJsData","maskSrcKey","uid","isMasked","func","_isMasked","funcProto","funcToString","toSource","_toSource","reRegExpChar","reIsHostCtor","reIsNative","baseIsNative","_baseIsNative","getValue","_getValue","getNative","_getNative","Map","_Map","nativeCreate","_nativeCreate","hashClear","_hashClear","hashDelete","_hashDelete","HASH_UNDEFINED","hashGet","_hashGet","hashHas","_hashHas","hashSet","_hashSet","Hash","_Hash","mapCacheClear","_mapCacheClear","isKeyable","_isKeyable","getMapData","map","_getMapData","mapCacheDelete","_mapCacheDelete","mapCacheGet","_mapCacheGet","mapCacheHas","_mapCacheHas","mapCacheSet","_mapCacheSet","MapCache","_MapCache","LARGE_ARRAY_SIZE","stackSet","pairs","_stackSet","Stack","_Stack","arrayEach","_arrayEach","defineProperty","_defineProperty","baseAssignValue","_baseAssignValue","assignValue","objValue","_assignValue","copyObject","customizer","isNew","newValue","_copyObject","baseTimes","_baseTimes","argsTag","baseIsArguments","_baseIsArguments","propertyIsEnumerable","isArguments","isArguments_1","stubFalse","stubFalse_1","freeExports","freeModule","module","moduleExports","Buffer","nativeIsBuffer","isBuffer","arrayTag","boolTag","dateTag","errorTag","mapTag","numberTag","objectTag","regexpTag","setTag","stringTag","weakMapTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","typedArrayTags","baseIsTypedArray","_baseIsTypedArray","baseUnary","_baseUnary","freeProcess","nodeUtil","types","nodeIsTypedArray","isTypedArray","isTypedArray_1","arrayLikeKeys","inherited","isArr","isArg","isBuff","isType","skipIndexes","_arrayLikeKeys","isPrototype","Ctor","_isPrototype","overArg","transform","arg","_overArg","nativeKeys","_nativeKeys","baseKeys","_baseKeys","keys_1","baseAssign","_baseAssign","nativeKeysIn","_nativeKeysIn","baseKeysIn","isProto","_baseKeysIn","keysIn","keysIn_1","baseAssignIn","_baseAssignIn","allocUnsafe","cloneBuffer","buffer","isDeep","arrayFilter","predicate","_arrayFilter","stubArray","stubArray_1","nativeGetSymbols","getSymbols","symbol","_getSymbols","copySymbols","_copySymbols","arrayPush","offset","_arrayPush","getPrototype","_getPrototype","getSymbolsIn","_getSymbolsIn","copySymbolsIn","_copySymbolsIn","baseGetAllKeys","keysFunc","symbolsFunc","_baseGetAllKeys","getAllKeys","_getAllKeys","getAllKeysIn","_getAllKeysIn","DataView","_DataView","Promise","_Promise","Set","_Set","WeakMap","_WeakMap","require$$6","promiseTag","dataViewCtorString","mapCtorString","promiseCtorString","setCtorString","weakMapCtorString","getTag","ctorString","_getTag","initCloneArray","_initCloneArray","Uint8Array","_Uint8Array","cloneArrayBuffer","arrayBuffer","_cloneArrayBuffer","cloneDataView","dataView","_cloneDataView","reFlags","cloneRegExp","regexp","_cloneRegExp","symbolValueOf","cloneSymbol","_cloneSymbol","cloneTypedArray","typedArray","_cloneTypedArray","initCloneByTag","_initCloneByTag","initCloneObject","_initCloneObject","baseIsMap","_baseIsMap","nodeIsMap","isMap","isMap_1","baseIsSet","_baseIsSet","nodeIsSet","isSet","isSet_1","require$$7","require$$8","require$$9","require$$10","require$$11","require$$12","require$$13","require$$14","require$$15","require$$16","require$$17","require$$18","require$$19","require$$20","require$$21","CLONE_DEEP_FLAG","CLONE_FLAT_FLAG","CLONE_SYMBOLS_FLAG","cloneableTags","baseClone","bitmask","isFlat","isFull","isFunc","stacked","subValue","_baseClone","clone","clone_1","cloneDeep","cloneDeep_1","compact","compact_1","spreadableSymbol","isFlattenable","_isFlattenable","baseFlatten","depth","isStrict","_baseFlatten","concat","concat_1","identity","identity_1","metaMap","_metaMap","baseSetData","_baseSetData","createCtor","thisBinding","_createCtor","WRAP_BIND_FLAG","createBind","thisArg","isBind","fn","_createBind","apply","_apply","composeArgs","partials","holders","isCurried","argsIndex","argsLength","holdersLength","leftIndex","leftLength","rangeLength","isUncurried","_composeArgs","composeArgsRight","holdersIndex","rightIndex","rightLength","_composeArgsRight","countHolders","placeholder","_countHolders","noop","noop_1","getData","_getData","realNames","_realNames","getFuncName","otherFunc","_getFuncName","isLaziable","funcName","_isLaziable","HOT_COUNT","HOT_SPAN","nativeNow","shortOut","count","lastCalled","stamp","remaining","_shortOut","setData","_setData","reWrapDetails","reSplitDetails","getWrapDetails","_getWrapDetails","reWrapComment","insertWrapDetails","details","_insertWrapDetails","constant","constant_1","baseSetToString","_baseSetToString","setToString","_setToString","baseFindIndex","fromIndex","fromRight","_baseFindIndex","baseIsNaN","_baseIsNaN","strictIndexOf","_strictIndexOf","baseIndexOf","_baseIndexOf","arrayIncludes","_arrayIncludes","WRAP_BIND_KEY_FLAG","WRAP_CURRY_FLAG","WRAP_CURRY_RIGHT_FLAG","WRAP_PARTIAL_FLAG","WRAP_PARTIAL_RIGHT_FLAG","WRAP_ARY_FLAG","WRAP_REARG_FLAG","WRAP_FLIP_FLAG","wrapFlags","updateWrapDetails","pair","_updateWrapDetails","setWrapToString","reference","_setWrapToString","WRAP_CURRY_BOUND_FLAG","createRecurry","wrapFunc","argPos","ary","arity","isCurry","newHolders","newHoldersRight","newPartials","newPartialsRight","newData","_createRecurry","getHolder","_getHolder","nativeMin","reorder","indexes","arrLength","oldArray","_reorder","PLACEHOLDER","replaceHolders","_replaceHolders","createHybrid","partialsRight","holdersRight","isAry","isBindKey","isFlip","holdersCount","_createHybrid","createCurry","_createCurry","createPartial","_createPartial","mergeData","srcBitmask","newBitmask","isCommon","isCombo","_mergeData","FUNC_ERROR_TEXT","createWrap","setter","_createWrap","curry","curry_1","now","now_1","debounce","wait","options","lastArgs","lastThis","maxWait","timerId","lastCallTime","lastInvokeTime","leading","maxing","invokeFunc","time","leadingEdge","timerExpired","remainingWait","timeSinceLastCall","timeSinceLastInvoke","timeWaiting","shouldInvoke","trailingEdge","cancel","flush","debounced","isInvoking","debounce_1","reHasRegExpChar","escapeRegExp","escapeRegExp_1","createBaseFor","iterable","_createBaseFor","baseFor","_baseFor","baseForOwn","_baseForOwn","createBaseEach","eachFunc","collection","_createBaseEach","baseEach","_baseEach","setCacheAdd","_setCacheAdd","setCacheHas","_setCacheHas","SetCache","_SetCache","arraySome","_arraySome","cacheHas","cache","_cacheHas","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","equalArrays","equalFunc","isPartial","othLength","arrStacked","othStacked","seen","arrValue","othValue","compared","othIndex","_equalArrays","mapToArray","_mapToArray","setToArray","set","_setToArray","equalByTag","convert","_equalByTag","equalObjects","objProps","objLength","othProps","objStacked","skipCtor","objCtor","othCtor","_equalObjects","baseIsEqualDeep","objIsArr","othIsArr","objTag","othTag","objIsObj","othIsObj","isSameTag","objIsWrapped","othIsWrapped","objUnwrapped","othUnwrapped","_baseIsEqualDeep","baseIsEqual","_baseIsEqual","baseIsMatch","matchData","noCustomizer","srcValue","_baseIsMatch","isStrictComparable","_isStrictComparable","getMatchData","_getMatchData","matchesStrictComparable","_matchesStrictComparable","baseMatches","_baseMatches","reIsDeepProp","reIsPlainProp","isKey","_isKey","memoize","resolver","memoized","memoize_1","MAX_MEMOIZE_SIZE","memoizeCapped","_memoizeCapped","rePropName","reEscapeChar","stringToPath","number","quote","subString","_stringToPath","castPath","_castPath","toKey","_toKey","baseGet","_baseGet","get","defaultValue","get_1","baseHasIn","_baseHasIn","hasPath","hasFunc","_hasPath","hasIn","hasIn_1","baseMatchesProperty","_baseMatchesProperty","baseProperty","_baseProperty","basePropertyDeep","_basePropertyDeep","property","property_1","baseIteratee","_baseIteratee","baseFilter","_baseFilter","filter","filter_1","createFind","findIndexFunc","_createFind","findIndex","findIndex_1","find","find_1","flatten","flatten_1","arrayAggregator","_arrayAggregator","baseAggregator","_baseAggregator","createAggregator","initializer","_createAggregator","groupBy","groupBy_1","arrayIncludesWith","comparator","_arrayIncludesWith","baseIntersection","arrays","includes","caches","maxLength","outer","computed","_baseIntersection","overRest","otherArgs","_overRest","baseRest","_baseRest","isArrayLikeObject","isArrayLikeObject_1","castArrayLikeObject","_castArrayLikeObject","intersection","mapped","intersection_1","last","last_1","intersectionWith","intersectionWith_1","isEmpty","isEmpty_1","isEqual","isEqual_1","nativeIsFinite","isFinite","_isFinite","isString","isString_1","isUndefined","isUndefined_1","keyBy","keyBy_1","baseMap","_baseMap","map_1","mapValues","mapValues_1","assignMergeValue","_assignMergeValue","objectCtorString","isPlainObject","isPlainObject_1","safeGet","_safeGet","toPlainObject","toPlainObject_1","baseMergeDeep","srcIndex","mergeFunc","isTyped","_baseMergeDeep","baseMerge","_baseMerge","createAssigner","assigner","sources","_createAssigner","merge","merge_1","mergeWith","mergeWith_1","negate","negate_1","baseSet","nested","_baseSet","basePickBy","paths","_basePickBy","pickBy","prop","pickBy_1","omitBy","omitBy_1","baseSortBy","comparer","_baseSortBy","compareAscending","valIsDefined","valIsNull","valIsReflexive","valIsSymbol","othIsDefined","othIsNull","othIsReflexive","othIsSymbol","_compareAscending","compareMultiple","orders","objCriteria","othCriteria","ordersLength","order","_compareMultiple","baseOrderBy","iteratees","criteria","_baseOrderBy","orderBy","orderBy_1","partition","partition_1","createRound","precision","_createRound","round","round_1","snakeCase","snakeCase_1","baseSome","_baseSome","some","some_1","sortBy","sortBy_1","startCase","startCase_1","baseSum","current","_baseSum","sum","sum_1","createSet","_createSet","baseUniq","seenIndex","_baseUniq","uniq","uniq_1","uniqBy","uniqBy_1","uniqWith","uniqWith_1","baseValues","_baseValues","values_1","addressParser","addr","_a","displayForAddress","address","isHumanNameArray","isStringArray","nameParser","displayForName","humanName","acc","val","telecomParser","use","system","withUse","displayForTelecom","telecom","addressUseMap","getAddress","parser","addressXml","xpath","contactPointUseMap","contactPointTelecomMap","getTelecom","telecomXml","splitValue","backupSystem","contactPoint","getContactDetails","humanNameUseMap","getHumanName","nameXml","patientParsedName","getId","id","rootValue","extensionValue","getIndexFromEnd","date","rawDate","plusSign","minusSign","signOnThreePlacesLeft","isCorrectValue","char","constructISOString","year","month","day","hour","minute","second","timezoneHour","timezoneMinute","timezoneSign","parseToISOString","timezone","getPeriod","xmlData","low","high","isBefore","replaceInXML","xmlString","toReplace","toReplaceWith","escape","modify","replaceTag","oldTag","newTag","oldTags","newTags","_","fixHtml","fixedHtml","formatDate","isoDate","isGeneralInfoExist","isExtendedGeneralInfoExist","getAuthenticatorData","document","authenticators","authenticator","assignedEntity","assignedPerson","contactDetails","BasicRow","dataChunk","indexKey","chunkSize","_b","newDataChunk","Fragment","singleData","colSpan","TupleRow","tuple","Table","normalEntries","tupleEntries","Authenticator","finalData","getAuthor","authors","author","personName","deviceName","manufacturerModelName","softwareName","representedOrganizationName","authoredOn","__spreadProps","__spreadValues","getAuthorData","authorXmls","getAuthorDataFromHeader","authorXml","assignedAuthor","authorContactDetails","representedOrganization","organizationContactDetails","Author","getConsent","consents","consent","code","status","getAuthorizationData","inFulfillmentOf","getConsentDataFromHeader","Authorization","authorizations","authorization","getCustodianData","representedCustodianOrganization","Custodian","custodian","getDataEntererData","dataEnterer","DataEnterer","confidentialityCodeMap","getDocumentData","effectiveTimeValue","createdOn","version","setId","confidentialityCode","languageCode","Document","getDocumentationOf","serviceEvents","serviceEvent","effectiveTime","period","performers","performer","getDocumentationOfData","serviceEventXmls","documentationOfs","getDocumentationOfDataFromHeader","serviceEventXml","finalPerformers","performerXml","index2","functionCode","DocumentationOf","documentationOf","getEncounter","encompassingEncounter","getEncounterData","encounter","dischargeDisposition","encounterLocation","Encounter","dateTime","getInformantData","informants","informant","relatedEntity","relatedPerson","relationship","Informant","getInformationRecipientData","intendedRecipients","intendedRecipient","informationRecipientName","informationRecipient","ids","receivedOrganizationName","receivedOrganization","InformationRecipient","informationRecipients","getInFulfillmentOf","orderXmls","orderXml","getInFulfillmentOfData","getInFulfillmentOfDataFromHeader","InFulfillmentOf","inFulfillmentOfs","getLegalAuthenticatorData","legalAuthenticator","LegalAuthenticator","withSignedAt","getParticipantData","participants","participant","associatedEntity","associatedPerson","Participant","getBirthPlace","patient","birthPlace","getEthnicity","ethnicGroup","detailedEthnicGroup","getGuardian","patientRole","guardians","guardian","guardianPerson","withRelationship","guardianNames","getGuardianFromHeader","getLanguage","language","preferred","withNewLine","withPreferred","getMaritalStatus","getProviderOrganization","providerOrganization","finalProvider","names","withNames","getRace","race","detailedRace","getReligion","getPatient","patientName","patientIds","administrativeGenderCode","birthTime","parseISO","deceasedTime","deceasedInd","withDeceased","differenceInYears","isValid","dateOfBirth","res","getPatientData","patientRoles","dataFromHeader","getPatientDataFromHeader","patients","valueAsObject","ethnicity","maritalStatus","religion","Patient","DocumentDetails","SearchIcon","svgRef","ForwardRef","SearchIcon$3","ThumbDownIcon","ThumbDownIcon$1","ThumbUpIcon","ThumbUpIcon$1","XIcon","XIcon$1","CTW_MODAL_ID","DOCUMENT_HEADER_ID","TABLE_OF_CONTENT_ID","navigateIntoView","sectionId","modalElement","headerOffset","tocBottom","sectionElement","sectionTop","ZusSVG$1","useIsomorphicLayoutEffect","useLayoutEffect","useEffect","CLASS_PREFIX","defaultBreakpoints","TailwindTheme","EmptyTailwindCSSVars","DefaultTheme","nameCSSVar","mapToCSSVar","colorConfig","properties","colorTitle","colorValueOrObj","hexToRGB","colorName","colorMapping","opacity","r","ThemeContext","createContext","createRef","useTheme","useContext","useResizeObserver","useResizeObserverTemp","useBreakpoints","target","theme","breakpoints","setBreakpoints","useState","updateBreakpoints","useCallback","targetEl","width","breakpointsTmp","useHeaderOffset","elementId","setOffset","updateOffset","newOffset","timeoutId","resizeObserver","Header","sections","overridePatient","containerRef","useRef","tableOfContents","title","cx","TableOfContents","DocumentHeader","onClose","actions","zapContextPatient","usePatient","ZusSVG","CloseDocument","isHidden","setIsHidden","trackInteraction","useAnalytics","handleClick","FontAwesomeIcon","faChevronDown","TableOfContentsItems","Details","betterWithTwoCols","betterWithOneCol","divisor","gridTemplateRows","gridTemplateColumns","AnalyticsContext","DrawerContext","dummyChild","_props","DrawerProvider","isOpen","setIsOpen","drawerProps","setProps","analytics","state","useMemo","useDrawer","context","ModalContext","ModalProvider","modalProps","useModal","PatientContext","AuthenticationContext","useGetAuthToken","CTWStateContext","getZusApiBaseUrl","env","getZusServiceUrl","service","getZapIFrameUrl","getZusProxyApiBaseUrl","VITE_LOCAL_EHR_HOOKS_URL","getZusFhirBaseUrl","getZusFhirWriteBackBaseUrl","getFormsConditionsUrl","getFormsMedicationsUrl","getCTWBaseUrl","getLensBuilderId","RequestError","response","params","__publicField","ReactQueryError","query","SESSION_INACTIVE_TIME_MS","SESSION_TIMESTAMP_KEY","SESSION_USER_ID_KEY","Session","timestampStr","lastActiveTimestamp","userId","isOperationOutcome","mapping","fallbackHolder","push","baseArity","baseAry","cloneArray","createCloner","flatSpread","wrapImmutable","cloner","baseConvert","util","isLib","isObj","defaultHolder","forceCurry","forceFixed","forceRearg","pristine","helpers","assign","each","isError","isWeakMap","rearg","toPath","aryMethodKeys","wrappers","castArray","mixin","nthArg","runInContext","castCap","iterateeRearg","iterateeAry","castCurry","castFixed","castRearg","cloneByPath","convertLib","createConverter","realName","oldOptions","newUtil","newFunc","newOptions","wrap","wrapped","aryKey","otherName","afterRearg","alias","_baseConvert","ary_1","domExcTag","isError_1","isWeakMap_1","iteratee_1","flatRest","_flatRest","rearg_1","toPath_1","_util","convert_1","_falseOptions","parent","_parent","baseUnset","_baseUnset","customOmitClone","_customOmitClone","omit","omit_1","basePick","_basePick","pick","pick_1","createFlow","funcs","prereq","_createFlow","flow","flow_1","pipe","matchesProperty","matchesProperty_1","propEq","set_1","baseIsRegExp","_baseIsRegExp","nodeIsRegExp","isRegExp","isRegExp_1","split","separator","limit","split_1","toLower","toLower_1","formatDateISOToLocal","dateStr","treatMidnightUTCAsDate","utcDate","toZonedTime","matchDatePattern","patterns","parsedDate","parse","formatDateLocalToISO","formatISO","formatStringToDate","dateToISO","formatPhoneNumber","phoneNumber","maybeFormatDateStringToLocal","formatAge","age","unit","compactToTruthyAndZero","ensureJsTimestamp","formatISODateStringToDate","formatPeriod","formatRange","range","unitStr","_c","formatQuantity","quantity","arr","onlyTruthyAndZero","SYSTEM_ACT_CODE","SYSTEM_BASIC_RESOURCE_TYPE","SYSTEM_CONDITION_CATEGORY","SYSTEM_CONDITION_CLINICAL","SYSTEM_CONDITION_VERIFICATION_STATUS","SYSTEM_DIAGNOSTIC_SERVICE_SECTION_ID","SYSTEM_MARITAL_STATUS","SYSTEM_NULL_FLAVOR","SYSTEM_PROVENANCE_ACTIVITY_TYPE","SYSTEM_PROVENANCE_AGENT_TYPE","SYSTEM_RELATIONSHIP","SYSTEM_TASK_STATUS","SYSTEM_CCS","SYSTEM_CCI","SYSTEM_CPT","SYSTEM_CVX","SYSTEM_CMS_HCC","SYSTEM_ICD9","SYSTEM_ICD9_CM","SYSTEM_ICD10","SYSTEM_ICD10_CM","SYSTEM_RXNORM","SYSTEM_LOINC","SYSTEM_NDC","SYSTEM_SNOMED","SYSTEM_SUMMARY","SYSTEM_ZUS_BUILDER_ID","SYSTEM_ZUS_CREATED_AT","SYSTEM_ZUS_LENS","SYSTEM_ZUS_SUMMARY","SYSTEM_ZUS_OWNER","SYSTEM_ZUS_PRACTITIONER_ID","SYSTEM_ZUS_PROFILE_ACTION","SYSTEM_ZUS_THIRD_PARTY","SYSTEM_ZUS_UNIVERSAL_ID","SYSTEM_ZUS_UPI_RECORD_TYPE","SYSTEM_ZUS_USER_TYPE","SYSTEM_ENRICHMENT","LENS_EXTENSION_AGGREGATED_FROM","LENS_EXTENSION_ID","LENS_EXTENSION_MEDICATION_LAST_FILL_DATE","LENS_EXTENSION_MEDICATION_LAST_PRESCRIBED_DATE","LENS_EXTENSION_MEDICATION_QUANTITY","LENS_EXTENSION_MEDICATION_DAYS_SUPPLY","LENS_EXTENSION_MEDICATION_REFILLS","LENS_EXTENSION_MEDICATION_LAST_PRESCRIBER","CTW_EXTENSION_LENS_AGGREGATED_FROM","SYSTEM_ATHENA_PATIENT","isFHIRDomainResource","resource","isFHIRResource","FHIRModel","includedResources","basics","extension","x","basic","t","profileActions","ordered","coding","builderId","ownerTag","_d","splitTag","_e","codeableConceptLabel","concept","favoredSystemDisplay","c","firstWithDisplay","firstWithCode","codeableConceptTextOrDisplay","firstDisplay","findCoding","hasMatchingCode","codes","findCodingWithEnrichment","findAllCodingsWithEnrichment","findCodingWithEnrichmentValueString","valueString","findCodingByOrderOfPreference","preferences","OperationOutcomeIssueModel","issue","OperationOutcomeModel","locationError","isFhirError","fhirErrorResponse","errorStr","APP_TOAST_CONTAINER_ID","APP_TOAST_CONTAINER_DRAWER_ID","notify","body","containerId","toastOptions","content","toast","faCircleCheck","faCircleExclamation","AUTH_BUILDER_ID","AUTH_BUILDER_NAME","AUTH_PRACTITIONER_ID","AUTH_IS_SUPER_ORG","AUTH_EMAIL","AUTH_USER_ID","AUTH_USER_TYPE","getClaims","authToken","jwt_decode","claimsUserType","claimsBuilderId","claimsBuilderName","claimsExp","claimsPractitionerId","claimsAuthEmail","hasUnexpiredToken","hasValidClaimsAuthEmail","sendInvalidTokenNotification","toastId","message","prodDatadogConfig","devDatadogConfig","origin","FLUSH_DEFERRED_TIMEOUT_MS","isLocalDevelopment","isInitialized","listenersHaveBeenAdded","_Telemetry","environment","ehr","allowDataDogLogging","datadogLogs","packageJson","event","isTrusted","htmlElement","upid","accessToken","user","jwtDecode","decodedUser","viewName","overrideMessage","action","metadata","datadogMetricName","eventMetadata","__objRest","metric","additionalTags","__async","_0","_1","_2","tags","eventName","eventProperties","analyticEvent","telemetryKey","explicitTargetName","eventTarget","nextTarget","targetName","Telemetry","withTimerMetric","sendMetric","logOnError","queryClient","QueryClient","QueryCache","CTW_REQUEST_HEADER","xmlTypes","pdfTypes","tiffTypes","webImageTypes","ctwFetch","input","init","headers","newInit","fetchResponse","assertResponseOK","getResponseContent","contentType","errorMsg","getFhirClients","resourceSaveHeaders","customHeaders","fhirClient","Client","writeBackCustomHeaders","fhirWriteBackClient","fixupFHIR","fixupFHIRHelper","v","graphQLToFHIR","graphQLToFHIRHelper","aliasRegEx","isMouseEvent","hasNumber","str","isEmptyValue","isReactNode","MAX_OBJECTS_PER_REQUEST","createGraphqlClient","requestContext","endpoint","GraphQLClient","fqsRequest","client","variables","updatedVariables","errors","fhirData","getFetchFromFqs","url","getResourceNodes","y","getHistoryResources","useCTW","getAuthToken","contextValueRef","getRequestContext","updatedContext","getUsersPractitionerReference","practitionerId","QUERY_KEY_AI_SEARCH","QUERY_KEY_AUTH_TOKEN","QUERY_KEY_BINARY","QUERY_KEY_BUILDER_CONFIG","QUERY_KEY_CARETEAM","QUERY_KEY_ALLERGY_HISTORY","QUERY_KEY_CONDITION_HISTORY","QUERY_KEY_MEDICATION_HISTORY","QUERY_KEY_PATIENT_SUMMARY_CONDITIONS","QUERY_KEY_DATA_INDICATORS","QUERY_KEY_PATIENT_DIAGNOSTIC_REPORTS","QUERY_KEY_PATIENT_SUMMARY_MEDICATIONS","QUERY_KEY_PATIENT","QUERY_KEY_PATIENT_ALLERGIES","QUERY_KEY_PATIENT_BUILDER_MEDICATIONS","QUERY_KEY_BUILDER_CONDITIONS","QUERY_KEY_PATIENT_DOCUMENTS","QUERY_KEY_PATIENT_ENCOUNTERS","QUERY_KEY_PATIENT_EPISODES_OF_CARE","QUERY_KEY_PATIENT_HISTORY_DETAILS","QUERY_KEY_PATIENT_HISTORY_LIST","QUERY_KEY_PATIENT_IMMUNIZATIONS","QUERY_KEY_PATIENT_VITALS","QUERY_KEY_PATIENTS_LIST_ODS","QUERY_KEY_PATIENTS_LIST_FQS","QUERY_KEY_PROVENANCE","QUERY_KEY_PATIENT_MEDICATION_DISPENSE","QUERY_KEY_MATCHED_PATIENTS","QUERY_KEY_BUILDER_PATIENTS_BY_UPID","searchProvenancesFQS","resourceType","targets","targetIds","graphClient","provenanceQueries","gql","provenanceQuery","targetId","ASSEMBLER_CODING","CREATE_CODING","UPDATE_CODING","createProvenance","builderName","versionId","provenance","searchProvenances","models","getBinaryIDFromProvenance","binaryIDReference","entity","sleep","ms","resolve","TIMEOUT_MS","longPollFQS","resourceId","lastUpdated","targetTimestamp","retryCount","currentTimestamp","startTime","__pow","createOrEditFhirResource","updating","resourceModified","OrganizationModel","phone","findReference","contained","found","referenceToId","filterByTags","resources","resourceTag","MaritalStatuses","PatientModel","s","rest","secTag","displayOnset","AllergyModel","manifestations","reaction","manifestation","concatenatedString","note","codings","ALLERGY_CODE_PREFERENCE_ORDER","prev","next","PractitionerModel","firstEntryInName","CCSChapterName","getAddConditionWithDefaults","condition","getClincalAndVerificationStatus","verificationStatus","clinicalStatus","createOrEditCondition","patientID","fhirCondition","_f","ConditionModel","CONDITION_CODE_PREFERENCE_ORDER","getNewCondition","patientId","newCondition","bodySite","category","display","evidence","practitioner","stage","summary","clinicalStatusMap","verificationStatusMap","subjectID","conditionStatuses","outsideConditionStatuses","ZUS_DOCUMENT_SYSTEM_IDS","DocumentModel","binaryID","systemId","organizationName","loincCoding","codeableConcept","LOINC_ANALYTES","ObservationModel","filteredCoding","nonAcceptedValues","interpretation","trendDataMap","analytes","analyte","diagnosticFlagged","a1cDisplay","trendFlagged","DiagnosticReportModel","model","label","standardizedLoincDisplay","inferStartDateFromResults","inferEndDateFromResults","tResult","o","ext","filterOutFalsy","results","obs","min","medStatusDisplays","getMedicationCodeableConcept","medication","medicationResource","getIdentifyingRxNormCode","getIdentifyingRxNormCoding","rxNorm","getMedicationDisplayName","medCodeableConcept","getPerformingOrganization","patientStatus","MedicationDispenseModel","MedicationAdministrationModel","text","dose","route","MedicationRequestModel","organization","city","postalCode","line","cityStatePostal","MedicationStatementModel","dateAsserted","informationSource","family","given","lastPrescribedDate","lastFillDate","dates","maxDate","max","MedicationModel","_i","_h","_g","EmptyNotes","dismissFilter","listView","faEye","faEyeSlash","THIRD_PARTY_SOURCE_SYSTEM","isFromThirdParties","doc","thirdParties","thirdPartyTag","isRenderableBinary","ZUS_CREATION_DATE_URL","RAINBOW_CUTOVER_DATE","zusCreationDate","createExtension","isViewablePreRainbow","creationDate","filterHighestLevelDocs","docs","highestLevelDocs","documentGroups","binaryId","isSectionDocument","isPdfOrImage","docRef","isEmptyClinicalNote","noteText","emptyNoteStr","applyDocumentFilters","isHighestLevelDoc","docModel","documentModels","valuesToDedupeOn","documentsFilter","isNullFlavorSystem","EncounterModel","documentPool","locations","reasons","uniqueLocations","classDisplay","classSystem","classCode","firstTypeCoding","typeText","typeCode","isNullFlavor","mappings","codeDisplay","DISCHARGE_NARRATIVE_URL","DISCHARGE_DISP_URL","DISCHARGE_LOC_URL","ADMIT_LOC_URL","findViaExtensionByURL","EpisodeOfCareModel","classExt","dischargeExt","dischargeLoc","admitLoc","editPatient","fhirPatient","TelemetryContext","useTelemetry","useQueryWithCTW","queryKey","enabled","staleTime","useQuery","useTimerQueryWithCTW","isBundle","getResources","bundle","bundleToResourceMap","MAX_COUNT","DEBUG_ODS_FETCH_ALL_PAGES","DEBUG_ODS_FETCH_ALL_PAGES_CUTOFF","excludeTagsinPatientRecordSearch","UPI_TAGS","CONDITIONS_LENS_TAGS","SUMMARY_TAGS","MEDICATION_LENS_TAGS","THIRD_PARTY_TAGS","FIRST_PARTY_TAG_SUPPORTED_RESOURCES","searchAllRecords","searchParams","patientUPID","_count","patientSearchParams","fetchAllPages","searchBuilderRecords","nonBuilderTags","firstPartyParams","mergeParams","records","filterSearchReturnByBuilderId","params2","v2","identifier","searchReturn","matchOwnerBuilderId","includedOwnerBuilderId","record","currentBundle","link","fragmentBasic","fragmentCoding","fragmentEncounterReference","fragmentPractitioner","fragmentPatient","fragmentReference","fragmentObservation","fragmentOrganization","patientsForUPIDQuery","patientsForBuilderQuery","fqsRequestContext","ctwContext","searchRecordsFQS","resourceString","baseUrl","urlParams","searchBuilderRecordsFQS","fetchResource","applySorts","sorts","dateIteratee","column","sortEntry","dir","isDate","sort","getValueFn","sortByDate","aDate","bDate","dateA","dateB","useBuilderPatientsByUPID","useTimingQueryWithPatient","getPatientsForUPIDFQS","useMatchedPatients","getBuilderFhirPatientByExternalIdentifier","systemURL","sortedPatients","patientModel","getPatientByID","usePatientsListFQS","pageSize","cursor","getBuilderPatientsListFQS","getBuilderPatientListWithSearch","paginationOptions","pageOffset","searchValue","PATIENT_STALE_TIME","PatientProvider","patientResourceID","onPatientSave","onResourceSave","providerState","usePatientContext","usePatientPromise","patientIdUsed","useHandlePatientSave","useQueryWithPatient","patientResponse","telemetry","Section","humanReadable","cleanedHtml","DOMPurify","SectionContainer","Interweave","tableOfContentsId","overrideDefaultHidden","documentHeaderOffset","wrappedInDiv","parseNestedElement","childNodes","itemChildNode","documents","parseElement","parseCaptionElement","parseContentElement","parseListElement","parseParagraphElement","parseTableElement","parseTextNode","tableElementXml","theadElementXml","tbodyElementXml","tableContent","parsedTheadElement","parseTheadElement","parsedTbodyElement","parseTbodyElement","parseTdElement","tdElementXml","nestedData","tdElementText","textNodeXml","paragraphElementXml","paragraphText","listElelementXml","listType","parsedListItems","listItem","textData","contentElementXml","contentText","captionElementXml","captionText","trElementXml","parsedTrElement","parseTrElement","trElementsXml","parsedTrElements","parseThElement","thElementXml","thElementText","thElements","thElement","tdElements","tdElement","getNarrativeForSection","textElementsToParse","parsedTextElements","Wrapper","className","StackedWrapper","htmlProps","classNames","Heading","Title","Body","titleChildren","showTitleContainer","ErrorBoundary","Component","errorInfo","CTWBox.Wrapper","CTWBox.Body","withErrorBoundary","component","trackView","Wrapped","forwardRef","createElement","sectionToUseSectionNarrative","CcdaViewerComponent","texts","section","textContent","sectionNarrative","CcdaViewer","formatString","getTitle","getHeaderData","labelTypeData","arrayOfData","filteredData","tiffToPNG","page","imageFileDirectory","UTIF","imageFileDirectoryPage","rgba","canvas","ctx","img","ChevronLeftIcon","ChevronLeftIcon$1","ChevronRightIcon","ChevronRightIcon$1","ExclamationCircleIcon","ExclamationCircleIcon$1","ExclamationIcon","ExclamationIcon$1","FireIcon","FireIcon$1","LockClosedIcon","LockClosedIcon$1","SearchIcon$1","ErrorAlert","header","CautionAlert","FileIcon","ImageIcon","PdfIcon","IMAGE_RE","PDF_RE","ContentTypeIcon","Spinner","Loading","iconClass","getUnleashProxyForEnv","getUnleashContext","zusToken","decoded","hostname","FeatureFlagContext","FeatureFlagProvider","unleashClient","UnleashClient","FlagProvider","FeatureFlagProviderComponent","updateContext","useUnleashContext","authTokenPromise","setAuthToken","unleashClientStarted","setUnleashClientStarted","unleashClientFailed","setUnleashClientFailed","useFeatureToggle","useUnleashClient","useFlagsStatus","isSpecificContentType","extensions","BinaryField","blob","showPrintBtn","showNewCCDAViewer","setArrayBuffer","ccdaDoc","PreviewTiffImg","PreviewPdf","xmlDocument","DOMParser","downloadAndPrintButtons","DownloadAndPrintButtons","OriginalCCDAViewer","CCDAViewerOriginal","fileUrl","setFileUrl","fileTitle","setFileTitle","downloadDocument","fileType","faPrint","dataUrl","description","Viewer","downloadBlob","tempLink","CCDAModalBase","base64toBlob","bytes","out","getBinaryId","provenances","blobToBase64","reader","reject","base64String","binaryString","getBinaryDocumentReq","based64binary","decodedData","getBinaryDocument","ViewDocument","rawBinary","setRawBinary","isLoading","setIsLoading","load","BinaryContent","OldBinaryContent","contentToPrint","handlePrint","useReactToPrint","downloadButton","DownloadButtons","allergyFilter","allergyQuery","subjectFragment","fragmentCondition","conditionsQuery","useHistory","getHistoryEntry","getFiltersFQS","clientSideFiltersFQS","fetchResourcesFQS","dedupeHistory","enrichedFirst","getResourceFQSQuery","filteredResources","filterLensAndSummary","constructor","useAllergiesHistory","allergy","allergies","tokens","modelTokens","matchingCodeDisplay","token","detailData","defaultAllergySort","allergySortOptions","MIN_SOURCE_COLUMNS_IN_NOTE_TO_TRANSPOSE","MAX_DEPTH_FIND_TABLE_TO_TRANSPOSE","recursivelyTransposeTables","curDepth","transposeTable","el","newChildren","newNode","tbl","theads","thead","tbodies","tbody","headerRows","dataRows","newRows","dataRow","rowIdx","newDivs","accRow","dataCell","cellIdx","headerRow","DetailsCard","hideEmpty","documentButton","transposedValues","setTransposedValues","newlyTransposedValues","detail","idx","valueWithTransposedTables","Modal","onAfterClosed","closeOnEscapeOrBackdrop","Transition","Dialog","useCCDAModal","openModal","CCDAModal","CCDAModalOld","useDownloadBinary","isDownloading","setIsDownloading","setError","filename","binary","MAX_CCDA_VIEWER_WIDTH","ResponsiveSourceDocumentLink","documentTitle","forceInModel","telemetryTarget","showIcon","openCCDAModal","allowSmallBreakpointCCDAViewer","featureFlags","downloadBinaryById","setWidth","isDownloadBtn","downloadText","showOpenInNewTab","faExternalLinkAlt","HistoryEntry","subtitle","resourceTypeTitle","isDetailShown","setIsDetailShown","DetailSummary","hasDocument","faFileLines","faChevronRight","DEFAULT_HISTORY_PAGE_LIMIT","History","getHistory","history","showAll","setShowAll","sortedEntries","displayedEntries","recordProfileAction","existingBasic","profileAction","toggleDismiss","toggleRead","useToggleDismiss","useToggleRead","DropdownMenuSimple","items","onItemSelect","buttonClassName","side","align","isMenuOpen","setIsMenuOpen","Menu","RadixDropdownMenu","menuItem","useRequestContext","setRequestContext","isMounted","useUserBuilderId","userBuilderId","setUserBuilderId","__shared__","__shared__1","ToastContext","ToastProvider","ToastContainer","Zoom","transitionClasses","Drawer","onOpen","onAfterOpen","showCloseFooter","disableCloseOnBlur","DrawerContent","DrawerFooter","DrawerCloseButton","DrawerBody","useFHIRDrawer","openDrawer","FHIRDrawer","ViewFHIR","ReactJason","github","consoleLogger","Logger","concreteLogger","_len","_key","_len3","_key3","_len4","_key4","lvl","prefix","debugOnly","moduleName","baseLogger","EventEmitter","events","listener","observer","defer","rej","promise","makeString","copy","getLastOfPath","Empty","cleanKey","canNotTraverseDeeper","setPath","obj","pushPath","getPath","getPathWithDefaults","defaultData","deepExtend","overwrite","regexEscape","_entityMap","chars","looksLikeObjectPath","nsSeparator","keySeparator","possibleChars","matched","ki","deepFind","j","mix","joinedPath","getCleanedCode","ResourceStore","ns","lng","ignoreJSONStructure","deep","pack","postProcessor","processors","translator","processor","checkedLoadedFor","Translator","services","resolved","namespaces","wouldCheckForNsInKey","seemsNaturalLanguage","parts","lastKey","returnDetails","namespace","appendNamespaceToCIMode","resUsedKey","resExactUsedKey","resType","noObject","joinArrays","handleAsObjectInI18nFormat","resTypeIsArray","newKeyToUse","deepKey","usedDefault","usedKey","needsPluralHandling","hasDefaultValue","defaultValueSuffix","defaultValueSuffixOrdinalFallback","resForMissing","updateMissing","fk","lngs","fallbackLngs","send","specificDefaultValue","defaultForMissing","suffix","_this","skipOnVariables","nestBef","nb","na","nestAft","postProcess","postProcessorNames","exactUsedKey","usedLng","usedNS","extracted","needsZeroSuffixLookup","needsContextHandling","finalKeys","pluralSuffix","zeroSuffix","ordinalPrefix","contextKey","possibleKey","optionsKeys","useOptionsReplaceForData","option","LanguageUtil","specialCases","part","cleanedLng","lngOnly","supportedLng","fallbacks","fallbackCode","fallbackCodes","addCode","fc","sets","_rulesPluralsTypes","nonIntlVersions","intlVersions","suffixesOrder","createRules","rules","PluralResolver","languageUtils","rule","pluralCategory1","pluralCategory2","pluralCategory","returnSuffix","deepFindWithDefaults","Interpolator","iOpts","regexpStr","regexpUnescapeStr","nestingRegexpStr","replaces","regexSafe","handleFormat","missingInterpolationHandler","todo","matchedVar","temp","safeValue","clonedOptions","handleHasOptions","inheritedOptions","sep","optionsString","matchedSingleQuotes","matchedDoubleQuotes","formatters","doReduce","elem","parseFormatStr","formatStr","formatName","formatOptions","optStr","opt","createCachedFormatter","formatter","Formatter","mem","formatted","valOptions","removePending","Connector","backend","store","languages","toLoad","pending","toLoadLanguages","toLoadNamespaces","hasAllNamespaces","loaded","loadedKeys","fcName","tried","fallbackValue","isUpdate","clb","opts","ret","transformOptions","bindMemberFunctions","inst","I18n","defOpts","createClassOnDemand","ClassOrObject","lu","deferred","finish","usedCallback","append","li","lngInLngs","_this2","setLngProps","done","setLng","keyPrefix","_this3","fixedT","resultKey","fallbackLng","lastLng","loadNotPending","loadState","preResult","preloaded","newLngs","rtlLngs","forkResourceStore","mergedOptions","instance","warn","alreadyWarned","warnOnce","loadedClb","i18n","cb","initialized","loadNamespaces","loadLanguages","oldI18nextHasLoadedNamespace","hasLoadedNamespace","i18nInstance","matchHtmlEntity","htmlEntities","unescapeHtmlEntity","unescape","defaultOptions","setDefaults","getDefaults","setI18n","getI18n","initReactI18next","I18nContext","ReportNamespaces","usePrevious","ignore","useTranslation","i18nFromProps","i18nFromContext","defaultNSFromContext","notReadyT","optsOrDefaultValue","retNotReady","i18nOptions","useSuspense","ready","getT","setT","joinedNS","previousJoinedNS","bindI18n","bindI18nStore","boundReset","isInitial","useBaseTranslations","useAdditionalResourceActions","rowActions","enableDismissAndReadActions","isInFooter","selectedAction","setSelectedAction","dismissAndReadActions","useDismissAndReadActions","onSuccess","extraActions","combinedActions","selectedOption","faChevronUp","testId","onClick","disabled","render","isToggleDismissLoading","isToggleReadLoading","archiveLabel","readLabel","disableReadButton","TableColGroup","columns","TableHead","TableDataCell","TableFullLengthRow","LoadingTable","TableRows","emptyMessage","handleRowClick","canClickRow","RowActions","getRowClassName","DEFAULT_PAGE_SIZE","ExpandList","total","changeCount","allShown","hasPages","showTableHead","hidePagination","tableRef","scrollContainerRef","showLeftShadow","setShowLeftShadow","showRightShadow","setShowRightShadow","setCount","updateShadows","container","table","rightSide","hasData","ResourceTable","onRowClick","shouldShowTableHead","RowActionsWithAdditions","onRowClickWithRead","usePatientError","NoAuthIcon","AuthError","PatientResourceTable","authError","notFoundError","emptyMessage2","isLoading2","useCtwThemeRef","useResourceDetailsDrawer","trackingMetadata","ResourceDetailsDrawer","getSourceDocument","subHeader","renderChild","ctwThemeRef","setBinaryId","MenuItem","icon","DropdownMenuAction","pinnedActions","RenderCorrectFieldType","inputType","faCheck","ViewButton","defaultView","onChange","defaultViewOption","selected","setSelected","displayFilterItem","filterChangeEvent","filters","activeFilterKeys","activeFilterValues","filterChangeEventToValuesRecord","filterState","FilterBarCheckboxPill","filterValues","onRemove","selectedItems","faTrash","ListBox","useBasicStyles","btnClassName","optionsClassName","defaultIndex","selectedIndex","selectedTabIndex","setSelectedTabIndex","selectedItem","Listbox","renderDisplay","active","builtInButton","removeButton","FilterBarSelectPill","FilterBarTagPill","faX","FilterBarPill","updateSelectedFilterValues","handleRemove","INTERNAL_KEYS","removeInternalKeys","FilterBar","defaultFilters","recentlyAdded","setRecentlyAdded","clearAllFilters","resetAllFilters","initialState","toggleFilter","remove","updatedKeys","updateSelectedFilter","valueKey","isSelected","activeValues","toFilterMenuItem","isActive","activeFilters","inactiveFilters","activeFiltersWithToggle","aboveDivider","belowDivider","faRefresh","maybeDivider","menuItems","_index","faPlus","SortButton","defaultSort","ResourceTableActions","filterOptions","sortOptions","viewOptions","Badge","color","noFlex","colorClasses","sizeClasses","Tooltip","open","defaultOpen","onOpenChange","TooltipPrimitive","ResourceTitleColumn","subTitle","renderIcon","RenderOwnedByBuilderIcon","ownedByBuilder","RenderInfoBadge","infoBadge","infoBadgeClassName","RenderDocBadge","toolTipText","faFilePdf","faFileImage","patientAllergiesColumns","RefreshIcon","phoneNumberRegex","zipCodeRegex","getStateEnum","requiredError","z","stateCode","getRequestData","includePatientDemographicsForm","_j","_k","_m","_l","_n","_o","requestHistorySchema","savePatientAndRequestHistorySchema","SaveButton","submitting","getFormResponseErrors","requestErrors","responseIsSuccess","parseParams","schema","shape","ZodObject","ZodEffects","parentProp","def","processDef","parsedValue","ZodString","ZodLiteral","ZodNumber","num","ZodDate","ZodBoolean","ZodNativeEnum","ZodEnum","ZodOptional","ZodDefault","ZodArray","parsedJson","ZodUnknown","isIterable","getParamsInternal","getFormData","getOptions","zodField","useFormInputProps","zodThing","getInputProps","minLength","inputProps","DrawerForm","errorHeader","isSubmitting","setIsSubmitting","setErrors","reset","onFormSubmit","form","inputs","inputErrors","formResult","formResponseErrors","FormField","lines","readonly","hidden","getFieldComponent","FormFieldLabel","required","DrawerFormWithFields","drawerFormProps","FormFieldEntries","field","FormFieldEntry","recordList","fieldErrors","schedulePatientHistory","resultData","endpointUrl","errorMessage","PatientHistoryRequestDrawer","setClinicalHistoryExists","onScheduleHistory","patientHistoryResponse","usePatientHistory","usePatientHistoryDetails","getBuilderRefreshHistoryMessages","excludeFutureJobs","paramsObj","getPatientHistoryDetails","requests","job","targetDate","useIsFetchingHistory","isFetching","setIsFetching","isPolling","setIsPolling","poll","pollPatientHistory","isDone","provider","RequestRecordsButton","displayText","openHistoryRequestDrawer","EmptyPatientTable","patientHistory","showRequestRecordsFormToggle","isTestPatient","latestInProgress","latestCompleted","nextScheduledAt","requestMade","EmptyTableFetchingHistory","EmptyTableNoneFound","resourceName","hasZeroFilteredRecords","faInbox","errorText","subText","faMagnifyingGlass","AnalyticsProvider","contextValue","applyAllergyFilters","allergyModel","sortedByDate","builderOwnedFirst","usePatientAllergies","getAllergyIntoleranceFromFQS","getAllergyIntolerancesById","filterHidden","filterItems","showHidden","applyFilters","filterFuncs","filterFunc","filterItem","targetFilter","uniqueValues","saveToLocalStorage","cacheKey","getDefaultsFromLocalStorage","defaults","cachedDefaults","useFilteredSortedData","filterPredicates","originalDefaultFilters","originalDefaultSort","originalDefaultView","viewOption","setViewOption","setFilters","sortOption","setSortOption","setViewOptionCached","view","setFiltersCached","filters2","verifyFilter","setSortOptionCached","fixupFilters","filteredAndSortedData","missingPredicateMap","allergyHistory","PatientAllergiesComponent","patientAllergiesQuery","setSort","openDetails","allergyData","PatientAllergies","UnreadNotificationIcon","UnreadNotification","UnreadAllergiesNotification","patientCareTeamColumns","careTeam","careTeamSortOptions","defaultCareTeamSort","dateFilter","days","allowNullDates","datePredicate","differenceInDays","getDateRangeView","CareTeamModel","CareTeamPractitionerModel","careTeamsQuery","usePatientCareTeamMembers","getCareTeamMembersFromFQS","nodes","getFilteredCareTeamMembers","careTeams","careteam","careTeamMembers","filteredCareTeamMembers","ct","sortedCareTeamPractitionerModels","PatientCareTeam","patientCareTeamQuery","allTime","careTeamData","careTeamPractitioner","ConditionHeader","ComboboxField","defaultSearchTerm","onSearchChange","enableSearchIcon","onCustomSelectChange","renderCustomOption","searchTerm","setSearchTerm","inputValue","setInputValue","inputState","inputValueParsed","debouncedSearchInputChange","newSearchTerm","onSelectChange","Combobox","ComboboxOptions","ComboboxOption","getAutoCompleteConditions","contextBuilderId","ConditionsAutoComplete","defaultCoding","setOptions","handleSearchChange","conditions","getAddConditionData","i18next","sharedFields","getEditingPatientConditionData","conditionSchema","conditionRefinement","Zod","conditionEditSchema","refinementCtx","conditionAddSchema","ModalConfirmDelete","onDelete","alert","setAlert","isDeleting","setIsDeleting","onConfirm","filterResourcesByBuilderId","usePatientBuilderConditions","fetchPatientBuilderConditionsFQS","usePatientSummaryConditions","fetchPatientSummaryConditionsFQS","usePatientConditionsOutside","setConditions","builderConditionsQuery","summaryConditionsQuery","builderConditions","outsideConditions","filterOutsideConditions","filterUndesirableConditions","outdatedThreshold","subYears","isAfter","usePatientConditionsAll","summaries","associateSummaryWithBuilderConditions","summaryConditions","builderConditionsById","hasMatch","builderCondition","setupConditionModelsWithFQS","conditionResources","filterAndSort","deleteCondition","clonedResource","outsideCondition","otherRecordedDate","patientRecordedDate","isMatch","isEnteredInError","isOlder","hasSameStatus","fetchConditionsByIdFQS","useAddConditionForm","referenceCondition","useEditConditionForm","useConfirmDeleteCondition","fixedColumns","conditionsColumnGroupedClassNames","patientConditionsColumnsGrouped","faInfoCircle","patientConditionsColumns","onsetText","patientConditionsAllColumns","NotesList","notes","useConditionHistory","CodingList","conditionHistory","useConditionDetailsDrawer","conditionFilters","includeDismiss","showAllStatuses","onlyShowOptionsForStatus","statusesToShow","faClipboardCheck","faClipboardList","faClock","scores","aScore","bScore","lastUpdatedMostRecentConditionSort","nameAzConditionSort","conditionSortOptions","groupedConditionSortOptions","statusFilter","statuses","statusView","PatientConditionsBase","outside","openDetailsDrawer","empty","PatientConditionsComponent","readOnly","showAddConditionForm","useRowActions","PatientConditions","showEditConditionForm","confirmDelete","OVERVIEW_CARD_MIN_WIDTH","OVERVIEW_CARD_MIN_WIDTH_CLASS_NAME","OverviewCard","footerIcon","footerOnClick","footerText","hideFooter","noShadow","tooltipText","titleClassName","titleSize","OverviewCardHeader","OverviewCardBodyMessage","OverviewCardBody","OverviewCardFooter","faAngleRight","ResourceOverviewCard","onSeeAllResources","trackingName","rowClassName","overviewCardProps","isNoFooter","useGroupedBy","groupedRecords","groupKey","group","sortedKeys","ResourceTableGrouped","columnHeaders","resourceTableProps","useConditionRowActions","PatientConditionsAllComponent","onlyAllowAddOutsideConditions","PatientConditionsAll","PatientConditionsAllGroupedComponent","PatientConditionsAllGroupedFeatureRelease","hasConditionsGrouped","PatientConditionsAllGrouped","PatientHistoryDetail","tooltipElement","isPropsWithIcon","tooltip","iconElement","cloneElement","completedProviderStatus","failedProviderStatus","PatientHistoryRequestModel","historyInfo","providers","usePatientHistoryStatus","hasJob","jobStatus","PatientHistoryLastCompleted","lastCompletedDate","derivedStatus","faWarning","PatientHistoryWithAction","hideRequestRecords","latestInProgressText","showLastCompleted","PatientConditionsOutsideComponent","patientHistoryQuery","hasNoOutsideDataAndHasNeverRequestedPatientHistory","PatientConditionsOutside","PatientConditionsOutsideBadge","ResourceOverviewCardGrouped","titleKey","ZapPropsStateContext","PatientConditionOverview","filteredSortedData","noData","useFeatureVariant","variant","processVariantPayload","payloadSchema","DISMISSED_ALERTS_KEY","THEME_TYPES","faTriangleExclamation","faCircleInfo","PAYLOAD_SCHEMA","AlertFeatureFlag","featureFlag","dismissed","setDismissed","featureVariant","payload","dismissedAlerts","getDismissedAlerts","dismiss","faXmark","PatientHeader","collapse","ZapTabStateContext","RenderIf","ZAPTabGroupComponent","forceHorizontalTabs","topRightContent","topRightContentRef","topLeftContentRef","moreMenuRef","tabOverflowCutoff","setTabOverflowCutoff","selectedZapTabIndex","setSelectedTab","tabOrder","shown","setShown","moreWidth","tabs","tab","onClickBlur","handleOnChange","showTopRightContent","shownContent","Tab","ZAPTabGroup","UnreadConditionsNotification","BetaLabel","bpSystolicCodes","bpDiastolicCodes","heartRateCodes","tempCodes","respiratoryRateCodes","o2Codes","heightCodes","weightCodes","bmiCodes","headCircumferenceCodes","lmpCodes","painCodes","vitalLoincCodes","resourceNameMapping","generateDataIndicatorQuery","zapTabNames","tabName","tabNames","filterName","generateQueryForPatientMatching","generateQueryForGenericResource","useDataIndicators","getDataIndicators","vitalCodes","loincCode","dataIndicatorQuery","DisplayCorrectTabLabel","isBeta","useHasDataRecordsByResource","finalResources","zapTabName","handleResourceType","patientDiagnosticReportsColumns","diagnostic","faArrowTrendUp","diagnosticReportFilter","diagnosticReportSortOptions","defaultDiagnosticReportSort","BubbleIcon","ObservationTrends","isTrendsShown","setIsTrendsShown","openDiagnosticReportDetails","useObservationsDetailsDrawer","trend","faArrowRight","ObservationsColumns","ObservationsTable","diagnosticReportData","diagnosticReport","ObservationDetailsComponent","observationEntries","setObservationsEntries","ObservationDetails","ObservationsDrawer","ResourceActions","createTrendDataMap","observations","trendData","observationsProperties","getDiagnosticReportQuery","includeObservations","usePatientDiagnosticReports","getDiagnosticReports","usePatientDiagnosticReportsWithTrendData","diagnosticReportsQuery","diagnosticReportsWithTrends","setDiagnosticReportsWithTrends","diagnosticReports","dr","uniqueDiagnosticReports","fetchDiagnosticReportsFromFQS","fetchDiagnosticReportsFromFQSById","PatientDiagnosticReportsComponent","PatientDiagnosticReports","documentsQuery","usePatientTopLevelDocuments","usePatientDocuments","filteredDocuments","getDocumentsFromFQS","getDocumentsByIdFromFQS","noteTypeValues","encounterFilterPredicates","encounterTypePredicate","noteTypePredicate","encounterFilters","encounters","availableNoteTypeValues","hasOtherEncounterNoteTypes","dedupeAndMergeEncounters","dupeGroups","mergeEncounters","dedupedEncounters","encs","aVal","bVal","mergedEncounter","sortedEncResources","enc","merged","curr","parsedValues","parsedAllValues","hasValueMatch","hasOtherMatch","fragmentCodeableConcept","fragmentEncounter","encountersQuery","getEncountersFromFQS","usePatientEncounters","usePatientEncountersWithClinicalNotes","encounterQuery","encountersWithClinicalNotes","setEncountersWithClinicalNotes","quantityLabel","ImmunizationModel","cvxCoding","organizationDisplay","immunizationsQuery","usePatientImmunizations","getImmunizationFromFQS","getFilteredImmunizations","immunizations","immunization","medicationAdministrationQuery","medicationDispenseQuery","medicationRequestQuery","medicationStatementQuery","getBuilderMedicationsFQS","searchFilters","medStatements","applySearchFiltersToFQSResponse","getMedicationStatementsForPatientByIdFQS","resourceIds","getMedicationAdministrationsForPatientByIdFQS","getMedicationDispensesForPatientByIdFQS","getMedicationRequestsForPatientByIdFQS","medicationStatements","removeMedsWithNoRxNorm","medications","getSummaryMedicationsFQS","getMedicationStatementsByIdFQS","medicationStatementIds","filterMedicationsWithNoRxNorms","resourceMap","splitMedications","summarizedMedications","builderOwnedMedications","otherProviderMedications","builderMed","summarizedMed","builderMedResource","LENS_MEDICATION_EXTENSIONS","medHistory","useMedicationHistory","getMedicationHistoryFQS","useLastPrescriber","lastPrescriber","setLastPrescriber","historyQuery","prescriber","fpSortBy","mr","fpLast","aggregatedFromReferences","groups","medicationStatementResponse","medicationAdministrationResponse","medicationRequestResponse","medicationDispenseResponse","medicationResources","fpCompact","usePatientBuilderMedications","usePatientSummaryMedications","useQueryAllPatientMedications","expandedBuilderMedications","setExpandedBuilderMedications","setOtherProviderMedications","allMedications","setAllMedications","summaryMedicationsQuery","builderMedicationsQuery","builderMedications","summaryMedications","medi","agg","splitData","numRecordsToLookbackForUnread","UnreadRecordsNotification","DEFAULT_ZAP_TABS","useUnreadRecordsByResource","isUnread","useUnreadZAPTabsCount","hasUnread","allergiesQuery","medicationsQuery","ZAP_TAB_NAMES","UnreadDocumentsNotification","SimpleMoreList","displayItems","patientEncounterColumns","diagnoses","NotesEntry","isDetailShownOnOpen","NoteSummary","getNoteDisplay","cleanNote","Notes","documentIdToStartOpen","DATE_FORMATS","parseWithoutFormat","retval","dateFormatIdx","dateFormat","usePatientEncounterDetailsDrawer","parsedStartDate","parsedEndDate","encounterData","defaultEncounterSort","encounterSortOptions","PatientEncountersComponent","openEncounterDetails","PatientEncounters","UnreadEncountersNotification","UnreadImmunizationsNotification","medicationFilters","includeDismissed","prescriberNames","faUser","patientMedicationColumns","patientMedicationsAllColumns","med","useMedicationHistoryEntries","medHistoryQuery","createMedicationDetailsCard","createMedicationStatementCard","createMedicationRequestCard","createMedicationDispenseCard","createMedicationAdminCard","medStatement","numberOfRepeatsAllowed","initialFill","medDispense","quantityDisplay","supplied","performerDetails","medAdmin","entryFromArray","medicationHistory","useMedicationDetailsDrawer","LastPrescriber","medicationSortOptions","defaultMedicationSort","defaultMedicationSortOverview","PatientMedicationsBase","defaultView2","views","onOpenHistoryDrawer","selectedFilters","past","medicationViews","defaultMedicationView","PatientMedicationsComponent","PatientMedications","getAutoCompleteMedications","MedicationsAutoComplete","getMedicationFormData","medicationStatementSchema","QUERY_KEYS","createMedicationStatement","fhirMedicationStatement","resourceModel","useAddMedicationForm","AddNewMedDrawer","patientSubjectRef","medStatementModelForFormPopulation","createMedData","PatientMedicationsAllComponent","onAddToRecord","past6Months","useMedicationRowActions","PatientMedicationsAll","showAddMedicationForm","PatientMedicationsOutsideComponent","PatientMedicationsOutside","toggleArchive","PatientMedicationsOutsideBadge","UnreadMedicationsNotification","ZusInformationCard","faArrowUpRightFromSquare","hasA1CCode","A1CCodes","containsText","cleanupA1CDisplay","getOverviewFilters","useA1CCodes","PatientDiagnosticReportsOverview","setA1CCodes","mergedData","setMergedData","useA1CCodesResponse","faFlask","EncountersOverviewCard","sortedData","getEncounterOverviewFilters","faCircleH","faNoteSticky","DEFAULT_CONFIG","useBuilderConfig","PatientInfoLine","mrn","useEpisodeOfCareDrawer","linkToPatient","episodeOfCare","EpisodeOfCareHeader","episodeOfCareData","encountersAndNotes","toc","links","RelatedDocumentButton","gender","episodeOfCareQuery","usePatientEpisodesOfCare","EpisodeOfCareOverviewCard","openEpisodeOfCareDetails","episodesOfCareQuery","getEpisodeOfCareOverviewFilters","PatientMedicationOverview","dedupedData","meds","faPills","VitalsBucket","vitals","systolic","diastolic","getVitalQuantity","cleanUpVitalValue","withUnit","getVitalValue","matchingVitalsWithValues","units","vitalQuery","usePatientVitals","fetchVitals","fetchVitalObservations","fetchVitalEncounters","createVitalBuckets","vital","encounterRefs","observation","encounterIds","vitalsByDate","encountersByDate","dateVitals","orderedEncounters","OVERVIEW_VITALS","VITALS_TO_DROP_WHEN_BLANK","usePatientVitalsOverview","sortedBuckets","vitalBucket","PatientVitalsOverview","faHeartPulse","useOverviewCardsLoadedState","conditionsAllQuery","vitalsQuery","patientHistoryStatus","PatientOverviewComponent","columnsCount","setColumnsCount","hasVitalFeature","cardsLoadedState","builderConfig","gutterWidth","additionalColumns","tablesAreEmpty","overviewCards","cardIsEnabled","cardName","Masonry","PatientOverview","PatientOverviewZapComponent","handleSeeAllResources","PatientOverviewZap","FeedbackContext","FeedbackProvider","useSubmitFeedback","analyticsEvent","isSubmitted","setIsSubmitted","setIsError","setErrorMessage","FeedbackForm","showTextInput","setShowTextInput","showFinalMessage","setShowFinalMessage","feedbackType","setFeedbackType","feedback","setFeedback","submit","handleThumbsDownClick","handleThumbsUpClick","handleTextInputChange","handleSubmit","handleClear","SearchResult","heading","DocumentNotes","allDocuments","clinicalNotes","useDocumentDetailsDrawer","documentData","getRelevantContentFromDocumentSearchResult","spans","sortedSpans","getNonOverlappingSpans","span","nonOverlappingSpans","currentSpan","previousSpan","SearchResultRow","openConditionDetails","openAllergyDetails","openDocumentDetails","openMedicationDetails","observationQuery","fetchObservationsById","EMPTY_SEARCH_RESULTS","EMPTY_RESOURCE_BY_TYPE_MAPPING","PatientRecordSearch$1","patientRecordSearchResponse","resourcesByTypePartial","resourcesByType","usePatientRecordSearch","fetchResourcesById","searchOptions","patientRecordSearchResult","PatientRecordSearch","allergyIds","conditionIds","documentIds","medicationIds","diagnosticReportIds","observationIds","PatientRecordSearchComponent","searchTextInputValue","setSearchTextInputValue","setSearchValue","handleSubmitForm","handleChangeInput","clearSearch","userHasSearched","hasResults","patientSourcesColumns","matchedPatient","PatientSourcesComponent","patientSourcesQuery","hasNoData","PatientSources","patientTimelineColumns","timelineEvent","timelineFilters","timelineEvents","te","defaultTimelineFilters","defaultTimelineSort","timelineSortOptions","TimelineEventModel","useTimelineEvents","setTimelineEvents","patientEncountersQuery","diagnosticReportQuery","queries","PatientTimeline","timelineEventsQuery","vitalFilters","defaultVitalSort","vitalSortOptions","past30days","past3months","pastYear","mostRecent5","vitalViewOptions","defaultVitalView","getVitalRows","rows","RotatedTable","row","PatientVitals","setRows","patientDocumentColumns","documentSortOptions","defaultDocumentSort","PatientDocumentsComponent","patientDocumentQuery","openCCDA","useDocumentDrawerActions","documentActions","PatientDocuments","patientImmunizationsColumns","immunizationsFilter","defaultImmunizationSort","immunizationSortOptions","PatientImmunizationsComponent","patientImmunizationsQuery","immunizationData","PatientImmunizations","zusAggregatedProfileTabs","enableDataIndicators","TabHelper","beta","notification","ZusAggregatedProfileComponent","allergiesProps","careTeamProps","conditionsProps","conditionsOutsideProps","conditionsAllProps","diagnosticReportsProps","documentsProps","immunizationsProps","medicationsProps","medicationsOutsideProps","medicationsAllProps","timelineProps","encounterProps","searchProps","sourcesProps","vitalsProps","hideTitle","removeBranding","removeRequestRecords","hasSearchFeature","showNewDataIndicators","hasShowRequestRecordsFeature","setTabOrder","subcomponentProps","showRequestRecordsButton","tabbedContent","ZusAggregatedProfile","PatientConditionsProfile","UnreadDiagnosticReportsNotification","patientMedicationDispenseColumns","applyMedDispenseFilters","usePatientMedicationDispense","getMedicationDispenseFromFQS","PatientMedDispenseComponent","patientMedicationDispenseQuery","PatientMedicationDispense","PatientMedicationsProfile","patientHistoryJobStatuses","patientHistoryFilters","faHourglass","faCalendarWeek","defaultPatientHistoryFilters","useBuilderPatientHistoryList","patientsMap","patientHistoryPatients","SimplePagination","setCurrentPage","currentPage","hasNext","PaginateButton","pageToNavigateTo","PatientHistoryTable","includeBorder","setPatients","setStatus","setExcludeFutureJobs","setSelectedFilters","responsePatients","responseTotal","onFilterChange","CTWBox.StackedWrapper","CTWBox.Heading","PatientNameColumn","mapSourceToSourceLabel","RenderCorrectStatusLabel","serviceName","StatusLabel","usePatientSearchList","searchNameValue","PatientSearch","onSearchClick","CustomComboBox","IS_NEW_MINUTES_THRESHOLD","REFETCH_INTERVAL_MS","useUpidPolling","fetchedPatients","patientsTmp","fetchedPatientIds","patientsTmpIds","continuePolling","patientsWithoutUpid","isNewPatient","refreshedPatient","differenceInMinutes","invalidateQueries","invalidateQueriesFrom","invalidateBuilderMedsQueries","invalidateOtherProviderMedsQueries","invalidateMedicationHistoryQueries","invalidateAllMedicationQueries","PatientsTable","cursors","setCursors","cursorIndex","newCursors","email","refreshPatientsTable","ZapIFrameConfigMessageType","ZapIFrameReadyMessageType","ZapOnResourceSaveMessageType","ZapOnPatientSaveMessageType","ZapOnAddToRecordMessageType","ZapOnConfigReceivedMessageType","IFRAME_MAX_LOAD_TIME_MS","ZusAggregatedProfileIFrameComponent","telemetryContext","overrideIframeUrl","iframeRef","hostedZapReady","setHostedZapReady","preparedOnReadyListener","setPreparedOnReadyListener","iframeShouldBeLoaded","setIframeShouldBeLoaded","sentZapConfig","setSentZapConfig","zapURL","setZapUrl","setOnAddToRecord","onAddToRecordHandler","medicationStatement","updatedOnAddToRecordHandler","onMessageReady","onMessageSave","ZusAggregatedProfileIFrame","ActionList","itemProps","ActionListItem","onAction","onSecondaryAction","secondaryActionText","actionText","undoActionText","onUndoAction","activeClassName","ZusIcon","includeZusText","Pagination","pageCount","prevPage","nextPage","pagesToShow","Page","pagesSkipped","EXPIRY_PADDING_MS","AUTH_ERROR_TOAST_ID","AuthenticationProvider","authTokenURL","setToken","showingErrorNotice","setShowingErrorNotice","unsubscribe","newToken","checkOrRefreshAuth","TelemetryProvider","enableTelemetry","ThemeProvider","locals","style","setStyle","styles","lang","iframe","tailwindTheme","ZapPropsProvider","ZapTabStateProvider","setSelectedZapTabIndex","CTWProvider","QueryClientProvider","Worker","Toggle","ToggleControl","toggleProps","onFormChange"],"mappings":";;;;;;;6CAQa,IAAIA,EAAEC,EAAiBC,EAAE,MAA6B,GAAvBC,GAAA,SAAiB,MAAsB,OAAO,QAApB,YAA4B,OAAO,IAAI,CAAC,IAAIC,EAAE,OAAO,IAAIF,EAAEE,EAAE,eAAe,EAAED,GAAA,SAAiBC,EAAE,gBAAgB,CAAC,CAAC,IAAIC,EAAEL,EAAE,mDAAmD,kBAAkBM,EAAE,OAAO,UAAU,eAAeC,EAAE,CAAC,IAAI,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,EAAE,EAC9U,SAASC,EAAE,EAAEC,EAAEC,EAAE,CAAC,IAAIC,EAA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EAAAA,IAAC09H,IAEC,SAAC19H,EAAA,IAAA89H,GAAA,OAAA,CAAO,UAAU,gEAChB,SAAA99H,EAAAA,IAACy9H,IACE,SAAA59H,CACH,CAAA,CAAA,CACF,CACF,CAAA,CAAA,CACF,CACF,CAAA,CAAA,CACF,CAAA,CACF,CACF,CAAA,EACF,CACF,CAAA,CAEJ,CCnGa,MAAAk+H,GAAS,CAAC,CAAE,KAAArkI,EAAM,KAAAi/D,EAAM,SAAA24B,EAAU,WAAAkJ,KAC7Cv6F,EAAAA,KAAC,MAAI,CAAA,UAAU,aACb,SAAA,CAACD,EAAAA,IAAA,MAAA,CAAI,UAAU,+HACb,SAAAC,EAAA,KAAC,QAAA,CACC,QAASvG,EACT,UAAU,8GAEV,SAAA,CAACsG,EAAAA,IAAA,QAAA4lC,EAAAC,EAAA,CAAM,SAAAyrD,GAAwBkJ,GAA9B,CAA0C,KAAK,WAAW,KAAA9gG,EAAY,GAAIA,GAAM,EACjFsG,EAAAA,IAAC,OAAK,CAAA,UAAU,iBAAkB,CAAA,CAAA,CAAA,CAAA,EAEtC,QAEC,QAAM,CAAA,QAAStG,EAAM,UAAU,oDAC7B,SACHi/D,EAAA,CAAA,CACF,CAAA,EC1BWqlE,GAAgB,CAAC,CAAE,YAAAC,EAAa,aAAAC,KAC1Cl+H,EAAA,IAAA,OAAA,CAAK,SAAUk+H,EAAc,UAAU,eACtC,SAAAl+H,EAAAA,IAAC+9H,GAAQl4F,EAAA,GAAGo4F,EAAa,CAC3B,CAAA","x_google_ignoreList":[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,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,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,354,355,356,357,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,574,575,576,577,578,579,580,615,616,621,622,623,624,625,626,627,628]}