@mherod/get-cookie 4.4.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config.ts","../src/utils/logger.ts","../src/utils/logHelpers.ts","../src/utils/platformUtils.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/utils/execSimple.ts","../src/core/browsers/chrome/windows/getChromePassword.ts","../src/core/browsers/chrome/linux/getChromePassword.ts","../src/core/browsers/sql/CookieQueryBuilder.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/cookies/cookieSpecsFromUrl.ts","../src/utils/argv.ts","../src/cli/cli.ts","../src/utils/errorUtils.ts","../src/cli/cliQueryCookies.ts","../src/cli/handlers/DefaultOutputHandler.ts","../src/cli/handlers/DumpOutputHandler.ts","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isSymbol.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayMap.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseToString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/identity.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_defineProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssignValue.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKey.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/memoize.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_memoizeCapped.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stringToPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/toString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_castPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toKey.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/get.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsMatch.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isStrictComparable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMatchData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseMatches.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseHasIn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hasPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/hasIn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseMatchesProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_basePropertyDeep.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/property.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIteratee.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseFor.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseFor.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseForOwn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseEach.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseEach.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/groupBy.js","../src/cli/handlers/GroupedDumpOutputHandler.ts","../src/core/cookies/renderCookies.ts","../src/cli/handlers/GroupedRenderOutputHandler.ts","../src/cli/handlers/JsonOutputHandler.ts","../src/cli/handlers/RenderOutputHandler.ts","../src/cli/handlers/OutputHandlerFactory.ts","../src/cli/services/CookieQueryService.ts","../src/core/browsers/BrowserDetector.ts","../src/core/browsers/StrategyFactory.ts","../src/core/browsers/chromium/ChromiumCookieQueryStrategy.ts","../src/core/browsers/chrome/ChromiumBrowsers.ts","../src/core/browsers/chromium/BaseChromiumCookieQueryStrategy.ts","../src/utils/ProcessDetector.ts","../src/utils/chromeDates.ts","../src/core/browsers/BaseCookieQueryStrategy.ts","../src/utils/BrowserControl.ts","../src/utils/FileHandleDetector.ts","../src/core/browsers/platform/PlatformBrowserControl.ts","../src/core/browsers/BrowserLockHandler.ts","../src/core/browsers/chrome/decrypt.ts","../src/core/browsers/chrome/windows/decryptV10Cookie.ts","../src/core/browsers/chrome/getChromiumPassword.ts","../src/core/browsers/sql/DatabaseConnectionManager.ts","../src/core/browsers/sql/QueryMonitor.ts","../src/core/browsers/arc/ArcCookieQueryStrategy.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/utils/flatMapAsync.ts","../src/core/browsers/CompositeCookieQueryStrategy.ts","../src/core/browsers/edge/EdgeCookieQueryStrategy.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/core/browsers/opera/OperaCookieQueryStrategy.ts","../src/core/browsers/opera/OperaGXCookieQueryStrategy.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/utils/SystemPermissions.ts","../src/core/browsers/safari/BinaryCodableCookies.ts","../src/core/browsers/safari/BinaryCodablePage.ts","../src/types/schemas.ts","../src/core/browsers/safari/BinaryCodableCookie.ts","../src/core/browsers/safari/decodeBinaryCookies.ts","../src/cli/services/CookieStrategyFactory.ts"],"names":["EnvironmentSchema","env","init_config","__esmMin","config","z","val","homedir","consola","logger","logger_default","init_logger","createConsola","logError","message","error","context","errorMessage","logWarn","component","createTaggedLogger","init_logHelpers","getPlatform","platformCache","osPlatform","isMacOS","isWindows","isPlatformSupported","p","assertPlatformSupported","init_platformUtils","chromeApplicationSupport","init_ChromeApplicationSupport","home","join","execSimple","command","options","result","execPromise","CommandExecutionError","init_execSimple","promisify","exec","originalError","getChromePassword_exports","__export","getChromePassword","decryptDPAPIKey","localStatePath","localStateContent","readFileSync","localState","encryptedKeyBuffer","init_getChromePassword","password","CookieQueryBuilder_exports","CookieQueryBuilder","createQueryBuilder","isSqlBrowser","browser","BROWSER_SCHEMAS","init_CookieQueryBuilder","name","domain","exactDomain","limit","includeExpired","schema","selectColumns","whereClause","params","sql","specs","specConditions","allParams","spec","combinedWhere","minLimit","min","key","columns","col","conditions","nowSeconds","sqlKeywords","checkString","str","field","upperStr","keyword","listChromeProfilePaths","files","fg","listChromeProfiles","processDomainsIntoCookieSpecs","parts","cookieSpecs","i","subDomain","cookieSpecsFromUrl","url","urlObj","parseArgv","argv","parsed","minimist","arg","flag","_","values","getErrorMessage","getErrorDetails","errorMessageContains","searchText","DATABASE_ERROR_PATTERNS","containsAnyPattern","patterns","pattern","getDatabaseErrorType","formatErrorForLogging","details","DefaultOutputHandler","_args","results","uniqueValues","value","DumpOutputHandler","args","freeGlobal","freeGlobal_default","freeSelf","root","root_default","Symbol","Symbol_default","objectProto","hasOwnProperty","nativeObjectToString","symToStringTag","getRawTag","isOwn","tag","unmasked","getRawTag_default","objectToString","objectToString_default","nullTag","undefinedTag","baseGetTag","baseGetTag_default","isObjectLike","isObjectLike_default","symbolTag","isSymbol","isSymbol_default","arrayMap","array","iteratee","index","length","arrayMap_default","isArray","isArray_default","INFINITY","symbolProto","symbolToString","baseToString","baseToString_default","isObject","type","isObject_default","identity","identity_default","asyncTag","funcTag","genTag","proxyTag","isFunction","isFunction_default","coreJsData","coreJsData_default","maskSrcKey","uid","isMasked","func","isMasked_default","funcProto","funcToString","toSource","toSource_default","reRegExpChar","reIsHostCtor","reIsNative","baseIsNative","baseIsNative_default","getValue","object","getValue_default","getNative","getNative_default","WeakMap","WeakMap_default","defineProperty","defineProperty_default","MAX_SAFE_INTEGER","reIsUint","isIndex","isIndex_default","baseAssignValue","baseAssignValue_default","eq","other","eq_default","isLength","isLength_default","isArrayLike","isArrayLike_default","isPrototype","Ctor","proto","isPrototype_default","baseTimes","n","baseTimes_default","argsTag","baseIsArguments","baseIsArguments_default","propertyIsEnumerable","isArguments","isArguments_default","stubFalse","stubFalse_default","freeExports","freeModule","moduleExports","Buffer","nativeIsBuffer","isBuffer","isBuffer_default","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_default","baseUnary","baseUnary_default","freeProcess","nodeUtil","types","nodeUtil_default","nodeIsTypedArray","isTypedArray","isTypedArray_default","arrayLikeKeys","inherited","isArr","isArg","isBuff","isType","skipIndexes","arrayLikeKeys_default","overArg","transform","overArg_default","nativeKeys","nativeKeys_default","baseKeys","baseKeys_default","keys","keys_default","reIsDeepProp","reIsPlainProp","isKey","isKey_default","nativeCreate","nativeCreate_default","hashClear","hashClear_default","hashDelete","hashDelete_default","HASH_UNDEFINED","hashGet","data","hashGet_default","hashHas","hashHas_default","hashSet","hashSet_default","Hash","entries","entry","Hash_default","listCacheClear","listCacheClear_default","assocIndexOf","assocIndexOf_default","arrayProto","splice","listCacheDelete","lastIndex","listCacheDelete_default","listCacheGet","listCacheGet_default","listCacheHas","listCacheHas_default","listCacheSet","listCacheSet_default","ListCache","ListCache_default","Map","Map_default","mapCacheClear","mapCacheClear_default","isKeyable","isKeyable_default","getMapData","map","getMapData_default","mapCacheDelete","mapCacheDelete_default","mapCacheGet","mapCacheGet_default","mapCacheHas","mapCacheHas_default","mapCacheSet","size","mapCacheSet_default","MapCache","MapCache_default","FUNC_ERROR_TEXT","memoize","resolver","memoized","cache","memoize_default","MAX_MEMOIZE_SIZE","memoizeCapped","memoizeCapped_default","rePropName","reEscapeChar","stringToPath","string","match","number","quote","subString","stringToPath_default","toString","toString_default","castPath","castPath_default","toKey","toKey_default","baseGet","path","baseGet_default","get","defaultValue","get_default","arrayPush","offset","arrayPush_default","stackClear","stackClear_default","stackDelete","stackDelete_default","stackGet","stackGet_default","stackHas","stackHas_default","LARGE_ARRAY_SIZE","stackSet","pairs","stackSet_default","Stack","Stack_default","arrayFilter","predicate","resIndex","arrayFilter_default","stubArray","stubArray_default","nativeGetSymbols","getSymbols","symbol","getSymbols_default","baseGetAllKeys","keysFunc","symbolsFunc","baseGetAllKeys_default","getAllKeys","getAllKeys_default","DataView","DataView_default","Promise","Promise_default","Set","Set_default","promiseTag","dataViewCtorString","mapCtorString","promiseCtorString","setCtorString","weakMapCtorString","getTag","ctorString","getTag_default","Uint8Array","Uint8Array_default","setCacheAdd","setCacheAdd_default","setCacheHas","setCacheHas_default","SetCache","SetCache_default","arraySome","arraySome_default","cacheHas","cacheHas_default","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","equalArrays","bitmask","customizer","equalFunc","stack","isPartial","arrLength","othLength","arrStacked","othStacked","seen","arrValue","othValue","compared","othIndex","equalArrays_default","mapToArray","mapToArray_default","setToArray","set","setToArray_default","symbolValueOf","equalByTag","convert","stacked","equalByTag_default","equalObjects","objProps","objLength","othProps","objStacked","skipCtor","objValue","objCtor","othCtor","equalObjects_default","baseIsEqualDeep","objIsArr","othIsArr","objTag","othTag","objIsObj","othIsObj","isSameTag","objIsWrapped","othIsWrapped","objUnwrapped","othUnwrapped","baseIsEqualDeep_default","baseIsEqual","baseIsEqual_default","baseIsMatch","source","matchData","noCustomizer","srcValue","baseIsMatch_default","isStrictComparable","isStrictComparable_default","getMatchData","getMatchData_default","matchesStrictComparable","matchesStrictComparable_default","baseMatches","baseMatches_default","baseHasIn","baseHasIn_default","hasPath","hasFunc","hasPath_default","hasIn","hasIn_default","baseMatchesProperty","baseMatchesProperty_default","baseProperty","baseProperty_default","basePropertyDeep","basePropertyDeep_default","property","property_default","baseIteratee","baseIteratee_default","arrayAggregator","setter","accumulator","arrayAggregator_default","createBaseFor","fromRight","iterable","props","createBaseFor_default","baseFor","baseFor_default","baseForOwn","baseForOwn_default","createBaseEach","eachFunc","collection","createBaseEach_default","baseEach","baseEach_default","baseAggregator","baseAggregator_default","createAggregator","initializer","createAggregator_default","groupBy","groupBy_default","GroupedDumpOutputHandler","groupedByFile","r","renderCookies","cookies","format","showFilePaths","separator","c","file","fileCookies","GroupedRenderOutputHandler","JsonOutputHandler","RenderOutputHandler","OutputHandlerFactory","validFormats","handler","CookieQueryService","strategy","SAFARI_MAGIC_BYTES","BROWSER_PATTERNS","filename","checkSafariMagicBytes","storePath","buffer","detectBrowserFromFilename","detectBrowserFromStore","existsSync","detectedBrowser","isValidBrowserType","getChromiumBrowserPath","currentPlatform","paths","parseProcessLine","line","defaultCommand","pidStr","pid","parsedCommand","parseWindowsProcessLine","detectBrowserProcesses","browserName","grepPattern","windowsProcessMap","processName","stdout","processes","lines","processInfo","isFirefoxRunning","isChromeRunning","isSafariRunning","getBrowserConflictAdvice","processCount","browserDisplayName","chromeTimestampToDate","chromeTimestamp","unixTimestampSeconds","fallbackLogger","BaseCookieQueryStrategy","strategyName","taggedLogger","store","force","execAsync","isInteractiveEnvironment","isCI","isTest","BROWSER_APP_NAMES","isBrowserRunningMacOS","appName","script","quitBrowserMacOS","quitScript","resolve","saveBrowserSessionMacOS","promptUserConfirmation","rl","readline","answer","closeBrowserGracefully","success","waitForBrowserToClose","maxWaitMs","startTime","checkInterval","execFileAsync","execFile","parseFuserLine","user","mode","isValidProcessResult","parsePowerShellOutput","handles","processId","parseError","detectWithLsof","filePath","fd","handle","detectWithFuser","output","detectOnWindows","escapedPath","psScript","detectWithHandleExe","detectFileHandles","os","h","getFileLockInfo","BasePlatformBrowserControl","_BasePlatformBrowserControl","executables","exe","checkCommand","MacOSBrowserControl","WindowsBrowserControl","LinuxBrowserControl","cmd","platformControlInstance","createPlatformBrowserControl","platformOverride","control","createControlForPlatform","platform","BrowserLockHandler","platformControl","autoClose","dbErrorType","fileHandles","lockInfo","handleError","processError","processesWithDetails","advice","relaunchError","decryptV10Cookie","encryptedValue","VERSION_PREFIX","ciphertext","NONCE_LENGTH","TAG_LENGTH","nonce","encryptedData","authTag","decipher","createDecipheriv","isV10Cookie","memoizeBuffer","fn","keyFn","cachedResult","removeV10Prefix","removePadding","decrypted","padding","extractValue","decodedString","uuidMatch","endPatterns","cleanupPatterns","decrypt","metaVersion","reject","pbkdf2","iv","e","MACOS_KEYCHAIN_SERVICES","getMacOSPassword","service","chromeCommand","getWindowsPassword","getLinuxPassword","getChromiumPassword","DatabaseConnectionManager","EventEmitter","filepath","now","existing","lastError","attempt","database","BetterSqlite3","metadata","connectionTime","queryFn","queryDescription","connection","duration","metrics","totalQueryTime","totalQueryCount","activeConnections","toClose","lruPath","lruTime","ms","globalManager","exitHandler","getGlobalConnectionManager","QueryMonitor","db","execution","stmt","MonitoredStatement","statement","monitor","globalMonitor","getGlobalQueryMonitor","createExportedCookie","expiry","BaseChromiumCookieQueryStrategy","browserType","fileResults","connectionManager","queryBuilder","queryOptions","queryConfig","encryptedCookies","row","cookie","cookieFiles","lockResult","shouldRelaunch","retryError","metaQuery","metaResult","decryptedValue","ChromiumCookieQueryStrategy","browserPath","ArcCookieQueryStrategy","ChromeCookieQueryStrategy","profileName","fs","firstPath","chromeDataDir","dirname","profileCache","targetDir","dir","info","cookiePath","flatMapAsync","callback","item","CompositeCookieQueryStrategy","strategies","EdgeCookieQueryStrategy","findFirefoxCookieFiles","profileDirs","devEditionPath","esrPath","localFirefoxPath","matches","FirefoxCookieQueryStrategy","retryConfig","fileList","OperaCookieQueryStrategy","OperaGXCookieQueryStrategy","openFullDiskAccessSettings","getTerminalApp","termProgram","promptForPermissionGrant","handleSafariPermissionError","terminalApp","checkFilePermission","CookieDomainSchema","CookieNameSchema","CookiePathSchema","CookieValueSchema","destr","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","ExportedCookieSchema","CookieRowSchema","BrowserNameSchema","CookieQueryStrategySchema","BaseCookieQueryOptionsSchema","SqlBrowserTypeSchema","BinaryCodableCookie","container","processed","lastProcessed","token","payloadPart","payload","primitiveResult","stringValue","decoded","jwtResult","jsonResult","jwtPayload","jsonValue","macTimestamp","flagsValue","expiryUnix","creationUnix","version","hasPort","offsets","expirationBuffer","expiration","creationBuffer","creation","offsetEntries","a","b","end","baseOffset","_BinaryCodablePage","cookieRow","header","cookieCount","pageStart","cookieOffsets","cookieOffset","footer","cookieSize","cookieBuffer","BinaryCodablePage","_BinaryCodableCookies","page","pageCookies","magic","pageCount","pageSizes","pageSize","currentOffset","pageBuffer","checksum","BinaryCodableCookies","decodeBinaryCookies","cookieDbPath","SafariCookieQueryStrategy","flags","bit","formattedDomain","nameMatches","domainMatches","cookieObj","normalizedName","normalizedDomain","firstAttemptResult","STRATEGY_REGISTRY","createBrowserStrategy","Strategy","createCompositeStrategy","createStrategy","profile","normalizedBrowser","CookieStrategyFactory","queryAndLimitCookies","queryService","cookieMap","buildQueryOptions","removeExpired","deduplicateCookies","cliQueryCookies","cookieSpec","showHelp","createCookieSpec","normalizeWildcard","listProfiles","browserLower","profiles","dataDir","homeDir","appData","getCookieSpecs","positionals","handleCookieQuery","main"],"mappings":";okCAAA,IAQMA,EAAAA,CAoBOC,GA5BbC,EAAAC,CAAAA,CAAAA,CAAA,IAMAC,CAAAA,aAAAA,EAEMJ,CAAAA,EAAAA,CAAoBK,KAAE,CAAA,MAAA,CAAO,CACjC,SAAA,CAAWA,KAAE,CAAA,IAAA,CAAK,CAAC,OAAA,CAAS,OAAQ,MAAQ,CAAA,OAAO,CAAC,CAAA,CAAE,OAAQ,CAAA,MAAM,CACpE,CAAA,IAAA,CAAMA,KACH,CAAA,MAAA,EACA,CAAA,QAAA,EACA,CAAA,SAAA,CAAWC,CAAQA,EAAAA,CAAAA,EAAO,OAAQ,CAAA,GAAA,CAAI,WAAe,EAAA,EAAE,CACvD,CAAA,IAAA,CAAKD,KAAE,CAAA,MAAA,EAAS,CAAA,GAAA,CAAI,CAAC,CAAC,CAC3B,CAAC,EAaYJ,EAAMD,CAAAA,EAAAA,CAAkB,KAAM,CAAA,CACzC,SAAW,CA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AE,EAAAA,EAAO,CAAA,KAAA,CAAO34B,GAAU,CAClBA,CAAAA,YAAiB,KACnBL,CAAAA,CAAAA,CAAO,KAAM,CAAA,cAAA,CAAgBK,CAAM,CAAA,OAAO,CAE1CL,CAAAA,CAAAA,CAAO,KAAM,CAAA,iCAAiC,CAEhD,CAAA,OAAA,CAAQ,IAAK,CAAA,CAAC,EAChB,CAAC,CAAA","file":"cli.cjs","sourcesContent":["import { homedir } from \"node:os\";\n\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\n\n// Load environment variables from .env file\nconfig();\n\nconst EnvironmentSchema = z.object({\n LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n HOME: z\n .string()\n .optional()\n .transform((val) => val ?? process.env.USERPROFILE ?? \"\")\n .pipe(z.string().min(1)),\n});\n\n/**\n * Validated environment variables with type safety and fallbacks\n * @example\n * // Using the environment variables\n * if (env.LOG_LEVEL === \"debug\") {\n * console.log(\"Debug mode enabled\");\n * }\n *\n * // Accessing home directory\n * const cookiePath = join(env.HOME, \"Library/Cookies\");\n */\nexport const env = EnvironmentSchema.parse({\n LOG_LEVEL: process.env.LOG_LEVEL,\n HOME: homedir(),\n});\n","import { type ConsolaInstance, createConsola } from \"consola\";\n\nimport { env } from \"../config\";\n\n/**\n * Standard log levels and their usage:\n * - debug: Detailed information for debugging\n * - info: General operational information\n * - success: Successful operations\n * - warn: Warning conditions\n * - error: Error conditions that might still allow the app to continue\n * - fatal: Critical errors that prevent the app from continuing\n */\nconst consola = createConsola({\n formatOptions: {\n showLogLevel: false,\n colors: true,\n date: false,\n compact: true,\n columns:\n typeof process.stdout.columns === \"number\" ? process.stdout.columns : 80,\n },\n level: env.LOG_LEVEL === \"debug\" ? 5 : 2,\n});\n\n/**\n * Indicates whether debug logging is enabled\n * @example\n * if (isDebug) {\n * logger.debug(\"Detailed debugging information\");\n * }\n */\nexport const isDebug = env.LOG_LEVEL === \"debug\";\n\n/**\n * Configured logger instance with standardized formatting and colored output.\n * Used for consistent logging throughout the application.\n * @example\n * // Basic usage\n * logger.info('Operation started');\n * logger.success('Task completed');\n * logger.error('Failed to process', error);\n *\n * // Tagged logging for module context\n * const moduleLogger = logger.withTag('ModuleName');\n * moduleLogger.info('Module specific log');\n *\n * // Structured logging\n * logger.info('User action', {\n * userId: '123',\n * action: 'login',\n * timestamp: new Date()\n * });\n *\n * // Error logging with full context\n * logger.error('Operation failed', {\n * error: error,\n * context: 'operation name',\n * input: data\n * });\n */\nconst logger: ConsolaInstance = consola;\n\n/**\n *\n */\nexport default logger;\n","import type { ConsolaInstance } from \"consola\";\n\nimport logger from \"./logger\";\n\n/**\n * Helper functions for common logging patterns.\n * @module\n * @example\n * ```typescript\n * import { logOperationResult, logError } from './logHelpers';\n *\n * try {\n * const result = await someOperation();\n * logOperationResult('Operation', true, { data: result });\n * } catch (error) {\n * logError('Operation failed', error);\n * }\n * ```\n */\n\ninterface OperationContext {\n [key: string]: unknown;\n}\n\n/**\n * Log the result of an operation with consistent formatting\n * @param operation - The name of the operation\n * @param success - Whether the operation was successful\n * @param context - Additional context to log\n */\nexport function logOperationResult(\n operation: string,\n success: boolean,\n context?: OperationContext,\n): void {\n if (success) {\n logger.success(`${operation} succeeded`, context);\n } else {\n logger.error(`${operation} failed`, context);\n }\n}\n\n/**\n * Log an error with consistent formatting\n * @param message - The error message\n * @param error - The error object\n * @param context - Additional context to log\n */\nexport function logError(\n message: string,\n error: unknown,\n context?: OperationContext,\n): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(message, { ...context, error: errorMessage });\n}\n\n/**\n * Log a warning with consistent formatting\n * @param component - The component generating the warning\n * @param message - The warning message\n * @param context - Additional context to log\n */\nexport function logWarn(\n component: string,\n message: string,\n context?: OperationContext,\n): void {\n logger.warn(`[${component}] ${message}`, context);\n}\n\n/**\n * Create a logger instance with a component tag\n * @param component - The component name to tag logs with\n * @returns A logger instance that prefixes all messages with the component tag\n * @example\n * ```typescript\n * const dbLogger = createTaggedLogger('Database');\n * dbLogger.info('Connection established');\n * ```\n */\nexport function createTaggedLogger(component: string): ConsolaInstance {\n return logger.withTag(component);\n}\n\n// Re-export the base logger for direct usage\n/**\n * Re-export of the base logger for direct usage.\n */\nexport { default as logger } from \"./logger\";\n","import { platform as osPlatform } from \"node:os\";\n\n/**\n * Cache for platform value\n */\nlet platformCache: string | undefined;\n\n/**\n * Clear the platform cache (for testing)\n * @internal\n */\nexport function clearPlatformCache(): void {\n platformCache = undefined;\n}\n\n/**\n * Supported platform types\n */\nexport type Platform = \"darwin\" | \"win32\" | \"linux\";\n\n/**\n * Get the current platform (with caching)\n * @returns The current platform from os.platform()\n */\nexport function getPlatform(): string {\n platformCache ??= osPlatform();\n return platformCache;\n}\n\n/**\n * Check if the current platform is macOS\n * @returns True if running on macOS\n */\nexport function isMacOS(): boolean {\n return getPlatform() === \"darwin\";\n}\n\n/**\n * Check if the current platform is Windows\n * @returns True if running on Windows\n */\nexport function isWindows(): boolean {\n return getPlatform() === \"win32\";\n}\n\n/**\n * Check if the current platform is Linux\n * @returns True if running on Linux\n */\nexport function isLinux(): boolean {\n return getPlatform() === \"linux\";\n}\n\n/**\n * Check if the current platform is Unix-like (macOS, Linux, FreeBSD, etc.)\n * @returns True if running on a Unix-like system\n */\nexport function isUnixLike(): boolean {\n const p = getPlatform();\n return p !== \"win32\";\n}\n\n/**\n * Check if the current platform is supported\n * @returns True if the platform is supported\n */\nexport function isPlatformSupported(): boolean {\n const p = getPlatform();\n return p === \"darwin\" || p === \"win32\" || p === \"linux\";\n}\n\n/**\n * Get a human-readable platform name\n * @returns A human-readable platform name\n */\nexport function getPlatformDisplayName(): string {\n const platform = getPlatform();\n switch (platform) {\n case \"darwin\":\n return \"macOS\";\n case \"win32\":\n return \"Windows\";\n case \"linux\":\n return \"Linux\";\n default:\n return platform;\n }\n}\n\n/**\n * Throw an error if the current platform is not supported\n * @throws Error if platform is not supported\n */\nexport function assertPlatformSupported(): void {\n if (!isPlatformSupported()) {\n throw new Error(\n `Unsupported platform: ${getPlatform()}. Supported platforms are: darwin, win32, linux`,\n );\n }\n}\n\n/**\n * Get platform-specific path separator\n * @returns The path separator for the current platform\n */\nexport function getPathSeparator(): string {\n return isWindows() ? \"\\\\\" : \"/\";\n}\n\n/**\n * Get platform-specific executable extension\n * @returns The executable extension for the current platform\n */\nexport function getExecutableExtension(): string {\n return isWindows() ? \".exe\" : \"\";\n}\n\n/**\n * Check if the current platform matches any of the specified platforms\n * @param platforms - Platform or platforms to check against current platform\n * @returns True if the current platform matches any of the specified platforms\n */\nexport function isPlatform(...platforms: string[]): boolean {\n const current = osPlatform();\n return platforms.includes(current);\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\n/**\n * The path to Chrome's application support directory for the current platform\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @throws {Error} If unable to determine user's home directory or platform is not supported\n */\nexport const chromeApplicationSupport = (() => {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n assertPlatformSupported();\n\n switch (getPlatform()) {\n case \"darwin\":\n return join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\");\n case \"win32\":\n return join(home, \"AppData\", \"Local\", \"Google\", \"Chrome\", \"User Data\");\n case \"linux\":\n return join(home, \".config\", \"google-chrome\");\n default:\n // This should never happen due to assertPlatformSupported\n throw new Error(`Platform ${getPlatform()} is not supported`);\n }\n})();\n","// External imports\nimport { type ExecOptions, exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\n// Internal imports\nimport { logError } from \"./logHelpers\";\n\nconst execPromise = promisify(exec);\n\n/**\n * Custom error class for command execution failures.\n * @property {string} command - The command that failed to execute\n * @property {Error} [originalError] - The underlying error that caused the failure\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * throw new CommandExecutionError(\n * 'Command timed out',\n * 'git status',\n * originalError\n * );\n * ```\n */\nclass CommandExecutionError extends Error {\n public constructor(\n message: string,\n public readonly command: string,\n public readonly originalError?: Error,\n ) {\n super(message);\n this.name = \"CommandExecutionError\";\n }\n}\n\n/**\n * Executes a shell command and returns its output.\n * @param command - The command to execute\n * @param options - Optional execution options\n * @returns Promise resolving to command output\n * @throws CommandExecutionError if execution fails\n * @example\n * ```typescript\n * try {\n * const { stdout } = await execSimple('git status');\n * logger.info('Git status:', stdout);\n * } catch (error) {\n * if (error instanceof CommandExecutionError) {\n * logger.error('Git command failed:', error.message);\n * }\n * }\n * ```\n */\nexport async function execSimple(\n command: string,\n options?: ExecOptions,\n): Promise<{ stdout: string; stderr: string }> {\n try {\n const result = await execPromise(command, {\n ...options,\n encoding: \"utf8\",\n });\n return {\n stdout: result.stdout.toString(),\n stderr: result.stderr.toString(),\n };\n } catch (error) {\n logError(\"Command execution failed\", error, { command });\n throw new CommandExecutionError(\n error instanceof Error ? error.message : String(error),\n command,\n error instanceof Error ? error : undefined,\n );\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { isWindows } from \"@utils/platformUtils\";\n\nimport { chromeApplicationSupport } from \"../ChromeApplicationSupport\";\n\n/**\n * Windows Chrome Local State file structure for encrypted key\n */\ninterface WindowsChromeLocalState {\n os_crypt: {\n encrypted_key: string;\n };\n}\n\n/**\n * Decrypts Windows DPAPI encrypted key using Windows CryptoAPI\n * On Windows, Chrome uses DPAPI (Data Protection API) to encrypt the master key\n * which is then used to encrypt cookies.\n * @param encryptedKey - The DPAPI encrypted key buffer\n * @returns The decrypted key as a Buffer\n * @throws {Error} If DPAPI decryption fails or key format is invalid\n */\nfunction decryptDPAPIKey(encryptedKey: Buffer): Buffer {\n // Remove the DPAPI prefix (first 5 bytes: \"DPAPI\")\n const DPAPI_PREFIX = Buffer.from(\"DPAPI\");\n if (!encryptedKey.subarray(0, 5).equals(DPAPI_PREFIX)) {\n throw new Error(\"Invalid DPAPI key prefix\");\n }\n\n const encryptedData = encryptedKey.subarray(5);\n\n // Try to use native DPAPI if available on Windows\n if (isWindows()) {\n try {\n // Use eval to prevent bundlers from analyzing the require\n // This ensures the module is loaded at runtime, not bundled\n const moduleName = \"@primno\" + \"/dpapi\"; // Split to prevent static analysis\n // biome-ignore lint/security/noGlobalEval: Required for dynamic optional dependency loading\n const dpapi = eval(`require(\"${moduleName}\")`) as {\n unprotectData: (data: Buffer) => Buffer;\n };\n\n if (typeof dpapi.unprotectData === \"function\") {\n return dpapi.unprotectData(encryptedData);\n }\n } catch (error) {\n // Module not available or failed to load - this is expected for optional dependency\n // Don't log the full error to avoid cluttering output\n if (process.env.VERBOSE !== undefined && process.env.VERBOSE !== \"\") {\n console.warn(\"DPAPI module not available:\", error);\n }\n }\n }\n\n // Fallback for testing or when DPAPI is not available\n // This won't work for real encrypted cookies but allows the code to run\n throw new Error(\n \"Windows DPAPI decryption requires native bindings. Install @primno/dpapi package for Windows support.\",\n );\n}\n\n/**\n * Retrieves the Chrome Safe Storage password on Windows\n * On Windows, Chrome stores an encrypted master key in Local State file\n * which is encrypted using Windows DPAPI (Data Protection API)\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from Local State file\n */\nexport function getChromePassword(): string {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localStateContent = readFileSync(localStatePath, \"utf8\");\n const localState = JSON.parse(localStateContent) as WindowsChromeLocalState;\n\n if (!localState.os_crypt.encrypted_key) {\n throw new Error(\"No encrypted key found in Chrome Local State\");\n }\n\n // Decode the base64 encrypted key\n const encryptedKeyBuffer = Buffer.from(\n localState.os_crypt.encrypted_key,\n \"base64\",\n );\n\n // Decrypt using DPAPI\n const masterKey = decryptDPAPIKey(encryptedKeyBuffer);\n\n // Return the key as a buffer (not string) for use in AES-GCM decryption\n return masterKey.toString(\"latin1\");\n } catch (error) {\n throw new Error(\n `Failed to retrieve Chrome password on Windows: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { execSimple } from \"../../../../utils/execSimple\";\n\n/**\n * Attempts to retrieve Chrome password from various Linux keyrings\n *\n * Chrome on Linux can store passwords in:\n * 1. GNOME Keyring (via libsecret)\n * 2. KWallet (KDE)\n * 3. Basic password store (plaintext \"peanuts\")\n * @returns The Chrome Safe Storage password\n */\nexport async function getChromePassword(): Promise<string> {\n // Try different methods in order of preference\n\n // Method 1: Try libsecret (GNOME Keyring)\n try {\n const command =\n \"secret-tool lookup application chrome-libsecret-password-v2 || \" +\n \"secret-tool lookup application chrome\";\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password) {\n return password;\n }\n } catch {\n // Continue to next method\n }\n\n // Method 2: Try python keyring module\n try {\n const command =\n \"python3 -c \\\"import keyring; print(keyring.get_password('Chrome Safe Storage', 'Chrome'))\\\"\";\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password && password !== \"None\") {\n return password;\n }\n } catch {\n // Continue to next method\n }\n\n // Method 3: Try KWallet (KDE)\n try {\n const command =\n 'kwallet-query kdewallet -f \"Chrome Safe Storage\" -r Chrome';\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password) {\n return password;\n }\n } catch {\n // Continue to fallback\n }\n\n // Method 4: Fallback to default password\n // On some Linux systems, Chrome uses a hardcoded password\n return \"peanuts\";\n}\n","/**\n * Unified SQL query builder for cookie database operations\n * Provides a centralized, type-safe way to build SQL queries for different browsers\n */\n\nimport type { SqlCookieQueryOptions } from \"../../../types/schemas\";\n\n/**\n * Browser types that use SQL databases for cookie storage\n */\nexport type SqlBrowserType =\n | \"chrome\"\n | \"chromium\"\n | \"edge\"\n | \"firefox\"\n | \"opera\"\n | \"brave\"\n | \"arc\";\n\n/**\n * SQL query configuration\n */\nexport interface SqlQueryConfig {\n sql: string;\n params: unknown[];\n description?: string;\n}\n\n/**\n * Cookie query options - re-export from schemas for backward compatibility\n */\nexport type CookieQueryOptions = SqlCookieQueryOptions;\n\n/**\n * Database schema information\n */\ninterface BrowserSchema {\n tableName: string;\n nameColumn: string;\n valueColumn: string;\n domainColumn: string;\n expiryColumn: string;\n encryptedValueColumn?: string;\n pathColumn?: string;\n secureColumn?: string;\n httpOnlyColumn?: string;\n}\n\n/**\n * Browser-specific SQL schemas\n */\nconst BROWSER_SCHEMAS: Record<SqlBrowserType, BrowserSchema> = {\n chrome: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n chromium: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n edge: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n opera: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n brave: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n arc: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n firefox: {\n tableName: \"moz_cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host\",\n expiryColumn: \"expiry\",\n pathColumn: \"path\",\n secureColumn: \"isSecure\",\n httpOnlyColumn: \"isHttpOnly\",\n },\n};\n\n/**\n * SQL query builder for cookie operations\n */\nexport class CookieQueryBuilder {\n private readonly schema: BrowserSchema;\n private readonly browser: SqlBrowserType;\n\n /**\n *\n * @param browser\n */\n constructor(browser: SqlBrowserType) {\n this.browser = browser;\n this.schema = BROWSER_SCHEMAS[browser];\n if (!this.schema) {\n throw new Error(`Unsupported browser type: ${browser}`);\n }\n }\n\n /**\n * Build a SELECT query for cookies\n * @param options\n */\n buildSelectQuery(options: CookieQueryOptions): SqlQueryConfig {\n const { name, domain, exactDomain, limit, includeExpired } = options;\n const schema = this.schema;\n\n // Build SELECT clause based on browser type\n const selectColumns = this.buildSelectColumns();\n\n // Build WHERE clause\n const { whereClause, params } = this.buildWhereClause(\n name,\n domain,\n exactDomain,\n includeExpired,\n );\n\n // Build complete SQL\n let sql = `SELECT ${selectColumns} FROM ${schema.tableName}`;\n if (whereClause) {\n sql += ` WHERE ${whereClause}`;\n }\n\n // Add ORDER BY for consistent results\n sql += ` ORDER BY ${schema.expiryColumn} DESC`;\n\n // Add LIMIT if specified\n if (limit && limit > 0) {\n sql += ` LIMIT ${limit}`;\n }\n\n return {\n sql,\n params,\n description: `Query ${this.browser} cookies: name=${name}, domain=${domain}`,\n };\n }\n\n /**\n * Build a batch SELECT query for multiple cookie specs\n * Combines multiple cookie specs into a single query with OR conditions\n * @param specs - Array of cookie query options\n */\n buildBatchSelectQuery(specs: CookieQueryOptions[]): SqlQueryConfig {\n if (specs.length === 0) {\n throw new Error(\"At least one spec is required for batch query\");\n }\n\n const schema = this.schema;\n const selectColumns = this.buildSelectColumns();\n\n // Build combined WHERE clause\n const specConditions: string[] = [];\n const allParams: unknown[] = [];\n\n for (const spec of specs) {\n const { whereClause, params } = this.buildWhereClause(\n spec.name,\n spec.domain,\n spec.exactDomain,\n spec.includeExpired,\n );\n\n if (whereClause) {\n // Wrap each spec's conditions in parentheses\n specConditions.push(`(${whereClause})`);\n allParams.push(...params);\n }\n }\n\n // Combine all specs with OR\n const combinedWhere = specConditions.join(\" OR \");\n\n // Build complete SQL\n let sql = `SELECT ${selectColumns} FROM ${schema.tableName}`;\n if (combinedWhere) {\n sql += ` WHERE ${combinedWhere}`;\n }\n\n // Add ORDER BY for consistent results\n sql += ` ORDER BY ${schema.expiryColumn} DESC`;\n\n // Find the minimum limit across all specs (if any have limits)\n const minLimit = specs.reduce(\n (min, spec) => {\n if (spec.limit && spec.limit > 0) {\n return min ? Math.min(min, spec.limit) : spec.limit;\n }\n return min;\n },\n undefined as number | undefined,\n );\n\n if (minLimit && minLimit > 0) {\n sql += ` LIMIT ${minLimit * specs.length}`; // Multiply by specs count to ensure we get enough results\n }\n\n return {\n sql,\n params: allParams,\n description: `Batch query ${this.browser} cookies for ${specs.length} specs`,\n };\n }\n\n /**\n * Build a query to get database metadata\n * @param key\n */\n buildMetaQuery(key: string): SqlQueryConfig {\n // Only Chromium-based browsers have meta table\n if (this.browser === \"firefox\") {\n throw new Error(\"Firefox does not have a meta table\");\n }\n\n return {\n sql: \"SELECT value FROM meta WHERE key = ?\",\n params: [key],\n description: `Get metadata: ${key}`,\n };\n }\n\n /**\n * Build a query to check if table exists\n */\n buildTableExistsQuery(): SqlQueryConfig {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type='table' AND name=?\",\n params: [this.schema.tableName],\n description: `Check if ${this.schema.tableName} table exists`,\n };\n }\n\n /**\n * Build SELECT columns based on browser\n */\n private buildSelectColumns(): string {\n const schema = this.schema;\n const columns = [\n schema.nameColumn,\n schema.domainColumn,\n schema.expiryColumn,\n ];\n\n // Add encrypted_value for Chromium-based browsers\n if (schema.encryptedValueColumn && this.browser !== \"firefox\") {\n columns.push(schema.encryptedValueColumn);\n } else {\n columns.push(schema.valueColumn);\n }\n\n // Add additional columns if available\n if (schema.pathColumn) {\n columns.push(schema.pathColumn);\n }\n if (schema.secureColumn) {\n columns.push(schema.secureColumn);\n }\n if (schema.httpOnlyColumn) {\n columns.push(schema.httpOnlyColumn);\n }\n\n // Use aliases for consistent output\n return columns\n .map((col) => {\n switch (col) {\n case schema.domainColumn:\n return `${col} AS domain`;\n case schema.expiryColumn:\n return `${col} AS expiry`;\n case schema.encryptedValueColumn:\n return `${col} AS encrypted_value`;\n case schema.valueColumn:\n return `${col} AS value`;\n case schema.nameColumn:\n return `${col} AS name`;\n case schema.pathColumn:\n return `${col} AS path`;\n case schema.secureColumn:\n return `${col} AS is_secure`;\n case schema.httpOnlyColumn:\n return `${col} AS is_httponly`;\n default:\n return col;\n }\n })\n .join(\", \");\n }\n\n /**\n * Build WHERE clause with proper parameter binding\n * @param name\n * @param domain\n * @param exactDomain\n * @param includeExpired\n */\n private buildWhereClause(\n name: string,\n domain: string,\n exactDomain?: boolean,\n includeExpired?: boolean,\n ): { whereClause: string; params: unknown[] } {\n const schema = this.schema;\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Handle name condition\n if (name === \"%\") {\n // Wildcard - no name condition needed\n } else if (name.includes(\"%\") || name.includes(\"_\")) {\n // Pattern matching\n conditions.push(`${schema.nameColumn} LIKE ?`);\n params.push(name);\n } else {\n // Exact match\n conditions.push(`${schema.nameColumn} = ?`);\n params.push(name);\n }\n\n // Handle domain condition\n if (domain) {\n if (exactDomain) {\n conditions.push(`${schema.domainColumn} = ?`);\n params.push(domain);\n } else {\n // Optimize domain matching:\n // 1. For domains starting with \".\", use suffix match (more efficient)\n // 2. For regular domains, try to match the domain and subdomains\n if (domain.startsWith(\".\")) {\n // Match exact suffix (e.g., \".github.com\")\n conditions.push(`${schema.domainColumn} LIKE ?`);\n params.push(`%${domain}`);\n } else {\n // Match domain and all subdomains efficiently\n // This matches \"github.com\", \".github.com\", \"api.github.com\", etc.\n conditions.push(\n `(${schema.domainColumn} = ? OR ${schema.domainColumn} = ? OR ${schema.domainColumn} LIKE ?)`,\n );\n params.push(domain, `.${domain}`, `%.${domain}`);\n }\n }\n }\n\n // Handle expiry condition\n if (!includeExpired) {\n // Firefox uses seconds, Chrome uses microseconds since 1601\n if (this.browser === \"firefox\") {\n // Pre-calculate the timestamp to avoid function call per row\n const nowSeconds = Math.floor(Date.now() / 1000);\n conditions.push(`${schema.expiryColumn} > ?`);\n params.push(nowSeconds);\n } else {\n // Chrome timestamp: microseconds since January 1, 1601\n // We'll let the caller handle the conversion\n conditions.push(`${schema.expiryColumn} > 0`);\n }\n }\n\n return {\n whereClause: conditions.join(\" AND \"),\n params,\n };\n }\n\n /**\n * Validate and sanitize query parameters\n * @param options\n */\n static validateQueryParams(options: CookieQueryOptions): void {\n const { name, domain, limit } = options;\n\n // Validate name\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"Cookie name must be a non-empty string\");\n }\n\n // Validate domain\n if (typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"Domain must be a non-empty string\");\n }\n\n // Prevent SQL injection attempts\n const sqlKeywords = [\n \"SELECT\",\n \"INSERT\",\n \"UPDATE\",\n \"DELETE\",\n \"DROP\",\n \"CREATE\",\n \"ALTER\",\n \"--\",\n \";\",\n ];\n const checkString = (str: string, field: string) => {\n const upperStr = str.toUpperCase();\n for (const keyword of sqlKeywords) {\n if (upperStr.includes(keyword)) {\n throw new Error(\n `Invalid ${field}: contains SQL keyword '${keyword}'`,\n );\n }\n }\n };\n\n checkString(name, \"name\");\n checkString(domain, \"domain\");\n\n // Validate limit\n if (limit !== undefined) {\n if (!Number.isInteger(limit) || limit <= 0 || limit > 10000) {\n throw new Error(\"Limit must be a positive integer between 1 and 10000\");\n }\n }\n }\n\n /**\n * Get browser type for a query builder\n */\n getBrowserType(): SqlBrowserType {\n return this.browser;\n }\n\n /**\n * Get schema information\n */\n getSchema(): Readonly<BrowserSchema> {\n return Object.freeze({ ...this.schema });\n }\n}\n\n/**\n * Factory function for creating query builders\n * @param browser\n */\nexport function createQueryBuilder(\n browser: SqlBrowserType,\n): CookieQueryBuilder {\n return new CookieQueryBuilder(browser);\n}\n\n/**\n * Check if a browser uses SQL for cookie storage\n * @param browser\n */\nexport function isSqlBrowser(browser: string): browser is SqlBrowserType {\n return browser in BROWSER_SCHEMAS;\n}\n","// External imports\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport fg from \"fast-glob\";\n\n// Internal imports\nimport { createTaggedLogger } from \"../../utils/logHelpers\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst logger = createTaggedLogger(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * logger.error('Failed to access Chrome profiles', { error });\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = fg.sync(\"./**/Cookies\", {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n logger.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * logger.warn('No Chrome profiles found');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n logger.debug(\"Failed to access Chrome profiles\", { error });\n return [];\n }\n}\n","import type { CookieSpec } from \"../../types/schemas\";\n\n/**\n * Process a domain into cookie specifications, including parent domains\n * @internal\n * @param domain - The domain to process (e.g., 'api.example.com')\n * @returns Array of cookie specifications for the domain and its parents\n */\nfunction processDomainsIntoCookieSpecs(domain: string): CookieSpec[] {\n const parts = domain.split(\".\");\n const cookieSpecs: CookieSpec[] = [];\n\n /**\n * Add the full domain first to ensure exact matches are prioritized\n * The '%' wildcard in the name field matches any cookie name for this domain\n */\n cookieSpecs.push({\n name: \"%\",\n domain: domain,\n });\n\n /**\n * Add parent domains to support domain-level cookie matching\n * For example, for 'sub.example.com', we also want to match 'example.com'\n * This is important because cookies can be set at parent domain levels\n */\n for (let i = 1; i < parts.length - 1; i++) {\n const subDomain = parts.slice(i).join(\".\");\n cookieSpecs.push({\n name: \"%\",\n domain: subDomain,\n });\n }\n\n return cookieSpecs;\n}\n\n/**\n * Generate cookie specifications from a URL by creating specs for both the exact domain\n * and its parent domains. This allows for proper cookie matching across domain levels.\n * @param url - The URL to generate cookie specs from (e.g., 'https://example.com' or just 'example.com')\n * @returns An array of cookie specifications for the URL and its parent domains\n * @remarks\n * - If the URL is provided without a protocol, it will first try to parse with 'https://' prefix\n * - If parsing fails, it will treat the input as a plain domain name\n * - The function handles invalid URLs gracefully by treating them as domain names\n * - The '%' wildcard is used for the name to match all cookies for the domain\n * @example\n * ```typescript\n * // Basic URL with protocol\n * cookieSpecsFromUrl('https://example.com')\n * // Returns: [{ name: '%', domain: 'example.com' }]\n *\n * // URL with subdomain\n * cookieSpecsFromUrl('https://api.example.com')\n * // Returns: [\n * // { name: '%', domain: 'api.example.com' },\n * // { name: '%', domain: 'example.com' }\n * // ]\n *\n * // Domain without protocol (automatically handled)\n * cookieSpecsFromUrl('example.com')\n * // Returns: [{ name: '%', domain: 'example.com' }]\n * ```\n */\nexport function cookieSpecsFromUrl(url: string): CookieSpec[] {\n // For URLs without protocol, try adding https://\n if (!url.includes(\"://\")) {\n try {\n return cookieSpecsFromUrl(`https://${url}`);\n } catch {\n // If adding protocol fails, treat as domain name\n return [\n {\n name: \"%\",\n domain: url,\n },\n ];\n }\n }\n\n try {\n const urlObj = new URL(url);\n return processDomainsIntoCookieSpecs(urlObj.hostname);\n } catch (_error) {\n /**\n * Fallback handling for any parsing errors\n * This ensures the function remains robust even with invalid input\n * Returns a single spec treating the entire input as a domain name\n */\n return [\n {\n name: \"%\",\n domain: url,\n },\n ];\n }\n}\n","import minimist from \"minimist\";\n\n/**\n * Interface representing parsed command line arguments.\n * @property values - Record of option values parsed from command line\n * @property positionals - Array of positional arguments\n * @example\n * ```typescript\n * const args: ParsedArgs = {\n * values: {\n * browser: 'chrome',\n * profile: 'default',\n * verbose: true\n * },\n * positionals: ['script.js', 'input.txt']\n * }\n * ```\n */\ninterface ParsedArgs {\n /** Record of option values parsed from command line */\n values: Record<string, string | boolean | string[]>;\n /** Array of positional arguments */\n positionals: string[];\n}\n\n/**\n * Parses command line arguments into a structured format.\n * @internal\n * @param argv - Array of command line arguments to parse\n * @returns Parsed command line arguments object\n * @example\n * ```typescript\n * // Basic usage\n * const args = parseArgv(['--browser', 'chrome', '--verbose', 'script.js']);\n * // Returns: { values: { browser: 'chrome', verbose: true }, positionals: ['script.js'] }\n *\n * // Using short options\n * const args = parseArgv(['-b', 'firefox', '-v', 'script.js']);\n * // Returns: { values: { browser: 'firefox', verbose: true }, positionals: ['script.js'] }\n *\n * // Error handling\n * const args = parseArgv(['--invalid']); // Will throw error for unknown option\n * ```\n */\nexport function parseArgv(argv: string[]): ParsedArgs {\n const parsed = minimist(argv, {\n string: [\"browser\", \"profile\", \"url\", \"domain\", \"name\", \"output\", \"store\"],\n boolean: [\n \"help\",\n \"version\",\n \"verbose\",\n \"dump\",\n \"dump-grouped\",\n \"render\",\n \"render-grouped\",\n \"force\",\n \"include-expired\",\n \"include-all\",\n \"list-profiles\",\n ],\n alias: {\n b: \"browser\",\n p: \"profile\",\n u: \"url\",\n d: \"dump\",\n D: \"domain\",\n n: \"name\",\n h: \"help\",\n v: \"verbose\",\n f: \"force\",\n G: \"dump-grouped\",\n r: \"render\",\n R: \"render-grouped\",\n },\n unknown: (arg: string) => {\n // Allow positional arguments (don't start with -)\n if (!arg.startsWith(\"-\")) {\n return true;\n }\n // Check if it's a known flag or alias\n const knownFlags = [\n \"--browser\",\n \"-b\",\n \"--profile\",\n \"-p\",\n \"--url\",\n \"-u\",\n \"--domain\",\n \"-D\",\n \"--name\",\n \"-n\",\n \"--output\",\n \"--store\",\n \"--help\",\n \"-h\",\n \"--version\",\n \"--verbose\",\n \"-v\",\n \"--dump\",\n \"-d\",\n \"--dump-grouped\",\n \"-G\",\n \"--render\",\n \"-r\",\n \"--render-grouped\",\n \"-R\",\n \"--force\",\n \"-f\",\n \"--include-expired\",\n \"--include-all\",\n \"--list-profiles\",\n ];\n const isKnown = knownFlags.some((flag) => arg.startsWith(flag));\n if (!isKnown) {\n throw new Error(`Unknown option: ${arg}`);\n }\n return true;\n },\n });\n\n const { _, ...values } = parsed;\n return { values, positionals: _ };\n}\n","#!/usr/bin/env node\n\n// Local imports - core\nimport { listChromeProfiles } from \"@core/browsers/listChromeProfiles\";\nimport { cookieSpecsFromUrl } from \"@core/cookies/cookieSpecsFromUrl\";\nimport { parseArgv } from \"@utils/argv\";\nimport logger from \"@utils/logger\";\n\nimport type { CookieSpec } from \"../types/schemas\";\n\nimport { cliQueryCookies } from \"./cliQueryCookies\";\n\n// This will be replaced at build time by esbuild\ndeclare const BUILD_TIMESTAMP: string;\n\nfunction showHelp(): void {\n logger.log(\"Usage: get-cookie [name] [domain] [options]\");\n\n // Show build info if available\n if (typeof BUILD_TIMESTAMP !== \"undefined\") {\n logger.log(`Build: ${BUILD_TIMESTAMP}`);\n }\n\n logger.log(\"\");\n logger.log(\"Examples:\");\n logger.log(\" get-cookie auth example.com # Get specific cookie\");\n logger.log(\n \" get-cookie % github.com --output json # Get all cookies as JSON\",\n );\n logger.log(\" get-cookie --url https://example.com # Extract from URL\");\n logger.log(\"\");\n logger.log(\"Options:\");\n logger.log(\" -h, --help Show this help message\");\n logger.log(\" -v, --verbose Enable verbose output\");\n logger.log(\n \" -f, --force Force operation despite warnings (e.g., locked databases)\",\n );\n logger.log(\n \" --list-profiles List available browser profiles (use with --browser)\",\n );\n logger.log(\"\");\n logger.log(\"Query options:\");\n logger.log(\n \" -n, --name PATTERN Cookie name pattern (% for wildcard)\",\n );\n logger.log(\" -D, --domain PATTERN Cookie domain pattern\");\n logger.log(\" -u, --url URL URL to extract cookie specs from\");\n logger.log(\n \" --browser BROWSER Target specific browser (chrome|edge|arc|opera|opera-gx|firefox|safari)\",\n );\n logger.log(\n \" --profile NAME Target specific Chrome profile by name (e.g., 'Default', 'Profile 1')\",\n );\n logger.log(\n \" --store PATH Path to a specific cookie store file\",\n );\n logger.log(\n \" --include-expired Include expired cookies (filtered by default)\",\n );\n logger.log(\n \" --include-all Include all duplicate cookies (newest only by default)\",\n );\n logger.log(\"\");\n logger.log(\"Output options:\");\n logger.log(\" --output FORMAT Output format (json)\");\n logger.log(\" -d, --dump Dump all cookie details\");\n logger.log(\n \" -G, --dump-grouped Dump all results, grouped by profile\",\n );\n logger.log(\n \" -r, --render Render all results in formatted output\",\n );\n}\n\nfunction createCookieSpec(name: string, domain: string): CookieSpec {\n return {\n name: name || \"%\",\n domain: domain || \"%\",\n };\n}\n\nfunction normalizeWildcard(pattern: string): string {\n // Convert * to % for consistent wildcard handling\n return pattern === \"*\" ? \"%\" : pattern;\n}\n\ninterface ChromeProfileInfo {\n name: string;\n user_name?: string;\n [key: string]: unknown;\n}\n\nfunction listProfiles(browser?: string): void {\n if (!browser) {\n logger.error(\"Please specify a browser with --browser\");\n logger.log(\"Example: get-cookie --browser chrome --list-profiles\");\n return;\n }\n\n const browserLower = browser.toLowerCase();\n\n if (\n browserLower === \"chrome\" ||\n browserLower === \"edge\" ||\n browserLower === \"arc\" ||\n browserLower === \"opera\" ||\n browserLower === \"opera-gx\"\n ) {\n try {\n const profiles = listChromeProfiles();\n\n if (profiles.length === 0) {\n logger.log(`No ${browser} profiles found`);\n return;\n }\n\n logger.log(`${browser} profiles:`);\n logger.log(\"\");\n\n // Get the profile directory mapping from Chrome's Local State\n const fs = require(\"node:fs\");\n const path = require(\"node:path\");\n const os = require(\"node:os\");\n\n // Determine the browser data directory based on browser type and platform\n let dataDir: string;\n const platform = process.platform;\n\n if (platform === \"darwin\") {\n const homeDir = os.homedir();\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Google\",\n \"Chrome\",\n );\n break;\n case \"edge\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Microsoft Edge\",\n );\n break;\n case \"arc\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Arc\",\n );\n break;\n case \"opera\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.Opera\",\n );\n break;\n case \"opera-gx\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.OperaGX\",\n );\n break;\n default:\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Google\",\n \"Chrome\",\n );\n }\n } else if (platform === \"win32\") {\n const appData =\n process.env.LOCALAPPDATA ||\n path.join(os.homedir(), \"AppData\", \"Local\");\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(appData, \"Google\", \"Chrome\", \"User Data\");\n break;\n case \"edge\":\n dataDir = path.join(appData, \"Microsoft\", \"Edge\", \"User Data\");\n break;\n default:\n dataDir = path.join(appData, \"Google\", \"Chrome\", \"User Data\");\n }\n } else {\n // Linux\n const homeDir = os.homedir();\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(homeDir, \".config\", \"google-chrome\");\n break;\n default:\n dataDir = path.join(homeDir, \".config\", \"google-chrome\");\n }\n }\n\n const localStatePath = path.join(dataDir, \"Local State\");\n\n if (fs.existsSync(localStatePath)) {\n const localState = JSON.parse(fs.readFileSync(localStatePath, \"utf8\"));\n const profileCache = localState.profile?.info_cache || {};\n\n for (const [dir, info] of Object.entries(profileCache)) {\n const profile = info as ChromeProfileInfo;\n logger.log(` • ${profile.name}`);\n logger.log(` Directory: ${dir}`);\n if (profile.user_name) {\n logger.log(` User: ${profile.user_name}`);\n }\n logger.log(\"\");\n }\n } else {\n // Fallback to just listing profile objects\n profiles.forEach((profile) => {\n logger.log(` • ${profile.name}`);\n if (profile.user_name) {\n logger.log(` User: ${profile.user_name}`);\n }\n logger.log(\"\");\n });\n }\n } catch (error) {\n logger.error(\n `Failed to list ${browser} profiles:`,\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n } else if (browserLower === \"firefox\") {\n logger.log(\"Firefox profile listing is not yet implemented\");\n logger.log(\n \"Firefox stores profiles in different locations based on the platform\",\n );\n } else if (browserLower === \"safari\") {\n logger.log(\"Safari does not use named profiles\");\n logger.log(\"Safari uses the system keychain for the current user\");\n } else {\n logger.error(`Unknown browser: ${browser}`);\n }\n}\n\nfunction getCookieSpecs(\n values: Record<string, string | boolean | string[]>,\n positionals: string[],\n): CookieSpec[] {\n const url = values.url as string | undefined;\n\n if (typeof url === \"string\") {\n const specs = cookieSpecsFromUrl(url);\n if (!Array.isArray(specs)) {\n logger.error(\"Invalid cookie specs from URL\");\n return [];\n }\n return specs;\n }\n\n const name = normalizeWildcard(\n (values.name as string) ?? positionals[0] ?? \"%\",\n );\n const domain = normalizeWildcard(\n (values.domain as string) ?? positionals[1] ?? \"%\",\n );\n return [createCookieSpec(name, domain)];\n}\n\nasync function handleCookieQuery(\n values: Record<string, string | boolean | string[]>,\n positionals: string[],\n): Promise<void> {\n const cookieSpecs = getCookieSpecs(values, positionals);\n\n if (values.verbose === true) {\n logger.log(\"cookieSpecs\", cookieSpecs);\n }\n\n try {\n // Default to removing expired cookies unless --include-expired is set\n const removeExpired = values[\"include-expired\"] !== true;\n // Default to deduplicating cookies unless --include-all is set\n const deduplicateCookies = values[\"include-all\"] !== true;\n\n await cliQueryCookies(\n values,\n cookieSpecs,\n undefined,\n removeExpired,\n values.store as string | undefined,\n deduplicateCookies,\n );\n } catch (error) {\n if (error instanceof Error) {\n logger.error(\"Error querying cookies:\", error.message);\n } else {\n logger.error(\"An unknown error occurred while querying cookies\");\n }\n }\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n\n // Show help if no arguments provided\n if (args.length === 0) {\n showHelp();\n return;\n }\n\n const { values, positionals } = parseArgv(args);\n\n if (values.help === true) {\n showHelp();\n return;\n }\n\n if (values[\"list-profiles\"] === true) {\n const browser =\n typeof values.browser === \"string\" ? values.browser : undefined;\n listProfiles(browser);\n return;\n }\n\n await handleCookieQuery(values, positionals);\n}\n\nmain().catch((error) => {\n if (error instanceof Error) {\n logger.error(\"Fatal error:\", error.message);\n } else {\n logger.error(\"An unknown fatal error occurred\");\n }\n process.exit(1);\n});\n","/**\n * Utility functions for consistent error handling across the codebase\n * Following DRY principle to eliminate repetitive error handling patterns\n */\n\n/**\n * Safely extract error message from unknown error types\n * @param error - Any thrown value (Error, string, unknown)\n * @returns A string representation of the error\n * @example\n * try {\n * // some operation\n * } catch (error) {\n * const message = getErrorMessage(error);\n * logger.error('Operation failed', { error: message });\n * }\n */\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (\n error !== null &&\n error !== undefined &&\n typeof error === \"object\" &&\n \"message\" in error\n ) {\n return String(error.message);\n }\n return String(error);\n}\n\n/**\n * Get detailed error information including stack trace\n * @param error - Any thrown value\n * @returns Object with error details\n */\nexport function getErrorDetails(error: unknown): {\n message: string;\n stack?: string;\n name?: string;\n code?: string;\n} {\n const message = getErrorMessage(error);\n\n if (error instanceof Error) {\n const result: ReturnType<typeof getErrorDetails> = { message };\n if (error.stack !== undefined) {\n result.stack = error.stack;\n }\n if (error.name !== undefined) {\n result.name = error.name;\n }\n if (\"code\" in error && error.code !== undefined) {\n result.code = String(error.code);\n }\n return result;\n }\n\n return { message };\n}\n\n/**\n * Check if error message contains specific text (case-insensitive)\n * @param error - Any thrown value\n * @param searchText - Text to search for\n * @returns True if error message contains the text\n */\nexport function errorMessageContains(\n error: unknown,\n searchText: string,\n): boolean {\n const message = getErrorMessage(error).toLowerCase();\n return message.includes(searchText.toLowerCase());\n}\n\n/**\n * Error pattern constants for database error classification\n */\nconst DATABASE_ERROR_PATTERNS = {\n locked: [\"database is locked\", \"database locked\", \"sqlite_busy\"],\n busy: [\"busy\"],\n permission: [\n \"eperm\",\n \"permission denied\",\n \"operation not permitted\",\n \"eacces\",\n ],\n not_found: [\"enoent\", \"no such file\", \"not found\"],\n} as const;\n\n/**\n * Checks if a message contains any of the given patterns\n * @param message - The error message to check\n * @param patterns - Array of patterns to match against\n * @returns True if any pattern is found\n */\nfunction containsAnyPattern(\n message: string,\n patterns: readonly string[],\n): boolean {\n return patterns.some((pattern) => message.includes(pattern));\n}\n\n/**\n * Check if error is a specific type of database error\n * @param error - Any thrown value\n * @returns Type of database error or null\n */\nexport function getDatabaseErrorType(\n error: unknown,\n): \"locked\" | \"busy\" | \"permission\" | \"not_found\" | null {\n const message = getErrorMessage(error).toLowerCase();\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.locked)) {\n return \"locked\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.busy)) {\n return \"busy\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.permission)) {\n return \"permission\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.not_found)) {\n return \"not_found\";\n }\n\n return null;\n}\n\n/**\n * Format error for logging with consistent structure\n * @param error - Any thrown value\n * @param context - Additional context for the error\n * @returns Formatted error object for logging\n */\nexport function formatErrorForLogging(\n error: unknown,\n context?: Record<string, unknown>,\n): Record<string, unknown> {\n const details = getErrorDetails(error);\n\n return {\n ...context,\n error: details.message,\n errorName: details.name,\n errorCode: details.code,\n // Only include stack in development/debug mode\n ...(process.env.NODE_ENV !== \"production\" &&\n details.stack !== undefined &&\n details.stack !== \"\"\n ? { errorStack: details.stack }\n : {}),\n };\n}\n\n/**\n * Type guard to check if value is an Error instance\n * @param error - Any value to check\n * @returns True if error is an Error instance\n */\nexport function isError(error: unknown): error is Error {\n return error instanceof Error;\n}\n\n/**\n * Type guard to check if error has a message property\n * @param error - Any value to check\n * @returns True if error has a message property\n */\nexport function hasErrorMessage(error: unknown): error is { message: unknown } {\n return (\n error !== null &&\n error !== undefined &&\n typeof error === \"object\" &&\n \"message\" in error\n );\n}\n\n/**\n * Create a standardized error from unknown input\n * @param error - Any thrown value\n * @param fallbackMessage - Message to use if error can't be converted\n * @returns Error instance\n */\nexport function ensureError(\n error: unknown,\n fallbackMessage = \"An unknown error occurred\",\n): Error {\n if (error instanceof Error) {\n return error;\n }\n\n const message = getErrorMessage(error) || fallbackMessage;\n const standardError = new Error(message);\n\n // Preserve original error as cause if supported\n if (\"cause\" in standardError) {\n standardError.cause = error;\n }\n\n return standardError;\n}\n\n/**\n * Wrap an async operation with consistent error handling\n * @param operation - Async function to execute\n * @param errorHandler - Function to handle errors\n * @returns Result of operation or undefined if error\n */\nexport async function withErrorHandling<T>(\n operation: () => Promise<T>,\n errorHandler: (error: unknown) => void,\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n errorHandler(error);\n return undefined;\n }\n}\n\n/**\n * Retry an operation with exponential backoff\n * @param operation - Async function to execute\n * @param options - Retry options\n * @param options.maxAttempts - Maximum number of retry attempts\n * @param options.initialDelay - Initial delay in milliseconds\n * @param options.maxDelay - Maximum delay in milliseconds\n * @param options.shouldRetry - Function to determine if retry should be attempted\n * @returns Result of successful operation\n */\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n options: {\n maxAttempts?: number;\n initialDelay?: number;\n maxDelay?: number;\n shouldRetry?: (error: unknown) => boolean;\n } = {},\n): Promise<T> {\n const {\n maxAttempts = 3,\n initialDelay = 100,\n maxDelay = 5000,\n shouldRetry = () => true,\n } = options;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error;\n\n if (attempt === maxAttempts || !shouldRetry(error)) {\n throw error;\n }\n\n const delay = Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type { CookieSpec, ExportedCookie } from \"../types/schemas\";\nimport { getErrorMessage } from \"../utils/errorUtils\";\nimport { logger } from \"../utils/logHelpers\";\n\nimport { OutputHandlerFactory } from \"./handlers/OutputHandlerFactory\";\nimport { CookieQueryService } from \"./services/CookieQueryService\";\nimport {\n type CookieQueryStrategy,\n CookieStrategyFactory,\n} from \"./services/CookieStrategyFactory\";\n\ninterface QueryOptions {\n /** Maximum number of cookies to return */\n limit?: number;\n /** Whether to remove expired cookies */\n removeExpired: boolean;\n /** Whether to deduplicate cookies (keep newest) */\n deduplicateCookies: boolean;\n /** Optional path to a specific binarycookies store file */\n store?: string;\n /** Strategy for querying cookies */\n strategy: CookieQueryStrategy;\n /** Whether to force operations despite warnings */\n force?: boolean;\n}\n\n/**\n * Internal function to query cookies and apply limit\n * @param queryService - The query service to use\n * @param specs - Cookie specifications to query\n * @param options - Query options including limit, expiry handling, store path, and strategy\n * @returns Array of cookies\n */\nasync function queryAndLimitCookies(\n queryService: CookieQueryService,\n specs: CookieSpec[],\n options: QueryOptions,\n): Promise<ExportedCookie[]> {\n let results: ExportedCookie[] = [];\n\n for (const spec of specs) {\n const cookies = await queryService.queryCookies(spec, options);\n results = [...results, ...cookies];\n\n if (\n typeof options.limit === \"number\" &&\n options.limit > 0 &&\n results.length >= options.limit\n ) {\n results = results.slice(0, options.limit);\n break;\n }\n }\n\n // Deduplicate cookies if requested (keep newest based on creation time or longest value)\n if (options.deduplicateCookies && results.length > 0) {\n const cookieMap = new Map<string, ExportedCookie>();\n\n for (const cookie of results) {\n const key = `${cookie.name}:${cookie.domain}`;\n const existing = cookieMap.get(key);\n\n if (!existing) {\n cookieMap.set(key, cookie);\n } else {\n // Keep the cookie with the longest value (most likely to be valid)\n // or if same length, keep the one with latest creation time\n // Replace with longer value, or if same length, keep the newer one\n // Since we don't have creation time, we'll just prefer longer values\n const shouldReplace = cookie.value.length > existing.value.length;\n\n if (shouldReplace) {\n cookieMap.set(key, cookie);\n }\n }\n }\n\n results = Array.from(cookieMap.values());\n }\n\n return results;\n}\n\n/**\n * Query cookies from the browser using the specified strategy\n * @param args - Command line arguments including browser and output format options\n * @param cookieSpec - Cookie specification(s) to query for\n * @param limit - Maximum number of cookies to return\n * @param removeExpired - Whether to remove expired cookies\n * @param store - Optional path to a specific binarycookies store file\n */\n/**\n * Builds query options from command line arguments and parameters.\n * Consolidates various options into a single QueryOptions object for cookie querying.\n * @param args - Command line arguments containing optional force flag\n * @param strategy - The browser-specific cookie query strategy to use\n * @param removeExpired - Whether to filter out expired cookies from results\n * @param deduplicateCookies\n * @param limit - Optional maximum number of cookies to return\n * @param store - Optional path to a specific cookie store file (e.g., Safari binarycookies)\n * @returns Configured QueryOptions object for cookie querying\n */\nfunction buildQueryOptions(\n args: Record<string, unknown>,\n strategy: CookieQueryStrategy,\n removeExpired: boolean,\n deduplicateCookies: boolean,\n limit?: number,\n store?: string,\n): QueryOptions {\n const queryOptions: QueryOptions = {\n removeExpired,\n deduplicateCookies,\n strategy,\n };\n const force = typeof args.force === \"boolean\" ? args.force : false;\n\n if (limit !== undefined) {\n queryOptions.limit = limit;\n }\n if (store !== undefined) {\n queryOptions.store = store;\n }\n if (force) {\n queryOptions.force = force;\n }\n\n return queryOptions;\n}\n\n/**\n * Queries browser cookies from the command line interface and outputs results.\n * This is the main entry point for CLI cookie queries, handling browser detection,\n * strategy selection, and output formatting.\n * @param args - Command line arguments including browser selection and output format\n * @param cookieSpec - Cookie specification(s) defining which cookies to retrieve\n * @param limit - Optional maximum number of cookies to return\n * @param removeExpired - Whether to exclude expired cookies from results (default: false)\n * @param store - Optional path to a specific cookie store file for direct access\n * @param deduplicateCookies\n * @returns Promise that resolves when query and output are complete\n * @example\n * ```typescript\n * // Query all cookies named \"session\" from Chrome\n * await cliQueryCookies(\n * { browser: \"chrome\", output: \"json\" },\n * { name: \"session\", domain: \"example.com\" }\n * );\n * ```\n */\nexport async function cliQueryCookies(\n args: Record<string, unknown>,\n cookieSpec: CookieSpec | CookieSpec[],\n limit?: number,\n removeExpired = false,\n store?: string,\n deduplicateCookies = true,\n): Promise<void> {\n try {\n const browser = typeof args.browser === \"string\" ? args.browser : undefined;\n const profile = typeof args.profile === \"string\" ? args.profile : undefined;\n const strategy = CookieStrategyFactory.createStrategy(\n browser,\n store,\n profile,\n );\n const queryService = new CookieQueryService(strategy);\n const specs = Array.isArray(cookieSpec) ? cookieSpec : [cookieSpec];\n\n const queryOptions = buildQueryOptions(\n args,\n strategy,\n removeExpired,\n deduplicateCookies,\n limit,\n store,\n );\n const results = await queryAndLimitCookies(\n queryService,\n specs,\n queryOptions,\n );\n\n if (results.length === 0) {\n logger.error(\"No results\");\n\n // Provide helpful feedback for profile-related issues\n const profile =\n typeof args.profile === \"string\" ? args.profile : undefined;\n const browser =\n typeof args.browser === \"string\" ? args.browser : undefined;\n\n if (profile && browser) {\n logger.error(`Could not find cookies for profile: ${profile}`);\n logger.error(\n `Try 'get-cookie --browser ${browser} --list-profiles' to see available profiles`,\n );\n }\n\n return;\n }\n\n const outputFactory = new OutputHandlerFactory();\n const outputHandler = outputFactory.getHandler(args);\n outputHandler.handle(results);\n } catch (error) {\n logger.error(getErrorMessage(error));\n }\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Default handler for cookie output when no specific format is requested\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs:\n * // abc123\n * // xyz789\n * ```\n */\nexport class DefaultOutputHandler implements OutputHandler {\n /**\n * Always returns true as this is the default handler\n * @param _args - The parsed command line arguments\n * @returns Always returns true\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * const canHandle = handler.canHandle({ format: 'default' }); // true\n * ```\n */\n public canHandle(_args: ParsedArgs): boolean {\n return true;\n }\n\n /**\n * Outputs unique cookie values\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'example.com', value: 'abc123' }, // Duplicate value\n * { name: 'token', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs only unique values:\n * // abc123\n * // xyz789\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n const uniqueValues = new Set(\n results.map((result) => result.value as string),\n );\n for (const value of uniqueValues) {\n logger.log(value);\n }\n }\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles raw dump output of cookie data\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs the full cookie objects:\n * // [\n * // { name: 'session', domain: 'example.com', value: 'abc123' },\n * // { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * // ]\n * ```\n */\nexport class DumpOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on dump flags\n * @param args - The parsed command line arguments\n * @returns True if dump flags are set\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.canHandle({ dump: true }); // true\n * handler.canHandle({ d: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args.dump === true || args.d === true;\n }\n\n /**\n * Outputs the raw cookie data\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.handle([{\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome'\n * }\n * }]);\n * // Outputs the full cookie object with all properties\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(results);\n }\n}\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\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\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\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\nexport default 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\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\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\nexport default 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\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default isSymbol;\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\nexport default 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\nexport default isArray;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\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\nexport default baseToString;\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\nexport default isObject;\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\nexport default identity;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\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\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\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\nexport default 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\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\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\nexport default 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\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\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\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\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\nexport default isIndex;\n","import defineProperty from './_defineProperty.js';\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\nexport default baseAssignValue;\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\nexport default eq;\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\nexport default isLength;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\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\nexport default isArrayLike;\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\nexport default isPrototype;\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\nexport default baseTimes;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default 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\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\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\nexport default isBuffer;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default 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\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\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\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\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\nexport default isTypedArray;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\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\nexport default arrayLikeKeys;\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\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\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\nexport default baseKeys;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\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\nexport default keys;\n","import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\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\nexport default isKey;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default 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\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\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\nexport default Hash;\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\nexport default listCacheClear;\n","import eq from './eq.js';\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\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\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\nexport default ListCache;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\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\nexport default 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\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\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\nexport default getMapData;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\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\nexport default MapCache;\n","import MapCache from './_MapCache.js';\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\nexport default memoize;\n","import memoize from './memoize.js';\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\nexport default memoizeCapped;\n","import memoizeCapped from './_memoizeCapped.js';\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\nexport default stringToPath;\n","import baseToString from './_baseToString.js';\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\nexport default toString;\n","import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\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\nexport default castPath;\n","import isSymbol from './isSymbol.js';\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\nexport default toKey;\n","import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\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\nexport default baseGet;\n","import baseGet from './_baseGet.js';\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\nexport default get;\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\nexport default arrayPush;\n","import ListCache from './_ListCache.js';\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\nexport default 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\nexport default 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\nexport default 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\nexport default stackHas;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\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\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\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\nexport default Stack;\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\nexport default 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\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\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\nexport default getSymbols;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\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\nexport default baseGetAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\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\nexport default getAllKeys;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\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\nexport default getTag;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\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\nexport default 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\nexport default setCacheHas;\n","import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\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\nexport default 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\nexport default 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\nexport default cacheHas;\n","import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\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\nexport default 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\nexport default 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\nexport default setToArray;\n","import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\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\nexport default equalByTag;\n","import getAllKeys from './_getAllKeys.js';\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\nexport default equalObjects;\n","import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\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\nexport default baseIsEqualDeep;\n","import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default baseIsEqual;\n","import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\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\nexport default baseIsMatch;\n","import isObject from './isObject.js';\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\nexport default isStrictComparable;\n","import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\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\nexport default 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\nexport default matchesStrictComparable;\n","import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\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\nexport default baseMatches;\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\nexport default baseHasIn;\n","import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\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\nexport default hasPath;\n","import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\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\nexport default hasIn;\n","import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\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\nexport default 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\nexport default baseProperty;\n","import baseGet from './_baseGet.js';\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\nexport default basePropertyDeep;\n","import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\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\nexport default property;\n","import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\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\nexport default baseIteratee;\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\nexport default arrayAggregator;\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\nexport default createBaseFor;\n","import createBaseFor from './_createBaseFor.js';\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\nexport default baseFor;\n","import baseFor from './_baseFor.js';\nimport keys from './keys.js';\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\nexport default baseForOwn;\n","import isArrayLike from './isArrayLike.js';\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\nexport default createBaseEach;\n","import baseForOwn from './_baseForOwn.js';\nimport createBaseEach from './_createBaseEach.js';\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\nexport default baseEach;\n","import baseEach from './_baseEach.js';\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\nexport default baseAggregator;\n","import arrayAggregator from './_arrayAggregator.js';\nimport baseAggregator from './_baseAggregator.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\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\nexport default createAggregator;\n","import baseAssignValue from './_baseAssignValue.js';\nimport createAggregator from './_createAggregator.js';\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\nexport default groupBy;\n","import { groupBy } from \"lodash-es\";\n\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles grouped dump output of cookie data\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies1.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies2.db' }\n * }\n * ]);\n * // Outputs cookies grouped by file:\n * // {\n * // \"/path/to/cookies1.db\": [\n * // { name: \"session\", domain: \"example.com\", value: \"abc123\", ... }\n * // ],\n * // \"/path/to/cookies2.db\": [\n * // { name: \"auth\", domain: \"api.example.com\", value: \"xyz789\", ... }\n * // ]\n * // }\n * ```\n */\nexport class GroupedDumpOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on grouped dump flags\n * @param args - The parsed command line arguments\n * @returns True if grouped dump flags are set\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.canHandle({ 'dump-grouped': true }); // true\n * handler.canHandle({ D: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args[\"dump-grouped\"] === true || args.D === true;\n }\n\n /**\n * Outputs the cookie data grouped by source file\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/chrome/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/firefox/cookies.sqlite' }\n * }\n * ]);\n * // Groups and outputs cookies by their source file\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n const groupedByFile = groupBy(results, (r) => r.meta?.file ?? \"unknown\");\n logger.log(JSON.stringify(groupedByFile, null, 2));\n }\n}\n","import { groupBy } from \"lodash-es\";\n\nimport type { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n // Format cookies as they would appear in a Cookie header or document.cookie\n // Each cookie is \"name=value\" separated by \"; \"\n return cookies.map((c) => `${c.name}=${c.value}`).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies\n .map((c) => `${c.name}=${c.value}`)\n .join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import { renderCookies } from \"@core/cookies/renderCookies\";\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles grouped render output of cookie data\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies1.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies2.db' }\n * }\n * ]);\n * // Outputs cookies in a grouped format:\n * // /path/to/cookies1.db:\n * // example.com:\n * // session=abc123\n * // /path/to/cookies2.db:\n * // api.example.com:\n * // auth=xyz789\n * ```\n */\nexport class GroupedRenderOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on grouped render flags\n * @param args - The parsed command line arguments\n * @returns True if grouped render flags are set\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.canHandle({ 'render-grouped': true }); // true\n * handler.canHandle({ R: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args[\"render-grouped\"] === true || args.R === true;\n }\n\n /**\n * Outputs the cookie data in a grouped format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/chrome/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/firefox/cookies.sqlite' }\n * }\n * ]);\n * // Outputs:\n * // /path/to/chrome/cookies.db:\n * // example.com:\n * // session=abc123\n * // /path/to/firefox/cookies.sqlite:\n * // example.com:\n * // auth=xyz789\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(renderCookies(results, { format: \"grouped\" }));\n }\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles JSON output of cookie data\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies.db' }\n * }\n * ]);\n * // Outputs:\n * // {\n * // \"name\": \"session\",\n * // \"domain\": \"example.com\",\n * // \"value\": \"abc123\",\n * // \"meta\": {\n * // \"file\": \"/path/to/cookies.db\"\n * // }\n * // }\n * ```\n */\nexport class JsonOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on JSON output flag\n * @param args - The parsed command line arguments\n * @returns True if output is set to \"json\"\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.canHandle({ output: 'json' }); // true\n * handler.canHandle({ output: 'text' }); // false\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args.output === \"json\";\n }\n\n /**\n * Outputs the cookie data in JSON format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.handle([{\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome',\n * decrypted: true\n * }\n * }]);\n * // Outputs formatted JSON with all cookie properties\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(JSON.stringify(results, null, 2));\n }\n}\n","import { renderCookies } from \"@core/cookies/renderCookies\";\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles merged render output of cookie data\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies.db' }\n * }\n * ]);\n * // Outputs cookies in a merged format:\n * // example.com:\n * // session=abc123\n * // api.example.com:\n * // auth=xyz789\n * ```\n */\nexport class RenderOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on render flags\n * @param args - The parsed command line arguments\n * @returns True if any render flag is set\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.canHandle({ render: true }); // true\n * handler.canHandle({ 'render-merged': true }); // true\n * handler.canHandle({ r: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return (\n args.render === true || args[\"render-merged\"] === true || args.r === true\n );\n }\n\n /**\n * Outputs the cookie data in a merged format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome'\n * }\n * }\n * ]);\n * // Outputs:\n * // example.com:\n * // session=abc123\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(renderCookies(results, { format: \"merged\" }));\n }\n}\n","import { DefaultOutputHandler } from \"./DefaultOutputHandler\";\nimport { DumpOutputHandler } from \"./DumpOutputHandler\";\nimport { GroupedDumpOutputHandler } from \"./GroupedDumpOutputHandler\";\nimport { GroupedRenderOutputHandler } from \"./GroupedRenderOutputHandler\";\nimport { JsonOutputHandler } from \"./JsonOutputHandler\";\nimport { RenderOutputHandler } from \"./RenderOutputHandler\";\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Factory for creating appropriate output handlers based on command-line arguments\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Get JSON output handler\n * const jsonHandler = factory.getHandler({ output: 'json' });\n *\n * // Get dump output handler\n * const dumpHandler = factory.getHandler({ dump: true });\n *\n * // Get default handler when no matching handler found\n * const defaultHandler = factory.getHandler({});\n * ```\n */\nexport class OutputHandlerFactory {\n private readonly handlers: OutputHandler[];\n private readonly validOutputFormats = [\"json\"] as const;\n\n /**\n * Initializes the factory with all available output handlers\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n * // Factory is initialized with:\n * // - DumpOutputHandler\n * // - GroupedDumpOutputHandler\n * // - RenderOutputHandler\n * // - GroupedRenderOutputHandler\n * // - JsonOutputHandler\n * // - DefaultOutputHandler\n * ```\n */\n public constructor() {\n this.handlers = [\n new DumpOutputHandler(),\n new GroupedDumpOutputHandler(),\n new RenderOutputHandler(),\n new GroupedRenderOutputHandler(),\n new JsonOutputHandler(),\n new DefaultOutputHandler(),\n ];\n }\n\n /**\n * Validates the output format specified in arguments\n * @param args - The parsed command line arguments\n * @throws Error if an invalid output format is specified\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Valid format - no error\n * factory.validateOutputFormat({ output: 'json' });\n *\n * // Invalid format - throws error\n * try {\n * factory.validateOutputFormat({ output: 'invalid' });\n * } catch (error) {\n * console.error('Invalid output format'); // Error thrown\n * }\n * ```\n */\n private validateOutputFormat(args: ParsedArgs): void {\n if (\n args.output !== undefined &&\n !this.validOutputFormats.includes(\n args.output as (typeof this.validOutputFormats)[number],\n )\n ) {\n const validFormats = this.validOutputFormats.join(\", \");\n throw new Error(\n `Invalid output format: '${args.output}'. Valid formats are: ${validFormats}`,\n );\n }\n }\n\n /**\n * Returns the first handler that can handle the given arguments\n * @param args - The parsed command line arguments\n * @returns The first handler that can handle the arguments, or DefaultOutputHandler if none found\n * @throws Error if an invalid output format is specified\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Get JSON handler\n * const jsonHandler = factory.getHandler({ output: 'json' });\n *\n * // Get grouped render handler\n * const groupedHandler = factory.getHandler({ 'render-grouped': true });\n *\n * // Get dump handler\n * const dumpHandler = factory.getHandler({ dump: true });\n *\n * // Get default handler when no specific format requested\n * const defaultHandler = factory.getHandler({});\n * ```\n */\n public getHandler(args: ParsedArgs): OutputHandler {\n this.validateOutputFormat(args);\n\n return (\n this.handlers.find((handler) => handler.canHandle(args)) ??\n new DefaultOutputHandler()\n );\n }\n}\n","import type {\n CookieQueryOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\n\nimport type { CookieQueryStrategy } from \"./CookieStrategyFactory\";\n\n/**\n * Service for querying cookies using a strategy\n */\nexport class CookieQueryService {\n /**\n * Creates a new CookieQueryService instance\n * @param strategy - The strategy to use for querying cookies\n */\n public constructor(private readonly strategy: CookieQueryStrategy) {}\n\n /**\n * Queries cookies from the strategy with options\n * @param spec - The cookie specification to query for\n * @param options - Query options including limit, removeExpired, store path, and force flag\n * @returns Array of exported cookies\n */\n public async queryCookies(\n spec: CookieSpec,\n options?: CookieQueryOptions,\n ): Promise<ExportedCookie[]> {\n return this.strategy.queryCookies(\n spec.name,\n spec.domain,\n options?.store,\n options?.force,\n );\n }\n}\n","/**\n * Browser detection utilities for cookie store files\n * @module BrowserDetector\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"BrowserDetector\");\n\n/**\n * Supported browser types for cookie extraction\n */\nexport type BrowserType =\n | \"chrome\"\n | \"firefox\"\n | \"safari\"\n | \"edge\"\n | \"arc\"\n | \"opera\"\n | \"opera-gx\";\n\n/**\n * Magic bytes for Safari binary cookies format\n */\nconst SAFARI_MAGIC_BYTES = {\n c: 0x63, // 'c'\n o1: 0x6f, // 'o'\n o2: 0x6f, // 'o'\n k: 0x6b, // 'k'\n};\n\n/**\n * Browser detection patterns for cookie store files\n */\nconst BROWSER_PATTERNS: Array<{\n browser: BrowserType;\n pattern: (filename: string) => boolean;\n}> = [\n {\n browser: \"firefox\",\n pattern: (filename) => filename.includes(\"cookies.sqlite\"),\n },\n {\n browser: \"chrome\",\n pattern: (filename) =>\n filename.includes(\"cookies\") && filename.endsWith(\".db\"),\n },\n {\n browser: \"safari\",\n pattern: (filename) => filename.includes(\"cookies.binarycookies\"),\n },\n];\n\n/**\n * Checks if a file contains Safari binary cookies magic bytes\n * @param storePath - Path to the cookie store file\n * @returns True if the file has Safari's binary cookie format signature\n */\nexport function checkSafariMagicBytes(storePath: string): boolean {\n try {\n const buffer = readFileSync(storePath);\n // Safari binary cookies start with \"cook\" magic bytes\n return (\n buffer.length >= 4 &&\n buffer[0] === SAFARI_MAGIC_BYTES.c &&\n buffer[1] === SAFARI_MAGIC_BYTES.o1 &&\n buffer[2] === SAFARI_MAGIC_BYTES.o2 &&\n buffer[3] === SAFARI_MAGIC_BYTES.k\n );\n } catch (error) {\n logger.debug(\"Failed to read file for magic bytes check\", {\n path: storePath,\n error,\n });\n return false;\n }\n}\n\n/**\n * Detects browser type from filename patterns\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n */\nexport function detectBrowserFromFilename(\n storePath: string,\n): BrowserType | undefined {\n const filename = storePath.toLowerCase();\n\n for (const { browser, pattern } of BROWSER_PATTERNS) {\n if (pattern(filename)) {\n logger.debug(\"Detected browser from filename\", {\n browser,\n filename,\n });\n return browser;\n }\n }\n\n return undefined;\n}\n\n/**\n * Detects the browser type from a cookie store file\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n */\nexport function detectBrowserFromStore(\n storePath: string,\n): BrowserType | undefined {\n if (!storePath || !existsSync(storePath)) {\n logger.debug(\"Store path does not exist\", { storePath });\n return undefined;\n }\n\n // Check for Safari binary cookies format first (most specific)\n if (checkSafariMagicBytes(storePath)) {\n logger.info(\"Detected Safari binary cookies from magic bytes\");\n return \"safari\";\n }\n\n // Check filename patterns\n const detectedBrowser = detectBrowserFromFilename(storePath);\n if (detectedBrowser) {\n logger.info(\"Detected browser from filename pattern\", {\n browser: detectedBrowser,\n });\n return detectedBrowser;\n }\n\n logger.debug(\"Could not detect browser type from store\", { storePath });\n return undefined;\n}\n\n/**\n * Validates if a string is a known browser type\n * @param browser - The browser string to validate\n * @returns True if the browser is a known type\n */\nexport function isValidBrowserType(browser: string): browser is BrowserType {\n const validTypes: BrowserType[] = [\n \"chrome\",\n \"firefox\",\n \"safari\",\n \"edge\",\n \"arc\",\n \"opera\",\n \"opera-gx\",\n ];\n return validTypes.includes(browser as BrowserType);\n}\n\n/**\n * Gets a human-readable name for a browser type\n * @param browser - The browser type\n * @returns The display name for the browser\n */\nexport function getBrowserDisplayName(browser: BrowserType): string {\n const displayNames: Record<BrowserType, string> = {\n chrome: \"Google Chrome\",\n firefox: \"Mozilla Firefox\",\n safari: \"Safari\",\n edge: \"Microsoft Edge\",\n arc: \"Arc\",\n opera: \"Opera\",\n \"opera-gx\": \"Opera GX\",\n };\n return displayNames[browser];\n}\n","/**\n * Factory for creating browser-specific cookie query strategies\n * @module StrategyFactory\n */\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport { ArcCookieQueryStrategy } from \"./arc/ArcCookieQueryStrategy\";\nimport type { BaseCookieQueryStrategy } from \"./BaseCookieQueryStrategy\";\nimport {\n type BrowserType,\n detectBrowserFromStore,\n isValidBrowserType,\n} from \"./BrowserDetector\";\nimport { ChromeCookieQueryStrategy } from \"./chrome/ChromeCookieQueryStrategy\";\nimport { CompositeCookieQueryStrategy } from \"./CompositeCookieQueryStrategy\";\nimport { EdgeCookieQueryStrategy } from \"./edge/EdgeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"./firefox/FirefoxCookieQueryStrategy\";\nimport { OperaCookieQueryStrategy } from \"./opera/OperaCookieQueryStrategy\";\nimport { OperaGXCookieQueryStrategy } from \"./opera/OperaGXCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"./safari/SafariCookieQueryStrategy\";\n\n/**\n * A strategy that can query cookies - either a single browser or composite\n */\nexport type AnyQueryStrategy =\n | BaseCookieQueryStrategy\n | CompositeCookieQueryStrategy;\n\nconst logger = createTaggedLogger(\"StrategyFactory\");\n\n/**\n * Strategy constructor type\n */\ntype StrategyConstructor = new (profile?: string) => BaseCookieQueryStrategy;\n\n/**\n * Registry of browser strategies\n */\nconst STRATEGY_REGISTRY: Record<BrowserType, StrategyConstructor> = {\n safari: SafariCookieQueryStrategy,\n firefox: FirefoxCookieQueryStrategy,\n chrome: ChromeCookieQueryStrategy,\n edge: EdgeCookieQueryStrategy,\n arc: ArcCookieQueryStrategy,\n opera: OperaCookieQueryStrategy,\n \"opera-gx\": OperaGXCookieQueryStrategy,\n};\n\n/**\n * Creates a strategy for the specified browser\n * @param browser - The browser to create a strategy for\n * @returns A cookie query strategy for the specified browser\n */\nexport function createBrowserStrategy(\n browser: BrowserType,\n): BaseCookieQueryStrategy {\n const Strategy = STRATEGY_REGISTRY[browser];\n if (!Strategy) {\n logger.warn(\"Unknown browser type, falling back to default\", {\n browser,\n });\n // Return Chrome as a default single-browser strategy instead of composite\n return new ChromeCookieQueryStrategy();\n }\n\n logger.debug(\"Creating browser strategy\", { browser });\n return new Strategy();\n}\n\n/**\n * Creates a composite strategy with all browser strategies\n * @returns A composite strategy that queries all browsers\n */\nexport function createCompositeStrategy(): CompositeCookieQueryStrategy {\n logger.debug(\"Creating composite strategy with all browsers\");\n // Use the existing CompositeCookieQueryStrategy which already knows\n // how to combine all browser strategies\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new EdgeCookieQueryStrategy(),\n new ArcCookieQueryStrategy(),\n new OperaCookieQueryStrategy(),\n new OperaGXCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n return new CompositeCookieQueryStrategy(strategies);\n}\n\n/**\n * Creates a composite strategy with selected browser strategies\n * @param browsers - Array of browser types to include\n * @returns A composite strategy that queries selected browsers\n */\nexport function createSelectiveCompositeStrategy(\n browsers: BrowserType[],\n): CompositeCookieQueryStrategy {\n logger.debug(\"Creating selective composite strategy\", { browsers });\n\n const strategies = browsers\n .map((browser) => {\n const Strategy = STRATEGY_REGISTRY[browser];\n return Strategy ? new Strategy() : null;\n })\n .filter(\n (strategy): strategy is BaseCookieQueryStrategy => strategy !== null,\n );\n\n if (strategies.length === 0) {\n logger.warn(\"No valid strategies found, using full composite\");\n return createCompositeStrategy();\n }\n\n return new CompositeCookieQueryStrategy(strategies);\n}\n\n/**\n * Creates a strategy based on browser type or store path\n * @param options - Options for strategy creation\n * @param options.browser - Optional browser type\n * @param options.storePath - Optional path to a cookie store file\n * @param options.profile\n * @returns A cookie query strategy\n */\nexport function createStrategy(options?: {\n browser?: string;\n storePath?: string;\n profile?: string;\n}): AnyQueryStrategy {\n const { browser, storePath, profile } = options || {};\n\n // If store path is provided, try to detect the browser type\n if (storePath && !browser) {\n const detectedBrowser = detectBrowserFromStore(storePath);\n if (detectedBrowser) {\n logger.info(\"Auto-detected browser from store path\", {\n browser: detectedBrowser,\n storePath,\n });\n return createBrowserStrategy(detectedBrowser);\n }\n }\n\n // If browser is specified, normalize to lowercase and check if valid\n if (browser) {\n const normalizedBrowser = browser.toLowerCase();\n if (isValidBrowserType(normalizedBrowser)) {\n // Special handling for Chrome with profile\n if (normalizedBrowser === \"chrome\" && profile) {\n logger.debug(\"Creating Chrome strategy with profile\", { profile });\n return new ChromeCookieQueryStrategy(profile);\n }\n return createBrowserStrategy(normalizedBrowser);\n }\n // Log warning for invalid browser type\n logger.warn(\"Invalid browser type specified\", { browser });\n }\n\n // Default to composite strategy\n logger.debug(\"Creating composite strategy as default\");\n return createCompositeStrategy();\n}\n\n/**\n * Gets all available browser types\n * @returns Array of available browser types\n */\nexport function getAvailableBrowsers(): BrowserType[] {\n return Object.keys(STRATEGY_REGISTRY) as BrowserType[];\n}\n\n/**\n * Checks if a browser is supported\n * @param browser - The browser to check\n * @returns True if the browser is supported\n */\nexport function isBrowserSupported(browser: string): boolean {\n return isValidBrowserType(browser);\n}\n","import fg from \"fast-glob\";\n\nimport {\n type ChromiumBrowser,\n getChromiumBrowserPath,\n} from \"../chrome/ChromiumBrowsers\";\n\nimport { BaseChromiumCookieQueryStrategy } from \"./BaseChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Chromium-based browsers (Chrome, Brave, Edge, etc.)\n * This class extends the BaseChromiumCookieQueryStrategy with browser-specific path discovery.\n * @example\n * ```typescript\n * const strategy = new ChromiumCookieQueryStrategy('brave');\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromiumCookieQueryStrategy extends BaseChromiumCookieQueryStrategy {\n private readonly browser: ChromiumBrowser;\n\n /**\n * Creates a new instance of ChromiumCookieQueryStrategy\n * @param browser - The Chromium-based browser to query (chrome, brave, edge, etc.)\n */\n public constructor(browser: ChromiumBrowser = \"chrome\") {\n const browserName = browser.charAt(0).toUpperCase() + browser.slice(1);\n super(`${browserName}CookieQueryStrategy`, browserName, browser);\n this.browser = browser;\n }\n\n /**\n * Get browser-specific cookie file paths\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected getCookieFilePaths(store?: string): string[] {\n if (store !== undefined && store !== \"\") {\n return [store];\n }\n\n try {\n const browserPath = getChromiumBrowserPath(this.browser);\n const files = fg.sync(\"./**/Cookies\", {\n cwd: browserPath,\n absolute: true,\n });\n\n this.logger.debug(\n `Found ${files.length} cookie files for ${this.browser}`,\n );\n\n return files;\n } catch (error) {\n this.logger.warn(`Failed to find ${this.browser} cookie files`, {\n error: this.getErrorMessage(error),\n });\n return [];\n }\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\n/**\n * Chromium browser configuration and path management\n * Supports Chrome, Chromium, Brave, Edge, Opera, Vivaldi, and Whale browsers\n * across Windows, macOS, and Linux platforms\n */\n\n/**\n * Supported Chromium-based browsers\n */\nexport const CHROMIUM_BASED_BROWSERS = [\n \"chrome\",\n \"chromium\",\n \"brave\",\n \"edge\",\n \"arc\",\n \"opera\",\n \"opera-gx\",\n \"vivaldi\",\n \"whale\",\n] as const;\n\n/**\n * Type representing all supported Chromium-based browsers.\n * This includes Chrome, Edge, Brave, Arc, Opera, and other Chromium derivatives.\n */\nexport type ChromiumBrowser = (typeof CHROMIUM_BASED_BROWSERS)[number];\n\n/**\n * Browser directory configuration for different platforms\n */\ninterface BrowserPaths {\n windows: string;\n macos: string;\n linux: string;\n}\n\n/**\n * Get the browser configuration directory for a specific browser and platform\n * @param browser - The chromium browser type\n * @returns The path to the browser's configuration directory\n * @throws {Error} If the user home directory cannot be determined or platform is unsupported\n */\nexport function getChromiumBrowserPath(browser: ChromiumBrowser): string {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n assertPlatformSupported();\n const currentPlatform = getPlatform();\n\n const browserPaths: Record<ChromiumBrowser, BrowserPaths> = {\n chrome: {\n windows: join(home, \"AppData\", \"Local\", \"Google\", \"Chrome\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\"),\n linux: join(home, \".config\", \"google-chrome\"),\n },\n chromium: {\n windows: join(home, \"AppData\", \"Local\", \"Chromium\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Chromium\"),\n linux: join(home, \".config\", \"chromium\"),\n },\n brave: {\n windows: join(\n home,\n \"AppData\",\n \"Local\",\n \"BraveSoftware\",\n \"Brave-Browser\",\n \"User Data\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"BraveSoftware\",\n \"Brave-Browser\",\n ),\n linux: join(home, \".config\", \"BraveSoftware\", \"Brave-Browser\"),\n },\n edge: {\n windows: join(home, \"AppData\", \"Local\", \"Microsoft\", \"Edge\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Microsoft Edge\"),\n linux: join(home, \".config\", \"microsoft-edge\"),\n },\n arc: {\n windows: join(home, \"AppData\", \"Local\", \"Arc\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Arc\", \"User Data\"),\n linux: join(home, \".config\", \"arc\"),\n },\n opera: {\n windows: join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Opera Software\",\n \"Opera Stable\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.Opera\",\n ),\n linux: join(home, \".config\", \"opera\"),\n },\n \"opera-gx\": {\n windows: join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Opera Software\",\n \"Opera GX Stable\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.OperaGX\",\n ),\n linux: join(home, \".config\", \"opera-gx\"),\n },\n vivaldi: {\n windows: join(home, \"AppData\", \"Local\", \"Vivaldi\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Vivaldi\"),\n linux: join(home, \".config\", \"vivaldi\"),\n },\n whale: {\n windows: join(\n home,\n \"AppData\",\n \"Local\",\n \"Naver\",\n \"Naver Whale\",\n \"User Data\",\n ),\n macos: join(home, \"Library\", \"Application Support\", \"Naver\", \"Whale\"),\n linux: join(home, \".config\", \"naver-whale\"),\n },\n };\n\n const paths = browserPaths[browser];\n\n switch (currentPlatform) {\n case \"win32\":\n return paths.windows;\n case \"darwin\":\n return paths.macos;\n case \"linux\":\n return paths.linux;\n default:\n throw new Error(`Platform ${currentPlatform} is not supported`);\n }\n}\n\n/**\n * Get all Chromium browser paths for the current platform\n * @returns Record mapping browser names to their configuration directory paths\n */\nexport function getAllChromiumBrowserPaths(): Record<ChromiumBrowser, string> {\n const result: Partial<Record<ChromiumBrowser, string>> = {};\n\n for (const browser of CHROMIUM_BASED_BROWSERS) {\n try {\n result[browser] = getChromiumBrowserPath(browser);\n } catch {\n // Skip browsers that fail (e.g., unsupported platform)\n }\n }\n\n return result as Record<ChromiumBrowser, string>;\n}\n","import { getPlatform, isPlatformSupported } from \"@utils/platformUtils\";\nimport { isChromeRunning } from \"@utils/ProcessDetector\";\n\nimport type {\n CookieRow,\n CookieSpec,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { chromeTimestampToDate } from \"../../../utils/chromeDates\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\nimport type { ChromiumBrowser } from \"../chrome/ChromiumBrowsers\";\nimport { decrypt } from \"../chrome/decrypt\";\nimport { getChromiumPassword } from \"../chrome/getChromiumPassword\";\nimport { CookieQueryBuilder } from \"../sql/CookieQueryBuilder\";\nimport { getGlobalConnectionManager } from \"../sql/DatabaseConnectionManager\";\nimport { getGlobalQueryMonitor } from \"../sql/QueryMonitor\";\n\ninterface DecryptionContext {\n file: string;\n password: string | Buffer;\n browser: string;\n metaVersion?: number;\n}\n\n/**\n * Create an exported cookie object\n * @param domain - Cookie domain\n * @param name - Cookie name\n * @param value - Cookie value\n * @param expiry - Cookie expiry timestamp\n * @param file - Source file path\n * @param browser - Browser name\n * @param decrypted - Whether the cookie was decrypted\n * @returns ExportedCookie object\n */\nexport function createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n browser: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: chromeTimestampToDate(expiry),\n meta: {\n file,\n browser,\n decrypted,\n },\n };\n}\n\n/**\n * Base strategy for querying cookies from Chromium-based browsers.\n * This abstract class provides shared logic for Chrome, Chromium, Brave, Edge, etc.\n */\nexport abstract class BaseChromiumCookieQueryStrategy extends BaseCookieQueryStrategy {\n protected lockHandler: BrowserLockHandler;\n protected browserDisplayName: string;\n protected browserType: ChromiumBrowser;\n\n /**\n * Creates a new instance of BaseChromiumCookieQueryStrategy\n * @param strategyName - Name of the strategy for logging\n * @param browserName - Display name of the browser\n * @param browserType - The Chromium browser type for password retrieval\n */\n public constructor(\n strategyName: string,\n browserName: string,\n browserType: ChromiumBrowser = \"chrome\",\n ) {\n super(strategyName, \"Chrome\"); // Use \"Chrome\" for base class compatibility\n this.browserDisplayName = browserName;\n this.browserType = browserType;\n this.lockHandler = new BrowserLockHandler(this.logger, \"Chrome\");\n }\n\n /**\n * Batch query cookies for multiple specs\n * Optimized to execute combined SQL queries per database file\n * @param specs - Array of cookie specifications\n * @returns Array of exported cookies\n */\n async batchQueryCookies(specs: CookieSpec[]): Promise<ExportedCookie[]> {\n if (!this.isPlatformSupported()) {\n return [];\n }\n\n const files = this.getCookieFiles();\n if (files.length === 0) {\n this.logger.debug(`No ${this.browserDisplayName} cookie files found`);\n return [];\n }\n\n try {\n const password = await getChromiumPassword(this.browserType);\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n const fileResults = await this.processBatchFile(file, specs, password);\n results.push(...fileResults);\n }\n\n return results;\n } catch (error) {\n this.logger.error(\n `Failed to get ${this.browserDisplayName} password for batch query`,\n {\n error: this.getErrorMessage(error),\n },\n );\n return [];\n }\n }\n\n /**\n * Process a batch of specs for a single cookie file\n * @param file - Cookie file path\n * @param specs - Array of cookie specifications\n * @param password - Decryption password\n * @returns Array of exported cookies\n */\n protected async processBatchFile(\n file: string,\n specs: CookieSpec[],\n password: string | Buffer,\n ): Promise<ExportedCookie[]> {\n try {\n const connectionManager = getGlobalConnectionManager();\n const monitor = getGlobalQueryMonitor();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n\n // Convert CookieSpec to CookieQueryOptions\n const queryOptions = specs.map((spec) => ({\n name: spec.name,\n domain: spec.domain,\n browser: \"chrome\" as const,\n }));\n\n const queryConfig = queryBuilder.buildBatchSelectQuery(queryOptions);\n\n const encryptedCookies = await connectionManager.executeQuery(\n file,\n (db) => {\n const rows = monitor.executeQuery<{\n encrypted_value: Buffer;\n name: string;\n domain: string;\n expiry: number;\n }>(db, queryConfig.sql, queryConfig.params, file);\n\n return rows.map(\n (row): CookieRow => ({\n name: row.name,\n domain: row.domain,\n value: row.encrypted_value,\n expiry: row.expiry,\n }),\n );\n },\n queryConfig.description || queryConfig.sql,\n );\n\n const metaVersion = await this.getMetaVersion(file);\n const context: DecryptionContext = {\n file,\n password,\n browser: this.browserDisplayName,\n metaVersion,\n };\n\n const results = await Promise.allSettled(\n encryptedCookies.map(async (cookie) =>\n this.processCookie(cookie, context),\n ),\n );\n\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie> =>\n result.status === \"fulfilled\",\n )\n .map((result) => result.value);\n } catch (error) {\n this.logger.warn(\n `Error batch processing ${this.browserDisplayName} cookie file ${file}`,\n {\n error: this.getErrorMessage(error),\n file,\n specsCount: specs.length,\n },\n );\n return [];\n }\n }\n\n /**\n * Get cookie file paths for the browser\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected abstract getCookieFilePaths(store?: string): string[];\n\n /**\n * Get the browser-specific display name\n * @returns Browser display name\n */\n protected getBrowserName(): string {\n return this.browserDisplayName;\n }\n\n /**\n * Executes the Chromium-specific query logic\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings\n * @returns A promise that resolves to an array of exported cookies\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n if (!this.isPlatformSupported()) {\n return [];\n }\n\n const files = this.getCookieFiles(store);\n if (files.length === 0) {\n this.logger.debug(`No ${this.browserDisplayName} cookie files found`);\n return [];\n }\n\n try {\n const password = await getChromiumPassword(this.browserType);\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n const fileResults = await this.processFileWithRetry(\n file,\n name,\n domain,\n password,\n force,\n );\n results.push(...fileResults);\n }\n\n return results;\n } catch (error) {\n this.logger.error(`Failed to get ${this.browserDisplayName} password`, {\n error: this.getErrorMessage(error),\n });\n return [];\n }\n }\n\n /**\n * Check if the current platform is supported\n * @returns True if platform is supported\n */\n protected isPlatformSupported(): boolean {\n if (!isPlatformSupported()) {\n this.logger.warn(\"Platform not supported\", {\n platform: getPlatform(),\n supportedPlatforms: [\"darwin\", \"win32\", \"linux\"],\n });\n return false;\n }\n return true;\n }\n\n /**\n * Get cookie files to process\n * @param store - Optional specific store path\n * @returns Array of file paths\n */\n protected getCookieFiles(store?: string): string[] {\n const cookieFiles = store ?? this.getCookieFilePaths();\n return Array.isArray(cookieFiles) ? cookieFiles : [cookieFiles];\n }\n\n /**\n * Convert error to string message\n * @param error - The error to convert\n * @returns Error message string\n */\n protected getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n }\n\n /**\n * Process a file with retry logic for lock conflicts\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @param force - Force processing\n * @returns Array of exported cookies\n */\n private async processFileWithRetry(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n return await this.processFile(file, name, domain, password);\n } catch (error) {\n const lockResult = await this.handleFileError(\n error,\n file,\n name,\n domain,\n force,\n );\n\n if (lockResult.resolved) {\n return this.retryAfterBrowserClose(\n file,\n name,\n domain,\n password,\n lockResult.shouldRelaunch,\n );\n }\n\n return [];\n }\n }\n\n /**\n * Handle file processing errors\n * @param error - The error that occurred\n * @param file - File path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param force - Whether to force operations\n * @returns Lock result indicating if resolved and should relaunch\n */\n private async handleFileError(\n error: unknown,\n file: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<{ resolved: boolean; shouldRelaunch: boolean }> {\n const processes = await isChromeRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n file,\n processes,\n force !== true,\n );\n\n if (!lockResult.resolved) {\n this.logger.warn(\n `Error reading ${this.browserDisplayName} cookie file ${file}`,\n {\n error: this.getErrorMessage(error),\n file,\n name,\n domain,\n },\n );\n }\n\n return lockResult;\n }\n\n /**\n * Retry after browser close\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @param shouldRelaunch - Whether to relaunch browser\n * @returns Array of exported cookies\n */\n private async retryAfterBrowserClose(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n shouldRelaunch: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\n `Retrying ${this.browserDisplayName} cookie extraction after browser close...`,\n );\n const cookies = await this.processFile(file, name, domain, password);\n this.logger.success(\n `Successfully extracted cookies after closing ${this.browserDisplayName}`,\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError) {\n this.logger.error(\n `Failed to extract cookies even after closing ${this.browserDisplayName}`,\n {\n error: this.getErrorMessage(retryError),\n file,\n },\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n }\n\n /**\n * Process a single cookie file\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @returns Array of exported cookies\n */\n protected async processFile(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n ): Promise<ExportedCookie[]> {\n try {\n // Use SQL utilities directly instead of getEncryptedChromeCookie\n const connectionManager = getGlobalConnectionManager();\n const monitor = getGlobalQueryMonitor();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n\n const queryConfig = queryBuilder.buildSelectQuery({\n name,\n domain,\n browser: \"chrome\",\n });\n\n const encryptedCookies = await connectionManager.executeQuery(\n file,\n (db) => {\n // The CookieQueryBuilder aliases columns, so we get 'domain' not 'host_key'\n const rows = monitor.executeQuery<{\n encrypted_value: Buffer;\n name: string;\n domain: string;\n expiry: number;\n }>(db, queryConfig.sql, queryConfig.params, file);\n\n // Transform to CookieRow format\n return rows.map(\n (row): CookieRow => ({\n name: row.name,\n domain: row.domain,\n value: row.encrypted_value,\n expiry: row.expiry,\n }),\n );\n },\n queryConfig.sql,\n );\n\n const metaVersion = await this.getMetaVersion(file);\n const context: DecryptionContext = {\n file,\n password,\n browser: this.browserDisplayName,\n metaVersion,\n };\n\n const results = await Promise.allSettled(\n encryptedCookies.map(async (cookie) =>\n this.processCookie(cookie, context),\n ),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n this.logger.error(\n `Failed to process ${this.browserDisplayName} cookie file`,\n {\n error: this.getErrorMessage(error),\n file,\n name,\n domain,\n },\n );\n return [];\n }\n }\n\n /**\n * Get meta version from Chrome database\n * @param file - Database file path\n * @returns Meta version number\n */\n protected async getMetaVersion(file: string): Promise<number> {\n try {\n const connectionManager = getGlobalConnectionManager();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n const metaQuery = queryBuilder.buildMetaQuery(\"version\");\n\n const metaResult = await connectionManager.executeQuery(\n file,\n (db) => {\n const stmt = db.prepare(metaQuery.sql);\n return stmt.get(...metaQuery.params) as { value: string } | undefined;\n },\n \"Get meta version\",\n );\n\n return metaResult ? Number.parseInt(metaResult.value, 10) : 0;\n } catch (error) {\n this.logger.debug(\"Could not retrieve meta version, defaulting to 0\", {\n error: this.getErrorMessage(error),\n });\n return 0;\n }\n }\n\n /**\n * Process a single cookie\n * @param cookie - Cookie row from database\n * @param context - Decryption context\n * @returns Exported cookie\n */\n protected async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(\n value,\n context.password,\n context.metaVersion,\n );\n\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n context.browser,\n true,\n );\n } catch (error) {\n this.logger.warn(`Failed to decrypt ${context.browser} cookie`, {\n error: this.getErrorMessage(error),\n });\n\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n context.browser,\n false,\n );\n }\n }\n}\n","import { getErrorMessage } from \"./errorUtils\";\nimport { execSimple } from \"./execSimple\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isWindows, getPlatform } from \"./platformUtils\";\n\nconst logger = createTaggedLogger(\"ProcessDetector\");\n\n/**\n * Parse a process line from ps output\n * @param line - The process line from ps output\n * @param defaultCommand - Default command name if parsing fails\n * @returns ProcessInfo if valid, null otherwise\n */\nfunction parseProcessLine(\n line: string,\n defaultCommand: string,\n): ProcessInfo | null {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n const parsedCommand = parts.slice(10).join(\" \");\n return {\n pid,\n command: parsedCommand !== \"\" ? parsedCommand : defaultCommand,\n details: line.trim(),\n };\n}\n\n/**\n * Parse a process line from Windows tasklist CSV output\n * @param line - Process line from tasklist /FO CSV\n * @param defaultCommand - Default command name if parsing fails\n * @returns ProcessInfo if valid, null otherwise\n */\nfunction parseWindowsProcessLine(\n line: string,\n defaultCommand: string,\n): ProcessInfo | null {\n // Windows tasklist CSV format: \"Image Name\",\"PID\",\"Session Name\",\"Session#\",\"Mem Usage\"\n // Example: \"firefox.exe\",\"1234\",\"Console\",\"1\",\"123,456 K\"\n const parts = line.split(\",\").map((p) => p.replace(/\"/g, \"\").trim());\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n return {\n pid,\n command: parts[0] ?? defaultCommand,\n details: line.trim(),\n };\n}\n\n/**\n * Information about a detected process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n /** Process name/command */\n command: string;\n /** Full process details */\n details: string;\n}\n\n/**\n * Generic browser process detection\n * @param browserName - Name of the browser to detect\n * @param grepPattern - Pattern to grep for in ps output\n * @returns Promise that resolves to array of process information\n */\nasync function detectBrowserProcesses(\n browserName: string,\n grepPattern: string,\n): Promise<ProcessInfo[]> {\n try {\n let command: string;\n\n if (isWindows()) {\n // On Windows, use tasklist or wmic to find processes\n // Map common browser names to Windows process names\n const windowsProcessMap: Record<string, string> = {\n firefox: \"firefox.exe\",\n chrome: \"chrome.exe\",\n \"google chrome\": \"chrome.exe\",\n chromium: \"chromium.exe\",\n safari: \"safari.exe\", // Won't exist on Windows but included for consistency\n edge: \"msedge.exe\",\n };\n\n const processName =\n windowsProcessMap[browserName.toLowerCase()] ??\n windowsProcessMap[grepPattern.toLowerCase()] ??\n `${browserName.toLowerCase()}.exe`;\n\n // Use tasklist which is available on all Windows versions\n command = `tasklist /FI \"IMAGENAME eq ${processName}\" /FO CSV | findstr /i \"${processName}\"`;\n } else {\n // Unix-like systems (macOS, Linux)\n command = `ps aux | grep -i '${grepPattern}' | grep -v grep`;\n }\n\n const { stdout } = await execSimple(command);\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const processes: ProcessInfo[] = [];\n const lines = stdout.split(\"\\n\").filter((line) => line.trim() !== \"\");\n\n for (const line of lines) {\n const processInfo = isWindows()\n ? parseWindowsProcessLine(line, browserName.toLowerCase())\n : parseProcessLine(line, browserName.toLowerCase());\n if (processInfo) {\n processes.push(processInfo);\n }\n }\n\n logger.debug(`${browserName} process detection completed`, {\n processCount: processes.length,\n processes: processes.map((p) => ({ pid: p.pid, command: p.command })),\n platform: getPlatform(),\n });\n\n return processes;\n } catch (error) {\n logger.debug(`Failed to detect ${browserName} processes`, {\n error: getErrorMessage(error),\n platform: getPlatform(),\n });\n return [];\n }\n}\n\n/**\n * Check if Firefox browser is currently running\n * @returns Promise that resolves to array of Firefox process information\n * @example\n * ```typescript\n * const firefoxProcesses = await isFirefoxRunning();\n * if (firefoxProcesses.length > 0) {\n * console.log('Firefox is running, consider closing it for reliable cookie access');\n * }\n * ```\n */\nexport async function isFirefoxRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\"Firefox\", \"firefox\");\n}\n\n/**\n * Check if Chrome browser is currently running\n * @returns Promise that resolves to array of Chrome process information\n */\nexport async function isChromeRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\"Chrome\", \"google chrome\\\\|chromium\");\n}\n\n/**\n * Check if Safari browser is currently running\n * @returns Promise that resolves to array of Safari process information\n */\nexport async function isSafariRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\n \"Safari\",\n \"/Applications/Safari.app/Contents/MacOS/Safari\",\n );\n}\n\n/**\n * Get user-friendly advice for browser conflicts\n * @param browserName - Name of the browser\n * @param processes - Array of detected processes\n * @returns User-friendly message with advice\n */\nexport function getBrowserConflictAdvice(\n browserName: string,\n processes: ProcessInfo[],\n): string {\n if (processes.length === 0) {\n return \"\";\n }\n\n const processCount = processes.length;\n const browserDisplayName =\n browserName.charAt(0).toUpperCase() + browserName.slice(1);\n\n return `${browserDisplayName} is currently running (${processCount} process${processCount > 1 ? \"es\" : \"\"} detected). For reliable cookie access, consider closing ${browserDisplayName} and trying again. Alternatively, use the --force flag to attempt access despite the lock.`;\n}\n","/**\n * Chrome date conversion utilities\n *\n * Chrome/Chromium stores timestamps as microseconds since 1601-01-01 00:00:00 UTC\n * JavaScript Date uses milliseconds since 1970-01-01 00:00:00 UTC\n */\n\n/**\n * The number of seconds between Chrome epoch (1601-01-01) and Unix epoch (1970-01-01)\n * This is 369 years worth of seconds\n */\nexport const CHROME_EPOCH_OFFSET_SECONDS = 11644473600;\n\n/**\n * Microseconds per second\n */\nexport const MICROSECONDS_PER_SECOND = 1000000;\n\n/**\n * Milliseconds per second\n */\nexport const MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * Converts a Chrome timestamp to a JavaScript Date object\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns JavaScript Date object or \"Infinity\" for session cookies, undefined for null/undefined\n */\nexport function chromeTimestampToDate(\n chromeTimestamp: number | undefined | null,\n): Date | \"Infinity\" | undefined {\n // Handle null or undefined\n if (chromeTimestamp === null || chromeTimestamp === undefined) {\n return undefined;\n }\n\n // Handle invalid numbers\n if (typeof chromeTimestamp !== \"number\" || Number.isNaN(chromeTimestamp)) {\n return undefined;\n }\n\n // Chrome uses 0 for session cookies\n if (chromeTimestamp <= 0) {\n return \"Infinity\";\n }\n\n // Convert Chrome timestamp to Unix timestamp\n const unixTimestampSeconds =\n chromeTimestamp / MICROSECONDS_PER_SECOND - CHROME_EPOCH_OFFSET_SECONDS;\n\n // Sanity check: Unix timestamp should be positive and reasonable\n // Max date: year 3000 (32503680000 seconds since Unix epoch)\n if (unixTimestampSeconds < 0 || unixTimestampSeconds > 32503680000) {\n // Treat unreasonable dates as session cookies\n return \"Infinity\";\n }\n\n // Convert to milliseconds for JavaScript Date\n return new Date(unixTimestampSeconds * MILLISECONDS_PER_SECOND);\n}\n\n/**\n * Converts a JavaScript Date to a Chrome timestamp\n * @param date - JavaScript Date object\n * @returns Microseconds since 1601-01-01 00:00:00 UTC\n */\nexport function dateToChromeTimestamp(date: Date): number {\n if (!(date instanceof Date) || Number.isNaN(date.getTime())) {\n return 0; // Session cookie\n }\n\n // Get Unix timestamp in seconds\n const unixTimestampSeconds = date.getTime() / MILLISECONDS_PER_SECOND;\n\n // Convert to Chrome timestamp\n const chromeTimestampSeconds =\n unixTimestampSeconds + CHROME_EPOCH_OFFSET_SECONDS;\n\n // Convert to microseconds\n return chromeTimestampSeconds * MICROSECONDS_PER_SECOND;\n}\n\n/**\n * Checks if a Chrome timestamp represents a session cookie\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns True if this is a session cookie (no expiry)\n */\nexport function isChromeSessionCookie(\n chromeTimestamp: number | undefined | null,\n): boolean {\n return (\n chromeTimestamp === null ||\n chromeTimestamp === undefined ||\n chromeTimestamp === 0 ||\n (typeof chromeTimestamp === \"number\" && chromeTimestamp <= 0) ||\n // Far future dates (like year 4000) are treated as session cookies by Chrome\n (typeof chromeTimestamp === \"number\" &&\n chromeTimestamp >= 64092211200 * MICROSECONDS_PER_SECOND)\n );\n}\n\n/**\n * Formats a Chrome timestamp for display\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns Human-readable string representation\n */\nexport function formatChromeTimestamp(\n chromeTimestamp: number | undefined | null,\n): string {\n if (isChromeSessionCookie(chromeTimestamp)) {\n return \"Session\";\n }\n\n const date = chromeTimestampToDate(chromeTimestamp);\n\n if (date === undefined) {\n return \"Session\";\n }\n\n if (date === \"Infinity\") {\n return \"Session\";\n }\n\n return date.toISOString();\n}\n","import { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../types/schemas\";\n\n// Create a simple fallback logger for tests\nconst fallbackLogger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n debug: () => {},\n success: () => {},\n fatal: () => {},\n log: () => {},\n};\n\n/**\n * Base class for cookie query strategies.\n * Provides common functionality and standardized error handling for browser-specific implementations.\n * @implements {CookieQueryStrategy}\n * @abstract\n */\nexport abstract class BaseCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * Logger instance for this strategy\n * @protected\n */\n protected readonly logger;\n\n /**\n * Creates a new instance of BaseCookieQueryStrategy\n * @param strategyName - The name of the strategy for logging purposes\n * @param browserName - The name of the browser this strategy is for\n */\n public constructor(\n strategyName: string,\n public readonly browserName: BrowserName,\n ) {\n const taggedLogger = createTaggedLogger(strategyName);\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/strict-boolean-expressions\n this.logger = taggedLogger || fallbackLogger;\n }\n\n /**\n * Queries cookies from the browser's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain, store, force });\n return await this.executeQuery(name, domain, store, force);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to query cookies\", {\n error: error.message,\n browser: this.browserName,\n strategy: this.constructor.name,\n name,\n domain,\n store,\n force,\n });\n } else {\n this.logger.error(\"Failed to query cookies\", {\n error: String(error),\n browser: this.browserName,\n strategy: this.constructor.name,\n name,\n domain,\n store,\n force,\n });\n }\n return [];\n }\n }\n\n /**\n * Executes the browser-specific query logic\n * @abstract\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n * @protected\n */\n protected abstract executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]>;\n}\n","import { exec } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promisify } from \"node:util\";\n\nimport type { BrowserName } from \"../types/schemas\";\n\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isMacOS } from \"./platformUtils\";\n\n// Re-export BrowserName from schemas for backward compatibility\n/**\n *\n */\nexport type { BrowserName } from \"../types/schemas\";\n\nconst execAsync = promisify(exec);\nconst logger = createTaggedLogger(\"BrowserControl\");\n\n/**\n * Check if the current environment supports interactive prompts\n * @returns True if environment can handle interactive prompts\n */\nfunction isInteractiveEnvironment(): boolean {\n const isCI = process.env.CI === \"true\" || process.env.CI === \"1\";\n const isTest =\n process.env.NODE_ENV === \"test\" || process.env.JEST_WORKER_ID !== undefined;\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n\n return hasTTY && !isCI && !isTest;\n}\n\n/**\n *\n */\nexport interface BrowserControlOptions {\n force?: boolean;\n interactive?: boolean;\n}\n\n/**\n * Map of browser names to their macOS application names\n * Only includes browsers that can be controlled on macOS\n */\nconst BROWSER_APP_NAMES: Partial<Record<BrowserName, string>> = {\n Firefox: \"Firefox\",\n Chrome: \"Google Chrome\",\n Safari: \"Safari\",\n};\n\n/**\n * Check if a browser is running on macOS\n * @param browserName - Name of the browser to check\n * @returns Promise that resolves to true if browser is running\n */\nasync function isBrowserRunningMacOS(\n browserName: BrowserName,\n): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return false;\n }\n const script = `tell application \"System Events\" to (name of processes) contains \"${appName}\"`;\n const { stdout } = await execAsync(`osascript -e '${script}'`);\n return stdout.trim() === \"true\";\n } catch (error) {\n logger.debug(\"Failed to check if browser is running\", {\n browserName,\n error,\n });\n return false;\n }\n}\n\n/**\n * Gracefully quit a browser on macOS\n * @param browserName - Name of the browser to quit\n * @returns Promise that resolves to true if browser was quit successfully\n */\nasync function quitBrowserMacOS(browserName: BrowserName): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return false;\n }\n\n // First, try to quit gracefully\n const quitScript = `tell application \"${appName}\" to quit`;\n await execAsync(`osascript -e '${quitScript}'`);\n\n // Wait a moment for the browser to quit\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n // Check if it's still running\n const stillRunning = await isBrowserRunningMacOS(browserName);\n if (!stillRunning) {\n logger.info(\"Browser quit successfully\", { browserName });\n return true;\n }\n\n logger.warn(\"Browser did not quit gracefully\", { browserName });\n return false;\n } catch (error) {\n logger.error(\"Failed to quit browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Save open tabs in browser before closing (macOS only)\n * This will attempt to save the session so tabs can be restored\n * @param browserName - Name of the browser\n * @returns Promise that resolves when tabs are saved\n */\nasync function saveBrowserSessionMacOS(\n browserName: BrowserName,\n): Promise<void> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return;\n }\n\n if (browserName === \"Firefox\") {\n // Firefox: Use keyboard shortcut to save session (Cmd+Shift+D to bookmark all tabs)\n const script = `\n tell application \"${appName}\"\n activate\n end tell\n tell application \"System Events\"\n keystroke \"d\" using {command down, shift down}\n delay 0.5\n key code 36\n end tell\n `;\n await execAsync(`osascript -e '${script}'`);\n logger.debug(\"Attempted to save Firefox session\", { browserName });\n } else if (browserName === \"Chrome\") {\n // Chrome will restore tabs automatically if quit gracefully\n logger.debug(\"Chrome will restore tabs automatically\", { browserName });\n } else {\n // Safari will restore tabs if quit gracefully\n logger.debug(\"Safari will restore tabs automatically\", { browserName });\n }\n } catch (error) {\n logger.debug(\"Failed to save browser session\", { browserName, error });\n }\n}\n\n/**\n * Prompt user for confirmation before closing browser\n * @param browserName - Name of the browser\n * @returns Promise that resolves to true if user confirms\n */\nasync function promptUserConfirmation(\n browserName: BrowserName,\n): Promise<boolean> {\n // Check if we're in a TTY-capable environment\n if (!isInteractiveEnvironment()) {\n logger.debug(\"Non-interactive environment detected, skipping prompt\", {\n browserName,\n CI: process.env.CI,\n NODE_ENV: process.env.NODE_ENV,\n JEST_WORKER_ID: process.env.JEST_WORKER_ID,\n stdin_tty: process.stdin.isTTY,\n stdout_tty: process.stdout.isTTY,\n });\n return false;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `\\n⚠️ ${browserName} is currently running and blocking cookie access.\\n` +\n `Would you like to close ${browserName}? Your tabs will be restored when you reopen it. (y/N): `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n },\n );\n });\n}\n\n/**\n * Relaunch a browser after it has been closed\n * @param browserName - Name of the browser to relaunch\n * @returns Promise that resolves to true if browser was relaunched\n */\nasync function relaunchBrowserMacOS(\n browserName: BrowserName,\n): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n\n // Launch the browser\n const launchScript = `tell application \"${appName}\" to activate`;\n await execAsync(`osascript -e '${launchScript}'`);\n\n // Give it a moment to start\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n // Check if it's running\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (isRunning) {\n logger.info(\"Browser relaunched successfully\", { browserName });\n return true;\n }\n\n logger.warn(\"Browser did not relaunch\", { browserName });\n return false;\n } catch (error) {\n logger.error(\"Failed to relaunch browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Attempt to close a browser gracefully\n * @param browserName - Name of the browser to close\n * @param options - Control options\n * @returns Promise that resolves to true if browser was closed\n */\nexport async function closeBrowserGracefully(\n browserName: BrowserName,\n options: BrowserControlOptions = {},\n): Promise<boolean> {\n if (!isMacOS()) {\n logger.debug(\"Browser control only supported on macOS\");\n return false;\n }\n\n try {\n // Check if browser is running\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (!isRunning) {\n logger.debug(\"Browser is not running\", { browserName });\n return true;\n }\n\n // If interactive mode, prompt user\n if (options.interactive === true && options.force !== true) {\n const confirmed = await promptUserConfirmation(browserName);\n if (!confirmed) {\n logger.info(\"User cancelled browser close\", { browserName });\n return false;\n }\n }\n\n // Try to save session first (for browsers that support it)\n await saveBrowserSessionMacOS(browserName);\n\n // Quit the browser\n const success = await quitBrowserMacOS(browserName);\n\n if (success) {\n logger.success(\n `${browserName} closed successfully. Tabs will be restored on next launch.`,\n );\n } else {\n logger.warn(\n `Failed to close ${browserName}. You may need to close it manually.`,\n );\n }\n\n return success;\n } catch (error) {\n logger.error(\"Failed to control browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Close browser, perform an action, then relaunch the browser\n * @param browserName - Name of the browser\n * @param action - Action to perform while browser is closed\n * @param options - Control options\n * @returns Promise that resolves to the result of the action\n */\nexport async function closeBrowserForAction<T>(\n browserName: BrowserName,\n action: () => Promise<T>,\n options: BrowserControlOptions = {},\n): Promise<T | null> {\n if (!isMacOS()) {\n logger.debug(\"Browser control only supported on macOS\");\n return null;\n }\n\n let browserWasClosed = false;\n\n try {\n // Check if browser is running\n const wasRunning = await isBrowserRunningMacOS(browserName);\n\n if (wasRunning) {\n // Close the browser\n browserWasClosed = await closeBrowserGracefully(browserName, options);\n\n if (!browserWasClosed) {\n logger.warn(\"Failed to close browser, attempting action anyway\");\n } else {\n // Wait for browser to fully close\n await waitForBrowserToClose(browserName, 5000);\n }\n }\n\n // Perform the action\n const result = await action();\n\n // Relaunch browser if we closed it\n if (wasRunning && browserWasClosed) {\n logger.info(`Relaunching ${browserName}...`);\n const relaunched = await relaunchBrowserMacOS(browserName);\n\n if (relaunched) {\n logger.success(\n `${browserName} has been relaunched with your tabs restored`,\n );\n } else {\n logger.warn(\n `Could not relaunch ${browserName} automatically. Please reopen it manually.`,\n );\n }\n }\n\n return result;\n } catch (error) {\n logger.error(\"Failed during browser action\", { browserName, error });\n\n // Try to relaunch browser if we closed it\n if (browserWasClosed) {\n await relaunchBrowserMacOS(browserName);\n }\n\n return null;\n }\n}\n\n/**\n * Wait for a browser to close\n * @param browserName - Name of the browser\n * @param maxWaitMs - Maximum time to wait in milliseconds\n * @returns Promise that resolves to true if browser closed within timeout\n */\nexport async function waitForBrowserToClose(\n browserName: BrowserName,\n maxWaitMs = 10000,\n): Promise<boolean> {\n if (!isMacOS()) {\n return false;\n }\n\n const startTime = Date.now();\n const checkInterval = 500;\n\n while (Date.now() - startTime < maxWaitMs) {\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (!isRunning) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n }\n\n return false;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport { errorMessageContains, getErrorMessage } from \"./errorUtils\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { getPlatform, isWindows } from \"./platformUtils\";\n\nconst execFileAsync = promisify(execFile);\nconst logger = createTaggedLogger(\"FileHandleDetector\");\n\n/**\n * Parse a fuser output line into FileHandleInfo\n * @param line - Line from fuser output\n * @returns FileHandleInfo or null if parsing fails\n */\nfunction parseFuserLine(line: string): FileHandleInfo | null {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n const result: FileHandleInfo = {\n pid: pid,\n command: parts[2] ?? \"unknown\",\n };\n\n const user = parts[0];\n if (user !== undefined && user !== \"\") {\n result.user = user;\n }\n\n const mode = parts[3];\n if (mode !== undefined && mode !== \"\") {\n result.mode = mode;\n }\n\n return result;\n}\n\n/**\n * Check if value is a valid process result object\n * @param value - Value to check\n * @returns True if valid process result\n */\nfunction isValidProcessResult(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"ProcessId\" in value &&\n \"ProcessName\" in value\n );\n}\n\n/**\n * Parse PowerShell output into FileHandleInfo array\n * @param stdout - PowerShell command output\n * @returns Array of FileHandleInfo\n */\nfunction parsePowerShellOutput(stdout: string): FileHandleInfo[] {\n const handles: FileHandleInfo[] = [];\n\n try {\n const parsed: unknown = JSON.parse(stdout);\n const results = Array.isArray(parsed) ? parsed : [parsed];\n\n for (const result of results) {\n if (!isValidProcessResult(result)) {\n continue;\n }\n\n const processId = result.ProcessId;\n const processName = result.ProcessName;\n\n if (typeof processId === \"string\" && processId !== \"\") {\n handles.push({\n command: typeof processName === \"string\" ? processName : \"unknown\",\n pid: Number.parseInt(processId, 10),\n });\n }\n }\n } catch (parseError) {\n logger.debug(\"Failed to parse PowerShell output\", {\n error: getErrorMessage(parseError),\n });\n }\n\n return handles;\n}\n\n/**\n * Information about a process holding a file handle\n */\nexport interface FileHandleInfo {\n /** Process ID */\n pid: number;\n /** Process name/command */\n command: string;\n /** User running the process */\n user?: string;\n /** File descriptor or handle type */\n fd?: string;\n /** Access mode (read, write, etc.) */\n mode?: string;\n}\n\n/**\n * Detect processes holding handles to a specific file using lsof\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithLsof(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // Use execFile instead of exec to prevent shell injection\n const { stdout } = await execFileAsync(\"lsof\", [filePath], {\n encoding: \"utf8\",\n });\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const lines = stdout.split(\"\\n\").slice(1); // Skip header\n const handles: FileHandleInfo[] = [];\n\n for (const line of lines) {\n const parts = line.trim().split(/\\s+/);\n const command = parts[0];\n const pidStr = parts[1];\n const user = parts[2];\n const fd = parts[3];\n\n if (\n command !== undefined &&\n command !== \"\" &&\n pidStr !== undefined &&\n pidStr !== \"\" &&\n parts.length >= 4\n ) {\n const pid = Number.parseInt(pidStr, 10);\n if (!Number.isNaN(pid)) {\n const handle: FileHandleInfo = {\n command,\n pid,\n };\n if (user !== undefined && user !== \"\") {\n handle.user = user;\n }\n if (fd !== undefined && fd !== \"\") {\n handle.fd = fd;\n handle.mode = fd.includes(\"w\") ? \"write\" : \"read\";\n }\n handles.push(handle);\n }\n }\n }\n\n logger.debug(\"Detected file handles with lsof\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n\n // Check if lsof is not found\n if (errorMessageContains(error, \"ENOENT\")) {\n logger.debug(\"lsof not available on this system\");\n } else if (errorMessageContains(error, \"No such file\")) {\n // File doesn't exist - return empty array\n logger.debug(\"File does not exist\", { file: filePath });\n } else {\n logger.debug(\"lsof detection failed\", { error: errorMessage });\n }\n\n return [];\n }\n}\n\n/**\n * Detect processes holding handles to a specific file using fuser\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithFuser(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // fuser outputs to stderr, not stdout\n // Use execFile to prevent shell injection\n const result = await execFileAsync(\"fuser\", [\"-v\", filePath], {\n encoding: \"utf8\",\n });\n\n // fuser writes to stderr even on success\n const output = result.stderr || result.stdout || \"\";\n\n if (output.trim() === \"\") {\n return [];\n }\n\n const handles: FileHandleInfo[] = [];\n const lines = output.split(\"\\n\").slice(1); // Skip header\n\n for (const line of lines) {\n const handle = parseFuserLine(line);\n if (handle) {\n handles.push(handle);\n }\n }\n\n logger.debug(\"Detected file handles with fuser\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n\n if (errorMessageContains(error, \"ENOENT\")) {\n logger.debug(\"fuser not available on this system\");\n } else {\n logger.debug(\"fuser detection failed\", { error: errorMessage });\n }\n\n return [];\n }\n}\n\n/**\n * Windows-specific handle detection using PowerShell\n * SECURITY: Properly escapes file path for PowerShell\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectOnWindows(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // Escape single quotes in the file path for PowerShell\n const escapedPath = filePath.replace(/'/g, \"''\");\n\n // Use Get-Process with error handling\n const psScript = `\n $ErrorActionPreference = 'SilentlyContinue'\n $handles = @()\n \n # Try to find processes with the file open\n Get-Process | ForEach-Object {\n try {\n $proc = $_\n # Check if any modules match the file path\n $modules = $proc.Modules | Where-Object { $_.FileName -eq '${escapedPath}' }\n if ($modules) {\n $handles += [PSCustomObject]@{\n ProcessName = $proc.ProcessName\n ProcessId = $proc.Id\n }\n }\n } catch {\n # Skip processes we can't access\n }\n }\n \n # Also try using Get-CimInstance for better file handle detection\n try {\n $query = \"SELECT * FROM CIM_DataFile WHERE Name='${escapedPath.replace(/\\\\/g, \"\\\\\\\\\")}'\"\n $file = Get-CimInstance -Query $query -ErrorAction SilentlyContinue\n if ($file) {\n $assoc = Get-CimAssociatedInstance -InputObject $file -ResultClassName Win32_Process\n foreach ($proc in $assoc) {\n $handles += [PSCustomObject]@{\n ProcessName = $proc.Name\n ProcessId = $proc.ProcessId\n }\n }\n }\n } catch {\n # WMI query failed, ignore\n }\n \n $handles | ConvertTo-Json -Compress\n `;\n\n const { stdout } = await execFileAsync(\n \"powershell\",\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", psScript],\n { encoding: \"utf8\", maxBuffer: 1024 * 1024 },\n );\n\n if (!stdout || stdout.trim() === \"\" || stdout.trim() === \"null\") {\n return [];\n }\n\n const handles = parsePowerShellOutput(stdout);\n\n logger.debug(\"Detected file handles with PowerShell\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n logger.debug(\"Windows handle detection failed\", {\n error: getErrorMessage(error),\n });\n return [];\n }\n}\n\n/**\n * Try to detect using handle.exe from Sysinternals (if available)\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithHandleExe(\n filePath: string,\n): Promise<FileHandleInfo[]> {\n try {\n // handle.exe must be in PATH or current directory\n const { stdout } = await execFileAsync(\"handle\", [\"-nobanner\", filePath], {\n encoding: \"utf8\",\n });\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const handles: FileHandleInfo[] = [];\n const lines = stdout.split(\"\\n\");\n\n for (const line of lines) {\n // Format: process.exe pid: type handle: path\n const match = line.match(\n /^(.+?)\\s+pid:\\s+(\\d+)\\s+type:\\s+(\\w+)\\s+.+:\\s+(.+)$/i,\n );\n if (\n match?.[1] !== undefined &&\n match?.[1] !== \"\" &&\n match?.[2] !== undefined &&\n match?.[2] !== \"\"\n ) {\n const pid = Number.parseInt(match[2], 10);\n if (!Number.isNaN(pid)) {\n const handle: FileHandleInfo = {\n command: match[1],\n pid,\n };\n if (match?.[3] !== undefined && match[3] !== \"\") {\n handle.fd = match[3];\n }\n handle.mode = \"unknown\";\n handles.push(handle);\n }\n }\n }\n\n logger.debug(\"Detected file handles with handle.exe\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch {\n // handle.exe not available, silently fall back\n return [];\n }\n}\n\n/**\n * Detect all processes that have open handles to a specific file\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nexport async function detectFileHandles(\n filePath: string,\n): Promise<FileHandleInfo[]> {\n const os = getPlatform();\n\n logger.debug(\"Detecting file handles\", { file: filePath, platform: os });\n\n if (isWindows()) {\n // Try handle.exe first (most accurate)\n const handles = await detectWithHandleExe(filePath);\n if (handles.length > 0) {\n return handles;\n }\n\n // Fall back to PowerShell\n return detectOnWindows(filePath);\n }\n\n // Unix-like systems: try lsof first\n let handles = await detectWithLsof(filePath);\n\n // Fallback to fuser if lsof didn't work\n if (handles.length === 0) {\n handles = await detectWithFuser(filePath);\n }\n\n if (handles.length > 0) {\n logger.info(\"File has open handles\", {\n file: filePath,\n handleCount: handles.length,\n processes: handles.map((h) => ({\n pid: h.pid,\n command: h.command,\n mode: h.mode,\n })),\n });\n }\n\n return handles;\n}\n\n/**\n * Check if a file is locked by any process\n * @param filePath - Path to the file to check\n * @returns True if file has open handles, false otherwise\n */\nexport async function isFileLocked(filePath: string): Promise<boolean> {\n const handles = await detectFileHandles(filePath);\n return handles.length > 0;\n}\n\n/**\n * Get detailed information about processes locking a file\n * @param filePath - Path to the file to check\n * @returns Human-readable string describing the lock status\n */\nexport async function getFileLockInfo(filePath: string): Promise<string> {\n const handles = await detectFileHandles(filePath);\n\n if (handles.length === 0) {\n return \"File is not locked\";\n }\n\n const processInfo = handles\n .map(\n (h) =>\n `${h.command} (PID: ${h.pid}${h.user !== undefined && h.user !== \"\" ? `, User: ${h.user}` : \"\"}${h.mode !== undefined && h.mode !== \"\" ? `, Mode: ${h.mode}` : \"\"})`,\n )\n .join(\", \");\n\n return `File is locked by ${handles.length} process${handles.length > 1 ? \"es\" : \"\"}: ${processInfo}`;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { BrowserName } from \"@utils/BrowserControl\";\nimport { getPlatform, isWindows, type Platform } from \"@utils/platformUtils\";\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Interface for platform-specific browser control operations\n * Following SOLID principles - Interface Segregation\n */\nexport interface PlatformBrowserControl {\n /**\n * Check if the browser is supported on this platform\n * @param browserName - The name of the browser to check\n * @returns True if the browser is supported on this platform\n */\n isBrowserSupported(browserName: BrowserName): boolean;\n\n /**\n * Get executable names for a browser on this platform\n * @param browserName - The name of the browser\n * @returns Array of executable names for the browser\n */\n getBrowserExecutables(browserName: BrowserName): string[];\n\n /**\n * Launch a browser on this platform\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported or cannot be launched\n */\n launchBrowser(browserName: BrowserName): Promise<void>;\n\n /**\n * Get the platform name\n * @returns The name of the current platform\n */\n getPlatformName(): string;\n\n /**\n * Check if a browser is installed\n * @param browserName - The name of the browser to check\n * @returns Promise that resolves to true if the browser is installed\n */\n isBrowserInstalled(browserName: BrowserName): Promise<boolean>;\n}\n\n/**\n * Base implementation with common functionality\n * Following DRY principle\n */\nexport abstract class BasePlatformBrowserControl\n implements PlatformBrowserControl\n{\n protected readonly browserExecutables: Partial<Record<BrowserName, string[]>>;\n\n /**\n * Creates a new instance of BasePlatformBrowserControl\n */\n public constructor() {\n this.browserExecutables = this.initializeBrowserExecutables();\n }\n\n /**\n * Initialize browser executables for this platform\n * @returns Record mapping browser names to their executable names\n */\n protected abstract initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n >;\n\n public isBrowserSupported(browserName: BrowserName): boolean {\n const executables = this.browserExecutables[browserName];\n return Boolean(executables && executables.length > 0);\n }\n\n public getBrowserExecutables(browserName: BrowserName): string[] {\n return this.browserExecutables[browserName] || [];\n }\n\n /**\n * Launch a browser on this platform\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported or cannot be launched\n */\n public abstract launchBrowser(browserName: BrowserName): Promise<void>;\n\n /**\n * Get the platform name\n * @returns The name of the current platform\n */\n public abstract getPlatformName(): string;\n\n /**\n * Default implementation to check if browser is installed\n * Can be overridden by platform-specific implementations\n * @param browserName - The name of the browser to check\n * @returns Promise that resolves to true if the browser is installed\n */\n public async isBrowserInstalled(browserName: BrowserName): Promise<boolean> {\n const executables = this.getBrowserExecutables(browserName);\n\n for (const exe of executables) {\n try {\n // Try to check if executable exists using 'which' or 'where'\n const checkCommand = isWindows() ? \"where\" : \"which\";\n await execFileAsync(checkCommand, [exe], { timeout: 1000 });\n return true;\n } catch {\n // Continue checking other executables\n }\n }\n\n return false;\n }\n\n /**\n * Execute command helper with proper escaping\n * @param command - The command to execute\n * @param args - Arguments to pass to the command\n * @returns Promise that resolves when the command completes\n */\n protected async executeCommand(\n command: string,\n args: string[] = [],\n ): Promise<void> {\n try {\n await execFileAsync(command, args, {\n timeout: 5000,\n windowsHide: true,\n });\n } catch (error: unknown) {\n // Log but don't throw - browser may still launch\n if (this.isNodeError(error) && error.code !== \"ENOENT\") {\n console.debug(\n `Browser launch warning: ${BasePlatformBrowserControl.getErrorMessage(error)}`,\n );\n }\n }\n }\n\n /**\n * Helper to check if error is a Node.js error with code property\n * @param error - The error to check\n * @returns True if the error has a code property\n */\n private isNodeError(error: unknown): error is { code: string } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"string\"\n );\n }\n\n /**\n * Helper to get error message from unknown error\n * @param error - The error to get message from\n * @returns Error message as string\n */\n protected static getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n return String(error);\n }\n}\n\n/**\n * macOS implementation for browser control operations\n * Handles browser launching using AppleScript on macOS systems\n */\nexport class MacOSBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for macOS platform\n * @returns Record mapping browser names to their executable names on macOS\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"Firefox\"],\n Chrome: [\"Google Chrome\"],\n Safari: [\"Safari\"],\n };\n }\n\n /**\n * Launch a browser on macOS using AppleScript\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported on macOS\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const appNames: Partial<Record<BrowserName, string>> = {\n Firefox: \"Firefox\",\n Chrome: \"Google Chrome\",\n Safari: \"Safari\",\n };\n\n const appName = appNames[browserName];\n if (!appName) {\n throw new Error(`${browserName} not supported on macOS`);\n }\n\n // Use osascript with proper argument separation to avoid injection\n await this.executeCommand(\"osascript\", [\n \"-e\",\n `tell application \"${appName}\" to activate`,\n ]);\n }\n\n /**\n * Get the platform name for macOS\n * @returns The platform name \"macOS\"\n */\n public getPlatformName(): string {\n return \"macOS\";\n }\n}\n\n/**\n * Windows implementation for browser control operations\n * Handles browser launching using cmd.exe start command on Windows systems\n */\nexport class WindowsBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for Windows platform\n * @returns Record mapping browser names to their executable names on Windows\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"firefox.exe\", \"Firefox\"],\n Chrome: [\"chrome.exe\", \"Google Chrome\"],\n Safari: [], // Not available on Windows\n };\n }\n\n /**\n * Launch a browser on Windows using cmd.exe start command\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not available or fails to launch\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const executables = this.getBrowserExecutables(browserName);\n\n if (executables.length === 0) {\n throw new Error(`${browserName} not available on Windows`);\n }\n\n // Try each executable until one works\n for (const exe of executables) {\n if (await this.tryLaunchExecutable(exe)) {\n return; // Success, exit early\n }\n }\n\n throw new Error(`Failed to launch ${browserName} on Windows`);\n }\n\n /**\n * Try to launch a specific executable on Windows\n * @param exe - The executable name to launch\n * @returns Promise that resolves to true if launch was successful\n */\n private async tryLaunchExecutable(exe: string): Promise<boolean> {\n try {\n // Use cmd.exe with /c flag to run start command safely\n await execFileAsync(\"cmd.exe\", [\"/c\", \"start\", \"\", exe], {\n timeout: 5000,\n windowsHide: true,\n });\n return true;\n } catch {\n // Try next executable\n return false;\n }\n }\n\n /**\n * Get the platform name for Windows\n * @returns The platform name \"Windows\"\n */\n public getPlatformName(): string {\n return \"Windows\";\n }\n}\n\n/**\n * Linux implementation for browser control operations\n * Handles browser launching using direct executable calls or xdg-open on Linux systems\n */\nexport class LinuxBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for Linux platform\n * @returns Record mapping browser names to their executable names on Linux\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"firefox\", \"firefox-bin\"],\n Chrome: [\n \"google-chrome\",\n \"google-chrome-stable\",\n \"chromium\",\n \"chromium-browser\",\n ],\n Safari: [], // Not available on Linux\n };\n }\n\n /**\n * Launch a browser on Linux using direct executable calls or xdg-open fallback\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not available or fails to launch\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const executables = this.getBrowserExecutables(browserName);\n\n if (executables.length === 0) {\n throw new Error(`${browserName} not available on Linux`);\n }\n\n // Try each possible command\n if (await this.tryLaunchExecutables(executables)) {\n return; // Success\n }\n\n // Fallback to xdg-open if no browser executable worked\n await this.tryXdgOpenFallback(browserName);\n }\n\n /**\n * Try to launch browser executables\n * @param executables - Array of executable names to try\n * @returns Promise that resolves to true if any executable was successful\n */\n private async tryLaunchExecutables(executables: string[]): Promise<boolean> {\n for (const cmd of executables) {\n try {\n // Use direct execution without shell to avoid injection\n await execFileAsync(cmd, [], {\n timeout: 5000,\n });\n return true; // Success\n } catch {}\n }\n return false;\n }\n\n /**\n * Try xdg-open as fallback when direct executables fail\n * @param browserName - The name of the browser that failed to launch\n * @returns Promise that resolves when xdg-open succeeds\n * @throws {Error} When xdg-open also fails\n */\n private async tryXdgOpenFallback(browserName: BrowserName): Promise<void> {\n try {\n await execFileAsync(\"xdg-open\", [\"http://localhost\"], {\n timeout: 5000,\n });\n } catch (error: unknown) {\n throw new Error(\n `Failed to launch ${browserName} on Linux: ${BasePlatformBrowserControl.getErrorMessage(error)}`,\n );\n }\n }\n\n /**\n * Get the platform name for Linux\n * @returns The platform name \"Linux\"\n */\n public getPlatformName(): string {\n return \"Linux\";\n }\n}\n\n/**\n * Factory to create platform-specific browser control\n * Following SOLID - Single Responsibility and Open/Closed principles\n */\nlet platformControlInstance: PlatformBrowserControl | null = null;\n\n/**\n * Creates platform-specific browser control instance\n * @param platformOverride - Optional platform override for testing\n * @returns Platform-specific browser control instance\n * @throws {Error} When platform is not supported\n */\nexport function createPlatformBrowserControl(\n platformOverride?: Platform | NodeJS.Platform,\n): PlatformBrowserControl {\n // Use singleton for efficiency when not overriding\n if (platformControlInstance !== null && platformOverride === undefined) {\n return platformControlInstance;\n }\n\n const currentPlatform = platformOverride ?? getPlatform();\n const control = createControlForPlatform(currentPlatform);\n\n if (platformOverride === undefined) {\n platformControlInstance = control;\n }\n\n return control;\n}\n\n/**\n * Creates the appropriate control instance for the given platform\n * @param platform - The platform to create control for\n * @returns Platform-specific browser control instance\n * @throws {Error} When platform is not supported\n */\nfunction createControlForPlatform(platform: string): PlatformBrowserControl {\n switch (platform) {\n case \"darwin\":\n return new MacOSBrowserControl();\n case \"win32\":\n return new WindowsBrowserControl();\n case \"linux\":\n case \"freebsd\":\n case \"openbsd\":\n return new LinuxBrowserControl();\n default:\n // For any other platform string, try Linux as fallback\n return new LinuxBrowserControl();\n }\n}\n\n/**\n * Clear the singleton instance (useful for testing)\n */\nexport function clearPlatformControlInstance(): void {\n platformControlInstance = null;\n}\n","import {\n type BrowserName,\n closeBrowserGracefully,\n waitForBrowserToClose,\n} from \"@utils/BrowserControl\";\nimport { getDatabaseErrorType, getErrorMessage } from \"@utils/errorUtils\";\nimport { detectFileHandles, getFileLockInfo } from \"@utils/FileHandleDetector\";\nimport type { createTaggedLogger } from \"@utils/logHelpers\";\nimport { getBrowserConflictAdvice } from \"@utils/ProcessDetector\";\n\nimport {\n createPlatformBrowserControl,\n type PlatformBrowserControl,\n} from \"./platform/PlatformBrowserControl\";\n\n/**\n * Result of a browser conflict handling operation\n */\nexport interface BrowserLockResult {\n /** Whether the conflict was resolved */\n resolved: boolean;\n /** Whether the browser should be relaunched */\n shouldRelaunch: boolean;\n}\n\n/**\n * Shared handler for browser lock/permission issues\n * Follows DRY principle to avoid duplicating logic across browser strategies\n * Uses Strategy pattern for platform-specific operations\n */\nexport class BrowserLockHandler {\n private readonly platformControl: PlatformBrowserControl;\n\n /**\n * Creates a new BrowserLockHandler instance\n * @param logger - Tagged logger instance for this handler\n * @param browserName - Name of the browser this handler manages\n * @param platformControl - Optional platform control strategy (for testing)\n */\n public constructor(\n private readonly logger: ReturnType<typeof createTaggedLogger>,\n private readonly browserName: BrowserName,\n platformControl?: PlatformBrowserControl,\n ) {\n // Use provided control or create platform-specific one\n this.platformControl = platformControl ?? createPlatformBrowserControl();\n }\n\n /**\n * Handle database lock or permission errors\n * @param error - The error to check\n * @param file - The file that was locked/inaccessible\n * @param processes - Running processes for this browser\n * @param autoClose - Whether to attempt auto-closing the browser\n * @returns Promise that resolves to lock result\n */\n public async handleBrowserConflict(\n error: unknown,\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose = false,\n ): Promise<BrowserLockResult> {\n if (!(error instanceof Error)) {\n return { resolved: false, shouldRelaunch: false };\n }\n\n if (!this.isLockError(error)) {\n return { resolved: false, shouldRelaunch: false };\n }\n\n await this.logFileHandleInfo(file, processes);\n return this.handleProcessConflict(file, processes, autoClose);\n }\n\n /**\n * Check if an error indicates a database lock or permission issue\n * @param error - The error to check\n * @returns True if this is a lock-related error\n */\n private isLockError(error: Error): boolean {\n const dbErrorType = getDatabaseErrorType(error);\n return dbErrorType === \"locked\" || dbErrorType === \"permission\";\n }\n\n /**\n * Log detailed file handle information\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n */\n private async logFileHandleInfo(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n ): Promise<void> {\n try {\n const fileHandles = await detectFileHandles(file);\n\n if (fileHandles.length > 0) {\n const lockInfo = await getFileLockInfo(file);\n\n this.logger.debug(\"Database locked by specific processes\", {\n file,\n lockInfo,\n handleCount: fileHandles.length,\n handles: fileHandles.map((h) => ({\n pid: h.pid,\n command: h.command,\n mode: h.mode,\n user: h.user,\n })),\n });\n\n if (processes.length === 0) {\n this.logger.info(\n \"File is locked but no browser processes detected - another tool may be accessing the database\",\n {\n lockingProcesses: fileHandles\n .map((h) => `${h.command} (PID: ${h.pid})`)\n .join(\", \"),\n },\n );\n }\n }\n } catch (handleError) {\n this.logger.debug(\"Could not detect file handles\", {\n error:\n handleError instanceof Error\n ? handleError.message\n : String(handleError),\n });\n }\n }\n\n /**\n * Handle process conflicts and optionally close the browser\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n * @param autoClose - Whether to attempt auto-closing\n * @returns Promise that resolves to lock result\n */\n private async handleProcessConflict(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose: boolean,\n ): Promise<BrowserLockResult> {\n try {\n if (processes.length > 0) {\n return await this.handleBrowserProcesses(file, processes, autoClose);\n }\n\n this.logger.debug(\n \"Database/file locked but no browser processes detected\",\n {\n file,\n browserName: this.browserName,\n suggestion: \"Another process may be accessing the file\",\n },\n );\n } catch (processError) {\n this.logger.debug(\"Failed to check browser processes\", {\n error:\n processError instanceof Error\n ? processError.message\n : String(processError),\n });\n }\n\n return { resolved: false, shouldRelaunch: false };\n }\n\n /**\n * Handle detected browser processes\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n * @param autoClose - Whether to attempt auto-closing\n * @returns Promise that resolves to lock result\n */\n private async handleBrowserProcesses(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose: boolean,\n ): Promise<BrowserLockResult> {\n const processesWithDetails = processes.map((p) => ({\n ...p,\n details: `PID: ${p.pid}, Command: ${p.command}`,\n }));\n\n const advice = getBrowserConflictAdvice(\n this.browserName.toLowerCase(),\n processesWithDetails,\n );\n\n this.logger.debug(`${this.browserName} process conflict detected`, {\n file,\n processCount: processes.length,\n advice,\n });\n\n if (autoClose) {\n return this.attemptBrowserClose();\n }\n\n return Promise.resolve({ resolved: false, shouldRelaunch: false });\n }\n\n /**\n * Attempt to close the browser gracefully\n * @returns Promise that resolves to lock result\n */\n private async attemptBrowserClose(): Promise<BrowserLockResult> {\n this.logger.info(`Attempting to close ${this.browserName} gracefully...`);\n\n const closed = await closeBrowserGracefully(this.browserName, {\n interactive: true,\n force: false,\n });\n\n if (closed) {\n await waitForBrowserToClose(this.browserName, 5000);\n return { resolved: true, shouldRelaunch: true };\n }\n\n return { resolved: false, shouldRelaunch: false };\n }\n\n /**\n * Relaunch browser after successful operation\n * @returns Promise that resolves when browser is relaunched\n */\n public async relaunchBrowser(): Promise<void> {\n this.logger.info(`Relaunching ${this.browserName}...`);\n\n try {\n // Check if browser is supported on this platform\n if (!this.platformControl.isBrowserSupported(this.browserName)) {\n this.logger.debug(\n `${this.browserName} is not available on ${this.platformControl.getPlatformName()}`,\n );\n return;\n }\n\n // Use platform-specific strategy to launch browser\n await this.platformControl.launchBrowser(this.browserName);\n\n this.logger.success(\n `${this.browserName} has been relaunched with your tabs restored`,\n );\n } catch (relaunchError) {\n this.logger.debug(\n `Could not relaunch ${this.browserName} automatically`,\n {\n error: getErrorMessage(relaunchError),\n platform: this.platformControl.getPlatformName(),\n },\n );\n }\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"node:crypto\";\n\nimport { isMacOS, isWindows } from \"@utils/platformUtils\";\n\n/**\n * Simple memoization utility for caching Buffer operations\n * @param fn - The function to memoize that takes a Buffer and returns a Buffer\n * @param keyFn - Optional function to generate cache keys from Buffer values\n * @returns A memoized version of the input function\n */\nfunction memoizeBuffer(\n fn: (value: Buffer) => Buffer,\n keyFn?: (value: Buffer) => string,\n): (value: Buffer) => Buffer {\n const cache = new Map<string, Buffer>();\n\n return (value: Buffer): Buffer => {\n const key = keyFn ? keyFn(value) : value.toString(\"hex\");\n\n if (cache.has(key)) {\n const cachedResult = cache.get(key);\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n }\n\n const result = fn(value);\n cache.set(key, result);\n return result;\n };\n}\n\nimport { decryptV10Cookie, isV10Cookie } from \"./windows/decryptV10Cookie\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoizeBuffer(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoizeBuffer(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n // First try to find a UUID pattern which is common in cookies\n const uuidMatch = decodedString.match(\n /([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i,\n );\n if (uuidMatch?.[1]) {\n return uuidMatch[1];\n }\n\n // Look for common patterns at the end of the string\n const endPatterns = [\n /([A-Z]{3})$/, // Currency codes (USD, GBP, EUR)\n /([a-z]{2}_[A-Z]{2})$/, // Locale codes (en_US, en_GB)\n /(\\d{3}-\\d{7}-\\d{7})$/, // Amazon session IDs\n ];\n\n for (const pattern of endPatterns) {\n const match = decodedString.match(pattern);\n if (match?.[1]) {\n return match[1];\n }\n }\n\n // Then try other cleanup patterns\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E]+)$/, // Non-printable chars followed by printable chars\n /.*?([a-zA-Z0-9_\\-.]+)$/, // Alphanumeric value at the end\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @param metaVersion - Optional meta version for determining decryption behavior\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string | Buffer,\n metaVersion?: number,\n): Promise<string> {\n // v10 cookies use AES-GCM on Windows only\n // On macOS, cookies starting with v10 are actually v11 encrypted with a value that starts with \"v10,\"\n // Only treat as v10 cookie if we're on Windows AND it has sufficient length AND password is a Buffer (real scenario)\n if (\n isWindows() &&\n isV10Cookie(encryptedValue) &&\n encryptedValue.length >= 31 &&\n Buffer.isBuffer(password)\n ) {\n return decryptV10Cookie(encryptedValue, password);\n }\n\n // On macOS, cookies that don't start with v10 are considered 'old data' stored as plaintext\n // Ref: https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm\n if (isMacOS()) {\n // Check if this looks like encrypted data (starts with common version prefixes)\n const hasVersionPrefix = encryptedValue\n .slice(0, 3)\n .toString()\n .match(/^v\\d\\d$/);\n if (!hasVersionPrefix) {\n // Not a version prefix - treat as plaintext on macOS\n return Promise.resolve(encryptedValue.toString(\"utf8\"));\n }\n }\n\n // v11 cookies and other encrypted cookies use AES-CBC with PBKDF2\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(`Failed to derive key: ${error.message}`));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(`Failed to finalize decryption: ${(e as Error).message}`),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n\n // Skip the first 32 bytes (hash prefix) if meta version >= 24\n // Ref: https://chromium.googlesource.com/chromium/src/+/b02dcebd7cafab92770734dc2bc317bd07f1d891/net/extras/sqlite/sqlite_persistent_cookie_store.cc#223\n const useHashPrefix = (metaVersion ?? 0) >= 24;\n const finalDecrypted =\n useHashPrefix && decrypted.length > 32\n ? decrypted.slice(32)\n : decrypted;\n\n const decodedString = finalDecrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(`Decryption failed: ${(e as Error).message}`));\n }\n });\n });\n}\n","import { createDecipheriv } from \"node:crypto\";\n\n/**\n * Decrypts Chrome v10 encrypted cookies on Windows using AES-256-GCM\n *\n * Chrome v10 cookies use AES-256-GCM encryption with:\n * - 12-byte nonce (96 bits)\n * - 16-byte authentication tag\n * @param encryptedValue - The encrypted cookie value starting with 'v10' prefix\n * @param key - The decrypted master key from DPAPI\n * @returns The decrypted cookie value\n * @throws {Error} If the cookie is not v10 format or decryption fails\n */\nexport function decryptV10Cookie(encryptedValue: Buffer, key: Buffer): string {\n // Check for v10 prefix\n const VERSION_PREFIX = Buffer.from(\"v10\");\n if (!encryptedValue.subarray(0, 3).equals(VERSION_PREFIX)) {\n throw new Error(\"Not a v10 encrypted cookie\");\n }\n\n // Remove the version prefix\n const ciphertext = encryptedValue.subarray(3);\n\n // Extract components\n const NONCE_LENGTH = 12; // 96 bits / 8\n const TAG_LENGTH = 16; // 128 bits / 8\n\n if (ciphertext.length < NONCE_LENGTH + TAG_LENGTH) {\n throw new Error(\"Invalid v10 cookie: too short\");\n }\n\n const nonce = ciphertext.subarray(0, NONCE_LENGTH);\n const encryptedData = ciphertext.subarray(\n NONCE_LENGTH,\n ciphertext.length - TAG_LENGTH,\n );\n const authTag = ciphertext.subarray(ciphertext.length - TAG_LENGTH);\n\n // Decrypt using AES-256-GCM\n const decipher = createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAuthTag(authTag);\n\n const decrypted = Buffer.concat([\n decipher.update(encryptedData),\n decipher.final(),\n ]);\n\n return decrypted.toString(\"utf8\");\n}\n\n/**\n * Checks if a cookie value is v10 encrypted\n * @param value - The cookie value to check\n * @returns True if the cookie starts with 'v10' prefix\n */\nexport function isV10Cookie(value: Buffer): boolean {\n const VERSION_PREFIX = Buffer.from(\"v10\");\n return value.length >= 3 && value.subarray(0, 3).equals(VERSION_PREFIX);\n}\n","import { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\nimport { execSimple } from \"../../../utils/execSimple\";\n\nimport type { ChromiumBrowser } from \"./ChromiumBrowsers\";\n\n/**\n * Maps browser types to their keychain service names on macOS\n */\nconst MACOS_KEYCHAIN_SERVICES: Record<ChromiumBrowser, string> = {\n chrome: \"Chrome Safe Storage\",\n chromium: \"Chromium Safe Storage\",\n brave: \"Brave Safe Storage\",\n edge: \"Microsoft Edge Safe Storage\",\n arc: \"Arc Safe Storage\",\n opera: \"Opera Safe Storage\",\n \"opera-gx\": \"Opera Safe Storage\", // Opera GX shares Opera's keychain\n vivaldi: \"Vivaldi Safe Storage\",\n whale: \"Whale Safe Storage\",\n};\n\n/**\n * Gets the Chromium browser Safe Storage password for macOS\n * @param browser - The browser type to get the password for\n * @returns A promise that resolves to the browser's Safe Storage password\n */\nasync function getMacOSPassword(browser: ChromiumBrowser): Promise<string> {\n const service = MACOS_KEYCHAIN_SERVICES[browser];\n if (!service) {\n throw new Error(`Unknown browser type: ${browser}`);\n }\n\n try {\n const command = `security find-generic-password -w -s \"${service}\"`;\n const result = await execSimple(command);\n return result.stdout.trim();\n } catch (error) {\n // Fallback to Chrome if browser-specific key not found\n // This is useful for browsers that share Chrome's encryption\n if (browser !== \"chrome\") {\n const chromeCommand = `security find-generic-password -w -s \"Chrome Safe Storage\"`;\n try {\n const result = await execSimple(chromeCommand);\n return result.stdout.trim();\n } catch {\n // If Chrome fallback also fails, throw original error\n }\n }\n throw new Error(\n `Failed to get ${browser} password from keychain: ${error}`,\n );\n }\n}\n\n/**\n * Gets the Chromium browser password for Windows\n * Windows uses DPAPI which is browser-agnostic\n */\nasync function getWindowsPassword(): Promise<string | Buffer> {\n // Import dynamically to avoid loading on non-Windows platforms\n const { getChromePassword } = await import(\"./windows/getChromePassword\");\n return getChromePassword();\n}\n\n/**\n * Gets the Chromium browser password for Linux\n * Linux typically uses a hardcoded key or libsecret\n */\nasync function getLinuxPassword(): Promise<string> {\n // Import dynamically to avoid loading on non-Linux platforms\n const { getChromePassword } = await import(\"./linux/getChromePassword\");\n return getChromePassword();\n}\n\n/**\n * Gets the Chromium-based browser Safe Storage password for the current platform.\n * This password is used to decrypt cookies stored in the browser's cookie database.\n * Supports macOS (keychain), Windows (DPAPI), and Linux (keyring/libsecret).\n * @param browser - The Chromium-based browser to get the password for\n * @returns A promise that resolves to the browser's Safe Storage password or Buffer\n * @throws {Error} If the password cannot be retrieved or the platform is not supported\n */\nexport async function getChromiumPassword(\n browser: ChromiumBrowser = \"chrome\",\n): Promise<string | Buffer> {\n assertPlatformSupported();\n\n switch (getPlatform()) {\n case \"darwin\": {\n return getMacOSPassword(browser);\n }\n case \"win32\": {\n // Windows uses DPAPI which works for all Chromium browsers\n return getWindowsPassword();\n }\n case \"linux\": {\n // Linux uses a hardcoded key for all Chromium browsers\n return getLinuxPassword();\n }\n default:\n throw new Error(`Platform ${getPlatform()} is not supported`);\n }\n}\n","/**\n * Database connection manager with pooling and performance monitoring\n * Manages SQLite connections efficiently with automatic cleanup and monitoring\n */\n\nimport { EventEmitter } from \"node:events\";\n\nimport BetterSqlite3, { type Database } from \"better-sqlite3\";\n\nimport { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"DatabaseConnectionManager\");\n\n/**\n * Connection pool configuration\n */\nexport interface PoolConfig {\n /** Maximum number of connections in the pool */\n maxConnections?: number;\n /** Connection timeout in milliseconds */\n connectionTimeout?: number;\n /** Idle timeout before closing connection */\n idleTimeout?: number;\n /** Enable performance monitoring */\n enableMonitoring?: boolean;\n /** Retry attempts for locked databases */\n retryAttempts?: number;\n /** Retry delay in milliseconds */\n retryDelay?: number;\n /** Query execution timeout in milliseconds */\n queryTimeout?: number;\n}\n\n/**\n * Database connection metadata\n */\ninterface ConnectionMetadata {\n database: Database;\n filepath: string;\n inUse: boolean;\n lastAccessed: number;\n queryCount: number;\n totalQueryTime: number;\n created: number;\n}\n\n/**\n * Query performance metrics\n */\nexport interface QueryMetrics {\n query: string;\n duration: number;\n rowCount: number;\n filepath: string;\n timestamp: number;\n success: boolean;\n error?: string;\n}\n\n/**\n * Connection pool statistics\n */\nexport interface PoolStatistics {\n totalConnections: number;\n activeConnections: number;\n idleConnections: number;\n totalQueries: number;\n averageQueryTime: number;\n cacheHitRate: number;\n connectionReuse: number;\n}\n\n/**\n * Database connection manager with pooling\n */\nexport class DatabaseConnectionManager extends EventEmitter {\n private readonly connections: Map<string, ConnectionMetadata>;\n private readonly config: Required<PoolConfig>;\n private readonly queryMetrics: QueryMetrics[];\n private lastCleanupTime: number;\n private totalQueries: number;\n private cacheHits: number;\n private connectionReuses: number;\n\n /**\n *\n * @param config\n */\n constructor(config: PoolConfig = {}) {\n super();\n\n this.connections = new Map();\n this.queryMetrics = [];\n this.totalQueries = 0;\n this.cacheHits = 0;\n this.connectionReuses = 0;\n this.lastCleanupTime = Date.now();\n\n this.config = {\n maxConnections: config.maxConnections ?? 5,\n connectionTimeout: config.connectionTimeout ?? 5000,\n idleTimeout: config.idleTimeout ?? 30000,\n enableMonitoring: config.enableMonitoring ?? true,\n retryAttempts: config.retryAttempts ?? 3,\n retryDelay: config.retryDelay ?? 100,\n queryTimeout: config.queryTimeout ?? 3000, // 3 seconds default\n };\n }\n\n /**\n * Get or create a database connection\n * @param filepath\n */\n async getConnection(filepath: string): Promise<Database> {\n // Perform cleanup if needed (every 30 seconds)\n const now = Date.now();\n if (now - this.lastCleanupTime > 30000) {\n this.cleanupIdleConnections();\n this.lastCleanupTime = now;\n }\n\n // Check existing connection\n const existing = this.connections.get(filepath);\n if (existing && !existing.inUse) {\n existing.inUse = true;\n existing.lastAccessed = Date.now();\n this.connectionReuses++;\n\n logger.debug(\"Reusing existing connection\", {\n filepath,\n queryCount: existing.queryCount,\n });\n\n return existing.database;\n }\n\n // Check pool limit\n if (this.connections.size >= this.config.maxConnections) {\n await this.evictLeastRecentlyUsed();\n }\n\n // Create new connection\n return this.createConnection(filepath);\n }\n\n /**\n * Create a new database connection\n * @param filepath\n */\n private async createConnection(filepath: string): Promise<Database> {\n const startTime = Date.now();\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.config.retryAttempts; attempt++) {\n try {\n const database = new BetterSqlite3(filepath, {\n readonly: true,\n fileMustExist: true,\n });\n\n // Set busy timeout for all queries on this connection\n // This timeout only applies to actual query execution, not connection retries\n database.pragma(`busy_timeout = ${this.config.queryTimeout}`);\n\n const metadata: ConnectionMetadata = {\n database,\n filepath,\n inUse: true,\n lastAccessed: Date.now(),\n queryCount: 0,\n totalQueryTime: 0,\n created: Date.now(),\n };\n\n this.connections.set(filepath, metadata);\n\n const connectionTime = Date.now() - startTime;\n logger.debug(\"Created new connection\", {\n filepath,\n connectionTime,\n attempt: attempt + 1,\n });\n\n this.emit(\"connection:created\", { filepath, connectionTime });\n\n return database;\n } catch (error) {\n lastError = error as Error;\n\n if (this.isDatabaseLocked(error)) {\n logger.warn(\"Database locked, retrying\", {\n filepath,\n attempt: attempt + 1,\n maxAttempts: this.config.retryAttempts,\n });\n\n await this.delay(this.config.retryDelay * 2 ** attempt);\n continue;\n }\n\n throw error;\n }\n }\n\n throw lastError || new Error(`Failed to connect to database: ${filepath}`);\n }\n\n /**\n * Execute a query with the connection manager\n * The connection already has busy_timeout set, so queries will timeout appropriately\n * @param filepath\n * @param queryFn\n * @param queryDescription\n */\n async executeQuery<T>(\n filepath: string,\n queryFn: (db: Database) => T,\n queryDescription?: string,\n ): Promise<T> {\n const startTime = Date.now();\n const connection = await this.getConnection(filepath);\n const metadata = this.connections.get(filepath);\n\n try {\n const result = queryFn(connection);\n const duration = Date.now() - startTime;\n\n if (metadata) {\n metadata.queryCount++;\n metadata.totalQueryTime += duration;\n }\n\n this.totalQueries++;\n this.cacheHits++; // Increment cache hits for successful queries\n\n // Log slow queries at debug level\n if (duration > 100) {\n logger.debug(\"Slow query detected\", {\n query: queryDescription || \"Unknown query\",\n duration,\n filepath,\n });\n }\n\n // Record metrics\n if (this.config.enableMonitoring) {\n const metrics: QueryMetrics = {\n query: queryDescription || \"Unknown query\",\n duration,\n rowCount: Array.isArray(result) ? result.length : 1,\n filepath,\n timestamp: Date.now(),\n success: true,\n };\n\n this.recordMetrics(metrics);\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Increment query count even for failed queries\n this.totalQueries++;\n\n // Record error metrics\n if (this.config.enableMonitoring) {\n const metrics: QueryMetrics = {\n query: queryDescription || \"Unknown query\",\n duration,\n rowCount: 0,\n filepath,\n timestamp: Date.now(),\n success: false,\n error: (error as Error).message,\n };\n\n this.recordMetrics(metrics);\n }\n\n throw error;\n } finally {\n // Release connection\n if (metadata) {\n metadata.inUse = false;\n metadata.lastAccessed = Date.now();\n }\n }\n }\n\n /**\n * Release a connection back to the pool\n * @param filepath\n */\n releaseConnection(filepath: string): void {\n const metadata = this.connections.get(filepath);\n if (metadata) {\n metadata.inUse = false;\n metadata.lastAccessed = Date.now();\n logger.debug(\"Released connection\", { filepath });\n }\n }\n\n /**\n * Close a specific connection\n * @param filepath\n */\n closeConnection(filepath: string): void {\n const metadata = this.connections.get(filepath);\n if (metadata) {\n try {\n metadata.database.close();\n this.connections.delete(filepath);\n\n logger.debug(\"Closed connection\", {\n filepath,\n queryCount: metadata.queryCount,\n lifetime: Date.now() - metadata.created,\n });\n\n this.emit(\"connection:closed\", { filepath });\n } catch (error) {\n logError(\"Failed to close connection\", error, { filepath });\n }\n }\n }\n\n /**\n * Close all connections\n */\n closeAll(): void {\n for (const [filepath, metadata] of this.connections) {\n try {\n metadata.database.close();\n logger.debug(\"Closed connection\", { filepath });\n } catch (error) {\n logError(\"Failed to close connection\", error, { filepath });\n }\n }\n\n this.connections.clear();\n\n logger.info(\"Closed all connections\", {\n totalQueries: this.totalQueries,\n connectionReuses: this.connectionReuses,\n });\n }\n\n /**\n * Get pool statistics\n */\n getStatistics(): PoolStatistics {\n let totalQueryTime = 0;\n let totalQueryCount = 0;\n let activeConnections = 0;\n\n for (const metadata of this.connections.values()) {\n totalQueryTime += metadata.totalQueryTime;\n totalQueryCount += metadata.queryCount;\n if (metadata.inUse) {\n activeConnections++;\n }\n }\n\n return {\n totalConnections: this.connections.size,\n activeConnections,\n idleConnections: this.connections.size - activeConnections,\n totalQueries: this.totalQueries,\n averageQueryTime:\n totalQueryCount > 0 ? totalQueryTime / totalQueryCount : 0,\n cacheHitRate:\n this.totalQueries > 0 ? this.cacheHits / this.totalQueries : 0,\n connectionReuse: this.connectionReuses,\n };\n }\n\n /**\n * Get recent query metrics\n * @param limit\n */\n getQueryMetrics(limit = 100): QueryMetrics[] {\n return this.queryMetrics.slice(-limit);\n }\n\n /**\n * Clear query metrics\n */\n clearMetrics(): void {\n this.queryMetrics.length = 0;\n }\n\n /**\n * Clean up idle connections\n */\n private cleanupIdleConnections(): void {\n const now = Date.now();\n const toClose: string[] = [];\n\n for (const [filepath, metadata] of this.connections) {\n if (\n !metadata.inUse &&\n now - metadata.lastAccessed > this.config.idleTimeout\n ) {\n toClose.push(filepath);\n }\n }\n\n for (const filepath of toClose) {\n this.closeConnection(filepath);\n }\n\n if (toClose.length > 0) {\n logger.debug(\"Cleaned up idle connections\", { count: toClose.length });\n }\n }\n\n /**\n * Evict least recently used connection\n */\n private async evictLeastRecentlyUsed(): Promise<void> {\n let lruPath: string | null = null;\n let lruTime = Date.now();\n\n for (const [filepath, metadata] of this.connections) {\n if (!metadata.inUse && metadata.lastAccessed < lruTime) {\n lruPath = filepath;\n lruTime = metadata.lastAccessed;\n }\n }\n\n if (lruPath) {\n this.closeConnection(lruPath);\n logger.debug(\"Evicted LRU connection\", { filepath: lruPath });\n } else {\n // All connections are in use, wait a bit\n await this.delay(100);\n }\n }\n\n /**\n * Record query metrics\n * @param metrics\n */\n private recordMetrics(metrics: QueryMetrics): void {\n this.queryMetrics.push(metrics);\n\n // Keep only recent metrics (last 1000)\n if (this.queryMetrics.length > 1000) {\n this.queryMetrics.splice(0, this.queryMetrics.length - 1000);\n }\n\n this.emit(\"query:executed\", metrics);\n }\n\n /**\n * Check if error indicates database lock\n * @param error\n */\n private isDatabaseLocked(error: unknown): boolean {\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n return (\n message.includes(\"database is locked\") ||\n message.includes(\"database locked\") ||\n message.includes(\"sqlite_busy\")\n );\n }\n return false;\n }\n\n /**\n * Delay helper\n * @param ms\n */\n private async delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Global connection manager instance\n */\nlet globalManager: DatabaseConnectionManager | null = null;\n\n/**\n * Process exit handler function\n */\nlet exitHandler: (() => void) | null = null;\n\n/**\n * Get or create global connection manager\n * @param config\n */\nexport function getGlobalConnectionManager(\n config?: PoolConfig,\n): DatabaseConnectionManager {\n if (!globalManager) {\n globalManager = new DatabaseConnectionManager(config);\n\n // Ensure cleanup on process exit (only add once)\n if (!exitHandler) {\n exitHandler = () => {\n if (globalManager) {\n globalManager.closeAll();\n }\n };\n process.on(\"exit\", exitHandler);\n }\n }\n\n return globalManager;\n}\n\n/**\n * Reset global connection manager (mainly for testing)\n */\nexport function resetGlobalConnectionManager(): void {\n if (globalManager) {\n globalManager.closeAll();\n globalManager = null;\n }\n\n // Remove the exit handler to prevent memory leaks in tests\n if (exitHandler) {\n process.removeListener(\"exit\", exitHandler);\n exitHandler = null;\n }\n}\n","/**\n * Query monitoring wrapper for SQL operations\n * Provides clean, type-safe monitoring without monkey-patching\n */\n\nimport type { Database, Statement } from \"better-sqlite3\";\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"QueryMonitor\");\n\n/**\n * Query execution metrics\n */\nexport interface QueryExecution {\n sql: string;\n params: unknown[];\n startTime: number;\n endTime?: number;\n duration?: number;\n rowCount?: number;\n error?: Error;\n filepath?: string;\n}\n\n/**\n * Query monitoring options\n */\nexport interface MonitoringOptions {\n /** Log slow queries (in ms) */\n slowQueryThreshold?: number;\n /** Enable detailed logging */\n verbose?: boolean;\n /** Track query history */\n trackHistory?: boolean;\n /** Maximum history size */\n maxHistorySize?: number;\n}\n\n/**\n * Query monitor for tracking SQL performance\n */\nexport class QueryMonitor {\n private readonly options: Required<MonitoringOptions>;\n private readonly queryHistory: QueryExecution[];\n private totalQueries: number;\n private totalDuration: number;\n private slowQueries: number;\n private errors: number;\n\n /**\n * Creates a new QueryMonitor instance for tracking SQL query performance and metrics.\n * @param options - Configuration options for monitoring behavior\n * @param options.slowQueryThreshold - Milliseconds before a query is considered slow (default: 100ms)\n * @param options.verbose - Whether to log detailed query information (default: false)\n * @param options.trackHistory - Whether to maintain query history (default: true)\n * @param options.maxHistorySize - Maximum number of queries to keep in history (default: 1000)\n */\n constructor(options: MonitoringOptions = {}) {\n this.options = {\n slowQueryThreshold: options.slowQueryThreshold ?? 100,\n verbose: options.verbose ?? false,\n trackHistory: options.trackHistory ?? true,\n maxHistorySize: options.maxHistorySize ?? 1000,\n };\n\n this.queryHistory = [];\n this.totalQueries = 0;\n this.totalDuration = 0;\n this.slowQueries = 0;\n this.errors = 0;\n }\n\n /**\n * Execute a query with monitoring\n * @param db\n * @param sql\n * @param params\n * @param filepath\n */\n executeQuery<T>(\n db: Database,\n sql: string,\n params: unknown[] = [],\n filepath?: string,\n ): T[] {\n const execution: QueryExecution = {\n sql,\n params,\n startTime: Date.now(),\n };\n if (filepath !== undefined) {\n execution.filepath = filepath;\n }\n\n try {\n // Execute the query (timeout is already set on the connection)\n const stmt = db.prepare(sql);\n const result = stmt.all(...params) as T[];\n\n // Record success metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.rowCount = result.length;\n\n this.recordExecution(execution);\n\n return result;\n } catch (error) {\n // Record error metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.error = error as Error;\n\n this.recordExecution(execution);\n\n throw error;\n }\n }\n\n /**\n * Execute a single row query with monitoring\n * @param db\n * @param sql\n * @param params\n * @param filepath\n */\n executeGet<T>(\n db: Database,\n sql: string,\n params: unknown[] = [],\n filepath?: string,\n ): T | undefined {\n const execution: QueryExecution = {\n sql,\n params,\n startTime: Date.now(),\n };\n if (filepath !== undefined) {\n execution.filepath = filepath;\n }\n\n try {\n // Execute the query (timeout is already set on the connection)\n const stmt = db.prepare(sql);\n const result = stmt.get(...params) as T | undefined;\n\n // Record success metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.rowCount = result ? 1 : 0;\n\n this.recordExecution(execution);\n\n return result;\n } catch (error) {\n // Record error metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.error = error as Error;\n\n this.recordExecution(execution);\n\n throw error;\n }\n }\n\n /**\n * Create a monitored statement wrapper\n * @param db\n * @param sql\n * @param filepath\n */\n prepareStatement<T>(\n db: Database,\n sql: string,\n filepath?: string,\n ): MonitoredStatement<T> {\n const stmt = db.prepare(sql);\n return new MonitoredStatement(stmt, sql, this, filepath);\n }\n\n /**\n * Record query execution\n * @param execution\n */\n private recordExecution(execution: QueryExecution): void {\n // Update statistics\n this.totalQueries++;\n\n if (execution.duration !== undefined) {\n this.totalDuration += execution.duration;\n\n // Check for slow query\n if (execution.duration > this.options.slowQueryThreshold) {\n this.slowQueries++;\n\n logger.debug(\"Slow query detected\", {\n sql: execution.sql,\n duration: execution.duration,\n rowCount: execution.rowCount,\n filepath: execution.filepath,\n });\n }\n }\n\n if (execution.error) {\n this.errors++;\n\n if (this.options.verbose) {\n logger.error(\"Query failed\", {\n sql: execution.sql,\n error: execution.error.message,\n filepath: execution.filepath,\n });\n }\n } else if (this.options.verbose) {\n logger.debug(\"Query executed\", {\n sql: execution.sql,\n duration: execution.duration,\n rowCount: execution.rowCount,\n });\n }\n\n // Track history\n if (this.options.trackHistory) {\n this.queryHistory.push(execution);\n\n // Trim history if needed\n if (this.queryHistory.length > this.options.maxHistorySize) {\n this.queryHistory.splice(\n 0,\n this.queryHistory.length - this.options.maxHistorySize,\n );\n }\n }\n }\n\n /**\n * Get monitoring statistics\n */\n getStatistics() {\n return {\n totalQueries: this.totalQueries,\n averageDuration:\n this.totalQueries > 0 ? this.totalDuration / this.totalQueries : 0,\n slowQueries: this.slowQueries,\n slowQueryRate:\n this.totalQueries > 0 ? this.slowQueries / this.totalQueries : 0,\n errors: this.errors,\n errorRate: this.totalQueries > 0 ? this.errors / this.totalQueries : 0,\n historySize: this.queryHistory.length,\n };\n }\n\n /**\n * Get query history\n * @param limit\n */\n getHistory(limit?: number): QueryExecution[] {\n if (limit) {\n return this.queryHistory.slice(-limit);\n }\n return [...this.queryHistory];\n }\n\n /**\n * Clear history\n */\n clearHistory(): void {\n this.queryHistory.length = 0;\n }\n\n /**\n * Reset all statistics\n */\n reset(): void {\n this.clearHistory();\n this.totalQueries = 0;\n this.totalDuration = 0;\n this.slowQueries = 0;\n this.errors = 0;\n }\n}\n\n/**\n * Monitored statement wrapper\n */\nexport class MonitoredStatement<T> {\n /**\n * Creates a monitored wrapper around a prepared SQL statement.\n * This wrapper automatically tracks execution metrics for all queries run through it.\n * @param statement - The prepared SQLite statement to monitor\n * @param sql - The SQL query string for logging and debugging\n * @param monitor - The QueryMonitor instance that will track metrics\n * @param filepath - Optional database file path for additional context in logs\n */\n constructor(\n private readonly statement: Statement,\n private readonly sql: string,\n private readonly monitor: QueryMonitor,\n private readonly filepath?: string,\n ) {}\n\n /**\n * Execute all with monitoring\n * @param {...any} params\n */\n all(...params: unknown[]): T[] {\n return this.monitor.executeQuery<T>(\n { prepare: () => this.statement } as unknown as Database,\n this.sql,\n params,\n this.filepath,\n );\n }\n\n /**\n * Execute get with monitoring\n * @param {...any} params\n */\n get(...params: unknown[]): T | undefined {\n return this.monitor.executeGet<T>(\n { prepare: () => this.statement } as unknown as Database,\n this.sql,\n params,\n this.filepath,\n );\n }\n\n /**\n * Get underlying statement\n */\n getStatement(): Statement {\n return this.statement;\n }\n}\n\n/**\n * Create a global query monitor instance\n */\nlet globalMonitor: QueryMonitor | null = null;\n\n/**\n * Get or create global query monitor\n * @param options\n */\nexport function getGlobalQueryMonitor(\n options?: MonitoringOptions,\n): QueryMonitor {\n if (!globalMonitor) {\n globalMonitor = new QueryMonitor(options);\n }\n return globalMonitor;\n}\n\n/**\n * Reset global query monitor\n */\nexport function resetGlobalQueryMonitor(): void {\n if (globalMonitor) {\n globalMonitor.reset();\n globalMonitor = null;\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Arc browser.\n * Arc is a Chromium-based browser with unique features but standard cookie storage.\n * @example\n * ```typescript\n * const strategy = new ArcCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ArcCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of ArcCookieQueryStrategy\n */\n public constructor() {\n super(\"arc\");\n }\n}\n","import { dirname } from \"node:path\";\n\nimport { BaseChromiumCookieQueryStrategy } from \"../chromium/BaseChromiumCookieQueryStrategy\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\n/**\n * Interface representing Chrome profile information from Local State\n */\ninterface ChromeProfileInfo {\n name?: string;\n user_name?: string;\n [key: string]: unknown;\n}\n\n/**\n * Strategy for querying cookies from Chrome browser.\n * This class extends the BaseChromiumCookieQueryStrategy with Chrome-specific logic.\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy extends BaseChromiumCookieQueryStrategy {\n private readonly profileName?: string;\n\n /**\n * Creates a new instance of ChromeCookieQueryStrategy\n * @param profileName - Optional specific profile name to target\n */\n public constructor(profileName?: string) {\n super(\"ChromeCookieQueryStrategy\", \"Chrome\");\n if (profileName !== undefined) {\n this.profileName = profileName;\n }\n }\n\n /**\n * Get Chrome-specific cookie file paths\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected getCookieFilePaths(store?: string): string[] {\n if (store !== undefined && store !== \"\") {\n return [store];\n }\n\n let paths = listChromeProfilePaths();\n\n // Filter by profile name if specified\n if (this.profileName) {\n // Read Chrome's Local State to map profile names to directories\n try {\n const fs = require(\"node:fs\");\n const path = require(\"node:path\");\n\n // Ensure we have at least one path to determine the Chrome data directory\n if (paths.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const firstPath = paths[0];\n if (!firstPath) {\n return [];\n }\n const chromeDataDir = dirname(dirname(firstPath)); // Get Chrome data directory\n const localStatePath = path.join(chromeDataDir, \"Local State\");\n\n if (fs.existsSync(localStatePath)) {\n const localState = JSON.parse(\n fs.readFileSync(localStatePath, \"utf8\"),\n );\n const profileCache = localState.profile?.info_cache || {};\n\n // Find the directory for the given profile name\n let targetDir: string | undefined;\n\n for (const [dir, info] of Object.entries(profileCache)) {\n const profile = info as ChromeProfileInfo;\n if (\n profile.name?.toLowerCase() === this.profileName.toLowerCase()\n ) {\n targetDir = dir;\n break;\n }\n }\n\n // Also check if user passed the directory name directly (e.g., \"Default\" or \"Profile 2\")\n if (!targetDir) {\n for (const dir of Object.keys(profileCache)) {\n if (dir.toLowerCase() === this.profileName.toLowerCase()) {\n targetDir = dir;\n break;\n }\n }\n }\n\n if (targetDir) {\n // Filter paths to only include the target directory\n paths = paths.filter((cookiePath) => {\n const dir = dirname(cookiePath);\n return dir.endsWith(targetDir);\n });\n\n if (paths.length === 0) {\n this.logger.warn(\n `No cookie files found for profile: ${this.profileName} (directory: ${targetDir})`,\n );\n } else {\n this.logger.debug(\n `Found ${paths.length} cookie file(s) for profile: ${this.profileName}`,\n );\n }\n } else {\n this.logger.debug(\"Profile not found in Chrome Local State\", {\n requestedProfile: this.profileName,\n availableProfiles: Object.entries(profileCache).map(\n ([dir, info]) => ({\n directory: dir,\n name: (info as ChromeProfileInfo).name,\n }),\n ),\n });\n\n // Return empty array to avoid querying wrong profile\n return [];\n }\n }\n } catch (error) {\n this.logger.warn(`Failed to read Chrome profile info: ${error}`);\n }\n }\n\n return Array.isArray(paths) ? paths : [paths];\n }\n}\n","/**\n * Asynchronously maps over an array and flattens the result.\n * Similar to Array.prototype.flatMap but for async operations.\n * @param array - The input array to map over\n * @param callback - The async mapping function to apply to each element\n * @param defaultValue - The default value to return if the array is empty\n * @returns A flattened array of results\n * @example\n * // Basic usage with number arrays\n * const numbers = [1, 2, 3];\n * const result = await flatMapAsync(\n * numbers,\n * async (num) => [num, num * 2]\n * );\n * console.log(result); // [1, 2, 2, 4, 3, 6]\n * @example\n * // Error handling with default value\n * const data = ['valid', 'invalid'];\n * const result = await flatMapAsync(\n * data,\n * async (item) => {\n * if (item === 'invalid') throw new Error();\n * return [item.toUpperCase()];\n * },\n * ['DEFAULT']\n * );\n * console.log(result); // ['VALID', 'DEFAULT']\n */\nexport async function flatMapAsync<T, U>(\n array: T[],\n callback: (item: T) => Promise<U[]>,\n defaultValue: U[] = [],\n): Promise<U[]> {\n if (array.length === 0) {\n return defaultValue;\n }\n\n const results = await Promise.all(\n array.map(async (item) => {\n try {\n return await callback(item);\n } catch (_error) {\n return defaultValue;\n }\n }),\n );\n return results.flat();\n}\n","import { flatMapAsync } from \"@utils/flatMapAsync\";\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../types/schemas\";\n\n/**\n * A composite strategy that combines multiple cookie query strategies.\n * This class implements the CookieQueryStrategy interface and allows querying cookies\n * from multiple browser-specific strategies simultaneously.\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy(),\n * new SafariCookieQueryStrategy()\n * ]);\n * const cookies = await strategy.queryCookies('sessionId', 'example.com');\n * ```\n */\nexport class CompositeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"CompositeCookieQueryStrategy\");\n\n /**\n * The browser name identifier for this strategy\n * @remarks Always returns 'internal' as this is a composite strategy\n */\n public readonly browserName: BrowserName = \"internal\";\n\n /**\n * Creates a new instance of CompositeCookieQueryStrategy\n * @param strategies - Array of browser-specific strategies to use for querying cookies\n * @remarks\n * - Each strategy in the array should implement the CookieQueryStrategy interface\n * - The order of strategies determines the order of cookie querying\n * - Failed strategies will be gracefully handled and skipped\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy()\n * ]);\n * ```\n */\n public constructor(private readonly strategies: CookieQueryStrategy[]) {}\n\n /**\n * Handles strategy-specific errors and logs them appropriately\n * @internal\n * @param error - The error that occurred during strategy execution\n * @param strategy - The strategy that failed\n */\n private handleStrategyError(\n error: unknown,\n strategy: CookieQueryStrategy,\n ): void {\n if (error instanceof Error) {\n this.logger.error(\"Strategy failed\", { error, strategy });\n } else {\n this.logger.error(\"Strategy failed with unknown error\", {\n error: String(error),\n strategy,\n });\n }\n }\n\n /**\n * Queries cookies using all available strategies in parallel\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - The store pattern to match cookies against\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns Promise resolving to combined array of cookies from all strategies\n * @remarks\n * - Failures in individual strategies are logged but don't affect other strategies\n * - Results are combined from all successful strategy queries\n * - Empty arrays are returned for failed strategy queries\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy()\n * ]);\n * const cookies = await strategy.queryCookies('sessionId', 'example.com');\n * console.log(cookies); // Combined results from all browsers\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies from all strategies\", {\n name,\n domain,\n store,\n force,\n strategyCount: this.strategies.length,\n });\n\n /**\n * Use flatMapAsync to process strategies in sequence while collecting results\n * This approach provides better error isolation than Promise.all\n * Each strategy failure is handled independently\n */\n return await flatMapAsync(\n this.strategies,\n async (strategy) => {\n try {\n return await strategy.queryCookies(name, domain, store, force);\n } catch (error) {\n this.handleStrategyError(error, strategy);\n return [];\n }\n },\n [],\n );\n } catch (error) {\n /**\n * Handle top-level errors that may occur during strategy processing\n * This ensures the function always returns an array, even in catastrophic failure\n */\n if (error instanceof Error) {\n this.logger.error(\"Failed to query cookies\", { error });\n } else {\n this.logger.error(\"Failed to query cookies with unknown error\", {\n error: String(error),\n });\n }\n return [];\n }\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Microsoft Edge browser.\n * Edge is Chromium-based and uses the same cookie storage format as Chrome.\n * @example\n * ```typescript\n * const strategy = new EdgeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class EdgeCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of EdgeCookieQueryStrategy\n */\n public constructor() {\n super(\"edge\");\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport type { createTaggedLogger } from \"@utils/logHelpers\";\nimport { getPlatform } from \"@utils/platformUtils\";\nimport { isFirefoxRunning } from \"@utils/ProcessDetector\";\n\nimport type { ExportedCookie } from \"../../../types/schemas\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\nimport { getGlobalConnectionManager } from \"../sql/DatabaseConnectionManager\";\nimport { getGlobalQueryMonitor } from \"../sql/QueryMonitor\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @param logger - Logger instance for logging messages\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(\n logger: ReturnType<typeof createTaggedLogger>,\n): string[] {\n const home = homedir();\n if (!home) {\n logger.warn(\"Failed to get home directory\");\n return [];\n }\n\n // Fast path: Check if Firefox profile directories exist before attempting glob\n const platform = getPlatform();\n const profileDirs: string[] = [];\n const patterns: string[] = [];\n\n switch (platform) {\n case \"darwin\":\n profileDirs.push(join(home, \"Library/Application Support/Firefox\"));\n patterns.push(\n join(\n home,\n \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\",\n ),\n );\n break;\n case \"win32\": {\n // Regular Firefox\n profileDirs.push(join(home, \"AppData\", \"Roaming\", \"Mozilla\", \"Firefox\"));\n patterns.push(\n join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox\",\n \"Profiles\",\n \"*\",\n \"cookies.sqlite\",\n ),\n );\n // Firefox Developer Edition\n const devEditionPath = join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox Developer Edition\",\n );\n if (existsSync(devEditionPath)) {\n profileDirs.push(devEditionPath);\n patterns.push(join(devEditionPath, \"Profiles\", \"*\", \"cookies.sqlite\"));\n }\n // Firefox ESR (Extended Support Release)\n const esrPath = join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox ESR\",\n );\n if (existsSync(esrPath)) {\n profileDirs.push(esrPath);\n patterns.push(join(esrPath, \"Profiles\", \"*\", \"cookies.sqlite\"));\n }\n // Also check Local AppData for some installations\n const localFirefoxPath = join(\n home,\n \"AppData\",\n \"Local\",\n \"Mozilla\",\n \"Firefox\",\n );\n if (existsSync(localFirefoxPath)) {\n profileDirs.push(localFirefoxPath);\n patterns.push(\n join(localFirefoxPath, \"Profiles\", \"*\", \"cookies.sqlite\"),\n );\n }\n break;\n }\n case \"linux\":\n profileDirs.push(join(home, \".mozilla/firefox\"));\n patterns.push(join(home, \".mozilla/firefox/*/cookies.sqlite\"));\n break;\n default:\n logger.debug(\"Unsupported platform for Firefox cookie extraction\", {\n platform,\n });\n return [];\n }\n\n const existingProfileDirs = profileDirs.filter((dir) => existsSync(dir));\n\n if (existingProfileDirs.length === 0) {\n logger.debug(\n \"No Firefox profile directories found - Firefox may not be installed\",\n {\n checked: profileDirs,\n platform,\n },\n );\n return [];\n }\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = fg.sync(pattern);\n files.push(...matches);\n }\n\n logger.debug(\"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser.\n * This class extends the BaseCookieQueryStrategy and implements Firefox-specific\n * cookie extraction logic. It searches for cookie databases in standard Firefox\n * profile locations and extracts cookies matching the specified name and domain.\n * @example\n * ```typescript\n * import { FirefoxCookieQueryStrategy } from './FirefoxCookieQueryStrategy';\n *\n * const strategy = new FirefoxCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('sessionid', 'example.com');\n * console.log(cookies);\n * ```\n */\nexport class FirefoxCookieQueryStrategy extends BaseCookieQueryStrategy {\n private readonly lockHandler: BrowserLockHandler;\n\n /**\n * Creates a new instance of FirefoxCookieQueryStrategy\n */\n public constructor() {\n super(\"FirefoxCookieQueryStrategy\", \"Firefox\");\n this.lockHandler = new BrowserLockHandler(this.logger, \"Firefox\");\n }\n\n /**\n * Creates the query parameters for cookie extraction using the new query builder\n * @param name - The cookie name to search for\n * @param domain - The domain pattern to match cookies against\n * @param file - The database file path for metadata\n * @returns Query configuration object\n * @private\n */\n private async createCookieQueryConfig(\n name: string,\n domain: string,\n file: string,\n ): Promise<{\n file: string;\n sql: string;\n params: unknown[];\n rowTransform: (row: FirefoxCookieRow) => ExportedCookie;\n }> {\n // Import the query builder dynamically to avoid circular dependencies\n const { CookieQueryBuilder } = await import(\"../sql/CookieQueryBuilder\");\n const queryBuilder = new CookieQueryBuilder(\"firefox\");\n\n const queryConfig = queryBuilder.buildSelectQuery({\n name,\n domain,\n browser: \"firefox\",\n });\n\n return {\n file,\n sql: queryConfig.sql,\n params: queryConfig.params,\n rowTransform: (row: FirefoxCookieRow): ExportedCookie => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n };\n }\n\n /**\n * Handles errors that occur during cookie extraction\n * @param error - The error that occurred\n * @param file - The database file being queried\n * @param force - Whether operations are being forced\n * @param name - The cookie name being searched\n * @param domain - The domain being searched\n * @returns Promise resolving to retry configuration\n * @private\n */\n private async handleCookieExtractionError(\n error: unknown,\n file: string,\n force: boolean | undefined,\n name: string,\n domain: string,\n ): Promise<{ retryAfterClose: boolean; shouldRelaunch: boolean }> {\n const processes = await isFirefoxRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n file,\n processes,\n force !== true,\n );\n\n if (lockResult.resolved) {\n return {\n retryAfterClose: true,\n shouldRelaunch: lockResult.shouldRelaunch,\n };\n }\n\n this.logExtractError(error, file, name, domain);\n return { retryAfterClose: false, shouldRelaunch: false };\n }\n\n /**\n * Logs cookie extraction errors in a consistent format\n * @param error - The error to log\n * @param file - The file that failed\n * @param name - The cookie name\n * @param domain - The domain\n * @private\n */\n private logExtractError(\n error: unknown,\n file: string,\n name: string,\n domain: string,\n ): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.logger.debug(`Error reading Firefox cookie file ${file}`, {\n error: errorMessage,\n file,\n name,\n domain,\n });\n }\n\n /**\n * Performs a retry attempt after browser closure\n * @param queryConfig - The cookie query configuration\n * @param shouldRelaunch - Whether to relaunch the browser after success\n * @returns Promise resolving to extracted cookies\n * @private\n */\n private async performRetryAfterClose(\n queryConfig: Awaited<ReturnType<typeof this.createCookieQueryConfig>>,\n shouldRelaunch: boolean,\n ): Promise<ExportedCookie[]> {\n this.logger.info(\n \"Retrying Firefox cookie extraction after browser close...\",\n );\n\n try {\n const cookies = await this.executeQueryWithNewUtilities(queryConfig);\n this.logger.success(\n \"Successfully extracted cookies after closing Firefox\",\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError) {\n this.logger.error(\n \"Failed to extract cookies even after closing Firefox\",\n {\n error:\n retryError instanceof Error\n ? retryError.message\n : String(retryError),\n file: queryConfig.file,\n },\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n }\n\n /**\n * Processes a single Firefox cookie file for the given parameters\n * @param file - The cookie file to process\n * @param name - The cookie name to search for\n * @param domain - The domain pattern to match\n * @param force - Whether to force operations despite warnings\n * @returns Promise resolving to extracted cookies from this file\n * @private\n */\n private async processCookieFile(\n file: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const queryConfig = await this.createCookieQueryConfig(name, domain, file);\n\n try {\n return await this.executeQueryWithNewUtilities(queryConfig);\n } catch (error) {\n const retryConfig = await this.handleCookieExtractionError(\n error,\n file,\n force,\n name,\n domain,\n );\n\n if (retryConfig.retryAfterClose) {\n return this.performRetryAfterClose(\n queryConfig,\n retryConfig.shouldRelaunch,\n );\n }\n\n return [];\n }\n }\n\n /**\n * Execute query using the new SQL utilities\n * @param queryConfig - Query configuration from createCookieQueryConfig\n * @param queryConfig.file\n * @param queryConfig.sql\n * @param queryConfig.params\n * @param queryConfig.rowTransform\n * @returns Promise resolving to exported cookies\n * @private\n */\n private async executeQueryWithNewUtilities(queryConfig: {\n file: string;\n sql: string;\n params: unknown[];\n rowTransform: (row: FirefoxCookieRow) => ExportedCookie;\n }): Promise<ExportedCookie[]> {\n const connectionManager = getGlobalConnectionManager({\n retryAttempts: 1, // Fail fast for Firefox - we have lock handling\n retryDelay: 0, // No delay - let lock handler deal with it\n queryTimeout: 100, // Very short timeout for Firefox to fail fast on locks\n enableMonitoring: true,\n });\n\n const monitor = getGlobalQueryMonitor();\n\n return connectionManager.executeQuery(\n queryConfig.file,\n (db) => {\n // Use the query monitor for tracking\n const rows = monitor.executeQuery<FirefoxCookieRow>(\n db,\n queryConfig.sql,\n queryConfig.params,\n queryConfig.file,\n );\n\n // Apply transformation\n return rows.map(queryConfig.rowTransform);\n },\n queryConfig.sql, // Pass SQL for monitoring\n );\n }\n\n /**\n * Executes the Firefox-specific query logic\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n * @protected\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const files = store ?? findFirefoxCookieFiles(this.logger);\n const fileList = Array.isArray(files) ? files : [files];\n\n // Fast path: If no Firefox cookie files found (Firefox not installed),\n // return early to avoid unnecessary database queries and process detection\n if (fileList.length === 0) {\n this.logger.debug(\"No Firefox cookie files to query\");\n return [];\n }\n\n const results: ExportedCookie[] = [];\n\n for (const file of fileList) {\n const cookies = await this.processCookieFile(file, name, domain, force);\n results.push(...cookies);\n }\n\n return results;\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Opera browser.\n * Opera is a Chromium-based browser with its own keychain entry.\n * @example\n * ```typescript\n * const strategy = new OperaCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class OperaCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of OperaCookieQueryStrategy\n */\n public constructor() {\n super(\"opera\");\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Opera GX browser.\n * Opera GX is the gaming-focused variant of Opera, sharing the same keychain entry.\n * @example\n * ```typescript\n * const strategy = new OperaGXCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class OperaGXCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of OperaGXCookieQueryStrategy\n */\n public constructor() {\n super(\"opera-gx\");\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { errorMessageContains, formatErrorForLogging } from \"@utils/errorUtils\";\nimport { isMacOS } from \"@utils/platformUtils\";\nimport { isSafariRunning } from \"@utils/ProcessDetector\";\nimport {\n checkFilePermission,\n handleSafariPermissionError,\n} from \"@utils/SystemPermissions\";\n\nimport type { ExportedCookie } from \"../../../types/schemas\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\n\nimport { decodeBinaryCookies } from \"./decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser.\n * This class extends the BaseCookieQueryStrategy and implements Safari-specific\n * cookie extraction logic.\n */\nexport class SafariCookieQueryStrategy extends BaseCookieQueryStrategy {\n private readonly lockHandler: BrowserLockHandler;\n\n /**\n * Creates a new instance of SafariCookieQueryStrategy\n */\n public constructor() {\n super(\"SafariCookieQueryStrategy\", \"Safari\");\n this.lockHandler = new BrowserLockHandler(this.logger, \"Safari\");\n }\n\n /**\n * Gets the path to Safari's cookie database\n * @param home - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(home: string): string {\n return join(\n home,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Formats the domain by removing leading dot if present\n * @param domain - Domain to format\n * @returns Formatted domain or empty string if domain is invalid\n */\n private formatDomain(domain: string | undefined | null): string {\n if (domain === null || domain === undefined || typeof domain !== \"string\") {\n return \"\";\n }\n return domain.startsWith(\".\") ? domain.slice(1) : domain;\n }\n\n /**\n * Formats the expiry date\n * @param expiry - Expiry timestamp (Unix epoch seconds)\n * @returns Formatted expiry date or \"Infinity\"\n */\n private formatExpiry(\n expiry: number | undefined | null,\n ): Date | \"Infinity\" | undefined {\n // Handle undefined or null - return undefined instead of NaN date\n if (expiry === undefined || expiry === null) {\n return undefined;\n }\n\n if (typeof expiry !== \"number\" || Number.isNaN(expiry) || expiry <= 0) {\n return \"Infinity\";\n }\n\n // Validate timestamp is reasonable (1970-2100 range in seconds)\n const minTimestamp = 0; // 1970-01-01\n const maxTimestamp = 4102444800; // 2100-01-01\n\n if (expiry < minTimestamp || expiry > maxTimestamp) {\n this.logger.warn(\"Invalid expiry timestamp, treating as session cookie\", {\n expiry,\n });\n return \"Infinity\";\n }\n\n return new Date(expiry * 1000);\n }\n\n /**\n * Checks if a flag bit is set\n * @param flags - The flags value\n * @param bit - The bit to check\n * @returns True if the bit is set, false otherwise\n */\n private isFlagSet(flags: number | undefined | null, bit: number): boolean {\n if (typeof flags !== \"number\" || Number.isNaN(flags) || flags <= 0) {\n return false;\n }\n return (flags & bit) === bit;\n }\n\n /**\n * Formats the creation timestamp\n * @param creation - Creation timestamp (Unix epoch seconds)\n * @returns Formatted creation timestamp in milliseconds or undefined\n */\n private formatCreation(\n creation: number | undefined | null,\n ): number | undefined {\n if (\n typeof creation !== \"number\" ||\n Number.isNaN(creation) ||\n creation <= 0\n ) {\n return undefined;\n }\n\n // Validate timestamp is reasonable (1970-2100 range in seconds)\n const minTimestamp = 0; // 1970-01-01\n const maxTimestamp = 4102444800; // 2100-01-01\n\n if (creation < minTimestamp || creation > maxTimestamp) {\n this.logger.warn(\"Invalid creation timestamp, ignoring\", { creation });\n return undefined;\n }\n\n return creation * 1000;\n }\n\n /**\n * Processes a cookie value to ensure it's a string\n * @param value - The cookie value to process\n * @returns The processed value as a string\n */\n private processValue(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (Buffer.isBuffer(value)) {\n return value.toString();\n }\n\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // If JSON.stringify fails (e.g., circular reference), return a placeholder\n return \"[object]\";\n }\n }\n\n // Handle primitives (string, number, boolean, etc.)\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n\n // Fallback for any other type (should not happen with proper typing)\n return \"[unknown value]\";\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @param force - Whether to skip interactive prompts\n * @returns Array of exported cookies\n */\n private async decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n // Check permissions first\n const permissionResult = await this.checkAndHandlePermissions(\n cookieDbPath,\n force,\n );\n if (!permissionResult) {\n return [];\n }\n\n // Decode cookies and process them\n const cookies = decodeBinaryCookies(cookieDbPath);\n return this.processCookies(cookies, name, domain, cookieDbPath);\n } catch (error: unknown) {\n return this.handleDecodingError(error, cookieDbPath, name, domain, force);\n }\n }\n\n /**\n * Check file permissions and handle permission errors\n * @param cookieDbPath - Path to the cookie database\n * @param force - Whether to skip interactive prompts\n * @returns True if permissions are granted, false otherwise\n */\n private async checkAndHandlePermissions(\n cookieDbPath: string,\n force?: boolean,\n ): Promise<boolean> {\n const hasPermission = await checkFilePermission(cookieDbPath);\n if (hasPermission) {\n return true;\n }\n\n this.logger.warn(\"Cannot access Safari cookies due to macOS permissions\", {\n file: cookieDbPath,\n suggestion: \"Terminal application needs Full Disk Access permission\",\n });\n\n // Try to handle the permission error interactively\n const permissionGranted = await handleSafariPermissionError(\n new Error(\"EPERM: operation not permitted\"),\n {\n appName: process.env.TERM_PROGRAM ?? \"Terminal\",\n browserName: \"Safari\",\n interactive: force !== true,\n },\n );\n\n if (!permissionGranted) {\n return false;\n }\n\n // Check again after permission might have been granted\n const stillNoPermission = !(await checkFilePermission(cookieDbPath));\n if (stillNoPermission) {\n this.logger.error(\n \"Still cannot access Safari cookies after permission attempt\",\n {\n file: cookieDbPath,\n advice:\n \"Please restart your terminal application after granting Full Disk Access\",\n },\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Process and filter cookies based on name and domain criteria\n * @param cookies - Raw cookies from binary file\n * @param name - Name filter\n * @param domain - Domain filter\n * @param cookieDbPath - Path to cookie database for metadata\n * @returns Processed and filtered cookies\n */\n private processCookies(\n cookies: unknown[],\n name: string,\n domain: string,\n cookieDbPath: string,\n ): ExportedCookie[] {\n return cookies\n .filter((cookie) => this.matchesCriteria(cookie, name, domain))\n .map((cookie) => this.mapToExportedCookie(cookie, cookieDbPath));\n }\n\n /**\n * Check if cookie matches the search criteria\n * @param cookie - Raw cookie object\n * @param name - Name filter\n * @param domain - Domain filter\n * @returns True if cookie matches criteria\n */\n private matchesCriteria(\n cookie: unknown,\n name: string,\n domain: string,\n ): boolean {\n // Type guard for cookie object\n if (!this.isCookieObject(cookie)) {\n return false;\n }\n\n const formattedDomain = this.formatDomain(cookie.domain);\n\n // Skip cookies with invalid domains\n if (formattedDomain === \"\") {\n return false;\n }\n\n const nameMatches = name === \"%\" || cookie.name === name;\n const domainMatches = domain === \"%\" || formattedDomain.includes(domain);\n\n return nameMatches && domainMatches;\n }\n\n /**\n * Type guard to check if an object is a valid cookie object\n * @param cookie - Object to check\n * @returns True if object has expected cookie properties\n */\n private isCookieObject(cookie: unknown): cookie is {\n domain?: string;\n name: string;\n value: unknown;\n expiry?: number;\n creation?: number;\n flags?: number;\n path?: string;\n version?: number;\n comment?: string;\n commentURL?: string;\n port?: number;\n } {\n return (\n typeof cookie === \"object\" &&\n cookie !== null &&\n \"name\" in cookie &&\n typeof (cookie as { name: unknown }).name === \"string\"\n );\n }\n\n /**\n * Map raw cookie to ExportedCookie format\n * @param cookie - Raw cookie object\n * @param cookieDbPath - Path to cookie database for metadata\n * @returns Formatted ExportedCookie\n */\n private mapToExportedCookie(\n cookie: unknown,\n cookieDbPath: string,\n ): ExportedCookie {\n // We know it's a cookie object due to prior filtering\n const cookieObj = cookie as {\n domain?: string | null;\n name: string;\n value: unknown;\n expiry?: number | null;\n creation?: number | null;\n flags?: number | null;\n path?: string | null;\n version?: number | null;\n comment?: string | null;\n commentURL?: string | null;\n port?: number | null;\n };\n\n return {\n domain: this.formatDomain(cookieObj.domain),\n name: cookieObj.name,\n value: this.processValue(cookieObj.value),\n expiry: this.formatExpiry(cookieObj.expiry),\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n secure: this.isFlagSet(cookieObj.flags, 0x1),\n httpOnly: this.isFlagSet(cookieObj.flags, 0x4),\n path: cookieObj.path ?? undefined,\n version:\n cookieObj.version === undefined ? undefined : cookieObj.version,\n comment: cookieObj.comment ?? undefined,\n commentURL: cookieObj.commentURL ?? undefined,\n port: cookieObj.port === undefined ? undefined : cookieObj.port,\n creation: this.formatCreation(cookieObj.creation),\n },\n };\n }\n\n /**\n * Handle errors that occur during cookie decoding\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n * @param force - Whether interactive prompts were skipped\n * @returns Empty array as fallback\n */\n private async handleDecodingError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const isPermissionError =\n errorMessageContains(error, \"EPERM\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"Permission denied\");\n\n if (isPermissionError) {\n await this.handlePermissionError(\n error,\n cookieDbPath,\n name,\n domain,\n force,\n );\n } else {\n this.logDecodingError(error, cookieDbPath, name, domain);\n }\n\n return [];\n }\n\n /**\n * Handle permission-related errors\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n * @param force - Whether interactive prompts were skipped\n */\n private async handlePermissionError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<void> {\n const handled = await handleSafariPermissionError(error as Error, {\n appName: process.env.TERM_PROGRAM ?? \"Terminal\",\n browserName: \"Safari\",\n interactive: force !== true,\n });\n\n if (handled) {\n this.logger.info(\n \"Permission flow completed. Please run the command again after granting access.\",\n );\n } else {\n this.logger.warn(\n `Permission denied accessing Safari cookies at ${cookieDbPath}`,\n formatErrorForLogging(error, {\n file: cookieDbPath,\n name,\n domain,\n advice:\n \"Grant Full Disk Access to your terminal in System Settings > Privacy & Security\",\n }),\n );\n }\n }\n\n /**\n * Log non-permission errors that occur during decoding\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n */\n private logDecodingError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n ): void {\n this.logger.error(\n `Error decoding ${cookieDbPath}`,\n formatErrorForLogging(error, {\n file: cookieDbPath,\n name,\n domain,\n }),\n );\n }\n\n /**\n * Executes the Safari-specific query logic\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @param store - Optional store path\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns Array of matching cookies, or empty array if none found\n * @protected\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n // Fast path: Safari only exists on macOS\n if (!isMacOS()) {\n this.logger.debug(\"Safari strategy skipped on non-macOS platform\");\n return [];\n }\n\n try {\n this.logger.info(\"Querying cookies\", { name, domain, store });\n\n // Validate home directory\n const home = homedir();\n if (!this.isValidHomeDirectory(home)) {\n return [];\n }\n\n const cookieDbPath = store ?? this.getCookieDbPath(home);\n const normalizedName = name || \"%\";\n const normalizedDomain = domain || \"%\";\n\n // First attempt to decode cookies\n const firstAttemptResult = await this.attemptDecodeWithLockHandling(\n cookieDbPath,\n normalizedName,\n normalizedDomain,\n force,\n );\n\n if (firstAttemptResult.success) {\n return firstAttemptResult.cookies;\n }\n\n // Handle retry scenario if browser was closed\n if (firstAttemptResult.shouldRetry) {\n return this.retryAfterBrowserClose(\n cookieDbPath,\n normalizedName,\n normalizedDomain,\n force,\n firstAttemptResult.shouldRelaunch,\n );\n }\n\n return [];\n } catch (error: unknown) {\n this.logQueryError(error, name, domain);\n return [];\n }\n }\n\n /**\n * Validate home directory\n * @param home - Home directory path\n * @returns True if valid, false otherwise\n */\n private isValidHomeDirectory(home: string): boolean {\n if (typeof home !== \"string\" || home.length === 0) {\n this.logger.error(\"Failed to get home directory\");\n return false;\n }\n return true;\n }\n\n /**\n * Attempt to decode cookies with lock conflict handling\n * @param cookieDbPath - Path to cookie database\n * @param name - Normalized cookie name filter\n * @param domain - Normalized domain filter\n * @param force - Whether to force operations\n * @returns Result object with success status and data\n */\n private async attemptDecodeWithLockHandling(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<{\n success: boolean;\n cookies: ExportedCookie[];\n shouldRetry: boolean;\n shouldRelaunch: boolean;\n }> {\n try {\n const cookies = await this.decodeCookies(\n cookieDbPath,\n name,\n domain,\n force,\n );\n return {\n success: true,\n cookies,\n shouldRetry: false,\n shouldRelaunch: false,\n };\n } catch (error: unknown) {\n return this.handleLockConflict(error, cookieDbPath, force);\n }\n }\n\n /**\n * Handle browser lock conflicts\n * @param error - The error that occurred\n * @param cookieDbPath - Path to cookie database\n * @param force - Whether to force operations\n * @returns Result indicating what action to take next\n */\n private async handleLockConflict(\n error: unknown,\n cookieDbPath: string,\n force?: boolean,\n ): Promise<{\n success: boolean;\n cookies: ExportedCookie[];\n shouldRetry: boolean;\n shouldRelaunch: boolean;\n }> {\n if (!this.isLockError(error)) {\n throw error; // Re-throw non-lock errors\n }\n\n const processes = await isSafariRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n cookieDbPath,\n processes,\n force !== true,\n );\n\n if (lockResult.resolved) {\n return {\n success: false,\n cookies: [],\n shouldRetry: true,\n shouldRelaunch: lockResult.shouldRelaunch,\n };\n }\n\n this.logger.warn(\n \"Safari cookie file locked\",\n formatErrorForLogging(error, {\n file: cookieDbPath,\n advice:\n \"Safari may be accessing the cookie file. Try closing Safari and running again.\",\n }),\n );\n\n return {\n success: false,\n cookies: [],\n shouldRetry: false,\n shouldRelaunch: false,\n };\n }\n\n /**\n * Check if error indicates a lock conflict\n * @param error - Error to check\n * @returns True if this is a lock-related error\n */\n private isLockError(error: unknown): boolean {\n return (\n errorMessageContains(error, \"EPERM\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"Permission denied\") ||\n errorMessageContains(error, \"EBUSY\")\n );\n }\n\n /**\n * Retry cookie extraction after browser was closed\n * @param cookieDbPath - Path to cookie database\n * @param name - Cookie name filter\n * @param domain - Domain filter\n * @param force - Whether to force operations\n * @param shouldRelaunch - Whether browser should be relaunched\n * @returns Cookies or empty array\n */\n private async retryAfterBrowserClose(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n shouldRelaunch?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\n \"Retrying Safari cookie extraction after browser close...\",\n );\n\n const cookies = await this.decodeCookies(\n cookieDbPath,\n name,\n domain,\n force,\n );\n\n this.logger.success(\n \"Successfully extracted cookies after closing Safari\",\n );\n\n if (shouldRelaunch === true) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError: unknown) {\n return this.handleRetryFailure(retryError, cookieDbPath, shouldRelaunch);\n }\n }\n\n /**\n * Handle failure during retry attempt\n * @param retryError - Error that occurred during retry\n * @param cookieDbPath - Path to cookie database\n * @param shouldRelaunch - Whether browser should be relaunched\n * @returns Empty array\n */\n private async handleRetryFailure(\n retryError: unknown,\n cookieDbPath: string,\n shouldRelaunch?: boolean,\n ): Promise<ExportedCookie[]> {\n this.logger.error(\n \"Failed to extract cookies even after closing Safari\",\n formatErrorForLogging(retryError, { file: cookieDbPath }),\n );\n\n // Still try to relaunch Safari if needed\n if (shouldRelaunch === true) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n\n /**\n * Log query errors\n * @param error - The error that occurred\n * @param name - Cookie name filter\n * @param domain - Domain filter\n */\n private logQueryError(error: unknown, name: string, domain: string): void {\n this.logger.error(\n \"Failed to query cookies\",\n formatErrorForLogging(error, { name, domain }),\n );\n }\n}\n","import { exec } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promisify } from \"node:util\";\n\nimport { errorMessageContains, getErrorMessage } from \"./errorUtils\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isMacOS } from \"./platformUtils\";\n\nconst execAsync = promisify(exec);\nconst logger = createTaggedLogger(\"SystemPermissions\");\n\n/**\n *\n */\nexport interface PermissionRequestOptions {\n appName: string;\n browserName: string;\n interactive?: boolean;\n}\n\n/**\n * Open System Settings to the Full Disk Access page on macOS\n */\nasync function openFullDiskAccessSettings(): Promise<void> {\n try {\n // Open System Settings directly to Privacy & Security > Full Disk Access\n await execAsync(\n 'open \"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\"',\n );\n logger.info(\n \"Opened System Settings > Privacy & Security > Full Disk Access\",\n );\n } catch (_error) {\n // Fallback to general Privacy & Security\n try {\n await execAsync(\n 'open \"x-apple.systempreferences:com.apple.preference.security?Privacy\"',\n );\n logger.info(\"Opened System Settings > Privacy & Security\");\n } catch (_fallbackError) {\n // Last resort: just open System Settings\n await execAsync(\"open -b com.apple.systempreferences\");\n logger.info(\"Opened System Settings\");\n }\n }\n}\n\n/**\n * Check which terminal application is running\n * @returns The name of the terminal application or a fallback message\n */\nfunction getTerminalApp(): string {\n const termProgram = process.env.TERM_PROGRAM;\n\n if (termProgram === \"iTerm.app\") {\n return \"iTerm\";\n }\n if (termProgram === \"Apple_Terminal\") {\n return \"Terminal\";\n }\n if (termProgram === \"vscode\") {\n return \"Visual Studio Code\";\n }\n return termProgram ?? \"your terminal application\";\n}\n\n/**\n * Prompt user to grant permissions\n * @param appName - The name of the application requesting permissions\n * @param browserName - The name of the browser being accessed\n * @returns A promise that resolves to true if user grants permission\n */\nasync function promptForPermissionGrant(\n appName: string,\n browserName: string,\n): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n console.log(`\n⚠️ ${browserName} cookie access is blocked by macOS security.\n\nTo grant access, ${appName} needs permission to read ${browserName} data.\n\nWould you like to:\n1. Open System Settings to grant permission (recommended)\n2. Skip ${browserName} cookies for now\n3. Exit\n\nPlease enter your choice (1/2/3): `);\n\n rl.question(\"\", (answer) => {\n rl.close();\n resolve(answer.trim() === \"1\");\n });\n });\n}\n\n/**\n * Handle Safari permission errors with user guidance\n * @param error - The error encountered when accessing Safari cookies\n * @param options - Configuration options for permission requests\n * @returns A promise that resolves to true if permissions should be granted\n */\nexport async function handleSafariPermissionError(\n error: Error,\n options: PermissionRequestOptions,\n): Promise<boolean> {\n if (!isMacOS()) {\n return false;\n }\n\n const isPermissionError =\n errorMessageContains(error, \"eperm\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"permission denied\") ||\n errorMessageContains(error, \"authorization denied\");\n\n if (!isPermissionError) {\n return false;\n }\n\n const terminalApp = options.appName || getTerminalApp();\n\n logger.warn(`${options.browserName} cookie access denied by macOS`, {\n app: terminalApp,\n error: getErrorMessage(error),\n });\n\n if (options.interactive !== false) {\n const shouldOpenSettings = await promptForPermissionGrant(\n terminalApp,\n options.browserName,\n );\n\n if (shouldOpenSettings) {\n await openFullDiskAccessSettings();\n\n console.log(`\n✅ System Settings opened to Privacy & Security\n\nPlease follow these steps:\n1. Look for \"${terminalApp}\" in the list\n2. If not present, click the \"+\" button and add it\n3. Enable the toggle next to \"${terminalApp}\"\n4. You may need to restart ${terminalApp} after granting permission\n5. Then run this command again\n\nPress Enter when you've completed these steps...`);\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n await new Promise<void>((resolve) => {\n rl.question(\"\", () => {\n rl.close();\n resolve();\n });\n });\n\n return true;\n }\n } else {\n logger.info(\n `To grant ${options.browserName} access, add ${terminalApp} to System Settings > Privacy & Security > Full Disk Access`,\n );\n }\n\n return false;\n}\n\n/**\n * Check if we have permission to access a file\n * @param filePath - The path to the file to check permissions for\n * @returns A promise that resolves to true if file is accessible\n */\nexport async function checkFilePermission(filePath: string): Promise<boolean> {\n try {\n const { exec } = await import(\"node:child_process\");\n const { promisify } = await import(\"node:util\");\n const execAsync = promisify(exec);\n\n // Try to read the file\n await execAsync(`cat \"${filePath}\" > /dev/null 2>&1`);\n return true;\n } catch {\n return false;\n }\n}\n","import { Buffer } from \"node:buffer\";\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport type { BinaryCookieRow } from \"../../../types/schemas\";\nimport { createTaggedLogger, logWarn } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodablePage } from \"./BinaryCodablePage\";\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookies\");\n\n/**\n * Represents a binary cookies file structure used by Safari\n */\nexport class BinaryCodableCookies {\n /**\n *\n */\n public pages: BinaryCodablePage[];\n /**\n *\n */\n public metadata: Record<string, unknown>;\n private static readonly MAGIC = Buffer.from(\"cook\", \"utf8\");\n private static readonly FOOTER = BigInt(\"0x071720050000004b\");\n private static readonly DEFAULT_COOKIE_PATH = join(\n homedir(),\n \"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies\",\n );\n\n /**\n * Creates a new BinaryCookies instance from a buffer\n * @param buffer - The raw binary cookie file data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.pages = [];\n this.metadata = {};\n this.decode(container);\n }\n\n /**\n * Creates a BinaryCookies instance from a file path\n * @param path - Path to the Safari Cookies.binarycookies file\n * @returns A new BinaryCookies instance\n */\n public static fromFile(path: string): BinaryCodableCookies {\n const buffer = readFileSync(path);\n return new BinaryCodableCookies(buffer);\n }\n\n /**\n * Creates a BinaryCookies instance from the default Safari cookies location\n * @returns A new BinaryCookies instance\n */\n public static fromDefaultPath(): BinaryCodableCookies {\n return BinaryCodableCookies.fromFile(\n BinaryCodableCookies.DEFAULT_COOKIE_PATH,\n );\n }\n\n /**\n * Converts the binary cookie data into a validated array of cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const page of this.pages) {\n try {\n const pageCookies = page.toCookieRows();\n if (Array.isArray(pageCookies)) {\n cookies.push(...pageCookies);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting page cookies\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n try {\n // Check magic value\n const magic = container.buffer.subarray(\n container.offset,\n container.offset + 4,\n );\n container.offset += 4;\n logger.debug(\"Magic bytes:\", magic.toString());\n if (!magic.equals(BinaryCodableCookies.MAGIC)) {\n throw new Error(\"Missing magic value\");\n }\n\n // Read page count\n const pageCount = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page count:\", pageCount);\n container.offset += 4;\n\n // Read page sizes\n const pageSizes: number[] = [];\n for (let i = 0; i < pageCount; i++) {\n const pageSize = container.buffer.readUInt32BE(container.offset);\n pageSizes.push(pageSize);\n logger.debug(`Page ${i} size:`, pageSize);\n container.offset += 4;\n }\n\n // Calculate page offsets\n let currentOffset = container.offset;\n logger.debug(\"Starting page data at offset:\", currentOffset);\n for (const pageSize of pageSizes) {\n try {\n logger.debug(\n \"Reading page at offset:\",\n currentOffset,\n \"with size:\",\n pageSize,\n );\n const pageBuffer = container.buffer.subarray(\n currentOffset,\n currentOffset + pageSize,\n );\n const page = new BinaryCodablePage(pageBuffer);\n this.pages.push(page);\n currentOffset += pageSize;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger.warn(\"Error decoding page:\", { error: errorMessage });\n currentOffset += pageSize; // Skip the problematic page\n }\n }\n container.offset = currentOffset;\n\n // Read checksum\n const checksum = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Checksum:\", checksum.toString(16));\n container.offset += 4;\n\n // Read footer\n const footer = container.buffer.readBigUInt64BE(container.offset);\n logger.debug(\"Footer:\", footer.toString(16));\n container.offset += 8;\n if (footer !== BinaryCodableCookies.FOOTER) {\n logWarn(\"BinaryCookies\", \"Invalid cookie file format: wrong footer\");\n }\n\n // Read metadata plist\n // const plistData = container.buffer.subarray(container.offset);\n // Note: You'll need to implement or use a plist parser library here\n this.metadata = {}; // Placeholder for plist data\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error decoding binary cookies file\", {\n error: errorMessage,\n });\n throw error;\n }\n }\n}\n","import type { Buffer } from \"node:buffer\";\n\nimport type { BinaryCookieRow } from \"../../../types/schemas\";\nimport { createTaggedLogger, logWarn } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodableCookie } from \"./BinaryCodableCookie\";\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodablePage\");\n\n/**\n * Represents a page of cookies within the binary cookies file\n */\nexport class BinaryCodablePage {\n /**\n *\n */\n public cookies: BinaryCodableCookie[];\n private static readonly HEADER = 0x00000100;\n private static readonly FOOTER = 0x00000000;\n\n /**\n * Creates a new Page instance from a buffer\n * @param buffer - The raw binary page data\n */\n public constructor(buffer: Buffer) {\n this.cookies = [];\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Converts the page's cookies into validated cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const cookie of this.cookies) {\n try {\n const cookieRow = cookie.toCookieRow();\n if (cookieRow !== null) {\n cookies.push(cookieRow);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting cookie\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n // Read page tag (4 bytes)\n const header = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page header:\", header.toString(16));\n container.offset += 4;\n if (header !== BinaryCodablePage.HEADER) {\n throw new Error(\"Invalid page header\");\n }\n\n // Read number of cookies (4 bytes)\n const cookieCount = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie count:\", cookieCount);\n container.offset += 4;\n\n // Store the page start offset for calculating absolute cookie positions\n const pageStart = container.offset - 8;\n logger.debug(\"Page start offset:\", pageStart);\n\n // Read cookie offsets (4 bytes each)\n const cookieOffsets: number[] = [];\n for (let i = 0; i < cookieCount; i++) {\n const cookieOffset = container.buffer.readUInt32LE(container.offset);\n cookieOffsets.push(cookieOffset);\n logger.debug(`Cookie ${i} offset:`, cookieOffset);\n container.offset += 4;\n }\n\n // Read page end marker (4 bytes)\n const footer = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page footer:\", footer.toString(16));\n container.offset += 4;\n if (footer !== BinaryCodablePage.FOOTER) {\n throw new Error(\"Invalid page footer\");\n }\n\n // Read cookies at their offsets\n for (let i = 0; i < cookieCount; i++) {\n try {\n const cookieOffset = cookieOffsets[i]!;\n logger.debug(`Reading cookie ${i} at offset:`, cookieOffset);\n\n // Read cookie size from the cookie header\n const cookieSize = container.buffer.readUInt32LE(cookieOffset);\n logger.debug(`Cookie ${i} size:`, cookieSize);\n if (cookieSize < 48) {\n // Minimum cookie size is 48 bytes (header)\n logger.warn(`Invalid cookie size ${cookieSize} at index ${i}`);\n continue;\n }\n\n // Ensure we don't read past the buffer\n if (cookieOffset + cookieSize > container.buffer.length) {\n logger.warn(\n `Cookie size ${cookieSize} at index ${i} would exceed buffer length ${container.buffer.length}`,\n );\n continue;\n }\n\n const cookieBuffer = container.buffer.subarray(\n cookieOffset,\n cookieOffset + cookieSize,\n );\n const cookie = new BinaryCodableCookie(cookieBuffer);\n this.cookies.push(cookie);\n } catch (error) {\n logger.warn(\"Invalid cookie data\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) => name === \"%\" || /^[!#$%&'()*+\\-.:0-9A-Z ^_`a-z|~]+$/.test(name),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w~]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * logger.info('Valid cookie spec:', result.data);\n * } else {\n * logger.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown())\n .strict();\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * logger.info('Valid cookie:', result.data);\n * } else {\n * logger.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z\n .function()\n .args(\n z.string(),\n z.string(),\n z.string().optional(),\n z.boolean().optional(),\n )\n .returns(z.promise(z.array(ExportedCookieSchema))),\n })\n .strict();\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = z.infer<typeof CookieQueryStrategySchema>;\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n\n/**\n * Schema for base cookie query options\n */\nexport const BaseCookieQueryOptionsSchema = z.object({\n /** Maximum number of cookies to return */\n limit: z.number().int().positive().optional(),\n /** Whether to remove expired cookies from results */\n removeExpired: z.boolean().optional(),\n /** Include expired cookies in results */\n includeExpired: z.boolean().optional(),\n /** Storage location override */\n store: z.string().optional(),\n /** Force query even if browser is running */\n force: z.boolean().optional(),\n});\n\n/**\n * Schema for strategy-based cookie query options\n */\nexport const CookieQueryOptionsSchema = BaseCookieQueryOptionsSchema.extend({\n /** Strategy to use for querying cookies */\n strategy: CookieQueryStrategySchema.optional(),\n});\n\n/**\n * Schema for SQL browser types\n */\nexport const SqlBrowserTypeSchema = z.enum([\n \"chrome\",\n \"chromium\",\n \"edge\",\n \"firefox\",\n \"opera\",\n \"brave\",\n \"arc\",\n]);\n\n/**\n * Schema for SQL-specific cookie query options\n */\nexport const SqlCookieQueryOptionsSchema = CookieSpecSchema.extend({\n /** Browser type for SQL queries */\n browser: SqlBrowserTypeSchema,\n /** Enable exact domain matching instead of wildcard */\n exactDomain: z.boolean().optional(),\n /** Enable case-sensitive matching */\n caseSensitive: z.boolean().optional(),\n /** Maximum number of results */\n limit: z.number().int().positive().optional(),\n /** Include expired cookies */\n includeExpired: z.boolean().optional(),\n});\n\n/**\n * Type for base cookie query options\n */\nexport type BaseCookieQueryOptions = z.infer<\n typeof BaseCookieQueryOptionsSchema\n>;\n\n/**\n * Type for strategy-based cookie query options\n */\nexport type CookieQueryOptions<\n T extends CookieQueryStrategy = CookieQueryStrategy,\n> = BaseCookieQueryOptions & {\n strategy?: T;\n};\n\n/**\n * Type for SQL browser types\n */\nexport type SqlBrowserType = z.infer<typeof SqlBrowserTypeSchema>;\n\n/**\n * Type for SQL-specific cookie query options\n */\nexport type SqlCookieQueryOptions = z.infer<typeof SqlCookieQueryOptionsSchema>;\n","import { Buffer } from \"node:buffer\";\n\nimport {\n type BinaryCookieRow,\n BinaryCookieRowSchema,\n} from \"../../../types/schemas\";\nimport { createTaggedLogger } from \"../../../utils/logHelpers\";\n\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\nimport type { BinaryCodableFlags } from \"./interfaces/BinaryCodableFlags\";\nimport type { BinaryCodableOffsets } from \"./interfaces/BinaryCodableOffsets\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookie\");\n\n/**\n * Represents a single cookie within a page\n * Handles decoding of Safari's binary cookie format\n */\nexport class BinaryCodableCookie {\n /**\n * Cookie version number\n */\n public version = 0;\n\n /**\n * URL the cookie is associated with\n */\n public url = \"\";\n\n /**\n * Port number if specified\n */\n public port?: number;\n\n /**\n * Cookie name\n */\n public name = \"\";\n\n /**\n * Cookie path\n */\n public path = \"\";\n\n /**\n * Cookie value\n */\n public value = \"\";\n\n /**\n * Optional comment\n */\n public comment?: string;\n\n /**\n * Optional comment URL\n */\n public commentURL?: string;\n\n /**\n * Cookie flags (secure, httpOnly, etc.)\n */\n public flags: BinaryCodableFlags = {\n isSecure: false,\n isHTTPOnly: false,\n unknown1: false,\n unknown2: false,\n };\n\n /**\n * Expiration timestamp (Mac epoch seconds)\n */\n public expiration = 0;\n\n /**\n * Creation timestamp (Mac epoch seconds)\n */\n public creation = 0;\n\n /**\n * Creates a new Cookie instance from a buffer\n * @param buffer - The raw binary cookie data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Decode URL encoded values with multiple passes\n * @param value - The URL encoded string\n * @returns Decoded string\n */\n private decodeUrlValue(value: string): string {\n let processed = value;\n let lastProcessed: string;\n do {\n lastProcessed = processed;\n try {\n processed = decodeURIComponent(processed);\n } catch {\n return lastProcessed;\n }\n } while (processed !== lastProcessed && processed.includes(\"%\"));\n return processed;\n }\n\n /**\n * Decode JWT payload if the value is a valid JWT token\n * @param token - The JWT token string\n * @returns Decoded payload as JSON string or null if invalid\n */\n private decodeJwtPayload(token: string): string | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const payloadPart = parts[1];\n if (!payloadPart) {\n return null;\n }\n const payload = Buffer.from(payloadPart, \"base64\").toString(\"utf8\");\n const parsed = JSON.parse(payload) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n /**\n * Parse JSON value and return formatted JSON string\n * @param value - The JSON string to parse\n * @returns Formatted JSON string or null if invalid\n */\n private parseJsonValue(value: string): string | null {\n try {\n const parsed = JSON.parse(value) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n /**\n * Process cookie value with appropriate decoding\n * @param value - The raw cookie value\n * @returns Processed and decoded value as string\n */\n private processValue(value: unknown): string {\n // Handle non-string values\n const primitiveResult = this.handlePrimitiveValues(value);\n if (primitiveResult !== null) {\n return primitiveResult;\n }\n\n // Must be a string at this point\n const stringValue = value as string;\n\n // First, try URL decoding\n const decoded = this.decodeUrlValue(stringValue);\n\n // Try specialized decoding\n return this.trySpecializedDecoding(decoded);\n }\n\n /**\n * Handle primitive value types (null, undefined, buffer, non-string)\n * @param value - The value to check\n * @returns String representation or null if not a primitive type\n */\n private handlePrimitiveValues(value: unknown): string | null {\n if (value === null) {\n return \"null\";\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (Buffer.isBuffer(value)) {\n return value.toString();\n }\n\n if (typeof value !== \"string\") {\n return this.safeStringify(value);\n }\n\n return null; // Not a primitive type\n }\n\n /**\n * Try specialized decoding (JWT, JSON) on the decoded string\n * @param decoded - The URL-decoded string\n * @returns Specialized decoded value or the original decoded string\n */\n private trySpecializedDecoding(decoded: string): string {\n // Try JWT decoding if it looks like a JWT token\n const jwtResult = this.tryJwtDecoding(decoded);\n if (jwtResult !== null) {\n return jwtResult;\n }\n\n // Try JSON parsing if it looks like JSON\n const jsonResult = this.tryJsonDecoding(decoded);\n if (jsonResult !== null) {\n return jsonResult;\n }\n\n return decoded;\n }\n\n /**\n * Try JWT decoding if the value looks like a JWT token\n * @param decoded - The decoded string to check\n * @returns Decoded JWT payload or null if not a JWT or decoding failed\n */\n private tryJwtDecoding(decoded: string): string | null {\n if (decoded.match(/^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/)) {\n const jwtPayload = this.decodeJwtPayload(decoded);\n if (typeof jwtPayload === \"string\" && jwtPayload.length > 0) {\n return jwtPayload;\n }\n }\n return null;\n }\n\n /**\n * Try JSON decoding if the value looks like JSON\n * @param decoded - The decoded string to check\n * @returns Decoded JSON string or null if not JSON or decoding failed\n */\n private tryJsonDecoding(decoded: string): string | null {\n if (decoded.startsWith(\"{\") || decoded.startsWith(\"[\")) {\n const jsonValue = this.parseJsonValue(decoded);\n if (typeof jsonValue === \"string\" && jsonValue.length > 0) {\n return jsonValue;\n }\n }\n return null;\n }\n\n /**\n * Safely convert unknown value to string\n * @param value - The value to stringify\n * @returns String representation of the value\n */\n private safeStringify(value: unknown): string {\n try {\n if (typeof value === \"object\" && value !== null) {\n // For objects, use JSON.stringify if possible, otherwise use toString\n return JSON.stringify(value);\n }\n return String(value);\n } catch {\n // Fallback to String() if JSON.stringify fails\n return String(value);\n }\n }\n\n /**\n * Validates and converts Mac epoch timestamp to Unix epoch\n * @param macTimestamp - Timestamp in Mac epoch (seconds since 2001-01-01)\n * @returns Unix epoch timestamp or 0 for invalid timestamps\n */\n private convertMacTimestamp(macTimestamp: number): number {\n const macToUnixOffset = 978307200; // Seconds between 1970-01-01 and 2001-01-01\n\n if (macTimestamp <= 0) {\n return macTimestamp;\n }\n\n // Validate timestamp bounds - reasonable range is 0 to ~1 billion seconds (2032)\n const isValid =\n macTimestamp >= 0 &&\n macTimestamp <= 1000000000 &&\n Number.isFinite(macTimestamp);\n\n return isValid ? macTimestamp + macToUnixOffset : 0;\n }\n\n /**\n * Converts the cookie to a validated cookie row\n * @returns Validated cookie row object or null if validation fails\n */\n public toCookieRow(): BinaryCookieRow | null {\n try {\n // Convert flags to number\n const flagsValue = this.convertFlags();\n\n // Extract domain from URL\n const domain =\n this.url.replace(/^https?:\\/\\//, \"\").replace(/\\/.*$/, \"\") || \"uk\";\n\n // Convert timestamps from Mac epoch to Unix epoch with validation\n const expiryUnix = this.convertMacTimestamp(this.expiration);\n const creationUnix = this.convertMacTimestamp(this.creation);\n\n // Create cookie row with converted timestamps\n const cookieRow = BinaryCookieRowSchema.parse({\n name: this.name.replace(/^: /, \"\"), // Remove leading ': ' if present\n value: this.processValue(this.value) || \"\", // Process and ensure value is never undefined\n domain,\n path: this.path || \"/\",\n expiry: expiryUnix,\n creation: creationUnix,\n flags: flagsValue,\n version: this.version,\n port: this.port,\n comment: this.comment,\n commentURL: this.commentURL,\n });\n\n return cookieRow;\n } catch (_error) {\n return null;\n }\n }\n\n /**\n * Read the cookie header information\n * @param container - The binary container\n * @returns Object containing size, port flag, and string offsets\n */\n private readHeader(container: BinaryCodableContainer): {\n size: number;\n hasPort: number;\n offsets: BinaryCodableOffsets;\n } {\n // Cookie size (4 bytes)\n const size = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie size:\", size);\n container.offset += 4;\n\n // Version (4 bytes)\n const version = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie version:\", version);\n container.offset += 4;\n\n // Cookie flags (4 bytes)\n const flagsValue = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie flags:\", flagsValue.toString(2).padStart(8, \"0\"));\n container.offset += 4;\n this.flags = {\n isSecure: (flagsValue & 1) !== 0,\n isHTTPOnly: (flagsValue & 4) !== 0,\n unknown1: (flagsValue & 8) !== 0,\n unknown2: (flagsValue & 16) !== 0,\n };\n\n // Has port (4 bytes)\n const hasPort = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Has port:\", hasPort);\n container.offset += 4;\n\n // String offsets (24 bytes total)\n const offsets = {\n urlOffset: container.buffer.readUInt32LE(container.offset),\n nameOffset: container.buffer.readUInt32LE(container.offset + 4),\n pathOffset: container.buffer.readUInt32LE(container.offset + 8),\n valueOffset: container.buffer.readUInt32LE(container.offset + 12),\n commentOffset: container.buffer.readUInt32LE(container.offset + 16),\n commentURLOffset: container.buffer.readUInt32LE(container.offset + 20),\n };\n logger.debug(\"String offsets:\", offsets);\n\n return { size, hasPort, offsets };\n }\n\n /**\n * Read expiration and creation timestamps from the container\n * @param container - The binary container\n */\n private readTimestamps(container: BinaryCodableContainer): void {\n // Read expiration time (8 bytes, little-endian double)\n const expirationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n expirationBuffer[i] = container.buffer[container.offset + i]!;\n }\n const expiration = expirationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Read creation time (8 bytes, little-endian double)\n const creationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n creationBuffer[i] = container.buffer[container.offset + i]!;\n }\n const creation = creationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Store raw timestamps (seconds since 2001-01-01)\n // For expiration time, 0 means \"session cookie\" (expires when browser closes)\n // For creation time, 0 means \"no creation time recorded\"\n this.expiration = expiration;\n this.creation = creation;\n }\n\n /**\n * Read cookie string fields from the container\n * @param container - The binary container\n * @param size - Total size of the cookie\n * @param offsets - String field offsets\n */\n private readStrings(\n container: BinaryCodableContainer,\n size: number,\n offsets: BinaryCodableOffsets,\n ): void {\n // All offsets are relative to the start of the cookie\n const cookieStart = 0; // Offsets are relative to the cookie buffer start\n logger.debug(\"Reading strings from cookie buffer of size:\", size);\n\n // Read strings in order of their offsets\n const offsetEntries = [\n { field: \"url\", offset: offsets.urlOffset },\n { field: \"name\", offset: offsets.nameOffset },\n { field: \"path\", offset: offsets.pathOffset },\n { field: \"value\", offset: offsets.valueOffset },\n { field: \"comment\", offset: offsets.commentOffset },\n ]\n .filter((entry) => entry.offset > 0)\n .sort((a, b) => a.offset - b.offset);\n\n logger.debug(\n \"Reading strings in order:\",\n offsetEntries.map((e) => e.field),\n );\n\n // Calculate string lengths based on offset differences\n for (let i = 0; i < offsetEntries.length; i++) {\n const entry = offsetEntries[i]!;\n const { field, offset } = entry;\n const nextOffset =\n i < offsetEntries.length - 1 ? offsetEntries[i + 1]!.offset : size;\n const length = nextOffset - offset;\n\n // Read string up to null terminator\n let end = cookieStart + offset;\n while (\n end < cookieStart + offset + length &&\n container.buffer[end] !== 0\n ) {\n end++;\n }\n const value = container.buffer.toString(\n \"utf8\",\n cookieStart + offset,\n end,\n );\n logger.debug(`Read ${field}:`, value);\n\n switch (field) {\n case \"url\":\n this.url = value;\n break;\n case \"name\":\n this.name = value;\n break;\n case \"path\":\n this.path = value;\n break;\n case \"value\":\n this.value = value;\n break;\n case \"comment\":\n this.comment = value;\n break;\n }\n }\n }\n\n /**\n * Decode the cookie from the binary container\n * @param container - The binary container with cookie data\n */\n private decode(container: BinaryCodableContainer): void {\n const { size, hasPort, offsets } = this.readHeader(container);\n\n // Skip past all offsets (24 bytes)\n const baseOffset = container.offset;\n container.offset = baseOffset + 24;\n\n this.readTimestamps(container);\n\n if (hasPort > 0) {\n this.port = container.buffer.readUInt16LE(container.offset);\n container.offset += 2;\n }\n\n // Reset offset for string reading\n container.offset = baseOffset;\n this.readStrings(container, size, offsets);\n }\n\n /**\n * Convert cookie flags to numeric representation\n * @returns Numeric flags value\n */\n private convertFlags(): number {\n return (\n (this.flags.isSecure ? 0x1 : 0) |\n (this.flags.isHTTPOnly ? 0x4 : 0) |\n (this.flags.unknown1 ? 0x8 : 0) |\n (this.flags.unknown2 ? 0x10 : 0)\n );\n }\n}\n","import type { BinaryCookieRow } from \"../../../types/schemas\";\n\nimport { BinaryCodableCookies } from \"./BinaryCodableCookies\";\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromFile(cookieDbPath);\n return cookies.toCookieRows();\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromDefaultPath();\n return cookies.toCookieRows();\n}\n","/**\n * CLI adapter for browser cookie query strategies\n * Delegates to core browser modules for actual functionality\n */\n\nimport { detectBrowserFromStore } from \"@core/browsers/BrowserDetector\";\nimport {\n type AnyQueryStrategy,\n createStrategy as createCoreStrategy,\n} from \"@core/browsers/StrategyFactory\";\n\n/**\n * Represents a strategy for querying cookies from a browser\n * This is a type alias for the base strategy to maintain backward compatibility\n */\nexport type CookieQueryStrategy = AnyQueryStrategy;\n\n/**\n * Factory for creating browser-specific cookie query strategies\n * This is now a thin wrapper around the core StrategyFactory\n */\nexport const CookieStrategyFactory = {\n /**\n * Detects the cookie store type from a file path\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n * @deprecated Use detectBrowserFromStore from @core/browsers/BrowserDetector\n */\n detectStoreType(storePath: string): string | undefined {\n return detectBrowserFromStore(storePath);\n },\n\n /**\n * Creates a strategy for the specified browser\n * @param browser - The browser to create a strategy for\n * @param storePath - Optional path to a cookie store file\n * @param profile - Optional Chrome profile name\n * @returns A cookie query strategy for the specified browser\n */\n createStrategy(\n browser?: string,\n storePath?: string,\n profile?: string,\n ): CookieQueryStrategy {\n // Delegate to the core strategy factory\n // Only pass defined values to avoid exactOptionalPropertyTypes issues\n const options: Parameters<typeof createCoreStrategy>[0] = {};\n if (browser !== undefined) {\n options.browser = browser;\n }\n if (storePath !== undefined) {\n options.storePath = storePath;\n }\n if (profile !== undefined) {\n options.profile = profile;\n }\n return createCoreStrategy(options);\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/config.ts","../src/utils/logger.ts","../src/utils/logHelpers.ts","../src/utils/platformUtils.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/utils/execSimple.ts","../src/core/browsers/chrome/windows/getChromePassword.ts","../src/core/browsers/chrome/linux/getChromePassword.ts","../src/core/browsers/sql/CookieQueryBuilder.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/cookies/cookieSpecsFromUrl.ts","../src/utils/argv.ts","../src/cli/cli.ts","../src/utils/errorUtils.ts","../src/cli/cliQueryCookies.ts","../src/utils/jwt.ts","../src/core/cookies/JwtCookieDetector.ts","../src/cli/handlers/DefaultOutputHandler.ts","../src/cli/handlers/DumpOutputHandler.ts","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isSymbol.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayMap.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseToString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/identity.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_defineProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAssignValue.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKey.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/memoize.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_memoizeCapped.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stringToPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/toString.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_castPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toKey.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/get.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsMatch.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isStrictComparable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMatchData.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseMatches.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseHasIn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hasPath.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/hasIn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseMatchesProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseProperty.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_basePropertyDeep.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/property.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIteratee.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseFor.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseFor.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseForOwn.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseEach.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseEach.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createAggregator.js","../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/groupBy.js","../src/cli/handlers/GroupedDumpOutputHandler.ts","../src/core/cookies/renderCookies.ts","../src/cli/handlers/GroupedRenderOutputHandler.ts","../src/cli/handlers/JsonOutputHandler.ts","../src/cli/handlers/RenderOutputHandler.ts","../src/cli/handlers/OutputHandlerFactory.ts","../src/cli/services/CookieQueryService.ts","../src/core/browsers/BrowserDetector.ts","../src/core/browsers/StrategyFactory.ts","../src/core/browsers/chrome/ChromiumBrowsers.ts","../src/core/browsers/chromium/BaseChromiumCookieQueryStrategy.ts","../src/utils/ProcessDetector.ts","../src/utils/chromeDates.ts","../src/core/browsers/BaseCookieQueryStrategy.ts","../src/utils/BrowserControl.ts","../src/utils/FileHandleDetector.ts","../src/core/browsers/platform/PlatformBrowserControl.ts","../src/core/browsers/BrowserLockHandler.ts","../src/core/browsers/chrome/decrypt.ts","../src/core/browsers/chrome/windows/decryptV10Cookie.ts","../src/core/browsers/chrome/getChromiumPassword.ts","../src/core/browsers/sql/DatabaseConnectionManager.ts","../src/core/browsers/sql/QueryMonitor.ts","../src/core/browsers/chromium/ChromiumCookieQueryStrategy.ts","../src/core/browsers/arc/ArcCookieQueryStrategy.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/utils/flatMapAsync.ts","../src/core/browsers/CompositeCookieQueryStrategy.ts","../src/core/browsers/edge/EdgeCookieQueryStrategy.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/core/browsers/opera/OperaCookieQueryStrategy.ts","../src/core/browsers/opera/OperaGXCookieQueryStrategy.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/utils/SystemPermissions.ts","../src/core/browsers/safari/BinaryCodableCookies.ts","../src/core/browsers/safari/BinaryCodablePage.ts","../src/types/schemas.ts","../src/core/browsers/safari/BinaryCodableCookie.ts","../src/core/browsers/safari/decodeBinaryCookies.ts","../src/cli/services/CookieStrategyFactory.ts"],"names":["EnvironmentSchema","env","init_config","__esmMin","config","z","val","homedir","consola","logger","logger_default","init_logger","createConsola","logError","message","error","context","errorMessage","logWarn","component","createTaggedLogger","init_logHelpers","getPlatform","platformCache","osPlatform","isMacOS","isWindows","isPlatformSupported","p","assertPlatformSupported","init_platformUtils","chromeApplicationSupport","init_ChromeApplicationSupport","home","join","execSimple","command","options","result","execPromise","CommandExecutionError","init_execSimple","promisify","exec","originalError","getChromePassword_exports","__export","getChromePassword","decryptDPAPIKey","encryptedKey","DPAPI_PREFIX","encryptedData","dpapi","localStatePath","localStateContent","readFileSync","localState","encryptedKeyBuffer","init_getChromePassword","password","CookieQueryBuilder_exports","CookieQueryBuilder","createQueryBuilder","isSqlBrowser","browser","BROWSER_SCHEMAS","init_CookieQueryBuilder","name","domain","exactDomain","limit","includeExpired","schema","selectColumns","whereClause","params","sql","specs","specConditions","allParams","spec","combinedWhere","minLimit","min","key","columns","col","conditions","nowSeconds","sqlKeywords","checkString","str","field","upperStr","keyword","listChromeProfilePaths","files","fg","listChromeProfiles","processDomainsIntoCookieSpecs","parts","cookieSpecs","i","subDomain","cookieSpecsFromUrl","url","urlObj","CLI_OPTIONS","generateKnownFlags","flags","opt","short","long","KNOWN_FLAGS","parseArgv","argv","parsed","minimist","arg","flag","_","values","getErrorMessage","getErrorDetails","errorMessageContains","searchText","DATABASE_ERROR_PATTERNS","containsAnyPattern","patterns","pattern","getDatabaseErrorType","formatErrorForLogging","details","JWT_FORMAT_REGEX","isJWT","value","validateTokenFormat","token","verifySignature","secretOrPublicKey","jsonwebtoken","verifyError","checkExpiration","payload","exp","now","debugLog","data","validateTokenInput","decodeAndValidatePayload","validateToken","inputError","formatResult","signatureResult","decodeToken","detectJwtCookies","cookies","validateSignature","secretKey","decodeClaims","verbose","cookie","jwtMeta","validation","enrichJwtMetadata","decoded","meta","filterJwtCookies","DefaultOutputHandler","_args","results","uniqueValues","DumpOutputHandler","args","freeGlobal","freeGlobal_default","freeSelf","root","root_default","Symbol","Symbol_default","objectProto","hasOwnProperty","nativeObjectToString","symToStringTag","getRawTag","isOwn","tag","unmasked","getRawTag_default","objectToString","objectToString_default","nullTag","undefinedTag","baseGetTag","baseGetTag_default","isObjectLike","isObjectLike_default","symbolTag","isSymbol","isSymbol_default","arrayMap","array","iteratee","index","length","arrayMap_default","isArray","isArray_default","symbolProto","symbolToString","baseToString","INFINITY","baseToString_default","isObject","type","isObject_default","identity","identity_default","asyncTag","funcTag","genTag","proxyTag","isFunction","isFunction_default","coreJsData","coreJsData_default","maskSrcKey","uid","isMasked","func","isMasked_default","funcProto","funcToString","toSource","toSource_default","reRegExpChar","reIsHostCtor","reIsNative","baseIsNative","baseIsNative_default","getValue","object","getValue_default","getNative","getNative_default","WeakMap","WeakMap_default","defineProperty","defineProperty_default","MAX_SAFE_INTEGER","reIsUint","isIndex","isIndex_default","baseAssignValue","baseAssignValue_default","eq","other","eq_default","isLength","isLength_default","isArrayLike","isArrayLike_default","isPrototype","Ctor","proto","isPrototype_default","baseTimes","n","baseTimes_default","argsTag","baseIsArguments","baseIsArguments_default","propertyIsEnumerable","isArguments","isArguments_default","stubFalse","stubFalse_default","freeExports","freeModule","moduleExports","Buffer","nativeIsBuffer","isBuffer","isBuffer_default","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_default","baseUnary","baseUnary_default","freeProcess","nodeUtil","types","nodeUtil_default","nodeIsTypedArray","isTypedArray","isTypedArray_default","arrayLikeKeys","inherited","isArr","isArg","isBuff","isType","skipIndexes","arrayLikeKeys_default","overArg","transform","overArg_default","nativeKeys","nativeKeys_default","baseKeys","baseKeys_default","keys","keys_default","reIsDeepProp","reIsPlainProp","isKey","isKey_default","nativeCreate","nativeCreate_default","hashClear","hashClear_default","hashDelete","hashDelete_default","HASH_UNDEFINED","hashGet","hashGet_default","hashHas","hashHas_default","hashSet","hashSet_default","Hash","entries","entry","Hash_default","listCacheClear","listCacheClear_default","assocIndexOf","assocIndexOf_default","arrayProto","splice","listCacheDelete","lastIndex","listCacheDelete_default","listCacheGet","listCacheGet_default","listCacheHas","listCacheHas_default","listCacheSet","listCacheSet_default","ListCache","ListCache_default","Map","Map_default","mapCacheClear","mapCacheClear_default","isKeyable","isKeyable_default","getMapData","map","getMapData_default","mapCacheDelete","mapCacheDelete_default","mapCacheGet","mapCacheGet_default","mapCacheHas","mapCacheHas_default","mapCacheSet","size","mapCacheSet_default","MapCache","MapCache_default","FUNC_ERROR_TEXT","memoize","resolver","memoized","cache","memoize_default","MAX_MEMOIZE_SIZE","memoizeCapped","memoizeCapped_default","rePropName","reEscapeChar","stringToPath","string","match","number","quote","subString","stringToPath_default","toString","toString_default","castPath","castPath_default","toKey","toKey_default","baseGet","path","baseGet_default","get","defaultValue","get_default","arrayPush","offset","arrayPush_default","stackClear","stackClear_default","stackDelete","stackDelete_default","stackGet","stackGet_default","stackHas","stackHas_default","LARGE_ARRAY_SIZE","stackSet","pairs","stackSet_default","Stack","Stack_default","arrayFilter","predicate","resIndex","arrayFilter_default","stubArray","stubArray_default","nativeGetSymbols","getSymbols","symbol","getSymbols_default","baseGetAllKeys","keysFunc","symbolsFunc","baseGetAllKeys_default","getAllKeys","getAllKeys_default","DataView","DataView_default","Promise","Promise_default","Set","Set_default","promiseTag","dataViewCtorString","mapCtorString","promiseCtorString","setCtorString","weakMapCtorString","getTag","ctorString","getTag_default","Uint8Array","Uint8Array_default","setCacheAdd","setCacheAdd_default","setCacheHas","setCacheHas_default","SetCache","SetCache_default","arraySome","arraySome_default","cacheHas","cacheHas_default","COMPARE_PARTIAL_FLAG","COMPARE_UNORDERED_FLAG","equalArrays","bitmask","customizer","equalFunc","stack","isPartial","arrLength","othLength","arrStacked","othStacked","seen","arrValue","othValue","compared","othIndex","equalArrays_default","mapToArray","mapToArray_default","setToArray","set","setToArray_default","symbolValueOf","equalByTag","convert","stacked","equalByTag_default","equalObjects","objProps","objLength","othProps","objStacked","skipCtor","objValue","objCtor","othCtor","equalObjects_default","baseIsEqualDeep","objIsArr","othIsArr","objTag","othTag","objIsObj","othIsObj","isSameTag","objIsWrapped","othIsWrapped","objUnwrapped","othUnwrapped","baseIsEqualDeep_default","baseIsEqual","baseIsEqual_default","baseIsMatch","source","matchData","noCustomizer","srcValue","baseIsMatch_default","isStrictComparable","isStrictComparable_default","getMatchData","getMatchData_default","matchesStrictComparable","matchesStrictComparable_default","baseMatches","baseMatches_default","baseHasIn","baseHasIn_default","hasPath","hasFunc","hasPath_default","hasIn","hasIn_default","baseMatchesProperty","baseMatchesProperty_default","baseProperty","baseProperty_default","basePropertyDeep","basePropertyDeep_default","property","property_default","baseIteratee","baseIteratee_default","arrayAggregator","setter","accumulator","arrayAggregator_default","createBaseFor","fromRight","iterable","props","createBaseFor_default","baseFor","baseFor_default","baseForOwn","baseForOwn_default","createBaseEach","eachFunc","collection","createBaseEach_default","baseEach","baseEach_default","baseAggregator","baseAggregator_default","createAggregator","initializer","createAggregator_default","groupBy","groupBy_default","GroupedDumpOutputHandler","groupedByFile","r","renderCookies","format","showFilePaths","separator","c","file","fileCookies","GroupedRenderOutputHandler","JsonOutputHandler","RenderOutputHandler","OutputHandlerFactory","validFormats","handler","CookieQueryService","strategy","SAFARI_MAGIC_BYTES","BROWSER_PATTERNS","filename","checkSafariMagicBytes","storePath","buffer","detectBrowserFromFilename","detectBrowserFromStore","existsSync","detectedBrowser","isValidBrowserType","getChromiumBrowserPath","currentPlatform","paths","parseProcessLine","line","defaultCommand","pidStr","pid","parsedCommand","parseWindowsProcessLine","detectBrowserProcesses","browserName","grepPattern","windowsProcessMap","processName","stdout","processes","lines","processInfo","isFirefoxRunning","isChromeRunning","isSafariRunning","getBrowserConflictAdvice","processCount","browserDisplayName","chromeTimestampToDate","chromeTimestamp","unixTimestampSeconds","fallbackLogger","BaseCookieQueryStrategy","strategyName","taggedLogger","store","force","execAsync","isInteractiveEnvironment","isCI","isTest","BROWSER_APP_NAMES","isBrowserRunningMacOS","appName","script","quitBrowserMacOS","quitScript","resolve","saveBrowserSessionMacOS","promptUserConfirmation","rl","readline","answer","closeBrowserGracefully","success","waitForBrowserToClose","maxWaitMs","startTime","checkInterval","execFileAsync","execFile","parseFuserLine","user","mode","isValidProcessResult","parsePowerShellOutput","handles","processId","parseError","detectWithLsof","filePath","fd","handle","detectWithFuser","output","detectOnWindows","escapedPath","psScript","detectWithHandleExe","detectFileHandles","os","h","getFileLockInfo","BasePlatformBrowserControl","_BasePlatformBrowserControl","executables","exe","checkCommand","MacOSBrowserControl","WindowsBrowserControl","LinuxBrowserControl","cmd","platformControlInstance","createPlatformBrowserControl","platformOverride","control","createControlForPlatform","platform","BrowserLockHandler","platformControl","autoClose","dbErrorType","fileHandles","lockInfo","handleError","processError","processesWithDetails","advice","relaunchError","decryptV10Cookie","encryptedValue","VERSION_PREFIX","ciphertext","NONCE_LENGTH","TAG_LENGTH","nonce","authTag","decipher","createDecipheriv","isV10Cookie","memoizeBuffer","fn","keyFn","cachedResult","removeV10Prefix","removePadding","decrypted","padding","extractValue","decodedString","uuidMatch","endPatterns","cleanupPatterns","decrypt","metaVersion","reject","pbkdf2","iv","e","MACOS_KEYCHAIN_SERVICES","getMacOSPassword","service","chromeCommand","getWindowsPassword","getLinuxPassword","getChromiumPassword","DatabaseConnectionManager","EventEmitter","filepath","existing","lastError","attempt","database","BetterSqlite3","metadata","connectionTime","queryFn","queryDescription","connection","duration","metrics","totalQueryTime","totalQueryCount","activeConnections","toClose","lruPath","lruTime","ms","globalManager","exitHandler","getGlobalConnectionManager","QueryMonitor","db","execution","stmt","MonitoredStatement","statement","monitor","globalMonitor","getGlobalQueryMonitor","createExportedCookie","expiry","BaseChromiumCookieQueryStrategy","browserType","fileResults","connectionManager","queryBuilder","queryOptions","queryConfig","encryptedCookies","row","cookieFiles","lockResult","shouldRelaunch","retryError","metaQuery","metaResult","decryptedValue","ChromiumCookieQueryStrategy","browserPath","ArcCookieQueryStrategy","ChromeCookieQueryStrategy","profileName","fs","firstPath","chromeDataDir","dirname","profileCache","targetDir","dir","info","cookiePath","flatMapAsync","callback","item","CompositeCookieQueryStrategy","strategies","EdgeCookieQueryStrategy","findFirefoxCookieFiles","profileDirs","devEditionPath","esrPath","localFirefoxPath","matches","FirefoxCookieQueryStrategy","retryConfig","fileList","OperaCookieQueryStrategy","OperaGXCookieQueryStrategy","openFullDiskAccessSettings","getTerminalApp","termProgram","promptForPermissionGrant","handleSafariPermissionError","terminalApp","checkFilePermission","CookieDomainSchema","CookieNameSchema","CookiePathSchema","CookieValueSchema","destr","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","BrowserNameSchema","CookieQueryStrategySchema","BaseCookieQueryOptionsSchema","SqlBrowserTypeSchema","BinaryCodableCookie","container","processed","lastProcessed","payloadPart","primitiveResult","stringValue","jwtResult","jsonResult","jwtPayload","jsonValue","macTimestamp","flagsValue","expiryUnix","creationUnix","version","hasPort","offsets","expirationBuffer","expiration","creationBuffer","creation","offsetEntries","a","b","end","baseOffset","_BinaryCodablePage","cookieRow","header","cookieCount","pageStart","cookieOffsets","cookieOffset","footer","cookieSize","cookieBuffer","BinaryCodablePage","_BinaryCodableCookies","page","pageCookies","magic","pageCount","pageSizes","pageSize","currentOffset","pageBuffer","checksum","BinaryCodableCookies","decodeBinaryCookies","cookieDbPath","SafariCookieQueryStrategy","bit","formattedDomain","nameMatches","domainMatches","cookieObj","normalizedName","normalizedDomain","firstAttemptResult","STRATEGY_REGISTRY","createBrowserStrategy","Strategy","createCompositeStrategy","createStrategy","profile","normalizedBrowser","CookieStrategyFactory","queryAndLimitCookies","queryService","cookieMap","buildQueryOptions","removeExpired","deduplicateCookies","cliQueryCookies","cookieSpec","jwtOptions","showHelp","createCookieSpec","normalizeWildcard","listProfiles","browserLower","profiles","dataDir","homeDir","appData","getCookieSpecs","positionals","handleCookieQuery","main"],"mappings":";mxBAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OA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AO,CACVA,CAAAA,YAAiB,KAAA,CACnBL,CAAAA,CAAO,KAAA,CAAM,yBAAA,CAA2BK,CAAAA,CAAM,OAAO,CAAA,CAErDL,CAAAA,CAAO,KAAA,CAAM,kDAAkD,EAEnE,CACF,CAEA,eAAem7B,EAAAA,EAAsB,CACnC,IAAMhxB,CAAAA,CAAO,OAAA,CAAQ,KAAK,KAAA,CAAM,CAAC,CAAA,CAGjC,GAAIA,CAAAA,CAAK,MAAA,GAAW,CAAA,CAAG,CACrBowB,IAAS,CACT,MACF,CAEA,GAAM,CAAE,MAAA,CAAAxzB,CAAAA,CAAQ,WAAA,CAAAk0B,CAAY,CAAA,CAAIz0B,EAAAA,CAAU2D,CAAI,CAAA,CAE9C,GAAIpD,CAAAA,CAAO,IAAA,GAAS,KAAM,CACxBwzB,EAAAA,EAAS,CACT,MACF,CAEA,GAAIxzB,CAAAA,CAAO,eAAe,CAAA,GAAM,IAAA,CAAM,CACpC,IAAMzD,CAAAA,CACJ,OAAOyD,CAAAA,CAAO,OAAA,EAAY,SAAWA,CAAAA,CAAO,OAAA,CAAU,MAAA,CACxD2zB,EAAAA,CAAap3B,CAAO,CAAA,CACpB,MACF,CAEA,MAAM43B,EAAAA,CAAkBn0B,CAAAA,CAAQk0B,CAAW,EAC7C,CAEAE,EAAAA,EAAK,CAAE,MAAO96B,CAAAA,EAAU,CAClBA,CAAAA,YAAiB,KAAA,CACnBL,CAAAA,CAAO,KAAA,CAAM,cAAA,CAAgBK,CAAAA,CAAM,OAAO,CAAA,CAE1CL,CAAAA,CAAO,KAAA,CAAM,iCAAiC,CAAA,CAEhD,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CAAC,CAAA","file":"cli.cjs","sourcesContent":["import { homedir } from \"node:os\";\n\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\n\n// Load environment variables from .env file\nconfig();\n\nconst EnvironmentSchema = z.object({\n LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n HOME: z\n .string()\n .optional()\n .transform((val) => val ?? process.env.USERPROFILE ?? \"\")\n .pipe(z.string().min(1)),\n});\n\n/**\n * Validated environment variables with type safety and fallbacks\n * @example\n * // Using the environment variables\n * if (env.LOG_LEVEL === \"debug\") {\n * console.log(\"Debug mode enabled\");\n * }\n *\n * // Accessing home directory\n * const cookiePath = join(env.HOME, \"Library/Cookies\");\n */\nexport const env = EnvironmentSchema.parse({\n LOG_LEVEL: process.env.LOG_LEVEL,\n HOME: homedir(),\n});\n","import { type ConsolaInstance, createConsola } from \"consola\";\n\nimport { env } from \"../config\";\n\n/**\n * Standard log levels and their usage:\n * - debug: Detailed information for debugging\n * - info: General operational information\n * - success: Successful operations\n * - warn: Warning conditions\n * - error: Error conditions that might still allow the app to continue\n * - fatal: Critical errors that prevent the app from continuing\n */\nconst consola = createConsola({\n formatOptions: {\n showLogLevel: false,\n colors: true,\n date: false,\n compact: true,\n columns:\n typeof process.stdout.columns === \"number\" ? process.stdout.columns : 80,\n },\n level: env.LOG_LEVEL === \"debug\" ? 5 : 2,\n});\n\n/**\n * Indicates whether debug logging is enabled\n * @example\n * if (isDebug) {\n * logger.debug(\"Detailed debugging information\");\n * }\n */\nexport const isDebug = env.LOG_LEVEL === \"debug\";\n\n/**\n * Configured logger instance with standardized formatting and colored output.\n * Used for consistent logging throughout the application.\n * @example\n * // Basic usage\n * logger.info('Operation started');\n * logger.success('Task completed');\n * logger.error('Failed to process', error);\n *\n * // Tagged logging for module context\n * const moduleLogger = logger.withTag('ModuleName');\n * moduleLogger.info('Module specific log');\n *\n * // Structured logging\n * logger.info('User action', {\n * userId: '123',\n * action: 'login',\n * timestamp: new Date()\n * });\n *\n * // Error logging with full context\n * logger.error('Operation failed', {\n * error: error,\n * context: 'operation name',\n * input: data\n * });\n */\nconst logger: ConsolaInstance = consola;\n\n/**\n *\n */\nexport default logger;\n","import type { ConsolaInstance } from \"consola\";\n\nimport logger from \"./logger\";\n\n/**\n * Helper functions for common logging patterns.\n * @module\n * @example\n * ```typescript\n * import { logOperationResult, logError } from './logHelpers';\n *\n * try {\n * const result = await someOperation();\n * logOperationResult('Operation', true, { data: result });\n * } catch (error) {\n * logError('Operation failed', error);\n * }\n * ```\n */\n\ninterface OperationContext {\n [key: string]: unknown;\n}\n\n/**\n * Log the result of an operation with consistent formatting\n * @param operation - The name of the operation\n * @param success - Whether the operation was successful\n * @param context - Additional context to log\n */\nexport function logOperationResult(\n operation: string,\n success: boolean,\n context?: OperationContext,\n): void {\n if (success) {\n logger.success(`${operation} succeeded`, context);\n } else {\n logger.error(`${operation} failed`, context);\n }\n}\n\n/**\n * Log an error with consistent formatting\n * @param message - The error message\n * @param error - The error object\n * @param context - Additional context to log\n */\nexport function logError(\n message: string,\n error: unknown,\n context?: OperationContext,\n): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(message, { ...context, error: errorMessage });\n}\n\n/**\n * Log a warning with consistent formatting\n * @param component - The component generating the warning\n * @param message - The warning message\n * @param context - Additional context to log\n */\nexport function logWarn(\n component: string,\n message: string,\n context?: OperationContext,\n): void {\n logger.warn(`[${component}] ${message}`, context);\n}\n\n/**\n * Create a logger instance with a component tag\n * @param component - The component name to tag logs with\n * @returns A logger instance that prefixes all messages with the component tag\n * @example\n * ```typescript\n * const dbLogger = createTaggedLogger('Database');\n * dbLogger.info('Connection established');\n * ```\n */\nexport function createTaggedLogger(component: string): ConsolaInstance {\n return logger.withTag(component);\n}\n\n// Re-export the base logger for direct usage\n/**\n * Re-export of the base logger for direct usage.\n */\nexport { default as logger } from \"./logger\";\n","import { platform as osPlatform } from \"node:os\";\n\n/**\n * Cache for platform value\n */\nlet platformCache: string | undefined;\n\n/**\n * Clear the platform cache (for testing)\n * @internal\n */\nexport function clearPlatformCache(): void {\n platformCache = undefined;\n}\n\n/**\n * Supported platform types\n */\nexport type Platform = \"darwin\" | \"win32\" | \"linux\";\n\n/**\n * Get the current platform (with caching)\n * @returns The current platform from os.platform()\n */\nexport function getPlatform(): string {\n platformCache ??= osPlatform();\n return platformCache;\n}\n\n/**\n * Check if the current platform is macOS\n * @returns True if running on macOS\n */\nexport function isMacOS(): boolean {\n return getPlatform() === \"darwin\";\n}\n\n/**\n * Check if the current platform is Windows\n * @returns True if running on Windows\n */\nexport function isWindows(): boolean {\n return getPlatform() === \"win32\";\n}\n\n/**\n * Check if the current platform is Linux\n * @returns True if running on Linux\n */\nexport function isLinux(): boolean {\n return getPlatform() === \"linux\";\n}\n\n/**\n * Check if the current platform is Unix-like (macOS, Linux, FreeBSD, etc.)\n * @returns True if running on a Unix-like system\n */\nexport function isUnixLike(): boolean {\n const p = getPlatform();\n return p !== \"win32\";\n}\n\n/**\n * Check if the current platform is supported\n * @returns True if the platform is supported\n */\nexport function isPlatformSupported(): boolean {\n const p = getPlatform();\n return p === \"darwin\" || p === \"win32\" || p === \"linux\";\n}\n\n/**\n * Get a human-readable platform name\n * @returns A human-readable platform name\n */\nexport function getPlatformDisplayName(): string {\n const platform = getPlatform();\n switch (platform) {\n case \"darwin\":\n return \"macOS\";\n case \"win32\":\n return \"Windows\";\n case \"linux\":\n return \"Linux\";\n default:\n return platform;\n }\n}\n\n/**\n * Throw an error if the current platform is not supported\n * @throws Error if platform is not supported\n */\nexport function assertPlatformSupported(): void {\n if (!isPlatformSupported()) {\n throw new Error(\n `Unsupported platform: ${getPlatform()}. Supported platforms are: darwin, win32, linux`,\n );\n }\n}\n\n/**\n * Get platform-specific path separator\n * @returns The path separator for the current platform\n */\nexport function getPathSeparator(): string {\n return isWindows() ? \"\\\\\" : \"/\";\n}\n\n/**\n * Get platform-specific executable extension\n * @returns The executable extension for the current platform\n */\nexport function getExecutableExtension(): string {\n return isWindows() ? \".exe\" : \"\";\n}\n\n/**\n * Check if the current platform matches any of the specified platforms\n * @param platforms - Platform or platforms to check against current platform\n * @returns True if the current platform matches any of the specified platforms\n */\nexport function isPlatform(...platforms: string[]): boolean {\n const current = osPlatform();\n return platforms.includes(current);\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\n/**\n * The path to Chrome's application support directory for the current platform\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @throws {Error} If unable to determine user's home directory or platform is not supported\n */\nexport const chromeApplicationSupport = (() => {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n assertPlatformSupported();\n\n switch (getPlatform()) {\n case \"darwin\":\n return join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\");\n case \"win32\":\n return join(home, \"AppData\", \"Local\", \"Google\", \"Chrome\", \"User Data\");\n case \"linux\":\n return join(home, \".config\", \"google-chrome\");\n default:\n // This should never happen due to assertPlatformSupported\n throw new Error(`Platform ${getPlatform()} is not supported`);\n }\n})();\n","// External imports\nimport { type ExecOptions, exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\n// Internal imports\nimport { logError } from \"./logHelpers\";\n\nconst execPromise = promisify(exec);\n\n/**\n * Custom error class for command execution failures.\n * @property {string} command - The command that failed to execute\n * @property {Error} [originalError] - The underlying error that caused the failure\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * throw new CommandExecutionError(\n * 'Command timed out',\n * 'git status',\n * originalError\n * );\n * ```\n */\nclass CommandExecutionError extends Error {\n public constructor(\n message: string,\n public readonly command: string,\n public readonly originalError?: Error,\n ) {\n super(message);\n this.name = \"CommandExecutionError\";\n }\n}\n\n/**\n * Executes a shell command and returns its output.\n * @param command - The command to execute\n * @param options - Optional execution options\n * @returns Promise resolving to command output\n * @throws CommandExecutionError if execution fails\n * @example\n * ```typescript\n * try {\n * const { stdout } = await execSimple('git status');\n * logger.info('Git status:', stdout);\n * } catch (error) {\n * if (error instanceof CommandExecutionError) {\n * logger.error('Git command failed:', error.message);\n * }\n * }\n * ```\n */\nexport async function execSimple(\n command: string,\n options?: ExecOptions,\n): Promise<{ stdout: string; stderr: string }> {\n try {\n const result = await execPromise(command, {\n ...options,\n encoding: \"utf8\",\n });\n return {\n stdout: result.stdout.toString(),\n stderr: result.stderr.toString(),\n };\n } catch (error) {\n logError(\"Command execution failed\", error, { command });\n throw new CommandExecutionError(\n error instanceof Error ? error.message : String(error),\n command,\n error instanceof Error ? error : undefined,\n );\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { isWindows } from \"@utils/platformUtils\";\n\nimport { chromeApplicationSupport } from \"../ChromeApplicationSupport\";\n\n/**\n * Windows Chrome Local State file structure for encrypted key\n */\ninterface WindowsChromeLocalState {\n os_crypt: {\n encrypted_key: string;\n };\n}\n\n/**\n * Decrypts Windows DPAPI encrypted key using Windows CryptoAPI\n * On Windows, Chrome uses DPAPI (Data Protection API) to encrypt the master key\n * which is then used to encrypt cookies.\n * @param encryptedKey - The DPAPI encrypted key buffer\n * @returns A promise that resolves to the decrypted key as a Buffer\n * @throws {Error} If DPAPI decryption fails or key format is invalid\n */\nasync function decryptDPAPIKey(encryptedKey: Buffer): Promise<Buffer> {\n // Remove the DPAPI prefix (first 5 bytes: \"DPAPI\")\n const DPAPI_PREFIX = Buffer.from(\"DPAPI\");\n if (!encryptedKey.subarray(0, 5).equals(DPAPI_PREFIX)) {\n throw new Error(\"Invalid DPAPI key prefix\");\n }\n\n const encryptedData = encryptedKey.subarray(5);\n\n // Try to use native DPAPI if available on Windows\n if (isWindows()) {\n try {\n // Use dynamic import to load optional dependency at runtime\n // This works in both ESM and CommonJS contexts\n const moduleName = \"@primno\" + \"/dpapi\"; // Split to prevent static analysis\n const dpapi = (await import(moduleName)) as {\n unprotectData: (data: Buffer) => Buffer;\n };\n\n if (typeof dpapi.unprotectData === \"function\") {\n return dpapi.unprotectData(encryptedData);\n }\n } catch (error) {\n // Module not available or failed to load - this is expected for optional dependency\n // Don't log the full error to avoid cluttering output\n if (process.env.VERBOSE !== undefined && process.env.VERBOSE !== \"\") {\n console.warn(\"DPAPI module not available:\", error);\n }\n }\n }\n\n // Fallback for testing or when DPAPI is not available\n // This won't work for real encrypted cookies but allows the code to run\n throw new Error(\n \"Windows DPAPI decryption requires native bindings. Install @primno/dpapi package for Windows support.\",\n );\n}\n\n/**\n * Retrieves the Chrome Safe Storage password on Windows\n * On Windows, Chrome stores an encrypted master key in Local State file\n * which is encrypted using Windows DPAPI (Data Protection API)\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from Local State file\n */\nexport async function getChromePassword(): Promise<string> {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localStateContent = readFileSync(localStatePath, \"utf8\");\n const localState = JSON.parse(localStateContent) as WindowsChromeLocalState;\n\n if (!localState.os_crypt.encrypted_key) {\n throw new Error(\"No encrypted key found in Chrome Local State\");\n }\n\n // Decode the base64 encrypted key\n const encryptedKeyBuffer = Buffer.from(\n localState.os_crypt.encrypted_key,\n \"base64\",\n );\n\n // Decrypt using DPAPI\n const masterKey = await decryptDPAPIKey(encryptedKeyBuffer);\n\n // Return the key as a buffer (not string) for use in AES-GCM decryption\n return masterKey.toString(\"latin1\");\n } catch (error) {\n throw new Error(\n `Failed to retrieve Chrome password on Windows: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { execSimple } from \"../../../../utils/execSimple\";\n\n/**\n * Attempts to retrieve Chrome password from various Linux keyrings\n *\n * Chrome on Linux can store passwords in:\n * 1. GNOME Keyring (via libsecret)\n * 2. KWallet (KDE)\n * 3. Basic password store (plaintext \"peanuts\")\n * @returns The Chrome Safe Storage password\n */\nexport async function getChromePassword(): Promise<string> {\n // Try different methods in order of preference\n\n // Method 1: Try libsecret (GNOME Keyring)\n try {\n const command =\n \"secret-tool lookup application chrome-libsecret-password-v2 || \" +\n \"secret-tool lookup application chrome\";\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password) {\n return password;\n }\n } catch {\n // Continue to next method\n }\n\n // Method 2: Try python keyring module\n try {\n const command =\n \"python3 -c \\\"import keyring; print(keyring.get_password('Chrome Safe Storage', 'Chrome'))\\\"\";\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password && password !== \"None\") {\n return password;\n }\n } catch {\n // Continue to next method\n }\n\n // Method 3: Try KWallet (KDE)\n try {\n const command =\n 'kwallet-query kdewallet -f \"Chrome Safe Storage\" -r Chrome';\n const result = await execSimple(command);\n const password = result.stdout.trim();\n if (password) {\n return password;\n }\n } catch {\n // Continue to fallback\n }\n\n // Method 4: Fallback to default password\n // On some Linux systems, Chrome uses a hardcoded password\n return \"peanuts\";\n}\n","/**\n * Unified SQL query builder for cookie database operations\n * Provides a centralized, type-safe way to build SQL queries for different browsers\n */\n\nimport type { SqlCookieQueryOptions } from \"../../../types/schemas\";\n\n/**\n * Browser types that use SQL databases for cookie storage\n */\nexport type SqlBrowserType =\n | \"chrome\"\n | \"chromium\"\n | \"edge\"\n | \"firefox\"\n | \"opera\"\n | \"brave\"\n | \"arc\";\n\n/**\n * SQL query configuration\n */\nexport interface SqlQueryConfig {\n sql: string;\n params: unknown[];\n description?: string;\n}\n\n/**\n * Cookie query options - re-export from schemas for backward compatibility\n */\nexport type CookieQueryOptions = SqlCookieQueryOptions;\n\n/**\n * Database schema information\n */\ninterface BrowserSchema {\n tableName: string;\n nameColumn: string;\n valueColumn: string;\n domainColumn: string;\n expiryColumn: string;\n encryptedValueColumn?: string;\n pathColumn?: string;\n secureColumn?: string;\n httpOnlyColumn?: string;\n}\n\n/**\n * Browser-specific SQL schemas\n */\nconst BROWSER_SCHEMAS: Record<SqlBrowserType, BrowserSchema> = {\n chrome: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n chromium: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n edge: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n opera: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n brave: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n arc: {\n tableName: \"cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host_key\",\n expiryColumn: \"expires_utc\",\n encryptedValueColumn: \"encrypted_value\",\n pathColumn: \"path\",\n secureColumn: \"is_secure\",\n httpOnlyColumn: \"is_httponly\",\n },\n firefox: {\n tableName: \"moz_cookies\",\n nameColumn: \"name\",\n valueColumn: \"value\",\n domainColumn: \"host\",\n expiryColumn: \"expiry\",\n pathColumn: \"path\",\n secureColumn: \"isSecure\",\n httpOnlyColumn: \"isHttpOnly\",\n },\n};\n\n/**\n * SQL query builder for cookie operations\n */\nexport class CookieQueryBuilder {\n private readonly schema: BrowserSchema;\n private readonly browser: SqlBrowserType;\n\n /**\n *\n * @param browser\n */\n constructor(browser: SqlBrowserType) {\n this.browser = browser;\n this.schema = BROWSER_SCHEMAS[browser];\n if (!this.schema) {\n throw new Error(`Unsupported browser type: ${browser}`);\n }\n }\n\n /**\n * Build a SELECT query for cookies\n * @param options\n */\n buildSelectQuery(options: CookieQueryOptions): SqlQueryConfig {\n const { name, domain, exactDomain, limit, includeExpired } = options;\n const schema = this.schema;\n\n // Build SELECT clause based on browser type\n const selectColumns = this.buildSelectColumns();\n\n // Build WHERE clause\n const { whereClause, params } = this.buildWhereClause(\n name,\n domain,\n exactDomain,\n includeExpired,\n );\n\n // Build complete SQL\n let sql = `SELECT ${selectColumns} FROM ${schema.tableName}`;\n if (whereClause) {\n sql += ` WHERE ${whereClause}`;\n }\n\n // Add ORDER BY for consistent results\n sql += ` ORDER BY ${schema.expiryColumn} DESC`;\n\n // Add LIMIT if specified\n if (limit && limit > 0) {\n sql += ` LIMIT ${limit}`;\n }\n\n return {\n sql,\n params,\n description: `Query ${this.browser} cookies: name=${name}, domain=${domain}`,\n };\n }\n\n /**\n * Build a batch SELECT query for multiple cookie specs\n * Combines multiple cookie specs into a single query with OR conditions\n * @param specs - Array of cookie query options\n */\n buildBatchSelectQuery(specs: CookieQueryOptions[]): SqlQueryConfig {\n if (specs.length === 0) {\n throw new Error(\"At least one spec is required for batch query\");\n }\n\n const schema = this.schema;\n const selectColumns = this.buildSelectColumns();\n\n // Build combined WHERE clause\n const specConditions: string[] = [];\n const allParams: unknown[] = [];\n\n for (const spec of specs) {\n const { whereClause, params } = this.buildWhereClause(\n spec.name,\n spec.domain,\n spec.exactDomain,\n spec.includeExpired,\n );\n\n if (whereClause) {\n // Wrap each spec's conditions in parentheses\n specConditions.push(`(${whereClause})`);\n allParams.push(...params);\n }\n }\n\n // Combine all specs with OR\n const combinedWhere = specConditions.join(\" OR \");\n\n // Build complete SQL\n let sql = `SELECT ${selectColumns} FROM ${schema.tableName}`;\n if (combinedWhere) {\n sql += ` WHERE ${combinedWhere}`;\n }\n\n // Add ORDER BY for consistent results\n sql += ` ORDER BY ${schema.expiryColumn} DESC`;\n\n // Find the minimum limit across all specs (if any have limits)\n const minLimit = specs.reduce(\n (min, spec) => {\n if (spec.limit && spec.limit > 0) {\n return min ? Math.min(min, spec.limit) : spec.limit;\n }\n return min;\n },\n undefined as number | undefined,\n );\n\n if (minLimit && minLimit > 0) {\n sql += ` LIMIT ${minLimit * specs.length}`; // Multiply by specs count to ensure we get enough results\n }\n\n return {\n sql,\n params: allParams,\n description: `Batch query ${this.browser} cookies for ${specs.length} specs`,\n };\n }\n\n /**\n * Build a query to get database metadata\n * @param key\n */\n buildMetaQuery(key: string): SqlQueryConfig {\n // Only Chromium-based browsers have meta table\n if (this.browser === \"firefox\") {\n throw new Error(\"Firefox does not have a meta table\");\n }\n\n return {\n sql: \"SELECT value FROM meta WHERE key = ?\",\n params: [key],\n description: `Get metadata: ${key}`,\n };\n }\n\n /**\n * Build a query to check if table exists\n */\n buildTableExistsQuery(): SqlQueryConfig {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type='table' AND name=?\",\n params: [this.schema.tableName],\n description: `Check if ${this.schema.tableName} table exists`,\n };\n }\n\n /**\n * Build SELECT columns based on browser\n */\n private buildSelectColumns(): string {\n const schema = this.schema;\n const columns = [\n schema.nameColumn,\n schema.domainColumn,\n schema.expiryColumn,\n ];\n\n // Add encrypted_value for Chromium-based browsers\n if (schema.encryptedValueColumn && this.browser !== \"firefox\") {\n columns.push(schema.encryptedValueColumn);\n } else {\n columns.push(schema.valueColumn);\n }\n\n // Add additional columns if available\n if (schema.pathColumn) {\n columns.push(schema.pathColumn);\n }\n if (schema.secureColumn) {\n columns.push(schema.secureColumn);\n }\n if (schema.httpOnlyColumn) {\n columns.push(schema.httpOnlyColumn);\n }\n\n // Use aliases for consistent output\n return columns\n .map((col) => {\n switch (col) {\n case schema.domainColumn:\n return `${col} AS domain`;\n case schema.expiryColumn:\n return `${col} AS expiry`;\n case schema.encryptedValueColumn:\n return `${col} AS encrypted_value`;\n case schema.valueColumn:\n return `${col} AS value`;\n case schema.nameColumn:\n return `${col} AS name`;\n case schema.pathColumn:\n return `${col} AS path`;\n case schema.secureColumn:\n return `${col} AS is_secure`;\n case schema.httpOnlyColumn:\n return `${col} AS is_httponly`;\n default:\n return col;\n }\n })\n .join(\", \");\n }\n\n /**\n * Build WHERE clause with proper parameter binding\n * @param name\n * @param domain\n * @param exactDomain\n * @param includeExpired\n */\n private buildWhereClause(\n name: string,\n domain: string,\n exactDomain?: boolean,\n includeExpired?: boolean,\n ): { whereClause: string; params: unknown[] } {\n const schema = this.schema;\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Handle name condition\n if (name === \"%\") {\n // Wildcard - no name condition needed\n } else if (name.includes(\"%\") || name.includes(\"_\")) {\n // Pattern matching\n conditions.push(`${schema.nameColumn} LIKE ?`);\n params.push(name);\n } else {\n // Exact match\n conditions.push(`${schema.nameColumn} = ?`);\n params.push(name);\n }\n\n // Handle domain condition\n if (domain) {\n if (exactDomain) {\n conditions.push(`${schema.domainColumn} = ?`);\n params.push(domain);\n } else {\n // Optimize domain matching:\n // 1. For domains starting with \".\", use suffix match (more efficient)\n // 2. For regular domains, try to match the domain and subdomains\n if (domain.startsWith(\".\")) {\n // Match exact suffix (e.g., \".github.com\")\n conditions.push(`${schema.domainColumn} LIKE ?`);\n params.push(`%${domain}`);\n } else {\n // Match domain and all subdomains efficiently\n // This matches \"github.com\", \".github.com\", \"api.github.com\", etc.\n conditions.push(\n `(${schema.domainColumn} = ? OR ${schema.domainColumn} = ? OR ${schema.domainColumn} LIKE ?)`,\n );\n params.push(domain, `.${domain}`, `%.${domain}`);\n }\n }\n }\n\n // Handle expiry condition\n if (!includeExpired) {\n // Firefox uses seconds, Chrome uses microseconds since 1601\n if (this.browser === \"firefox\") {\n // Pre-calculate the timestamp to avoid function call per row\n const nowSeconds = Math.floor(Date.now() / 1000);\n conditions.push(`${schema.expiryColumn} > ?`);\n params.push(nowSeconds);\n } else {\n // Chrome timestamp: microseconds since January 1, 1601\n // We'll let the caller handle the conversion\n conditions.push(`${schema.expiryColumn} > 0`);\n }\n }\n\n return {\n whereClause: conditions.join(\" AND \"),\n params,\n };\n }\n\n /**\n * Validate and sanitize query parameters\n * @param options\n */\n static validateQueryParams(options: CookieQueryOptions): void {\n const { name, domain, limit } = options;\n\n // Validate name\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"Cookie name must be a non-empty string\");\n }\n\n // Validate domain\n if (typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"Domain must be a non-empty string\");\n }\n\n // Prevent SQL injection attempts\n const sqlKeywords = [\n \"SELECT\",\n \"INSERT\",\n \"UPDATE\",\n \"DELETE\",\n \"DROP\",\n \"CREATE\",\n \"ALTER\",\n \"--\",\n \";\",\n ];\n const checkString = (str: string, field: string) => {\n const upperStr = str.toUpperCase();\n for (const keyword of sqlKeywords) {\n if (upperStr.includes(keyword)) {\n throw new Error(\n `Invalid ${field}: contains SQL keyword '${keyword}'`,\n );\n }\n }\n };\n\n checkString(name, \"name\");\n checkString(domain, \"domain\");\n\n // Validate limit\n if (limit !== undefined) {\n if (!Number.isInteger(limit) || limit <= 0 || limit > 10000) {\n throw new Error(\"Limit must be a positive integer between 1 and 10000\");\n }\n }\n }\n\n /**\n * Get browser type for a query builder\n */\n getBrowserType(): SqlBrowserType {\n return this.browser;\n }\n\n /**\n * Get schema information\n */\n getSchema(): Readonly<BrowserSchema> {\n return Object.freeze({ ...this.schema });\n }\n}\n\n/**\n * Factory function for creating query builders\n * @param browser\n */\nexport function createQueryBuilder(\n browser: SqlBrowserType,\n): CookieQueryBuilder {\n return new CookieQueryBuilder(browser);\n}\n\n/**\n * Check if a browser uses SQL for cookie storage\n * @param browser\n */\nexport function isSqlBrowser(browser: string): browser is SqlBrowserType {\n return browser in BROWSER_SCHEMAS;\n}\n","// External imports\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport fg from \"fast-glob\";\n\n// Internal imports\nimport { createTaggedLogger } from \"../../utils/logHelpers\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst logger = createTaggedLogger(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * logger.error('Failed to access Chrome profiles', { error });\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = fg.sync(\"./**/Cookies\", {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n logger.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * logger.warn('No Chrome profiles found');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n logger.debug(\"Failed to access Chrome profiles\", { error });\n return [];\n }\n}\n","import type { CookieSpec } from \"../../types/schemas\";\n\n/**\n * Process a domain into cookie specifications, including parent domains\n * @internal\n * @param domain - The domain to process (e.g., 'api.example.com')\n * @returns Array of cookie specifications for the domain and its parents\n */\nfunction processDomainsIntoCookieSpecs(domain: string): CookieSpec[] {\n const parts = domain.split(\".\");\n const cookieSpecs: CookieSpec[] = [];\n\n /**\n * Add the full domain first to ensure exact matches are prioritized\n * The '%' wildcard in the name field matches any cookie name for this domain\n */\n cookieSpecs.push({\n name: \"%\",\n domain: domain,\n });\n\n /**\n * Add parent domains to support domain-level cookie matching\n * For example, for 'sub.example.com', we also want to match 'example.com'\n * This is important because cookies can be set at parent domain levels\n */\n for (let i = 1; i < parts.length - 1; i++) {\n const subDomain = parts.slice(i).join(\".\");\n cookieSpecs.push({\n name: \"%\",\n domain: subDomain,\n });\n }\n\n return cookieSpecs;\n}\n\n/**\n * Generate cookie specifications from a URL by creating specs for both the exact domain\n * and its parent domains. This allows for proper cookie matching across domain levels.\n * @param url - The URL to generate cookie specs from (e.g., 'https://example.com' or just 'example.com')\n * @returns An array of cookie specifications for the URL and its parent domains\n * @remarks\n * - If the URL is provided without a protocol, it will first try to parse with 'https://' prefix\n * - If parsing fails, it will treat the input as a plain domain name\n * - The function handles invalid URLs gracefully by treating them as domain names\n * - The '%' wildcard is used for the name to match all cookies for the domain\n * @example\n * ```typescript\n * // Basic URL with protocol\n * cookieSpecsFromUrl('https://example.com')\n * // Returns: [{ name: '%', domain: 'example.com' }]\n *\n * // URL with subdomain\n * cookieSpecsFromUrl('https://api.example.com')\n * // Returns: [\n * // { name: '%', domain: 'api.example.com' },\n * // { name: '%', domain: 'example.com' }\n * // ]\n *\n * // Domain without protocol (automatically handled)\n * cookieSpecsFromUrl('example.com')\n * // Returns: [{ name: '%', domain: 'example.com' }]\n * ```\n */\nexport function cookieSpecsFromUrl(url: string): CookieSpec[] {\n // For URLs without protocol, try adding https://\n if (!url.includes(\"://\")) {\n try {\n return cookieSpecsFromUrl(`https://${url}`);\n } catch {\n // If adding protocol fails, treat as domain name\n return [\n {\n name: \"%\",\n domain: url,\n },\n ];\n }\n }\n\n try {\n const urlObj = new URL(url);\n return processDomainsIntoCookieSpecs(urlObj.hostname);\n } catch (_error) {\n /**\n * Fallback handling for any parsing errors\n * This ensures the function remains robust even with invalid input\n * Returns a single spec treating the entire input as a domain name\n */\n return [\n {\n name: \"%\",\n domain: url,\n },\n ];\n }\n}\n","import minimist from \"minimist\";\n\n/**\n * Interface representing parsed command line arguments.\n * @property values - Record of option values parsed from command line\n * @property positionals - Array of positional arguments\n * @example\n * ```typescript\n * const args: ParsedArgs = {\n * values: {\n * browser: 'chrome',\n * profile: 'default',\n * verbose: true\n * },\n * positionals: ['script.js', 'input.txt']\n * }\n * ```\n */\ninterface ParsedArgs {\n /** Record of option values parsed from command line */\n values: Record<string, string | boolean | string[]>;\n /** Array of positional arguments */\n positionals: string[];\n}\n\n/**\n * Configuration for command line options\n */\nconst CLI_OPTIONS = {\n string: [\n \"browser\",\n \"profile\",\n \"url\",\n \"domain\",\n \"name\",\n \"output\",\n \"store\",\n \"jwt-secret\",\n ] as string[],\n boolean: [\n \"help\",\n \"version\",\n \"verbose\",\n \"dump\",\n \"dump-grouped\",\n \"render\",\n \"render-grouped\",\n \"force\",\n \"include-expired\",\n \"include-all\",\n \"list-profiles\",\n \"detect-jwt\",\n \"jwt-only\",\n ] as string[],\n alias: {\n b: \"browser\",\n p: \"profile\",\n u: \"url\",\n d: \"dump\",\n D: \"domain\",\n n: \"name\",\n h: \"help\",\n v: \"verbose\",\n f: \"force\",\n G: \"dump-grouped\",\n r: \"render\",\n R: \"render-grouped\",\n j: \"detect-jwt\",\n },\n};\n\n/**\n * Generate all known flags from the CLI_OPTIONS configuration\n * @returns Array of all valid CLI flags (both long and short forms)\n */\nfunction generateKnownFlags(): string[] {\n const flags: string[] = [];\n\n // Add string options\n for (const opt of CLI_OPTIONS.string) {\n flags.push(`--${opt}`);\n }\n\n // Add boolean options\n for (const opt of CLI_OPTIONS.boolean) {\n flags.push(`--${opt}`);\n }\n\n // Add aliases\n for (const [short, long] of Object.entries(CLI_OPTIONS.alias)) {\n flags.push(`-${short}`);\n // Also ensure the long form is included (in case not in string/boolean arrays)\n if (!flags.includes(`--${long}`)) {\n flags.push(`--${long}`);\n }\n }\n\n return flags;\n}\n\n/**\n * Cached known flags array\n */\nconst KNOWN_FLAGS = generateKnownFlags();\n\n/**\n * Parses command line arguments into a structured format.\n * @internal\n * @param argv - Array of command line arguments to parse\n * @returns Parsed command line arguments object\n * @example\n * ```typescript\n * // Basic usage\n * const args = parseArgv(['--browser', 'chrome', '--verbose', 'script.js']);\n * // Returns: { values: { browser: 'chrome', verbose: true }, positionals: ['script.js'] }\n *\n * // Using short options\n * const args = parseArgv(['-b', 'firefox', '-v', 'script.js']);\n * // Returns: { values: { browser: 'firefox', verbose: true }, positionals: ['script.js'] }\n *\n * // Error handling\n * const args = parseArgv(['--invalid']); // Will throw error for unknown option\n * ```\n */\nexport function parseArgv(argv: string[]): ParsedArgs {\n const parsed = minimist(argv, {\n ...CLI_OPTIONS,\n unknown: (arg: string) => {\n // Allow positional arguments (don't start with -)\n if (!arg.startsWith(\"-\")) {\n return true;\n }\n // Check if it's a known flag or alias\n const isKnown = KNOWN_FLAGS.some((flag) => arg.startsWith(flag));\n if (!isKnown) {\n throw new Error(`Unknown option: ${arg}`);\n }\n return true;\n },\n });\n\n const { _, ...values } = parsed;\n return { values, positionals: _ };\n}\n","#!/usr/bin/env node\n\n// Local imports - core\nimport { listChromeProfiles } from \"@core/browsers/listChromeProfiles\";\nimport { cookieSpecsFromUrl } from \"@core/cookies/cookieSpecsFromUrl\";\nimport { parseArgv } from \"@utils/argv\";\nimport logger from \"@utils/logger\";\n\nimport type { CookieSpec } from \"../types/schemas\";\n\nimport { cliQueryCookies } from \"./cliQueryCookies\";\n\n// This will be replaced at build time by esbuild\ndeclare const BUILD_TIMESTAMP: string;\n\nfunction showHelp(): void {\n logger.log(\"Usage: get-cookie [name] [domain] [options]\");\n\n // Show build info if available\n if (typeof BUILD_TIMESTAMP !== \"undefined\") {\n logger.log(`Build: ${BUILD_TIMESTAMP}`);\n }\n\n logger.log(\"\");\n logger.log(\"Examples:\");\n logger.log(\" get-cookie auth example.com # Get specific cookie\");\n logger.log(\n \" get-cookie % github.com --output json # Get all cookies as JSON\",\n );\n logger.log(\" get-cookie --url https://example.com # Extract from URL\");\n logger.log(\"\");\n logger.log(\"Options:\");\n logger.log(\" -h, --help Show this help message\");\n logger.log(\" -v, --verbose Enable verbose output\");\n logger.log(\n \" -f, --force Force operation despite warnings (e.g., locked databases)\",\n );\n logger.log(\n \" --list-profiles List available browser profiles (use with --browser)\",\n );\n logger.log(\"\");\n logger.log(\"Query options:\");\n logger.log(\n \" -n, --name PATTERN Cookie name pattern (% for wildcard)\",\n );\n logger.log(\" -D, --domain PATTERN Cookie domain pattern\");\n logger.log(\" -u, --url URL URL to extract cookie specs from\");\n logger.log(\n \" --browser BROWSER Target specific browser (chrome|edge|arc|opera|opera-gx|firefox|safari)\",\n );\n logger.log(\n \" --profile NAME Target specific Chrome profile by name (e.g., 'Default', 'Profile 1')\",\n );\n logger.log(\n \" --store PATH Path to a specific cookie store file\",\n );\n logger.log(\n \" --include-expired Include expired cookies (filtered by default)\",\n );\n logger.log(\n \" --include-all Include all duplicate cookies (newest only by default)\",\n );\n logger.log(\"\");\n logger.log(\"JWT detection options:\");\n logger.log(\n \" -j, --detect-jwt Detect and decode JWT tokens in cookies\",\n );\n logger.log(\n \" --jwt-only Only show cookies containing valid JWTs\",\n );\n logger.log(\n \" --jwt-secret KEY Validate JWT signatures with provided secret\",\n );\n logger.log(\"\");\n logger.log(\"Output options:\");\n logger.log(\" --output FORMAT Output format (json)\");\n logger.log(\" -d, --dump Dump all cookie details\");\n logger.log(\n \" -G, --dump-grouped Dump all results, grouped by profile\",\n );\n logger.log(\n \" -r, --render Render all results in formatted output\",\n );\n}\n\nfunction createCookieSpec(name: string, domain: string): CookieSpec {\n return {\n name: name || \"%\",\n domain: domain || \"%\",\n };\n}\n\nfunction normalizeWildcard(pattern: string): string {\n // Convert * to % for consistent wildcard handling\n return pattern === \"*\" ? \"%\" : pattern;\n}\n\ninterface ChromeProfileInfo {\n name: string;\n user_name?: string;\n [key: string]: unknown;\n}\n\nfunction listProfiles(browser?: string): void {\n if (!browser) {\n logger.error(\"Please specify a browser with --browser\");\n logger.log(\"Example: get-cookie --browser chrome --list-profiles\");\n return;\n }\n\n const browserLower = browser.toLowerCase();\n\n if (\n browserLower === \"chrome\" ||\n browserLower === \"edge\" ||\n browserLower === \"arc\" ||\n browserLower === \"opera\" ||\n browserLower === \"opera-gx\"\n ) {\n try {\n const profiles = listChromeProfiles();\n\n if (profiles.length === 0) {\n logger.log(`No ${browser} profiles found`);\n return;\n }\n\n logger.log(`${browser} profiles:`);\n logger.log(\"\");\n\n // Get the profile directory mapping from Chrome's Local State\n const fs = require(\"node:fs\");\n const path = require(\"node:path\");\n const os = require(\"node:os\");\n\n // Determine the browser data directory based on browser type and platform\n let dataDir: string;\n const platform = process.platform;\n\n if (platform === \"darwin\") {\n const homeDir = os.homedir();\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Google\",\n \"Chrome\",\n );\n break;\n case \"edge\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Microsoft Edge\",\n );\n break;\n case \"arc\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Arc\",\n );\n break;\n case \"opera\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.Opera\",\n );\n break;\n case \"opera-gx\":\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.OperaGX\",\n );\n break;\n default:\n dataDir = path.join(\n homeDir,\n \"Library\",\n \"Application Support\",\n \"Google\",\n \"Chrome\",\n );\n }\n } else if (platform === \"win32\") {\n const appData =\n process.env.LOCALAPPDATA ||\n path.join(os.homedir(), \"AppData\", \"Local\");\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(appData, \"Google\", \"Chrome\", \"User Data\");\n break;\n case \"edge\":\n dataDir = path.join(appData, \"Microsoft\", \"Edge\", \"User Data\");\n break;\n default:\n dataDir = path.join(appData, \"Google\", \"Chrome\", \"User Data\");\n }\n } else {\n // Linux\n const homeDir = os.homedir();\n switch (browserLower) {\n case \"chrome\":\n dataDir = path.join(homeDir, \".config\", \"google-chrome\");\n break;\n default:\n dataDir = path.join(homeDir, \".config\", \"google-chrome\");\n }\n }\n\n const localStatePath = path.join(dataDir, \"Local State\");\n\n if (fs.existsSync(localStatePath)) {\n const localState = JSON.parse(fs.readFileSync(localStatePath, \"utf8\"));\n const profileCache = localState.profile?.info_cache || {};\n\n for (const [dir, info] of Object.entries(profileCache)) {\n const profile = info as ChromeProfileInfo;\n logger.log(` • ${profile.name}`);\n logger.log(` Directory: ${dir}`);\n if (profile.user_name) {\n logger.log(` User: ${profile.user_name}`);\n }\n logger.log(\"\");\n }\n } else {\n // Fallback to just listing profile objects\n profiles.forEach((profile) => {\n logger.log(` • ${profile.name}`);\n if (profile.user_name) {\n logger.log(` User: ${profile.user_name}`);\n }\n logger.log(\"\");\n });\n }\n } catch (error) {\n logger.error(\n `Failed to list ${browser} profiles:`,\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n } else if (browserLower === \"firefox\") {\n logger.log(\"Firefox profile listing is not yet implemented\");\n logger.log(\n \"Firefox stores profiles in different locations based on the platform\",\n );\n } else if (browserLower === \"safari\") {\n logger.log(\"Safari does not use named profiles\");\n logger.log(\"Safari uses the system keychain for the current user\");\n } else {\n logger.error(`Unknown browser: ${browser}`);\n }\n}\n\nfunction getCookieSpecs(\n values: Record<string, string | boolean | string[]>,\n positionals: string[],\n): CookieSpec[] {\n const url = values.url as string | undefined;\n\n if (typeof url === \"string\") {\n const specs = cookieSpecsFromUrl(url);\n if (!Array.isArray(specs)) {\n logger.error(\"Invalid cookie specs from URL\");\n return [];\n }\n return specs;\n }\n\n const name = normalizeWildcard(\n (values.name as string) ?? positionals[0] ?? \"%\",\n );\n const domain = normalizeWildcard(\n (values.domain as string) ?? positionals[1] ?? \"%\",\n );\n return [createCookieSpec(name, domain)];\n}\n\nasync function handleCookieQuery(\n values: Record<string, string | boolean | string[]>,\n positionals: string[],\n): Promise<void> {\n const cookieSpecs = getCookieSpecs(values, positionals);\n\n if (values.verbose === true) {\n logger.log(\"cookieSpecs\", cookieSpecs);\n }\n\n try {\n // Default to removing expired cookies unless --include-expired is set\n const removeExpired = values[\"include-expired\"] !== true;\n // Default to deduplicating cookies unless --include-all is set\n const deduplicateCookies = values[\"include-all\"] !== true;\n\n await cliQueryCookies(\n values,\n cookieSpecs,\n undefined,\n removeExpired,\n values.store as string | undefined,\n deduplicateCookies,\n );\n } catch (error) {\n if (error instanceof Error) {\n logger.error(\"Error querying cookies:\", error.message);\n } else {\n logger.error(\"An unknown error occurred while querying cookies\");\n }\n }\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n\n // Show help if no arguments provided\n if (args.length === 0) {\n showHelp();\n return;\n }\n\n const { values, positionals } = parseArgv(args);\n\n if (values.help === true) {\n showHelp();\n return;\n }\n\n if (values[\"list-profiles\"] === true) {\n const browser =\n typeof values.browser === \"string\" ? values.browser : undefined;\n listProfiles(browser);\n return;\n }\n\n await handleCookieQuery(values, positionals);\n}\n\nmain().catch((error) => {\n if (error instanceof Error) {\n logger.error(\"Fatal error:\", error.message);\n } else {\n logger.error(\"An unknown fatal error occurred\");\n }\n process.exit(1);\n});\n","/**\n * Utility functions for consistent error handling across the codebase\n * Following DRY principle to eliminate repetitive error handling patterns\n */\n\n/**\n * Safely extract error message from unknown error types\n * @param error - Any thrown value (Error, string, unknown)\n * @returns A string representation of the error\n * @example\n * try {\n * // some operation\n * } catch (error) {\n * const message = getErrorMessage(error);\n * logger.error('Operation failed', { error: message });\n * }\n */\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (\n error !== null &&\n error !== undefined &&\n typeof error === \"object\" &&\n \"message\" in error\n ) {\n return String(error.message);\n }\n return String(error);\n}\n\n/**\n * Get detailed error information including stack trace\n * @param error - Any thrown value\n * @returns Object with error details\n */\nexport function getErrorDetails(error: unknown): {\n message: string;\n stack?: string;\n name?: string;\n code?: string;\n} {\n const message = getErrorMessage(error);\n\n if (error instanceof Error) {\n const result: ReturnType<typeof getErrorDetails> = { message };\n if (error.stack !== undefined) {\n result.stack = error.stack;\n }\n if (error.name !== undefined) {\n result.name = error.name;\n }\n if (\"code\" in error && error.code !== undefined) {\n result.code = String(error.code);\n }\n return result;\n }\n\n return { message };\n}\n\n/**\n * Check if error message contains specific text (case-insensitive)\n * @param error - Any thrown value\n * @param searchText - Text to search for\n * @returns True if error message contains the text\n */\nexport function errorMessageContains(\n error: unknown,\n searchText: string,\n): boolean {\n const message = getErrorMessage(error).toLowerCase();\n return message.includes(searchText.toLowerCase());\n}\n\n/**\n * Error pattern constants for database error classification\n */\nconst DATABASE_ERROR_PATTERNS = {\n locked: [\"database is locked\", \"database locked\", \"sqlite_busy\"],\n busy: [\"busy\"],\n permission: [\n \"eperm\",\n \"permission denied\",\n \"operation not permitted\",\n \"eacces\",\n ],\n not_found: [\"enoent\", \"no such file\", \"not found\"],\n} as const;\n\n/**\n * Checks if a message contains any of the given patterns\n * @param message - The error message to check\n * @param patterns - Array of patterns to match against\n * @returns True if any pattern is found\n */\nfunction containsAnyPattern(\n message: string,\n patterns: readonly string[],\n): boolean {\n return patterns.some((pattern) => message.includes(pattern));\n}\n\n/**\n * Check if error is a specific type of database error\n * @param error - Any thrown value\n * @returns Type of database error or null\n */\nexport function getDatabaseErrorType(\n error: unknown,\n): \"locked\" | \"busy\" | \"permission\" | \"not_found\" | null {\n const message = getErrorMessage(error).toLowerCase();\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.locked)) {\n return \"locked\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.busy)) {\n return \"busy\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.permission)) {\n return \"permission\";\n }\n\n if (containsAnyPattern(message, DATABASE_ERROR_PATTERNS.not_found)) {\n return \"not_found\";\n }\n\n return null;\n}\n\n/**\n * Format error for logging with consistent structure\n * @param error - Any thrown value\n * @param context - Additional context for the error\n * @returns Formatted error object for logging\n */\nexport function formatErrorForLogging(\n error: unknown,\n context?: Record<string, unknown>,\n): Record<string, unknown> {\n const details = getErrorDetails(error);\n\n return {\n ...context,\n error: details.message,\n errorName: details.name,\n errorCode: details.code,\n // Only include stack in development/debug mode\n ...(process.env.NODE_ENV !== \"production\" &&\n details.stack !== undefined &&\n details.stack !== \"\"\n ? { errorStack: details.stack }\n : {}),\n };\n}\n\n/**\n * Type guard to check if value is an Error instance\n * @param error - Any value to check\n * @returns True if error is an Error instance\n */\nexport function isError(error: unknown): error is Error {\n return error instanceof Error;\n}\n\n/**\n * Type guard to check if error has a message property\n * @param error - Any value to check\n * @returns True if error has a message property\n */\nexport function hasErrorMessage(error: unknown): error is { message: unknown } {\n return (\n error !== null &&\n error !== undefined &&\n typeof error === \"object\" &&\n \"message\" in error\n );\n}\n\n/**\n * Create a standardized error from unknown input\n * @param error - Any thrown value\n * @param fallbackMessage - Message to use if error can't be converted\n * @returns Error instance\n */\nexport function ensureError(\n error: unknown,\n fallbackMessage = \"An unknown error occurred\",\n): Error {\n if (error instanceof Error) {\n return error;\n }\n\n const message = getErrorMessage(error) || fallbackMessage;\n const standardError = new Error(message);\n\n // Preserve original error as cause if supported\n if (\"cause\" in standardError) {\n standardError.cause = error;\n }\n\n return standardError;\n}\n\n/**\n * Wrap an async operation with consistent error handling\n * @param operation - Async function to execute\n * @param errorHandler - Function to handle errors\n * @returns Result of operation or undefined if error\n */\nexport async function withErrorHandling<T>(\n operation: () => Promise<T>,\n errorHandler: (error: unknown) => void,\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n errorHandler(error);\n return undefined;\n }\n}\n\n/**\n * Retry an operation with exponential backoff\n * @param operation - Async function to execute\n * @param options - Retry options\n * @param options.maxAttempts - Maximum number of retry attempts\n * @param options.initialDelay - Initial delay in milliseconds\n * @param options.maxDelay - Maximum delay in milliseconds\n * @param options.shouldRetry - Function to determine if retry should be attempted\n * @returns Result of successful operation\n */\nexport async function retryWithBackoff<T>(\n operation: () => Promise<T>,\n options: {\n maxAttempts?: number;\n initialDelay?: number;\n maxDelay?: number;\n shouldRetry?: (error: unknown) => boolean;\n } = {},\n): Promise<T> {\n const {\n maxAttempts = 3,\n initialDelay = 100,\n maxDelay = 5000,\n shouldRetry = () => true,\n } = options;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error;\n\n if (attempt === maxAttempts || !shouldRetry(error)) {\n throw error;\n }\n\n const delay = Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type { CookieSpec, ExportedCookie } from \"../types/schemas\";\nimport { getErrorMessage } from \"../utils/errorUtils\";\nimport { logger } from \"../utils/logHelpers\";\nimport {\n detectJwtCookies,\n filterJwtCookies,\n type JwtDetectionOptions,\n} from \"../core/cookies/JwtCookieDetector\";\n\nimport { OutputHandlerFactory } from \"./handlers/OutputHandlerFactory\";\nimport { CookieQueryService } from \"./services/CookieQueryService\";\nimport {\n type CookieQueryStrategy,\n CookieStrategyFactory,\n} from \"./services/CookieStrategyFactory\";\n\ninterface QueryOptions {\n /** Maximum number of cookies to return */\n limit?: number;\n /** Whether to remove expired cookies */\n removeExpired: boolean;\n /** Whether to deduplicate cookies (keep newest) */\n deduplicateCookies: boolean;\n /** Optional path to a specific binarycookies store file */\n store?: string;\n /** Strategy for querying cookies */\n strategy: CookieQueryStrategy;\n /** Whether to force operations despite warnings */\n force?: boolean;\n}\n\n/**\n * Internal function to query cookies and apply limit\n * @param queryService - The query service to use\n * @param specs - Cookie specifications to query\n * @param options - Query options including limit, expiry handling, store path, and strategy\n * @returns Array of cookies\n */\nasync function queryAndLimitCookies(\n queryService: CookieQueryService,\n specs: CookieSpec[],\n options: QueryOptions,\n): Promise<ExportedCookie[]> {\n let results: ExportedCookie[] = [];\n\n for (const spec of specs) {\n const cookies = await queryService.queryCookies(spec, options);\n results = [...results, ...cookies];\n\n if (\n typeof options.limit === \"number\" &&\n options.limit > 0 &&\n results.length >= options.limit\n ) {\n results = results.slice(0, options.limit);\n break;\n }\n }\n\n // Deduplicate cookies if requested (keep newest based on creation time or longest value)\n if (options.deduplicateCookies && results.length > 0) {\n const cookieMap = new Map<string, ExportedCookie>();\n\n for (const cookie of results) {\n const key = `${cookie.name}:${cookie.domain}`;\n const existing = cookieMap.get(key);\n\n if (!existing) {\n cookieMap.set(key, cookie);\n } else {\n // Keep the cookie with the longest value (most likely to be valid)\n // or if same length, keep the one with latest creation time\n // Replace with longer value, or if same length, keep the newer one\n // Since we don't have creation time, we'll just prefer longer values\n const shouldReplace = cookie.value.length > existing.value.length;\n\n if (shouldReplace) {\n cookieMap.set(key, cookie);\n }\n }\n }\n\n results = Array.from(cookieMap.values());\n }\n\n return results;\n}\n\n/**\n * Query cookies from the browser using the specified strategy\n * @param args - Command line arguments including browser and output format options\n * @param cookieSpec - Cookie specification(s) to query for\n * @param limit - Maximum number of cookies to return\n * @param removeExpired - Whether to remove expired cookies\n * @param store - Optional path to a specific binarycookies store file\n */\n/**\n * Builds query options from command line arguments and parameters.\n * Consolidates various options into a single QueryOptions object for cookie querying.\n * @param args - Command line arguments containing optional force flag\n * @param strategy - The browser-specific cookie query strategy to use\n * @param removeExpired - Whether to filter out expired cookies from results\n * @param deduplicateCookies\n * @param limit - Optional maximum number of cookies to return\n * @param store - Optional path to a specific cookie store file (e.g., Safari binarycookies)\n * @returns Configured QueryOptions object for cookie querying\n */\nfunction buildQueryOptions(\n args: Record<string, unknown>,\n strategy: CookieQueryStrategy,\n removeExpired: boolean,\n deduplicateCookies: boolean,\n limit?: number,\n store?: string,\n): QueryOptions {\n const queryOptions: QueryOptions = {\n removeExpired,\n deduplicateCookies,\n strategy,\n };\n const force = typeof args.force === \"boolean\" ? args.force : false;\n\n if (limit !== undefined) {\n queryOptions.limit = limit;\n }\n if (store !== undefined) {\n queryOptions.store = store;\n }\n if (force) {\n queryOptions.force = force;\n }\n\n return queryOptions;\n}\n\n/**\n * Queries browser cookies from the command line interface and outputs results.\n * This is the main entry point for CLI cookie queries, handling browser detection,\n * strategy selection, and output formatting.\n * @param args - Command line arguments including browser selection and output format\n * @param cookieSpec - Cookie specification(s) defining which cookies to retrieve\n * @param limit - Optional maximum number of cookies to return\n * @param removeExpired - Whether to exclude expired cookies from results (default: false)\n * @param store - Optional path to a specific cookie store file for direct access\n * @param deduplicateCookies\n * @returns Promise that resolves when query and output are complete\n * @example\n * ```typescript\n * // Query all cookies named \"session\" from Chrome\n * await cliQueryCookies(\n * { browser: \"chrome\", output: \"json\" },\n * { name: \"session\", domain: \"example.com\" }\n * );\n * ```\n */\nexport async function cliQueryCookies(\n args: Record<string, unknown>,\n cookieSpec: CookieSpec | CookieSpec[],\n limit?: number,\n removeExpired = false,\n store?: string,\n deduplicateCookies = true,\n): Promise<void> {\n try {\n const browser = typeof args.browser === \"string\" ? args.browser : undefined;\n const profile = typeof args.profile === \"string\" ? args.profile : undefined;\n const strategy = CookieStrategyFactory.createStrategy(\n browser,\n store,\n profile,\n );\n const queryService = new CookieQueryService(strategy);\n const specs = Array.isArray(cookieSpec) ? cookieSpec : [cookieSpec];\n\n const queryOptions = buildQueryOptions(\n args,\n strategy,\n removeExpired,\n deduplicateCookies,\n limit,\n store,\n );\n let results = await queryAndLimitCookies(queryService, specs, queryOptions);\n\n // Handle JWT detection if requested\n if (args[\"detect-jwt\"] === true || args[\"jwt-only\"] === true) {\n const jwtOptions: JwtDetectionOptions = {\n decodeClaims: true,\n checkExpiration: true,\n verbose: args.verbose === true,\n };\n\n // Add JWT secret validation if provided\n if (typeof args[\"jwt-secret\"] === \"string\") {\n jwtOptions.validateSignature = true;\n jwtOptions.secretKey = args[\"jwt-secret\"];\n }\n\n if (args[\"jwt-only\"] === true) {\n // Filter to only show JWT cookies\n results = filterJwtCookies(results, jwtOptions);\n } else {\n // Enhance cookies with JWT metadata\n results = detectJwtCookies(results, jwtOptions);\n }\n }\n\n if (results.length === 0) {\n logger.error(\"No results\");\n\n // Provide helpful feedback for profile-related issues\n const profile =\n typeof args.profile === \"string\" ? args.profile : undefined;\n const browser =\n typeof args.browser === \"string\" ? args.browser : undefined;\n\n if (profile && browser) {\n logger.error(`Could not find cookies for profile: ${profile}`);\n logger.error(\n `Try 'get-cookie --browser ${browser} --list-profiles' to see available profiles`,\n );\n }\n\n // Add feedback for JWT-only mode\n if (args[\"jwt-only\"] === true) {\n logger.error(\"No cookies containing valid JWT tokens were found\");\n }\n\n return;\n }\n\n const outputFactory = new OutputHandlerFactory();\n const outputHandler = outputFactory.getHandler(args);\n outputHandler.handle(results);\n } catch (error) {\n logger.error(getErrorMessage(error));\n }\n}\n","import jsonwebtoken from \"jsonwebtoken\";\n\nimport { parseArgv } from \"./argv\";\nimport logger from \"./logger\";\n\n/**\n * Represents a JWT payload with optional standard claims\n */\nexport interface JwtPayload {\n exp?: number;\n iat?: number;\n sub?: string;\n [key: string]: unknown;\n}\n\n/**\n * Represents a JWT header\n */\nexport interface JwtHeader {\n alg: string;\n typ?: string;\n [key: string]: unknown;\n}\n\n/**\n * Result of JWT validation operations\n */\nexport interface ValidationResult {\n isValid: boolean;\n error?: string;\n decodedPayload?: JwtPayload;\n header?: JwtHeader;\n}\n\n/** @internal */\nconst JWT_FORMAT_REGEX = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\n\n/**\n * Validates if a string matches the basic JWT format\n * @param value - The value to check for JWT format\n * @returns True if the value is a valid JWT format string, false otherwise\n */\nexport function isJWT(value: unknown): boolean {\n if (value === null || value === undefined || typeof value !== \"string\") {\n return false;\n }\n return JWT_FORMAT_REGEX.test(value);\n}\n\n/**\n * Validates the basic format of a JWT token using regex pattern matching.\n * @param token - The JWT token string to validate\n * @returns The validation result indicating if the token format is valid\n */\nfunction validateTokenFormat(token: string): ValidationResult {\n if (!JWT_FORMAT_REGEX.test(token)) {\n return {\n isValid: false,\n error:\n \"Invalid JWT format - must be three dot-separated base64url-encoded strings\",\n };\n }\n return { isValid: true };\n}\n\n/**\n * Verifies JWT signature using the provided secret or public key.\n * @param token - The JWT token to verify\n * @param secretOrPublicKey - The secret or public key to use for verification\n * @returns The validation result if verification fails, null if successful\n */\nfunction verifySignature(\n token: string,\n secretOrPublicKey: string | Buffer,\n): ValidationResult | null {\n try {\n jsonwebtoken.verify(token, secretOrPublicKey);\n return null;\n } catch (verifyError) {\n const error =\n verifyError instanceof Error\n ? verifyError.message\n : \"Unknown verification error\";\n const args = parseArgv(process.argv);\n if (args.values.verbose === true) {\n logger.debug(`JWT verification failed: ${error}`);\n }\n return { isValid: false, error };\n }\n}\n\n/**\n * Checks if a JWT token has expired based on its exp claim.\n * @param payload - The decoded JWT payload to check for expiration\n * @returns The validation result indicating if the token is expired\n */\nfunction checkExpiration(payload: JwtPayload): ValidationResult {\n const exp = payload.exp;\n if (exp === undefined) {\n return {\n isValid: true,\n decodedPayload: payload,\n };\n }\n\n const now = Math.floor(Date.now() / 1000);\n const result: ValidationResult = {\n isValid: now <= exp,\n decodedPayload: payload,\n };\n if (now > exp) {\n result.error = \"Token has expired\";\n }\n return result;\n}\n\n/**\n * Internal utility for debug logging.\n * @internal\n * @param message - The debug message to log\n * @param data - Optional data to log with the message\n */\nfunction debugLog(message: string, data?: unknown): void {\n try {\n const args = parseArgv(process.argv);\n if (args.values.verbose === true) {\n logger.debug(message, data);\n }\n } catch (_error) {\n // Ignore parsing errors in debug logging\n }\n}\n\n/**\n * Validates input token string format.\n * @internal\n * @param token - The token string to validate\n * @returns ValidationResult for invalid tokens, null for valid ones\n */\nfunction validateTokenInput(\n token: string | null | undefined,\n): ValidationResult | null {\n if (token === null || token === undefined) {\n return { isValid: false, error: \"Token is null or undefined\" };\n }\n if (typeof token !== \"string\") {\n return { isValid: false, error: \"Token is not a string\" };\n }\n if (token.trim().length === 0) {\n return { isValid: false, error: \"Token is empty or whitespace\" };\n }\n return null;\n}\n\n/**\n * Decodes and validates JWT payload.\n * @internal\n * @param token - The token to decode and validate\n * @returns ValidationResult containing decoded information or error\n */\nfunction decodeAndValidatePayload(token: string): ValidationResult {\n const result = jsonwebtoken.decode(token, { complete: true });\n debugLog(\"Decoded JWT token:\", result ?? \"Failed to decode\");\n\n if (!result) {\n return { isValid: false, error: \"Failed to decode token\" };\n }\n\n const validationResult = checkExpiration(result.payload as JwtPayload);\n return {\n ...validationResult,\n header: result.header as JwtHeader,\n };\n}\n\n/**\n * Validates a JWT token by checking its format, signature (if key provided), and expiration.\n * This is the main function that should be used for JWT validation.\n * @param token - The JWT token to validate\n * @param secretOrPublicKey - Optional secret or public key for signature verification\n * @returns Validation result containing success status, error message, and decoded information\n * @example\n * ```typescript\n * // Basic validation without signature verification\n * const result = validateToken('your.jwt.token');\n *\n * // Validation with signature verification\n * const result = validateToken('your.jwt.token', 'your-secret-key');\n * ```\n */\nexport function validateToken(\n token: string | undefined,\n secretOrPublicKey?: string | Buffer,\n): ValidationResult {\n try {\n if (token === undefined) {\n const errorMessage = \"Token is undefined\";\n logger.debug(`JWT validation error: ${errorMessage}`);\n return {\n isValid: false,\n error: errorMessage,\n };\n }\n\n const inputError = validateTokenInput(token);\n if (inputError !== null) {\n return inputError;\n }\n\n const formatResult = validateTokenFormat(token);\n if (!formatResult.isValid) {\n return formatResult;\n }\n\n if (secretOrPublicKey !== undefined) {\n const signatureResult = verifySignature(token, secretOrPublicKey);\n if (signatureResult !== null) {\n return signatureResult;\n }\n }\n\n return decodeAndValidatePayload(token);\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Unknown error during JWT validation\";\n logger.debug(`JWT validation error: ${errorMessage}`);\n return {\n isValid: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Decodes a JWT token without verifying its signature.\n * Use this only when you don't need to verify the token's authenticity.\n * @param token - The JWT token to decode\n * @returns The decoded payload and header, or null if decoding fails\n * @example\n * ```typescript\n * const decoded = decodeToken('your.jwt.token');\n * if (decoded) {\n * console.log(decoded.payload.sub); // Access payload claims\n * }\n * ```\n */\nexport function decodeToken(\n token: string,\n): { payload: JwtPayload; header: JwtHeader } | null {\n try {\n const result = jsonwebtoken.decode(token, { complete: true });\n if (!result) {\n return null;\n }\n return {\n payload: result.payload as JwtPayload,\n header: result.header as JwtHeader,\n };\n } catch {\n return null;\n }\n}\n","import type { ExportedCookie, CookieMeta } from \"../../types/schemas\";\nimport {\n isJWT,\n decodeToken,\n validateToken,\n type JwtPayload,\n type ValidationResult,\n} from \"../../utils/jwt\";\nimport { createTaggedLogger } from \"../../utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"JwtCookieDetector\");\n\n/**\n * Extended metadata for cookies that contain JWT tokens\n */\nexport interface JwtCookieMeta extends CookieMeta {\n /** Indicates if the cookie value is a JWT */\n isJwt?: boolean;\n /** JWT validation result if the cookie contains a JWT */\n jwtValidation?: ValidationResult;\n /** Decoded JWT payload if valid */\n jwtPayload?: JwtPayload;\n /** JWT expiration date if present */\n jwtExpiry?: Date;\n /** JWT subject (sub claim) if present */\n jwtSubject?: string;\n /** JWT issuer (iss claim) if present */\n jwtIssuer?: string;\n}\n\n/**\n * Cookie with enhanced JWT metadata\n */\nexport interface JwtEnhancedCookie extends Omit<ExportedCookie, \"meta\"> {\n meta?: JwtCookieMeta;\n}\n\n/**\n * Options for JWT detection in cookies\n */\nexport interface JwtDetectionOptions {\n /** Whether to validate JWT signatures (requires secret key) */\n validateSignature?: boolean;\n /** Secret key for JWT signature validation */\n secretKey?: string | Buffer;\n /** Whether to check JWT expiration */\n checkExpiration?: boolean;\n /** Whether to decode JWT claims */\n decodeClaims?: boolean;\n /** Whether to log JWT detection details */\n verbose?: boolean;\n}\n\n/**\n * Detects and enhances cookies that contain JWT tokens\n * @param cookies - Array of cookies to check for JWTs\n * @param options - JWT detection options\n * @returns Array of cookies with enhanced JWT metadata\n * @example\n * ```typescript\n * const cookies = await getCookie({ name: 'auth', domain: 'example.com' });\n * const enhancedCookies = detectJwtCookies(cookies, {\n * decodeClaims: true,\n * checkExpiration: true\n * });\n *\n * for (const cookie of enhancedCookies) {\n * if (cookie.meta?.isJwt) {\n * console.log(`JWT Cookie: ${cookie.name}`);\n * console.log(` Subject: ${cookie.meta.jwtSubject}`);\n * console.log(` Expires: ${cookie.meta.jwtExpiry}`);\n * }\n * }\n * ```\n */\nexport function detectJwtCookies(\n cookies: ExportedCookie[],\n options: JwtDetectionOptions = {},\n): JwtEnhancedCookie[] {\n const {\n validateSignature = false,\n secretKey,\n checkExpiration = true,\n decodeClaims = true,\n verbose = false,\n } = options;\n\n return cookies.map((cookie) => {\n // Skip if value is not a string or doesn't look like a JWT\n if (typeof cookie.value !== \"string\" || !isJWT(cookie.value)) {\n return cookie as JwtEnhancedCookie;\n }\n\n if (verbose) {\n logger.info(`Detected JWT in cookie: ${cookie.name}`);\n }\n\n // Create enhanced metadata\n const jwtMeta: JwtCookieMeta = {\n ...cookie.meta,\n isJwt: true,\n };\n\n // Validate or decode the JWT\n if (validateSignature && secretKey) {\n const validation = validateToken(cookie.value, secretKey);\n jwtMeta.jwtValidation = validation;\n\n if (validation.isValid && validation.decodedPayload) {\n enrichJwtMetadata(\n jwtMeta,\n validation.decodedPayload,\n checkExpiration,\n verbose,\n );\n } else if (verbose) {\n logger.warn(\n `JWT validation failed for cookie ${cookie.name}: ${validation.error}`,\n );\n }\n } else if (decodeClaims) {\n // Just decode without validation\n const decoded = decodeToken(cookie.value);\n if (decoded) {\n jwtMeta.jwtValidation = {\n isValid: true,\n decodedPayload: decoded.payload,\n header: decoded.header,\n };\n enrichJwtMetadata(jwtMeta, decoded.payload, checkExpiration, verbose);\n }\n }\n\n return {\n ...cookie,\n meta: jwtMeta,\n };\n });\n}\n\n/**\n * Enriches JWT metadata with decoded claims\n * @internal\n */\nfunction enrichJwtMetadata(\n meta: JwtCookieMeta,\n payload: JwtPayload,\n checkExpiration: boolean,\n verbose: boolean,\n): void {\n meta.jwtPayload = payload;\n\n // Extract common JWT claims\n if (payload.sub) {\n meta.jwtSubject = payload.sub;\n }\n\n if (payload.iss && typeof payload.iss === \"string\") {\n meta.jwtIssuer = payload.iss;\n }\n\n // Handle expiration\n if (payload.exp) {\n meta.jwtExpiry = new Date(payload.exp * 1000);\n\n if (checkExpiration) {\n const now = new Date();\n if (meta.jwtExpiry < now) {\n meta.jwtValidation = {\n ...meta.jwtValidation,\n isValid: false,\n error: \"JWT has expired\",\n };\n\n if (verbose) {\n logger.warn(\n `JWT in cookie has expired (exp: ${meta.jwtExpiry.toISOString()})`,\n );\n }\n }\n }\n }\n}\n\n/**\n * Filters cookies to only include those containing valid JWTs\n * @param cookies - Array of cookies to filter\n * @param options - JWT detection options\n * @returns Array of cookies that contain valid JWTs\n * @example\n * ```typescript\n * const allCookies = await getCookie({ domain: 'example.com' });\n * const jwtCookies = filterJwtCookies(allCookies);\n * console.log(`Found ${jwtCookies.length} JWT cookies`);\n * ```\n */\nexport function filterJwtCookies(\n cookies: ExportedCookie[],\n options: JwtDetectionOptions = {},\n): JwtEnhancedCookie[] {\n const enhanced = detectJwtCookies(cookies, options);\n return enhanced.filter(\n (cookie) =>\n cookie.meta?.isJwt &&\n (!cookie.meta.jwtValidation || cookie.meta.jwtValidation.isValid),\n );\n}\n\n/**\n * Groups cookies by JWT validity status\n * @param cookies - Array of cookies to group\n * @param options - JWT detection options\n * @returns Object with grouped cookies\n * @example\n * ```typescript\n * const cookies = await getCookie({ domain: 'api.example.com' });\n * const grouped = groupCookiesByJwtStatus(cookies);\n *\n * console.log(`Valid JWTs: ${grouped.validJwts.length}`);\n * console.log(`Invalid JWTs: ${grouped.invalidJwts.length}`);\n * console.log(`Non-JWT cookies: ${grouped.nonJwts.length}`);\n * ```\n */\nexport function groupCookiesByJwtStatus(\n cookies: ExportedCookie[],\n options: JwtDetectionOptions = {},\n): {\n validJwts: JwtEnhancedCookie[];\n invalidJwts: JwtEnhancedCookie[];\n nonJwts: JwtEnhancedCookie[];\n} {\n const enhanced = detectJwtCookies(cookies, options);\n\n const validJwts: JwtEnhancedCookie[] = [];\n const invalidJwts: JwtEnhancedCookie[] = [];\n const nonJwts: JwtEnhancedCookie[] = [];\n\n for (const cookie of enhanced) {\n if (!cookie.meta?.isJwt) {\n nonJwts.push(cookie);\n } else if (cookie.meta.jwtValidation?.isValid) {\n validJwts.push(cookie);\n } else {\n invalidJwts.push(cookie);\n }\n }\n\n return { validJwts, invalidJwts, nonJwts };\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Default handler for cookie output when no specific format is requested\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs:\n * // abc123\n * // xyz789\n * ```\n */\nexport class DefaultOutputHandler implements OutputHandler {\n /**\n * Always returns true as this is the default handler\n * @param _args - The parsed command line arguments\n * @returns Always returns true\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * const canHandle = handler.canHandle({ format: 'default' }); // true\n * ```\n */\n public canHandle(_args: ParsedArgs): boolean {\n return true;\n }\n\n /**\n * Outputs unique cookie values\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new DefaultOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'example.com', value: 'abc123' }, // Duplicate value\n * { name: 'token', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs only unique values:\n * // abc123\n * // xyz789\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n const uniqueValues = new Set(\n results.map((result) => result.value as string),\n );\n for (const value of uniqueValues) {\n logger.log(value);\n }\n }\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles raw dump output of cookie data\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.handle([\n * { name: 'session', domain: 'example.com', value: 'abc123' },\n * { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * ]);\n * // Outputs the full cookie objects:\n * // [\n * // { name: 'session', domain: 'example.com', value: 'abc123' },\n * // { name: 'auth', domain: 'api.example.com', value: 'xyz789' }\n * // ]\n * ```\n */\nexport class DumpOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on dump flags\n * @param args - The parsed command line arguments\n * @returns True if dump flags are set\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.canHandle({ dump: true }); // true\n * handler.canHandle({ d: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args.dump === true || args.d === true;\n }\n\n /**\n * Outputs the raw cookie data\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new DumpOutputHandler();\n * handler.handle([{\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome'\n * }\n * }]);\n * // Outputs the full cookie object with all properties\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(results);\n }\n}\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\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\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\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\nexport default 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\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\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\nexport default 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\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default isSymbol;\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\nexport default 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\nexport default isArray;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\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\nexport default baseToString;\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\nexport default isObject;\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\nexport default identity;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\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\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\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\nexport default 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\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\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\nexport default 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\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\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\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\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\nexport default isIndex;\n","import defineProperty from './_defineProperty.js';\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\nexport default baseAssignValue;\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\nexport default eq;\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\nexport default isLength;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\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\nexport default isArrayLike;\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\nexport default isPrototype;\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\nexport default baseTimes;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default 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\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\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\nexport default isBuffer;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default 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\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\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\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\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\nexport default isTypedArray;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\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\nexport default arrayLikeKeys;\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\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\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\nexport default baseKeys;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\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\nexport default keys;\n","import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\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\nexport default isKey;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default 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\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\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\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\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\nexport default Hash;\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\nexport default listCacheClear;\n","import eq from './eq.js';\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\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\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\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\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\nexport default ListCache;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\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\nexport default 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\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\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\nexport default getMapData;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\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\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\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\nexport default MapCache;\n","import MapCache from './_MapCache.js';\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\nexport default memoize;\n","import memoize from './memoize.js';\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\nexport default memoizeCapped;\n","import memoizeCapped from './_memoizeCapped.js';\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\nexport default stringToPath;\n","import baseToString from './_baseToString.js';\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\nexport default toString;\n","import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\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\nexport default castPath;\n","import isSymbol from './isSymbol.js';\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\nexport default toKey;\n","import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\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\nexport default baseGet;\n","import baseGet from './_baseGet.js';\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\nexport default get;\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\nexport default arrayPush;\n","import ListCache from './_ListCache.js';\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\nexport default 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\nexport default 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\nexport default 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\nexport default stackHas;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\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\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\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\nexport default Stack;\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\nexport default 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\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\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\nexport default getSymbols;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\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\nexport default baseGetAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\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\nexport default getAllKeys;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\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\nexport default getTag;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\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\nexport default 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\nexport default setCacheHas;\n","import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\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\nexport default 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\nexport default 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\nexport default cacheHas;\n","import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\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\nexport default 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\nexport default 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\nexport default setToArray;\n","import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\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\nexport default equalByTag;\n","import getAllKeys from './_getAllKeys.js';\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\nexport default equalObjects;\n","import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\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\nexport default baseIsEqualDeep;\n","import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\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\nexport default baseIsEqual;\n","import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\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\nexport default baseIsMatch;\n","import isObject from './isObject.js';\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\nexport default isStrictComparable;\n","import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\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\nexport default 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\nexport default matchesStrictComparable;\n","import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\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\nexport default baseMatches;\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\nexport default baseHasIn;\n","import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\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\nexport default hasPath;\n","import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\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\nexport default hasIn;\n","import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\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\nexport default 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\nexport default baseProperty;\n","import baseGet from './_baseGet.js';\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\nexport default basePropertyDeep;\n","import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\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\nexport default property;\n","import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\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\nexport default baseIteratee;\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\nexport default arrayAggregator;\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\nexport default createBaseFor;\n","import createBaseFor from './_createBaseFor.js';\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\nexport default baseFor;\n","import baseFor from './_baseFor.js';\nimport keys from './keys.js';\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\nexport default baseForOwn;\n","import isArrayLike from './isArrayLike.js';\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\nexport default createBaseEach;\n","import baseForOwn from './_baseForOwn.js';\nimport createBaseEach from './_createBaseEach.js';\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\nexport default baseEach;\n","import baseEach from './_baseEach.js';\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\nexport default baseAggregator;\n","import arrayAggregator from './_arrayAggregator.js';\nimport baseAggregator from './_baseAggregator.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\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\nexport default createAggregator;\n","import baseAssignValue from './_baseAssignValue.js';\nimport createAggregator from './_createAggregator.js';\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\nexport default groupBy;\n","import { groupBy } from \"lodash-es\";\n\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles grouped dump output of cookie data\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies1.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies2.db' }\n * }\n * ]);\n * // Outputs cookies grouped by file:\n * // {\n * // \"/path/to/cookies1.db\": [\n * // { name: \"session\", domain: \"example.com\", value: \"abc123\", ... }\n * // ],\n * // \"/path/to/cookies2.db\": [\n * // { name: \"auth\", domain: \"api.example.com\", value: \"xyz789\", ... }\n * // ]\n * // }\n * ```\n */\nexport class GroupedDumpOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on grouped dump flags\n * @param args - The parsed command line arguments\n * @returns True if grouped dump flags are set\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.canHandle({ 'dump-grouped': true }); // true\n * handler.canHandle({ D: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args[\"dump-grouped\"] === true || args.D === true;\n }\n\n /**\n * Outputs the cookie data grouped by source file\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new GroupedDumpOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/chrome/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/firefox/cookies.sqlite' }\n * }\n * ]);\n * // Groups and outputs cookies by their source file\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n const groupedByFile = groupBy(results, (r) => r.meta?.file ?? \"unknown\");\n logger.log(JSON.stringify(groupedByFile, null, 2));\n }\n}\n","import { groupBy } from \"lodash-es\";\n\nimport type { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n // Format cookies as they would appear in a Cookie header or document.cookie\n // Each cookie is \"name=value\" separated by \"; \"\n return cookies.map((c) => `${c.name}=${c.value}`).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies\n .map((c) => `${c.name}=${c.value}`)\n .join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import { renderCookies } from \"@core/cookies/renderCookies\";\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles grouped render output of cookie data\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies1.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies2.db' }\n * }\n * ]);\n * // Outputs cookies in a grouped format:\n * // /path/to/cookies1.db:\n * // example.com:\n * // session=abc123\n * // /path/to/cookies2.db:\n * // api.example.com:\n * // auth=xyz789\n * ```\n */\nexport class GroupedRenderOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on grouped render flags\n * @param args - The parsed command line arguments\n * @returns True if grouped render flags are set\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.canHandle({ 'render-grouped': true }); // true\n * handler.canHandle({ R: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args[\"render-grouped\"] === true || args.R === true;\n }\n\n /**\n * Outputs the cookie data in a grouped format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new GroupedRenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/chrome/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/firefox/cookies.sqlite' }\n * }\n * ]);\n * // Outputs:\n * // /path/to/chrome/cookies.db:\n * // example.com:\n * // session=abc123\n * // /path/to/firefox/cookies.sqlite:\n * // example.com:\n * // auth=xyz789\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(renderCookies(results, { format: \"grouped\" }));\n }\n}\n","import logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles JSON output of cookie data\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies.db' }\n * }\n * ]);\n * // Outputs:\n * // {\n * // \"name\": \"session\",\n * // \"domain\": \"example.com\",\n * // \"value\": \"abc123\",\n * // \"meta\": {\n * // \"file\": \"/path/to/cookies.db\"\n * // }\n * // }\n * ```\n */\nexport class JsonOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on JSON output flag\n * @param args - The parsed command line arguments\n * @returns True if output is set to \"json\"\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.canHandle({ output: 'json' }); // true\n * handler.canHandle({ output: 'text' }); // false\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return args.output === \"json\";\n }\n\n /**\n * Outputs the cookie data in JSON format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new JsonOutputHandler();\n * handler.handle([{\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome',\n * decrypted: true\n * }\n * }]);\n * // Outputs formatted JSON with all cookie properties\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(JSON.stringify(results, null, 2));\n }\n}\n","import { renderCookies } from \"@core/cookies/renderCookies\";\nimport logger from \"@utils/logger\";\n\nimport type { ExportedCookie } from \"../../types/schemas\";\n\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Handles merged render output of cookie data\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: { file: '/path/to/cookies.db' }\n * },\n * {\n * name: 'auth',\n * domain: 'api.example.com',\n * value: 'xyz789',\n * meta: { file: '/path/to/cookies.db' }\n * }\n * ]);\n * // Outputs cookies in a merged format:\n * // example.com:\n * // session=abc123\n * // api.example.com:\n * // auth=xyz789\n * ```\n */\nexport class RenderOutputHandler implements OutputHandler {\n /**\n * Checks if this handler should be used based on render flags\n * @param args - The parsed command line arguments\n * @returns True if any render flag is set\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.canHandle({ render: true }); // true\n * handler.canHandle({ 'render-merged': true }); // true\n * handler.canHandle({ r: true }); // true\n * handler.canHandle({}); // false\n * ```\n */\n public canHandle(args: ParsedArgs): boolean {\n return (\n args.render === true || args[\"render-merged\"] === true || args.r === true\n );\n }\n\n /**\n * Outputs the cookie data in a merged format\n * @param results - Array of exported cookies to output\n * @example\n * ```typescript\n * const handler = new RenderOutputHandler();\n * handler.handle([\n * {\n * name: 'session',\n * domain: 'example.com',\n * value: 'abc123',\n * meta: {\n * file: '/path/to/cookies.db',\n * browser: 'Chrome'\n * }\n * }\n * ]);\n * // Outputs:\n * // example.com:\n * // session=abc123\n * ```\n */\n public handle(results: ExportedCookie[]): void {\n logger.log(renderCookies(results, { format: \"merged\" }));\n }\n}\n","import { DefaultOutputHandler } from \"./DefaultOutputHandler\";\nimport { DumpOutputHandler } from \"./DumpOutputHandler\";\nimport { GroupedDumpOutputHandler } from \"./GroupedDumpOutputHandler\";\nimport { GroupedRenderOutputHandler } from \"./GroupedRenderOutputHandler\";\nimport { JsonOutputHandler } from \"./JsonOutputHandler\";\nimport { RenderOutputHandler } from \"./RenderOutputHandler\";\nimport type { OutputHandler, ParsedArgs } from \"./types\";\n\n/**\n * Factory for creating appropriate output handlers based on command-line arguments\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Get JSON output handler\n * const jsonHandler = factory.getHandler({ output: 'json' });\n *\n * // Get dump output handler\n * const dumpHandler = factory.getHandler({ dump: true });\n *\n * // Get default handler when no matching handler found\n * const defaultHandler = factory.getHandler({});\n * ```\n */\nexport class OutputHandlerFactory {\n private readonly handlers: OutputHandler[];\n private readonly validOutputFormats = [\"json\"] as const;\n\n /**\n * Initializes the factory with all available output handlers\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n * // Factory is initialized with:\n * // - DumpOutputHandler\n * // - GroupedDumpOutputHandler\n * // - RenderOutputHandler\n * // - GroupedRenderOutputHandler\n * // - JsonOutputHandler\n * // - DefaultOutputHandler\n * ```\n */\n public constructor() {\n this.handlers = [\n new DumpOutputHandler(),\n new GroupedDumpOutputHandler(),\n new RenderOutputHandler(),\n new GroupedRenderOutputHandler(),\n new JsonOutputHandler(),\n new DefaultOutputHandler(),\n ];\n }\n\n /**\n * Validates the output format specified in arguments\n * @param args - The parsed command line arguments\n * @throws Error if an invalid output format is specified\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Valid format - no error\n * factory.validateOutputFormat({ output: 'json' });\n *\n * // Invalid format - throws error\n * try {\n * factory.validateOutputFormat({ output: 'invalid' });\n * } catch (error) {\n * console.error('Invalid output format'); // Error thrown\n * }\n * ```\n */\n private validateOutputFormat(args: ParsedArgs): void {\n if (\n args.output !== undefined &&\n !this.validOutputFormats.includes(\n args.output as (typeof this.validOutputFormats)[number],\n )\n ) {\n const validFormats = this.validOutputFormats.join(\", \");\n throw new Error(\n `Invalid output format: '${args.output}'. Valid formats are: ${validFormats}`,\n );\n }\n }\n\n /**\n * Returns the first handler that can handle the given arguments\n * @param args - The parsed command line arguments\n * @returns The first handler that can handle the arguments, or DefaultOutputHandler if none found\n * @throws Error if an invalid output format is specified\n * @example\n * ```typescript\n * const factory = new OutputHandlerFactory();\n *\n * // Get JSON handler\n * const jsonHandler = factory.getHandler({ output: 'json' });\n *\n * // Get grouped render handler\n * const groupedHandler = factory.getHandler({ 'render-grouped': true });\n *\n * // Get dump handler\n * const dumpHandler = factory.getHandler({ dump: true });\n *\n * // Get default handler when no specific format requested\n * const defaultHandler = factory.getHandler({});\n * ```\n */\n public getHandler(args: ParsedArgs): OutputHandler {\n this.validateOutputFormat(args);\n\n return (\n this.handlers.find((handler) => handler.canHandle(args)) ??\n new DefaultOutputHandler()\n );\n }\n}\n","import type {\n CookieQueryOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\n\nimport type { CookieQueryStrategy } from \"./CookieStrategyFactory\";\n\n/**\n * Service for querying cookies using a strategy\n */\nexport class CookieQueryService {\n /**\n * Creates a new CookieQueryService instance\n * @param strategy - The strategy to use for querying cookies\n */\n public constructor(private readonly strategy: CookieQueryStrategy) {}\n\n /**\n * Queries cookies from the strategy with options\n * @param spec - The cookie specification to query for\n * @param options - Query options including limit, removeExpired, store path, and force flag\n * @returns Array of exported cookies\n */\n public async queryCookies(\n spec: CookieSpec,\n options?: CookieQueryOptions,\n ): Promise<ExportedCookie[]> {\n return this.strategy.queryCookies(\n spec.name,\n spec.domain,\n options?.store,\n options?.force,\n );\n }\n}\n","/**\n * Browser detection utilities for cookie store files\n * @module BrowserDetector\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"BrowserDetector\");\n\n/**\n * Supported browser types for cookie extraction\n */\nexport type BrowserType =\n | \"chrome\"\n | \"firefox\"\n | \"safari\"\n | \"edge\"\n | \"arc\"\n | \"opera\"\n | \"opera-gx\";\n\n/**\n * Magic bytes for Safari binary cookies format\n */\nconst SAFARI_MAGIC_BYTES = {\n c: 0x63, // 'c'\n o1: 0x6f, // 'o'\n o2: 0x6f, // 'o'\n k: 0x6b, // 'k'\n};\n\n/**\n * Browser detection patterns for cookie store files\n */\nconst BROWSER_PATTERNS: Array<{\n browser: BrowserType;\n pattern: (filename: string) => boolean;\n}> = [\n {\n browser: \"firefox\",\n pattern: (filename) => filename.includes(\"cookies.sqlite\"),\n },\n {\n browser: \"chrome\",\n pattern: (filename) =>\n filename.includes(\"cookies\") && filename.endsWith(\".db\"),\n },\n {\n browser: \"safari\",\n pattern: (filename) => filename.includes(\"cookies.binarycookies\"),\n },\n];\n\n/**\n * Checks if a file contains Safari binary cookies magic bytes\n * @param storePath - Path to the cookie store file\n * @returns True if the file has Safari's binary cookie format signature\n */\nexport function checkSafariMagicBytes(storePath: string): boolean {\n try {\n const buffer = readFileSync(storePath);\n // Safari binary cookies start with \"cook\" magic bytes\n return (\n buffer.length >= 4 &&\n buffer[0] === SAFARI_MAGIC_BYTES.c &&\n buffer[1] === SAFARI_MAGIC_BYTES.o1 &&\n buffer[2] === SAFARI_MAGIC_BYTES.o2 &&\n buffer[3] === SAFARI_MAGIC_BYTES.k\n );\n } catch (error) {\n logger.debug(\"Failed to read file for magic bytes check\", {\n path: storePath,\n error,\n });\n return false;\n }\n}\n\n/**\n * Detects browser type from filename patterns\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n */\nexport function detectBrowserFromFilename(\n storePath: string,\n): BrowserType | undefined {\n const filename = storePath.toLowerCase();\n\n for (const { browser, pattern } of BROWSER_PATTERNS) {\n if (pattern(filename)) {\n logger.debug(\"Detected browser from filename\", {\n browser,\n filename,\n });\n return browser;\n }\n }\n\n return undefined;\n}\n\n/**\n * Detects the browser type from a cookie store file\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n */\nexport function detectBrowserFromStore(\n storePath: string,\n): BrowserType | undefined {\n if (!storePath || !existsSync(storePath)) {\n logger.debug(\"Store path does not exist\", { storePath });\n return undefined;\n }\n\n // Check for Safari binary cookies format first (most specific)\n if (checkSafariMagicBytes(storePath)) {\n logger.info(\"Detected Safari binary cookies from magic bytes\");\n return \"safari\";\n }\n\n // Check filename patterns\n const detectedBrowser = detectBrowserFromFilename(storePath);\n if (detectedBrowser) {\n logger.info(\"Detected browser from filename pattern\", {\n browser: detectedBrowser,\n });\n return detectedBrowser;\n }\n\n logger.debug(\"Could not detect browser type from store\", { storePath });\n return undefined;\n}\n\n/**\n * Validates if a string is a known browser type\n * @param browser - The browser string to validate\n * @returns True if the browser is a known type\n */\nexport function isValidBrowserType(browser: string): browser is BrowserType {\n const validTypes: BrowserType[] = [\n \"chrome\",\n \"firefox\",\n \"safari\",\n \"edge\",\n \"arc\",\n \"opera\",\n \"opera-gx\",\n ];\n return validTypes.includes(browser as BrowserType);\n}\n\n/**\n * Gets a human-readable name for a browser type\n * @param browser - The browser type\n * @returns The display name for the browser\n */\nexport function getBrowserDisplayName(browser: BrowserType): string {\n const displayNames: Record<BrowserType, string> = {\n chrome: \"Google Chrome\",\n firefox: \"Mozilla Firefox\",\n safari: \"Safari\",\n edge: \"Microsoft Edge\",\n arc: \"Arc\",\n opera: \"Opera\",\n \"opera-gx\": \"Opera GX\",\n };\n return displayNames[browser];\n}\n","/**\n * Factory for creating browser-specific cookie query strategies\n * @module StrategyFactory\n */\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport { ArcCookieQueryStrategy } from \"./arc/ArcCookieQueryStrategy\";\nimport type { BaseCookieQueryStrategy } from \"./BaseCookieQueryStrategy\";\nimport {\n type BrowserType,\n detectBrowserFromStore,\n isValidBrowserType,\n} from \"./BrowserDetector\";\nimport { ChromeCookieQueryStrategy } from \"./chrome/ChromeCookieQueryStrategy\";\nimport { CompositeCookieQueryStrategy } from \"./CompositeCookieQueryStrategy\";\nimport { EdgeCookieQueryStrategy } from \"./edge/EdgeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"./firefox/FirefoxCookieQueryStrategy\";\nimport { OperaCookieQueryStrategy } from \"./opera/OperaCookieQueryStrategy\";\nimport { OperaGXCookieQueryStrategy } from \"./opera/OperaGXCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"./safari/SafariCookieQueryStrategy\";\n\n/**\n * A strategy that can query cookies - either a single browser or composite\n */\nexport type AnyQueryStrategy =\n | BaseCookieQueryStrategy\n | CompositeCookieQueryStrategy;\n\nconst logger = createTaggedLogger(\"StrategyFactory\");\n\n/**\n * Strategy constructor type\n */\ntype StrategyConstructor = new (profile?: string) => BaseCookieQueryStrategy;\n\n/**\n * Registry of browser strategies\n */\nconst STRATEGY_REGISTRY: Record<BrowserType, StrategyConstructor> = {\n safari: SafariCookieQueryStrategy,\n firefox: FirefoxCookieQueryStrategy,\n chrome: ChromeCookieQueryStrategy,\n edge: EdgeCookieQueryStrategy,\n arc: ArcCookieQueryStrategy,\n opera: OperaCookieQueryStrategy,\n \"opera-gx\": OperaGXCookieQueryStrategy,\n};\n\n/**\n * Creates a strategy for the specified browser\n * @param browser - The browser to create a strategy for\n * @returns A cookie query strategy for the specified browser\n */\nexport function createBrowserStrategy(\n browser: BrowserType,\n): BaseCookieQueryStrategy {\n const Strategy = STRATEGY_REGISTRY[browser];\n if (!Strategy) {\n logger.warn(\"Unknown browser type, falling back to default\", {\n browser,\n });\n // Return Chrome as a default single-browser strategy instead of composite\n return new ChromeCookieQueryStrategy();\n }\n\n logger.debug(\"Creating browser strategy\", { browser });\n return new Strategy();\n}\n\n/**\n * Creates a composite strategy with all browser strategies\n * @returns A composite strategy that queries all browsers\n */\nexport function createCompositeStrategy(): CompositeCookieQueryStrategy {\n logger.debug(\"Creating composite strategy with all browsers\");\n // Use the existing CompositeCookieQueryStrategy which already knows\n // how to combine all browser strategies\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new EdgeCookieQueryStrategy(),\n new ArcCookieQueryStrategy(),\n new OperaCookieQueryStrategy(),\n new OperaGXCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n return new CompositeCookieQueryStrategy(strategies);\n}\n\n/**\n * Creates a composite strategy with selected browser strategies\n * @param browsers - Array of browser types to include\n * @returns A composite strategy that queries selected browsers\n */\nexport function createSelectiveCompositeStrategy(\n browsers: BrowserType[],\n): CompositeCookieQueryStrategy {\n logger.debug(\"Creating selective composite strategy\", { browsers });\n\n const strategies = browsers\n .map((browser) => {\n const Strategy = STRATEGY_REGISTRY[browser];\n return Strategy ? new Strategy() : null;\n })\n .filter(\n (strategy): strategy is BaseCookieQueryStrategy => strategy !== null,\n );\n\n if (strategies.length === 0) {\n logger.warn(\"No valid strategies found, using full composite\");\n return createCompositeStrategy();\n }\n\n return new CompositeCookieQueryStrategy(strategies);\n}\n\n/**\n * Creates a strategy based on browser type or store path\n * @param options - Options for strategy creation\n * @param options.browser - Optional browser type\n * @param options.storePath - Optional path to a cookie store file\n * @param options.profile\n * @returns A cookie query strategy\n */\nexport function createStrategy(options?: {\n browser?: string;\n storePath?: string;\n profile?: string;\n}): AnyQueryStrategy {\n const { browser, storePath, profile } = options || {};\n\n // If store path is provided, try to detect the browser type\n if (storePath && !browser) {\n const detectedBrowser = detectBrowserFromStore(storePath);\n if (detectedBrowser) {\n logger.info(\"Auto-detected browser from store path\", {\n browser: detectedBrowser,\n storePath,\n });\n return createBrowserStrategy(detectedBrowser);\n }\n }\n\n // If browser is specified, normalize to lowercase and check if valid\n if (browser) {\n const normalizedBrowser = browser.toLowerCase();\n if (isValidBrowserType(normalizedBrowser)) {\n // Special handling for Chrome with profile\n if (normalizedBrowser === \"chrome\" && profile) {\n logger.debug(\"Creating Chrome strategy with profile\", { profile });\n return new ChromeCookieQueryStrategy(profile);\n }\n return createBrowserStrategy(normalizedBrowser);\n }\n // Log warning for invalid browser type\n logger.warn(\"Invalid browser type specified\", { browser });\n }\n\n // Default to composite strategy\n logger.debug(\"Creating composite strategy as default\");\n return createCompositeStrategy();\n}\n\n/**\n * Gets all available browser types\n * @returns Array of available browser types\n */\nexport function getAvailableBrowsers(): BrowserType[] {\n return Object.keys(STRATEGY_REGISTRY) as BrowserType[];\n}\n\n/**\n * Checks if a browser is supported\n * @param browser - The browser to check\n * @returns True if the browser is supported\n */\nexport function isBrowserSupported(browser: string): boolean {\n return isValidBrowserType(browser);\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\n/**\n * Chromium browser configuration and path management\n * Supports Chrome, Chromium, Brave, Edge, Opera, Vivaldi, and Whale browsers\n * across Windows, macOS, and Linux platforms\n */\n\n/**\n * Supported Chromium-based browsers\n */\nexport const CHROMIUM_BASED_BROWSERS = [\n \"chrome\",\n \"chromium\",\n \"brave\",\n \"edge\",\n \"arc\",\n \"opera\",\n \"opera-gx\",\n \"vivaldi\",\n \"whale\",\n] as const;\n\n/**\n * Type representing all supported Chromium-based browsers.\n * This includes Chrome, Edge, Brave, Arc, Opera, and other Chromium derivatives.\n */\nexport type ChromiumBrowser = (typeof CHROMIUM_BASED_BROWSERS)[number];\n\n/**\n * Browser directory configuration for different platforms\n */\ninterface BrowserPaths {\n windows: string;\n macos: string;\n linux: string;\n}\n\n/**\n * Get the browser configuration directory for a specific browser and platform\n * @param browser - The chromium browser type\n * @returns The path to the browser's configuration directory\n * @throws {Error} If the user home directory cannot be determined or platform is unsupported\n */\nexport function getChromiumBrowserPath(browser: ChromiumBrowser): string {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n\n assertPlatformSupported();\n const currentPlatform = getPlatform();\n\n const browserPaths: Record<ChromiumBrowser, BrowserPaths> = {\n chrome: {\n windows: join(home, \"AppData\", \"Local\", \"Google\", \"Chrome\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\"),\n linux: join(home, \".config\", \"google-chrome\"),\n },\n chromium: {\n windows: join(home, \"AppData\", \"Local\", \"Chromium\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Chromium\"),\n linux: join(home, \".config\", \"chromium\"),\n },\n brave: {\n windows: join(\n home,\n \"AppData\",\n \"Local\",\n \"BraveSoftware\",\n \"Brave-Browser\",\n \"User Data\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"BraveSoftware\",\n \"Brave-Browser\",\n ),\n linux: join(home, \".config\", \"BraveSoftware\", \"Brave-Browser\"),\n },\n edge: {\n windows: join(home, \"AppData\", \"Local\", \"Microsoft\", \"Edge\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Microsoft Edge\"),\n linux: join(home, \".config\", \"microsoft-edge\"),\n },\n arc: {\n windows: join(home, \"AppData\", \"Local\", \"Arc\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Arc\", \"User Data\"),\n linux: join(home, \".config\", \"arc\"),\n },\n opera: {\n windows: join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Opera Software\",\n \"Opera Stable\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.Opera\",\n ),\n linux: join(home, \".config\", \"opera\"),\n },\n \"opera-gx\": {\n windows: join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Opera Software\",\n \"Opera GX Stable\",\n ),\n macos: join(\n home,\n \"Library\",\n \"Application Support\",\n \"com.operasoftware.OperaGX\",\n ),\n linux: join(home, \".config\", \"opera-gx\"),\n },\n vivaldi: {\n windows: join(home, \"AppData\", \"Local\", \"Vivaldi\", \"User Data\"),\n macos: join(home, \"Library\", \"Application Support\", \"Vivaldi\"),\n linux: join(home, \".config\", \"vivaldi\"),\n },\n whale: {\n windows: join(\n home,\n \"AppData\",\n \"Local\",\n \"Naver\",\n \"Naver Whale\",\n \"User Data\",\n ),\n macos: join(home, \"Library\", \"Application Support\", \"Naver\", \"Whale\"),\n linux: join(home, \".config\", \"naver-whale\"),\n },\n };\n\n const paths = browserPaths[browser];\n\n switch (currentPlatform) {\n case \"win32\":\n return paths.windows;\n case \"darwin\":\n return paths.macos;\n case \"linux\":\n return paths.linux;\n default:\n throw new Error(`Platform ${currentPlatform} is not supported`);\n }\n}\n\n/**\n * Get all Chromium browser paths for the current platform\n * @returns Record mapping browser names to their configuration directory paths\n */\nexport function getAllChromiumBrowserPaths(): Record<ChromiumBrowser, string> {\n const result: Partial<Record<ChromiumBrowser, string>> = {};\n\n for (const browser of CHROMIUM_BASED_BROWSERS) {\n try {\n result[browser] = getChromiumBrowserPath(browser);\n } catch {\n // Skip browsers that fail (e.g., unsupported platform)\n }\n }\n\n return result as Record<ChromiumBrowser, string>;\n}\n","import { getPlatform, isPlatformSupported } from \"@utils/platformUtils\";\nimport { isChromeRunning } from \"@utils/ProcessDetector\";\n\nimport type {\n CookieRow,\n CookieSpec,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { chromeTimestampToDate } from \"../../../utils/chromeDates\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\nimport type { ChromiumBrowser } from \"../chrome/ChromiumBrowsers\";\nimport { decrypt } from \"../chrome/decrypt\";\nimport { getChromiumPassword } from \"../chrome/getChromiumPassword\";\nimport { CookieQueryBuilder } from \"../sql/CookieQueryBuilder\";\nimport { getGlobalConnectionManager } from \"../sql/DatabaseConnectionManager\";\nimport { getGlobalQueryMonitor } from \"../sql/QueryMonitor\";\n\ninterface DecryptionContext {\n file: string;\n password: string | Buffer;\n browser: string;\n metaVersion?: number;\n}\n\n/**\n * Create an exported cookie object\n * @param domain - Cookie domain\n * @param name - Cookie name\n * @param value - Cookie value\n * @param expiry - Cookie expiry timestamp\n * @param file - Source file path\n * @param browser - Browser name\n * @param decrypted - Whether the cookie was decrypted\n * @returns ExportedCookie object\n */\nexport function createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n browser: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: chromeTimestampToDate(expiry),\n meta: {\n file,\n browser,\n decrypted,\n },\n };\n}\n\n/**\n * Base strategy for querying cookies from Chromium-based browsers.\n * This abstract class provides shared logic for Chrome, Chromium, Brave, Edge, etc.\n */\nexport abstract class BaseChromiumCookieQueryStrategy extends BaseCookieQueryStrategy {\n protected lockHandler: BrowserLockHandler;\n protected browserDisplayName: string;\n protected browserType: ChromiumBrowser;\n\n /**\n * Creates a new instance of BaseChromiumCookieQueryStrategy\n * @param strategyName - Name of the strategy for logging\n * @param browserName - Display name of the browser\n * @param browserType - The Chromium browser type for password retrieval\n */\n public constructor(\n strategyName: string,\n browserName: string,\n browserType: ChromiumBrowser = \"chrome\",\n ) {\n super(strategyName, \"Chrome\"); // Use \"Chrome\" for base class compatibility\n this.browserDisplayName = browserName;\n this.browserType = browserType;\n this.lockHandler = new BrowserLockHandler(this.logger, \"Chrome\");\n }\n\n /**\n * Batch query cookies for multiple specs\n * Optimized to execute combined SQL queries per database file\n * @param specs - Array of cookie specifications\n * @returns Array of exported cookies\n */\n async batchQueryCookies(specs: CookieSpec[]): Promise<ExportedCookie[]> {\n if (!this.isPlatformSupported()) {\n return [];\n }\n\n const files = this.getCookieFiles();\n if (files.length === 0) {\n this.logger.debug(`No ${this.browserDisplayName} cookie files found`);\n return [];\n }\n\n try {\n const password = await getChromiumPassword(this.browserType);\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n const fileResults = await this.processBatchFile(file, specs, password);\n results.push(...fileResults);\n }\n\n return results;\n } catch (error) {\n this.logger.error(\n `Failed to get ${this.browserDisplayName} password for batch query`,\n {\n error: this.getErrorMessage(error),\n },\n );\n return [];\n }\n }\n\n /**\n * Process a batch of specs for a single cookie file\n * @param file - Cookie file path\n * @param specs - Array of cookie specifications\n * @param password - Decryption password\n * @returns Array of exported cookies\n */\n protected async processBatchFile(\n file: string,\n specs: CookieSpec[],\n password: string | Buffer,\n ): Promise<ExportedCookie[]> {\n try {\n const connectionManager = getGlobalConnectionManager();\n const monitor = getGlobalQueryMonitor();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n\n // Convert CookieSpec to CookieQueryOptions\n const queryOptions = specs.map((spec) => ({\n name: spec.name,\n domain: spec.domain,\n browser: \"chrome\" as const,\n }));\n\n const queryConfig = queryBuilder.buildBatchSelectQuery(queryOptions);\n\n const encryptedCookies = await connectionManager.executeQuery(\n file,\n (db) => {\n const rows = monitor.executeQuery<{\n encrypted_value: Buffer;\n name: string;\n domain: string;\n expiry: number;\n }>(db, queryConfig.sql, queryConfig.params, file);\n\n return rows.map(\n (row): CookieRow => ({\n name: row.name,\n domain: row.domain,\n value: row.encrypted_value,\n expiry: row.expiry,\n }),\n );\n },\n queryConfig.description || queryConfig.sql,\n );\n\n const metaVersion = await this.getMetaVersion(file);\n const context: DecryptionContext = {\n file,\n password,\n browser: this.browserDisplayName,\n metaVersion,\n };\n\n const results = await Promise.allSettled(\n encryptedCookies.map(async (cookie) =>\n this.processCookie(cookie, context),\n ),\n );\n\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie> =>\n result.status === \"fulfilled\",\n )\n .map((result) => result.value);\n } catch (error) {\n this.logger.warn(\n `Error batch processing ${this.browserDisplayName} cookie file ${file}`,\n {\n error: this.getErrorMessage(error),\n file,\n specsCount: specs.length,\n },\n );\n return [];\n }\n }\n\n /**\n * Get cookie file paths for the browser\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected abstract getCookieFilePaths(store?: string): string[];\n\n /**\n * Get the browser-specific display name\n * @returns Browser display name\n */\n protected getBrowserName(): string {\n return this.browserDisplayName;\n }\n\n /**\n * Executes the Chromium-specific query logic\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings\n * @returns A promise that resolves to an array of exported cookies\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n if (!this.isPlatformSupported()) {\n return [];\n }\n\n const files = this.getCookieFiles(store);\n if (files.length === 0) {\n this.logger.debug(`No ${this.browserDisplayName} cookie files found`);\n return [];\n }\n\n try {\n const password = await getChromiumPassword(this.browserType);\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n const fileResults = await this.processFileWithRetry(\n file,\n name,\n domain,\n password,\n force,\n );\n results.push(...fileResults);\n }\n\n return results;\n } catch (error) {\n this.logger.error(`Failed to get ${this.browserDisplayName} password`, {\n error: this.getErrorMessage(error),\n });\n return [];\n }\n }\n\n /**\n * Check if the current platform is supported\n * @returns True if platform is supported\n */\n protected isPlatformSupported(): boolean {\n if (!isPlatformSupported()) {\n this.logger.warn(\"Platform not supported\", {\n platform: getPlatform(),\n supportedPlatforms: [\"darwin\", \"win32\", \"linux\"],\n });\n return false;\n }\n return true;\n }\n\n /**\n * Get cookie files to process\n * @param store - Optional specific store path\n * @returns Array of file paths\n */\n protected getCookieFiles(store?: string): string[] {\n const cookieFiles = store ?? this.getCookieFilePaths();\n return Array.isArray(cookieFiles) ? cookieFiles : [cookieFiles];\n }\n\n /**\n * Convert error to string message\n * @param error - The error to convert\n * @returns Error message string\n */\n protected getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n }\n\n /**\n * Process a file with retry logic for lock conflicts\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @param force - Force processing\n * @returns Array of exported cookies\n */\n private async processFileWithRetry(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n return await this.processFile(file, name, domain, password);\n } catch (error) {\n const lockResult = await this.handleFileError(\n error,\n file,\n name,\n domain,\n force,\n );\n\n if (lockResult.resolved) {\n return this.retryAfterBrowserClose(\n file,\n name,\n domain,\n password,\n lockResult.shouldRelaunch,\n );\n }\n\n return [];\n }\n }\n\n /**\n * Handle file processing errors\n * @param error - The error that occurred\n * @param file - File path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param force - Whether to force operations\n * @returns Lock result indicating if resolved and should relaunch\n */\n private async handleFileError(\n error: unknown,\n file: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<{ resolved: boolean; shouldRelaunch: boolean }> {\n const processes = await isChromeRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n file,\n processes,\n force !== true,\n );\n\n if (!lockResult.resolved) {\n this.logger.warn(\n `Error reading ${this.browserDisplayName} cookie file ${file}`,\n {\n error: this.getErrorMessage(error),\n file,\n name,\n domain,\n },\n );\n }\n\n return lockResult;\n }\n\n /**\n * Retry after browser close\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @param shouldRelaunch - Whether to relaunch browser\n * @returns Array of exported cookies\n */\n private async retryAfterBrowserClose(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n shouldRelaunch: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\n `Retrying ${this.browserDisplayName} cookie extraction after browser close...`,\n );\n const cookies = await this.processFile(file, name, domain, password);\n this.logger.success(\n `Successfully extracted cookies after closing ${this.browserDisplayName}`,\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError) {\n this.logger.error(\n `Failed to extract cookies even after closing ${this.browserDisplayName}`,\n {\n error: this.getErrorMessage(retryError),\n file,\n },\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n }\n\n /**\n * Process a single cookie file\n * @param file - Cookie file path\n * @param name - Cookie name pattern\n * @param domain - Domain pattern\n * @param password - Decryption password\n * @returns Array of exported cookies\n */\n protected async processFile(\n file: string,\n name: string,\n domain: string,\n password: string | Buffer,\n ): Promise<ExportedCookie[]> {\n try {\n // Use SQL utilities directly instead of getEncryptedChromeCookie\n const connectionManager = getGlobalConnectionManager();\n const monitor = getGlobalQueryMonitor();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n\n const queryConfig = queryBuilder.buildSelectQuery({\n name,\n domain,\n browser: \"chrome\",\n });\n\n const encryptedCookies = await connectionManager.executeQuery(\n file,\n (db) => {\n // The CookieQueryBuilder aliases columns, so we get 'domain' not 'host_key'\n const rows = monitor.executeQuery<{\n encrypted_value: Buffer;\n name: string;\n domain: string;\n expiry: number;\n }>(db, queryConfig.sql, queryConfig.params, file);\n\n // Transform to CookieRow format\n return rows.map(\n (row): CookieRow => ({\n name: row.name,\n domain: row.domain,\n value: row.encrypted_value,\n expiry: row.expiry,\n }),\n );\n },\n queryConfig.sql,\n );\n\n const metaVersion = await this.getMetaVersion(file);\n const context: DecryptionContext = {\n file,\n password,\n browser: this.browserDisplayName,\n metaVersion,\n };\n\n const results = await Promise.allSettled(\n encryptedCookies.map(async (cookie) =>\n this.processCookie(cookie, context),\n ),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n this.logger.error(\n `Failed to process ${this.browserDisplayName} cookie file`,\n {\n error: this.getErrorMessage(error),\n file,\n name,\n domain,\n },\n );\n return [];\n }\n }\n\n /**\n * Get meta version from Chrome database\n * @param file - Database file path\n * @returns Meta version number\n */\n protected async getMetaVersion(file: string): Promise<number> {\n try {\n const connectionManager = getGlobalConnectionManager();\n const queryBuilder = new CookieQueryBuilder(\"chrome\");\n const metaQuery = queryBuilder.buildMetaQuery(\"version\");\n\n const metaResult = await connectionManager.executeQuery(\n file,\n (db) => {\n const stmt = db.prepare(metaQuery.sql);\n return stmt.get(...metaQuery.params) as { value: string } | undefined;\n },\n \"Get meta version\",\n );\n\n return metaResult ? Number.parseInt(metaResult.value, 10) : 0;\n } catch (error) {\n this.logger.debug(\"Could not retrieve meta version, defaulting to 0\", {\n error: this.getErrorMessage(error),\n });\n return 0;\n }\n }\n\n /**\n * Process a single cookie\n * @param cookie - Cookie row from database\n * @param context - Decryption context\n * @returns Exported cookie\n */\n protected async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(\n value,\n context.password,\n context.metaVersion,\n );\n\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n context.browser,\n true,\n );\n } catch (error) {\n this.logger.warn(`Failed to decrypt ${context.browser} cookie`, {\n error: this.getErrorMessage(error),\n });\n\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n context.browser,\n false,\n );\n }\n }\n}\n","import { getErrorMessage } from \"./errorUtils\";\nimport { execSimple } from \"./execSimple\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isWindows, getPlatform } from \"./platformUtils\";\n\nconst logger = createTaggedLogger(\"ProcessDetector\");\n\n/**\n * Parse a process line from ps output\n * @param line - The process line from ps output\n * @param defaultCommand - Default command name if parsing fails\n * @returns ProcessInfo if valid, null otherwise\n */\nfunction parseProcessLine(\n line: string,\n defaultCommand: string,\n): ProcessInfo | null {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n const parsedCommand = parts.slice(10).join(\" \");\n return {\n pid,\n command: parsedCommand !== \"\" ? parsedCommand : defaultCommand,\n details: line.trim(),\n };\n}\n\n/**\n * Parse a process line from Windows tasklist CSV output\n * @param line - Process line from tasklist /FO CSV\n * @param defaultCommand - Default command name if parsing fails\n * @returns ProcessInfo if valid, null otherwise\n */\nfunction parseWindowsProcessLine(\n line: string,\n defaultCommand: string,\n): ProcessInfo | null {\n // Windows tasklist CSV format: \"Image Name\",\"PID\",\"Session Name\",\"Session#\",\"Mem Usage\"\n // Example: \"firefox.exe\",\"1234\",\"Console\",\"1\",\"123,456 K\"\n const parts = line.split(\",\").map((p) => p.replace(/\"/g, \"\").trim());\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n return {\n pid,\n command: parts[0] ?? defaultCommand,\n details: line.trim(),\n };\n}\n\n/**\n * Information about a detected process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n /** Process name/command */\n command: string;\n /** Full process details */\n details: string;\n}\n\n/**\n * Generic browser process detection\n * @param browserName - Name of the browser to detect\n * @param grepPattern - Pattern to grep for in ps output\n * @returns Promise that resolves to array of process information\n */\nasync function detectBrowserProcesses(\n browserName: string,\n grepPattern: string,\n): Promise<ProcessInfo[]> {\n try {\n let command: string;\n\n if (isWindows()) {\n // On Windows, use tasklist or wmic to find processes\n // Map common browser names to Windows process names\n const windowsProcessMap: Record<string, string> = {\n firefox: \"firefox.exe\",\n chrome: \"chrome.exe\",\n \"google chrome\": \"chrome.exe\",\n chromium: \"chromium.exe\",\n safari: \"safari.exe\", // Won't exist on Windows but included for consistency\n edge: \"msedge.exe\",\n };\n\n const processName =\n windowsProcessMap[browserName.toLowerCase()] ??\n windowsProcessMap[grepPattern.toLowerCase()] ??\n `${browserName.toLowerCase()}.exe`;\n\n // Use tasklist which is available on all Windows versions\n command = `tasklist /FI \"IMAGENAME eq ${processName}\" /FO CSV | findstr /i \"${processName}\"`;\n } else {\n // Unix-like systems (macOS, Linux)\n command = `ps aux | grep -i '${grepPattern}' | grep -v grep`;\n }\n\n const { stdout } = await execSimple(command);\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const processes: ProcessInfo[] = [];\n const lines = stdout.split(\"\\n\").filter((line) => line.trim() !== \"\");\n\n for (const line of lines) {\n const processInfo = isWindows()\n ? parseWindowsProcessLine(line, browserName.toLowerCase())\n : parseProcessLine(line, browserName.toLowerCase());\n if (processInfo) {\n processes.push(processInfo);\n }\n }\n\n logger.debug(`${browserName} process detection completed`, {\n processCount: processes.length,\n processes: processes.map((p) => ({ pid: p.pid, command: p.command })),\n platform: getPlatform(),\n });\n\n return processes;\n } catch (error) {\n logger.debug(`Failed to detect ${browserName} processes`, {\n error: getErrorMessage(error),\n platform: getPlatform(),\n });\n return [];\n }\n}\n\n/**\n * Check if Firefox browser is currently running\n * @returns Promise that resolves to array of Firefox process information\n * @example\n * ```typescript\n * const firefoxProcesses = await isFirefoxRunning();\n * if (firefoxProcesses.length > 0) {\n * console.log('Firefox is running, consider closing it for reliable cookie access');\n * }\n * ```\n */\nexport async function isFirefoxRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\"Firefox\", \"firefox\");\n}\n\n/**\n * Check if Chrome browser is currently running\n * @returns Promise that resolves to array of Chrome process information\n */\nexport async function isChromeRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\"Chrome\", \"google chrome\\\\|chromium\");\n}\n\n/**\n * Check if Safari browser is currently running\n * @returns Promise that resolves to array of Safari process information\n */\nexport async function isSafariRunning(): Promise<ProcessInfo[]> {\n return detectBrowserProcesses(\n \"Safari\",\n \"/Applications/Safari.app/Contents/MacOS/Safari\",\n );\n}\n\n/**\n * Get user-friendly advice for browser conflicts\n * @param browserName - Name of the browser\n * @param processes - Array of detected processes\n * @returns User-friendly message with advice\n */\nexport function getBrowserConflictAdvice(\n browserName: string,\n processes: ProcessInfo[],\n): string {\n if (processes.length === 0) {\n return \"\";\n }\n\n const processCount = processes.length;\n const browserDisplayName =\n browserName.charAt(0).toUpperCase() + browserName.slice(1);\n\n return `${browserDisplayName} is currently running (${processCount} process${processCount > 1 ? \"es\" : \"\"} detected). For reliable cookie access, consider closing ${browserDisplayName} and trying again. Alternatively, use the --force flag to attempt access despite the lock.`;\n}\n","/**\n * Chrome date conversion utilities\n *\n * Chrome/Chromium stores timestamps as microseconds since 1601-01-01 00:00:00 UTC\n * JavaScript Date uses milliseconds since 1970-01-01 00:00:00 UTC\n */\n\n/**\n * The number of seconds between Chrome epoch (1601-01-01) and Unix epoch (1970-01-01)\n * This is 369 years worth of seconds\n */\nexport const CHROME_EPOCH_OFFSET_SECONDS = 11644473600;\n\n/**\n * Microseconds per second\n */\nexport const MICROSECONDS_PER_SECOND = 1000000;\n\n/**\n * Milliseconds per second\n */\nexport const MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * Converts a Chrome timestamp to a JavaScript Date object\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns JavaScript Date object or \"Infinity\" for session cookies, undefined for null/undefined\n */\nexport function chromeTimestampToDate(\n chromeTimestamp: number | undefined | null,\n): Date | \"Infinity\" | undefined {\n // Handle null or undefined\n if (chromeTimestamp === null || chromeTimestamp === undefined) {\n return undefined;\n }\n\n // Handle invalid numbers\n if (typeof chromeTimestamp !== \"number\" || Number.isNaN(chromeTimestamp)) {\n return undefined;\n }\n\n // Chrome uses 0 for session cookies\n if (chromeTimestamp <= 0) {\n return \"Infinity\";\n }\n\n // Convert Chrome timestamp to Unix timestamp\n const unixTimestampSeconds =\n chromeTimestamp / MICROSECONDS_PER_SECOND - CHROME_EPOCH_OFFSET_SECONDS;\n\n // Sanity check: Unix timestamp should be positive and reasonable\n // Max date: year 3000 (32503680000 seconds since Unix epoch)\n if (unixTimestampSeconds < 0 || unixTimestampSeconds > 32503680000) {\n // Treat unreasonable dates as session cookies\n return \"Infinity\";\n }\n\n // Convert to milliseconds for JavaScript Date\n return new Date(unixTimestampSeconds * MILLISECONDS_PER_SECOND);\n}\n\n/**\n * Converts a JavaScript Date to a Chrome timestamp\n * @param date - JavaScript Date object\n * @returns Microseconds since 1601-01-01 00:00:00 UTC\n */\nexport function dateToChromeTimestamp(date: Date): number {\n if (!(date instanceof Date) || Number.isNaN(date.getTime())) {\n return 0; // Session cookie\n }\n\n // Get Unix timestamp in seconds\n const unixTimestampSeconds = date.getTime() / MILLISECONDS_PER_SECOND;\n\n // Convert to Chrome timestamp\n const chromeTimestampSeconds =\n unixTimestampSeconds + CHROME_EPOCH_OFFSET_SECONDS;\n\n // Convert to microseconds\n return chromeTimestampSeconds * MICROSECONDS_PER_SECOND;\n}\n\n/**\n * Checks if a Chrome timestamp represents a session cookie\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns True if this is a session cookie (no expiry)\n */\nexport function isChromeSessionCookie(\n chromeTimestamp: number | undefined | null,\n): boolean {\n return (\n chromeTimestamp === null ||\n chromeTimestamp === undefined ||\n chromeTimestamp === 0 ||\n (typeof chromeTimestamp === \"number\" && chromeTimestamp <= 0) ||\n // Far future dates (like year 4000) are treated as session cookies by Chrome\n (typeof chromeTimestamp === \"number\" &&\n chromeTimestamp >= 64092211200 * MICROSECONDS_PER_SECOND)\n );\n}\n\n/**\n * Formats a Chrome timestamp for display\n * @param chromeTimestamp - Microseconds since 1601-01-01 00:00:00 UTC\n * @returns Human-readable string representation\n */\nexport function formatChromeTimestamp(\n chromeTimestamp: number | undefined | null,\n): string {\n if (isChromeSessionCookie(chromeTimestamp)) {\n return \"Session\";\n }\n\n const date = chromeTimestampToDate(chromeTimestamp);\n\n if (date === undefined) {\n return \"Session\";\n }\n\n if (date === \"Infinity\") {\n return \"Session\";\n }\n\n return date.toISOString();\n}\n","import { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../types/schemas\";\n\n// Create a simple fallback logger for tests\nconst fallbackLogger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n debug: () => {},\n success: () => {},\n fatal: () => {},\n log: () => {},\n};\n\n/**\n * Base class for cookie query strategies.\n * Provides common functionality and standardized error handling for browser-specific implementations.\n * @implements {CookieQueryStrategy}\n * @abstract\n */\nexport abstract class BaseCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * Logger instance for this strategy\n * @protected\n */\n protected readonly logger;\n\n /**\n * Creates a new instance of BaseCookieQueryStrategy\n * @param strategyName - The name of the strategy for logging purposes\n * @param browserName - The name of the browser this strategy is for\n */\n public constructor(\n strategyName: string,\n public readonly browserName: BrowserName,\n ) {\n const taggedLogger = createTaggedLogger(strategyName);\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/strict-boolean-expressions\n this.logger = taggedLogger || fallbackLogger;\n }\n\n /**\n * Queries cookies from the browser's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain, store, force });\n return await this.executeQuery(name, domain, store, force);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to query cookies\", {\n error: error.message,\n browser: this.browserName,\n strategy: this.constructor.name,\n name,\n domain,\n store,\n force,\n });\n } else {\n this.logger.error(\"Failed to query cookies\", {\n error: String(error),\n browser: this.browserName,\n strategy: this.constructor.name,\n name,\n domain,\n store,\n force,\n });\n }\n return [];\n }\n }\n\n /**\n * Executes the browser-specific query logic\n * @abstract\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n * @protected\n */\n protected abstract executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]>;\n}\n","import { exec } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promisify } from \"node:util\";\n\nimport type { BrowserName } from \"../types/schemas\";\n\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isMacOS } from \"./platformUtils\";\n\n// Re-export BrowserName from schemas for backward compatibility\n/**\n *\n */\nexport type { BrowserName } from \"../types/schemas\";\n\nconst execAsync = promisify(exec);\nconst logger = createTaggedLogger(\"BrowserControl\");\n\n/**\n * Check if the current environment supports interactive prompts\n * @returns True if environment can handle interactive prompts\n */\nfunction isInteractiveEnvironment(): boolean {\n const isCI = process.env.CI === \"true\" || process.env.CI === \"1\";\n const isTest =\n process.env.NODE_ENV === \"test\" || process.env.JEST_WORKER_ID !== undefined;\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n\n return hasTTY && !isCI && !isTest;\n}\n\n/**\n *\n */\nexport interface BrowserControlOptions {\n force?: boolean;\n interactive?: boolean;\n}\n\n/**\n * Map of browser names to their macOS application names\n * Only includes browsers that can be controlled on macOS\n */\nconst BROWSER_APP_NAMES: Partial<Record<BrowserName, string>> = {\n Firefox: \"Firefox\",\n Chrome: \"Google Chrome\",\n Safari: \"Safari\",\n};\n\n/**\n * Check if a browser is running on macOS\n * @param browserName - Name of the browser to check\n * @returns Promise that resolves to true if browser is running\n */\nasync function isBrowserRunningMacOS(\n browserName: BrowserName,\n): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return false;\n }\n const script = `tell application \"System Events\" to (name of processes) contains \"${appName}\"`;\n const { stdout } = await execAsync(`osascript -e '${script}'`);\n return stdout.trim() === \"true\";\n } catch (error) {\n logger.debug(\"Failed to check if browser is running\", {\n browserName,\n error,\n });\n return false;\n }\n}\n\n/**\n * Gracefully quit a browser on macOS\n * @param browserName - Name of the browser to quit\n * @returns Promise that resolves to true if browser was quit successfully\n */\nasync function quitBrowserMacOS(browserName: BrowserName): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return false;\n }\n\n // First, try to quit gracefully\n const quitScript = `tell application \"${appName}\" to quit`;\n await execAsync(`osascript -e '${quitScript}'`);\n\n // Wait a moment for the browser to quit\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n // Check if it's still running\n const stillRunning = await isBrowserRunningMacOS(browserName);\n if (!stillRunning) {\n logger.info(\"Browser quit successfully\", { browserName });\n return true;\n }\n\n logger.warn(\"Browser did not quit gracefully\", { browserName });\n return false;\n } catch (error) {\n logger.error(\"Failed to quit browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Save open tabs in browser before closing (macOS only)\n * This will attempt to save the session so tabs can be restored\n * @param browserName - Name of the browser\n * @returns Promise that resolves when tabs are saved\n */\nasync function saveBrowserSessionMacOS(\n browserName: BrowserName,\n): Promise<void> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n if (!appName) {\n logger.debug(\"Browser not supported for macOS control\", { browserName });\n return;\n }\n\n if (browserName === \"Firefox\") {\n // Firefox: Use keyboard shortcut to save session (Cmd+Shift+D to bookmark all tabs)\n const script = `\n tell application \"${appName}\"\n activate\n end tell\n tell application \"System Events\"\n keystroke \"d\" using {command down, shift down}\n delay 0.5\n key code 36\n end tell\n `;\n await execAsync(`osascript -e '${script}'`);\n logger.debug(\"Attempted to save Firefox session\", { browserName });\n } else if (browserName === \"Chrome\") {\n // Chrome will restore tabs automatically if quit gracefully\n logger.debug(\"Chrome will restore tabs automatically\", { browserName });\n } else {\n // Safari will restore tabs if quit gracefully\n logger.debug(\"Safari will restore tabs automatically\", { browserName });\n }\n } catch (error) {\n logger.debug(\"Failed to save browser session\", { browserName, error });\n }\n}\n\n/**\n * Prompt user for confirmation before closing browser\n * @param browserName - Name of the browser\n * @returns Promise that resolves to true if user confirms\n */\nasync function promptUserConfirmation(\n browserName: BrowserName,\n): Promise<boolean> {\n // Check if we're in a TTY-capable environment\n if (!isInteractiveEnvironment()) {\n logger.debug(\"Non-interactive environment detected, skipping prompt\", {\n browserName,\n CI: process.env.CI,\n NODE_ENV: process.env.NODE_ENV,\n JEST_WORKER_ID: process.env.JEST_WORKER_ID,\n stdin_tty: process.stdin.isTTY,\n stdout_tty: process.stdout.isTTY,\n });\n return false;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `\\n⚠️ ${browserName} is currently running and blocking cookie access.\\n` +\n `Would you like to close ${browserName}? Your tabs will be restored when you reopen it. (y/N): `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n },\n );\n });\n}\n\n/**\n * Relaunch a browser after it has been closed\n * @param browserName - Name of the browser to relaunch\n * @returns Promise that resolves to true if browser was relaunched\n */\nasync function relaunchBrowserMacOS(\n browserName: BrowserName,\n): Promise<boolean> {\n try {\n const appName = BROWSER_APP_NAMES[browserName];\n\n // Launch the browser\n const launchScript = `tell application \"${appName}\" to activate`;\n await execAsync(`osascript -e '${launchScript}'`);\n\n // Give it a moment to start\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n // Check if it's running\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (isRunning) {\n logger.info(\"Browser relaunched successfully\", { browserName });\n return true;\n }\n\n logger.warn(\"Browser did not relaunch\", { browserName });\n return false;\n } catch (error) {\n logger.error(\"Failed to relaunch browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Attempt to close a browser gracefully\n * @param browserName - Name of the browser to close\n * @param options - Control options\n * @returns Promise that resolves to true if browser was closed\n */\nexport async function closeBrowserGracefully(\n browserName: BrowserName,\n options: BrowserControlOptions = {},\n): Promise<boolean> {\n if (!isMacOS()) {\n logger.debug(\"Browser control only supported on macOS\");\n return false;\n }\n\n try {\n // Check if browser is running\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (!isRunning) {\n logger.debug(\"Browser is not running\", { browserName });\n return true;\n }\n\n // If interactive mode, prompt user\n if (options.interactive === true && options.force !== true) {\n const confirmed = await promptUserConfirmation(browserName);\n if (!confirmed) {\n logger.info(\"User cancelled browser close\", { browserName });\n return false;\n }\n }\n\n // Try to save session first (for browsers that support it)\n await saveBrowserSessionMacOS(browserName);\n\n // Quit the browser\n const success = await quitBrowserMacOS(browserName);\n\n if (success) {\n logger.success(\n `${browserName} closed successfully. Tabs will be restored on next launch.`,\n );\n } else {\n logger.warn(\n `Failed to close ${browserName}. You may need to close it manually.`,\n );\n }\n\n return success;\n } catch (error) {\n logger.error(\"Failed to control browser\", { browserName, error });\n return false;\n }\n}\n\n/**\n * Close browser, perform an action, then relaunch the browser\n * @param browserName - Name of the browser\n * @param action - Action to perform while browser is closed\n * @param options - Control options\n * @returns Promise that resolves to the result of the action\n */\nexport async function closeBrowserForAction<T>(\n browserName: BrowserName,\n action: () => Promise<T>,\n options: BrowserControlOptions = {},\n): Promise<T | null> {\n if (!isMacOS()) {\n logger.debug(\"Browser control only supported on macOS\");\n return null;\n }\n\n let browserWasClosed = false;\n\n try {\n // Check if browser is running\n const wasRunning = await isBrowserRunningMacOS(browserName);\n\n if (wasRunning) {\n // Close the browser\n browserWasClosed = await closeBrowserGracefully(browserName, options);\n\n if (!browserWasClosed) {\n logger.warn(\"Failed to close browser, attempting action anyway\");\n } else {\n // Wait for browser to fully close\n await waitForBrowserToClose(browserName, 5000);\n }\n }\n\n // Perform the action\n const result = await action();\n\n // Relaunch browser if we closed it\n if (wasRunning && browserWasClosed) {\n logger.info(`Relaunching ${browserName}...`);\n const relaunched = await relaunchBrowserMacOS(browserName);\n\n if (relaunched) {\n logger.success(\n `${browserName} has been relaunched with your tabs restored`,\n );\n } else {\n logger.warn(\n `Could not relaunch ${browserName} automatically. Please reopen it manually.`,\n );\n }\n }\n\n return result;\n } catch (error) {\n logger.error(\"Failed during browser action\", { browserName, error });\n\n // Try to relaunch browser if we closed it\n if (browserWasClosed) {\n await relaunchBrowserMacOS(browserName);\n }\n\n return null;\n }\n}\n\n/**\n * Wait for a browser to close\n * @param browserName - Name of the browser\n * @param maxWaitMs - Maximum time to wait in milliseconds\n * @returns Promise that resolves to true if browser closed within timeout\n */\nexport async function waitForBrowserToClose(\n browserName: BrowserName,\n maxWaitMs = 10000,\n): Promise<boolean> {\n if (!isMacOS()) {\n return false;\n }\n\n const startTime = Date.now();\n const checkInterval = 500;\n\n while (Date.now() - startTime < maxWaitMs) {\n const isRunning = await isBrowserRunningMacOS(browserName);\n if (!isRunning) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n }\n\n return false;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport { errorMessageContains, getErrorMessage } from \"./errorUtils\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { getPlatform, isWindows } from \"./platformUtils\";\n\nconst execFileAsync = promisify(execFile);\nconst logger = createTaggedLogger(\"FileHandleDetector\");\n\n/**\n * Parse a fuser output line into FileHandleInfo\n * @param line - Line from fuser output\n * @returns FileHandleInfo or null if parsing fails\n */\nfunction parseFuserLine(line: string): FileHandleInfo | null {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 2) {\n return null;\n }\n\n const pidStr = parts[1];\n if (pidStr === undefined || pidStr === \"\") {\n return null;\n }\n\n const pid = Number.parseInt(pidStr, 10);\n if (Number.isNaN(pid)) {\n return null;\n }\n\n const result: FileHandleInfo = {\n pid: pid,\n command: parts[2] ?? \"unknown\",\n };\n\n const user = parts[0];\n if (user !== undefined && user !== \"\") {\n result.user = user;\n }\n\n const mode = parts[3];\n if (mode !== undefined && mode !== \"\") {\n result.mode = mode;\n }\n\n return result;\n}\n\n/**\n * Check if value is a valid process result object\n * @param value - Value to check\n * @returns True if valid process result\n */\nfunction isValidProcessResult(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"ProcessId\" in value &&\n \"ProcessName\" in value\n );\n}\n\n/**\n * Parse PowerShell output into FileHandleInfo array\n * @param stdout - PowerShell command output\n * @returns Array of FileHandleInfo\n */\nfunction parsePowerShellOutput(stdout: string): FileHandleInfo[] {\n const handles: FileHandleInfo[] = [];\n\n try {\n const parsed: unknown = JSON.parse(stdout);\n const results = Array.isArray(parsed) ? parsed : [parsed];\n\n for (const result of results) {\n if (!isValidProcessResult(result)) {\n continue;\n }\n\n const processId = result.ProcessId;\n const processName = result.ProcessName;\n\n if (typeof processId === \"string\" && processId !== \"\") {\n handles.push({\n command: typeof processName === \"string\" ? processName : \"unknown\",\n pid: Number.parseInt(processId, 10),\n });\n }\n }\n } catch (parseError) {\n logger.debug(\"Failed to parse PowerShell output\", {\n error: getErrorMessage(parseError),\n });\n }\n\n return handles;\n}\n\n/**\n * Information about a process holding a file handle\n */\nexport interface FileHandleInfo {\n /** Process ID */\n pid: number;\n /** Process name/command */\n command: string;\n /** User running the process */\n user?: string;\n /** File descriptor or handle type */\n fd?: string;\n /** Access mode (read, write, etc.) */\n mode?: string;\n}\n\n/**\n * Detect processes holding handles to a specific file using lsof\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithLsof(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // Use execFile instead of exec to prevent shell injection\n const { stdout } = await execFileAsync(\"lsof\", [filePath], {\n encoding: \"utf8\",\n });\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const lines = stdout.split(\"\\n\").slice(1); // Skip header\n const handles: FileHandleInfo[] = [];\n\n for (const line of lines) {\n const parts = line.trim().split(/\\s+/);\n const command = parts[0];\n const pidStr = parts[1];\n const user = parts[2];\n const fd = parts[3];\n\n if (\n command !== undefined &&\n command !== \"\" &&\n pidStr !== undefined &&\n pidStr !== \"\" &&\n parts.length >= 4\n ) {\n const pid = Number.parseInt(pidStr, 10);\n if (!Number.isNaN(pid)) {\n const handle: FileHandleInfo = {\n command,\n pid,\n };\n if (user !== undefined && user !== \"\") {\n handle.user = user;\n }\n if (fd !== undefined && fd !== \"\") {\n handle.fd = fd;\n handle.mode = fd.includes(\"w\") ? \"write\" : \"read\";\n }\n handles.push(handle);\n }\n }\n }\n\n logger.debug(\"Detected file handles with lsof\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n\n // Check if lsof is not found\n if (errorMessageContains(error, \"ENOENT\")) {\n logger.debug(\"lsof not available on this system\");\n } else if (errorMessageContains(error, \"No such file\")) {\n // File doesn't exist - return empty array\n logger.debug(\"File does not exist\", { file: filePath });\n } else {\n logger.debug(\"lsof detection failed\", { error: errorMessage });\n }\n\n return [];\n }\n}\n\n/**\n * Detect processes holding handles to a specific file using fuser\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithFuser(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // fuser outputs to stderr, not stdout\n // Use execFile to prevent shell injection\n const result = await execFileAsync(\"fuser\", [\"-v\", filePath], {\n encoding: \"utf8\",\n });\n\n // fuser writes to stderr even on success\n const output = result.stderr || result.stdout || \"\";\n\n if (output.trim() === \"\") {\n return [];\n }\n\n const handles: FileHandleInfo[] = [];\n const lines = output.split(\"\\n\").slice(1); // Skip header\n\n for (const line of lines) {\n const handle = parseFuserLine(line);\n if (handle) {\n handles.push(handle);\n }\n }\n\n logger.debug(\"Detected file handles with fuser\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n\n if (errorMessageContains(error, \"ENOENT\")) {\n logger.debug(\"fuser not available on this system\");\n } else {\n logger.debug(\"fuser detection failed\", { error: errorMessage });\n }\n\n return [];\n }\n}\n\n/**\n * Windows-specific handle detection using PowerShell\n * SECURITY: Properly escapes file path for PowerShell\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectOnWindows(filePath: string): Promise<FileHandleInfo[]> {\n try {\n // Escape single quotes in the file path for PowerShell\n const escapedPath = filePath.replace(/'/g, \"''\");\n\n // Use Get-Process with error handling\n const psScript = `\n $ErrorActionPreference = 'SilentlyContinue'\n $handles = @()\n \n # Try to find processes with the file open\n Get-Process | ForEach-Object {\n try {\n $proc = $_\n # Check if any modules match the file path\n $modules = $proc.Modules | Where-Object { $_.FileName -eq '${escapedPath}' }\n if ($modules) {\n $handles += [PSCustomObject]@{\n ProcessName = $proc.ProcessName\n ProcessId = $proc.Id\n }\n }\n } catch {\n # Skip processes we can't access\n }\n }\n \n # Also try using Get-CimInstance for better file handle detection\n try {\n $query = \"SELECT * FROM CIM_DataFile WHERE Name='${escapedPath.replace(/\\\\/g, \"\\\\\\\\\")}'\"\n $file = Get-CimInstance -Query $query -ErrorAction SilentlyContinue\n if ($file) {\n $assoc = Get-CimAssociatedInstance -InputObject $file -ResultClassName Win32_Process\n foreach ($proc in $assoc) {\n $handles += [PSCustomObject]@{\n ProcessName = $proc.Name\n ProcessId = $proc.ProcessId\n }\n }\n }\n } catch {\n # WMI query failed, ignore\n }\n \n $handles | ConvertTo-Json -Compress\n `;\n\n const { stdout } = await execFileAsync(\n \"powershell\",\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", psScript],\n { encoding: \"utf8\", maxBuffer: 1024 * 1024 },\n );\n\n if (!stdout || stdout.trim() === \"\" || stdout.trim() === \"null\") {\n return [];\n }\n\n const handles = parsePowerShellOutput(stdout);\n\n logger.debug(\"Detected file handles with PowerShell\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch (error) {\n logger.debug(\"Windows handle detection failed\", {\n error: getErrorMessage(error),\n });\n return [];\n }\n}\n\n/**\n * Try to detect using handle.exe from Sysinternals (if available)\n * SECURITY: Uses execFile to prevent shell injection\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nasync function detectWithHandleExe(\n filePath: string,\n): Promise<FileHandleInfo[]> {\n try {\n // handle.exe must be in PATH or current directory\n const { stdout } = await execFileAsync(\"handle\", [\"-nobanner\", filePath], {\n encoding: \"utf8\",\n });\n\n if (!stdout || stdout.trim() === \"\") {\n return [];\n }\n\n const handles: FileHandleInfo[] = [];\n const lines = stdout.split(\"\\n\");\n\n for (const line of lines) {\n // Format: process.exe pid: type handle: path\n const match = line.match(\n /^(.+?)\\s+pid:\\s+(\\d+)\\s+type:\\s+(\\w+)\\s+.+:\\s+(.+)$/i,\n );\n if (\n match?.[1] !== undefined &&\n match?.[1] !== \"\" &&\n match?.[2] !== undefined &&\n match?.[2] !== \"\"\n ) {\n const pid = Number.parseInt(match[2], 10);\n if (!Number.isNaN(pid)) {\n const handle: FileHandleInfo = {\n command: match[1],\n pid,\n };\n if (match?.[3] !== undefined && match[3] !== \"\") {\n handle.fd = match[3];\n }\n handle.mode = \"unknown\";\n handles.push(handle);\n }\n }\n }\n\n logger.debug(\"Detected file handles with handle.exe\", {\n file: filePath,\n handleCount: handles.length,\n });\n\n return handles;\n } catch {\n // handle.exe not available, silently fall back\n return [];\n }\n}\n\n/**\n * Detect all processes that have open handles to a specific file\n * @param filePath - Path to the file to check\n * @returns Array of processes holding handles to the file\n */\nexport async function detectFileHandles(\n filePath: string,\n): Promise<FileHandleInfo[]> {\n const os = getPlatform();\n\n logger.debug(\"Detecting file handles\", { file: filePath, platform: os });\n\n if (isWindows()) {\n // Try handle.exe first (most accurate)\n const handles = await detectWithHandleExe(filePath);\n if (handles.length > 0) {\n return handles;\n }\n\n // Fall back to PowerShell\n return detectOnWindows(filePath);\n }\n\n // Unix-like systems: try lsof first\n let handles = await detectWithLsof(filePath);\n\n // Fallback to fuser if lsof didn't work\n if (handles.length === 0) {\n handles = await detectWithFuser(filePath);\n }\n\n if (handles.length > 0) {\n logger.info(\"File has open handles\", {\n file: filePath,\n handleCount: handles.length,\n processes: handles.map((h) => ({\n pid: h.pid,\n command: h.command,\n mode: h.mode,\n })),\n });\n }\n\n return handles;\n}\n\n/**\n * Check if a file is locked by any process\n * @param filePath - Path to the file to check\n * @returns True if file has open handles, false otherwise\n */\nexport async function isFileLocked(filePath: string): Promise<boolean> {\n const handles = await detectFileHandles(filePath);\n return handles.length > 0;\n}\n\n/**\n * Get detailed information about processes locking a file\n * @param filePath - Path to the file to check\n * @returns Human-readable string describing the lock status\n */\nexport async function getFileLockInfo(filePath: string): Promise<string> {\n const handles = await detectFileHandles(filePath);\n\n if (handles.length === 0) {\n return \"File is not locked\";\n }\n\n const processInfo = handles\n .map(\n (h) =>\n `${h.command} (PID: ${h.pid}${h.user !== undefined && h.user !== \"\" ? `, User: ${h.user}` : \"\"}${h.mode !== undefined && h.mode !== \"\" ? `, Mode: ${h.mode}` : \"\"})`,\n )\n .join(\", \");\n\n return `File is locked by ${handles.length} process${handles.length > 1 ? \"es\" : \"\"}: ${processInfo}`;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { BrowserName } from \"@utils/BrowserControl\";\nimport { getPlatform, isWindows, type Platform } from \"@utils/platformUtils\";\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Interface for platform-specific browser control operations\n * Following SOLID principles - Interface Segregation\n */\nexport interface PlatformBrowserControl {\n /**\n * Check if the browser is supported on this platform\n * @param browserName - The name of the browser to check\n * @returns True if the browser is supported on this platform\n */\n isBrowserSupported(browserName: BrowserName): boolean;\n\n /**\n * Get executable names for a browser on this platform\n * @param browserName - The name of the browser\n * @returns Array of executable names for the browser\n */\n getBrowserExecutables(browserName: BrowserName): string[];\n\n /**\n * Launch a browser on this platform\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported or cannot be launched\n */\n launchBrowser(browserName: BrowserName): Promise<void>;\n\n /**\n * Get the platform name\n * @returns The name of the current platform\n */\n getPlatformName(): string;\n\n /**\n * Check if a browser is installed\n * @param browserName - The name of the browser to check\n * @returns Promise that resolves to true if the browser is installed\n */\n isBrowserInstalled(browserName: BrowserName): Promise<boolean>;\n}\n\n/**\n * Base implementation with common functionality\n * Following DRY principle\n */\nexport abstract class BasePlatformBrowserControl\n implements PlatformBrowserControl\n{\n protected readonly browserExecutables: Partial<Record<BrowserName, string[]>>;\n\n /**\n * Creates a new instance of BasePlatformBrowserControl\n */\n public constructor() {\n this.browserExecutables = this.initializeBrowserExecutables();\n }\n\n /**\n * Initialize browser executables for this platform\n * @returns Record mapping browser names to their executable names\n */\n protected abstract initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n >;\n\n public isBrowserSupported(browserName: BrowserName): boolean {\n const executables = this.browserExecutables[browserName];\n return Boolean(executables && executables.length > 0);\n }\n\n public getBrowserExecutables(browserName: BrowserName): string[] {\n return this.browserExecutables[browserName] || [];\n }\n\n /**\n * Launch a browser on this platform\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported or cannot be launched\n */\n public abstract launchBrowser(browserName: BrowserName): Promise<void>;\n\n /**\n * Get the platform name\n * @returns The name of the current platform\n */\n public abstract getPlatformName(): string;\n\n /**\n * Default implementation to check if browser is installed\n * Can be overridden by platform-specific implementations\n * @param browserName - The name of the browser to check\n * @returns Promise that resolves to true if the browser is installed\n */\n public async isBrowserInstalled(browserName: BrowserName): Promise<boolean> {\n const executables = this.getBrowserExecutables(browserName);\n\n for (const exe of executables) {\n try {\n // Try to check if executable exists using 'which' or 'where'\n const checkCommand = isWindows() ? \"where\" : \"which\";\n await execFileAsync(checkCommand, [exe], { timeout: 1000 });\n return true;\n } catch {\n // Continue checking other executables\n }\n }\n\n return false;\n }\n\n /**\n * Execute command helper with proper escaping\n * @param command - The command to execute\n * @param args - Arguments to pass to the command\n * @returns Promise that resolves when the command completes\n */\n protected async executeCommand(\n command: string,\n args: string[] = [],\n ): Promise<void> {\n try {\n await execFileAsync(command, args, {\n timeout: 5000,\n windowsHide: true,\n });\n } catch (error: unknown) {\n // Log but don't throw - browser may still launch\n if (this.isNodeError(error) && error.code !== \"ENOENT\") {\n console.debug(\n `Browser launch warning: ${BasePlatformBrowserControl.getErrorMessage(error)}`,\n );\n }\n }\n }\n\n /**\n * Helper to check if error is a Node.js error with code property\n * @param error - The error to check\n * @returns True if the error has a code property\n */\n private isNodeError(error: unknown): error is { code: string } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"string\"\n );\n }\n\n /**\n * Helper to get error message from unknown error\n * @param error - The error to get message from\n * @returns Error message as string\n */\n protected static getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n return String(error);\n }\n}\n\n/**\n * macOS implementation for browser control operations\n * Handles browser launching using AppleScript on macOS systems\n */\nexport class MacOSBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for macOS platform\n * @returns Record mapping browser names to their executable names on macOS\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"Firefox\"],\n Chrome: [\"Google Chrome\"],\n Safari: [\"Safari\"],\n };\n }\n\n /**\n * Launch a browser on macOS using AppleScript\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not supported on macOS\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const appNames: Partial<Record<BrowserName, string>> = {\n Firefox: \"Firefox\",\n Chrome: \"Google Chrome\",\n Safari: \"Safari\",\n };\n\n const appName = appNames[browserName];\n if (!appName) {\n throw new Error(`${browserName} not supported on macOS`);\n }\n\n // Use osascript with proper argument separation to avoid injection\n await this.executeCommand(\"osascript\", [\n \"-e\",\n `tell application \"${appName}\" to activate`,\n ]);\n }\n\n /**\n * Get the platform name for macOS\n * @returns The platform name \"macOS\"\n */\n public getPlatformName(): string {\n return \"macOS\";\n }\n}\n\n/**\n * Windows implementation for browser control operations\n * Handles browser launching using cmd.exe start command on Windows systems\n */\nexport class WindowsBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for Windows platform\n * @returns Record mapping browser names to their executable names on Windows\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"firefox.exe\", \"Firefox\"],\n Chrome: [\"chrome.exe\", \"Google Chrome\"],\n Safari: [], // Not available on Windows\n };\n }\n\n /**\n * Launch a browser on Windows using cmd.exe start command\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not available or fails to launch\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const executables = this.getBrowserExecutables(browserName);\n\n if (executables.length === 0) {\n throw new Error(`${browserName} not available on Windows`);\n }\n\n // Try each executable until one works\n for (const exe of executables) {\n if (await this.tryLaunchExecutable(exe)) {\n return; // Success, exit early\n }\n }\n\n throw new Error(`Failed to launch ${browserName} on Windows`);\n }\n\n /**\n * Try to launch a specific executable on Windows\n * @param exe - The executable name to launch\n * @returns Promise that resolves to true if launch was successful\n */\n private async tryLaunchExecutable(exe: string): Promise<boolean> {\n try {\n // Use cmd.exe with /c flag to run start command safely\n await execFileAsync(\"cmd.exe\", [\"/c\", \"start\", \"\", exe], {\n timeout: 5000,\n windowsHide: true,\n });\n return true;\n } catch {\n // Try next executable\n return false;\n }\n }\n\n /**\n * Get the platform name for Windows\n * @returns The platform name \"Windows\"\n */\n public getPlatformName(): string {\n return \"Windows\";\n }\n}\n\n/**\n * Linux implementation for browser control operations\n * Handles browser launching using direct executable calls or xdg-open on Linux systems\n */\nexport class LinuxBrowserControl extends BasePlatformBrowserControl {\n /**\n * Initialize browser executables for Linux platform\n * @returns Record mapping browser names to their executable names on Linux\n */\n protected initializeBrowserExecutables(): Partial<\n Record<BrowserName, string[]>\n > {\n return {\n Firefox: [\"firefox\", \"firefox-bin\"],\n Chrome: [\n \"google-chrome\",\n \"google-chrome-stable\",\n \"chromium\",\n \"chromium-browser\",\n ],\n Safari: [], // Not available on Linux\n };\n }\n\n /**\n * Launch a browser on Linux using direct executable calls or xdg-open fallback\n * @param browserName - The name of the browser to launch\n * @returns Promise that resolves when the browser is launched\n * @throws {Error} When the browser is not available or fails to launch\n */\n public async launchBrowser(browserName: BrowserName): Promise<void> {\n const executables = this.getBrowserExecutables(browserName);\n\n if (executables.length === 0) {\n throw new Error(`${browserName} not available on Linux`);\n }\n\n // Try each possible command\n if (await this.tryLaunchExecutables(executables)) {\n return; // Success\n }\n\n // Fallback to xdg-open if no browser executable worked\n await this.tryXdgOpenFallback(browserName);\n }\n\n /**\n * Try to launch browser executables\n * @param executables - Array of executable names to try\n * @returns Promise that resolves to true if any executable was successful\n */\n private async tryLaunchExecutables(executables: string[]): Promise<boolean> {\n for (const cmd of executables) {\n try {\n // Use direct execution without shell to avoid injection\n await execFileAsync(cmd, [], {\n timeout: 5000,\n });\n return true; // Success\n } catch {}\n }\n return false;\n }\n\n /**\n * Try xdg-open as fallback when direct executables fail\n * @param browserName - The name of the browser that failed to launch\n * @returns Promise that resolves when xdg-open succeeds\n * @throws {Error} When xdg-open also fails\n */\n private async tryXdgOpenFallback(browserName: BrowserName): Promise<void> {\n try {\n await execFileAsync(\"xdg-open\", [\"http://localhost\"], {\n timeout: 5000,\n });\n } catch (error: unknown) {\n throw new Error(\n `Failed to launch ${browserName} on Linux: ${BasePlatformBrowserControl.getErrorMessage(error)}`,\n );\n }\n }\n\n /**\n * Get the platform name for Linux\n * @returns The platform name \"Linux\"\n */\n public getPlatformName(): string {\n return \"Linux\";\n }\n}\n\n/**\n * Factory to create platform-specific browser control\n * Following SOLID - Single Responsibility and Open/Closed principles\n */\nlet platformControlInstance: PlatformBrowserControl | null = null;\n\n/**\n * Creates platform-specific browser control instance\n * @param platformOverride - Optional platform override for testing\n * @returns Platform-specific browser control instance\n * @throws {Error} When platform is not supported\n */\nexport function createPlatformBrowserControl(\n platformOverride?: Platform | NodeJS.Platform,\n): PlatformBrowserControl {\n // Use singleton for efficiency when not overriding\n if (platformControlInstance !== null && platformOverride === undefined) {\n return platformControlInstance;\n }\n\n const currentPlatform = platformOverride ?? getPlatform();\n const control = createControlForPlatform(currentPlatform);\n\n if (platformOverride === undefined) {\n platformControlInstance = control;\n }\n\n return control;\n}\n\n/**\n * Creates the appropriate control instance for the given platform\n * @param platform - The platform to create control for\n * @returns Platform-specific browser control instance\n * @throws {Error} When platform is not supported\n */\nfunction createControlForPlatform(platform: string): PlatformBrowserControl {\n switch (platform) {\n case \"darwin\":\n return new MacOSBrowserControl();\n case \"win32\":\n return new WindowsBrowserControl();\n case \"linux\":\n case \"freebsd\":\n case \"openbsd\":\n return new LinuxBrowserControl();\n default:\n // For any other platform string, try Linux as fallback\n return new LinuxBrowserControl();\n }\n}\n\n/**\n * Clear the singleton instance (useful for testing)\n */\nexport function clearPlatformControlInstance(): void {\n platformControlInstance = null;\n}\n","import {\n type BrowserName,\n closeBrowserGracefully,\n waitForBrowserToClose,\n} from \"@utils/BrowserControl\";\nimport { getDatabaseErrorType, getErrorMessage } from \"@utils/errorUtils\";\nimport { detectFileHandles, getFileLockInfo } from \"@utils/FileHandleDetector\";\nimport type { createTaggedLogger } from \"@utils/logHelpers\";\nimport { getBrowserConflictAdvice } from \"@utils/ProcessDetector\";\n\nimport {\n createPlatformBrowserControl,\n type PlatformBrowserControl,\n} from \"./platform/PlatformBrowserControl\";\n\n/**\n * Result of a browser conflict handling operation\n */\nexport interface BrowserLockResult {\n /** Whether the conflict was resolved */\n resolved: boolean;\n /** Whether the browser should be relaunched */\n shouldRelaunch: boolean;\n}\n\n/**\n * Shared handler for browser lock/permission issues\n * Follows DRY principle to avoid duplicating logic across browser strategies\n * Uses Strategy pattern for platform-specific operations\n */\nexport class BrowserLockHandler {\n private readonly platformControl: PlatformBrowserControl;\n\n /**\n * Creates a new BrowserLockHandler instance\n * @param logger - Tagged logger instance for this handler\n * @param browserName - Name of the browser this handler manages\n * @param platformControl - Optional platform control strategy (for testing)\n */\n public constructor(\n private readonly logger: ReturnType<typeof createTaggedLogger>,\n private readonly browserName: BrowserName,\n platformControl?: PlatformBrowserControl,\n ) {\n // Use provided control or create platform-specific one\n this.platformControl = platformControl ?? createPlatformBrowserControl();\n }\n\n /**\n * Handle database lock or permission errors\n * @param error - The error to check\n * @param file - The file that was locked/inaccessible\n * @param processes - Running processes for this browser\n * @param autoClose - Whether to attempt auto-closing the browser\n * @returns Promise that resolves to lock result\n */\n public async handleBrowserConflict(\n error: unknown,\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose = false,\n ): Promise<BrowserLockResult> {\n if (!(error instanceof Error)) {\n return { resolved: false, shouldRelaunch: false };\n }\n\n if (!this.isLockError(error)) {\n return { resolved: false, shouldRelaunch: false };\n }\n\n await this.logFileHandleInfo(file, processes);\n return this.handleProcessConflict(file, processes, autoClose);\n }\n\n /**\n * Check if an error indicates a database lock or permission issue\n * @param error - The error to check\n * @returns True if this is a lock-related error\n */\n private isLockError(error: Error): boolean {\n const dbErrorType = getDatabaseErrorType(error);\n return dbErrorType === \"locked\" || dbErrorType === \"permission\";\n }\n\n /**\n * Log detailed file handle information\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n */\n private async logFileHandleInfo(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n ): Promise<void> {\n try {\n const fileHandles = await detectFileHandles(file);\n\n if (fileHandles.length > 0) {\n const lockInfo = await getFileLockInfo(file);\n\n this.logger.debug(\"Database locked by specific processes\", {\n file,\n lockInfo,\n handleCount: fileHandles.length,\n handles: fileHandles.map((h) => ({\n pid: h.pid,\n command: h.command,\n mode: h.mode,\n user: h.user,\n })),\n });\n\n if (processes.length === 0) {\n this.logger.info(\n \"File is locked but no browser processes detected - another tool may be accessing the database\",\n {\n lockingProcesses: fileHandles\n .map((h) => `${h.command} (PID: ${h.pid})`)\n .join(\", \"),\n },\n );\n }\n }\n } catch (handleError) {\n this.logger.debug(\"Could not detect file handles\", {\n error:\n handleError instanceof Error\n ? handleError.message\n : String(handleError),\n });\n }\n }\n\n /**\n * Handle process conflicts and optionally close the browser\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n * @param autoClose - Whether to attempt auto-closing\n * @returns Promise that resolves to lock result\n */\n private async handleProcessConflict(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose: boolean,\n ): Promise<BrowserLockResult> {\n try {\n if (processes.length > 0) {\n return await this.handleBrowserProcesses(file, processes, autoClose);\n }\n\n this.logger.debug(\n \"Database/file locked but no browser processes detected\",\n {\n file,\n browserName: this.browserName,\n suggestion: \"Another process may be accessing the file\",\n },\n );\n } catch (processError) {\n this.logger.debug(\"Failed to check browser processes\", {\n error:\n processError instanceof Error\n ? processError.message\n : String(processError),\n });\n }\n\n return { resolved: false, shouldRelaunch: false };\n }\n\n /**\n * Handle detected browser processes\n * @param file - The file that was locked\n * @param processes - Browser processes detected\n * @param autoClose - Whether to attempt auto-closing\n * @returns Promise that resolves to lock result\n */\n private async handleBrowserProcesses(\n file: string,\n processes: Array<{ pid: number; command: string }>,\n autoClose: boolean,\n ): Promise<BrowserLockResult> {\n const processesWithDetails = processes.map((p) => ({\n ...p,\n details: `PID: ${p.pid}, Command: ${p.command}`,\n }));\n\n const advice = getBrowserConflictAdvice(\n this.browserName.toLowerCase(),\n processesWithDetails,\n );\n\n this.logger.debug(`${this.browserName} process conflict detected`, {\n file,\n processCount: processes.length,\n advice,\n });\n\n if (autoClose) {\n return this.attemptBrowserClose();\n }\n\n return Promise.resolve({ resolved: false, shouldRelaunch: false });\n }\n\n /**\n * Attempt to close the browser gracefully\n * @returns Promise that resolves to lock result\n */\n private async attemptBrowserClose(): Promise<BrowserLockResult> {\n this.logger.info(`Attempting to close ${this.browserName} gracefully...`);\n\n const closed = await closeBrowserGracefully(this.browserName, {\n interactive: true,\n force: false,\n });\n\n if (closed) {\n await waitForBrowserToClose(this.browserName, 5000);\n return { resolved: true, shouldRelaunch: true };\n }\n\n return { resolved: false, shouldRelaunch: false };\n }\n\n /**\n * Relaunch browser after successful operation\n * @returns Promise that resolves when browser is relaunched\n */\n public async relaunchBrowser(): Promise<void> {\n this.logger.info(`Relaunching ${this.browserName}...`);\n\n try {\n // Check if browser is supported on this platform\n if (!this.platformControl.isBrowserSupported(this.browserName)) {\n this.logger.debug(\n `${this.browserName} is not available on ${this.platformControl.getPlatformName()}`,\n );\n return;\n }\n\n // Use platform-specific strategy to launch browser\n await this.platformControl.launchBrowser(this.browserName);\n\n this.logger.success(\n `${this.browserName} has been relaunched with your tabs restored`,\n );\n } catch (relaunchError) {\n this.logger.debug(\n `Could not relaunch ${this.browserName} automatically`,\n {\n error: getErrorMessage(relaunchError),\n platform: this.platformControl.getPlatformName(),\n },\n );\n }\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"node:crypto\";\n\nimport { isMacOS, isWindows } from \"@utils/platformUtils\";\n\n/**\n * Simple memoization utility for caching Buffer operations\n * @param fn - The function to memoize that takes a Buffer and returns a Buffer\n * @param keyFn - Optional function to generate cache keys from Buffer values\n * @returns A memoized version of the input function\n */\nfunction memoizeBuffer(\n fn: (value: Buffer) => Buffer,\n keyFn?: (value: Buffer) => string,\n): (value: Buffer) => Buffer {\n const cache = new Map<string, Buffer>();\n\n return (value: Buffer): Buffer => {\n const key = keyFn ? keyFn(value) : value.toString(\"hex\");\n\n if (cache.has(key)) {\n const cachedResult = cache.get(key);\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n }\n\n const result = fn(value);\n cache.set(key, result);\n return result;\n };\n}\n\nimport { decryptV10Cookie, isV10Cookie } from \"./windows/decryptV10Cookie\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoizeBuffer(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoizeBuffer(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n // First try to find a UUID pattern which is common in cookies\n const uuidMatch = decodedString.match(\n /([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i,\n );\n if (uuidMatch?.[1]) {\n return uuidMatch[1];\n }\n\n // Look for common patterns at the end of the string\n const endPatterns = [\n /([A-Z]{3})$/, // Currency codes (USD, GBP, EUR)\n /([a-z]{2}_[A-Z]{2})$/, // Locale codes (en_US, en_GB)\n /(\\d{3}-\\d{7}-\\d{7})$/, // Amazon session IDs\n ];\n\n for (const pattern of endPatterns) {\n const match = decodedString.match(pattern);\n if (match?.[1]) {\n return match[1];\n }\n }\n\n // Then try other cleanup patterns\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E]+)$/, // Non-printable chars followed by printable chars\n /.*?([a-zA-Z0-9_\\-.]+)$/, // Alphanumeric value at the end\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @param metaVersion - Optional meta version for determining decryption behavior\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string | Buffer,\n metaVersion?: number,\n): Promise<string> {\n // v10 cookies use AES-GCM on Windows only\n // On macOS, cookies starting with v10 are actually v11 encrypted with a value that starts with \"v10,\"\n // Only treat as v10 cookie if we're on Windows AND it has sufficient length AND password is a Buffer (real scenario)\n if (\n isWindows() &&\n isV10Cookie(encryptedValue) &&\n encryptedValue.length >= 31 &&\n Buffer.isBuffer(password)\n ) {\n return decryptV10Cookie(encryptedValue, password);\n }\n\n // On macOS, cookies that don't start with v10 are considered 'old data' stored as plaintext\n // Ref: https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm\n if (isMacOS()) {\n // Check if this looks like encrypted data (starts with common version prefixes)\n const hasVersionPrefix = encryptedValue\n .slice(0, 3)\n .toString()\n .match(/^v\\d\\d$/);\n if (!hasVersionPrefix) {\n // Not a version prefix - treat as plaintext on macOS\n return Promise.resolve(encryptedValue.toString(\"utf8\"));\n }\n }\n\n // v11 cookies and other encrypted cookies use AES-CBC with PBKDF2\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(`Failed to derive key: ${error.message}`));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted: Buffer = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(`Failed to finalize decryption: ${(e as Error).message}`),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n\n // Skip the first 32 bytes (hash prefix) if meta version >= 24\n // Ref: https://chromium.googlesource.com/chromium/src/+/b02dcebd7cafab92770734dc2bc317bd07f1d891/net/extras/sqlite/sqlite_persistent_cookie_store.cc#223\n const useHashPrefix = (metaVersion ?? 0) >= 24;\n const finalDecrypted =\n useHashPrefix && decrypted.length > 32\n ? decrypted.slice(32)\n : decrypted;\n\n const decodedString = finalDecrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(`Decryption failed: ${(e as Error).message}`));\n }\n });\n });\n}\n","import { createDecipheriv } from \"node:crypto\";\n\n/**\n * Decrypts Chrome v10 encrypted cookies on Windows using AES-256-GCM\n *\n * Chrome v10 cookies use AES-256-GCM encryption with:\n * - 12-byte nonce (96 bits)\n * - 16-byte authentication tag\n * @param encryptedValue - The encrypted cookie value starting with 'v10' prefix\n * @param key - The decrypted master key from DPAPI\n * @returns The decrypted cookie value\n * @throws {Error} If the cookie is not v10 format or decryption fails\n */\nexport function decryptV10Cookie(encryptedValue: Buffer, key: Buffer): string {\n // Check for v10 prefix\n const VERSION_PREFIX = Buffer.from(\"v10\");\n if (!encryptedValue.subarray(0, 3).equals(VERSION_PREFIX)) {\n throw new Error(\"Not a v10 encrypted cookie\");\n }\n\n // Remove the version prefix\n const ciphertext = encryptedValue.subarray(3);\n\n // Extract components\n const NONCE_LENGTH = 12; // 96 bits / 8\n const TAG_LENGTH = 16; // 128 bits / 8\n\n if (ciphertext.length < NONCE_LENGTH + TAG_LENGTH) {\n throw new Error(\"Invalid v10 cookie: too short\");\n }\n\n const nonce = ciphertext.subarray(0, NONCE_LENGTH);\n const encryptedData = ciphertext.subarray(\n NONCE_LENGTH,\n ciphertext.length - TAG_LENGTH,\n );\n const authTag = ciphertext.subarray(ciphertext.length - TAG_LENGTH);\n\n // Decrypt using AES-256-GCM\n const decipher = createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAuthTag(authTag);\n\n const decrypted = Buffer.concat([\n decipher.update(encryptedData),\n decipher.final(),\n ]);\n\n return decrypted.toString(\"utf8\");\n}\n\n/**\n * Checks if a cookie value is v10 encrypted\n * @param value - The cookie value to check\n * @returns True if the cookie starts with 'v10' prefix\n */\nexport function isV10Cookie(value: Buffer): boolean {\n const VERSION_PREFIX = Buffer.from(\"v10\");\n return value.length >= 3 && value.subarray(0, 3).equals(VERSION_PREFIX);\n}\n","import { assertPlatformSupported, getPlatform } from \"@utils/platformUtils\";\n\nimport { execSimple } from \"../../../utils/execSimple\";\n\nimport type { ChromiumBrowser } from \"./ChromiumBrowsers\";\n\n/**\n * Maps browser types to their keychain service names on macOS\n */\nconst MACOS_KEYCHAIN_SERVICES: Record<ChromiumBrowser, string> = {\n chrome: \"Chrome Safe Storage\",\n chromium: \"Chromium Safe Storage\",\n brave: \"Brave Safe Storage\",\n edge: \"Microsoft Edge Safe Storage\",\n arc: \"Arc Safe Storage\",\n opera: \"Opera Safe Storage\",\n \"opera-gx\": \"Opera Safe Storage\", // Opera GX shares Opera's keychain\n vivaldi: \"Vivaldi Safe Storage\",\n whale: \"Whale Safe Storage\",\n};\n\n/**\n * Gets the Chromium browser Safe Storage password for macOS\n * @param browser - The browser type to get the password for\n * @returns A promise that resolves to the browser's Safe Storage password\n */\nasync function getMacOSPassword(browser: ChromiumBrowser): Promise<string> {\n const service = MACOS_KEYCHAIN_SERVICES[browser];\n if (!service) {\n throw new Error(`Unknown browser type: ${browser}`);\n }\n\n try {\n const command = `security find-generic-password -w -s \"${service}\"`;\n const result = await execSimple(command);\n return result.stdout.trim();\n } catch (error) {\n // Fallback to Chrome if browser-specific key not found\n // This is useful for browsers that share Chrome's encryption\n if (browser !== \"chrome\") {\n const chromeCommand = `security find-generic-password -w -s \"Chrome Safe Storage\"`;\n try {\n const result = await execSimple(chromeCommand);\n return result.stdout.trim();\n } catch {\n // If Chrome fallback also fails, throw original error\n }\n }\n throw new Error(\n `Failed to get ${browser} password from keychain: ${error}`,\n );\n }\n}\n\n/**\n * Gets the Chromium browser password for Windows\n * Windows uses DPAPI which is browser-agnostic\n */\nasync function getWindowsPassword(): Promise<string | Buffer> {\n // Import dynamically to avoid loading on non-Windows platforms\n const { getChromePassword } = await import(\"./windows/getChromePassword\");\n return getChromePassword();\n}\n\n/**\n * Gets the Chromium browser password for Linux\n * Linux typically uses a hardcoded key or libsecret\n */\nasync function getLinuxPassword(): Promise<string> {\n // Import dynamically to avoid loading on non-Linux platforms\n const { getChromePassword } = await import(\"./linux/getChromePassword\");\n return getChromePassword();\n}\n\n/**\n * Gets the Chromium-based browser Safe Storage password for the current platform.\n * This password is used to decrypt cookies stored in the browser's cookie database.\n * Supports macOS (keychain), Windows (DPAPI), and Linux (keyring/libsecret).\n * @param browser - The Chromium-based browser to get the password for\n * @returns A promise that resolves to the browser's Safe Storage password or Buffer\n * @throws {Error} If the password cannot be retrieved or the platform is not supported\n */\nexport async function getChromiumPassword(\n browser: ChromiumBrowser = \"chrome\",\n): Promise<string | Buffer> {\n assertPlatformSupported();\n\n switch (getPlatform()) {\n case \"darwin\": {\n return getMacOSPassword(browser);\n }\n case \"win32\": {\n // Windows uses DPAPI which works for all Chromium browsers\n return getWindowsPassword();\n }\n case \"linux\": {\n // Linux uses a hardcoded key for all Chromium browsers\n return getLinuxPassword();\n }\n default:\n throw new Error(`Platform ${getPlatform()} is not supported`);\n }\n}\n","/**\n * Database connection manager with pooling and performance monitoring\n * Manages SQLite connections efficiently with automatic cleanup and monitoring\n */\n\nimport { EventEmitter } from \"node:events\";\n\nimport BetterSqlite3, { type Database } from \"better-sqlite3\";\n\nimport { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"DatabaseConnectionManager\");\n\n/**\n * Connection pool configuration\n */\nexport interface PoolConfig {\n /** Maximum number of connections in the pool */\n maxConnections?: number;\n /** Connection timeout in milliseconds */\n connectionTimeout?: number;\n /** Idle timeout before closing connection */\n idleTimeout?: number;\n /** Enable performance monitoring */\n enableMonitoring?: boolean;\n /** Retry attempts for locked databases */\n retryAttempts?: number;\n /** Retry delay in milliseconds */\n retryDelay?: number;\n /** Query execution timeout in milliseconds */\n queryTimeout?: number;\n}\n\n/**\n * Database connection metadata\n */\ninterface ConnectionMetadata {\n database: Database;\n filepath: string;\n inUse: boolean;\n lastAccessed: number;\n queryCount: number;\n totalQueryTime: number;\n created: number;\n}\n\n/**\n * Query performance metrics\n */\nexport interface QueryMetrics {\n query: string;\n duration: number;\n rowCount: number;\n filepath: string;\n timestamp: number;\n success: boolean;\n error?: string;\n}\n\n/**\n * Connection pool statistics\n */\nexport interface PoolStatistics {\n totalConnections: number;\n activeConnections: number;\n idleConnections: number;\n totalQueries: number;\n averageQueryTime: number;\n cacheHitRate: number;\n connectionReuse: number;\n}\n\n/**\n * Database connection manager with pooling\n */\nexport class DatabaseConnectionManager extends EventEmitter {\n private readonly connections: Map<string, ConnectionMetadata>;\n private readonly config: Required<PoolConfig>;\n private readonly queryMetrics: QueryMetrics[];\n private lastCleanupTime: number;\n private totalQueries: number;\n private cacheHits: number;\n private connectionReuses: number;\n\n /**\n *\n * @param config\n */\n constructor(config: PoolConfig = {}) {\n super();\n\n this.connections = new Map();\n this.queryMetrics = [];\n this.totalQueries = 0;\n this.cacheHits = 0;\n this.connectionReuses = 0;\n this.lastCleanupTime = Date.now();\n\n this.config = {\n maxConnections: config.maxConnections ?? 5,\n connectionTimeout: config.connectionTimeout ?? 5000,\n idleTimeout: config.idleTimeout ?? 30000,\n enableMonitoring: config.enableMonitoring ?? true,\n retryAttempts: config.retryAttempts ?? 3,\n retryDelay: config.retryDelay ?? 100,\n queryTimeout: config.queryTimeout ?? 3000, // 3 seconds default\n };\n }\n\n /**\n * Get or create a database connection\n * @param filepath\n */\n async getConnection(filepath: string): Promise<Database> {\n // Perform cleanup if needed (every 30 seconds)\n const now = Date.now();\n if (now - this.lastCleanupTime > 30000) {\n this.cleanupIdleConnections();\n this.lastCleanupTime = now;\n }\n\n // Check existing connection\n const existing = this.connections.get(filepath);\n if (existing && !existing.inUse) {\n existing.inUse = true;\n existing.lastAccessed = Date.now();\n this.connectionReuses++;\n\n logger.debug(\"Reusing existing connection\", {\n filepath,\n queryCount: existing.queryCount,\n });\n\n return existing.database;\n }\n\n // Check pool limit\n if (this.connections.size >= this.config.maxConnections) {\n await this.evictLeastRecentlyUsed();\n }\n\n // Create new connection\n return this.createConnection(filepath);\n }\n\n /**\n * Create a new database connection\n * @param filepath\n */\n private async createConnection(filepath: string): Promise<Database> {\n const startTime = Date.now();\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.config.retryAttempts; attempt++) {\n try {\n const database = new BetterSqlite3(filepath, {\n readonly: true,\n fileMustExist: true,\n });\n\n // Set busy timeout for all queries on this connection\n // This timeout only applies to actual query execution, not connection retries\n database.pragma(`busy_timeout = ${this.config.queryTimeout}`);\n\n const metadata: ConnectionMetadata = {\n database,\n filepath,\n inUse: true,\n lastAccessed: Date.now(),\n queryCount: 0,\n totalQueryTime: 0,\n created: Date.now(),\n };\n\n this.connections.set(filepath, metadata);\n\n const connectionTime = Date.now() - startTime;\n logger.debug(\"Created new connection\", {\n filepath,\n connectionTime,\n attempt: attempt + 1,\n });\n\n this.emit(\"connection:created\", { filepath, connectionTime });\n\n return database;\n } catch (error) {\n lastError = error as Error;\n\n if (this.isDatabaseLocked(error)) {\n logger.warn(\"Database locked, retrying\", {\n filepath,\n attempt: attempt + 1,\n maxAttempts: this.config.retryAttempts,\n });\n\n await this.delay(this.config.retryDelay * 2 ** attempt);\n continue;\n }\n\n throw error;\n }\n }\n\n throw lastError || new Error(`Failed to connect to database: ${filepath}`);\n }\n\n /**\n * Execute a query with the connection manager\n * The connection already has busy_timeout set, so queries will timeout appropriately\n * @param filepath\n * @param queryFn\n * @param queryDescription\n */\n async executeQuery<T>(\n filepath: string,\n queryFn: (db: Database) => T,\n queryDescription?: string,\n ): Promise<T> {\n const startTime = Date.now();\n const connection = await this.getConnection(filepath);\n const metadata = this.connections.get(filepath);\n\n try {\n const result = queryFn(connection);\n const duration = Date.now() - startTime;\n\n if (metadata) {\n metadata.queryCount++;\n metadata.totalQueryTime += duration;\n }\n\n this.totalQueries++;\n this.cacheHits++; // Increment cache hits for successful queries\n\n // Log slow queries at debug level\n if (duration > 100) {\n logger.debug(\"Slow query detected\", {\n query: queryDescription || \"Unknown query\",\n duration,\n filepath,\n });\n }\n\n // Record metrics\n if (this.config.enableMonitoring) {\n const metrics: QueryMetrics = {\n query: queryDescription || \"Unknown query\",\n duration,\n rowCount: Array.isArray(result) ? result.length : 1,\n filepath,\n timestamp: Date.now(),\n success: true,\n };\n\n this.recordMetrics(metrics);\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Increment query count even for failed queries\n this.totalQueries++;\n\n // Record error metrics\n if (this.config.enableMonitoring) {\n const metrics: QueryMetrics = {\n query: queryDescription || \"Unknown query\",\n duration,\n rowCount: 0,\n filepath,\n timestamp: Date.now(),\n success: false,\n error: (error as Error).message,\n };\n\n this.recordMetrics(metrics);\n }\n\n throw error;\n } finally {\n // Release connection\n if (metadata) {\n metadata.inUse = false;\n metadata.lastAccessed = Date.now();\n }\n }\n }\n\n /**\n * Release a connection back to the pool\n * @param filepath\n */\n releaseConnection(filepath: string): void {\n const metadata = this.connections.get(filepath);\n if (metadata) {\n metadata.inUse = false;\n metadata.lastAccessed = Date.now();\n logger.debug(\"Released connection\", { filepath });\n }\n }\n\n /**\n * Close a specific connection\n * @param filepath\n */\n closeConnection(filepath: string): void {\n const metadata = this.connections.get(filepath);\n if (metadata) {\n try {\n metadata.database.close();\n this.connections.delete(filepath);\n\n logger.debug(\"Closed connection\", {\n filepath,\n queryCount: metadata.queryCount,\n lifetime: Date.now() - metadata.created,\n });\n\n this.emit(\"connection:closed\", { filepath });\n } catch (error) {\n logError(\"Failed to close connection\", error, { filepath });\n }\n }\n }\n\n /**\n * Close all connections\n */\n closeAll(): void {\n for (const [filepath, metadata] of this.connections) {\n try {\n metadata.database.close();\n logger.debug(\"Closed connection\", { filepath });\n } catch (error) {\n logError(\"Failed to close connection\", error, { filepath });\n }\n }\n\n this.connections.clear();\n\n logger.info(\"Closed all connections\", {\n totalQueries: this.totalQueries,\n connectionReuses: this.connectionReuses,\n });\n }\n\n /**\n * Get pool statistics\n */\n getStatistics(): PoolStatistics {\n let totalQueryTime = 0;\n let totalQueryCount = 0;\n let activeConnections = 0;\n\n for (const metadata of this.connections.values()) {\n totalQueryTime += metadata.totalQueryTime;\n totalQueryCount += metadata.queryCount;\n if (metadata.inUse) {\n activeConnections++;\n }\n }\n\n return {\n totalConnections: this.connections.size,\n activeConnections,\n idleConnections: this.connections.size - activeConnections,\n totalQueries: this.totalQueries,\n averageQueryTime:\n totalQueryCount > 0 ? totalQueryTime / totalQueryCount : 0,\n cacheHitRate:\n this.totalQueries > 0 ? this.cacheHits / this.totalQueries : 0,\n connectionReuse: this.connectionReuses,\n };\n }\n\n /**\n * Get recent query metrics\n * @param limit\n */\n getQueryMetrics(limit = 100): QueryMetrics[] {\n return this.queryMetrics.slice(-limit);\n }\n\n /**\n * Clear query metrics\n */\n clearMetrics(): void {\n this.queryMetrics.length = 0;\n }\n\n /**\n * Clean up idle connections\n */\n private cleanupIdleConnections(): void {\n const now = Date.now();\n const toClose: string[] = [];\n\n for (const [filepath, metadata] of this.connections) {\n if (\n !metadata.inUse &&\n now - metadata.lastAccessed > this.config.idleTimeout\n ) {\n toClose.push(filepath);\n }\n }\n\n for (const filepath of toClose) {\n this.closeConnection(filepath);\n }\n\n if (toClose.length > 0) {\n logger.debug(\"Cleaned up idle connections\", { count: toClose.length });\n }\n }\n\n /**\n * Evict least recently used connection\n */\n private async evictLeastRecentlyUsed(): Promise<void> {\n let lruPath: string | null = null;\n let lruTime = Date.now();\n\n for (const [filepath, metadata] of this.connections) {\n if (!metadata.inUse && metadata.lastAccessed < lruTime) {\n lruPath = filepath;\n lruTime = metadata.lastAccessed;\n }\n }\n\n if (lruPath) {\n this.closeConnection(lruPath);\n logger.debug(\"Evicted LRU connection\", { filepath: lruPath });\n } else {\n // All connections are in use, wait a bit\n await this.delay(100);\n }\n }\n\n /**\n * Record query metrics\n * @param metrics\n */\n private recordMetrics(metrics: QueryMetrics): void {\n this.queryMetrics.push(metrics);\n\n // Keep only recent metrics (last 1000)\n if (this.queryMetrics.length > 1000) {\n this.queryMetrics.splice(0, this.queryMetrics.length - 1000);\n }\n\n this.emit(\"query:executed\", metrics);\n }\n\n /**\n * Check if error indicates database lock\n * @param error\n */\n private isDatabaseLocked(error: unknown): boolean {\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n return (\n message.includes(\"database is locked\") ||\n message.includes(\"database locked\") ||\n message.includes(\"sqlite_busy\")\n );\n }\n return false;\n }\n\n /**\n * Delay helper\n * @param ms\n */\n private async delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Global connection manager instance\n */\nlet globalManager: DatabaseConnectionManager | null = null;\n\n/**\n * Process exit handler function\n */\nlet exitHandler: (() => void) | null = null;\n\n/**\n * Get or create global connection manager\n * @param config\n */\nexport function getGlobalConnectionManager(\n config?: PoolConfig,\n): DatabaseConnectionManager {\n if (!globalManager) {\n globalManager = new DatabaseConnectionManager(config);\n\n // Ensure cleanup on process exit (only add once)\n if (!exitHandler) {\n exitHandler = () => {\n if (globalManager) {\n globalManager.closeAll();\n }\n };\n process.on(\"exit\", exitHandler);\n }\n }\n\n return globalManager;\n}\n\n/**\n * Reset global connection manager (mainly for testing)\n */\nexport function resetGlobalConnectionManager(): void {\n if (globalManager) {\n globalManager.closeAll();\n globalManager = null;\n }\n\n // Remove the exit handler to prevent memory leaks in tests\n if (exitHandler) {\n process.removeListener(\"exit\", exitHandler);\n exitHandler = null;\n }\n}\n","/**\n * Query monitoring wrapper for SQL operations\n * Provides clean, type-safe monitoring without monkey-patching\n */\n\nimport type { Database, Statement } from \"better-sqlite3\";\n\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"QueryMonitor\");\n\n/**\n * Query execution metrics\n */\nexport interface QueryExecution {\n sql: string;\n params: unknown[];\n startTime: number;\n endTime?: number;\n duration?: number;\n rowCount?: number;\n error?: Error;\n filepath?: string;\n}\n\n/**\n * Query monitoring options\n */\nexport interface MonitoringOptions {\n /** Log slow queries (in ms) */\n slowQueryThreshold?: number;\n /** Enable detailed logging */\n verbose?: boolean;\n /** Track query history */\n trackHistory?: boolean;\n /** Maximum history size */\n maxHistorySize?: number;\n}\n\n/**\n * Query monitor for tracking SQL performance\n */\nexport class QueryMonitor {\n private readonly options: Required<MonitoringOptions>;\n private readonly queryHistory: QueryExecution[];\n private totalQueries: number;\n private totalDuration: number;\n private slowQueries: number;\n private errors: number;\n\n /**\n * Creates a new QueryMonitor instance for tracking SQL query performance and metrics.\n * @param options - Configuration options for monitoring behavior\n * @param options.slowQueryThreshold - Milliseconds before a query is considered slow (default: 100ms)\n * @param options.verbose - Whether to log detailed query information (default: false)\n * @param options.trackHistory - Whether to maintain query history (default: true)\n * @param options.maxHistorySize - Maximum number of queries to keep in history (default: 1000)\n */\n constructor(options: MonitoringOptions = {}) {\n this.options = {\n slowQueryThreshold: options.slowQueryThreshold ?? 100,\n verbose: options.verbose ?? false,\n trackHistory: options.trackHistory ?? true,\n maxHistorySize: options.maxHistorySize ?? 1000,\n };\n\n this.queryHistory = [];\n this.totalQueries = 0;\n this.totalDuration = 0;\n this.slowQueries = 0;\n this.errors = 0;\n }\n\n /**\n * Execute a query with monitoring\n * @param db\n * @param sql\n * @param params\n * @param filepath\n */\n executeQuery<T>(\n db: Database,\n sql: string,\n params: unknown[] = [],\n filepath?: string,\n ): T[] {\n const execution: QueryExecution = {\n sql,\n params,\n startTime: Date.now(),\n };\n if (filepath !== undefined) {\n execution.filepath = filepath;\n }\n\n try {\n // Execute the query (timeout is already set on the connection)\n const stmt = db.prepare(sql);\n const result = stmt.all(...params) as T[];\n\n // Record success metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.rowCount = result.length;\n\n this.recordExecution(execution);\n\n return result;\n } catch (error) {\n // Record error metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.error = error as Error;\n\n this.recordExecution(execution);\n\n throw error;\n }\n }\n\n /**\n * Execute a single row query with monitoring\n * @param db\n * @param sql\n * @param params\n * @param filepath\n */\n executeGet<T>(\n db: Database,\n sql: string,\n params: unknown[] = [],\n filepath?: string,\n ): T | undefined {\n const execution: QueryExecution = {\n sql,\n params,\n startTime: Date.now(),\n };\n if (filepath !== undefined) {\n execution.filepath = filepath;\n }\n\n try {\n // Execute the query (timeout is already set on the connection)\n const stmt = db.prepare(sql);\n const result = stmt.get(...params) as T | undefined;\n\n // Record success metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.rowCount = result ? 1 : 0;\n\n this.recordExecution(execution);\n\n return result;\n } catch (error) {\n // Record error metrics\n execution.endTime = Date.now();\n execution.duration = execution.endTime - execution.startTime;\n execution.error = error as Error;\n\n this.recordExecution(execution);\n\n throw error;\n }\n }\n\n /**\n * Create a monitored statement wrapper\n * @param db\n * @param sql\n * @param filepath\n */\n prepareStatement<T>(\n db: Database,\n sql: string,\n filepath?: string,\n ): MonitoredStatement<T> {\n const stmt = db.prepare(sql);\n return new MonitoredStatement(stmt, sql, this, filepath);\n }\n\n /**\n * Record query execution\n * @param execution\n */\n private recordExecution(execution: QueryExecution): void {\n // Update statistics\n this.totalQueries++;\n\n if (execution.duration !== undefined) {\n this.totalDuration += execution.duration;\n\n // Check for slow query\n if (execution.duration > this.options.slowQueryThreshold) {\n this.slowQueries++;\n\n logger.debug(\"Slow query detected\", {\n sql: execution.sql,\n duration: execution.duration,\n rowCount: execution.rowCount,\n filepath: execution.filepath,\n });\n }\n }\n\n if (execution.error) {\n this.errors++;\n\n if (this.options.verbose) {\n logger.error(\"Query failed\", {\n sql: execution.sql,\n error: execution.error.message,\n filepath: execution.filepath,\n });\n }\n } else if (this.options.verbose) {\n logger.debug(\"Query executed\", {\n sql: execution.sql,\n duration: execution.duration,\n rowCount: execution.rowCount,\n });\n }\n\n // Track history\n if (this.options.trackHistory) {\n this.queryHistory.push(execution);\n\n // Trim history if needed\n if (this.queryHistory.length > this.options.maxHistorySize) {\n this.queryHistory.splice(\n 0,\n this.queryHistory.length - this.options.maxHistorySize,\n );\n }\n }\n }\n\n /**\n * Get monitoring statistics\n */\n getStatistics() {\n return {\n totalQueries: this.totalQueries,\n averageDuration:\n this.totalQueries > 0 ? this.totalDuration / this.totalQueries : 0,\n slowQueries: this.slowQueries,\n slowQueryRate:\n this.totalQueries > 0 ? this.slowQueries / this.totalQueries : 0,\n errors: this.errors,\n errorRate: this.totalQueries > 0 ? this.errors / this.totalQueries : 0,\n historySize: this.queryHistory.length,\n };\n }\n\n /**\n * Get query history\n * @param limit\n */\n getHistory(limit?: number): QueryExecution[] {\n if (limit) {\n return this.queryHistory.slice(-limit);\n }\n return [...this.queryHistory];\n }\n\n /**\n * Clear history\n */\n clearHistory(): void {\n this.queryHistory.length = 0;\n }\n\n /**\n * Reset all statistics\n */\n reset(): void {\n this.clearHistory();\n this.totalQueries = 0;\n this.totalDuration = 0;\n this.slowQueries = 0;\n this.errors = 0;\n }\n}\n\n/**\n * Monitored statement wrapper\n */\nexport class MonitoredStatement<T> {\n /**\n * Creates a monitored wrapper around a prepared SQL statement.\n * This wrapper automatically tracks execution metrics for all queries run through it.\n * @param statement - The prepared SQLite statement to monitor\n * @param sql - The SQL query string for logging and debugging\n * @param monitor - The QueryMonitor instance that will track metrics\n * @param filepath - Optional database file path for additional context in logs\n */\n constructor(\n private readonly statement: Statement,\n private readonly sql: string,\n private readonly monitor: QueryMonitor,\n private readonly filepath?: string,\n ) {}\n\n /**\n * Execute all with monitoring\n * @param {...any} params\n */\n all(...params: unknown[]): T[] {\n return this.monitor.executeQuery<T>(\n { prepare: () => this.statement } as unknown as Database,\n this.sql,\n params,\n this.filepath,\n );\n }\n\n /**\n * Execute get with monitoring\n * @param {...any} params\n */\n get(...params: unknown[]): T | undefined {\n return this.monitor.executeGet<T>(\n { prepare: () => this.statement } as unknown as Database,\n this.sql,\n params,\n this.filepath,\n );\n }\n\n /**\n * Get underlying statement\n */\n getStatement(): Statement {\n return this.statement;\n }\n}\n\n/**\n * Create a global query monitor instance\n */\nlet globalMonitor: QueryMonitor | null = null;\n\n/**\n * Get or create global query monitor\n * @param options\n */\nexport function getGlobalQueryMonitor(\n options?: MonitoringOptions,\n): QueryMonitor {\n if (!globalMonitor) {\n globalMonitor = new QueryMonitor(options);\n }\n return globalMonitor;\n}\n\n/**\n * Reset global query monitor\n */\nexport function resetGlobalQueryMonitor(): void {\n if (globalMonitor) {\n globalMonitor.reset();\n globalMonitor = null;\n }\n}\n","import fg from \"fast-glob\";\n\nimport {\n type ChromiumBrowser,\n getChromiumBrowserPath,\n} from \"../chrome/ChromiumBrowsers\";\n\nimport { BaseChromiumCookieQueryStrategy } from \"./BaseChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Chromium-based browsers (Chrome, Brave, Edge, etc.)\n * This class extends the BaseChromiumCookieQueryStrategy with browser-specific path discovery.\n * @example\n * ```typescript\n * const strategy = new ChromiumCookieQueryStrategy('brave');\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromiumCookieQueryStrategy extends BaseChromiumCookieQueryStrategy {\n private readonly browser: ChromiumBrowser;\n\n /**\n * Creates a new instance of ChromiumCookieQueryStrategy\n * @param browser - The Chromium-based browser to query (chrome, brave, edge, etc.)\n */\n public constructor(browser: ChromiumBrowser = \"chrome\") {\n const browserName = browser.charAt(0).toUpperCase() + browser.slice(1);\n super(`${browserName}CookieQueryStrategy`, browserName, browser);\n this.browser = browser;\n }\n\n /**\n * Get browser-specific cookie file paths\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected getCookieFilePaths(store?: string): string[] {\n if (store !== undefined && store !== \"\") {\n return [store];\n }\n\n try {\n const browserPath = getChromiumBrowserPath(this.browser);\n const files = fg.sync(\"./**/Cookies\", {\n cwd: browserPath,\n absolute: true,\n });\n\n this.logger.debug(\n `Found ${files.length} cookie files for ${this.browser}`,\n );\n\n return files;\n } catch (error) {\n this.logger.warn(`Failed to find ${this.browser} cookie files`, {\n error: this.getErrorMessage(error),\n });\n return [];\n }\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Arc browser.\n * Arc is a Chromium-based browser with unique features but standard cookie storage.\n * @example\n * ```typescript\n * const strategy = new ArcCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ArcCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of ArcCookieQueryStrategy\n */\n public constructor() {\n super(\"arc\");\n }\n}\n","import { dirname } from \"node:path\";\n\nimport { BaseChromiumCookieQueryStrategy } from \"../chromium/BaseChromiumCookieQueryStrategy\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\n/**\n * Interface representing Chrome profile information from Local State\n */\ninterface ChromeProfileInfo {\n name?: string;\n user_name?: string;\n [key: string]: unknown;\n}\n\n/**\n * Strategy for querying cookies from Chrome browser.\n * This class extends the BaseChromiumCookieQueryStrategy with Chrome-specific logic.\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy extends BaseChromiumCookieQueryStrategy {\n private readonly profileName?: string;\n\n /**\n * Creates a new instance of ChromeCookieQueryStrategy\n * @param profileName - Optional specific profile name to target\n */\n public constructor(profileName?: string) {\n super(\"ChromeCookieQueryStrategy\", \"Chrome\");\n if (profileName !== undefined) {\n this.profileName = profileName;\n }\n }\n\n /**\n * Get Chrome-specific cookie file paths\n * @param store - Optional specific store path\n * @returns Array of cookie file paths\n */\n protected getCookieFilePaths(store?: string): string[] {\n if (store !== undefined && store !== \"\") {\n return [store];\n }\n\n let paths = listChromeProfilePaths();\n\n // Filter by profile name if specified\n if (this.profileName) {\n // Read Chrome's Local State to map profile names to directories\n try {\n const fs = require(\"node:fs\");\n const path = require(\"node:path\");\n\n // Ensure we have at least one path to determine the Chrome data directory\n if (paths.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const firstPath = paths[0];\n if (!firstPath) {\n return [];\n }\n const chromeDataDir = dirname(dirname(firstPath)); // Get Chrome data directory\n const localStatePath = path.join(chromeDataDir, \"Local State\");\n\n if (fs.existsSync(localStatePath)) {\n const localState = JSON.parse(\n fs.readFileSync(localStatePath, \"utf8\"),\n );\n const profileCache = localState.profile?.info_cache || {};\n\n // Find the directory for the given profile name\n let targetDir: string | undefined;\n\n for (const [dir, info] of Object.entries(profileCache)) {\n const profile = info as ChromeProfileInfo;\n if (\n profile.name?.toLowerCase() === this.profileName.toLowerCase()\n ) {\n targetDir = dir;\n break;\n }\n }\n\n // Also check if user passed the directory name directly (e.g., \"Default\" or \"Profile 2\")\n if (!targetDir) {\n for (const dir of Object.keys(profileCache)) {\n if (dir.toLowerCase() === this.profileName.toLowerCase()) {\n targetDir = dir;\n break;\n }\n }\n }\n\n if (targetDir) {\n // Filter paths to only include the target directory\n paths = paths.filter((cookiePath) => {\n const dir = dirname(cookiePath);\n return dir.endsWith(targetDir);\n });\n\n if (paths.length === 0) {\n this.logger.warn(\n `No cookie files found for profile: ${this.profileName} (directory: ${targetDir})`,\n );\n } else {\n this.logger.debug(\n `Found ${paths.length} cookie file(s) for profile: ${this.profileName}`,\n );\n }\n } else {\n this.logger.debug(\"Profile not found in Chrome Local State\", {\n requestedProfile: this.profileName,\n availableProfiles: Object.entries(profileCache).map(\n ([dir, info]) => ({\n directory: dir,\n name: (info as ChromeProfileInfo).name,\n }),\n ),\n });\n\n // Return empty array to avoid querying wrong profile\n return [];\n }\n }\n } catch (error) {\n this.logger.warn(`Failed to read Chrome profile info: ${error}`);\n }\n }\n\n return Array.isArray(paths) ? paths : [paths];\n }\n}\n","/**\n * Asynchronously maps over an array and flattens the result.\n * Similar to Array.prototype.flatMap but for async operations.\n * @param array - The input array to map over\n * @param callback - The async mapping function to apply to each element\n * @param defaultValue - The default value to return if the array is empty\n * @returns A flattened array of results\n * @example\n * // Basic usage with number arrays\n * const numbers = [1, 2, 3];\n * const result = await flatMapAsync(\n * numbers,\n * async (num) => [num, num * 2]\n * );\n * console.log(result); // [1, 2, 2, 4, 3, 6]\n * @example\n * // Error handling with default value\n * const data = ['valid', 'invalid'];\n * const result = await flatMapAsync(\n * data,\n * async (item) => {\n * if (item === 'invalid') throw new Error();\n * return [item.toUpperCase()];\n * },\n * ['DEFAULT']\n * );\n * console.log(result); // ['VALID', 'DEFAULT']\n */\nexport async function flatMapAsync<T, U>(\n array: T[],\n callback: (item: T) => Promise<U[]>,\n defaultValue: U[] = [],\n): Promise<U[]> {\n if (array.length === 0) {\n return defaultValue;\n }\n\n const results = await Promise.all(\n array.map(async (item) => {\n try {\n return await callback(item);\n } catch (_error) {\n return defaultValue;\n }\n }),\n );\n return results.flat();\n}\n","import { flatMapAsync } from \"@utils/flatMapAsync\";\nimport { createTaggedLogger } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../types/schemas\";\n\n/**\n * A composite strategy that combines multiple cookie query strategies.\n * This class implements the CookieQueryStrategy interface and allows querying cookies\n * from multiple browser-specific strategies simultaneously.\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy(),\n * new SafariCookieQueryStrategy()\n * ]);\n * const cookies = await strategy.queryCookies('sessionId', 'example.com');\n * ```\n */\nexport class CompositeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"CompositeCookieQueryStrategy\");\n\n /**\n * The browser name identifier for this strategy\n * @remarks Always returns 'internal' as this is a composite strategy\n */\n public readonly browserName: BrowserName = \"internal\";\n\n /**\n * Creates a new instance of CompositeCookieQueryStrategy\n * @param strategies - Array of browser-specific strategies to use for querying cookies\n * @remarks\n * - Each strategy in the array should implement the CookieQueryStrategy interface\n * - The order of strategies determines the order of cookie querying\n * - Failed strategies will be gracefully handled and skipped\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy()\n * ]);\n * ```\n */\n public constructor(private readonly strategies: CookieQueryStrategy[]) {}\n\n /**\n * Handles strategy-specific errors and logs them appropriately\n * @internal\n * @param error - The error that occurred during strategy execution\n * @param strategy - The strategy that failed\n */\n private handleStrategyError(\n error: unknown,\n strategy: CookieQueryStrategy,\n ): void {\n if (error instanceof Error) {\n this.logger.error(\"Strategy failed\", { error, strategy });\n } else {\n this.logger.error(\"Strategy failed with unknown error\", {\n error: String(error),\n strategy,\n });\n }\n }\n\n /**\n * Queries cookies using all available strategies in parallel\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - The store pattern to match cookies against\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns Promise resolving to combined array of cookies from all strategies\n * @remarks\n * - Failures in individual strategies are logged but don't affect other strategies\n * - Results are combined from all successful strategy queries\n * - Empty arrays are returned for failed strategy queries\n * @example\n * ```typescript\n * const strategy = new CompositeCookieQueryStrategy([\n * new ChromeCookieQueryStrategy(),\n * new FirefoxCookieQueryStrategy()\n * ]);\n * const cookies = await strategy.queryCookies('sessionId', 'example.com');\n * console.log(cookies); // Combined results from all browsers\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies from all strategies\", {\n name,\n domain,\n store,\n force,\n strategyCount: this.strategies.length,\n });\n\n /**\n * Use flatMapAsync to process strategies in sequence while collecting results\n * This approach provides better error isolation than Promise.all\n * Each strategy failure is handled independently\n */\n return await flatMapAsync(\n this.strategies,\n async (strategy) => {\n try {\n return await strategy.queryCookies(name, domain, store, force);\n } catch (error) {\n this.handleStrategyError(error, strategy);\n return [];\n }\n },\n [],\n );\n } catch (error) {\n /**\n * Handle top-level errors that may occur during strategy processing\n * This ensures the function always returns an array, even in catastrophic failure\n */\n if (error instanceof Error) {\n this.logger.error(\"Failed to query cookies\", { error });\n } else {\n this.logger.error(\"Failed to query cookies with unknown error\", {\n error: String(error),\n });\n }\n return [];\n }\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Microsoft Edge browser.\n * Edge is Chromium-based and uses the same cookie storage format as Chrome.\n * @example\n * ```typescript\n * const strategy = new EdgeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class EdgeCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of EdgeCookieQueryStrategy\n */\n public constructor() {\n super(\"edge\");\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport type { createTaggedLogger } from \"@utils/logHelpers\";\nimport { getPlatform } from \"@utils/platformUtils\";\nimport { isFirefoxRunning } from \"@utils/ProcessDetector\";\n\nimport type { ExportedCookie } from \"../../../types/schemas\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\nimport { getGlobalConnectionManager } from \"../sql/DatabaseConnectionManager\";\nimport { getGlobalQueryMonitor } from \"../sql/QueryMonitor\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @param logger - Logger instance for logging messages\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(\n logger: ReturnType<typeof createTaggedLogger>,\n): string[] {\n const home = homedir();\n if (!home) {\n logger.warn(\"Failed to get home directory\");\n return [];\n }\n\n // Fast path: Check if Firefox profile directories exist before attempting glob\n const platform = getPlatform();\n const profileDirs: string[] = [];\n const patterns: string[] = [];\n\n switch (platform) {\n case \"darwin\":\n profileDirs.push(join(home, \"Library/Application Support/Firefox\"));\n patterns.push(\n join(\n home,\n \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\",\n ),\n );\n break;\n case \"win32\": {\n // Regular Firefox\n profileDirs.push(join(home, \"AppData\", \"Roaming\", \"Mozilla\", \"Firefox\"));\n patterns.push(\n join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox\",\n \"Profiles\",\n \"*\",\n \"cookies.sqlite\",\n ),\n );\n // Firefox Developer Edition\n const devEditionPath = join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox Developer Edition\",\n );\n if (existsSync(devEditionPath)) {\n profileDirs.push(devEditionPath);\n patterns.push(join(devEditionPath, \"Profiles\", \"*\", \"cookies.sqlite\"));\n }\n // Firefox ESR (Extended Support Release)\n const esrPath = join(\n home,\n \"AppData\",\n \"Roaming\",\n \"Mozilla\",\n \"Firefox ESR\",\n );\n if (existsSync(esrPath)) {\n profileDirs.push(esrPath);\n patterns.push(join(esrPath, \"Profiles\", \"*\", \"cookies.sqlite\"));\n }\n // Also check Local AppData for some installations\n const localFirefoxPath = join(\n home,\n \"AppData\",\n \"Local\",\n \"Mozilla\",\n \"Firefox\",\n );\n if (existsSync(localFirefoxPath)) {\n profileDirs.push(localFirefoxPath);\n patterns.push(\n join(localFirefoxPath, \"Profiles\", \"*\", \"cookies.sqlite\"),\n );\n }\n break;\n }\n case \"linux\":\n profileDirs.push(join(home, \".mozilla/firefox\"));\n patterns.push(join(home, \".mozilla/firefox/*/cookies.sqlite\"));\n break;\n default:\n logger.debug(\"Unsupported platform for Firefox cookie extraction\", {\n platform,\n });\n return [];\n }\n\n const existingProfileDirs = profileDirs.filter((dir) => existsSync(dir));\n\n if (existingProfileDirs.length === 0) {\n logger.debug(\n \"No Firefox profile directories found - Firefox may not be installed\",\n {\n checked: profileDirs,\n platform,\n },\n );\n return [];\n }\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = fg.sync(pattern);\n files.push(...matches);\n }\n\n logger.debug(\"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser.\n * This class extends the BaseCookieQueryStrategy and implements Firefox-specific\n * cookie extraction logic. It searches for cookie databases in standard Firefox\n * profile locations and extracts cookies matching the specified name and domain.\n * @example\n * ```typescript\n * import { FirefoxCookieQueryStrategy } from './FirefoxCookieQueryStrategy';\n *\n * const strategy = new FirefoxCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('sessionid', 'example.com');\n * console.log(cookies);\n * ```\n */\nexport class FirefoxCookieQueryStrategy extends BaseCookieQueryStrategy {\n private readonly lockHandler: BrowserLockHandler;\n\n /**\n * Creates a new instance of FirefoxCookieQueryStrategy\n */\n public constructor() {\n super(\"FirefoxCookieQueryStrategy\", \"Firefox\");\n this.lockHandler = new BrowserLockHandler(this.logger, \"Firefox\");\n }\n\n /**\n * Creates the query parameters for cookie extraction using the new query builder\n * @param name - The cookie name to search for\n * @param domain - The domain pattern to match cookies against\n * @param file - The database file path for metadata\n * @returns Query configuration object\n * @private\n */\n private async createCookieQueryConfig(\n name: string,\n domain: string,\n file: string,\n ): Promise<{\n file: string;\n sql: string;\n params: unknown[];\n rowTransform: (row: FirefoxCookieRow) => ExportedCookie;\n }> {\n // Import the query builder dynamically to avoid circular dependencies\n const { CookieQueryBuilder } = await import(\"../sql/CookieQueryBuilder\");\n const queryBuilder = new CookieQueryBuilder(\"firefox\");\n\n const queryConfig = queryBuilder.buildSelectQuery({\n name,\n domain,\n browser: \"firefox\",\n });\n\n return {\n file,\n sql: queryConfig.sql,\n params: queryConfig.params,\n rowTransform: (row: FirefoxCookieRow): ExportedCookie => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n };\n }\n\n /**\n * Handles errors that occur during cookie extraction\n * @param error - The error that occurred\n * @param file - The database file being queried\n * @param force - Whether operations are being forced\n * @param name - The cookie name being searched\n * @param domain - The domain being searched\n * @returns Promise resolving to retry configuration\n * @private\n */\n private async handleCookieExtractionError(\n error: unknown,\n file: string,\n force: boolean | undefined,\n name: string,\n domain: string,\n ): Promise<{ retryAfterClose: boolean; shouldRelaunch: boolean }> {\n const processes = await isFirefoxRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n file,\n processes,\n force !== true,\n );\n\n if (lockResult.resolved) {\n return {\n retryAfterClose: true,\n shouldRelaunch: lockResult.shouldRelaunch,\n };\n }\n\n this.logExtractError(error, file, name, domain);\n return { retryAfterClose: false, shouldRelaunch: false };\n }\n\n /**\n * Logs cookie extraction errors in a consistent format\n * @param error - The error to log\n * @param file - The file that failed\n * @param name - The cookie name\n * @param domain - The domain\n * @private\n */\n private logExtractError(\n error: unknown,\n file: string,\n name: string,\n domain: string,\n ): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.logger.debug(`Error reading Firefox cookie file ${file}`, {\n error: errorMessage,\n file,\n name,\n domain,\n });\n }\n\n /**\n * Performs a retry attempt after browser closure\n * @param queryConfig - The cookie query configuration\n * @param shouldRelaunch - Whether to relaunch the browser after success\n * @returns Promise resolving to extracted cookies\n * @private\n */\n private async performRetryAfterClose(\n queryConfig: Awaited<ReturnType<typeof this.createCookieQueryConfig>>,\n shouldRelaunch: boolean,\n ): Promise<ExportedCookie[]> {\n this.logger.info(\n \"Retrying Firefox cookie extraction after browser close...\",\n );\n\n try {\n const cookies = await this.executeQueryWithNewUtilities(queryConfig);\n this.logger.success(\n \"Successfully extracted cookies after closing Firefox\",\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError) {\n this.logger.error(\n \"Failed to extract cookies even after closing Firefox\",\n {\n error:\n retryError instanceof Error\n ? retryError.message\n : String(retryError),\n file: queryConfig.file,\n },\n );\n\n if (shouldRelaunch) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n }\n\n /**\n * Processes a single Firefox cookie file for the given parameters\n * @param file - The cookie file to process\n * @param name - The cookie name to search for\n * @param domain - The domain pattern to match\n * @param force - Whether to force operations despite warnings\n * @returns Promise resolving to extracted cookies from this file\n * @private\n */\n private async processCookieFile(\n file: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const queryConfig = await this.createCookieQueryConfig(name, domain, file);\n\n try {\n return await this.executeQueryWithNewUtilities(queryConfig);\n } catch (error) {\n const retryConfig = await this.handleCookieExtractionError(\n error,\n file,\n force,\n name,\n domain,\n );\n\n if (retryConfig.retryAfterClose) {\n return this.performRetryAfterClose(\n queryConfig,\n retryConfig.shouldRelaunch,\n );\n }\n\n return [];\n }\n }\n\n /**\n * Execute query using the new SQL utilities\n * @param queryConfig - Query configuration from createCookieQueryConfig\n * @param queryConfig.file\n * @param queryConfig.sql\n * @param queryConfig.params\n * @param queryConfig.rowTransform\n * @returns Promise resolving to exported cookies\n * @private\n */\n private async executeQueryWithNewUtilities(queryConfig: {\n file: string;\n sql: string;\n params: unknown[];\n rowTransform: (row: FirefoxCookieRow) => ExportedCookie;\n }): Promise<ExportedCookie[]> {\n const connectionManager = getGlobalConnectionManager({\n retryAttempts: 1, // Fail fast for Firefox - we have lock handling\n retryDelay: 0, // No delay - let lock handler deal with it\n queryTimeout: 100, // Very short timeout for Firefox to fail fast on locks\n enableMonitoring: true,\n });\n\n const monitor = getGlobalQueryMonitor();\n\n return connectionManager.executeQuery(\n queryConfig.file,\n (db) => {\n // Use the query monitor for tracking\n const rows = monitor.executeQuery<FirefoxCookieRow>(\n db,\n queryConfig.sql,\n queryConfig.params,\n queryConfig.file,\n );\n\n // Apply transformation\n return rows.map(queryConfig.rowTransform);\n },\n queryConfig.sql, // Pass SQL for monitoring\n );\n }\n\n /**\n * Executes the Firefox-specific query logic\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns A promise that resolves to an array of exported cookies\n * @protected\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const files = store ?? findFirefoxCookieFiles(this.logger);\n const fileList = Array.isArray(files) ? files : [files];\n\n // Fast path: If no Firefox cookie files found (Firefox not installed),\n // return early to avoid unnecessary database queries and process detection\n if (fileList.length === 0) {\n this.logger.debug(\"No Firefox cookie files to query\");\n return [];\n }\n\n const results: ExportedCookie[] = [];\n\n for (const file of fileList) {\n const cookies = await this.processCookieFile(file, name, domain, force);\n results.push(...cookies);\n }\n\n return results;\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Opera browser.\n * Opera is a Chromium-based browser with its own keychain entry.\n * @example\n * ```typescript\n * const strategy = new OperaCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class OperaCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of OperaCookieQueryStrategy\n */\n public constructor() {\n super(\"opera\");\n }\n}\n","import { ChromiumCookieQueryStrategy } from \"../chromium/ChromiumCookieQueryStrategy\";\n\n/**\n * Strategy for querying cookies from Opera GX browser.\n * Opera GX is the gaming-focused variant of Opera, sharing the same keychain entry.\n * @example\n * ```typescript\n * const strategy = new OperaGXCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class OperaGXCookieQueryStrategy extends ChromiumCookieQueryStrategy {\n /**\n * Creates a new instance of OperaGXCookieQueryStrategy\n */\n public constructor() {\n super(\"opera-gx\");\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { errorMessageContains, formatErrorForLogging } from \"@utils/errorUtils\";\nimport { isMacOS } from \"@utils/platformUtils\";\nimport { isSafariRunning } from \"@utils/ProcessDetector\";\nimport {\n checkFilePermission,\n handleSafariPermissionError,\n} from \"@utils/SystemPermissions\";\n\nimport type { ExportedCookie } from \"../../../types/schemas\";\nimport { BaseCookieQueryStrategy } from \"../BaseCookieQueryStrategy\";\nimport { BrowserLockHandler } from \"../BrowserLockHandler\";\n\nimport { decodeBinaryCookies } from \"./decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser.\n * This class extends the BaseCookieQueryStrategy and implements Safari-specific\n * cookie extraction logic.\n */\nexport class SafariCookieQueryStrategy extends BaseCookieQueryStrategy {\n private readonly lockHandler: BrowserLockHandler;\n\n /**\n * Creates a new instance of SafariCookieQueryStrategy\n */\n public constructor() {\n super(\"SafariCookieQueryStrategy\", \"Safari\");\n this.lockHandler = new BrowserLockHandler(this.logger, \"Safari\");\n }\n\n /**\n * Gets the path to Safari's cookie database\n * @param home - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(home: string): string {\n return join(\n home,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Formats the domain by removing leading dot if present\n * @param domain - Domain to format\n * @returns Formatted domain or empty string if domain is invalid\n */\n private formatDomain(domain: string | undefined | null): string {\n if (domain === null || domain === undefined || typeof domain !== \"string\") {\n return \"\";\n }\n return domain.startsWith(\".\") ? domain.slice(1) : domain;\n }\n\n /**\n * Formats the expiry date\n * @param expiry - Expiry timestamp (Unix epoch seconds)\n * @returns Formatted expiry date or \"Infinity\"\n */\n private formatExpiry(\n expiry: number | undefined | null,\n ): Date | \"Infinity\" | undefined {\n // Handle undefined or null - return undefined instead of NaN date\n if (expiry === undefined || expiry === null) {\n return undefined;\n }\n\n if (typeof expiry !== \"number\" || Number.isNaN(expiry) || expiry <= 0) {\n return \"Infinity\";\n }\n\n // Validate timestamp is reasonable (1970-2100 range in seconds)\n const minTimestamp = 0; // 1970-01-01\n const maxTimestamp = 4102444800; // 2100-01-01\n\n if (expiry < minTimestamp || expiry > maxTimestamp) {\n this.logger.warn(\"Invalid expiry timestamp, treating as session cookie\", {\n expiry,\n });\n return \"Infinity\";\n }\n\n return new Date(expiry * 1000);\n }\n\n /**\n * Checks if a flag bit is set\n * @param flags - The flags value\n * @param bit - The bit to check\n * @returns True if the bit is set, false otherwise\n */\n private isFlagSet(flags: number | undefined | null, bit: number): boolean {\n if (typeof flags !== \"number\" || Number.isNaN(flags) || flags <= 0) {\n return false;\n }\n return (flags & bit) === bit;\n }\n\n /**\n * Formats the creation timestamp\n * @param creation - Creation timestamp (Unix epoch seconds)\n * @returns Formatted creation timestamp in milliseconds or undefined\n */\n private formatCreation(\n creation: number | undefined | null,\n ): number | undefined {\n if (\n typeof creation !== \"number\" ||\n Number.isNaN(creation) ||\n creation <= 0\n ) {\n return undefined;\n }\n\n // Validate timestamp is reasonable (1970-2100 range in seconds)\n const minTimestamp = 0; // 1970-01-01\n const maxTimestamp = 4102444800; // 2100-01-01\n\n if (creation < minTimestamp || creation > maxTimestamp) {\n this.logger.warn(\"Invalid creation timestamp, ignoring\", { creation });\n return undefined;\n }\n\n return creation * 1000;\n }\n\n /**\n * Processes a cookie value to ensure it's a string\n * @param value - The cookie value to process\n * @returns The processed value as a string\n */\n private processValue(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (Buffer.isBuffer(value)) {\n return value.toString();\n }\n\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // If JSON.stringify fails (e.g., circular reference), return a placeholder\n return \"[object]\";\n }\n }\n\n // Handle primitives (string, number, boolean, etc.)\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n\n // Fallback for any other type (should not happen with proper typing)\n return \"[unknown value]\";\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @param force - Whether to skip interactive prompts\n * @returns Array of exported cookies\n */\n private async decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n // Check permissions first\n const permissionResult = await this.checkAndHandlePermissions(\n cookieDbPath,\n force,\n );\n if (!permissionResult) {\n return [];\n }\n\n // Decode cookies and process them\n const cookies = decodeBinaryCookies(cookieDbPath);\n return this.processCookies(cookies, name, domain, cookieDbPath);\n } catch (error: unknown) {\n return this.handleDecodingError(error, cookieDbPath, name, domain, force);\n }\n }\n\n /**\n * Check file permissions and handle permission errors\n * @param cookieDbPath - Path to the cookie database\n * @param force - Whether to skip interactive prompts\n * @returns True if permissions are granted, false otherwise\n */\n private async checkAndHandlePermissions(\n cookieDbPath: string,\n force?: boolean,\n ): Promise<boolean> {\n const hasPermission = await checkFilePermission(cookieDbPath);\n if (hasPermission) {\n return true;\n }\n\n this.logger.warn(\"Cannot access Safari cookies due to macOS permissions\", {\n file: cookieDbPath,\n suggestion: \"Terminal application needs Full Disk Access permission\",\n });\n\n // Try to handle the permission error interactively\n const permissionGranted = await handleSafariPermissionError(\n new Error(\"EPERM: operation not permitted\"),\n {\n appName: process.env.TERM_PROGRAM ?? \"Terminal\",\n browserName: \"Safari\",\n interactive: force !== true,\n },\n );\n\n if (!permissionGranted) {\n return false;\n }\n\n // Check again after permission might have been granted\n const stillNoPermission = !(await checkFilePermission(cookieDbPath));\n if (stillNoPermission) {\n this.logger.error(\n \"Still cannot access Safari cookies after permission attempt\",\n {\n file: cookieDbPath,\n advice:\n \"Please restart your terminal application after granting Full Disk Access\",\n },\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Process and filter cookies based on name and domain criteria\n * @param cookies - Raw cookies from binary file\n * @param name - Name filter\n * @param domain - Domain filter\n * @param cookieDbPath - Path to cookie database for metadata\n * @returns Processed and filtered cookies\n */\n private processCookies(\n cookies: unknown[],\n name: string,\n domain: string,\n cookieDbPath: string,\n ): ExportedCookie[] {\n return cookies\n .filter((cookie) => this.matchesCriteria(cookie, name, domain))\n .map((cookie) => this.mapToExportedCookie(cookie, cookieDbPath));\n }\n\n /**\n * Check if cookie matches the search criteria\n * @param cookie - Raw cookie object\n * @param name - Name filter\n * @param domain - Domain filter\n * @returns True if cookie matches criteria\n */\n private matchesCriteria(\n cookie: unknown,\n name: string,\n domain: string,\n ): boolean {\n // Type guard for cookie object\n if (!this.isCookieObject(cookie)) {\n return false;\n }\n\n const formattedDomain = this.formatDomain(cookie.domain);\n\n // Skip cookies with invalid domains\n if (formattedDomain === \"\") {\n return false;\n }\n\n const nameMatches = name === \"%\" || cookie.name === name;\n const domainMatches = domain === \"%\" || formattedDomain.includes(domain);\n\n return nameMatches && domainMatches;\n }\n\n /**\n * Type guard to check if an object is a valid cookie object\n * @param cookie - Object to check\n * @returns True if object has expected cookie properties\n */\n private isCookieObject(cookie: unknown): cookie is {\n domain?: string;\n name: string;\n value: unknown;\n expiry?: number;\n creation?: number;\n flags?: number;\n path?: string;\n version?: number;\n comment?: string;\n commentURL?: string;\n port?: number;\n } {\n return (\n typeof cookie === \"object\" &&\n cookie !== null &&\n \"name\" in cookie &&\n typeof (cookie as { name: unknown }).name === \"string\"\n );\n }\n\n /**\n * Map raw cookie to ExportedCookie format\n * @param cookie - Raw cookie object\n * @param cookieDbPath - Path to cookie database for metadata\n * @returns Formatted ExportedCookie\n */\n private mapToExportedCookie(\n cookie: unknown,\n cookieDbPath: string,\n ): ExportedCookie {\n // We know it's a cookie object due to prior filtering\n const cookieObj = cookie as {\n domain?: string | null;\n name: string;\n value: unknown;\n expiry?: number | null;\n creation?: number | null;\n flags?: number | null;\n path?: string | null;\n version?: number | null;\n comment?: string | null;\n commentURL?: string | null;\n port?: number | null;\n };\n\n return {\n domain: this.formatDomain(cookieObj.domain),\n name: cookieObj.name,\n value: this.processValue(cookieObj.value),\n expiry: this.formatExpiry(cookieObj.expiry),\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n secure: this.isFlagSet(cookieObj.flags, 0x1),\n httpOnly: this.isFlagSet(cookieObj.flags, 0x4),\n path: cookieObj.path ?? undefined,\n version:\n cookieObj.version === undefined ? undefined : cookieObj.version,\n comment: cookieObj.comment ?? undefined,\n commentURL: cookieObj.commentURL ?? undefined,\n port: cookieObj.port === undefined ? undefined : cookieObj.port,\n creation: this.formatCreation(cookieObj.creation),\n },\n };\n }\n\n /**\n * Handle errors that occur during cookie decoding\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n * @param force - Whether interactive prompts were skipped\n * @returns Empty array as fallback\n */\n private async handleDecodingError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n const isPermissionError =\n errorMessageContains(error, \"EPERM\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"Permission denied\");\n\n if (isPermissionError) {\n await this.handlePermissionError(\n error,\n cookieDbPath,\n name,\n domain,\n force,\n );\n } else {\n this.logDecodingError(error, cookieDbPath, name, domain);\n }\n\n return [];\n }\n\n /**\n * Handle permission-related errors\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n * @param force - Whether interactive prompts were skipped\n */\n private async handlePermissionError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<void> {\n const handled = await handleSafariPermissionError(error as Error, {\n appName: process.env.TERM_PROGRAM ?? \"Terminal\",\n browserName: \"Safari\",\n interactive: force !== true,\n });\n\n if (handled) {\n this.logger.info(\n \"Permission flow completed. Please run the command again after granting access.\",\n );\n } else {\n this.logger.warn(\n `Permission denied accessing Safari cookies at ${cookieDbPath}`,\n formatErrorForLogging(error, {\n file: cookieDbPath,\n name,\n domain,\n advice:\n \"Grant Full Disk Access to your terminal in System Settings > Privacy & Security\",\n }),\n );\n }\n }\n\n /**\n * Log non-permission errors that occur during decoding\n * @param error - The error that occurred\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name filter used\n * @param domain - Domain filter used\n */\n private logDecodingError(\n error: unknown,\n cookieDbPath: string,\n name: string,\n domain: string,\n ): void {\n this.logger.error(\n `Error decoding ${cookieDbPath}`,\n formatErrorForLogging(error, {\n file: cookieDbPath,\n name,\n domain,\n }),\n );\n }\n\n /**\n * Executes the Safari-specific query logic\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @param store - Optional store path\n * @param force - Whether to force operations despite warnings (e.g., locked databases)\n * @returns Array of matching cookies, or empty array if none found\n * @protected\n */\n protected async executeQuery(\n name: string,\n domain: string,\n store?: string,\n force?: boolean,\n ): Promise<ExportedCookie[]> {\n // Fast path: Safari only exists on macOS\n if (!isMacOS()) {\n this.logger.debug(\"Safari strategy skipped on non-macOS platform\");\n return [];\n }\n\n try {\n this.logger.info(\"Querying cookies\", { name, domain, store });\n\n // Validate home directory\n const home = homedir();\n if (!this.isValidHomeDirectory(home)) {\n return [];\n }\n\n const cookieDbPath = store ?? this.getCookieDbPath(home);\n const normalizedName = name || \"%\";\n const normalizedDomain = domain || \"%\";\n\n // First attempt to decode cookies\n const firstAttemptResult = await this.attemptDecodeWithLockHandling(\n cookieDbPath,\n normalizedName,\n normalizedDomain,\n force,\n );\n\n if (firstAttemptResult.success) {\n return firstAttemptResult.cookies;\n }\n\n // Handle retry scenario if browser was closed\n if (firstAttemptResult.shouldRetry) {\n return this.retryAfterBrowserClose(\n cookieDbPath,\n normalizedName,\n normalizedDomain,\n force,\n firstAttemptResult.shouldRelaunch,\n );\n }\n\n return [];\n } catch (error: unknown) {\n this.logQueryError(error, name, domain);\n return [];\n }\n }\n\n /**\n * Validate home directory\n * @param home - Home directory path\n * @returns True if valid, false otherwise\n */\n private isValidHomeDirectory(home: string): boolean {\n if (typeof home !== \"string\" || home.length === 0) {\n this.logger.error(\"Failed to get home directory\");\n return false;\n }\n return true;\n }\n\n /**\n * Attempt to decode cookies with lock conflict handling\n * @param cookieDbPath - Path to cookie database\n * @param name - Normalized cookie name filter\n * @param domain - Normalized domain filter\n * @param force - Whether to force operations\n * @returns Result object with success status and data\n */\n private async attemptDecodeWithLockHandling(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n ): Promise<{\n success: boolean;\n cookies: ExportedCookie[];\n shouldRetry: boolean;\n shouldRelaunch: boolean;\n }> {\n try {\n const cookies = await this.decodeCookies(\n cookieDbPath,\n name,\n domain,\n force,\n );\n return {\n success: true,\n cookies,\n shouldRetry: false,\n shouldRelaunch: false,\n };\n } catch (error: unknown) {\n return this.handleLockConflict(error, cookieDbPath, force);\n }\n }\n\n /**\n * Handle browser lock conflicts\n * @param error - The error that occurred\n * @param cookieDbPath - Path to cookie database\n * @param force - Whether to force operations\n * @returns Result indicating what action to take next\n */\n private async handleLockConflict(\n error: unknown,\n cookieDbPath: string,\n force?: boolean,\n ): Promise<{\n success: boolean;\n cookies: ExportedCookie[];\n shouldRetry: boolean;\n shouldRelaunch: boolean;\n }> {\n if (!this.isLockError(error)) {\n throw error; // Re-throw non-lock errors\n }\n\n const processes = await isSafariRunning();\n const lockResult = await this.lockHandler.handleBrowserConflict(\n error,\n cookieDbPath,\n processes,\n force !== true,\n );\n\n if (lockResult.resolved) {\n return {\n success: false,\n cookies: [],\n shouldRetry: true,\n shouldRelaunch: lockResult.shouldRelaunch,\n };\n }\n\n this.logger.warn(\n \"Safari cookie file locked\",\n formatErrorForLogging(error, {\n file: cookieDbPath,\n advice:\n \"Safari may be accessing the cookie file. Try closing Safari and running again.\",\n }),\n );\n\n return {\n success: false,\n cookies: [],\n shouldRetry: false,\n shouldRelaunch: false,\n };\n }\n\n /**\n * Check if error indicates a lock conflict\n * @param error - Error to check\n * @returns True if this is a lock-related error\n */\n private isLockError(error: unknown): boolean {\n return (\n errorMessageContains(error, \"EPERM\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"Permission denied\") ||\n errorMessageContains(error, \"EBUSY\")\n );\n }\n\n /**\n * Retry cookie extraction after browser was closed\n * @param cookieDbPath - Path to cookie database\n * @param name - Cookie name filter\n * @param domain - Domain filter\n * @param force - Whether to force operations\n * @param shouldRelaunch - Whether browser should be relaunched\n * @returns Cookies or empty array\n */\n private async retryAfterBrowserClose(\n cookieDbPath: string,\n name: string,\n domain: string,\n force?: boolean,\n shouldRelaunch?: boolean,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\n \"Retrying Safari cookie extraction after browser close...\",\n );\n\n const cookies = await this.decodeCookies(\n cookieDbPath,\n name,\n domain,\n force,\n );\n\n this.logger.success(\n \"Successfully extracted cookies after closing Safari\",\n );\n\n if (shouldRelaunch === true) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return cookies;\n } catch (retryError: unknown) {\n return this.handleRetryFailure(retryError, cookieDbPath, shouldRelaunch);\n }\n }\n\n /**\n * Handle failure during retry attempt\n * @param retryError - Error that occurred during retry\n * @param cookieDbPath - Path to cookie database\n * @param shouldRelaunch - Whether browser should be relaunched\n * @returns Empty array\n */\n private async handleRetryFailure(\n retryError: unknown,\n cookieDbPath: string,\n shouldRelaunch?: boolean,\n ): Promise<ExportedCookie[]> {\n this.logger.error(\n \"Failed to extract cookies even after closing Safari\",\n formatErrorForLogging(retryError, { file: cookieDbPath }),\n );\n\n // Still try to relaunch Safari if needed\n if (shouldRelaunch === true) {\n await this.lockHandler.relaunchBrowser();\n }\n\n return [];\n }\n\n /**\n * Log query errors\n * @param error - The error that occurred\n * @param name - Cookie name filter\n * @param domain - Domain filter\n */\n private logQueryError(error: unknown, name: string, domain: string): void {\n this.logger.error(\n \"Failed to query cookies\",\n formatErrorForLogging(error, { name, domain }),\n );\n }\n}\n","import { exec } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promisify } from \"node:util\";\n\nimport { errorMessageContains, getErrorMessage } from \"./errorUtils\";\nimport { createTaggedLogger } from \"./logHelpers\";\nimport { isMacOS } from \"./platformUtils\";\n\nconst execAsync = promisify(exec);\nconst logger = createTaggedLogger(\"SystemPermissions\");\n\n/**\n *\n */\nexport interface PermissionRequestOptions {\n appName: string;\n browserName: string;\n interactive?: boolean;\n}\n\n/**\n * Open System Settings to the Full Disk Access page on macOS\n */\nasync function openFullDiskAccessSettings(): Promise<void> {\n try {\n // Open System Settings directly to Privacy & Security > Full Disk Access\n await execAsync(\n 'open \"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\"',\n );\n logger.info(\n \"Opened System Settings > Privacy & Security > Full Disk Access\",\n );\n } catch (_error) {\n // Fallback to general Privacy & Security\n try {\n await execAsync(\n 'open \"x-apple.systempreferences:com.apple.preference.security?Privacy\"',\n );\n logger.info(\"Opened System Settings > Privacy & Security\");\n } catch (_fallbackError) {\n // Last resort: just open System Settings\n await execAsync(\"open -b com.apple.systempreferences\");\n logger.info(\"Opened System Settings\");\n }\n }\n}\n\n/**\n * Check which terminal application is running\n * @returns The name of the terminal application or a fallback message\n */\nfunction getTerminalApp(): string {\n const termProgram = process.env.TERM_PROGRAM;\n\n if (termProgram === \"iTerm.app\") {\n return \"iTerm\";\n }\n if (termProgram === \"Apple_Terminal\") {\n return \"Terminal\";\n }\n if (termProgram === \"vscode\") {\n return \"Visual Studio Code\";\n }\n return termProgram ?? \"your terminal application\";\n}\n\n/**\n * Prompt user to grant permissions\n * @param appName - The name of the application requesting permissions\n * @param browserName - The name of the browser being accessed\n * @returns A promise that resolves to true if user grants permission\n */\nasync function promptForPermissionGrant(\n appName: string,\n browserName: string,\n): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n console.log(`\n⚠️ ${browserName} cookie access is blocked by macOS security.\n\nTo grant access, ${appName} needs permission to read ${browserName} data.\n\nWould you like to:\n1. Open System Settings to grant permission (recommended)\n2. Skip ${browserName} cookies for now\n3. Exit\n\nPlease enter your choice (1/2/3): `);\n\n rl.question(\"\", (answer) => {\n rl.close();\n resolve(answer.trim() === \"1\");\n });\n });\n}\n\n/**\n * Handle Safari permission errors with user guidance\n * @param error - The error encountered when accessing Safari cookies\n * @param options - Configuration options for permission requests\n * @returns A promise that resolves to true if permissions should be granted\n */\nexport async function handleSafariPermissionError(\n error: Error,\n options: PermissionRequestOptions,\n): Promise<boolean> {\n if (!isMacOS()) {\n return false;\n }\n\n const isPermissionError =\n errorMessageContains(error, \"eperm\") ||\n errorMessageContains(error, \"operation not permitted\") ||\n errorMessageContains(error, \"permission denied\") ||\n errorMessageContains(error, \"authorization denied\");\n\n if (!isPermissionError) {\n return false;\n }\n\n const terminalApp = options.appName || getTerminalApp();\n\n logger.warn(`${options.browserName} cookie access denied by macOS`, {\n app: terminalApp,\n error: getErrorMessage(error),\n });\n\n if (options.interactive !== false) {\n const shouldOpenSettings = await promptForPermissionGrant(\n terminalApp,\n options.browserName,\n );\n\n if (shouldOpenSettings) {\n await openFullDiskAccessSettings();\n\n console.log(`\n✅ System Settings opened to Privacy & Security\n\nPlease follow these steps:\n1. Look for \"${terminalApp}\" in the list\n2. If not present, click the \"+\" button and add it\n3. Enable the toggle next to \"${terminalApp}\"\n4. You may need to restart ${terminalApp} after granting permission\n5. Then run this command again\n\nPress Enter when you've completed these steps...`);\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n await new Promise<void>((resolve) => {\n rl.question(\"\", () => {\n rl.close();\n resolve();\n });\n });\n\n return true;\n }\n } else {\n logger.info(\n `To grant ${options.browserName} access, add ${terminalApp} to System Settings > Privacy & Security > Full Disk Access`,\n );\n }\n\n return false;\n}\n\n/**\n * Check if we have permission to access a file\n * @param filePath - The path to the file to check permissions for\n * @returns A promise that resolves to true if file is accessible\n */\nexport async function checkFilePermission(filePath: string): Promise<boolean> {\n try {\n const { exec } = await import(\"node:child_process\");\n const { promisify } = await import(\"node:util\");\n const execAsync = promisify(exec);\n\n // Try to read the file\n await execAsync(`cat \"${filePath}\" > /dev/null 2>&1`);\n return true;\n } catch {\n return false;\n }\n}\n","import { Buffer } from \"node:buffer\";\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport type { BinaryCookieRow } from \"../../../types/schemas\";\nimport { createTaggedLogger, logWarn } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodablePage } from \"./BinaryCodablePage\";\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookies\");\n\n/**\n * Represents a binary cookies file structure used by Safari\n */\nexport class BinaryCodableCookies {\n /**\n *\n */\n public pages: BinaryCodablePage[];\n /**\n *\n */\n public metadata: Record<string, unknown>;\n private static readonly MAGIC = Buffer.from(\"cook\", \"utf8\");\n private static readonly FOOTER = BigInt(\"0x071720050000004b\");\n private static readonly DEFAULT_COOKIE_PATH = join(\n homedir(),\n \"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies\",\n );\n\n /**\n * Creates a new BinaryCookies instance from a buffer\n * @param buffer - The raw binary cookie file data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.pages = [];\n this.metadata = {};\n this.decode(container);\n }\n\n /**\n * Creates a BinaryCookies instance from a file path\n * @param path - Path to the Safari Cookies.binarycookies file\n * @returns A new BinaryCookies instance\n */\n public static fromFile(path: string): BinaryCodableCookies {\n const buffer = readFileSync(path);\n return new BinaryCodableCookies(buffer);\n }\n\n /**\n * Creates a BinaryCookies instance from the default Safari cookies location\n * @returns A new BinaryCookies instance\n */\n public static fromDefaultPath(): BinaryCodableCookies {\n return BinaryCodableCookies.fromFile(\n BinaryCodableCookies.DEFAULT_COOKIE_PATH,\n );\n }\n\n /**\n * Converts the binary cookie data into a validated array of cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const page of this.pages) {\n try {\n const pageCookies = page.toCookieRows();\n if (Array.isArray(pageCookies)) {\n cookies.push(...pageCookies);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting page cookies\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n try {\n // Check magic value\n const magic = container.buffer.subarray(\n container.offset,\n container.offset + 4,\n );\n container.offset += 4;\n logger.debug(\"Magic bytes:\", magic.toString());\n if (!magic.equals(BinaryCodableCookies.MAGIC)) {\n throw new Error(\"Missing magic value\");\n }\n\n // Read page count\n const pageCount = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page count:\", pageCount);\n container.offset += 4;\n\n // Read page sizes\n const pageSizes: number[] = [];\n for (let i = 0; i < pageCount; i++) {\n const pageSize = container.buffer.readUInt32BE(container.offset);\n pageSizes.push(pageSize);\n logger.debug(`Page ${i} size:`, pageSize);\n container.offset += 4;\n }\n\n // Calculate page offsets\n let currentOffset = container.offset;\n logger.debug(\"Starting page data at offset:\", currentOffset);\n for (const pageSize of pageSizes) {\n try {\n logger.debug(\n \"Reading page at offset:\",\n currentOffset,\n \"with size:\",\n pageSize,\n );\n const pageBuffer = container.buffer.subarray(\n currentOffset,\n currentOffset + pageSize,\n );\n const page = new BinaryCodablePage(pageBuffer);\n this.pages.push(page);\n currentOffset += pageSize;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger.warn(\"Error decoding page:\", { error: errorMessage });\n currentOffset += pageSize; // Skip the problematic page\n }\n }\n container.offset = currentOffset;\n\n // Read checksum\n const checksum = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Checksum:\", checksum.toString(16));\n container.offset += 4;\n\n // Read footer\n const footer = container.buffer.readBigUInt64BE(container.offset);\n logger.debug(\"Footer:\", footer.toString(16));\n container.offset += 8;\n if (footer !== BinaryCodableCookies.FOOTER) {\n logWarn(\"BinaryCookies\", \"Invalid cookie file format: wrong footer\");\n }\n\n // Read metadata plist\n // const plistData = container.buffer.subarray(container.offset);\n // Note: You'll need to implement or use a plist parser library here\n this.metadata = {}; // Placeholder for plist data\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error decoding binary cookies file\", {\n error: errorMessage,\n });\n throw error;\n }\n }\n}\n","import type { Buffer } from \"node:buffer\";\n\nimport type { BinaryCookieRow } from \"../../../types/schemas\";\nimport { createTaggedLogger, logWarn } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodableCookie } from \"./BinaryCodableCookie\";\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodablePage\");\n\n/**\n * Represents a page of cookies within the binary cookies file\n */\nexport class BinaryCodablePage {\n /**\n *\n */\n public cookies: BinaryCodableCookie[];\n private static readonly HEADER = 0x00000100;\n private static readonly FOOTER = 0x00000000;\n\n /**\n * Creates a new Page instance from a buffer\n * @param buffer - The raw binary page data\n */\n public constructor(buffer: Buffer) {\n this.cookies = [];\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Converts the page's cookies into validated cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const cookie of this.cookies) {\n try {\n const cookieRow = cookie.toCookieRow();\n if (cookieRow !== null) {\n cookies.push(cookieRow);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting cookie\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n // Read page tag (4 bytes)\n const header = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page header:\", header.toString(16));\n container.offset += 4;\n if (header !== BinaryCodablePage.HEADER) {\n throw new Error(\"Invalid page header\");\n }\n\n // Read number of cookies (4 bytes)\n const cookieCount = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie count:\", cookieCount);\n container.offset += 4;\n\n // Store the page start offset for calculating absolute cookie positions\n const pageStart = container.offset - 8;\n logger.debug(\"Page start offset:\", pageStart);\n\n // Read cookie offsets (4 bytes each)\n const cookieOffsets: number[] = [];\n for (let i = 0; i < cookieCount; i++) {\n const cookieOffset = container.buffer.readUInt32LE(container.offset);\n cookieOffsets.push(cookieOffset);\n logger.debug(`Cookie ${i} offset:`, cookieOffset);\n container.offset += 4;\n }\n\n // Read page end marker (4 bytes)\n const footer = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page footer:\", footer.toString(16));\n container.offset += 4;\n if (footer !== BinaryCodablePage.FOOTER) {\n throw new Error(\"Invalid page footer\");\n }\n\n // Read cookies at their offsets\n for (let i = 0; i < cookieCount; i++) {\n try {\n const cookieOffset = cookieOffsets[i]!;\n logger.debug(`Reading cookie ${i} at offset:`, cookieOffset);\n\n // Read cookie size from the cookie header\n const cookieSize = container.buffer.readUInt32LE(cookieOffset);\n logger.debug(`Cookie ${i} size:`, cookieSize);\n if (cookieSize < 48) {\n // Minimum cookie size is 48 bytes (header)\n logger.warn(`Invalid cookie size ${cookieSize} at index ${i}`);\n continue;\n }\n\n // Ensure we don't read past the buffer\n if (cookieOffset + cookieSize > container.buffer.length) {\n logger.warn(\n `Cookie size ${cookieSize} at index ${i} would exceed buffer length ${container.buffer.length}`,\n );\n continue;\n }\n\n const cookieBuffer = container.buffer.subarray(\n cookieOffset,\n cookieOffset + cookieSize,\n );\n const cookie = new BinaryCodableCookie(cookieBuffer);\n this.cookies.push(cookie);\n } catch (error) {\n logger.warn(\"Invalid cookie data\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) => name === \"%\" || /^[!#$%&'()*+\\-.:0-9A-Z ^_`a-z|~]+$/.test(name),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w~]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * logger.info('Valid cookie spec:', result.data);\n * } else {\n * logger.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown());\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * logger.info('Valid cookie:', result.data);\n * } else {\n * logger.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = {\n browserName: BrowserName;\n queryCookies: (\n domain: string,\n name: string,\n path?: string,\n secure?: boolean,\n ) => Promise<ExportedCookie[]>;\n};\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z.function(),\n })\n .strict();\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n\n/**\n * Schema for base cookie query options\n */\nexport const BaseCookieQueryOptionsSchema = z.object({\n /** Maximum number of cookies to return */\n limit: z.number().int().positive().optional(),\n /** Whether to remove expired cookies from results */\n removeExpired: z.boolean().optional(),\n /** Include expired cookies in results */\n includeExpired: z.boolean().optional(),\n /** Storage location override */\n store: z.string().optional(),\n /** Force query even if browser is running */\n force: z.boolean().optional(),\n});\n\n/**\n * Schema for strategy-based cookie query options\n */\nexport const CookieQueryOptionsSchema = BaseCookieQueryOptionsSchema.extend({\n /** Strategy to use for querying cookies */\n strategy: CookieQueryStrategySchema.optional(),\n});\n\n/**\n * Schema for SQL browser types\n */\nexport const SqlBrowserTypeSchema = z.enum([\n \"chrome\",\n \"chromium\",\n \"edge\",\n \"firefox\",\n \"opera\",\n \"brave\",\n \"arc\",\n]);\n\n/**\n * Schema for SQL-specific cookie query options\n */\nexport const SqlCookieQueryOptionsSchema = CookieSpecSchema.extend({\n /** Browser type for SQL queries */\n browser: SqlBrowserTypeSchema,\n /** Enable exact domain matching instead of wildcard */\n exactDomain: z.boolean().optional(),\n /** Enable case-sensitive matching */\n caseSensitive: z.boolean().optional(),\n /** Maximum number of results */\n limit: z.number().int().positive().optional(),\n /** Include expired cookies */\n includeExpired: z.boolean().optional(),\n});\n\n/**\n * Type for base cookie query options\n */\nexport type BaseCookieQueryOptions = z.infer<\n typeof BaseCookieQueryOptionsSchema\n>;\n\n/**\n * Type for strategy-based cookie query options\n */\nexport type CookieQueryOptions<\n T extends CookieQueryStrategy = CookieQueryStrategy,\n> = BaseCookieQueryOptions & {\n strategy?: T;\n};\n\n/**\n * Type for SQL browser types\n */\nexport type SqlBrowserType = z.infer<typeof SqlBrowserTypeSchema>;\n\n/**\n * Type for SQL-specific cookie query options\n */\nexport type SqlCookieQueryOptions = z.infer<typeof SqlCookieQueryOptionsSchema>;\n","import { Buffer } from \"node:buffer\";\n\nimport {\n type BinaryCookieRow,\n BinaryCookieRowSchema,\n} from \"../../../types/schemas\";\nimport { createTaggedLogger } from \"../../../utils/logHelpers\";\n\nimport type { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\nimport type { BinaryCodableFlags } from \"./interfaces/BinaryCodableFlags\";\nimport type { BinaryCodableOffsets } from \"./interfaces/BinaryCodableOffsets\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookie\");\n\n/**\n * Represents a single cookie within a page\n * Handles decoding of Safari's binary cookie format\n */\nexport class BinaryCodableCookie {\n /**\n * Cookie version number\n */\n public version = 0;\n\n /**\n * URL the cookie is associated with\n */\n public url = \"\";\n\n /**\n * Port number if specified\n */\n public port?: number;\n\n /**\n * Cookie name\n */\n public name = \"\";\n\n /**\n * Cookie path\n */\n public path = \"\";\n\n /**\n * Cookie value\n */\n public value = \"\";\n\n /**\n * Optional comment\n */\n public comment?: string;\n\n /**\n * Optional comment URL\n */\n public commentURL?: string;\n\n /**\n * Cookie flags (secure, httpOnly, etc.)\n */\n public flags: BinaryCodableFlags = {\n isSecure: false,\n isHTTPOnly: false,\n unknown1: false,\n unknown2: false,\n };\n\n /**\n * Expiration timestamp (Mac epoch seconds)\n */\n public expiration = 0;\n\n /**\n * Creation timestamp (Mac epoch seconds)\n */\n public creation = 0;\n\n /**\n * Creates a new Cookie instance from a buffer\n * @param buffer - The raw binary cookie data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Decode URL encoded values with multiple passes\n * @param value - The URL encoded string\n * @returns Decoded string\n */\n private decodeUrlValue(value: string): string {\n let processed = value;\n let lastProcessed: string;\n do {\n lastProcessed = processed;\n try {\n processed = decodeURIComponent(processed);\n } catch {\n return lastProcessed;\n }\n } while (processed !== lastProcessed && processed.includes(\"%\"));\n return processed;\n }\n\n /**\n * Decode JWT payload if the value is a valid JWT token\n * @param token - The JWT token string\n * @returns Decoded payload as JSON string or null if invalid\n */\n private decodeJwtPayload(token: string): string | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const payloadPart = parts[1];\n if (!payloadPart) {\n return null;\n }\n const payload = Buffer.from(payloadPart, \"base64\").toString(\"utf8\");\n const parsed = JSON.parse(payload) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n /**\n * Parse JSON value and return formatted JSON string\n * @param value - The JSON string to parse\n * @returns Formatted JSON string or null if invalid\n */\n private parseJsonValue(value: string): string | null {\n try {\n const parsed = JSON.parse(value) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n /**\n * Process cookie value with appropriate decoding\n * @param value - The raw cookie value\n * @returns Processed and decoded value as string\n */\n private processValue(value: unknown): string {\n // Handle non-string values\n const primitiveResult = this.handlePrimitiveValues(value);\n if (primitiveResult !== null) {\n return primitiveResult;\n }\n\n // Must be a string at this point\n const stringValue = value as string;\n\n // First, try URL decoding\n const decoded = this.decodeUrlValue(stringValue);\n\n // Try specialized decoding\n return this.trySpecializedDecoding(decoded);\n }\n\n /**\n * Handle primitive value types (null, undefined, buffer, non-string)\n * @param value - The value to check\n * @returns String representation or null if not a primitive type\n */\n private handlePrimitiveValues(value: unknown): string | null {\n if (value === null) {\n return \"null\";\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (Buffer.isBuffer(value)) {\n return value.toString();\n }\n\n if (typeof value !== \"string\") {\n return this.safeStringify(value);\n }\n\n return null; // Not a primitive type\n }\n\n /**\n * Try specialized decoding (JWT, JSON) on the decoded string\n * @param decoded - The URL-decoded string\n * @returns Specialized decoded value or the original decoded string\n */\n private trySpecializedDecoding(decoded: string): string {\n // Try JWT decoding if it looks like a JWT token\n const jwtResult = this.tryJwtDecoding(decoded);\n if (jwtResult !== null) {\n return jwtResult;\n }\n\n // Try JSON parsing if it looks like JSON\n const jsonResult = this.tryJsonDecoding(decoded);\n if (jsonResult !== null) {\n return jsonResult;\n }\n\n return decoded;\n }\n\n /**\n * Try JWT decoding if the value looks like a JWT token\n * @param decoded - The decoded string to check\n * @returns Decoded JWT payload or null if not a JWT or decoding failed\n */\n private tryJwtDecoding(decoded: string): string | null {\n if (decoded.match(/^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/)) {\n const jwtPayload = this.decodeJwtPayload(decoded);\n if (typeof jwtPayload === \"string\" && jwtPayload.length > 0) {\n return jwtPayload;\n }\n }\n return null;\n }\n\n /**\n * Try JSON decoding if the value looks like JSON\n * @param decoded - The decoded string to check\n * @returns Decoded JSON string or null if not JSON or decoding failed\n */\n private tryJsonDecoding(decoded: string): string | null {\n if (decoded.startsWith(\"{\") || decoded.startsWith(\"[\")) {\n const jsonValue = this.parseJsonValue(decoded);\n if (typeof jsonValue === \"string\" && jsonValue.length > 0) {\n return jsonValue;\n }\n }\n return null;\n }\n\n /**\n * Safely convert unknown value to string\n * @param value - The value to stringify\n * @returns String representation of the value\n */\n private safeStringify(value: unknown): string {\n try {\n if (typeof value === \"object\" && value !== null) {\n // For objects, use JSON.stringify if possible, otherwise use toString\n return JSON.stringify(value);\n }\n return String(value);\n } catch {\n // Fallback to String() if JSON.stringify fails\n return String(value);\n }\n }\n\n /**\n * Validates and converts Mac epoch timestamp to Unix epoch\n * @param macTimestamp - Timestamp in Mac epoch (seconds since 2001-01-01)\n * @returns Unix epoch timestamp or 0 for invalid timestamps\n */\n private convertMacTimestamp(macTimestamp: number): number {\n const macToUnixOffset = 978307200; // Seconds between 1970-01-01 and 2001-01-01\n\n if (macTimestamp <= 0) {\n return macTimestamp;\n }\n\n // Validate timestamp bounds - reasonable range is 0 to ~1 billion seconds (2032)\n const isValid =\n macTimestamp >= 0 &&\n macTimestamp <= 1000000000 &&\n Number.isFinite(macTimestamp);\n\n return isValid ? macTimestamp + macToUnixOffset : 0;\n }\n\n /**\n * Converts the cookie to a validated cookie row\n * @returns Validated cookie row object or null if validation fails\n */\n public toCookieRow(): BinaryCookieRow | null {\n try {\n // Convert flags to number\n const flagsValue = this.convertFlags();\n\n // Extract domain from URL\n const domain =\n this.url.replace(/^https?:\\/\\//, \"\").replace(/\\/.*$/, \"\") || \"uk\";\n\n // Convert timestamps from Mac epoch to Unix epoch with validation\n const expiryUnix = this.convertMacTimestamp(this.expiration);\n const creationUnix = this.convertMacTimestamp(this.creation);\n\n // Create cookie row with converted timestamps\n const cookieRow = BinaryCookieRowSchema.parse({\n name: this.name.replace(/^: /, \"\"), // Remove leading ': ' if present\n value: this.processValue(this.value) || \"\", // Process and ensure value is never undefined\n domain,\n path: this.path || \"/\",\n expiry: expiryUnix,\n creation: creationUnix,\n flags: flagsValue,\n version: this.version,\n port: this.port,\n comment: this.comment,\n commentURL: this.commentURL,\n });\n\n return cookieRow;\n } catch (_error) {\n return null;\n }\n }\n\n /**\n * Read the cookie header information\n * @param container - The binary container\n * @returns Object containing size, port flag, and string offsets\n */\n private readHeader(container: BinaryCodableContainer): {\n size: number;\n hasPort: number;\n offsets: BinaryCodableOffsets;\n } {\n // Cookie size (4 bytes)\n const size = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie size:\", size);\n container.offset += 4;\n\n // Version (4 bytes)\n const version = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie version:\", version);\n container.offset += 4;\n\n // Cookie flags (4 bytes)\n const flagsValue = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie flags:\", flagsValue.toString(2).padStart(8, \"0\"));\n container.offset += 4;\n this.flags = {\n isSecure: (flagsValue & 1) !== 0,\n isHTTPOnly: (flagsValue & 4) !== 0,\n unknown1: (flagsValue & 8) !== 0,\n unknown2: (flagsValue & 16) !== 0,\n };\n\n // Has port (4 bytes)\n const hasPort = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Has port:\", hasPort);\n container.offset += 4;\n\n // String offsets (24 bytes total)\n const offsets = {\n urlOffset: container.buffer.readUInt32LE(container.offset),\n nameOffset: container.buffer.readUInt32LE(container.offset + 4),\n pathOffset: container.buffer.readUInt32LE(container.offset + 8),\n valueOffset: container.buffer.readUInt32LE(container.offset + 12),\n commentOffset: container.buffer.readUInt32LE(container.offset + 16),\n commentURLOffset: container.buffer.readUInt32LE(container.offset + 20),\n };\n logger.debug(\"String offsets:\", offsets);\n\n return { size, hasPort, offsets };\n }\n\n /**\n * Read expiration and creation timestamps from the container\n * @param container - The binary container\n */\n private readTimestamps(container: BinaryCodableContainer): void {\n // Read expiration time (8 bytes, little-endian double)\n const expirationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n expirationBuffer[i] = container.buffer[container.offset + i]!;\n }\n const expiration = expirationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Read creation time (8 bytes, little-endian double)\n const creationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n creationBuffer[i] = container.buffer[container.offset + i]!;\n }\n const creation = creationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Store raw timestamps (seconds since 2001-01-01)\n // For expiration time, 0 means \"session cookie\" (expires when browser closes)\n // For creation time, 0 means \"no creation time recorded\"\n this.expiration = expiration;\n this.creation = creation;\n }\n\n /**\n * Read cookie string fields from the container\n * @param container - The binary container\n * @param size - Total size of the cookie\n * @param offsets - String field offsets\n */\n private readStrings(\n container: BinaryCodableContainer,\n size: number,\n offsets: BinaryCodableOffsets,\n ): void {\n // All offsets are relative to the start of the cookie\n const cookieStart = 0; // Offsets are relative to the cookie buffer start\n logger.debug(\"Reading strings from cookie buffer of size:\", size);\n\n // Read strings in order of their offsets\n const offsetEntries = [\n { field: \"url\", offset: offsets.urlOffset },\n { field: \"name\", offset: offsets.nameOffset },\n { field: \"path\", offset: offsets.pathOffset },\n { field: \"value\", offset: offsets.valueOffset },\n { field: \"comment\", offset: offsets.commentOffset },\n ]\n .filter((entry) => entry.offset > 0)\n .sort((a, b) => a.offset - b.offset);\n\n logger.debug(\n \"Reading strings in order:\",\n offsetEntries.map((e) => e.field),\n );\n\n // Calculate string lengths based on offset differences\n for (let i = 0; i < offsetEntries.length; i++) {\n const entry = offsetEntries[i]!;\n const { field, offset } = entry;\n const nextOffset =\n i < offsetEntries.length - 1 ? offsetEntries[i + 1]!.offset : size;\n const length = nextOffset - offset;\n\n // Read string up to null terminator\n let end = cookieStart + offset;\n while (\n end < cookieStart + offset + length &&\n container.buffer[end] !== 0\n ) {\n end++;\n }\n const value = container.buffer.toString(\n \"utf8\",\n cookieStart + offset,\n end,\n );\n logger.debug(`Read ${field}:`, value);\n\n switch (field) {\n case \"url\":\n this.url = value;\n break;\n case \"name\":\n this.name = value;\n break;\n case \"path\":\n this.path = value;\n break;\n case \"value\":\n this.value = value;\n break;\n case \"comment\":\n this.comment = value;\n break;\n }\n }\n }\n\n /**\n * Decode the cookie from the binary container\n * @param container - The binary container with cookie data\n */\n private decode(container: BinaryCodableContainer): void {\n const { size, hasPort, offsets } = this.readHeader(container);\n\n // Skip past all offsets (24 bytes)\n const baseOffset = container.offset;\n container.offset = baseOffset + 24;\n\n this.readTimestamps(container);\n\n if (hasPort > 0) {\n this.port = container.buffer.readUInt16LE(container.offset);\n container.offset += 2;\n }\n\n // Reset offset for string reading\n container.offset = baseOffset;\n this.readStrings(container, size, offsets);\n }\n\n /**\n * Convert cookie flags to numeric representation\n * @returns Numeric flags value\n */\n private convertFlags(): number {\n return (\n (this.flags.isSecure ? 0x1 : 0) |\n (this.flags.isHTTPOnly ? 0x4 : 0) |\n (this.flags.unknown1 ? 0x8 : 0) |\n (this.flags.unknown2 ? 0x10 : 0)\n );\n }\n}\n","import type { BinaryCookieRow } from \"../../../types/schemas\";\n\nimport { BinaryCodableCookies } from \"./BinaryCodableCookies\";\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromFile(cookieDbPath);\n return cookies.toCookieRows();\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromDefaultPath();\n return cookies.toCookieRows();\n}\n","/**\n * CLI adapter for browser cookie query strategies\n * Delegates to core browser modules for actual functionality\n */\n\nimport { detectBrowserFromStore } from \"@core/browsers/BrowserDetector\";\nimport {\n type AnyQueryStrategy,\n createStrategy as createCoreStrategy,\n} from \"@core/browsers/StrategyFactory\";\n\n/**\n * Represents a strategy for querying cookies from a browser\n * This is a type alias for the base strategy to maintain backward compatibility\n */\nexport type CookieQueryStrategy = AnyQueryStrategy;\n\n/**\n * Factory for creating browser-specific cookie query strategies\n * This is now a thin wrapper around the core StrategyFactory\n */\nexport const CookieStrategyFactory = {\n /**\n * Detects the cookie store type from a file path\n * @param storePath - Path to the cookie store file\n * @returns The detected browser type or undefined\n * @deprecated Use detectBrowserFromStore from @core/browsers/BrowserDetector\n */\n detectStoreType(storePath: string): string | undefined {\n return detectBrowserFromStore(storePath);\n },\n\n /**\n * Creates a strategy for the specified browser\n * @param browser - The browser to create a strategy for\n * @param storePath - Optional path to a cookie store file\n * @param profile - Optional Chrome profile name\n * @returns A cookie query strategy for the specified browser\n */\n createStrategy(\n browser?: string,\n storePath?: string,\n profile?: string,\n ): CookieQueryStrategy {\n // Delegate to the core strategy factory\n // Only pass defined values to avoid exactOptionalPropertyTypes issues\n const options: Parameters<typeof createCoreStrategy>[0] = {};\n if (browser !== undefined) {\n options.browser = browser;\n }\n if (storePath !== undefined) {\n options.storePath = storePath;\n }\n if (profile !== undefined) {\n options.profile = profile;\n }\n return createCoreStrategy(options);\n },\n};\n"]}