#!/usr/bin/env node
/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 634:
/***/ ((module) => {

module.exports = require("open");

/***/ }),

/***/ 269:
/***/ ((module) => {

module.exports = require("url");

/***/ }),

/***/ 147:
/***/ ((module) => {

module.exports = JSON.parse('{"name":"@bitwarden/cli","description":"A secure and free password manager for all of your devices.","version":"2023.2.0","keywords":["bitwarden","password","vault","password manager","cli"],"author":"Bitwarden Inc. <hello@bitwarden.com> (https://bitwarden.com)","homepage":"https://bitwarden.com","repository":{"type":"git","url":"https://github.com/bitwarden/clients"},"license":"GPL-3.0-only","scripts":{"clean":"rimraf dist/**/*","build":"webpack","build:debug":"npm run build && node --inspect ./build/bw.js","build:watch":"webpack --watch","build:prod":"cross-env NODE_ENV=production webpack","build:prod:watch":"cross-env NODE_ENV=production webpack --watch","package":"npm run package:win && npm run package:mac && npm run package:lin","package:win":"pkg . --targets win-x64 --output ./dist/windows/bw.exe --build","package:mac":"pkg . --targets macos-x64 --output ./dist/macos/bw","package:lin":"pkg . --targets linux-x64 --output ./dist/linux/bw","debug":"node --inspect ./build/bw.js","dist":"npm run build:prod && npm run clean && npm run package","dist:win":"npm run build:prod && npm run clean && npm run package:win","dist:mac":"npm run build:prod && npm run clean && npm run package:mac","dist:lin":"npm run build:prod && npm run clean && npm run package:lin","publish:npm":"npm run build:prod && npm publish --access public","test":"jest","test:watch":"jest --watch","test:watch:all":"jest --watchAll"},"bin":{"bw":"build/bw.js"},"pkg":{"assets":["./build/**/*","../../node_modules/argon2/**/*"]},"dependencies":{"@koa/multer":"^3.0.0","@koa/router":"^10.1.1","argon2":"^0.30.3","big-integer":"^1.6.51","browser-hrtime":"^1.1.8","chalk":"^4.1.1","commander":"7.2.0","form-data":"4.0.0","https-proxy-agent":"5.0.0","inquirer":"8.0.0","jsdom":"^16.7.0","jszip":"^3.10.0","koa":"^2.13.4","koa-bodyparser":"^4.3.0","koa-json":"^2.0.2","lowdb":"1.0.0","lunr":"^2.3.9","multer":"^1.4.5-lts.1","node-fetch":"^2.6.7","node-forge":"1.3.1","open":"^8.4.0","papaparse":"^5.3.2","proper-lockfile":"^4.1.2","rxjs":"^7.5.5","tldts":"^5.7.84","zxcvbn":"^4.4.2"}}');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// UNUSED EXPORTS: Main

;// CONCATENATED MODULE: external "fs"
const external_fs_namespaceObject = require("fs");
;// CONCATENATED MODULE: external "path"
const external_path_namespaceObject = require("path");
;// CONCATENATED MODULE: external "commander"
const external_commander_namespaceObject = require("commander");
;// CONCATENATED MODULE: external "jsdom"
const external_jsdom_namespaceObject = require("jsdom");
;// CONCATENATED MODULE: ../../libs/common/src/enums/clientType.ts
var ClientType;
(function (ClientType) {
    ClientType["Web"] = "web";
    ClientType["Browser"] = "browser";
    ClientType["Desktop"] = "desktop";
    ClientType["Mobile"] = "mobile";
    ClientType["Cli"] = "cli";
    ClientType["DirectoryConnector"] = "connector";
})(ClientType || (ClientType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/keySuffixOptions.ts
var KeySuffixOptions;
(function (KeySuffixOptions) {
    KeySuffixOptions["Auto"] = "auto";
    KeySuffixOptions["Biometric"] = "biometric";
})(KeySuffixOptions || (KeySuffixOptions = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/logLevelType.ts
var LogLevelType;
(function (LogLevelType) {
    LogLevelType[LogLevelType["Debug"] = 0] = "Debug";
    LogLevelType[LogLevelType["Info"] = 1] = "Info";
    LogLevelType[LogLevelType["Warning"] = 2] = "Warning";
    LogLevelType[LogLevelType["Error"] = 3] = "Error";
})(LogLevelType || (LogLevelType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/factories/accountFactory.ts
class AccountFactory {
    constructor(accountConstructor) {
        this.accountConstructor = accountConstructor;
    }
    create(args) {
        return new this.accountConstructor(args);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/factories/globalStateFactory.ts
class GlobalStateFactory {
    constructor(globalStateConstructor) {
        this.globalStateConstructor = globalStateConstructor;
    }
    create(args) {
        return new this.globalStateConstructor(args);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/factories/stateFactory.ts


class StateFactory {
    constructor(globalStateConstructor, accountConstructor) {
        this.globalStateFactory = new GlobalStateFactory(globalStateConstructor);
        this.accountFactory = new AccountFactory(accountConstructor);
    }
    createGlobal(args) {
        return this.globalStateFactory.create(args);
    }
    createAccount(args) {
        return this.accountFactory.create(args);
    }
}

;// CONCATENATED MODULE: external "tldts"
const external_tldts_namespaceObject = require("tldts");
;// CONCATENATED MODULE: ../../libs/common/src/misc/utils.ts
/* eslint-disable no-useless-escape */


const nodeURL = typeof window === "undefined" ? __webpack_require__(269) : null;
class Utils {
    static init() {
        if (Utils.inited) {
            return;
        }
        Utils.inited = true;
        Utils.isNode =
            typeof process !== "undefined" &&
                process.release != null &&
                process.release.name === "node";
        Utils.isBrowser = typeof window !== "undefined";
        Utils.isMobileBrowser = Utils.isBrowser && this.isMobile(window);
        Utils.isAppleMobileBrowser = Utils.isBrowser && this.isAppleMobile(window);
        if (Utils.isNode) {
            Utils.global = global;
        }
        else if (Utils.isBrowser) {
            Utils.global = window;
        }
        else {
            // If it's not browser or node then it must be a service worker
            Utils.global = self;
        }
    }
    static fromB64ToArray(str) {
        if (str == null) {
            return null;
        }
        if (Utils.isNode) {
            return new Uint8Array(Buffer.from(str, "base64"));
        }
        else {
            const binaryString = Utils.global.atob(str);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            return bytes;
        }
    }
    static fromUrlB64ToArray(str) {
        return Utils.fromB64ToArray(Utils.fromUrlB64ToB64(str));
    }
    static fromHexToArray(str) {
        if (Utils.isNode) {
            return new Uint8Array(Buffer.from(str, "hex"));
        }
        else {
            const bytes = new Uint8Array(str.length / 2);
            for (let i = 0; i < str.length; i += 2) {
                bytes[i / 2] = parseInt(str.substr(i, 2), 16);
            }
            return bytes;
        }
    }
    static fromUtf8ToArray(str) {
        if (Utils.isNode) {
            return new Uint8Array(Buffer.from(str, "utf8"));
        }
        else {
            const strUtf8 = unescape(encodeURIComponent(str));
            const arr = new Uint8Array(strUtf8.length);
            for (let i = 0; i < strUtf8.length; i++) {
                arr[i] = strUtf8.charCodeAt(i);
            }
            return arr;
        }
    }
    static fromByteStringToArray(str) {
        if (str == null) {
            return null;
        }
        const arr = new Uint8Array(str.length);
        for (let i = 0; i < str.length; i++) {
            arr[i] = str.charCodeAt(i);
        }
        return arr;
    }
    static fromBufferToB64(buffer) {
        if (buffer == null) {
            return null;
        }
        if (Utils.isNode) {
            return Buffer.from(buffer).toString("base64");
        }
        else {
            let binary = "";
            const bytes = new Uint8Array(buffer);
            for (let i = 0; i < bytes.byteLength; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return Utils.global.btoa(binary);
        }
    }
    static fromBufferToUrlB64(buffer) {
        return Utils.fromB64toUrlB64(Utils.fromBufferToB64(buffer));
    }
    static fromB64toUrlB64(b64Str) {
        return b64Str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
    }
    static fromBufferToUtf8(buffer) {
        if (Utils.isNode) {
            return Buffer.from(buffer).toString("utf8");
        }
        else {
            const bytes = new Uint8Array(buffer);
            const encodedString = String.fromCharCode.apply(null, bytes);
            return decodeURIComponent(escape(encodedString));
        }
    }
    static fromBufferToByteString(buffer) {
        return String.fromCharCode.apply(null, new Uint8Array(buffer));
    }
    // ref: https://stackoverflow.com/a/40031979/1090359
    static fromBufferToHex(buffer) {
        if (Utils.isNode) {
            return Buffer.from(buffer).toString("hex");
        }
        else {
            const bytes = new Uint8Array(buffer);
            return Array.prototype.map
                .call(bytes, (x) => ("00" + x.toString(16)).slice(-2))
                .join("");
        }
    }
    static fromUrlB64ToB64(urlB64Str) {
        let output = urlB64Str.replace(/-/g, "+").replace(/_/g, "/");
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += "==";
                break;
            case 3:
                output += "=";
                break;
            default:
                throw new Error("Illegal base64url string!");
        }
        return output;
    }
    static fromUrlB64ToUtf8(urlB64Str) {
        return Utils.fromB64ToUtf8(Utils.fromUrlB64ToB64(urlB64Str));
    }
    static fromUtf8ToB64(utfStr) {
        if (Utils.isNode) {
            return Buffer.from(utfStr, "utf8").toString("base64");
        }
        else {
            return decodeURIComponent(escape(Utils.global.btoa(utfStr)));
        }
    }
    static fromUtf8ToUrlB64(utfStr) {
        return Utils.fromBufferToUrlB64(Utils.fromUtf8ToArray(utfStr));
    }
    static fromB64ToUtf8(b64Str) {
        if (Utils.isNode) {
            return Buffer.from(b64Str, "base64").toString("utf8");
        }
        else {
            return decodeURIComponent(escape(Utils.global.atob(b64Str)));
        }
    }
    // ref: http://stackoverflow.com/a/2117523/1090359
    static newGuid() {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
            const r = (Math.random() * 16) | 0;
            const v = c === "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }
    static isGuid(id) {
        return RegExp(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, "i").test(id);
    }
    static getHostname(uriString) {
        if (Utils.isNullOrWhitespace(uriString)) {
            return null;
        }
        uriString = uriString.trim();
        if (uriString.startsWith("data:")) {
            return null;
        }
        if (uriString.startsWith("about:")) {
            return null;
        }
        if (uriString.startsWith("file:")) {
            return null;
        }
        // Does uriString contain invalid characters
        // TODO Needs to possibly be extended, although '!' is a reserved character
        if (uriString.indexOf("!") > 0) {
            return null;
        }
        try {
            const hostname = (0,external_tldts_namespaceObject.getHostname)(uriString, { validHosts: this.validHosts });
            if (hostname != null) {
                return hostname;
            }
        }
        catch (_a) {
            return null;
        }
        return null;
    }
    static getHost(uriString) {
        const url = Utils.getUrl(uriString);
        try {
            return url != null && url.host !== "" ? url.host : null;
        }
        catch (_a) {
            return null;
        }
    }
    static getDomain(uriString) {
        if (Utils.isNullOrWhitespace(uriString)) {
            return null;
        }
        uriString = uriString.trim();
        if (uriString.startsWith("data:")) {
            return null;
        }
        if (uriString.startsWith("about:")) {
            return null;
        }
        try {
            const parseResult = (0,external_tldts_namespaceObject.parse)(uriString, { validHosts: this.validHosts });
            if (parseResult != null && parseResult.hostname != null) {
                if (parseResult.hostname === "localhost" || parseResult.isIp) {
                    return parseResult.hostname;
                }
                if (parseResult.domain != null) {
                    return parseResult.domain;
                }
                return null;
            }
        }
        catch (_a) {
            return null;
        }
        return null;
    }
    static getQueryParams(uriString) {
        const url = Utils.getUrl(uriString);
        if (url == null || url.search == null || url.search === "") {
            return null;
        }
        const map = new Map();
        const pairs = (url.search[0] === "?" ? url.search.substr(1) : url.search).split("&");
        pairs.forEach((pair) => {
            const parts = pair.split("=");
            if (parts.length < 1) {
                return;
            }
            map.set(decodeURIComponent(parts[0]).toLowerCase(), parts[1] == null ? "" : decodeURIComponent(parts[1]));
        });
        return map;
    }
    static getSortFunction(i18nService, prop) {
        return (a, b) => {
            if (a[prop] == null && b[prop] != null) {
                return -1;
            }
            if (a[prop] != null && b[prop] == null) {
                return 1;
            }
            if (a[prop] == null && b[prop] == null) {
                return 0;
            }
            // The `as unknown as string` here is unfortunate because typescript doesn't property understand that the return of T[prop] will be a string
            return i18nService.collator
                ? i18nService.collator.compare(a[prop], b[prop])
                : a[prop].localeCompare(b[prop]);
        };
    }
    static isNullOrWhitespace(str) {
        return str == null || typeof str !== "string" || str.trim() === "";
    }
    static isNullOrEmpty(str) {
        return str == null || typeof str !== "string" || str == "";
    }
    static isPromise(obj) {
        return (obj != undefined && typeof obj["then"] === "function" && typeof obj["catch"] === "function");
    }
    static nameOf(name) {
        return name;
    }
    static assign(target, source) {
        return Object.assign(target, source);
    }
    static iterateEnum(obj) {
        return Object.keys(obj).filter((k) => Number.isNaN(+k)).map((k) => obj[k]);
    }
    static getUrl(uriString) {
        if (this.isNullOrWhitespace(uriString)) {
            return null;
        }
        uriString = uriString.trim();
        let url = Utils.getUrlObject(uriString);
        if (url == null) {
            const hasHttpProtocol = uriString.indexOf("http://") === 0 || uriString.indexOf("https://") === 0;
            if (!hasHttpProtocol && uriString.indexOf(".") > -1) {
                url = Utils.getUrlObject("http://" + uriString);
            }
        }
        return url;
    }
    static camelToPascalCase(s) {
        return s.charAt(0).toUpperCase() + s.slice(1);
    }
    /**
     * There are a few ways to calculate text color for contrast, this one seems to fit accessibility guidelines best.
     * https://stackoverflow.com/a/3943023/6869691
     *
     * @param {string} bgColor
     * @param {number} [threshold] see stackoverflow link above
     * @param {boolean} [svgTextFill]
     * Indicates if this method is performed on an SVG <text> 'fill' attribute (e.g. <text fill="black"></text>).
     * This check is necessary because the '!important' tag cannot be used in a 'fill' attribute.
     */
    static pickTextColorBasedOnBgColor(bgColor, threshold = 186, svgTextFill = false) {
        const bgColorHexNums = bgColor.charAt(0) === "#" ? bgColor.substring(1, 7) : bgColor;
        const r = parseInt(bgColorHexNums.substring(0, 2), 16); // hexToR
        const g = parseInt(bgColorHexNums.substring(2, 4), 16); // hexToG
        const b = parseInt(bgColorHexNums.substring(4, 6), 16); // hexToB
        const blackColor = svgTextFill ? "black" : "black !important";
        const whiteColor = svgTextFill ? "white" : "white !important";
        return r * 0.299 + g * 0.587 + b * 0.114 > threshold ? blackColor : whiteColor;
    }
    static stringToColor(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        let color = "#";
        for (let i = 0; i < 3; i++) {
            const value = (hash >> (i * 8)) & 0xff;
            color += ("00" + value.toString(16)).substr(-2);
        }
        return color;
    }
    /**
     * @throws Will throw an error if the ContainerService has not been attached to the window object
     */
    static getContainerService() {
        if (this.global.bitwardenContainerService == null) {
            throw new Error("global bitwardenContainerService not initialized.");
        }
        return this.global.bitwardenContainerService;
    }
    static validateHexColor(color) {
        return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color);
    }
    /**
     * Converts map to a Record<string, V> with the same data. Inverse of recordToMap
     * Useful in toJSON methods, since Maps are not serializable
     * @param map
     * @returns
     */
    static mapToRecord(map) {
        if (map == null) {
            return null;
        }
        if (!(map instanceof Map)) {
            return map;
        }
        return Object.fromEntries(map);
    }
    /**
     * Converts record to a Map<string, V> with the same data. Inverse of mapToRecord
     * Useful in fromJSON methods, since Maps are not serializable
     *
     * Warning: If the record has string keys that are numbers, they will be converted to numbers in the map
     * @param record
     * @returns
     */
    static recordToMap(record) {
        if (record == null) {
            return null;
        }
        else if (record instanceof Map) {
            return record;
        }
        const entries = Object.entries(record);
        if (entries.length === 0) {
            return new Map();
        }
        if (isNaN(Number(entries[0][0]))) {
            return new Map(entries);
        }
        else {
            return new Map(entries.map((e) => [Number(e[0]), e[1]]));
        }
    }
    /** Applies Object.assign, but converts the type nicely using Type-Fest Merge<Destination, Source> */
    static merge(destination, source) {
        return Object.assign(destination, source);
    }
    /**
     * encodeURIComponent escapes all characters except the following:
     * alphabetic, decimal digits, - _ . ! ~ * ' ( )
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#encoding_for_rfc3986
     */
    static encodeRFC3986URIComponent(str) {
        return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
    }
    /**
     * Normalizes a path for defense against attacks like traversals
     * @param denormalizedPath
     * @returns
     */
    static normalizePath(denormalizedPath) {
        return external_path_namespaceObject.normalize(decodeURIComponent(denormalizedPath)).replace(/^(\.\.(\/|\\|$))+/, "");
    }
    static isMobile(win) {
        let mobile = false;
        ((a) => {
            if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) ||
                /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
                mobile = true;
            }
        })(win.navigator.userAgent || win.navigator.vendor || win.opera);
        return mobile || win.navigator.userAgent.match(/iPad/i) != null;
    }
    static delay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    static isAppleMobile(win) {
        return (win.navigator.userAgent.match(/iPhone/i) != null ||
            win.navigator.userAgent.match(/iPad/i) != null);
    }
    static getUrlObject(uriString) {
        try {
            if (nodeURL != null) {
                return new nodeURL.URL(uriString);
            }
            else if (typeof URL === "function") {
                return new URL(uriString);
            }
            else if (typeof window !== "undefined") {
                const hasProtocol = uriString.indexOf("://") > -1;
                if (!hasProtocol && uriString.indexOf(".") > -1) {
                    uriString = "http://" + uriString;
                }
                else if (!hasProtocol) {
                    return null;
                }
                const anchor = window.document.createElement("a");
                anchor.href = uriString;
                return anchor;
            }
        }
        catch (e) {
            // Ignore error
        }
        return null;
    }
}
Utils.inited = false;
Utils.isNode = false;
Utils.isBrowser = true;
Utils.isMobileBrowser = false;
Utils.isAppleMobileBrowser = false;
Utils.global = null;
// Transpiled version of /\p{Emoji_Presentation}/gu using https://mothereff.in/regexpu. Used for compatability in older browsers.
Utils.regexpEmojiPresentation = /(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])/g;
Utils.validHosts = ["localhost"];
Utils.init();

;// CONCATENATED MODULE: ../../libs/common/src/models/data/server-config.data.ts
class ServerConfigData {
    constructor(serverConfigResponse) {
        this.version = serverConfigResponse === null || serverConfigResponse === void 0 ? void 0 : serverConfigResponse.version;
        this.gitHash = serverConfigResponse === null || serverConfigResponse === void 0 ? void 0 : serverConfigResponse.gitHash;
        this.server = (serverConfigResponse === null || serverConfigResponse === void 0 ? void 0 : serverConfigResponse.server)
            ? new ThirdPartyServerConfigData(serverConfigResponse.server)
            : null;
        this.utcDate = new Date().toISOString();
        this.environment = (serverConfigResponse === null || serverConfigResponse === void 0 ? void 0 : serverConfigResponse.environment)
            ? new EnvironmentServerConfigData(serverConfigResponse.environment)
            : null;
    }
    static fromJSON(obj) {
        return Object.assign(new ServerConfigData({}), obj, {
            server: (obj === null || obj === void 0 ? void 0 : obj.server) ? ThirdPartyServerConfigData.fromJSON(obj.server) : null,
            environment: (obj === null || obj === void 0 ? void 0 : obj.environment) ? EnvironmentServerConfigData.fromJSON(obj.environment) : null,
        });
    }
}
class ThirdPartyServerConfigData {
    constructor(response) {
        this.name = response.name;
        this.url = response.url;
    }
    static fromJSON(obj) {
        return Object.assign(new ThirdPartyServerConfigData({}), obj);
    }
}
class EnvironmentServerConfigData {
    constructor(response) {
        this.vault = response.vault;
        this.api = response.api;
        this.identity = response.identity;
        this.notifications = response.notifications;
        this.sso = response.sso;
    }
    static fromJSON(obj) {
        return Object.assign(new EnvironmentServerConfigData({}), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/encryptionType.ts
var EncryptionType;
(function (EncryptionType) {
    EncryptionType[EncryptionType["AesCbc256_B64"] = 0] = "AesCbc256_B64";
    EncryptionType[EncryptionType["AesCbc128_HmacSha256_B64"] = 1] = "AesCbc128_HmacSha256_B64";
    EncryptionType[EncryptionType["AesCbc256_HmacSha256_B64"] = 2] = "AesCbc256_HmacSha256_B64";
    EncryptionType[EncryptionType["Rsa2048_OaepSha256_B64"] = 3] = "Rsa2048_OaepSha256_B64";
    EncryptionType[EncryptionType["Rsa2048_OaepSha1_B64"] = 4] = "Rsa2048_OaepSha1_B64";
    EncryptionType[EncryptionType["Rsa2048_OaepSha256_HmacSha256_B64"] = 5] = "Rsa2048_OaepSha256_HmacSha256_B64";
    EncryptionType[EncryptionType["Rsa2048_OaepSha1_HmacSha256_B64"] = 6] = "Rsa2048_OaepSha1_HmacSha256_B64";
})(EncryptionType || (EncryptionType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/enc-string.ts
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class EncString {
    constructor(encryptedStringOrType, data, iv, mac) {
        if (data != null) {
            this.initFromData(encryptedStringOrType, data, iv, mac);
        }
        else {
            this.initFromEncryptedString(encryptedStringOrType);
        }
    }
    get ivBytes() {
        return this.iv == null ? null : Utils.fromB64ToArray(this.iv).buffer;
    }
    get macBytes() {
        return this.mac == null ? null : Utils.fromB64ToArray(this.mac).buffer;
    }
    get dataBytes() {
        return this.data == null ? null : Utils.fromB64ToArray(this.data).buffer;
    }
    toJSON() {
        return this.encryptedString;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        return new EncString(obj);
    }
    initFromData(encType, data, iv, mac) {
        if (iv != null) {
            this.encryptedString = encType + "." + iv + "|" + data;
        }
        else {
            this.encryptedString = encType + "." + data;
        }
        // mac
        if (mac != null) {
            this.encryptedString += "|" + mac;
        }
        this.encryptionType = encType;
        this.data = data;
        this.iv = iv;
        this.mac = mac;
    }
    initFromEncryptedString(encryptedString) {
        this.encryptedString = encryptedString;
        if (!this.encryptedString) {
            return;
        }
        const { encType, encPieces } = this.parseEncryptedString(this.encryptedString);
        this.encryptionType = encType;
        switch (encType) {
            case EncryptionType.AesCbc128_HmacSha256_B64:
            case EncryptionType.AesCbc256_HmacSha256_B64:
                if (encPieces.length !== 3) {
                    return;
                }
                this.iv = encPieces[0];
                this.data = encPieces[1];
                this.mac = encPieces[2];
                break;
            case EncryptionType.AesCbc256_B64:
                if (encPieces.length !== 2) {
                    return;
                }
                this.iv = encPieces[0];
                this.data = encPieces[1];
                break;
            case EncryptionType.Rsa2048_OaepSha256_B64:
            case EncryptionType.Rsa2048_OaepSha1_B64:
                if (encPieces.length !== 1) {
                    return;
                }
                this.data = encPieces[0];
                break;
            default:
                return;
        }
    }
    parseEncryptedString(encryptedString) {
        const headerPieces = encryptedString.split(".");
        let encType;
        let encPieces = null;
        if (headerPieces.length === 2) {
            try {
                encType = parseInt(headerPieces[0], null);
                encPieces = headerPieces[1].split("|");
            }
            catch (e) {
                return;
            }
        }
        else {
            encPieces = encryptedString.split("|");
            encType =
                encPieces.length === 3
                    ? EncryptionType.AesCbc128_HmacSha256_B64
                    : EncryptionType.AesCbc256_B64;
        }
        return {
            encType,
            encPieces,
        };
    }
    decrypt(orgId, key = null) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.decryptedValue != null) {
                return this.decryptedValue;
            }
            try {
                if (key == null) {
                    key = yield this.getKeyForDecryption(orgId);
                }
                if (key == null) {
                    throw new Error("No key to decrypt EncString with orgId " + orgId);
                }
                const encryptService = Utils.getContainerService().getEncryptService();
                this.decryptedValue = yield encryptService.decryptToUtf8(this, key);
            }
            catch (e) {
                this.decryptedValue = "[error: cannot decrypt]";
            }
            return this.decryptedValue;
        });
    }
    getKeyForDecryption(orgId) {
        return __awaiter(this, void 0, void 0, function* () {
            const cryptoService = Utils.getContainerService().getCryptoService();
            return orgId != null
                ? yield cryptoService.getOrgKey(orgId)
                : yield cryptoService.getKeyForUserEncryption();
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/environment-urls.ts
class EnvironmentUrls {
    constructor() {
        this.base = null;
        this.api = null;
        this.identity = null;
        this.icons = null;
        this.notifications = null;
        this.events = null;
        this.webVault = null;
        this.keyConnector = null;
    }
    static fromJSON(obj) {
        return Object.assign(new EnvironmentUrls(), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/symmetric-crypto-key.ts


class SymmetricCryptoKey {
    constructor(key, encType) {
        if (key == null) {
            throw new Error("Must provide key");
        }
        if (encType == null) {
            if (key.byteLength === 32) {
                encType = EncryptionType.AesCbc256_B64;
            }
            else if (key.byteLength === 64) {
                encType = EncryptionType.AesCbc256_HmacSha256_B64;
            }
            else {
                throw new Error("Unable to determine encType.");
            }
        }
        this.key = key;
        this.encType = encType;
        if (encType === EncryptionType.AesCbc256_B64 && key.byteLength === 32) {
            this.encKey = key;
            this.macKey = null;
        }
        else if (encType === EncryptionType.AesCbc128_HmacSha256_B64 && key.byteLength === 32) {
            this.encKey = key.slice(0, 16);
            this.macKey = key.slice(16, 32);
        }
        else if (encType === EncryptionType.AesCbc256_HmacSha256_B64 && key.byteLength === 64) {
            this.encKey = key.slice(0, 32);
            this.macKey = key.slice(32, 64);
        }
        else {
            throw new Error("Unsupported encType/key length.");
        }
        if (this.key != null) {
            this.keyB64 = Utils.fromBufferToB64(this.key);
        }
        if (this.encKey != null) {
            this.encKeyB64 = Utils.fromBufferToB64(this.encKey);
        }
        if (this.macKey != null) {
            this.macKeyB64 = Utils.fromBufferToB64(this.macKey);
        }
    }
    toJSON() {
        // The whole object is constructed from the initial key, so just store the B64 key
        return { keyB64: this.keyB64 };
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const arrayBuffer = Utils.fromB64ToArray(obj.keyB64).buffer;
        return new SymmetricCryptoKey(arrayBuffer);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/account.ts





class EncryptionPair {
    toJSON() {
        return {
            encrypted: this.encrypted,
            decrypted: this.decrypted instanceof ArrayBuffer
                ? Utils.fromBufferToByteString(this.decrypted)
                : this.decrypted,
        };
    }
    static fromJSON(obj, decryptedFromJson, encryptedFromJson) {
        if (obj == null) {
            return null;
        }
        const pair = new EncryptionPair();
        if ((obj === null || obj === void 0 ? void 0 : obj.encrypted) != null) {
            pair.encrypted = encryptedFromJson
                ? encryptedFromJson(obj.encrypted)
                : obj.encrypted;
        }
        if ((obj === null || obj === void 0 ? void 0 : obj.decrypted) != null) {
            pair.decrypted = decryptedFromJson
                ? decryptedFromJson(obj.decrypted)
                : obj.decrypted;
        }
        return pair;
    }
}
class DataEncryptionPair {
}
// This is a temporary structure to handle migrated `DataEncryptionPair` to
//  avoid needing a data migration at this stage. It should be replaced with
//  proper data migrations when `DataEncryptionPair` is deprecated.
class TemporaryDataEncryption {
}
class AccountData {
    constructor() {
        this.ciphers = new DataEncryptionPair();
        this.folders = new TemporaryDataEncryption();
        this.sends = new DataEncryptionPair();
        this.collections = new DataEncryptionPair();
        this.policies = new DataEncryptionPair();
        this.passwordGenerationHistory = new EncryptionPair();
    }
}
class AccountKeys {
    constructor() {
        this.cryptoSymmetricKey = new EncryptionPair();
        this.organizationKeys = new EncryptionPair();
        this.providerKeys = new EncryptionPair();
        this.privateKey = new EncryptionPair();
    }
    toJSON() {
        return Utils.merge(this, {
            publicKey: Utils.fromBufferToByteString(this.publicKey),
        });
    }
    static fromJSON(obj) {
        var _a;
        if (obj == null) {
            return null;
        }
        return Object.assign(new AccountKeys(), { cryptoMasterKey: SymmetricCryptoKey.fromJSON(obj === null || obj === void 0 ? void 0 : obj.cryptoMasterKey) }, {
            cryptoSymmetricKey: EncryptionPair.fromJSON(obj === null || obj === void 0 ? void 0 : obj.cryptoSymmetricKey, SymmetricCryptoKey.fromJSON),
        }, { organizationKeys: AccountKeys.initRecordEncryptionPairsFromJSON(obj === null || obj === void 0 ? void 0 : obj.organizationKeys) }, { providerKeys: AccountKeys.initRecordEncryptionPairsFromJSON(obj === null || obj === void 0 ? void 0 : obj.providerKeys) }, {
            privateKey: EncryptionPair.fromJSON(obj === null || obj === void 0 ? void 0 : obj.privateKey, (decObj) => Utils.fromByteStringToArray(decObj).buffer),
        }, {
            publicKey: (_a = Utils.fromByteStringToArray(obj === null || obj === void 0 ? void 0 : obj.publicKey)) === null || _a === void 0 ? void 0 : _a.buffer,
        });
    }
    static initRecordEncryptionPairsFromJSON(obj) {
        return EncryptionPair.fromJSON(obj, (decObj) => {
            if (obj == null) {
                return null;
            }
            const record = {};
            for (const id in decObj) {
                record[id] = SymmetricCryptoKey.fromJSON(decObj[id]);
            }
            return record;
        });
    }
}
class AccountProfile {
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        return Object.assign(new AccountProfile(), obj);
    }
}
class AccountSettings {
    constructor() {
        this.environmentUrls = new EnvironmentUrls();
        this.pinProtected = new EncryptionPair();
        this.vaultTimeoutAction = "lock";
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        return Object.assign(new AccountSettings(), obj, {
            environmentUrls: EnvironmentUrls.fromJSON(obj === null || obj === void 0 ? void 0 : obj.environmentUrls),
            pinProtected: EncryptionPair.fromJSON(obj === null || obj === void 0 ? void 0 : obj.pinProtected, EncString.fromJSON),
            serverConfig: ServerConfigData.fromJSON(obj === null || obj === void 0 ? void 0 : obj.serverConfig),
        });
    }
}
class AccountTokens {
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        return Object.assign(new AccountTokens(), obj);
    }
}
class Account {
    constructor(init) {
        this.data = new AccountData();
        this.keys = new AccountKeys();
        this.profile = new AccountProfile();
        this.settings = new AccountSettings();
        this.tokens = new AccountTokens();
        Object.assign(this, {
            data: Object.assign(Object.assign({}, new AccountData()), init === null || init === void 0 ? void 0 : init.data),
            keys: Object.assign(Object.assign({}, new AccountKeys()), init === null || init === void 0 ? void 0 : init.keys),
            profile: Object.assign(Object.assign({}, new AccountProfile()), init === null || init === void 0 ? void 0 : init.profile),
            settings: Object.assign(Object.assign({}, new AccountSettings()), init === null || init === void 0 ? void 0 : init.settings),
            tokens: Object.assign(Object.assign({}, new AccountTokens()), init === null || init === void 0 ? void 0 : init.tokens),
        });
    }
    static fromJSON(json) {
        if (json == null) {
            return null;
        }
        return Object.assign(new Account({}), json, {
            keys: AccountKeys.fromJSON(json === null || json === void 0 ? void 0 : json.keys),
            profile: AccountProfile.fromJSON(json === null || json === void 0 ? void 0 : json.profile),
            settings: AccountSettings.fromJSON(json === null || json === void 0 ? void 0 : json.settings),
            tokens: AccountTokens.fromJSON(json === null || json === void 0 ? void 0 : json.tokens),
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/stateVersion.ts
var StateVersion;
(function (StateVersion) {
    StateVersion[StateVersion["One"] = 1] = "One";
    StateVersion[StateVersion["Two"] = 2] = "Two";
    StateVersion[StateVersion["Three"] = 3] = "Three";
    StateVersion[StateVersion["Four"] = 4] = "Four";
    StateVersion[StateVersion["Five"] = 5] = "Five";
    StateVersion[StateVersion["Six"] = 6] = "Six";
    StateVersion[StateVersion["Latest"] = 6] = "Latest";
})(StateVersion || (StateVersion = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/themeType.ts
var ThemeType;
(function (ThemeType) {
    ThemeType["System"] = "system";
    ThemeType["Light"] = "light";
    ThemeType["Dark"] = "dark";
    ThemeType["Nord"] = "nord";
    ThemeType["SolarizedDark"] = "solarizedDark";
})(ThemeType || (ThemeType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/window-state.ts
class WindowState {
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/global-state.ts




class GlobalState {
    constructor() {
        this.theme = ThemeType.System;
        this.window = new WindowState();
        this.stateVersion = StateVersion.One;
        this.environmentUrls = new EnvironmentUrls();
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/htmlStorageLocation.ts
var HtmlStorageLocation;
(function (HtmlStorageLocation) {
    HtmlStorageLocation["Local"] = "local";
    HtmlStorageLocation["Memory"] = "memory";
    HtmlStorageLocation["Session"] = "session";
})(HtmlStorageLocation || (HtmlStorageLocation = {}));

;// CONCATENATED MODULE: ../../libs/common/src/services/appId.service.ts
var appId_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class AppIdService {
    constructor(storageService) {
        this.storageService = storageService;
    }
    getAppId() {
        return this.makeAndGetAppId("appId");
    }
    getAnonymousAppId() {
        return this.makeAndGetAppId("anonymousAppId");
    }
    makeAndGetAppId(key) {
        return appId_service_awaiter(this, void 0, void 0, function* () {
            const existingId = yield this.storageService.get(key, {
                htmlStorageLocation: HtmlStorageLocation.Local,
            });
            if (existingId != null) {
                return existingId;
            }
            const guid = Utils.newGuid();
            yield this.storageService.save(key, guid, {
                htmlStorageLocation: HtmlStorageLocation.Local,
            });
            return guid;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/throttle.ts
/**
 * Use as a Decorator on async functions, it will limit how many times the function can be
 * in-flight at a time.
 *
 * Calls beyond the limit will be queued, and run when one of the active calls finishes
 */
function throttle(limit, throttleKey) {
    return (target, propertyKey, descriptor) => {
        const originalMethod = descriptor.value;
        const allThrottles = new Map();
        const getThrottles = (obj) => {
            let throttles = allThrottles.get(obj);
            if (throttles != null) {
                return throttles;
            }
            throttles = new Map();
            allThrottles.set(obj, throttles);
            return throttles;
        };
        return {
            value: function (...args) {
                const throttles = getThrottles(this);
                const argsThrottleKey = throttleKey(args);
                let queue = throttles.get(argsThrottleKey);
                if (queue == null) {
                    queue = [];
                    throttles.set(argsThrottleKey, queue);
                }
                return new Promise((resolve, reject) => {
                    const exec = () => {
                        const onFinally = () => {
                            queue.splice(queue.indexOf(exec), 1);
                            if (queue.length >= limit) {
                                queue[limit - 1]();
                            }
                            else if (queue.length === 0) {
                                throttles.delete(argsThrottleKey);
                                if (throttles.size === 0) {
                                    allThrottles.delete(this);
                                }
                            }
                        };
                        originalMethod
                            .apply(this, args)
                            .then((val) => {
                            onFinally();
                            return val;
                        })
                            .catch((err) => {
                            onFinally();
                            throw err;
                        })
                            .then(resolve, reject);
                    };
                    queue.push(exec);
                    if (queue.length <= limit) {
                        exec();
                    }
                });
            },
        };
    };
}

;// CONCATENATED MODULE: ../../libs/common/src/services/audit.service.ts
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var audit_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


const PwnedPasswordsApi = "https://api.pwnedpasswords.com/range/";
class AuditService {
    constructor(cryptoFunctionService, apiService) {
        this.cryptoFunctionService = cryptoFunctionService;
        this.apiService = apiService;
    }
    passwordLeaked(password) {
        return audit_service_awaiter(this, void 0, void 0, function* () {
            const hashBytes = yield this.cryptoFunctionService.hash(password, "sha1");
            const hash = Utils.fromBufferToHex(hashBytes).toUpperCase();
            const hashStart = hash.substr(0, 5);
            const hashEnding = hash.substr(5);
            const response = yield this.apiService.nativeFetch(new Request(PwnedPasswordsApi + hashStart));
            const leakedHashes = yield response.text();
            const match = leakedHashes.split(/\r?\n/).find((v) => {
                return v.split(":")[0] === hashEnding;
            });
            return match != null ? parseInt(match.split(":")[1], 10) : 0;
        });
    }
    breachedAccounts(username) {
        return audit_service_awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.apiService.getHibpBreach(username);
            }
            catch (e) {
                const error = e;
                if (error.statusCode === 404) {
                    return [];
                }
                throw new Error();
            }
        });
    }
}
__decorate([
    throttle(100, () => "passwordLeaked"),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AuditService.prototype, "passwordLeaked", null);

;// CONCATENATED MODULE: external "rxjs"
const external_rxjs_namespaceObject = require("rxjs");
;// CONCATENATED MODULE: ../../libs/common/src/enums/authenticationStatus.ts
var AuthenticationStatus;
(function (AuthenticationStatus) {
    AuthenticationStatus[AuthenticationStatus["LoggedOut"] = 0] = "LoggedOut";
    AuthenticationStatus[AuthenticationStatus["Locked"] = 1] = "Locked";
    AuthenticationStatus[AuthenticationStatus["Unlocked"] = 2] = "Unlocked";
})(AuthenticationStatus || (AuthenticationStatus = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/authenticationType.ts
var authenticationType_AuthenticationType;
(function (AuthenticationType) {
    AuthenticationType[AuthenticationType["Password"] = 0] = "Password";
    AuthenticationType[AuthenticationType["Sso"] = 1] = "Sso";
    AuthenticationType[AuthenticationType["UserApi"] = 2] = "UserApi";
    AuthenticationType[AuthenticationType["Passwordless"] = 3] = "Passwordless";
})(authenticationType_AuthenticationType || (authenticationType_AuthenticationType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/hashPurpose.ts
var HashPurpose;
(function (HashPurpose) {
    HashPurpose[HashPurpose["ServerAuthorization"] = 1] = "ServerAuthorization";
    HashPurpose[HashPurpose["LocalAuthorization"] = 2] = "LocalAuthorization";
})(HashPurpose || (HashPurpose = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/request/identity-token/token.request.ts
class TokenRequest {
    constructor(twoFactor, device) {
        this.twoFactor = twoFactor;
        this.device = device != null ? device : null;
    }
    // eslint-disable-next-line
    alterIdentityTokenHeaders(headers) {
        // Implemented in subclass if required
    }
    setTwoFactor(twoFactor) {
        this.twoFactor = twoFactor;
    }
    setPasswordlessAccessCode(accessCode) {
        this.passwordlessAuthRequest = accessCode;
    }
    toIdentityToken(clientId) {
        const obj = {
            scope: "api offline_access",
            client_id: clientId,
        };
        if (this.device) {
            obj.deviceType = this.device.type;
            obj.deviceIdentifier = this.device.identifier;
            obj.deviceName = this.device.name;
            // no push tokens for browser apps yet
            // obj.devicePushToken = this.device.pushToken;
        }
        //passswordless login
        if (this.passwordlessAuthRequest) {
            obj.authRequest = this.passwordlessAuthRequest;
        }
        if (this.twoFactor) {
            if (this.twoFactor.token && this.twoFactor.provider != null) {
                obj.twoFactorToken = this.twoFactor.token;
                obj.twoFactorProvider = this.twoFactor.provider;
                obj.twoFactorRemember = this.twoFactor.remember ? "1" : "0";
            }
        }
        return obj;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/identity-token/password-token.request.ts


class PasswordTokenRequest extends TokenRequest {
    constructor(email, masterPasswordHash, captchaResponse, twoFactor, device) {
        super(twoFactor, device);
        this.email = email;
        this.masterPasswordHash = masterPasswordHash;
        this.captchaResponse = captchaResponse;
        this.twoFactor = twoFactor;
    }
    toIdentityToken(clientId) {
        const obj = super.toIdentityToken(clientId);
        obj.grant_type = "password";
        obj.username = this.email;
        obj.password = this.masterPasswordHash;
        if (this.captchaResponse != null) {
            obj.captchaResponse = this.captchaResponse;
        }
        return obj;
    }
    alterIdentityTokenHeaders(headers) {
        headers.set("Auth-Email", Utils.fromUtf8ToUrlB64(this.email));
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/twoFactorProviderType.ts
var TwoFactorProviderType;
(function (TwoFactorProviderType) {
    TwoFactorProviderType[TwoFactorProviderType["Authenticator"] = 0] = "Authenticator";
    TwoFactorProviderType[TwoFactorProviderType["Email"] = 1] = "Email";
    TwoFactorProviderType[TwoFactorProviderType["Duo"] = 2] = "Duo";
    TwoFactorProviderType[TwoFactorProviderType["Yubikey"] = 3] = "Yubikey";
    TwoFactorProviderType[TwoFactorProviderType["U2f"] = 4] = "U2f";
    TwoFactorProviderType[TwoFactorProviderType["Remember"] = 5] = "Remember";
    TwoFactorProviderType[TwoFactorProviderType["OrganizationDuo"] = 6] = "OrganizationDuo";
    TwoFactorProviderType[TwoFactorProviderType["WebAuthn"] = 7] = "WebAuthn";
})(TwoFactorProviderType || (TwoFactorProviderType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/auth-result.ts

class AuthResult {
    constructor() {
        this.captchaSiteKey = "";
        this.resetMasterPassword = false;
        this.forcePasswordReset = false;
        this.twoFactorProviders = null;
    }
    get requiresCaptcha() {
        return !Utils.isNullOrWhitespace(this.captchaSiteKey);
    }
    get requiresTwoFactor() {
        return this.twoFactorProviders != null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/device.request.ts
class DeviceRequest {
    constructor(appId, platformUtilsService) {
        this.type = platformUtilsService.getDevice();
        this.name = platformUtilsService.getDeviceString();
        this.identifier = appId;
        this.pushToken = null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/identity-token/token-two-factor.request.ts
class TokenTwoFactorRequest {
    constructor(provider = null, token = null, remember = false) {
        this.provider = provider;
        this.token = token;
        this.remember = remember;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/keys.request.ts
class KeysRequest {
    constructor(publicKey, encryptedPrivateKey) {
        this.publicKey = publicKey;
        this.encryptedPrivateKey = encryptedPrivateKey;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/base.response.ts
class BaseResponse {
    constructor(response) {
        this.response = response;
    }
    getResponseProperty(propertyName, response = null, exactName = false) {
        if (propertyName == null || propertyName === "") {
            throw new Error("propertyName must not be null/empty.");
        }
        if (response == null && this.response != null) {
            response = this.response;
        }
        if (response == null) {
            return null;
        }
        if (!exactName && response[propertyName] === undefined) {
            let otherCasePropertyName = null;
            if (propertyName.charAt(0) === propertyName.charAt(0).toUpperCase()) {
                otherCasePropertyName = propertyName.charAt(0).toLowerCase();
            }
            else {
                otherCasePropertyName = propertyName.charAt(0).toUpperCase();
            }
            if (propertyName.length > 1) {
                otherCasePropertyName += propertyName.slice(1);
            }
            propertyName = otherCasePropertyName;
            if (response[propertyName] === undefined) {
                propertyName = propertyName.toLowerCase();
            }
            if (response[propertyName] === undefined) {
                propertyName = propertyName.toUpperCase();
            }
        }
        return response[propertyName];
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/identity-captcha.response.ts

class IdentityCaptchaResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.siteKey = this.getResponseProperty("HCaptcha_SiteKey");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/identity-token.response.ts

class IdentityTokenResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.accessToken = response.access_token;
        this.expiresIn = response.expires_in;
        this.refreshToken = response.refresh_token;
        this.tokenType = response.token_type;
        this.resetMasterPassword = this.getResponseProperty("ResetMasterPassword");
        this.privateKey = this.getResponseProperty("PrivateKey");
        this.key = this.getResponseProperty("Key");
        this.twoFactorToken = this.getResponseProperty("TwoFactorToken");
        this.kdf = this.getResponseProperty("Kdf");
        this.kdfIterations = this.getResponseProperty("KdfIterations");
        this.kdfMemory = this.getResponseProperty("KdfMemory");
        this.kdfParallelism = this.getResponseProperty("KdfParallelism");
        this.forcePasswordReset = this.getResponseProperty("ForcePasswordReset");
        this.apiUseKeyConnector = this.getResponseProperty("ApiUseKeyConnector");
        this.keyConnectorUrl = this.getResponseProperty("KeyConnectorUrl");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/identity-two-factor.response.ts

class IdentityTwoFactorResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.twoFactorProviders2 = new Map();
        this.captchaToken = this.getResponseProperty("CaptchaBypassToken");
        this.twoFactorProviders = this.getResponseProperty("TwoFactorProviders");
        const twoFactorProviders2 = this.getResponseProperty("TwoFactorProviders2");
        if (twoFactorProviders2 != null) {
            for (const prop in twoFactorProviders2) {
                // eslint-disable-next-line
                if (twoFactorProviders2.hasOwnProperty(prop)) {
                    this.twoFactorProviders2.set(parseInt(prop, null), twoFactorProviders2[prop]);
                }
            }
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/logInStrategies/logIn.strategy.ts
var logIn_strategy_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};









class LogInStrategy {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService) {
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.tokenService = tokenService;
        this.appIdService = appIdService;
        this.platformUtilsService = platformUtilsService;
        this.messagingService = messagingService;
        this.logService = logService;
        this.stateService = stateService;
        this.twoFactorService = twoFactorService;
        this.captchaBypassToken = null;
    }
    logInTwoFactor(twoFactor, captchaResponse = null) {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            this.tokenRequest.setTwoFactor(twoFactor);
            return this.startLogIn();
        });
    }
    startLogIn() {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            this.twoFactorService.clearSelectedProvider();
            const response = yield this.apiService.postIdentityToken(this.tokenRequest);
            if (response instanceof IdentityTwoFactorResponse) {
                return this.processTwoFactorResponse(response);
            }
            else if (response instanceof IdentityCaptchaResponse) {
                return this.processCaptchaResponse(response);
            }
            else if (response instanceof IdentityTokenResponse) {
                return this.processTokenResponse(response);
            }
            throw new Error("Invalid response object.");
        });
    }
    buildDeviceRequest() {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            const appId = yield this.appIdService.getAppId();
            return new DeviceRequest(appId, this.platformUtilsService);
        });
    }
    buildTwoFactor(userProvidedTwoFactor) {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            if (userProvidedTwoFactor != null) {
                return userProvidedTwoFactor;
            }
            const storedTwoFactorToken = yield this.tokenService.getTwoFactorToken();
            if (storedTwoFactorToken != null) {
                return new TokenTwoFactorRequest(TwoFactorProviderType.Remember, storedTwoFactorToken, false);
            }
            return new TokenTwoFactorRequest();
        });
    }
    saveAccountInformation(tokenResponse) {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            const accountInformation = yield this.tokenService.decodeToken(tokenResponse.accessToken);
            yield this.stateService.addAccount(new Account({
                profile: Object.assign(Object.assign({}, new AccountProfile()), {
                    userId: accountInformation.sub,
                    name: accountInformation.name,
                    email: accountInformation.email,
                    hasPremiumPersonally: accountInformation.premium,
                    kdfIterations: tokenResponse.kdfIterations,
                    kdfMemory: tokenResponse.kdfMemory,
                    kdfParallelism: tokenResponse.kdfParallelism,
                    kdfType: tokenResponse.kdf,
                }),
                tokens: Object.assign(Object.assign({}, new AccountTokens()), {
                    accessToken: tokenResponse.accessToken,
                    refreshToken: tokenResponse.refreshToken,
                }),
            }));
        });
    }
    processTokenResponse(response) {
        var _a;
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            const result = new AuthResult();
            result.resetMasterPassword = response.resetMasterPassword;
            result.forcePasswordReset = response.forcePasswordReset;
            yield this.saveAccountInformation(response);
            if (response.twoFactorToken != null) {
                yield this.tokenService.setTwoFactorToken(response);
            }
            yield this.setUserKey(response);
            // Must come after the user Key is set, otherwise createKeyPairForOldAccount will fail
            const newSsoUser = response.key == null;
            if (!newSsoUser) {
                yield this.cryptoService.setEncKey(response.key);
                yield this.cryptoService.setEncPrivateKey((_a = response.privateKey) !== null && _a !== void 0 ? _a : (yield this.createKeyPairForOldAccount()));
            }
            this.messagingService.send("loggedIn");
            return result;
        });
    }
    processTwoFactorResponse(response) {
        var _a;
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            const result = new AuthResult();
            result.twoFactorProviders = response.twoFactorProviders2;
            this.twoFactorService.setProviders(response);
            this.captchaBypassToken = (_a = response.captchaToken) !== null && _a !== void 0 ? _a : null;
            return result;
        });
    }
    processCaptchaResponse(response) {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            const result = new AuthResult();
            result.captchaSiteKey = response.siteKey;
            return result;
        });
    }
    createKeyPairForOldAccount() {
        return logIn_strategy_awaiter(this, void 0, void 0, function* () {
            try {
                const [publicKey, privateKey] = yield this.cryptoService.makeKeyPair();
                yield this.apiService.postAccountKeys(new KeysRequest(publicKey, privateKey.encryptedString));
                return privateKey.encryptedString;
            }
            catch (e) {
                this.logService.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/logInStrategies/passwordLogin.strategy.ts
var passwordLogin_strategy_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class PasswordLogInStrategy extends LogInStrategy {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService, authService) {
        super(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService);
        this.authService = authService;
    }
    get email() {
        return this.tokenRequest.email;
    }
    get masterPasswordHash() {
        return this.tokenRequest.masterPasswordHash;
    }
    setUserKey() {
        return passwordLogin_strategy_awaiter(this, void 0, void 0, function* () {
            yield this.cryptoService.setKey(this.key);
            yield this.cryptoService.setKeyHash(this.localHashedPassword);
        });
    }
    logInTwoFactor(twoFactor, captchaResponse) {
        const _super = Object.create(null, {
            logInTwoFactor: { get: () => super.logInTwoFactor }
        });
        return passwordLogin_strategy_awaiter(this, void 0, void 0, function* () {
            this.tokenRequest.captchaResponse = captchaResponse !== null && captchaResponse !== void 0 ? captchaResponse : this.captchaBypassToken;
            return _super.logInTwoFactor.call(this, twoFactor);
        });
    }
    logIn(credentials) {
        return passwordLogin_strategy_awaiter(this, void 0, void 0, function* () {
            const { email, masterPassword, captchaToken, twoFactor } = credentials;
            this.key = yield this.authService.makePreloginKey(masterPassword, email);
            // Hash the password early (before authentication) so we don't persist it in memory in plaintext
            this.localHashedPassword = yield this.cryptoService.hashPassword(masterPassword, this.key, HashPurpose.LocalAuthorization);
            const hashedPassword = yield this.cryptoService.hashPassword(masterPassword, this.key);
            this.tokenRequest = new PasswordTokenRequest(email, hashedPassword, captchaToken, yield this.buildTwoFactor(twoFactor), yield this.buildDeviceRequest());
            return this.startLogIn();
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/logInStrategies/passwordlessLogin.strategy.ts
var passwordlessLogin_strategy_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class PasswordlessLogInStrategy extends LogInStrategy {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService, authService) {
        super(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService);
        this.authService = authService;
    }
    get email() {
        return this.tokenRequest.email;
    }
    get accessCode() {
        return this.passwordlessCredentials.accessCode;
    }
    get authRequestId() {
        return this.passwordlessCredentials.authRequestId;
    }
    setUserKey() {
        return passwordlessLogin_strategy_awaiter(this, void 0, void 0, function* () {
            yield this.cryptoService.setKey(this.passwordlessCredentials.decKey);
            yield this.cryptoService.setKeyHash(this.passwordlessCredentials.localPasswordHash);
        });
    }
    logInTwoFactor(twoFactor, captchaResponse) {
        const _super = Object.create(null, {
            logInTwoFactor: { get: () => super.logInTwoFactor }
        });
        return passwordlessLogin_strategy_awaiter(this, void 0, void 0, function* () {
            this.tokenRequest.captchaResponse = captchaResponse !== null && captchaResponse !== void 0 ? captchaResponse : this.captchaBypassToken;
            return _super.logInTwoFactor.call(this, twoFactor);
        });
    }
    logIn(credentials) {
        return passwordlessLogin_strategy_awaiter(this, void 0, void 0, function* () {
            this.passwordlessCredentials = credentials;
            this.tokenRequest = new PasswordTokenRequest(credentials.email, credentials.accessCode, null, yield this.buildTwoFactor(credentials.twoFactor), yield this.buildDeviceRequest());
            this.tokenRequest.setPasswordlessAccessCode(credentials.authRequestId);
            return this.startLogIn();
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/identity-token/sso-token.request.ts

class SsoTokenRequest extends TokenRequest {
    constructor(code, codeVerifier, redirectUri, twoFactor, device) {
        super(twoFactor, device);
        this.code = code;
        this.codeVerifier = codeVerifier;
        this.redirectUri = redirectUri;
        this.twoFactor = twoFactor;
    }
    toIdentityToken(clientId) {
        const obj = super.toIdentityToken(clientId);
        obj.grant_type = "authorization_code";
        obj.code = this.code;
        obj.code_verifier = this.codeVerifier;
        obj.redirect_uri = this.redirectUri;
        return obj;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/logInStrategies/ssoLogin.strategy.ts
var ssoLogin_strategy_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class SsoLogInStrategy extends LogInStrategy {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService, keyConnectorService) {
        super(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService);
        this.keyConnectorService = keyConnectorService;
    }
    setUserKey(tokenResponse) {
        return ssoLogin_strategy_awaiter(this, void 0, void 0, function* () {
            const newSsoUser = tokenResponse.key == null;
            if (tokenResponse.keyConnectorUrl != null) {
                if (!newSsoUser) {
                    yield this.keyConnectorService.getAndSetKey(tokenResponse.keyConnectorUrl);
                }
                else {
                    yield this.keyConnectorService.convertNewSsoUserToKeyConnector(tokenResponse, this.orgId);
                }
            }
        });
    }
    logIn(credentials) {
        return ssoLogin_strategy_awaiter(this, void 0, void 0, function* () {
            this.orgId = credentials.orgId;
            this.tokenRequest = new SsoTokenRequest(credentials.code, credentials.codeVerifier, credentials.redirectUrl, yield this.buildTwoFactor(credentials.twoFactor), yield this.buildDeviceRequest());
            return this.startLogIn();
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/identity-token/user-api-token.request.ts

class UserApiTokenRequest extends TokenRequest {
    constructor(clientId, clientSecret, twoFactor, device) {
        super(twoFactor, device);
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.twoFactor = twoFactor;
    }
    toIdentityToken() {
        const obj = super.toIdentityToken(this.clientId);
        obj.scope = this.clientId.startsWith("organization") ? "api.organization" : "api";
        obj.grant_type = "client_credentials";
        obj.client_secret = this.clientSecret;
        return obj;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/logInStrategies/user-api-login.strategy.ts
var user_api_login_strategy_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class UserApiLogInStrategy extends LogInStrategy {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService, environmentService, keyConnectorService) {
        super(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, stateService, twoFactorService);
        this.environmentService = environmentService;
        this.keyConnectorService = keyConnectorService;
    }
    setUserKey(tokenResponse) {
        return user_api_login_strategy_awaiter(this, void 0, void 0, function* () {
            if (tokenResponse.apiUseKeyConnector) {
                const keyConnectorUrl = this.environmentService.getKeyConnectorUrl();
                yield this.keyConnectorService.getAndSetKey(keyConnectorUrl);
            }
        });
    }
    logIn(credentials) {
        return user_api_login_strategy_awaiter(this, void 0, void 0, function* () {
            this.tokenRequest = new UserApiTokenRequest(credentials.clientId, credentials.clientSecret, yield this.buildTwoFactor(), yield this.buildDeviceRequest());
            return this.startLogIn();
        });
    }
    saveAccountInformation(tokenResponse) {
        const _super = Object.create(null, {
            saveAccountInformation: { get: () => super.saveAccountInformation }
        });
        return user_api_login_strategy_awaiter(this, void 0, void 0, function* () {
            yield _super.saveAccountInformation.call(this, tokenResponse);
            yield this.stateService.setApiKeyClientId(this.tokenRequest.clientId);
            yield this.stateService.setApiKeyClientSecret(this.tokenRequest.clientSecret);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/kdf-config.ts
class KdfConfig {
    constructor(iterations, memory, parallelism) {
        this.iterations = iterations;
        this.memory = memory;
        this.parallelism = parallelism;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/passwordless-auth.request.ts
class PasswordlessAuthRequest {
    constructor(key, masterPasswordHash, deviceIdentifier, requestApproved) {
        this.key = key;
        this.masterPasswordHash = masterPasswordHash;
        this.deviceIdentifier = deviceIdentifier;
        this.requestApproved = requestApproved;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/prelogin.request.ts
class PreloginRequest {
    constructor(email) {
        this.email = email;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/error.response.ts


class ErrorResponse extends BaseResponse {
    constructor(response, status, identityResponse) {
        var _a, _b;
        super(response);
        let errorModel = null;
        if (response != null) {
            const responseErrorModel = this.getResponseProperty("ErrorModel");
            if (responseErrorModel && identityResponse) {
                errorModel = responseErrorModel;
            }
            else {
                errorModel = response;
            }
        }
        if (status === 429) {
            this.message = "Rate limit exceeded. Try again later.";
        }
        else if (errorModel) {
            this.message = this.getResponseProperty("Message", errorModel);
            this.validationErrors = this.getResponseProperty("ValidationErrors", errorModel);
            this.captchaSiteKey = (_b = (_a = this.validationErrors) === null || _a === void 0 ? void 0 : _a.HCaptcha_SiteKey) === null || _b === void 0 ? void 0 : _b[0];
            this.captchaRequired = !Utils.isNullOrWhitespace(this.captchaSiteKey);
        }
        this.statusCode = status;
    }
    getSingleMessage() {
        if (this.validationErrors == null) {
            return this.message;
        }
        for (const key in this.validationErrors) {
            // eslint-disable-next-line
            if (!this.validationErrors.hasOwnProperty(key)) {
                continue;
            }
            if (this.validationErrors[key].length) {
                return this.validationErrors[key][0];
            }
        }
        return this.message;
    }
    getAllMessages() {
        const messages = [];
        if (this.validationErrors == null) {
            return messages;
        }
        for (const key in this.validationErrors) {
            // eslint-disable-next-line
            if (!this.validationErrors.hasOwnProperty(key)) {
                continue;
            }
            this.validationErrors[key].forEach((item) => {
                let prefix = "";
                if (key.indexOf("[") > -1 && key.indexOf("]") > -1) {
                    const lastSep = key.lastIndexOf(".");
                    prefix = key.substr(0, lastSep > -1 ? lastSep : key.length) + ": ";
                }
                messages.push(prefix + item);
            });
        }
        return messages;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/auth.service.ts
var auth_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};













const sessionTimeoutLength = 2 * 60 * 1000; // 2 minutes
class AuthService {
    constructor(cryptoService, apiService, tokenService, appIdService, platformUtilsService, messagingService, logService, keyConnectorService, environmentService, stateService, twoFactorService, i18nService, encryptService) {
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.tokenService = tokenService;
        this.appIdService = appIdService;
        this.platformUtilsService = platformUtilsService;
        this.messagingService = messagingService;
        this.logService = logService;
        this.keyConnectorService = keyConnectorService;
        this.environmentService = environmentService;
        this.stateService = stateService;
        this.twoFactorService = twoFactorService;
        this.i18nService = i18nService;
        this.encryptService = encryptService;
        this.pushNotificationSubject = new external_rxjs_namespaceObject.Subject();
    }
    get email() {
        if (this.logInStrategy instanceof PasswordLogInStrategy ||
            this.logInStrategy instanceof PasswordlessLogInStrategy) {
            return this.logInStrategy.email;
        }
        return null;
    }
    get masterPasswordHash() {
        return this.logInStrategy instanceof PasswordLogInStrategy
            ? this.logInStrategy.masterPasswordHash
            : null;
    }
    get accessCode() {
        return this.logInStrategy instanceof PasswordlessLogInStrategy
            ? this.logInStrategy.accessCode
            : null;
    }
    get authRequestId() {
        return this.logInStrategy instanceof PasswordlessLogInStrategy
            ? this.logInStrategy.authRequestId
            : null;
    }
    logIn(credentials) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            this.clearState();
            let strategy;
            switch (credentials.type) {
                case authenticationType_AuthenticationType.Password:
                    strategy = new PasswordLogInStrategy(this.cryptoService, this.apiService, this.tokenService, this.appIdService, this.platformUtilsService, this.messagingService, this.logService, this.stateService, this.twoFactorService, this);
                    break;
                case authenticationType_AuthenticationType.Sso:
                    strategy = new SsoLogInStrategy(this.cryptoService, this.apiService, this.tokenService, this.appIdService, this.platformUtilsService, this.messagingService, this.logService, this.stateService, this.twoFactorService, this.keyConnectorService);
                    break;
                case authenticationType_AuthenticationType.UserApi:
                    strategy = new UserApiLogInStrategy(this.cryptoService, this.apiService, this.tokenService, this.appIdService, this.platformUtilsService, this.messagingService, this.logService, this.stateService, this.twoFactorService, this.environmentService, this.keyConnectorService);
                    break;
                case authenticationType_AuthenticationType.Passwordless:
                    strategy = new PasswordlessLogInStrategy(this.cryptoService, this.apiService, this.tokenService, this.appIdService, this.platformUtilsService, this.messagingService, this.logService, this.stateService, this.twoFactorService, this);
                    break;
            }
            const result = yield strategy.logIn(credentials);
            if (result === null || result === void 0 ? void 0 : result.requiresTwoFactor) {
                this.saveState(strategy);
            }
            return result;
        });
    }
    logInTwoFactor(twoFactor, captchaResponse) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            if (this.logInStrategy == null) {
                throw new Error(this.i18nService.t("sessionTimeout"));
            }
            try {
                const result = yield this.logInStrategy.logInTwoFactor(twoFactor, captchaResponse);
                // Only clear state if 2FA token has been accepted, otherwise we need to be able to try again
                if (!result.requiresTwoFactor && !result.requiresCaptcha) {
                    this.clearState();
                }
                return result;
            }
            catch (e) {
                // API exceptions are okay, but if there are any unhandled client-side errors then clear state to be safe
                if (!(e instanceof ErrorResponse)) {
                    this.clearState();
                }
                throw e;
            }
        });
    }
    logOut(callback) {
        callback();
        this.messagingService.send("loggedOut");
    }
    authingWithUserApiKey() {
        return this.logInStrategy instanceof UserApiLogInStrategy;
    }
    authingWithSso() {
        return this.logInStrategy instanceof SsoLogInStrategy;
    }
    authingWithPassword() {
        return this.logInStrategy instanceof PasswordLogInStrategy;
    }
    authingWithPasswordless() {
        return this.logInStrategy instanceof PasswordlessLogInStrategy;
    }
    getAuthStatus(userId) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            const isAuthenticated = yield this.stateService.getIsAuthenticated({ userId: userId });
            if (!isAuthenticated) {
                return AuthenticationStatus.LoggedOut;
            }
            // Keys aren't stored for a device that is locked or logged out
            // Make sure we're logged in before checking this, otherwise we could mix up those states
            const neverLock = (yield this.cryptoService.hasKeyStored(KeySuffixOptions.Auto, userId)) &&
                !(yield this.stateService.getEverBeenUnlocked({ userId: userId }));
            if (neverLock) {
                // TODO: This also _sets_ the key so when we check memory in the next line it finds a key.
                // We should refactor here.
                yield this.cryptoService.getKey(KeySuffixOptions.Auto, userId);
            }
            const hasKeyInMemory = yield this.cryptoService.hasKeyInMemory(userId);
            if (!hasKeyInMemory) {
                return AuthenticationStatus.Locked;
            }
            return AuthenticationStatus.Unlocked;
        });
    }
    makePreloginKey(masterPassword, email) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            email = email.trim().toLowerCase();
            let kdf = null;
            let kdfConfig = null;
            try {
                const preloginResponse = yield this.apiService.postPrelogin(new PreloginRequest(email));
                if (preloginResponse != null) {
                    kdf = preloginResponse.kdf;
                    kdfConfig = new KdfConfig(preloginResponse.kdfIterations, preloginResponse.kdfMemory, preloginResponse.kdfParallelism);
                }
            }
            catch (e) {
                if (e == null || e.statusCode !== 404) {
                    throw e;
                }
            }
            return this.cryptoService.makeKey(masterPassword, email, kdf, kdfConfig);
        });
    }
    authResponsePushNotifiction(notification) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            this.pushNotificationSubject.next(notification.id);
        });
    }
    getPushNotifcationObs$() {
        return this.pushNotificationSubject.asObservable();
    }
    passwordlessLogin(id, key, requestApproved) {
        return auth_service_awaiter(this, void 0, void 0, function* () {
            const pubKey = Utils.fromB64ToArray(key);
            const encryptedKey = yield this.cryptoService.rsaEncrypt((yield this.cryptoService.getKey()).encKey, pubKey.buffer);
            const encryptedMasterPassword = yield this.cryptoService.rsaEncrypt(Utils.fromUtf8ToArray(yield this.stateService.getKeyHash()), pubKey.buffer);
            const request = new PasswordlessAuthRequest(encryptedKey.encryptedString, encryptedMasterPassword.encryptedString, yield this.appIdService.getAppId(), requestApproved);
            return yield this.apiService.putAuthRequest(id, request);
        });
    }
    saveState(strategy) {
        this.logInStrategy = strategy;
        this.startSessionTimeout();
    }
    clearState() {
        this.logInStrategy = null;
        this.clearSessionTimeout();
    }
    startSessionTimeout() {
        this.clearSessionTimeout();
        this.sessionTimeout = setTimeout(() => this.clearState(), sessionTimeoutLength);
    }
    clearSessionTimeout() {
        if (this.sessionTimeout != null) {
            clearTimeout(this.sessionTimeout);
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/broadcaster.service.ts
class BroadcasterService {
    constructor() {
        this.subscribers = new Map();
    }
    send(message, id) {
        if (id != null) {
            if (this.subscribers.has(id)) {
                this.subscribers.get(id)(message);
            }
            return;
        }
        this.subscribers.forEach((value) => {
            value(message);
        });
    }
    subscribe(id, messageCallback) {
        this.subscribers.set(id, messageCallback);
    }
    unsubscribe(id) {
        if (this.subscribers.has(id)) {
            this.subscribers.delete(id);
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/tree-node.ts
class TreeNode {
    constructor(node, parent, name, id) {
        this.children = [];
        this.parent = parent;
        this.node = node;
        if (name) {
            this.node.name = name;
        }
        if (id) {
            this.node.id = id;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/serviceUtils.ts

class ServiceUtils {
    /**
     * Recursively adds a node to nodeTree
     * @param {TreeNode<ITreeNodeObject>[]} nodeTree - An array of TreeNodes that the node will be added to
     * @param {number} partIndex - Index of the `parts` array that is being processed
     * @param {string[]} parts - Array of strings that represent the path to the `obj` node
     * @param {ITreeNodeObject} obj - The node to be added to the tree
     * @param {ITreeNodeObject} parent - The parent node of the `obj` node
     * @param {string} delimiter - The delimiter used to split the path string, will be used to combine the path for missing nodes
     */
    static nestedTraverse(nodeTree, partIndex, parts, obj, parent, delimiter) {
        if (parts.length <= partIndex) {
            return;
        }
        const end = partIndex === parts.length - 1;
        const partName = parts[partIndex];
        for (let i = 0; i < nodeTree.length; i++) {
            if (nodeTree[i].node.name !== partName) {
                continue;
            }
            if (end && nodeTree[i].node.id !== obj.id) {
                // Another node exists with the same name as the node being added
                nodeTree.push(new TreeNode(obj, parent, partName));
                return;
            }
            // Move down the tree to the next level
            ServiceUtils.nestedTraverse(nodeTree[i].children, partIndex + 1, parts, obj, nodeTree[i], delimiter);
            return;
        }
        // If there's no node here with the same name...
        if (nodeTree.filter((n) => n.node.name === partName).length === 0) {
            // And we're at the end of the path given, add the node
            if (end) {
                nodeTree.push(new TreeNode(obj, parent, partName));
                return;
            }
            // And we're not at the end of the path, combine the current name with the next name
            // 1, *1.2, 1.2.1 becomes
            // 1, *1.2/1.2.1
            const newPartName = partName + delimiter + parts[partIndex + 1];
            ServiceUtils.nestedTraverse(nodeTree, 0, [newPartName, ...parts.slice(partIndex + 2)], obj, parent, delimiter);
        }
    }
    /**
     * Searches a tree for a node with a matching `id`
     * @param {TreeNode<ITreeNodeObject>} nodeTree - A single TreeNode branch that will be searched
     * @param {string} id - The id of the node to be found
     * @returns {TreeNode<ITreeNodeObject>} The node with a matching `id`
     */
    static getTreeNodeObject(nodeTree, id) {
        if (nodeTree.node.id === id) {
            return nodeTree;
        }
        for (let i = 0; i < nodeTree.children.length; i++) {
            if (nodeTree.children[i].children != null) {
                const node = ServiceUtils.getTreeNodeObject(nodeTree.children[i], id);
                if (node !== null) {
                    return node;
                }
            }
        }
        return null;
    }
    /**
     * Searches an array of tree nodes for a node with a matching `id`
     * @param {TreeNode<ITreeNodeObject>} nodeTree - An array of TreeNode branches that will be searched
     * @param {string} id - The id of the node to be found
     * @returns {TreeNode<ITreeNodeObject>} The node with a matching `id`
     */
    static getTreeNodeObjectFromList(nodeTree, id) {
        for (let i = 0; i < nodeTree.length; i++) {
            if (nodeTree[i].node.id === id) {
                return nodeTree[i];
            }
            else if (nodeTree[i].children != null) {
                const node = ServiceUtils.getTreeNodeObjectFromList(nodeTree[i].children, id);
                if (node !== null) {
                    return node;
                }
            }
        }
        return null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/collection.data.ts
class CollectionData {
    constructor(response) {
        this.id = response.id;
        this.organizationId = response.organizationId;
        this.name = response.name;
        this.externalId = response.externalId;
        this.readOnly = response.readOnly;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/view/collection.view.ts

class CollectionView {
    constructor(c) {
        this.id = null;
        this.organizationId = null;
        this.name = null;
        this.externalId = null;
        this.readOnly = null;
        this.hidePasswords = null;
        if (!c) {
            return;
        }
        this.id = c.id;
        this.organizationId = c.organizationId;
        this.externalId = c.externalId;
        if (c instanceof Collection) {
            this.readOnly = c.readOnly;
            this.hidePasswords = c.hidePasswords;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/domain-base.ts
var domain_base_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class Domain {
    buildDomainModel(domain, dataObj, map, notEncList = []) {
        for (const prop in map) {
            // eslint-disable-next-line
            if (!map.hasOwnProperty(prop)) {
                continue;
            }
            const objProp = dataObj[map[prop] || prop];
            if (notEncList.indexOf(prop) > -1) {
                domain[prop] = objProp ? objProp : null;
            }
            else {
                domain[prop] = objProp ? new EncString(objProp) : null;
            }
        }
    }
    buildDataModel(domain, dataObj, map, notEncStringList = []) {
        for (const prop in map) {
            // eslint-disable-next-line
            if (!map.hasOwnProperty(prop)) {
                continue;
            }
            const objProp = domain[map[prop] || prop];
            if (notEncStringList.indexOf(prop) > -1) {
                dataObj[prop] = objProp != null ? objProp : null;
            }
            else {
                dataObj[prop] = objProp != null ? objProp.encryptedString : null;
            }
        }
    }
    decryptObj(viewModel, map, orgId, key = null) {
        return domain_base_awaiter(this, void 0, void 0, function* () {
            const promises = [];
            const self = this;
            for (const prop in map) {
                // eslint-disable-next-line
                if (!map.hasOwnProperty(prop)) {
                    continue;
                }
                (function (theProp) {
                    const p = Promise.resolve()
                        .then(() => {
                        const mapProp = map[theProp] || theProp;
                        if (self[mapProp]) {
                            return self[mapProp].decrypt(orgId, key);
                        }
                        return null;
                    })
                        .then((val) => {
                        viewModel[theProp] = val;
                    });
                    promises.push(p);
                })(prop);
            }
            yield Promise.all(promises);
            return viewModel;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/collection.ts


class Collection extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            id: null,
            organizationId: null,
            name: null,
            externalId: null,
            readOnly: null,
            hidePasswords: null,
        }, ["id", "organizationId", "externalId", "readOnly", "hidePasswords"]);
    }
    decrypt() {
        return this.decryptObj(new CollectionView(this), {
            name: null,
        }, this.organizationId);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/collection.service.ts
var collection_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





const NestingDelimiter = "/";
class CollectionService {
    constructor(cryptoService, i18nService, stateService) {
        this.cryptoService = cryptoService;
        this.i18nService = i18nService;
        this.stateService = stateService;
    }
    clearCache(userId) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedCollections(null, { userId: userId });
        });
    }
    encrypt(model) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            if (model.organizationId == null) {
                throw new Error("Collection has no organization id.");
            }
            const key = yield this.cryptoService.getOrgKey(model.organizationId);
            if (key == null) {
                throw new Error("No key for this collection's organization.");
            }
            const collection = new Collection();
            collection.id = model.id;
            collection.organizationId = model.organizationId;
            collection.readOnly = model.readOnly;
            collection.name = yield this.cryptoService.encrypt(model.name, key);
            return collection;
        });
    }
    decryptMany(collections) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            if (collections == null) {
                return [];
            }
            const decCollections = [];
            const promises = [];
            collections.forEach((collection) => {
                promises.push(collection.decrypt().then((c) => decCollections.push(c)));
            });
            yield Promise.all(promises);
            return decCollections.sort(Utils.getSortFunction(this.i18nService, "name"));
        });
    }
    get(id) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            const collections = yield this.stateService.getEncryptedCollections();
            // eslint-disable-next-line
            if (collections == null || !collections.hasOwnProperty(id)) {
                return null;
            }
            return new Collection(collections[id]);
        });
    }
    getAll() {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            const collections = yield this.stateService.getEncryptedCollections();
            const response = [];
            for (const id in collections) {
                // eslint-disable-next-line
                if (collections.hasOwnProperty(id)) {
                    response.push(new Collection(collections[id]));
                }
            }
            return response;
        });
    }
    getAllDecrypted() {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            let decryptedCollections = yield this.stateService.getDecryptedCollections();
            if (decryptedCollections != null) {
                return decryptedCollections;
            }
            const hasKey = yield this.cryptoService.hasKey();
            if (!hasKey) {
                throw new Error("No key.");
            }
            const collections = yield this.getAll();
            decryptedCollections = yield this.decryptMany(collections);
            yield this.stateService.setDecryptedCollections(decryptedCollections);
            return decryptedCollections;
        });
    }
    getAllNested(collections = null) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            if (collections == null) {
                collections = yield this.getAllDecrypted();
            }
            const nodes = [];
            collections.forEach((c) => {
                const collectionCopy = new CollectionView();
                collectionCopy.id = c.id;
                collectionCopy.organizationId = c.organizationId;
                const parts = c.name != null ? c.name.replace(/^\/+|\/+$/g, "").split(NestingDelimiter) : [];
                ServiceUtils.nestedTraverse(nodes, 0, parts, collectionCopy, null, NestingDelimiter);
            });
            return nodes;
        });
    }
    /**
     * @deprecated August 30 2022: Moved to new Vault Filter Service
     * Remove when Desktop and Browser are updated
     */
    getNested(id) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            const collections = yield this.getAllNested();
            return ServiceUtils.getTreeNodeObjectFromList(collections, id);
        });
    }
    upsert(collection) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            let collections = yield this.stateService.getEncryptedCollections();
            if (collections == null) {
                collections = {};
            }
            if (collection instanceof CollectionData) {
                const c = collection;
                collections[c.id] = c;
            }
            else {
                collection.forEach((c) => {
                    collections[c.id] = c;
                });
            }
            yield this.replace(collections);
        });
    }
    replace(collections) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearCache();
            yield this.stateService.setEncryptedCollections(collections);
        });
    }
    clear(userId) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearCache(userId);
            yield this.stateService.setEncryptedCollections(null, { userId: userId });
        });
    }
    delete(id) {
        return collection_service_awaiter(this, void 0, void 0, function* () {
            const collections = yield this.stateService.getEncryptedCollections();
            if (collections == null) {
                return;
            }
            if (typeof id === "string") {
                delete collections[id];
            }
            else {
                id.forEach((i) => {
                    delete collections[i];
                });
            }
            yield this.replace(collections);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/container.service.ts
class ContainerService {
    constructor(cryptoService, encryptService) {
        this.cryptoService = cryptoService;
        this.encryptService = encryptService;
    }
    attachToGlobal(global) {
        if (!global.bitwardenContainerService) {
            global.bitwardenContainerService = this;
        }
    }
    /**
     * @throws Will throw if CryptoService was not instantiated and provided to the ContainerService constructor
     */
    getCryptoService() {
        if (this.cryptoService == null) {
            throw new Error("ContainerService.cryptoService not initialized.");
        }
        return this.cryptoService;
    }
    /**
     * @throws Will throw if EncryptService was not instantiated and provided to the ContainerService constructor
     */
    getEncryptService() {
        if (this.encryptService == null) {
            throw new Error("ContainerService.encryptService not initialized.");
        }
        return this.encryptService;
    }
}

;// CONCATENATED MODULE: external "big-integer"
const external_big_integer_namespaceObject = require("big-integer");
;// CONCATENATED MODULE: ../../libs/common/src/enums/kdfType.ts

var KdfType;
(function (KdfType) {
    KdfType[KdfType["PBKDF2_SHA256"] = 0] = "PBKDF2_SHA256";
    KdfType[KdfType["Argon2id"] = 1] = "Argon2id";
})(KdfType || (KdfType = {}));
const DEFAULT_ARGON2_MEMORY = 64;
const DEFAULT_ARGON2_PARALLELISM = 4;
const DEFAULT_ARGON2_ITERATIONS = 3;
const DEFAULT_KDF_TYPE = KdfType.PBKDF2_SHA256;
const DEFAULT_PBKDF2_ITERATIONS = 600000;
const DEFAULT_KDF_CONFIG = new KdfConfig(DEFAULT_PBKDF2_ITERATIONS);
const SEND_KDF_ITERATIONS = 100000;

;// CONCATENATED MODULE: ../../libs/common/src/misc/sequentialize.ts
/**
 * Use as a Decorator on async functions, it will prevent multiple 'active' calls as the same time
 *
 * If a promise was returned from a previous call to this function, that hasn't yet resolved it will
 * be returned, instead of calling the original function again
 *
 * Results are not cached, once the promise has returned, the next call will result in a fresh call
 *
 * Read more at https://github.com/bitwarden/jslib/pull/7
 */
function sequentialize(cacheKey) {
    return (target, propertyKey, descriptor) => {
        const originalMethod = descriptor.value;
        const caches = new Map();
        const getCache = (obj) => {
            let cache = caches.get(obj);
            if (cache != null) {
                return cache;
            }
            cache = new Map();
            caches.set(obj, cache);
            return cache;
        };
        return {
            value: function (...args) {
                const cache = getCache(this);
                const argsCacheKey = cacheKey(args);
                let response = cache.get(argsCacheKey);
                if (response != null) {
                    return response;
                }
                const onFinally = () => {
                    cache.delete(argsCacheKey);
                    if (cache.size === 0) {
                        caches.delete(this);
                    }
                };
                response = originalMethod
                    .apply(this, args)
                    .then((val) => {
                    onFinally();
                    return val;
                })
                    .catch((err) => {
                    onFinally();
                    throw err;
                });
                cache.set(argsCacheKey, response);
                return response;
            },
        };
    };
}

;// CONCATENATED MODULE: ../../libs/common/src/misc/wordlist.ts
// EFF's Long Wordlist from https://www.eff.org/dice
const EFFLongWordList = [
    "abacus",
    "abdomen",
    "abdominal",
    "abide",
    "abiding",
    "ability",
    "ablaze",
    "able",
    "abnormal",
    "abrasion",
    "abrasive",
    "abreast",
    "abridge",
    "abroad",
    "abruptly",
    "absence",
    "absentee",
    "absently",
    "absinthe",
    "absolute",
    "absolve",
    "abstain",
    "abstract",
    "absurd",
    "accent",
    "acclaim",
    "acclimate",
    "accompany",
    "account",
    "accuracy",
    "accurate",
    "accustom",
    "acetone",
    "achiness",
    "aching",
    "acid",
    "acorn",
    "acquaint",
    "acquire",
    "acre",
    "acrobat",
    "acronym",
    "acting",
    "action",
    "activate",
    "activator",
    "active",
    "activism",
    "activist",
    "activity",
    "actress",
    "acts",
    "acutely",
    "acuteness",
    "aeration",
    "aerobics",
    "aerosol",
    "aerospace",
    "afar",
    "affair",
    "affected",
    "affecting",
    "affection",
    "affidavit",
    "affiliate",
    "affirm",
    "affix",
    "afflicted",
    "affluent",
    "afford",
    "affront",
    "aflame",
    "afloat",
    "aflutter",
    "afoot",
    "afraid",
    "afterglow",
    "afterlife",
    "aftermath",
    "aftermost",
    "afternoon",
    "aged",
    "ageless",
    "agency",
    "agenda",
    "agent",
    "aggregate",
    "aghast",
    "agile",
    "agility",
    "aging",
    "agnostic",
    "agonize",
    "agonizing",
    "agony",
    "agreeable",
    "agreeably",
    "agreed",
    "agreeing",
    "agreement",
    "aground",
    "ahead",
    "ahoy",
    "aide",
    "aids",
    "aim",
    "ajar",
    "alabaster",
    "alarm",
    "albatross",
    "album",
    "alfalfa",
    "algebra",
    "algorithm",
    "alias",
    "alibi",
    "alienable",
    "alienate",
    "aliens",
    "alike",
    "alive",
    "alkaline",
    "alkalize",
    "almanac",
    "almighty",
    "almost",
    "aloe",
    "aloft",
    "aloha",
    "alone",
    "alongside",
    "aloof",
    "alphabet",
    "alright",
    "although",
    "altitude",
    "alto",
    "aluminum",
    "alumni",
    "always",
    "amaretto",
    "amaze",
    "amazingly",
    "amber",
    "ambiance",
    "ambiguity",
    "ambiguous",
    "ambition",
    "ambitious",
    "ambulance",
    "ambush",
    "amendable",
    "amendment",
    "amends",
    "amenity",
    "amiable",
    "amicably",
    "amid",
    "amigo",
    "amino",
    "amiss",
    "ammonia",
    "ammonium",
    "amnesty",
    "amniotic",
    "among",
    "amount",
    "amperage",
    "ample",
    "amplifier",
    "amplify",
    "amply",
    "amuck",
    "amulet",
    "amusable",
    "amused",
    "amusement",
    "amuser",
    "amusing",
    "anaconda",
    "anaerobic",
    "anagram",
    "anatomist",
    "anatomy",
    "anchor",
    "anchovy",
    "ancient",
    "android",
    "anemia",
    "anemic",
    "aneurism",
    "anew",
    "angelfish",
    "angelic",
    "anger",
    "angled",
    "angler",
    "angles",
    "angling",
    "angrily",
    "angriness",
    "anguished",
    "angular",
    "animal",
    "animate",
    "animating",
    "animation",
    "animator",
    "anime",
    "animosity",
    "ankle",
    "annex",
    "annotate",
    "announcer",
    "annoying",
    "annually",
    "annuity",
    "anointer",
    "another",
    "answering",
    "antacid",
    "antarctic",
    "anteater",
    "antelope",
    "antennae",
    "anthem",
    "anthill",
    "anthology",
    "antibody",
    "antics",
    "antidote",
    "antihero",
    "antiquely",
    "antiques",
    "antiquity",
    "antirust",
    "antitoxic",
    "antitrust",
    "antiviral",
    "antivirus",
    "antler",
    "antonym",
    "antsy",
    "anvil",
    "anybody",
    "anyhow",
    "anymore",
    "anyone",
    "anyplace",
    "anything",
    "anytime",
    "anyway",
    "anywhere",
    "aorta",
    "apache",
    "apostle",
    "appealing",
    "appear",
    "appease",
    "appeasing",
    "appendage",
    "appendix",
    "appetite",
    "appetizer",
    "applaud",
    "applause",
    "apple",
    "appliance",
    "applicant",
    "applied",
    "apply",
    "appointee",
    "appraisal",
    "appraiser",
    "apprehend",
    "approach",
    "approval",
    "approve",
    "apricot",
    "april",
    "apron",
    "aptitude",
    "aptly",
    "aqua",
    "aqueduct",
    "arbitrary",
    "arbitrate",
    "ardently",
    "area",
    "arena",
    "arguable",
    "arguably",
    "argue",
    "arise",
    "armadillo",
    "armband",
    "armchair",
    "armed",
    "armful",
    "armhole",
    "arming",
    "armless",
    "armoire",
    "armored",
    "armory",
    "armrest",
    "army",
    "aroma",
    "arose",
    "around",
    "arousal",
    "arrange",
    "array",
    "arrest",
    "arrival",
    "arrive",
    "arrogance",
    "arrogant",
    "arson",
    "art",
    "ascend",
    "ascension",
    "ascent",
    "ascertain",
    "ashamed",
    "ashen",
    "ashes",
    "ashy",
    "aside",
    "askew",
    "asleep",
    "asparagus",
    "aspect",
    "aspirate",
    "aspire",
    "aspirin",
    "astonish",
    "astound",
    "astride",
    "astrology",
    "astronaut",
    "astronomy",
    "astute",
    "atlantic",
    "atlas",
    "atom",
    "atonable",
    "atop",
    "atrium",
    "atrocious",
    "atrophy",
    "attach",
    "attain",
    "attempt",
    "attendant",
    "attendee",
    "attention",
    "attentive",
    "attest",
    "attic",
    "attire",
    "attitude",
    "attractor",
    "attribute",
    "atypical",
    "auction",
    "audacious",
    "audacity",
    "audible",
    "audibly",
    "audience",
    "audio",
    "audition",
    "augmented",
    "august",
    "authentic",
    "author",
    "autism",
    "autistic",
    "autograph",
    "automaker",
    "automated",
    "automatic",
    "autopilot",
    "available",
    "avalanche",
    "avatar",
    "avenge",
    "avenging",
    "avenue",
    "average",
    "aversion",
    "avert",
    "aviation",
    "aviator",
    "avid",
    "avoid",
    "await",
    "awaken",
    "award",
    "aware",
    "awhile",
    "awkward",
    "awning",
    "awoke",
    "awry",
    "axis",
    "babble",
    "babbling",
    "babied",
    "baboon",
    "backache",
    "backboard",
    "backboned",
    "backdrop",
    "backed",
    "backer",
    "backfield",
    "backfire",
    "backhand",
    "backing",
    "backlands",
    "backlash",
    "backless",
    "backlight",
    "backlit",
    "backlog",
    "backpack",
    "backpedal",
    "backrest",
    "backroom",
    "backshift",
    "backside",
    "backslid",
    "backspace",
    "backspin",
    "backstab",
    "backstage",
    "backtalk",
    "backtrack",
    "backup",
    "backward",
    "backwash",
    "backwater",
    "backyard",
    "bacon",
    "bacteria",
    "bacterium",
    "badass",
    "badge",
    "badland",
    "badly",
    "badness",
    "baffle",
    "baffling",
    "bagel",
    "bagful",
    "baggage",
    "bagged",
    "baggie",
    "bagginess",
    "bagging",
    "baggy",
    "bagpipe",
    "baguette",
    "baked",
    "bakery",
    "bakeshop",
    "baking",
    "balance",
    "balancing",
    "balcony",
    "balmy",
    "balsamic",
    "bamboo",
    "banana",
    "banish",
    "banister",
    "banjo",
    "bankable",
    "bankbook",
    "banked",
    "banker",
    "banking",
    "banknote",
    "bankroll",
    "banner",
    "bannister",
    "banshee",
    "banter",
    "barbecue",
    "barbed",
    "barbell",
    "barber",
    "barcode",
    "barge",
    "bargraph",
    "barista",
    "baritone",
    "barley",
    "barmaid",
    "barman",
    "barn",
    "barometer",
    "barrack",
    "barracuda",
    "barrel",
    "barrette",
    "barricade",
    "barrier",
    "barstool",
    "bartender",
    "barterer",
    "bash",
    "basically",
    "basics",
    "basil",
    "basin",
    "basis",
    "basket",
    "batboy",
    "batch",
    "bath",
    "baton",
    "bats",
    "battalion",
    "battered",
    "battering",
    "battery",
    "batting",
    "battle",
    "bauble",
    "bazooka",
    "blabber",
    "bladder",
    "blade",
    "blah",
    "blame",
    "blaming",
    "blanching",
    "blandness",
    "blank",
    "blaspheme",
    "blasphemy",
    "blast",
    "blatancy",
    "blatantly",
    "blazer",
    "blazing",
    "bleach",
    "bleak",
    "bleep",
    "blemish",
    "blend",
    "bless",
    "blighted",
    "blimp",
    "bling",
    "blinked",
    "blinker",
    "blinking",
    "blinks",
    "blip",
    "blissful",
    "blitz",
    "blizzard",
    "bloated",
    "bloating",
    "blob",
    "blog",
    "bloomers",
    "blooming",
    "blooper",
    "blot",
    "blouse",
    "blubber",
    "bluff",
    "bluish",
    "blunderer",
    "blunt",
    "blurb",
    "blurred",
    "blurry",
    "blurt",
    "blush",
    "blustery",
    "boaster",
    "boastful",
    "boasting",
    "boat",
    "bobbed",
    "bobbing",
    "bobble",
    "bobcat",
    "bobsled",
    "bobtail",
    "bodacious",
    "body",
    "bogged",
    "boggle",
    "bogus",
    "boil",
    "bok",
    "bolster",
    "bolt",
    "bonanza",
    "bonded",
    "bonding",
    "bondless",
    "boned",
    "bonehead",
    "boneless",
    "bonelike",
    "boney",
    "bonfire",
    "bonnet",
    "bonsai",
    "bonus",
    "bony",
    "boogeyman",
    "boogieman",
    "book",
    "boondocks",
    "booted",
    "booth",
    "bootie",
    "booting",
    "bootlace",
    "bootleg",
    "boots",
    "boozy",
    "borax",
    "boring",
    "borough",
    "borrower",
    "borrowing",
    "boss",
    "botanical",
    "botanist",
    "botany",
    "botch",
    "both",
    "bottle",
    "bottling",
    "bottom",
    "bounce",
    "bouncing",
    "bouncy",
    "bounding",
    "boundless",
    "bountiful",
    "bovine",
    "boxcar",
    "boxer",
    "boxing",
    "boxlike",
    "boxy",
    "breach",
    "breath",
    "breeches",
    "breeching",
    "breeder",
    "breeding",
    "breeze",
    "breezy",
    "brethren",
    "brewery",
    "brewing",
    "briar",
    "bribe",
    "brick",
    "bride",
    "bridged",
    "brigade",
    "bright",
    "brilliant",
    "brim",
    "bring",
    "brink",
    "brisket",
    "briskly",
    "briskness",
    "bristle",
    "brittle",
    "broadband",
    "broadcast",
    "broaden",
    "broadly",
    "broadness",
    "broadside",
    "broadways",
    "broiler",
    "broiling",
    "broken",
    "broker",
    "bronchial",
    "bronco",
    "bronze",
    "bronzing",
    "brook",
    "broom",
    "brought",
    "browbeat",
    "brownnose",
    "browse",
    "browsing",
    "bruising",
    "brunch",
    "brunette",
    "brunt",
    "brush",
    "brussels",
    "brute",
    "brutishly",
    "bubble",
    "bubbling",
    "bubbly",
    "buccaneer",
    "bucked",
    "bucket",
    "buckle",
    "buckshot",
    "buckskin",
    "bucktooth",
    "buckwheat",
    "buddhism",
    "buddhist",
    "budding",
    "buddy",
    "budget",
    "buffalo",
    "buffed",
    "buffer",
    "buffing",
    "buffoon",
    "buggy",
    "bulb",
    "bulge",
    "bulginess",
    "bulgur",
    "bulk",
    "bulldog",
    "bulldozer",
    "bullfight",
    "bullfrog",
    "bullhorn",
    "bullion",
    "bullish",
    "bullpen",
    "bullring",
    "bullseye",
    "bullwhip",
    "bully",
    "bunch",
    "bundle",
    "bungee",
    "bunion",
    "bunkbed",
    "bunkhouse",
    "bunkmate",
    "bunny",
    "bunt",
    "busboy",
    "bush",
    "busily",
    "busload",
    "bust",
    "busybody",
    "buzz",
    "cabana",
    "cabbage",
    "cabbie",
    "cabdriver",
    "cable",
    "caboose",
    "cache",
    "cackle",
    "cacti",
    "cactus",
    "caddie",
    "caddy",
    "cadet",
    "cadillac",
    "cadmium",
    "cage",
    "cahoots",
    "cake",
    "calamari",
    "calamity",
    "calcium",
    "calculate",
    "calculus",
    "caliber",
    "calibrate",
    "calm",
    "caloric",
    "calorie",
    "calzone",
    "camcorder",
    "cameo",
    "camera",
    "camisole",
    "camper",
    "campfire",
    "camping",
    "campsite",
    "campus",
    "canal",
    "canary",
    "cancel",
    "candied",
    "candle",
    "candy",
    "cane",
    "canine",
    "canister",
    "cannabis",
    "canned",
    "canning",
    "cannon",
    "cannot",
    "canola",
    "canon",
    "canopener",
    "canopy",
    "canteen",
    "canyon",
    "capable",
    "capably",
    "capacity",
    "cape",
    "capillary",
    "capital",
    "capitol",
    "capped",
    "capricorn",
    "capsize",
    "capsule",
    "caption",
    "captivate",
    "captive",
    "captivity",
    "capture",
    "caramel",
    "carat",
    "caravan",
    "carbon",
    "cardboard",
    "carded",
    "cardiac",
    "cardigan",
    "cardinal",
    "cardstock",
    "carefully",
    "caregiver",
    "careless",
    "caress",
    "caretaker",
    "cargo",
    "caring",
    "carless",
    "carload",
    "carmaker",
    "carnage",
    "carnation",
    "carnival",
    "carnivore",
    "carol",
    "carpenter",
    "carpentry",
    "carpool",
    "carport",
    "carried",
    "carrot",
    "carrousel",
    "carry",
    "cartel",
    "cartload",
    "carton",
    "cartoon",
    "cartridge",
    "cartwheel",
    "carve",
    "carving",
    "carwash",
    "cascade",
    "case",
    "cash",
    "casing",
    "casino",
    "casket",
    "cassette",
    "casually",
    "casualty",
    "catacomb",
    "catalog",
    "catalyst",
    "catalyze",
    "catapult",
    "cataract",
    "catatonic",
    "catcall",
    "catchable",
    "catcher",
    "catching",
    "catchy",
    "caterer",
    "catering",
    "catfight",
    "catfish",
    "cathedral",
    "cathouse",
    "catlike",
    "catnap",
    "catnip",
    "catsup",
    "cattail",
    "cattishly",
    "cattle",
    "catty",
    "catwalk",
    "caucasian",
    "caucus",
    "causal",
    "causation",
    "cause",
    "causing",
    "cauterize",
    "caution",
    "cautious",
    "cavalier",
    "cavalry",
    "caviar",
    "cavity",
    "cedar",
    "celery",
    "celestial",
    "celibacy",
    "celibate",
    "celtic",
    "cement",
    "census",
    "ceramics",
    "ceremony",
    "certainly",
    "certainty",
    "certified",
    "certify",
    "cesarean",
    "cesspool",
    "chafe",
    "chaffing",
    "chain",
    "chair",
    "chalice",
    "challenge",
    "chamber",
    "chamomile",
    "champion",
    "chance",
    "change",
    "channel",
    "chant",
    "chaos",
    "chaperone",
    "chaplain",
    "chapped",
    "chaps",
    "chapter",
    "character",
    "charbroil",
    "charcoal",
    "charger",
    "charging",
    "chariot",
    "charity",
    "charm",
    "charred",
    "charter",
    "charting",
    "chase",
    "chasing",
    "chaste",
    "chastise",
    "chastity",
    "chatroom",
    "chatter",
    "chatting",
    "chatty",
    "cheating",
    "cheddar",
    "cheek",
    "cheer",
    "cheese",
    "cheesy",
    "chef",
    "chemicals",
    "chemist",
    "chemo",
    "cherisher",
    "cherub",
    "chess",
    "chest",
    "chevron",
    "chevy",
    "chewable",
    "chewer",
    "chewing",
    "chewy",
    "chief",
    "chihuahua",
    "childcare",
    "childhood",
    "childish",
    "childless",
    "childlike",
    "chili",
    "chill",
    "chimp",
    "chip",
    "chirping",
    "chirpy",
    "chitchat",
    "chivalry",
    "chive",
    "chloride",
    "chlorine",
    "choice",
    "chokehold",
    "choking",
    "chomp",
    "chooser",
    "choosing",
    "choosy",
    "chop",
    "chosen",
    "chowder",
    "chowtime",
    "chrome",
    "chubby",
    "chuck",
    "chug",
    "chummy",
    "chump",
    "chunk",
    "churn",
    "chute",
    "cider",
    "cilantro",
    "cinch",
    "cinema",
    "cinnamon",
    "circle",
    "circling",
    "circular",
    "circulate",
    "circus",
    "citable",
    "citadel",
    "citation",
    "citizen",
    "citric",
    "citrus",
    "city",
    "civic",
    "civil",
    "clad",
    "claim",
    "clambake",
    "clammy",
    "clamor",
    "clamp",
    "clamshell",
    "clang",
    "clanking",
    "clapped",
    "clapper",
    "clapping",
    "clarify",
    "clarinet",
    "clarity",
    "clash",
    "clasp",
    "class",
    "clatter",
    "clause",
    "clavicle",
    "claw",
    "clay",
    "clean",
    "clear",
    "cleat",
    "cleaver",
    "cleft",
    "clench",
    "clergyman",
    "clerical",
    "clerk",
    "clever",
    "clicker",
    "client",
    "climate",
    "climatic",
    "cling",
    "clinic",
    "clinking",
    "clip",
    "clique",
    "cloak",
    "clobber",
    "clock",
    "clone",
    "cloning",
    "closable",
    "closure",
    "clothes",
    "clothing",
    "cloud",
    "clover",
    "clubbed",
    "clubbing",
    "clubhouse",
    "clump",
    "clumsily",
    "clumsy",
    "clunky",
    "clustered",
    "clutch",
    "clutter",
    "coach",
    "coagulant",
    "coastal",
    "coaster",
    "coasting",
    "coastland",
    "coastline",
    "coat",
    "coauthor",
    "cobalt",
    "cobbler",
    "cobweb",
    "cocoa",
    "coconut",
    "cod",
    "coeditor",
    "coerce",
    "coexist",
    "coffee",
    "cofounder",
    "cognition",
    "cognitive",
    "cogwheel",
    "coherence",
    "coherent",
    "cohesive",
    "coil",
    "coke",
    "cola",
    "cold",
    "coleslaw",
    "coliseum",
    "collage",
    "collapse",
    "collar",
    "collected",
    "collector",
    "collide",
    "collie",
    "collision",
    "colonial",
    "colonist",
    "colonize",
    "colony",
    "colossal",
    "colt",
    "coma",
    "come",
    "comfort",
    "comfy",
    "comic",
    "coming",
    "comma",
    "commence",
    "commend",
    "comment",
    "commerce",
    "commode",
    "commodity",
    "commodore",
    "common",
    "commotion",
    "commute",
    "commuting",
    "compacted",
    "compacter",
    "compactly",
    "compactor",
    "companion",
    "company",
    "compare",
    "compel",
    "compile",
    "comply",
    "component",
    "composed",
    "composer",
    "composite",
    "compost",
    "composure",
    "compound",
    "compress",
    "comprised",
    "computer",
    "computing",
    "comrade",
    "concave",
    "conceal",
    "conceded",
    "concept",
    "concerned",
    "concert",
    "conch",
    "concierge",
    "concise",
    "conclude",
    "concrete",
    "concur",
    "condense",
    "condiment",
    "condition",
    "condone",
    "conducive",
    "conductor",
    "conduit",
    "cone",
    "confess",
    "confetti",
    "confidant",
    "confident",
    "confider",
    "confiding",
    "configure",
    "confined",
    "confining",
    "confirm",
    "conflict",
    "conform",
    "confound",
    "confront",
    "confused",
    "confusing",
    "confusion",
    "congenial",
    "congested",
    "congrats",
    "congress",
    "conical",
    "conjoined",
    "conjure",
    "conjuror",
    "connected",
    "connector",
    "consensus",
    "consent",
    "console",
    "consoling",
    "consonant",
    "constable",
    "constant",
    "constrain",
    "constrict",
    "construct",
    "consult",
    "consumer",
    "consuming",
    "contact",
    "container",
    "contempt",
    "contend",
    "contented",
    "contently",
    "contents",
    "contest",
    "context",
    "contort",
    "contour",
    "contrite",
    "control",
    "contusion",
    "convene",
    "convent",
    "copartner",
    "cope",
    "copied",
    "copier",
    "copilot",
    "coping",
    "copious",
    "copper",
    "copy",
    "coral",
    "cork",
    "cornball",
    "cornbread",
    "corncob",
    "cornea",
    "corned",
    "corner",
    "cornfield",
    "cornflake",
    "cornhusk",
    "cornmeal",
    "cornstalk",
    "corny",
    "coronary",
    "coroner",
    "corporal",
    "corporate",
    "corral",
    "correct",
    "corridor",
    "corrode",
    "corroding",
    "corrosive",
    "corsage",
    "corset",
    "cortex",
    "cosigner",
    "cosmetics",
    "cosmic",
    "cosmos",
    "cosponsor",
    "cost",
    "cottage",
    "cotton",
    "couch",
    "cough",
    "could",
    "countable",
    "countdown",
    "counting",
    "countless",
    "country",
    "county",
    "courier",
    "covenant",
    "cover",
    "coveted",
    "coveting",
    "coyness",
    "cozily",
    "coziness",
    "cozy",
    "crabbing",
    "crabgrass",
    "crablike",
    "crabmeat",
    "cradle",
    "cradling",
    "crafter",
    "craftily",
    "craftsman",
    "craftwork",
    "crafty",
    "cramp",
    "cranberry",
    "crane",
    "cranial",
    "cranium",
    "crank",
    "crate",
    "crave",
    "craving",
    "crawfish",
    "crawlers",
    "crawling",
    "crayfish",
    "crayon",
    "crazed",
    "crazily",
    "craziness",
    "crazy",
    "creamed",
    "creamer",
    "creamlike",
    "crease",
    "creasing",
    "creatable",
    "create",
    "creation",
    "creative",
    "creature",
    "credible",
    "credibly",
    "credit",
    "creed",
    "creme",
    "creole",
    "crepe",
    "crept",
    "crescent",
    "crested",
    "cresting",
    "crestless",
    "crevice",
    "crewless",
    "crewman",
    "crewmate",
    "crib",
    "cricket",
    "cried",
    "crier",
    "crimp",
    "crimson",
    "cringe",
    "cringing",
    "crinkle",
    "crinkly",
    "crisped",
    "crisping",
    "crisply",
    "crispness",
    "crispy",
    "criteria",
    "critter",
    "croak",
    "crock",
    "crook",
    "croon",
    "crop",
    "cross",
    "crouch",
    "crouton",
    "crowbar",
    "crowd",
    "crown",
    "crucial",
    "crudely",
    "crudeness",
    "cruelly",
    "cruelness",
    "cruelty",
    "crumb",
    "crummiest",
    "crummy",
    "crumpet",
    "crumpled",
    "cruncher",
    "crunching",
    "crunchy",
    "crusader",
    "crushable",
    "crushed",
    "crusher",
    "crushing",
    "crust",
    "crux",
    "crying",
    "cryptic",
    "crystal",
    "cubbyhole",
    "cube",
    "cubical",
    "cubicle",
    "cucumber",
    "cuddle",
    "cuddly",
    "cufflink",
    "culinary",
    "culminate",
    "culpable",
    "culprit",
    "cultivate",
    "cultural",
    "culture",
    "cupbearer",
    "cupcake",
    "cupid",
    "cupped",
    "cupping",
    "curable",
    "curator",
    "curdle",
    "cure",
    "curfew",
    "curing",
    "curled",
    "curler",
    "curliness",
    "curling",
    "curly",
    "curry",
    "curse",
    "cursive",
    "cursor",
    "curtain",
    "curtly",
    "curtsy",
    "curvature",
    "curve",
    "curvy",
    "cushy",
    "cusp",
    "cussed",
    "custard",
    "custodian",
    "custody",
    "customary",
    "customer",
    "customize",
    "customs",
    "cut",
    "cycle",
    "cyclic",
    "cycling",
    "cyclist",
    "cylinder",
    "cymbal",
    "cytoplasm",
    "cytoplast",
    "dab",
    "dad",
    "daffodil",
    "dagger",
    "daily",
    "daintily",
    "dainty",
    "dairy",
    "daisy",
    "dallying",
    "dance",
    "dancing",
    "dandelion",
    "dander",
    "dandruff",
    "dandy",
    "danger",
    "dangle",
    "dangling",
    "daredevil",
    "dares",
    "daringly",
    "darkened",
    "darkening",
    "darkish",
    "darkness",
    "darkroom",
    "darling",
    "darn",
    "dart",
    "darwinism",
    "dash",
    "dastardly",
    "data",
    "datebook",
    "dating",
    "daughter",
    "daunting",
    "dawdler",
    "dawn",
    "daybed",
    "daybreak",
    "daycare",
    "daydream",
    "daylight",
    "daylong",
    "dayroom",
    "daytime",
    "dazzler",
    "dazzling",
    "deacon",
    "deafening",
    "deafness",
    "dealer",
    "dealing",
    "dealmaker",
    "dealt",
    "dean",
    "debatable",
    "debate",
    "debating",
    "debit",
    "debrief",
    "debtless",
    "debtor",
    "debug",
    "debunk",
    "decade",
    "decaf",
    "decal",
    "decathlon",
    "decay",
    "deceased",
    "deceit",
    "deceiver",
    "deceiving",
    "december",
    "decency",
    "decent",
    "deception",
    "deceptive",
    "decibel",
    "decidable",
    "decimal",
    "decimeter",
    "decipher",
    "deck",
    "declared",
    "decline",
    "decode",
    "decompose",
    "decorated",
    "decorator",
    "decoy",
    "decrease",
    "decree",
    "dedicate",
    "dedicator",
    "deduce",
    "deduct",
    "deed",
    "deem",
    "deepen",
    "deeply",
    "deepness",
    "deface",
    "defacing",
    "defame",
    "default",
    "defeat",
    "defection",
    "defective",
    "defendant",
    "defender",
    "defense",
    "defensive",
    "deferral",
    "deferred",
    "defiance",
    "defiant",
    "defile",
    "defiling",
    "define",
    "definite",
    "deflate",
    "deflation",
    "deflator",
    "deflected",
    "deflector",
    "defog",
    "deforest",
    "defraud",
    "defrost",
    "deftly",
    "defuse",
    "defy",
    "degraded",
    "degrading",
    "degrease",
    "degree",
    "dehydrate",
    "deity",
    "dejected",
    "delay",
    "delegate",
    "delegator",
    "delete",
    "deletion",
    "delicacy",
    "delicate",
    "delicious",
    "delighted",
    "delirious",
    "delirium",
    "deliverer",
    "delivery",
    "delouse",
    "delta",
    "deluge",
    "delusion",
    "deluxe",
    "demanding",
    "demeaning",
    "demeanor",
    "demise",
    "democracy",
    "democrat",
    "demote",
    "demotion",
    "demystify",
    "denatured",
    "deniable",
    "denial",
    "denim",
    "denote",
    "dense",
    "density",
    "dental",
    "dentist",
    "denture",
    "deny",
    "deodorant",
    "deodorize",
    "departed",
    "departure",
    "depict",
    "deplete",
    "depletion",
    "deplored",
    "deploy",
    "deport",
    "depose",
    "depraved",
    "depravity",
    "deprecate",
    "depress",
    "deprive",
    "depth",
    "deputize",
    "deputy",
    "derail",
    "deranged",
    "derby",
    "derived",
    "desecrate",
    "deserve",
    "deserving",
    "designate",
    "designed",
    "designer",
    "designing",
    "deskbound",
    "desktop",
    "deskwork",
    "desolate",
    "despair",
    "despise",
    "despite",
    "destiny",
    "destitute",
    "destruct",
    "detached",
    "detail",
    "detection",
    "detective",
    "detector",
    "detention",
    "detergent",
    "detest",
    "detonate",
    "detonator",
    "detoxify",
    "detract",
    "deuce",
    "devalue",
    "deviancy",
    "deviant",
    "deviate",
    "deviation",
    "deviator",
    "device",
    "devious",
    "devotedly",
    "devotee",
    "devotion",
    "devourer",
    "devouring",
    "devoutly",
    "dexterity",
    "dexterous",
    "diabetes",
    "diabetic",
    "diabolic",
    "diagnoses",
    "diagnosis",
    "diagram",
    "dial",
    "diameter",
    "diaper",
    "diaphragm",
    "diary",
    "dice",
    "dicing",
    "dictate",
    "dictation",
    "dictator",
    "difficult",
    "diffused",
    "diffuser",
    "diffusion",
    "diffusive",
    "dig",
    "dilation",
    "diligence",
    "diligent",
    "dill",
    "dilute",
    "dime",
    "diminish",
    "dimly",
    "dimmed",
    "dimmer",
    "dimness",
    "dimple",
    "diner",
    "dingbat",
    "dinghy",
    "dinginess",
    "dingo",
    "dingy",
    "dining",
    "dinner",
    "diocese",
    "dioxide",
    "diploma",
    "dipped",
    "dipper",
    "dipping",
    "directed",
    "direction",
    "directive",
    "directly",
    "directory",
    "direness",
    "dirtiness",
    "disabled",
    "disagree",
    "disallow",
    "disarm",
    "disarray",
    "disaster",
    "disband",
    "disbelief",
    "disburse",
    "discard",
    "discern",
    "discharge",
    "disclose",
    "discolor",
    "discount",
    "discourse",
    "discover",
    "discuss",
    "disdain",
    "disengage",
    "disfigure",
    "disgrace",
    "dish",
    "disinfect",
    "disjoin",
    "disk",
    "dislike",
    "disliking",
    "dislocate",
    "dislodge",
    "disloyal",
    "dismantle",
    "dismay",
    "dismiss",
    "dismount",
    "disobey",
    "disorder",
    "disown",
    "disparate",
    "disparity",
    "dispatch",
    "dispense",
    "dispersal",
    "dispersed",
    "disperser",
    "displace",
    "display",
    "displease",
    "disposal",
    "dispose",
    "disprove",
    "dispute",
    "disregard",
    "disrupt",
    "dissuade",
    "distance",
    "distant",
    "distaste",
    "distill",
    "distinct",
    "distort",
    "distract",
    "distress",
    "district",
    "distrust",
    "ditch",
    "ditto",
    "ditzy",
    "dividable",
    "divided",
    "dividend",
    "dividers",
    "dividing",
    "divinely",
    "diving",
    "divinity",
    "divisible",
    "divisibly",
    "division",
    "divisive",
    "divorcee",
    "dizziness",
    "dizzy",
    "doable",
    "docile",
    "dock",
    "doctrine",
    "document",
    "dodge",
    "dodgy",
    "doily",
    "doing",
    "dole",
    "dollar",
    "dollhouse",
    "dollop",
    "dolly",
    "dolphin",
    "domain",
    "domelike",
    "domestic",
    "dominion",
    "dominoes",
    "donated",
    "donation",
    "donator",
    "donor",
    "donut",
    "doodle",
    "doorbell",
    "doorframe",
    "doorknob",
    "doorman",
    "doormat",
    "doornail",
    "doorpost",
    "doorstep",
    "doorstop",
    "doorway",
    "doozy",
    "dork",
    "dormitory",
    "dorsal",
    "dosage",
    "dose",
    "dotted",
    "doubling",
    "douche",
    "dove",
    "down",
    "dowry",
    "doze",
    "drab",
    "dragging",
    "dragonfly",
    "dragonish",
    "dragster",
    "drainable",
    "drainage",
    "drained",
    "drainer",
    "drainpipe",
    "dramatic",
    "dramatize",
    "drank",
    "drapery",
    "drastic",
    "draw",
    "dreaded",
    "dreadful",
    "dreadlock",
    "dreamboat",
    "dreamily",
    "dreamland",
    "dreamless",
    "dreamlike",
    "dreamt",
    "dreamy",
    "drearily",
    "dreary",
    "drench",
    "dress",
    "drew",
    "dribble",
    "dried",
    "drier",
    "drift",
    "driller",
    "drilling",
    "drinkable",
    "drinking",
    "dripping",
    "drippy",
    "drivable",
    "driven",
    "driver",
    "driveway",
    "driving",
    "drizzle",
    "drizzly",
    "drone",
    "drool",
    "droop",
    "drop-down",
    "dropbox",
    "dropkick",
    "droplet",
    "dropout",
    "dropper",
    "drove",
    "drown",
    "drowsily",
    "drudge",
    "drum",
    "dry",
    "dubbed",
    "dubiously",
    "duchess",
    "duckbill",
    "ducking",
    "duckling",
    "ducktail",
    "ducky",
    "duct",
    "dude",
    "duffel",
    "dugout",
    "duh",
    "duke",
    "duller",
    "dullness",
    "duly",
    "dumping",
    "dumpling",
    "dumpster",
    "duo",
    "dupe",
    "duplex",
    "duplicate",
    "duplicity",
    "durable",
    "durably",
    "duration",
    "duress",
    "during",
    "dusk",
    "dust",
    "dutiful",
    "duty",
    "duvet",
    "dwarf",
    "dweeb",
    "dwelled",
    "dweller",
    "dwelling",
    "dwindle",
    "dwindling",
    "dynamic",
    "dynamite",
    "dynasty",
    "dyslexia",
    "dyslexic",
    "each",
    "eagle",
    "earache",
    "eardrum",
    "earflap",
    "earful",
    "earlobe",
    "early",
    "earmark",
    "earmuff",
    "earphone",
    "earpiece",
    "earplugs",
    "earring",
    "earshot",
    "earthen",
    "earthlike",
    "earthling",
    "earthly",
    "earthworm",
    "earthy",
    "earwig",
    "easeful",
    "easel",
    "easiest",
    "easily",
    "easiness",
    "easing",
    "eastbound",
    "eastcoast",
    "easter",
    "eastward",
    "eatable",
    "eaten",
    "eatery",
    "eating",
    "eats",
    "ebay",
    "ebony",
    "ebook",
    "ecard",
    "eccentric",
    "echo",
    "eclair",
    "eclipse",
    "ecologist",
    "ecology",
    "economic",
    "economist",
    "economy",
    "ecosphere",
    "ecosystem",
    "edge",
    "edginess",
    "edging",
    "edgy",
    "edition",
    "editor",
    "educated",
    "education",
    "educator",
    "eel",
    "effective",
    "effects",
    "efficient",
    "effort",
    "eggbeater",
    "egging",
    "eggnog",
    "eggplant",
    "eggshell",
    "egomaniac",
    "egotism",
    "egotistic",
    "either",
    "eject",
    "elaborate",
    "elastic",
    "elated",
    "elbow",
    "eldercare",
    "elderly",
    "eldest",
    "electable",
    "election",
    "elective",
    "elephant",
    "elevate",
    "elevating",
    "elevation",
    "elevator",
    "eleven",
    "elf",
    "eligible",
    "eligibly",
    "eliminate",
    "elite",
    "elitism",
    "elixir",
    "elk",
    "ellipse",
    "elliptic",
    "elm",
    "elongated",
    "elope",
    "eloquence",
    "eloquent",
    "elsewhere",
    "elude",
    "elusive",
    "elves",
    "email",
    "embargo",
    "embark",
    "embassy",
    "embattled",
    "embellish",
    "ember",
    "embezzle",
    "emblaze",
    "emblem",
    "embody",
    "embolism",
    "emboss",
    "embroider",
    "emcee",
    "emerald",
    "emergency",
    "emission",
    "emit",
    "emote",
    "emoticon",
    "emotion",
    "empathic",
    "empathy",
    "emperor",
    "emphases",
    "emphasis",
    "emphasize",
    "emphatic",
    "empirical",
    "employed",
    "employee",
    "employer",
    "emporium",
    "empower",
    "emptier",
    "emptiness",
    "empty",
    "emu",
    "enable",
    "enactment",
    "enamel",
    "enchanted",
    "enchilada",
    "encircle",
    "enclose",
    "enclosure",
    "encode",
    "encore",
    "encounter",
    "encourage",
    "encroach",
    "encrust",
    "encrypt",
    "endanger",
    "endeared",
    "endearing",
    "ended",
    "ending",
    "endless",
    "endnote",
    "endocrine",
    "endorphin",
    "endorse",
    "endowment",
    "endpoint",
    "endurable",
    "endurance",
    "enduring",
    "energetic",
    "energize",
    "energy",
    "enforced",
    "enforcer",
    "engaged",
    "engaging",
    "engine",
    "engorge",
    "engraved",
    "engraver",
    "engraving",
    "engross",
    "engulf",
    "enhance",
    "enigmatic",
    "enjoyable",
    "enjoyably",
    "enjoyer",
    "enjoying",
    "enjoyment",
    "enlarged",
    "enlarging",
    "enlighten",
    "enlisted",
    "enquirer",
    "enrage",
    "enrich",
    "enroll",
    "enslave",
    "ensnare",
    "ensure",
    "entail",
    "entangled",
    "entering",
    "entertain",
    "enticing",
    "entire",
    "entitle",
    "entity",
    "entomb",
    "entourage",
    "entrap",
    "entree",
    "entrench",
    "entrust",
    "entryway",
    "entwine",
    "enunciate",
    "envelope",
    "enviable",
    "enviably",
    "envious",
    "envision",
    "envoy",
    "envy",
    "enzyme",
    "epic",
    "epidemic",
    "epidermal",
    "epidermis",
    "epidural",
    "epilepsy",
    "epileptic",
    "epilogue",
    "epiphany",
    "episode",
    "equal",
    "equate",
    "equation",
    "equator",
    "equinox",
    "equipment",
    "equity",
    "equivocal",
    "eradicate",
    "erasable",
    "erased",
    "eraser",
    "erasure",
    "ergonomic",
    "errand",
    "errant",
    "erratic",
    "error",
    "erupt",
    "escalate",
    "escalator",
    "escapable",
    "escapade",
    "escapist",
    "escargot",
    "eskimo",
    "esophagus",
    "espionage",
    "espresso",
    "esquire",
    "essay",
    "essence",
    "essential",
    "establish",
    "estate",
    "esteemed",
    "estimate",
    "estimator",
    "estranged",
    "estrogen",
    "etching",
    "eternal",
    "eternity",
    "ethanol",
    "ether",
    "ethically",
    "ethics",
    "euphemism",
    "evacuate",
    "evacuee",
    "evade",
    "evaluate",
    "evaluator",
    "evaporate",
    "evasion",
    "evasive",
    "even",
    "everglade",
    "evergreen",
    "everybody",
    "everyday",
    "everyone",
    "evict",
    "evidence",
    "evident",
    "evil",
    "evoke",
    "evolution",
    "evolve",
    "exact",
    "exalted",
    "example",
    "excavate",
    "excavator",
    "exceeding",
    "exception",
    "excess",
    "exchange",
    "excitable",
    "exciting",
    "exclaim",
    "exclude",
    "excluding",
    "exclusion",
    "exclusive",
    "excretion",
    "excretory",
    "excursion",
    "excusable",
    "excusably",
    "excuse",
    "exemplary",
    "exemplify",
    "exemption",
    "exerciser",
    "exert",
    "exes",
    "exfoliate",
    "exhale",
    "exhaust",
    "exhume",
    "exile",
    "existing",
    "exit",
    "exodus",
    "exonerate",
    "exorcism",
    "exorcist",
    "expand",
    "expanse",
    "expansion",
    "expansive",
    "expectant",
    "expedited",
    "expediter",
    "expel",
    "expend",
    "expenses",
    "expensive",
    "expert",
    "expire",
    "expiring",
    "explain",
    "expletive",
    "explicit",
    "explode",
    "exploit",
    "explore",
    "exploring",
    "exponent",
    "exporter",
    "exposable",
    "expose",
    "exposure",
    "express",
    "expulsion",
    "exquisite",
    "extended",
    "extending",
    "extent",
    "extenuate",
    "exterior",
    "external",
    "extinct",
    "extortion",
    "extradite",
    "extras",
    "extrovert",
    "extrude",
    "extruding",
    "exuberant",
    "fable",
    "fabric",
    "fabulous",
    "facebook",
    "facecloth",
    "facedown",
    "faceless",
    "facelift",
    "faceplate",
    "faceted",
    "facial",
    "facility",
    "facing",
    "facsimile",
    "faction",
    "factoid",
    "factor",
    "factsheet",
    "factual",
    "faculty",
    "fade",
    "fading",
    "failing",
    "falcon",
    "fall",
    "false",
    "falsify",
    "fame",
    "familiar",
    "family",
    "famine",
    "famished",
    "fanatic",
    "fancied",
    "fanciness",
    "fancy",
    "fanfare",
    "fang",
    "fanning",
    "fantasize",
    "fantastic",
    "fantasy",
    "fascism",
    "fastball",
    "faster",
    "fasting",
    "fastness",
    "faucet",
    "favorable",
    "favorably",
    "favored",
    "favoring",
    "favorite",
    "fax",
    "feast",
    "federal",
    "fedora",
    "feeble",
    "feed",
    "feel",
    "feisty",
    "feline",
    "felt-tip",
    "feminine",
    "feminism",
    "feminist",
    "feminize",
    "femur",
    "fence",
    "fencing",
    "fender",
    "ferment",
    "fernlike",
    "ferocious",
    "ferocity",
    "ferret",
    "ferris",
    "ferry",
    "fervor",
    "fester",
    "festival",
    "festive",
    "festivity",
    "fetal",
    "fetch",
    "fever",
    "fiber",
    "fiction",
    "fiddle",
    "fiddling",
    "fidelity",
    "fidgeting",
    "fidgety",
    "fifteen",
    "fifth",
    "fiftieth",
    "fifty",
    "figment",
    "figure",
    "figurine",
    "filing",
    "filled",
    "filler",
    "filling",
    "film",
    "filter",
    "filth",
    "filtrate",
    "finale",
    "finalist",
    "finalize",
    "finally",
    "finance",
    "financial",
    "finch",
    "fineness",
    "finer",
    "finicky",
    "finished",
    "finisher",
    "finishing",
    "finite",
    "finless",
    "finlike",
    "fiscally",
    "fit",
    "five",
    "flaccid",
    "flagman",
    "flagpole",
    "flagship",
    "flagstick",
    "flagstone",
    "flail",
    "flakily",
    "flaky",
    "flame",
    "flammable",
    "flanked",
    "flanking",
    "flannels",
    "flap",
    "flaring",
    "flashback",
    "flashbulb",
    "flashcard",
    "flashily",
    "flashing",
    "flashy",
    "flask",
    "flatbed",
    "flatfoot",
    "flatly",
    "flatness",
    "flatten",
    "flattered",
    "flatterer",
    "flattery",
    "flattop",
    "flatware",
    "flatworm",
    "flavored",
    "flavorful",
    "flavoring",
    "flaxseed",
    "fled",
    "fleshed",
    "fleshy",
    "flick",
    "flier",
    "flight",
    "flinch",
    "fling",
    "flint",
    "flip",
    "flirt",
    "float",
    "flock",
    "flogging",
    "flop",
    "floral",
    "florist",
    "floss",
    "flounder",
    "flyable",
    "flyaway",
    "flyer",
    "flying",
    "flyover",
    "flypaper",
    "foam",
    "foe",
    "fog",
    "foil",
    "folic",
    "folk",
    "follicle",
    "follow",
    "fondling",
    "fondly",
    "fondness",
    "fondue",
    "font",
    "food",
    "fool",
    "footage",
    "football",
    "footbath",
    "footboard",
    "footer",
    "footgear",
    "foothill",
    "foothold",
    "footing",
    "footless",
    "footman",
    "footnote",
    "footpad",
    "footpath",
    "footprint",
    "footrest",
    "footsie",
    "footsore",
    "footwear",
    "footwork",
    "fossil",
    "foster",
    "founder",
    "founding",
    "fountain",
    "fox",
    "foyer",
    "fraction",
    "fracture",
    "fragile",
    "fragility",
    "fragment",
    "fragrance",
    "fragrant",
    "frail",
    "frame",
    "framing",
    "frantic",
    "fraternal",
    "frayed",
    "fraying",
    "frays",
    "freckled",
    "freckles",
    "freebase",
    "freebee",
    "freebie",
    "freedom",
    "freefall",
    "freehand",
    "freeing",
    "freeload",
    "freely",
    "freemason",
    "freeness",
    "freestyle",
    "freeware",
    "freeway",
    "freewill",
    "freezable",
    "freezing",
    "freight",
    "french",
    "frenzied",
    "frenzy",
    "frequency",
    "frequent",
    "fresh",
    "fretful",
    "fretted",
    "friction",
    "friday",
    "fridge",
    "fried",
    "friend",
    "frighten",
    "frightful",
    "frigidity",
    "frigidly",
    "frill",
    "fringe",
    "frisbee",
    "frisk",
    "fritter",
    "frivolous",
    "frolic",
    "from",
    "front",
    "frostbite",
    "frosted",
    "frostily",
    "frosting",
    "frostlike",
    "frosty",
    "froth",
    "frown",
    "frozen",
    "fructose",
    "frugality",
    "frugally",
    "fruit",
    "frustrate",
    "frying",
    "gab",
    "gaffe",
    "gag",
    "gainfully",
    "gaining",
    "gains",
    "gala",
    "gallantly",
    "galleria",
    "gallery",
    "galley",
    "gallon",
    "gallows",
    "gallstone",
    "galore",
    "galvanize",
    "gambling",
    "game",
    "gaming",
    "gamma",
    "gander",
    "gangly",
    "gangrene",
    "gangway",
    "gap",
    "garage",
    "garbage",
    "garden",
    "gargle",
    "garland",
    "garlic",
    "garment",
    "garnet",
    "garnish",
    "garter",
    "gas",
    "gatherer",
    "gathering",
    "gating",
    "gauging",
    "gauntlet",
    "gauze",
    "gave",
    "gawk",
    "gazing",
    "gear",
    "gecko",
    "geek",
    "geiger",
    "gem",
    "gender",
    "generic",
    "generous",
    "genetics",
    "genre",
    "gentile",
    "gentleman",
    "gently",
    "gents",
    "geography",
    "geologic",
    "geologist",
    "geology",
    "geometric",
    "geometry",
    "geranium",
    "gerbil",
    "geriatric",
    "germicide",
    "germinate",
    "germless",
    "germproof",
    "gestate",
    "gestation",
    "gesture",
    "getaway",
    "getting",
    "getup",
    "giant",
    "gibberish",
    "giblet",
    "giddily",
    "giddiness",
    "giddy",
    "gift",
    "gigabyte",
    "gigahertz",
    "gigantic",
    "giggle",
    "giggling",
    "giggly",
    "gigolo",
    "gilled",
    "gills",
    "gimmick",
    "girdle",
    "giveaway",
    "given",
    "giver",
    "giving",
    "gizmo",
    "gizzard",
    "glacial",
    "glacier",
    "glade",
    "gladiator",
    "gladly",
    "glamorous",
    "glamour",
    "glance",
    "glancing",
    "glandular",
    "glare",
    "glaring",
    "glass",
    "glaucoma",
    "glazing",
    "gleaming",
    "gleeful",
    "glider",
    "gliding",
    "glimmer",
    "glimpse",
    "glisten",
    "glitch",
    "glitter",
    "glitzy",
    "gloater",
    "gloating",
    "gloomily",
    "gloomy",
    "glorified",
    "glorifier",
    "glorify",
    "glorious",
    "glory",
    "gloss",
    "glove",
    "glowing",
    "glowworm",
    "glucose",
    "glue",
    "gluten",
    "glutinous",
    "glutton",
    "gnarly",
    "gnat",
    "goal",
    "goatskin",
    "goes",
    "goggles",
    "going",
    "goldfish",
    "goldmine",
    "goldsmith",
    "golf",
    "goliath",
    "gonad",
    "gondola",
    "gone",
    "gong",
    "good",
    "gooey",
    "goofball",
    "goofiness",
    "goofy",
    "google",
    "goon",
    "gopher",
    "gore",
    "gorged",
    "gorgeous",
    "gory",
    "gosling",
    "gossip",
    "gothic",
    "gotten",
    "gout",
    "gown",
    "grab",
    "graceful",
    "graceless",
    "gracious",
    "gradation",
    "graded",
    "grader",
    "gradient",
    "grading",
    "gradually",
    "graduate",
    "graffiti",
    "grafted",
    "grafting",
    "grain",
    "granddad",
    "grandkid",
    "grandly",
    "grandma",
    "grandpa",
    "grandson",
    "granite",
    "granny",
    "granola",
    "grant",
    "granular",
    "grape",
    "graph",
    "grapple",
    "grappling",
    "grasp",
    "grass",
    "gratified",
    "gratify",
    "grating",
    "gratitude",
    "gratuity",
    "gravel",
    "graveness",
    "graves",
    "graveyard",
    "gravitate",
    "gravity",
    "gravy",
    "gray",
    "grazing",
    "greasily",
    "greedily",
    "greedless",
    "greedy",
    "green",
    "greeter",
    "greeting",
    "grew",
    "greyhound",
    "grid",
    "grief",
    "grievance",
    "grieving",
    "grievous",
    "grill",
    "grimace",
    "grimacing",
    "grime",
    "griminess",
    "grimy",
    "grinch",
    "grinning",
    "grip",
    "gristle",
    "grit",
    "groggily",
    "groggy",
    "groin",
    "groom",
    "groove",
    "grooving",
    "groovy",
    "grope",
    "ground",
    "grouped",
    "grout",
    "grove",
    "grower",
    "growing",
    "growl",
    "grub",
    "grudge",
    "grudging",
    "grueling",
    "gruffly",
    "grumble",
    "grumbling",
    "grumbly",
    "grumpily",
    "grunge",
    "grunt",
    "guacamole",
    "guidable",
    "guidance",
    "guide",
    "guiding",
    "guileless",
    "guise",
    "gulf",
    "gullible",
    "gully",
    "gulp",
    "gumball",
    "gumdrop",
    "gumminess",
    "gumming",
    "gummy",
    "gurgle",
    "gurgling",
    "guru",
    "gush",
    "gusto",
    "gusty",
    "gutless",
    "guts",
    "gutter",
    "guy",
    "guzzler",
    "gyration",
    "habitable",
    "habitant",
    "habitat",
    "habitual",
    "hacked",
    "hacker",
    "hacking",
    "hacksaw",
    "had",
    "haggler",
    "haiku",
    "half",
    "halogen",
    "halt",
    "halved",
    "halves",
    "hamburger",
    "hamlet",
    "hammock",
    "hamper",
    "hamster",
    "hamstring",
    "handbag",
    "handball",
    "handbook",
    "handbrake",
    "handcart",
    "handclap",
    "handclasp",
    "handcraft",
    "handcuff",
    "handed",
    "handful",
    "handgrip",
    "handgun",
    "handheld",
    "handiness",
    "handiwork",
    "handlebar",
    "handled",
    "handler",
    "handling",
    "handmade",
    "handoff",
    "handpick",
    "handprint",
    "handrail",
    "handsaw",
    "handset",
    "handsfree",
    "handshake",
    "handstand",
    "handwash",
    "handwork",
    "handwoven",
    "handwrite",
    "handyman",
    "hangnail",
    "hangout",
    "hangover",
    "hangup",
    "hankering",
    "hankie",
    "hanky",
    "haphazard",
    "happening",
    "happier",
    "happiest",
    "happily",
    "happiness",
    "happy",
    "harbor",
    "hardcopy",
    "hardcore",
    "hardcover",
    "harddisk",
    "hardened",
    "hardener",
    "hardening",
    "hardhat",
    "hardhead",
    "hardiness",
    "hardly",
    "hardness",
    "hardship",
    "hardware",
    "hardwired",
    "hardwood",
    "hardy",
    "harmful",
    "harmless",
    "harmonica",
    "harmonics",
    "harmonize",
    "harmony",
    "harness",
    "harpist",
    "harsh",
    "harvest",
    "hash",
    "hassle",
    "haste",
    "hastily",
    "hastiness",
    "hasty",
    "hatbox",
    "hatchback",
    "hatchery",
    "hatchet",
    "hatching",
    "hatchling",
    "hate",
    "hatless",
    "hatred",
    "haunt",
    "haven",
    "hazard",
    "hazelnut",
    "hazily",
    "haziness",
    "hazing",
    "hazy",
    "headache",
    "headband",
    "headboard",
    "headcount",
    "headdress",
    "headed",
    "header",
    "headfirst",
    "headgear",
    "heading",
    "headlamp",
    "headless",
    "headlock",
    "headphone",
    "headpiece",
    "headrest",
    "headroom",
    "headscarf",
    "headset",
    "headsman",
    "headstand",
    "headstone",
    "headway",
    "headwear",
    "heap",
    "heat",
    "heave",
    "heavily",
    "heaviness",
    "heaving",
    "hedge",
    "hedging",
    "heftiness",
    "hefty",
    "helium",
    "helmet",
    "helper",
    "helpful",
    "helping",
    "helpless",
    "helpline",
    "hemlock",
    "hemstitch",
    "hence",
    "henchman",
    "henna",
    "herald",
    "herbal",
    "herbicide",
    "herbs",
    "heritage",
    "hermit",
    "heroics",
    "heroism",
    "herring",
    "herself",
    "hertz",
    "hesitancy",
    "hesitant",
    "hesitate",
    "hexagon",
    "hexagram",
    "hubcap",
    "huddle",
    "huddling",
    "huff",
    "hug",
    "hula",
    "hulk",
    "hull",
    "human",
    "humble",
    "humbling",
    "humbly",
    "humid",
    "humiliate",
    "humility",
    "humming",
    "hummus",
    "humongous",
    "humorist",
    "humorless",
    "humorous",
    "humpback",
    "humped",
    "humvee",
    "hunchback",
    "hundredth",
    "hunger",
    "hungrily",
    "hungry",
    "hunk",
    "hunter",
    "hunting",
    "huntress",
    "huntsman",
    "hurdle",
    "hurled",
    "hurler",
    "hurling",
    "hurray",
    "hurricane",
    "hurried",
    "hurry",
    "hurt",
    "husband",
    "hush",
    "husked",
    "huskiness",
    "hut",
    "hybrid",
    "hydrant",
    "hydrated",
    "hydration",
    "hydrogen",
    "hydroxide",
    "hyperlink",
    "hypertext",
    "hyphen",
    "hypnoses",
    "hypnosis",
    "hypnotic",
    "hypnotism",
    "hypnotist",
    "hypnotize",
    "hypocrisy",
    "hypocrite",
    "ibuprofen",
    "ice",
    "iciness",
    "icing",
    "icky",
    "icon",
    "icy",
    "idealism",
    "idealist",
    "idealize",
    "ideally",
    "idealness",
    "identical",
    "identify",
    "identity",
    "ideology",
    "idiocy",
    "idiom",
    "idly",
    "igloo",
    "ignition",
    "ignore",
    "iguana",
    "illicitly",
    "illusion",
    "illusive",
    "image",
    "imaginary",
    "imagines",
    "imaging",
    "imbecile",
    "imitate",
    "imitation",
    "immature",
    "immerse",
    "immersion",
    "imminent",
    "immobile",
    "immodest",
    "immorally",
    "immortal",
    "immovable",
    "immovably",
    "immunity",
    "immunize",
    "impaired",
    "impale",
    "impart",
    "impatient",
    "impeach",
    "impeding",
    "impending",
    "imperfect",
    "imperial",
    "impish",
    "implant",
    "implement",
    "implicate",
    "implicit",
    "implode",
    "implosion",
    "implosive",
    "imply",
    "impolite",
    "important",
    "importer",
    "impose",
    "imposing",
    "impotence",
    "impotency",
    "impotent",
    "impound",
    "imprecise",
    "imprint",
    "imprison",
    "impromptu",
    "improper",
    "improve",
    "improving",
    "improvise",
    "imprudent",
    "impulse",
    "impulsive",
    "impure",
    "impurity",
    "iodine",
    "iodize",
    "ion",
    "ipad",
    "iphone",
    "ipod",
    "irate",
    "irk",
    "iron",
    "irregular",
    "irrigate",
    "irritable",
    "irritably",
    "irritant",
    "irritate",
    "islamic",
    "islamist",
    "isolated",
    "isolating",
    "isolation",
    "isotope",
    "issue",
    "issuing",
    "italicize",
    "italics",
    "item",
    "itinerary",
    "itunes",
    "ivory",
    "ivy",
    "jab",
    "jackal",
    "jacket",
    "jackknife",
    "jackpot",
    "jailbird",
    "jailbreak",
    "jailer",
    "jailhouse",
    "jalapeno",
    "jam",
    "janitor",
    "january",
    "jargon",
    "jarring",
    "jasmine",
    "jaundice",
    "jaunt",
    "java",
    "jawed",
    "jawless",
    "jawline",
    "jaws",
    "jaybird",
    "jaywalker",
    "jazz",
    "jeep",
    "jeeringly",
    "jellied",
    "jelly",
    "jersey",
    "jester",
    "jet",
    "jiffy",
    "jigsaw",
    "jimmy",
    "jingle",
    "jingling",
    "jinx",
    "jitters",
    "jittery",
    "job",
    "jockey",
    "jockstrap",
    "jogger",
    "jogging",
    "john",
    "joining",
    "jokester",
    "jokingly",
    "jolliness",
    "jolly",
    "jolt",
    "jot",
    "jovial",
    "joyfully",
    "joylessly",
    "joyous",
    "joyride",
    "joystick",
    "jubilance",
    "jubilant",
    "judge",
    "judgingly",
    "judicial",
    "judiciary",
    "judo",
    "juggle",
    "juggling",
    "jugular",
    "juice",
    "juiciness",
    "juicy",
    "jujitsu",
    "jukebox",
    "july",
    "jumble",
    "jumbo",
    "jump",
    "junction",
    "juncture",
    "june",
    "junior",
    "juniper",
    "junkie",
    "junkman",
    "junkyard",
    "jurist",
    "juror",
    "jury",
    "justice",
    "justifier",
    "justify",
    "justly",
    "justness",
    "juvenile",
    "kabob",
    "kangaroo",
    "karaoke",
    "karate",
    "karma",
    "kebab",
    "keenly",
    "keenness",
    "keep",
    "keg",
    "kelp",
    "kennel",
    "kept",
    "kerchief",
    "kerosene",
    "kettle",
    "kick",
    "kiln",
    "kilobyte",
    "kilogram",
    "kilometer",
    "kilowatt",
    "kilt",
    "kimono",
    "kindle",
    "kindling",
    "kindly",
    "kindness",
    "kindred",
    "kinetic",
    "kinfolk",
    "king",
    "kinship",
    "kinsman",
    "kinswoman",
    "kissable",
    "kisser",
    "kissing",
    "kitchen",
    "kite",
    "kitten",
    "kitty",
    "kiwi",
    "kleenex",
    "knapsack",
    "knee",
    "knelt",
    "knickers",
    "knoll",
    "koala",
    "kooky",
    "kosher",
    "krypton",
    "kudos",
    "kung",
    "labored",
    "laborer",
    "laboring",
    "laborious",
    "labrador",
    "ladder",
    "ladies",
    "ladle",
    "ladybug",
    "ladylike",
    "lagged",
    "lagging",
    "lagoon",
    "lair",
    "lake",
    "lance",
    "landed",
    "landfall",
    "landfill",
    "landing",
    "landlady",
    "landless",
    "landline",
    "landlord",
    "landmark",
    "landmass",
    "landmine",
    "landowner",
    "landscape",
    "landside",
    "landslide",
    "language",
    "lankiness",
    "lanky",
    "lantern",
    "lapdog",
    "lapel",
    "lapped",
    "lapping",
    "laptop",
    "lard",
    "large",
    "lark",
    "lash",
    "lasso",
    "last",
    "latch",
    "late",
    "lather",
    "latitude",
    "latrine",
    "latter",
    "latticed",
    "launch",
    "launder",
    "laundry",
    "laurel",
    "lavender",
    "lavish",
    "laxative",
    "lazily",
    "laziness",
    "lazy",
    "lecturer",
    "left",
    "legacy",
    "legal",
    "legend",
    "legged",
    "leggings",
    "legible",
    "legibly",
    "legislate",
    "lego",
    "legroom",
    "legume",
    "legwarmer",
    "legwork",
    "lemon",
    "lend",
    "length",
    "lens",
    "lent",
    "leotard",
    "lesser",
    "letdown",
    "lethargic",
    "lethargy",
    "letter",
    "lettuce",
    "level",
    "leverage",
    "levers",
    "levitate",
    "levitator",
    "liability",
    "liable",
    "liberty",
    "librarian",
    "library",
    "licking",
    "licorice",
    "lid",
    "life",
    "lifter",
    "lifting",
    "liftoff",
    "ligament",
    "likely",
    "likeness",
    "likewise",
    "liking",
    "lilac",
    "lilly",
    "lily",
    "limb",
    "limeade",
    "limelight",
    "limes",
    "limit",
    "limping",
    "limpness",
    "line",
    "lingo",
    "linguini",
    "linguist",
    "lining",
    "linked",
    "linoleum",
    "linseed",
    "lint",
    "lion",
    "lip",
    "liquefy",
    "liqueur",
    "liquid",
    "lisp",
    "list",
    "litigate",
    "litigator",
    "litmus",
    "litter",
    "little",
    "livable",
    "lived",
    "lively",
    "liver",
    "livestock",
    "lividly",
    "living",
    "lizard",
    "lubricant",
    "lubricate",
    "lucid",
    "luckily",
    "luckiness",
    "luckless",
    "lucrative",
    "ludicrous",
    "lugged",
    "lukewarm",
    "lullaby",
    "lumber",
    "luminance",
    "luminous",
    "lumpiness",
    "lumping",
    "lumpish",
    "lunacy",
    "lunar",
    "lunchbox",
    "luncheon",
    "lunchroom",
    "lunchtime",
    "lung",
    "lurch",
    "lure",
    "luridness",
    "lurk",
    "lushly",
    "lushness",
    "luster",
    "lustfully",
    "lustily",
    "lustiness",
    "lustrous",
    "lusty",
    "luxurious",
    "luxury",
    "lying",
    "lyrically",
    "lyricism",
    "lyricist",
    "lyrics",
    "macarena",
    "macaroni",
    "macaw",
    "mace",
    "machine",
    "machinist",
    "magazine",
    "magenta",
    "maggot",
    "magical",
    "magician",
    "magma",
    "magnesium",
    "magnetic",
    "magnetism",
    "magnetize",
    "magnifier",
    "magnify",
    "magnitude",
    "magnolia",
    "mahogany",
    "maimed",
    "majestic",
    "majesty",
    "majorette",
    "majority",
    "makeover",
    "maker",
    "makeshift",
    "making",
    "malformed",
    "malt",
    "mama",
    "mammal",
    "mammary",
    "mammogram",
    "manager",
    "managing",
    "manatee",
    "mandarin",
    "mandate",
    "mandatory",
    "mandolin",
    "manger",
    "mangle",
    "mango",
    "mangy",
    "manhandle",
    "manhole",
    "manhood",
    "manhunt",
    "manicotti",
    "manicure",
    "manifesto",
    "manila",
    "mankind",
    "manlike",
    "manliness",
    "manly",
    "manmade",
    "manned",
    "mannish",
    "manor",
    "manpower",
    "mantis",
    "mantra",
    "manual",
    "many",
    "map",
    "marathon",
    "marauding",
    "marbled",
    "marbles",
    "marbling",
    "march",
    "mardi",
    "margarine",
    "margarita",
    "margin",
    "marigold",
    "marina",
    "marine",
    "marital",
    "maritime",
    "marlin",
    "marmalade",
    "maroon",
    "married",
    "marrow",
    "marry",
    "marshland",
    "marshy",
    "marsupial",
    "marvelous",
    "marxism",
    "mascot",
    "masculine",
    "mashed",
    "mashing",
    "massager",
    "masses",
    "massive",
    "mastiff",
    "matador",
    "matchbook",
    "matchbox",
    "matcher",
    "matching",
    "matchless",
    "material",
    "maternal",
    "maternity",
    "math",
    "mating",
    "matriarch",
    "matrimony",
    "matrix",
    "matron",
    "matted",
    "matter",
    "maturely",
    "maturing",
    "maturity",
    "mauve",
    "maverick",
    "maximize",
    "maximum",
    "maybe",
    "mayday",
    "mayflower",
    "moaner",
    "moaning",
    "mobile",
    "mobility",
    "mobilize",
    "mobster",
    "mocha",
    "mocker",
    "mockup",
    "modified",
    "modify",
    "modular",
    "modulator",
    "module",
    "moisten",
    "moistness",
    "moisture",
    "molar",
    "molasses",
    "mold",
    "molecular",
    "molecule",
    "molehill",
    "mollusk",
    "mom",
    "monastery",
    "monday",
    "monetary",
    "monetize",
    "moneybags",
    "moneyless",
    "moneywise",
    "mongoose",
    "mongrel",
    "monitor",
    "monkhood",
    "monogamy",
    "monogram",
    "monologue",
    "monopoly",
    "monorail",
    "monotone",
    "monotype",
    "monoxide",
    "monsieur",
    "monsoon",
    "monstrous",
    "monthly",
    "monument",
    "moocher",
    "moodiness",
    "moody",
    "mooing",
    "moonbeam",
    "mooned",
    "moonlight",
    "moonlike",
    "moonlit",
    "moonrise",
    "moonscape",
    "moonshine",
    "moonstone",
    "moonwalk",
    "mop",
    "morale",
    "morality",
    "morally",
    "morbidity",
    "morbidly",
    "morphine",
    "morphing",
    "morse",
    "mortality",
    "mortally",
    "mortician",
    "mortified",
    "mortify",
    "mortuary",
    "mosaic",
    "mossy",
    "most",
    "mothball",
    "mothproof",
    "motion",
    "motivate",
    "motivator",
    "motive",
    "motocross",
    "motor",
    "motto",
    "mountable",
    "mountain",
    "mounted",
    "mounting",
    "mourner",
    "mournful",
    "mouse",
    "mousiness",
    "moustache",
    "mousy",
    "mouth",
    "movable",
    "move",
    "movie",
    "moving",
    "mower",
    "mowing",
    "much",
    "muck",
    "mud",
    "mug",
    "mulberry",
    "mulch",
    "mule",
    "mulled",
    "mullets",
    "multiple",
    "multiply",
    "multitask",
    "multitude",
    "mumble",
    "mumbling",
    "mumbo",
    "mummified",
    "mummify",
    "mummy",
    "mumps",
    "munchkin",
    "mundane",
    "municipal",
    "muppet",
    "mural",
    "murkiness",
    "murky",
    "murmuring",
    "muscular",
    "museum",
    "mushily",
    "mushiness",
    "mushroom",
    "mushy",
    "music",
    "musket",
    "muskiness",
    "musky",
    "mustang",
    "mustard",
    "muster",
    "mustiness",
    "musty",
    "mutable",
    "mutate",
    "mutation",
    "mute",
    "mutilated",
    "mutilator",
    "mutiny",
    "mutt",
    "mutual",
    "muzzle",
    "myself",
    "myspace",
    "mystified",
    "mystify",
    "myth",
    "nacho",
    "nag",
    "nail",
    "name",
    "naming",
    "nanny",
    "nanometer",
    "nape",
    "napkin",
    "napped",
    "napping",
    "nappy",
    "narrow",
    "nastily",
    "nastiness",
    "national",
    "native",
    "nativity",
    "natural",
    "nature",
    "naturist",
    "nautical",
    "navigate",
    "navigator",
    "navy",
    "nearby",
    "nearest",
    "nearly",
    "nearness",
    "neatly",
    "neatness",
    "nebula",
    "nebulizer",
    "nectar",
    "negate",
    "negation",
    "negative",
    "neglector",
    "negligee",
    "negligent",
    "negotiate",
    "nemeses",
    "nemesis",
    "neon",
    "nephew",
    "nerd",
    "nervous",
    "nervy",
    "nest",
    "net",
    "neurology",
    "neuron",
    "neurosis",
    "neurotic",
    "neuter",
    "neutron",
    "never",
    "next",
    "nibble",
    "nickname",
    "nicotine",
    "niece",
    "nifty",
    "nimble",
    "nimbly",
    "nineteen",
    "ninetieth",
    "ninja",
    "nintendo",
    "ninth",
    "nuclear",
    "nuclei",
    "nucleus",
    "nugget",
    "nullify",
    "number",
    "numbing",
    "numbly",
    "numbness",
    "numeral",
    "numerate",
    "numerator",
    "numeric",
    "numerous",
    "nuptials",
    "nursery",
    "nursing",
    "nurture",
    "nutcase",
    "nutlike",
    "nutmeg",
    "nutrient",
    "nutshell",
    "nuttiness",
    "nutty",
    "nuzzle",
    "nylon",
    "oaf",
    "oak",
    "oasis",
    "oat",
    "obedience",
    "obedient",
    "obituary",
    "object",
    "obligate",
    "obliged",
    "oblivion",
    "oblivious",
    "oblong",
    "obnoxious",
    "oboe",
    "obscure",
    "obscurity",
    "observant",
    "observer",
    "observing",
    "obsessed",
    "obsession",
    "obsessive",
    "obsolete",
    "obstacle",
    "obstinate",
    "obstruct",
    "obtain",
    "obtrusive",
    "obtuse",
    "obvious",
    "occultist",
    "occupancy",
    "occupant",
    "occupier",
    "occupy",
    "ocean",
    "ocelot",
    "octagon",
    "octane",
    "october",
    "octopus",
    "ogle",
    "oil",
    "oink",
    "ointment",
    "okay",
    "old",
    "olive",
    "olympics",
    "omega",
    "omen",
    "ominous",
    "omission",
    "omit",
    "omnivore",
    "onboard",
    "oncoming",
    "ongoing",
    "onion",
    "online",
    "onlooker",
    "only",
    "onscreen",
    "onset",
    "onshore",
    "onslaught",
    "onstage",
    "onto",
    "onward",
    "onyx",
    "oops",
    "ooze",
    "oozy",
    "opacity",
    "opal",
    "open",
    "operable",
    "operate",
    "operating",
    "operation",
    "operative",
    "operator",
    "opium",
    "opossum",
    "opponent",
    "oppose",
    "opposing",
    "opposite",
    "oppressed",
    "oppressor",
    "opt",
    "opulently",
    "osmosis",
    "other",
    "otter",
    "ouch",
    "ought",
    "ounce",
    "outage",
    "outback",
    "outbid",
    "outboard",
    "outbound",
    "outbreak",
    "outburst",
    "outcast",
    "outclass",
    "outcome",
    "outdated",
    "outdoors",
    "outer",
    "outfield",
    "outfit",
    "outflank",
    "outgoing",
    "outgrow",
    "outhouse",
    "outing",
    "outlast",
    "outlet",
    "outline",
    "outlook",
    "outlying",
    "outmatch",
    "outmost",
    "outnumber",
    "outplayed",
    "outpost",
    "outpour",
    "output",
    "outrage",
    "outrank",
    "outreach",
    "outright",
    "outscore",
    "outsell",
    "outshine",
    "outshoot",
    "outsider",
    "outskirts",
    "outsmart",
    "outsource",
    "outspoken",
    "outtakes",
    "outthink",
    "outward",
    "outweigh",
    "outwit",
    "oval",
    "ovary",
    "oven",
    "overact",
    "overall",
    "overarch",
    "overbid",
    "overbill",
    "overbite",
    "overblown",
    "overboard",
    "overbook",
    "overbuilt",
    "overcast",
    "overcoat",
    "overcome",
    "overcook",
    "overcrowd",
    "overdraft",
    "overdrawn",
    "overdress",
    "overdrive",
    "overdue",
    "overeager",
    "overeater",
    "overexert",
    "overfed",
    "overfeed",
    "overfill",
    "overflow",
    "overfull",
    "overgrown",
    "overhand",
    "overhang",
    "overhaul",
    "overhead",
    "overhear",
    "overheat",
    "overhung",
    "overjoyed",
    "overkill",
    "overlabor",
    "overlaid",
    "overlap",
    "overlay",
    "overload",
    "overlook",
    "overlord",
    "overlying",
    "overnight",
    "overpass",
    "overpay",
    "overplant",
    "overplay",
    "overpower",
    "overprice",
    "overrate",
    "overreach",
    "overreact",
    "override",
    "overripe",
    "overrule",
    "overrun",
    "overshoot",
    "overshot",
    "oversight",
    "oversized",
    "oversleep",
    "oversold",
    "overspend",
    "overstate",
    "overstay",
    "overstep",
    "overstock",
    "overstuff",
    "oversweet",
    "overtake",
    "overthrow",
    "overtime",
    "overtly",
    "overtone",
    "overture",
    "overturn",
    "overuse",
    "overvalue",
    "overview",
    "overwrite",
    "owl",
    "oxford",
    "oxidant",
    "oxidation",
    "oxidize",
    "oxidizing",
    "oxygen",
    "oxymoron",
    "oyster",
    "ozone",
    "paced",
    "pacemaker",
    "pacific",
    "pacifier",
    "pacifism",
    "pacifist",
    "pacify",
    "padded",
    "padding",
    "paddle",
    "paddling",
    "padlock",
    "pagan",
    "pager",
    "paging",
    "pajamas",
    "palace",
    "palatable",
    "palm",
    "palpable",
    "palpitate",
    "paltry",
    "pampered",
    "pamperer",
    "pampers",
    "pamphlet",
    "panama",
    "pancake",
    "pancreas",
    "panda",
    "pandemic",
    "pang",
    "panhandle",
    "panic",
    "panning",
    "panorama",
    "panoramic",
    "panther",
    "pantomime",
    "pantry",
    "pants",
    "pantyhose",
    "paparazzi",
    "papaya",
    "paper",
    "paprika",
    "papyrus",
    "parabola",
    "parachute",
    "parade",
    "paradox",
    "paragraph",
    "parakeet",
    "paralegal",
    "paralyses",
    "paralysis",
    "paralyze",
    "paramedic",
    "parameter",
    "paramount",
    "parasail",
    "parasite",
    "parasitic",
    "parcel",
    "parched",
    "parchment",
    "pardon",
    "parish",
    "parka",
    "parking",
    "parkway",
    "parlor",
    "parmesan",
    "parole",
    "parrot",
    "parsley",
    "parsnip",
    "partake",
    "parted",
    "parting",
    "partition",
    "partly",
    "partner",
    "partridge",
    "party",
    "passable",
    "passably",
    "passage",
    "passcode",
    "passenger",
    "passerby",
    "passing",
    "passion",
    "passive",
    "passivism",
    "passover",
    "passport",
    "password",
    "pasta",
    "pasted",
    "pastel",
    "pastime",
    "pastor",
    "pastrami",
    "pasture",
    "pasty",
    "patchwork",
    "patchy",
    "paternal",
    "paternity",
    "path",
    "patience",
    "patient",
    "patio",
    "patriarch",
    "patriot",
    "patrol",
    "patronage",
    "patronize",
    "pauper",
    "pavement",
    "paver",
    "pavestone",
    "pavilion",
    "paving",
    "pawing",
    "payable",
    "payback",
    "paycheck",
    "payday",
    "payee",
    "payer",
    "paying",
    "payment",
    "payphone",
    "payroll",
    "pebble",
    "pebbly",
    "pecan",
    "pectin",
    "peculiar",
    "peddling",
    "pediatric",
    "pedicure",
    "pedigree",
    "pedometer",
    "pegboard",
    "pelican",
    "pellet",
    "pelt",
    "pelvis",
    "penalize",
    "penalty",
    "pencil",
    "pendant",
    "pending",
    "penholder",
    "penknife",
    "pennant",
    "penniless",
    "penny",
    "penpal",
    "pension",
    "pentagon",
    "pentagram",
    "pep",
    "perceive",
    "percent",
    "perch",
    "percolate",
    "perennial",
    "perfected",
    "perfectly",
    "perfume",
    "periscope",
    "perish",
    "perjurer",
    "perjury",
    "perkiness",
    "perky",
    "perm",
    "peroxide",
    "perpetual",
    "perplexed",
    "persecute",
    "persevere",
    "persuaded",
    "persuader",
    "pesky",
    "peso",
    "pessimism",
    "pessimist",
    "pester",
    "pesticide",
    "petal",
    "petite",
    "petition",
    "petri",
    "petroleum",
    "petted",
    "petticoat",
    "pettiness",
    "petty",
    "petunia",
    "phantom",
    "phobia",
    "phoenix",
    "phonebook",
    "phoney",
    "phonics",
    "phoniness",
    "phony",
    "phosphate",
    "photo",
    "phrase",
    "phrasing",
    "placard",
    "placate",
    "placidly",
    "plank",
    "planner",
    "plant",
    "plasma",
    "plaster",
    "plastic",
    "plated",
    "platform",
    "plating",
    "platinum",
    "platonic",
    "platter",
    "platypus",
    "plausible",
    "plausibly",
    "playable",
    "playback",
    "player",
    "playful",
    "playgroup",
    "playhouse",
    "playing",
    "playlist",
    "playmaker",
    "playmate",
    "playoff",
    "playpen",
    "playroom",
    "playset",
    "plaything",
    "playtime",
    "plaza",
    "pleading",
    "pleat",
    "pledge",
    "plentiful",
    "plenty",
    "plethora",
    "plexiglas",
    "pliable",
    "plod",
    "plop",
    "plot",
    "plow",
    "ploy",
    "pluck",
    "plug",
    "plunder",
    "plunging",
    "plural",
    "plus",
    "plutonium",
    "plywood",
    "poach",
    "pod",
    "poem",
    "poet",
    "pogo",
    "pointed",
    "pointer",
    "pointing",
    "pointless",
    "pointy",
    "poise",
    "poison",
    "poker",
    "poking",
    "polar",
    "police",
    "policy",
    "polio",
    "polish",
    "politely",
    "polka",
    "polo",
    "polyester",
    "polygon",
    "polygraph",
    "polymer",
    "poncho",
    "pond",
    "pony",
    "popcorn",
    "pope",
    "poplar",
    "popper",
    "poppy",
    "popsicle",
    "populace",
    "popular",
    "populate",
    "porcupine",
    "pork",
    "porous",
    "porridge",
    "portable",
    "portal",
    "portfolio",
    "porthole",
    "portion",
    "portly",
    "portside",
    "poser",
    "posh",
    "posing",
    "possible",
    "possibly",
    "possum",
    "postage",
    "postal",
    "postbox",
    "postcard",
    "posted",
    "poster",
    "posting",
    "postnasal",
    "posture",
    "postwar",
    "pouch",
    "pounce",
    "pouncing",
    "pound",
    "pouring",
    "pout",
    "powdered",
    "powdering",
    "powdery",
    "power",
    "powwow",
    "pox",
    "praising",
    "prance",
    "prancing",
    "pranker",
    "prankish",
    "prankster",
    "prayer",
    "praying",
    "preacher",
    "preaching",
    "preachy",
    "preamble",
    "precinct",
    "precise",
    "precision",
    "precook",
    "precut",
    "predator",
    "predefine",
    "predict",
    "preface",
    "prefix",
    "preflight",
    "preformed",
    "pregame",
    "pregnancy",
    "pregnant",
    "preheated",
    "prelaunch",
    "prelaw",
    "prelude",
    "premiere",
    "premises",
    "premium",
    "prenatal",
    "preoccupy",
    "preorder",
    "prepaid",
    "prepay",
    "preplan",
    "preppy",
    "preschool",
    "prescribe",
    "preseason",
    "preset",
    "preshow",
    "president",
    "presoak",
    "press",
    "presume",
    "presuming",
    "preteen",
    "pretended",
    "pretender",
    "pretense",
    "pretext",
    "pretty",
    "pretzel",
    "prevail",
    "prevalent",
    "prevent",
    "preview",
    "previous",
    "prewar",
    "prewashed",
    "prideful",
    "pried",
    "primal",
    "primarily",
    "primary",
    "primate",
    "primer",
    "primp",
    "princess",
    "print",
    "prior",
    "prism",
    "prison",
    "prissy",
    "pristine",
    "privacy",
    "private",
    "privatize",
    "prize",
    "proactive",
    "probable",
    "probably",
    "probation",
    "probe",
    "probing",
    "probiotic",
    "problem",
    "procedure",
    "process",
    "proclaim",
    "procreate",
    "procurer",
    "prodigal",
    "prodigy",
    "produce",
    "product",
    "profane",
    "profanity",
    "professed",
    "professor",
    "profile",
    "profound",
    "profusely",
    "progeny",
    "prognosis",
    "program",
    "progress",
    "projector",
    "prologue",
    "prolonged",
    "promenade",
    "prominent",
    "promoter",
    "promotion",
    "prompter",
    "promptly",
    "prone",
    "prong",
    "pronounce",
    "pronto",
    "proofing",
    "proofread",
    "proofs",
    "propeller",
    "properly",
    "property",
    "proponent",
    "proposal",
    "propose",
    "props",
    "prorate",
    "protector",
    "protegee",
    "proton",
    "prototype",
    "protozoan",
    "protract",
    "protrude",
    "proud",
    "provable",
    "proved",
    "proven",
    "provided",
    "provider",
    "providing",
    "province",
    "proving",
    "provoke",
    "provoking",
    "provolone",
    "prowess",
    "prowler",
    "prowling",
    "proximity",
    "proxy",
    "prozac",
    "prude",
    "prudishly",
    "prune",
    "pruning",
    "pry",
    "psychic",
    "public",
    "publisher",
    "pucker",
    "pueblo",
    "pug",
    "pull",
    "pulmonary",
    "pulp",
    "pulsate",
    "pulse",
    "pulverize",
    "puma",
    "pumice",
    "pummel",
    "punch",
    "punctual",
    "punctuate",
    "punctured",
    "pungent",
    "punisher",
    "punk",
    "pupil",
    "puppet",
    "puppy",
    "purchase",
    "pureblood",
    "purebred",
    "purely",
    "pureness",
    "purgatory",
    "purge",
    "purging",
    "purifier",
    "purify",
    "purist",
    "puritan",
    "purity",
    "purple",
    "purplish",
    "purposely",
    "purr",
    "purse",
    "pursuable",
    "pursuant",
    "pursuit",
    "purveyor",
    "pushcart",
    "pushchair",
    "pusher",
    "pushiness",
    "pushing",
    "pushover",
    "pushpin",
    "pushup",
    "pushy",
    "putdown",
    "putt",
    "puzzle",
    "puzzling",
    "pyramid",
    "pyromania",
    "python",
    "quack",
    "quadrant",
    "quail",
    "quaintly",
    "quake",
    "quaking",
    "qualified",
    "qualifier",
    "qualify",
    "quality",
    "qualm",
    "quantum",
    "quarrel",
    "quarry",
    "quartered",
    "quarterly",
    "quarters",
    "quartet",
    "quench",
    "query",
    "quicken",
    "quickly",
    "quickness",
    "quicksand",
    "quickstep",
    "quiet",
    "quill",
    "quilt",
    "quintet",
    "quintuple",
    "quirk",
    "quit",
    "quiver",
    "quizzical",
    "quotable",
    "quotation",
    "quote",
    "rabid",
    "race",
    "racing",
    "racism",
    "rack",
    "racoon",
    "radar",
    "radial",
    "radiance",
    "radiantly",
    "radiated",
    "radiation",
    "radiator",
    "radio",
    "radish",
    "raffle",
    "raft",
    "rage",
    "ragged",
    "raging",
    "ragweed",
    "raider",
    "railcar",
    "railing",
    "railroad",
    "railway",
    "raisin",
    "rake",
    "raking",
    "rally",
    "ramble",
    "rambling",
    "ramp",
    "ramrod",
    "ranch",
    "rancidity",
    "random",
    "ranged",
    "ranger",
    "ranging",
    "ranked",
    "ranking",
    "ransack",
    "ranting",
    "rants",
    "rare",
    "rarity",
    "rascal",
    "rash",
    "rasping",
    "ravage",
    "raven",
    "ravine",
    "raving",
    "ravioli",
    "ravishing",
    "reabsorb",
    "reach",
    "reacquire",
    "reaction",
    "reactive",
    "reactor",
    "reaffirm",
    "ream",
    "reanalyze",
    "reappear",
    "reapply",
    "reappoint",
    "reapprove",
    "rearrange",
    "rearview",
    "reason",
    "reassign",
    "reassure",
    "reattach",
    "reawake",
    "rebalance",
    "rebate",
    "rebel",
    "rebirth",
    "reboot",
    "reborn",
    "rebound",
    "rebuff",
    "rebuild",
    "rebuilt",
    "reburial",
    "rebuttal",
    "recall",
    "recant",
    "recapture",
    "recast",
    "recede",
    "recent",
    "recess",
    "recharger",
    "recipient",
    "recital",
    "recite",
    "reckless",
    "reclaim",
    "recliner",
    "reclining",
    "recluse",
    "reclusive",
    "recognize",
    "recoil",
    "recollect",
    "recolor",
    "reconcile",
    "reconfirm",
    "reconvene",
    "recopy",
    "record",
    "recount",
    "recoup",
    "recovery",
    "recreate",
    "rectal",
    "rectangle",
    "rectified",
    "rectify",
    "recycled",
    "recycler",
    "recycling",
    "reemerge",
    "reenact",
    "reenter",
    "reentry",
    "reexamine",
    "referable",
    "referee",
    "reference",
    "refill",
    "refinance",
    "refined",
    "refinery",
    "refining",
    "refinish",
    "reflected",
    "reflector",
    "reflex",
    "reflux",
    "refocus",
    "refold",
    "reforest",
    "reformat",
    "reformed",
    "reformer",
    "reformist",
    "refract",
    "refrain",
    "refreeze",
    "refresh",
    "refried",
    "refueling",
    "refund",
    "refurbish",
    "refurnish",
    "refusal",
    "refuse",
    "refusing",
    "refutable",
    "refute",
    "regain",
    "regalia",
    "regally",
    "reggae",
    "regime",
    "region",
    "register",
    "registrar",
    "registry",
    "regress",
    "regretful",
    "regroup",
    "regular",
    "regulate",
    "regulator",
    "rehab",
    "reheat",
    "rehire",
    "rehydrate",
    "reimburse",
    "reissue",
    "reiterate",
    "rejoice",
    "rejoicing",
    "rejoin",
    "rekindle",
    "relapse",
    "relapsing",
    "relatable",
    "related",
    "relation",
    "relative",
    "relax",
    "relay",
    "relearn",
    "release",
    "relenting",
    "reliable",
    "reliably",
    "reliance",
    "reliant",
    "relic",
    "relieve",
    "relieving",
    "relight",
    "relish",
    "relive",
    "reload",
    "relocate",
    "relock",
    "reluctant",
    "rely",
    "remake",
    "remark",
    "remarry",
    "rematch",
    "remedial",
    "remedy",
    "remember",
    "reminder",
    "remindful",
    "remission",
    "remix",
    "remnant",
    "remodeler",
    "remold",
    "remorse",
    "remote",
    "removable",
    "removal",
    "removed",
    "remover",
    "removing",
    "rename",
    "renderer",
    "rendering",
    "rendition",
    "renegade",
    "renewable",
    "renewably",
    "renewal",
    "renewed",
    "renounce",
    "renovate",
    "renovator",
    "rentable",
    "rental",
    "rented",
    "renter",
    "reoccupy",
    "reoccur",
    "reopen",
    "reorder",
    "repackage",
    "repacking",
    "repaint",
    "repair",
    "repave",
    "repaying",
    "repayment",
    "repeal",
    "repeated",
    "repeater",
    "repent",
    "rephrase",
    "replace",
    "replay",
    "replica",
    "reply",
    "reporter",
    "repose",
    "repossess",
    "repost",
    "repressed",
    "reprimand",
    "reprint",
    "reprise",
    "reproach",
    "reprocess",
    "reproduce",
    "reprogram",
    "reps",
    "reptile",
    "reptilian",
    "repugnant",
    "repulsion",
    "repulsive",
    "repurpose",
    "reputable",
    "reputably",
    "request",
    "require",
    "requisite",
    "reroute",
    "rerun",
    "resale",
    "resample",
    "rescuer",
    "reseal",
    "research",
    "reselect",
    "reseller",
    "resemble",
    "resend",
    "resent",
    "reset",
    "reshape",
    "reshoot",
    "reshuffle",
    "residence",
    "residency",
    "resident",
    "residual",
    "residue",
    "resigned",
    "resilient",
    "resistant",
    "resisting",
    "resize",
    "resolute",
    "resolved",
    "resonant",
    "resonate",
    "resort",
    "resource",
    "respect",
    "resubmit",
    "result",
    "resume",
    "resupply",
    "resurface",
    "resurrect",
    "retail",
    "retainer",
    "retaining",
    "retake",
    "retaliate",
    "retention",
    "rethink",
    "retinal",
    "retired",
    "retiree",
    "retiring",
    "retold",
    "retool",
    "retorted",
    "retouch",
    "retrace",
    "retract",
    "retrain",
    "retread",
    "retreat",
    "retrial",
    "retrieval",
    "retriever",
    "retry",
    "return",
    "retying",
    "retype",
    "reunion",
    "reunite",
    "reusable",
    "reuse",
    "reveal",
    "reveler",
    "revenge",
    "revenue",
    "reverb",
    "revered",
    "reverence",
    "reverend",
    "reversal",
    "reverse",
    "reversing",
    "reversion",
    "revert",
    "revisable",
    "revise",
    "revision",
    "revisit",
    "revivable",
    "revival",
    "reviver",
    "reviving",
    "revocable",
    "revoke",
    "revolt",
    "revolver",
    "revolving",
    "reward",
    "rewash",
    "rewind",
    "rewire",
    "reword",
    "rework",
    "rewrap",
    "rewrite",
    "rhyme",
    "ribbon",
    "ribcage",
    "rice",
    "riches",
    "richly",
    "richness",
    "rickety",
    "ricotta",
    "riddance",
    "ridden",
    "ride",
    "riding",
    "rifling",
    "rift",
    "rigging",
    "rigid",
    "rigor",
    "rimless",
    "rimmed",
    "rind",
    "rink",
    "rinse",
    "rinsing",
    "riot",
    "ripcord",
    "ripeness",
    "ripening",
    "ripping",
    "ripple",
    "rippling",
    "riptide",
    "rise",
    "rising",
    "risk",
    "risotto",
    "ritalin",
    "ritzy",
    "rival",
    "riverbank",
    "riverbed",
    "riverboat",
    "riverside",
    "riveter",
    "riveting",
    "roamer",
    "roaming",
    "roast",
    "robbing",
    "robe",
    "robin",
    "robotics",
    "robust",
    "rockband",
    "rocker",
    "rocket",
    "rockfish",
    "rockiness",
    "rocking",
    "rocklike",
    "rockslide",
    "rockstar",
    "rocky",
    "rogue",
    "roman",
    "romp",
    "rope",
    "roping",
    "roster",
    "rosy",
    "rotten",
    "rotting",
    "rotunda",
    "roulette",
    "rounding",
    "roundish",
    "roundness",
    "roundup",
    "roundworm",
    "routine",
    "routing",
    "rover",
    "roving",
    "royal",
    "rubbed",
    "rubber",
    "rubbing",
    "rubble",
    "rubdown",
    "ruby",
    "ruckus",
    "rudder",
    "rug",
    "ruined",
    "rule",
    "rumble",
    "rumbling",
    "rummage",
    "rumor",
    "runaround",
    "rundown",
    "runner",
    "running",
    "runny",
    "runt",
    "runway",
    "rupture",
    "rural",
    "ruse",
    "rush",
    "rust",
    "rut",
    "sabbath",
    "sabotage",
    "sacrament",
    "sacred",
    "sacrifice",
    "sadden",
    "saddlebag",
    "saddled",
    "saddling",
    "sadly",
    "sadness",
    "safari",
    "safeguard",
    "safehouse",
    "safely",
    "safeness",
    "saffron",
    "saga",
    "sage",
    "sagging",
    "saggy",
    "said",
    "saint",
    "sake",
    "salad",
    "salami",
    "salaried",
    "salary",
    "saline",
    "salon",
    "saloon",
    "salsa",
    "salt",
    "salutary",
    "salute",
    "salvage",
    "salvaging",
    "salvation",
    "same",
    "sample",
    "sampling",
    "sanction",
    "sanctity",
    "sanctuary",
    "sandal",
    "sandbag",
    "sandbank",
    "sandbar",
    "sandblast",
    "sandbox",
    "sanded",
    "sandfish",
    "sanding",
    "sandlot",
    "sandpaper",
    "sandpit",
    "sandstone",
    "sandstorm",
    "sandworm",
    "sandy",
    "sanitary",
    "sanitizer",
    "sank",
    "santa",
    "sapling",
    "sappiness",
    "sappy",
    "sarcasm",
    "sarcastic",
    "sardine",
    "sash",
    "sasquatch",
    "sassy",
    "satchel",
    "satiable",
    "satin",
    "satirical",
    "satisfied",
    "satisfy",
    "saturate",
    "saturday",
    "sauciness",
    "saucy",
    "sauna",
    "savage",
    "savanna",
    "saved",
    "savings",
    "savior",
    "savor",
    "saxophone",
    "say",
    "scabbed",
    "scabby",
    "scalded",
    "scalding",
    "scale",
    "scaling",
    "scallion",
    "scallop",
    "scalping",
    "scam",
    "scandal",
    "scanner",
    "scanning",
    "scant",
    "scapegoat",
    "scarce",
    "scarcity",
    "scarecrow",
    "scared",
    "scarf",
    "scarily",
    "scariness",
    "scarring",
    "scary",
    "scavenger",
    "scenic",
    "schedule",
    "schematic",
    "scheme",
    "scheming",
    "schilling",
    "schnapps",
    "scholar",
    "science",
    "scientist",
    "scion",
    "scoff",
    "scolding",
    "scone",
    "scoop",
    "scooter",
    "scope",
    "scorch",
    "scorebook",
    "scorecard",
    "scored",
    "scoreless",
    "scorer",
    "scoring",
    "scorn",
    "scorpion",
    "scotch",
    "scoundrel",
    "scoured",
    "scouring",
    "scouting",
    "scouts",
    "scowling",
    "scrabble",
    "scraggly",
    "scrambled",
    "scrambler",
    "scrap",
    "scratch",
    "scrawny",
    "screen",
    "scribble",
    "scribe",
    "scribing",
    "scrimmage",
    "script",
    "scroll",
    "scrooge",
    "scrounger",
    "scrubbed",
    "scrubber",
    "scruffy",
    "scrunch",
    "scrutiny",
    "scuba",
    "scuff",
    "sculptor",
    "sculpture",
    "scurvy",
    "scuttle",
    "secluded",
    "secluding",
    "seclusion",
    "second",
    "secrecy",
    "secret",
    "sectional",
    "sector",
    "secular",
    "securely",
    "security",
    "sedan",
    "sedate",
    "sedation",
    "sedative",
    "sediment",
    "seduce",
    "seducing",
    "segment",
    "seismic",
    "seizing",
    "seldom",
    "selected",
    "selection",
    "selective",
    "selector",
    "self",
    "seltzer",
    "semantic",
    "semester",
    "semicolon",
    "semifinal",
    "seminar",
    "semisoft",
    "semisweet",
    "senate",
    "senator",
    "send",
    "senior",
    "senorita",
    "sensation",
    "sensitive",
    "sensitize",
    "sensually",
    "sensuous",
    "sepia",
    "september",
    "septic",
    "septum",
    "sequel",
    "sequence",
    "sequester",
    "series",
    "sermon",
    "serotonin",
    "serpent",
    "serrated",
    "serve",
    "service",
    "serving",
    "sesame",
    "sessions",
    "setback",
    "setting",
    "settle",
    "settling",
    "setup",
    "sevenfold",
    "seventeen",
    "seventh",
    "seventy",
    "severity",
    "shabby",
    "shack",
    "shaded",
    "shadily",
    "shadiness",
    "shading",
    "shadow",
    "shady",
    "shaft",
    "shakable",
    "shakily",
    "shakiness",
    "shaking",
    "shaky",
    "shale",
    "shallot",
    "shallow",
    "shame",
    "shampoo",
    "shamrock",
    "shank",
    "shanty",
    "shape",
    "shaping",
    "share",
    "sharpener",
    "sharper",
    "sharpie",
    "sharply",
    "sharpness",
    "shawl",
    "sheath",
    "shed",
    "sheep",
    "sheet",
    "shelf",
    "shell",
    "shelter",
    "shelve",
    "shelving",
    "sherry",
    "shield",
    "shifter",
    "shifting",
    "shiftless",
    "shifty",
    "shimmer",
    "shimmy",
    "shindig",
    "shine",
    "shingle",
    "shininess",
    "shining",
    "shiny",
    "ship",
    "shirt",
    "shivering",
    "shock",
    "shone",
    "shoplift",
    "shopper",
    "shopping",
    "shoptalk",
    "shore",
    "shortage",
    "shortcake",
    "shortcut",
    "shorten",
    "shorter",
    "shorthand",
    "shortlist",
    "shortly",
    "shortness",
    "shorts",
    "shortwave",
    "shorty",
    "shout",
    "shove",
    "showbiz",
    "showcase",
    "showdown",
    "shower",
    "showgirl",
    "showing",
    "showman",
    "shown",
    "showoff",
    "showpiece",
    "showplace",
    "showroom",
    "showy",
    "shrank",
    "shrapnel",
    "shredder",
    "shredding",
    "shrewdly",
    "shriek",
    "shrill",
    "shrimp",
    "shrine",
    "shrink",
    "shrivel",
    "shrouded",
    "shrubbery",
    "shrubs",
    "shrug",
    "shrunk",
    "shucking",
    "shudder",
    "shuffle",
    "shuffling",
    "shun",
    "shush",
    "shut",
    "shy",
    "siamese",
    "siberian",
    "sibling",
    "siding",
    "sierra",
    "siesta",
    "sift",
    "sighing",
    "silenced",
    "silencer",
    "silent",
    "silica",
    "silicon",
    "silk",
    "silliness",
    "silly",
    "silo",
    "silt",
    "silver",
    "similarly",
    "simile",
    "simmering",
    "simple",
    "simplify",
    "simply",
    "sincere",
    "sincerity",
    "singer",
    "singing",
    "single",
    "singular",
    "sinister",
    "sinless",
    "sinner",
    "sinuous",
    "sip",
    "siren",
    "sister",
    "sitcom",
    "sitter",
    "sitting",
    "situated",
    "situation",
    "sixfold",
    "sixteen",
    "sixth",
    "sixties",
    "sixtieth",
    "sixtyfold",
    "sizable",
    "sizably",
    "size",
    "sizing",
    "sizzle",
    "sizzling",
    "skater",
    "skating",
    "skedaddle",
    "skeletal",
    "skeleton",
    "skeptic",
    "sketch",
    "skewed",
    "skewer",
    "skid",
    "skied",
    "skier",
    "skies",
    "skiing",
    "skilled",
    "skillet",
    "skillful",
    "skimmed",
    "skimmer",
    "skimming",
    "skimpily",
    "skincare",
    "skinhead",
    "skinless",
    "skinning",
    "skinny",
    "skintight",
    "skipper",
    "skipping",
    "skirmish",
    "skirt",
    "skittle",
    "skydiver",
    "skylight",
    "skyline",
    "skype",
    "skyrocket",
    "skyward",
    "slab",
    "slacked",
    "slacker",
    "slacking",
    "slackness",
    "slacks",
    "slain",
    "slam",
    "slander",
    "slang",
    "slapping",
    "slapstick",
    "slashed",
    "slashing",
    "slate",
    "slather",
    "slaw",
    "sled",
    "sleek",
    "sleep",
    "sleet",
    "sleeve",
    "slept",
    "sliceable",
    "sliced",
    "slicer",
    "slicing",
    "slick",
    "slider",
    "slideshow",
    "sliding",
    "slighted",
    "slighting",
    "slightly",
    "slimness",
    "slimy",
    "slinging",
    "slingshot",
    "slinky",
    "slip",
    "slit",
    "sliver",
    "slobbery",
    "slogan",
    "sloped",
    "sloping",
    "sloppily",
    "sloppy",
    "slot",
    "slouching",
    "slouchy",
    "sludge",
    "slug",
    "slum",
    "slurp",
    "slush",
    "sly",
    "small",
    "smartly",
    "smartness",
    "smasher",
    "smashing",
    "smashup",
    "smell",
    "smelting",
    "smile",
    "smilingly",
    "smirk",
    "smite",
    "smith",
    "smitten",
    "smock",
    "smog",
    "smoked",
    "smokeless",
    "smokiness",
    "smoking",
    "smoky",
    "smolder",
    "smooth",
    "smother",
    "smudge",
    "smudgy",
    "smuggler",
    "smuggling",
    "smugly",
    "smugness",
    "snack",
    "snagged",
    "snaking",
    "snap",
    "snare",
    "snarl",
    "snazzy",
    "sneak",
    "sneer",
    "sneeze",
    "sneezing",
    "snide",
    "sniff",
    "snippet",
    "snipping",
    "snitch",
    "snooper",
    "snooze",
    "snore",
    "snoring",
    "snorkel",
    "snort",
    "snout",
    "snowbird",
    "snowboard",
    "snowbound",
    "snowcap",
    "snowdrift",
    "snowdrop",
    "snowfall",
    "snowfield",
    "snowflake",
    "snowiness",
    "snowless",
    "snowman",
    "snowplow",
    "snowshoe",
    "snowstorm",
    "snowsuit",
    "snowy",
    "snub",
    "snuff",
    "snuggle",
    "snugly",
    "snugness",
    "speak",
    "spearfish",
    "spearhead",
    "spearman",
    "spearmint",
    "species",
    "specimen",
    "specked",
    "speckled",
    "specks",
    "spectacle",
    "spectator",
    "spectrum",
    "speculate",
    "speech",
    "speed",
    "spellbind",
    "speller",
    "spelling",
    "spendable",
    "spender",
    "spending",
    "spent",
    "spew",
    "sphere",
    "spherical",
    "sphinx",
    "spider",
    "spied",
    "spiffy",
    "spill",
    "spilt",
    "spinach",
    "spinal",
    "spindle",
    "spinner",
    "spinning",
    "spinout",
    "spinster",
    "spiny",
    "spiral",
    "spirited",
    "spiritism",
    "spirits",
    "spiritual",
    "splashed",
    "splashing",
    "splashy",
    "splatter",
    "spleen",
    "splendid",
    "splendor",
    "splice",
    "splicing",
    "splinter",
    "splotchy",
    "splurge",
    "spoilage",
    "spoiled",
    "spoiler",
    "spoiling",
    "spoils",
    "spoken",
    "spokesman",
    "sponge",
    "spongy",
    "sponsor",
    "spoof",
    "spookily",
    "spooky",
    "spool",
    "spoon",
    "spore",
    "sporting",
    "sports",
    "sporty",
    "spotless",
    "spotlight",
    "spotted",
    "spotter",
    "spotting",
    "spotty",
    "spousal",
    "spouse",
    "spout",
    "sprain",
    "sprang",
    "sprawl",
    "spray",
    "spree",
    "sprig",
    "spring",
    "sprinkled",
    "sprinkler",
    "sprint",
    "sprite",
    "sprout",
    "spruce",
    "sprung",
    "spry",
    "spud",
    "spur",
    "sputter",
    "spyglass",
    "squabble",
    "squad",
    "squall",
    "squander",
    "squash",
    "squatted",
    "squatter",
    "squatting",
    "squeak",
    "squealer",
    "squealing",
    "squeamish",
    "squeegee",
    "squeeze",
    "squeezing",
    "squid",
    "squiggle",
    "squiggly",
    "squint",
    "squire",
    "squirt",
    "squishier",
    "squishy",
    "stability",
    "stabilize",
    "stable",
    "stack",
    "stadium",
    "staff",
    "stage",
    "staging",
    "stagnant",
    "stagnate",
    "stainable",
    "stained",
    "staining",
    "stainless",
    "stalemate",
    "staleness",
    "stalling",
    "stallion",
    "stamina",
    "stammer",
    "stamp",
    "stand",
    "stank",
    "staple",
    "stapling",
    "starboard",
    "starch",
    "stardom",
    "stardust",
    "starfish",
    "stargazer",
    "staring",
    "stark",
    "starless",
    "starlet",
    "starlight",
    "starlit",
    "starring",
    "starry",
    "starship",
    "starter",
    "starting",
    "startle",
    "startling",
    "startup",
    "starved",
    "starving",
    "stash",
    "state",
    "static",
    "statistic",
    "statue",
    "stature",
    "status",
    "statute",
    "statutory",
    "staunch",
    "stays",
    "steadfast",
    "steadier",
    "steadily",
    "steadying",
    "steam",
    "steed",
    "steep",
    "steerable",
    "steering",
    "steersman",
    "stegosaur",
    "stellar",
    "stem",
    "stench",
    "stencil",
    "step",
    "stereo",
    "sterile",
    "sterility",
    "sterilize",
    "sterling",
    "sternness",
    "sternum",
    "stew",
    "stick",
    "stiffen",
    "stiffly",
    "stiffness",
    "stifle",
    "stifling",
    "stillness",
    "stilt",
    "stimulant",
    "stimulate",
    "stimuli",
    "stimulus",
    "stinger",
    "stingily",
    "stinging",
    "stingray",
    "stingy",
    "stinking",
    "stinky",
    "stipend",
    "stipulate",
    "stir",
    "stitch",
    "stock",
    "stoic",
    "stoke",
    "stole",
    "stomp",
    "stonewall",
    "stoneware",
    "stonework",
    "stoning",
    "stony",
    "stood",
    "stooge",
    "stool",
    "stoop",
    "stoplight",
    "stoppable",
    "stoppage",
    "stopped",
    "stopper",
    "stopping",
    "stopwatch",
    "storable",
    "storage",
    "storeroom",
    "storewide",
    "storm",
    "stout",
    "stove",
    "stowaway",
    "stowing",
    "straddle",
    "straggler",
    "strained",
    "strainer",
    "straining",
    "strangely",
    "stranger",
    "strangle",
    "strategic",
    "strategy",
    "stratus",
    "straw",
    "stray",
    "streak",
    "stream",
    "street",
    "strength",
    "strenuous",
    "strep",
    "stress",
    "stretch",
    "strewn",
    "stricken",
    "strict",
    "stride",
    "strife",
    "strike",
    "striking",
    "strive",
    "striving",
    "strobe",
    "strode",
    "stroller",
    "strongbox",
    "strongly",
    "strongman",
    "struck",
    "structure",
    "strudel",
    "struggle",
    "strum",
    "strung",
    "strut",
    "stubbed",
    "stubble",
    "stubbly",
    "stubborn",
    "stucco",
    "stuck",
    "student",
    "studied",
    "studio",
    "study",
    "stuffed",
    "stuffing",
    "stuffy",
    "stumble",
    "stumbling",
    "stump",
    "stung",
    "stunned",
    "stunner",
    "stunning",
    "stunt",
    "stupor",
    "sturdily",
    "sturdy",
    "styling",
    "stylishly",
    "stylist",
    "stylized",
    "stylus",
    "suave",
    "subarctic",
    "subatomic",
    "subdivide",
    "subdued",
    "subduing",
    "subfloor",
    "subgroup",
    "subheader",
    "subject",
    "sublease",
    "sublet",
    "sublevel",
    "sublime",
    "submarine",
    "submerge",
    "submersed",
    "submitter",
    "subpanel",
    "subpar",
    "subplot",
    "subprime",
    "subscribe",
    "subscript",
    "subsector",
    "subside",
    "subsiding",
    "subsidize",
    "subsidy",
    "subsoil",
    "subsonic",
    "substance",
    "subsystem",
    "subtext",
    "subtitle",
    "subtly",
    "subtotal",
    "subtract",
    "subtype",
    "suburb",
    "subway",
    "subwoofer",
    "subzero",
    "succulent",
    "such",
    "suction",
    "sudden",
    "sudoku",
    "suds",
    "sufferer",
    "suffering",
    "suffice",
    "suffix",
    "suffocate",
    "suffrage",
    "sugar",
    "suggest",
    "suing",
    "suitable",
    "suitably",
    "suitcase",
    "suitor",
    "sulfate",
    "sulfide",
    "sulfite",
    "sulfur",
    "sulk",
    "sullen",
    "sulphate",
    "sulphuric",
    "sultry",
    "superbowl",
    "superglue",
    "superhero",
    "superior",
    "superjet",
    "superman",
    "supermom",
    "supernova",
    "supervise",
    "supper",
    "supplier",
    "supply",
    "support",
    "supremacy",
    "supreme",
    "surcharge",
    "surely",
    "sureness",
    "surface",
    "surfacing",
    "surfboard",
    "surfer",
    "surgery",
    "surgical",
    "surging",
    "surname",
    "surpass",
    "surplus",
    "surprise",
    "surreal",
    "surrender",
    "surrogate",
    "surround",
    "survey",
    "survival",
    "survive",
    "surviving",
    "survivor",
    "sushi",
    "suspect",
    "suspend",
    "suspense",
    "sustained",
    "sustainer",
    "swab",
    "swaddling",
    "swagger",
    "swampland",
    "swan",
    "swapping",
    "swarm",
    "sway",
    "swear",
    "sweat",
    "sweep",
    "swell",
    "swept",
    "swerve",
    "swifter",
    "swiftly",
    "swiftness",
    "swimmable",
    "swimmer",
    "swimming",
    "swimsuit",
    "swimwear",
    "swinger",
    "swinging",
    "swipe",
    "swirl",
    "switch",
    "swivel",
    "swizzle",
    "swooned",
    "swoop",
    "swoosh",
    "swore",
    "sworn",
    "swung",
    "sycamore",
    "sympathy",
    "symphonic",
    "symphony",
    "symptom",
    "synapse",
    "syndrome",
    "synergy",
    "synopses",
    "synopsis",
    "synthesis",
    "synthetic",
    "syrup",
    "system",
    "t-shirt",
    "tabasco",
    "tabby",
    "tableful",
    "tables",
    "tablet",
    "tableware",
    "tabloid",
    "tackiness",
    "tacking",
    "tackle",
    "tackling",
    "tacky",
    "taco",
    "tactful",
    "tactical",
    "tactics",
    "tactile",
    "tactless",
    "tadpole",
    "taekwondo",
    "tag",
    "tainted",
    "take",
    "taking",
    "talcum",
    "talisman",
    "tall",
    "talon",
    "tamale",
    "tameness",
    "tamer",
    "tamper",
    "tank",
    "tanned",
    "tannery",
    "tanning",
    "tantrum",
    "tapeless",
    "tapered",
    "tapering",
    "tapestry",
    "tapioca",
    "tapping",
    "taps",
    "tarantula",
    "target",
    "tarmac",
    "tarnish",
    "tarot",
    "tartar",
    "tartly",
    "tartness",
    "task",
    "tassel",
    "taste",
    "tastiness",
    "tasting",
    "tasty",
    "tattered",
    "tattle",
    "tattling",
    "tattoo",
    "taunt",
    "tavern",
    "thank",
    "that",
    "thaw",
    "theater",
    "theatrics",
    "thee",
    "theft",
    "theme",
    "theology",
    "theorize",
    "thermal",
    "thermos",
    "thesaurus",
    "these",
    "thesis",
    "thespian",
    "thicken",
    "thicket",
    "thickness",
    "thieving",
    "thievish",
    "thigh",
    "thimble",
    "thing",
    "think",
    "thinly",
    "thinner",
    "thinness",
    "thinning",
    "thirstily",
    "thirsting",
    "thirsty",
    "thirteen",
    "thirty",
    "thong",
    "thorn",
    "those",
    "thousand",
    "thrash",
    "thread",
    "threaten",
    "threefold",
    "thrift",
    "thrill",
    "thrive",
    "thriving",
    "throat",
    "throbbing",
    "throng",
    "throttle",
    "throwaway",
    "throwback",
    "thrower",
    "throwing",
    "thud",
    "thumb",
    "thumping",
    "thursday",
    "thus",
    "thwarting",
    "thyself",
    "tiara",
    "tibia",
    "tidal",
    "tidbit",
    "tidiness",
    "tidings",
    "tidy",
    "tiger",
    "tighten",
    "tightly",
    "tightness",
    "tightrope",
    "tightwad",
    "tigress",
    "tile",
    "tiling",
    "till",
    "tilt",
    "timid",
    "timing",
    "timothy",
    "tinderbox",
    "tinfoil",
    "tingle",
    "tingling",
    "tingly",
    "tinker",
    "tinkling",
    "tinsel",
    "tinsmith",
    "tint",
    "tinwork",
    "tiny",
    "tipoff",
    "tipped",
    "tipper",
    "tipping",
    "tiptoeing",
    "tiptop",
    "tiring",
    "tissue",
    "trace",
    "tracing",
    "track",
    "traction",
    "tractor",
    "trade",
    "trading",
    "tradition",
    "traffic",
    "tragedy",
    "trailing",
    "trailside",
    "train",
    "traitor",
    "trance",
    "tranquil",
    "transfer",
    "transform",
    "translate",
    "transpire",
    "transport",
    "transpose",
    "trapdoor",
    "trapeze",
    "trapezoid",
    "trapped",
    "trapper",
    "trapping",
    "traps",
    "trash",
    "travel",
    "traverse",
    "travesty",
    "tray",
    "treachery",
    "treading",
    "treadmill",
    "treason",
    "treat",
    "treble",
    "tree",
    "trekker",
    "tremble",
    "trembling",
    "tremor",
    "trench",
    "trend",
    "trespass",
    "triage",
    "trial",
    "triangle",
    "tribesman",
    "tribunal",
    "tribune",
    "tributary",
    "tribute",
    "triceps",
    "trickery",
    "trickily",
    "tricking",
    "trickle",
    "trickster",
    "tricky",
    "tricolor",
    "tricycle",
    "trident",
    "tried",
    "trifle",
    "trifocals",
    "trillion",
    "trilogy",
    "trimester",
    "trimmer",
    "trimming",
    "trimness",
    "trinity",
    "trio",
    "tripod",
    "tripping",
    "triumph",
    "trivial",
    "trodden",
    "trolling",
    "trombone",
    "trophy",
    "tropical",
    "tropics",
    "trouble",
    "troubling",
    "trough",
    "trousers",
    "trout",
    "trowel",
    "truce",
    "truck",
    "truffle",
    "trump",
    "trunks",
    "trustable",
    "trustee",
    "trustful",
    "trusting",
    "trustless",
    "truth",
    "try",
    "tubby",
    "tubeless",
    "tubular",
    "tucking",
    "tuesday",
    "tug",
    "tuition",
    "tulip",
    "tumble",
    "tumbling",
    "tummy",
    "turban",
    "turbine",
    "turbofan",
    "turbojet",
    "turbulent",
    "turf",
    "turkey",
    "turmoil",
    "turret",
    "turtle",
    "tusk",
    "tutor",
    "tutu",
    "tux",
    "tweak",
    "tweed",
    "tweet",
    "tweezers",
    "twelve",
    "twentieth",
    "twenty",
    "twerp",
    "twice",
    "twiddle",
    "twiddling",
    "twig",
    "twilight",
    "twine",
    "twins",
    "twirl",
    "twistable",
    "twisted",
    "twister",
    "twisting",
    "twisty",
    "twitch",
    "twitter",
    "tycoon",
    "tying",
    "tyke",
    "udder",
    "ultimate",
    "ultimatum",
    "ultra",
    "umbilical",
    "umbrella",
    "umpire",
    "unabashed",
    "unable",
    "unadorned",
    "unadvised",
    "unafraid",
    "unaired",
    "unaligned",
    "unaltered",
    "unarmored",
    "unashamed",
    "unaudited",
    "unawake",
    "unaware",
    "unbaked",
    "unbalance",
    "unbeaten",
    "unbend",
    "unbent",
    "unbiased",
    "unbitten",
    "unblended",
    "unblessed",
    "unblock",
    "unbolted",
    "unbounded",
    "unboxed",
    "unbraided",
    "unbridle",
    "unbroken",
    "unbuckled",
    "unbundle",
    "unburned",
    "unbutton",
    "uncanny",
    "uncapped",
    "uncaring",
    "uncertain",
    "unchain",
    "unchanged",
    "uncharted",
    "uncheck",
    "uncivil",
    "unclad",
    "unclaimed",
    "unclamped",
    "unclasp",
    "uncle",
    "unclip",
    "uncloak",
    "unclog",
    "unclothed",
    "uncoated",
    "uncoiled",
    "uncolored",
    "uncombed",
    "uncommon",
    "uncooked",
    "uncork",
    "uncorrupt",
    "uncounted",
    "uncouple",
    "uncouth",
    "uncover",
    "uncross",
    "uncrown",
    "uncrushed",
    "uncured",
    "uncurious",
    "uncurled",
    "uncut",
    "undamaged",
    "undated",
    "undaunted",
    "undead",
    "undecided",
    "undefined",
    "underage",
    "underarm",
    "undercoat",
    "undercook",
    "undercut",
    "underdog",
    "underdone",
    "underfed",
    "underfeed",
    "underfoot",
    "undergo",
    "undergrad",
    "underhand",
    "underline",
    "underling",
    "undermine",
    "undermost",
    "underpaid",
    "underpass",
    "underpay",
    "underrate",
    "undertake",
    "undertone",
    "undertook",
    "undertow",
    "underuse",
    "underwear",
    "underwent",
    "underwire",
    "undesired",
    "undiluted",
    "undivided",
    "undocked",
    "undoing",
    "undone",
    "undrafted",
    "undress",
    "undrilled",
    "undusted",
    "undying",
    "unearned",
    "unearth",
    "unease",
    "uneasily",
    "uneasy",
    "uneatable",
    "uneaten",
    "unedited",
    "unelected",
    "unending",
    "unengaged",
    "unenvied",
    "unequal",
    "unethical",
    "uneven",
    "unexpired",
    "unexposed",
    "unfailing",
    "unfair",
    "unfasten",
    "unfazed",
    "unfeeling",
    "unfiled",
    "unfilled",
    "unfitted",
    "unfitting",
    "unfixable",
    "unfixed",
    "unflawed",
    "unfocused",
    "unfold",
    "unfounded",
    "unframed",
    "unfreeze",
    "unfrosted",
    "unfrozen",
    "unfunded",
    "unglazed",
    "ungloved",
    "unglue",
    "ungodly",
    "ungraded",
    "ungreased",
    "unguarded",
    "unguided",
    "unhappily",
    "unhappy",
    "unharmed",
    "unhealthy",
    "unheard",
    "unhearing",
    "unheated",
    "unhelpful",
    "unhidden",
    "unhinge",
    "unhitched",
    "unholy",
    "unhook",
    "unicorn",
    "unicycle",
    "unified",
    "unifier",
    "uniformed",
    "uniformly",
    "unify",
    "unimpeded",
    "uninjured",
    "uninstall",
    "uninsured",
    "uninvited",
    "union",
    "uniquely",
    "unisexual",
    "unison",
    "unissued",
    "unit",
    "universal",
    "universe",
    "unjustly",
    "unkempt",
    "unkind",
    "unknotted",
    "unknowing",
    "unknown",
    "unlaced",
    "unlatch",
    "unlawful",
    "unleaded",
    "unlearned",
    "unleash",
    "unless",
    "unleveled",
    "unlighted",
    "unlikable",
    "unlimited",
    "unlined",
    "unlinked",
    "unlisted",
    "unlit",
    "unlivable",
    "unloaded",
    "unloader",
    "unlocked",
    "unlocking",
    "unlovable",
    "unloved",
    "unlovely",
    "unloving",
    "unluckily",
    "unlucky",
    "unmade",
    "unmanaged",
    "unmanned",
    "unmapped",
    "unmarked",
    "unmasked",
    "unmasking",
    "unmatched",
    "unmindful",
    "unmixable",
    "unmixed",
    "unmolded",
    "unmoral",
    "unmovable",
    "unmoved",
    "unmoving",
    "unnamable",
    "unnamed",
    "unnatural",
    "unneeded",
    "unnerve",
    "unnerving",
    "unnoticed",
    "unopened",
    "unopposed",
    "unpack",
    "unpadded",
    "unpaid",
    "unpainted",
    "unpaired",
    "unpaved",
    "unpeeled",
    "unpicked",
    "unpiloted",
    "unpinned",
    "unplanned",
    "unplanted",
    "unpleased",
    "unpledged",
    "unplowed",
    "unplug",
    "unpopular",
    "unproven",
    "unquote",
    "unranked",
    "unrated",
    "unraveled",
    "unreached",
    "unread",
    "unreal",
    "unreeling",
    "unrefined",
    "unrelated",
    "unrented",
    "unrest",
    "unretired",
    "unrevised",
    "unrigged",
    "unripe",
    "unrivaled",
    "unroasted",
    "unrobed",
    "unroll",
    "unruffled",
    "unruly",
    "unrushed",
    "unsaddle",
    "unsafe",
    "unsaid",
    "unsalted",
    "unsaved",
    "unsavory",
    "unscathed",
    "unscented",
    "unscrew",
    "unsealed",
    "unseated",
    "unsecured",
    "unseeing",
    "unseemly",
    "unseen",
    "unselect",
    "unselfish",
    "unsent",
    "unsettled",
    "unshackle",
    "unshaken",
    "unshaved",
    "unshaven",
    "unsheathe",
    "unshipped",
    "unsightly",
    "unsigned",
    "unskilled",
    "unsliced",
    "unsmooth",
    "unsnap",
    "unsocial",
    "unsoiled",
    "unsold",
    "unsolved",
    "unsorted",
    "unspoiled",
    "unspoken",
    "unstable",
    "unstaffed",
    "unstamped",
    "unsteady",
    "unsterile",
    "unstirred",
    "unstitch",
    "unstopped",
    "unstuck",
    "unstuffed",
    "unstylish",
    "unsubtle",
    "unsubtly",
    "unsuited",
    "unsure",
    "unsworn",
    "untagged",
    "untainted",
    "untaken",
    "untamed",
    "untangled",
    "untapped",
    "untaxed",
    "unthawed",
    "unthread",
    "untidy",
    "untie",
    "until",
    "untimed",
    "untimely",
    "untitled",
    "untoasted",
    "untold",
    "untouched",
    "untracked",
    "untrained",
    "untreated",
    "untried",
    "untrimmed",
    "untrue",
    "untruth",
    "unturned",
    "untwist",
    "untying",
    "unusable",
    "unused",
    "unusual",
    "unvalued",
    "unvaried",
    "unvarying",
    "unveiled",
    "unveiling",
    "unvented",
    "unviable",
    "unvisited",
    "unvocal",
    "unwanted",
    "unwarlike",
    "unwary",
    "unwashed",
    "unwatched",
    "unweave",
    "unwed",
    "unwelcome",
    "unwell",
    "unwieldy",
    "unwilling",
    "unwind",
    "unwired",
    "unwitting",
    "unwomanly",
    "unworldly",
    "unworn",
    "unworried",
    "unworthy",
    "unwound",
    "unwoven",
    "unwrapped",
    "unwritten",
    "unzip",
    "upbeat",
    "upchuck",
    "upcoming",
    "upcountry",
    "update",
    "upfront",
    "upgrade",
    "upheaval",
    "upheld",
    "uphill",
    "uphold",
    "uplifted",
    "uplifting",
    "upload",
    "upon",
    "upper",
    "upright",
    "uprising",
    "upriver",
    "uproar",
    "uproot",
    "upscale",
    "upside",
    "upstage",
    "upstairs",
    "upstart",
    "upstate",
    "upstream",
    "upstroke",
    "upswing",
    "uptake",
    "uptight",
    "uptown",
    "upturned",
    "upward",
    "upwind",
    "uranium",
    "urban",
    "urchin",
    "urethane",
    "urgency",
    "urgent",
    "urging",
    "urologist",
    "urology",
    "usable",
    "usage",
    "useable",
    "used",
    "uselessly",
    "user",
    "usher",
    "usual",
    "utensil",
    "utility",
    "utilize",
    "utmost",
    "utopia",
    "utter",
    "vacancy",
    "vacant",
    "vacate",
    "vacation",
    "vagabond",
    "vagrancy",
    "vagrantly",
    "vaguely",
    "vagueness",
    "valiant",
    "valid",
    "valium",
    "valley",
    "valuables",
    "value",
    "vanilla",
    "vanish",
    "vanity",
    "vanquish",
    "vantage",
    "vaporizer",
    "variable",
    "variably",
    "varied",
    "variety",
    "various",
    "varmint",
    "varnish",
    "varsity",
    "varying",
    "vascular",
    "vaseline",
    "vastly",
    "vastness",
    "veal",
    "vegan",
    "veggie",
    "vehicular",
    "velcro",
    "velocity",
    "velvet",
    "vendetta",
    "vending",
    "vendor",
    "veneering",
    "vengeful",
    "venomous",
    "ventricle",
    "venture",
    "venue",
    "venus",
    "verbalize",
    "verbally",
    "verbose",
    "verdict",
    "verify",
    "verse",
    "version",
    "versus",
    "vertebrae",
    "vertical",
    "vertigo",
    "very",
    "vessel",
    "vest",
    "veteran",
    "veto",
    "vexingly",
    "viability",
    "viable",
    "vibes",
    "vice",
    "vicinity",
    "victory",
    "video",
    "viewable",
    "viewer",
    "viewing",
    "viewless",
    "viewpoint",
    "vigorous",
    "village",
    "villain",
    "vindicate",
    "vineyard",
    "vintage",
    "violate",
    "violation",
    "violator",
    "violet",
    "violin",
    "viper",
    "viral",
    "virtual",
    "virtuous",
    "virus",
    "visa",
    "viscosity",
    "viscous",
    "viselike",
    "visible",
    "visibly",
    "vision",
    "visiting",
    "visitor",
    "visor",
    "vista",
    "vitality",
    "vitalize",
    "vitally",
    "vitamins",
    "vivacious",
    "vividly",
    "vividness",
    "vixen",
    "vocalist",
    "vocalize",
    "vocally",
    "vocation",
    "voice",
    "voicing",
    "void",
    "volatile",
    "volley",
    "voltage",
    "volumes",
    "voter",
    "voting",
    "voucher",
    "vowed",
    "vowel",
    "voyage",
    "wackiness",
    "wad",
    "wafer",
    "waffle",
    "waged",
    "wager",
    "wages",
    "waggle",
    "wagon",
    "wake",
    "waking",
    "walk",
    "walmart",
    "walnut",
    "walrus",
    "waltz",
    "wand",
    "wannabe",
    "wanted",
    "wanting",
    "wasabi",
    "washable",
    "washbasin",
    "washboard",
    "washbowl",
    "washcloth",
    "washday",
    "washed",
    "washer",
    "washhouse",
    "washing",
    "washout",
    "washroom",
    "washstand",
    "washtub",
    "wasp",
    "wasting",
    "watch",
    "water",
    "waviness",
    "waving",
    "wavy",
    "whacking",
    "whacky",
    "wham",
    "wharf",
    "wheat",
    "whenever",
    "whiff",
    "whimsical",
    "whinny",
    "whiny",
    "whisking",
    "whoever",
    "whole",
    "whomever",
    "whoopee",
    "whooping",
    "whoops",
    "why",
    "wick",
    "widely",
    "widen",
    "widget",
    "widow",
    "width",
    "wieldable",
    "wielder",
    "wife",
    "wifi",
    "wikipedia",
    "wildcard",
    "wildcat",
    "wilder",
    "wildfire",
    "wildfowl",
    "wildland",
    "wildlife",
    "wildly",
    "wildness",
    "willed",
    "willfully",
    "willing",
    "willow",
    "willpower",
    "wilt",
    "wimp",
    "wince",
    "wincing",
    "wind",
    "wing",
    "winking",
    "winner",
    "winnings",
    "winter",
    "wipe",
    "wired",
    "wireless",
    "wiring",
    "wiry",
    "wisdom",
    "wise",
    "wish",
    "wisplike",
    "wispy",
    "wistful",
    "wizard",
    "wobble",
    "wobbling",
    "wobbly",
    "wok",
    "wolf",
    "wolverine",
    "womanhood",
    "womankind",
    "womanless",
    "womanlike",
    "womanly",
    "womb",
    "woof",
    "wooing",
    "wool",
    "woozy",
    "word",
    "work",
    "worried",
    "worrier",
    "worrisome",
    "worry",
    "worsening",
    "worshiper",
    "worst",
    "wound",
    "woven",
    "wow",
    "wrangle",
    "wrath",
    "wreath",
    "wreckage",
    "wrecker",
    "wrecking",
    "wrench",
    "wriggle",
    "wriggly",
    "wrinkle",
    "wrinkly",
    "wrist",
    "writing",
    "written",
    "wrongdoer",
    "wronged",
    "wrongful",
    "wrongly",
    "wrongness",
    "wrought",
    "xbox",
    "xerox",
    "yahoo",
    "yam",
    "yanking",
    "yapping",
    "yard",
    "yarn",
    "yeah",
    "yearbook",
    "yearling",
    "yearly",
    "yearning",
    "yeast",
    "yelling",
    "yelp",
    "yen",
    "yesterday",
    "yiddish",
    "yield",
    "yin",
    "yippee",
    "yo-yo",
    "yodel",
    "yoga",
    "yogurt",
    "yonder",
    "yoyo",
    "yummy",
    "zap",
    "zealous",
    "zebra",
    "zen",
    "zeppelin",
    "zero",
    "zestfully",
    "zesty",
    "zigzagged",
    "zipfile",
    "zipping",
    "zippy",
    "zips",
    "zit",
    "zodiac",
    "zombie",
    "zone",
    "zoning",
    "zookeeper",
    "zoologist",
    "zoology",
    "zoom",
];

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/encrypted-organization-key.ts
var encrypted_organization_key_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class BaseEncryptedOrganizationKey {
    static fromData(data) {
        switch (data.type) {
            case "organization":
                return new EncryptedOrganizationKey(data.key);
            case "provider":
                return new ProviderEncryptedOrganizationKey(data.key, data.providerId);
            default:
                return null;
        }
    }
}
class EncryptedOrganizationKey {
    constructor(key) {
        this.key = key;
    }
    decrypt(cryptoService) {
        return encrypted_organization_key_awaiter(this, void 0, void 0, function* () {
            const decValue = yield cryptoService.rsaDecrypt(this.key);
            return new SymmetricCryptoKey(decValue);
        });
    }
    toData() {
        return {
            type: "organization",
            key: this.key,
        };
    }
}
class ProviderEncryptedOrganizationKey {
    constructor(key, providerId) {
        this.key = key;
        this.providerId = providerId;
    }
    decrypt(cryptoService) {
        return encrypted_organization_key_awaiter(this, void 0, void 0, function* () {
            const providerKey = yield cryptoService.getProviderKey(this.providerId);
            const decValue = yield cryptoService.decryptToBytes(new EncString(this.key), providerKey);
            return new SymmetricCryptoKey(decValue);
        });
    }
    toData() {
        return {
            type: "provider",
            key: this.key,
            providerId: this.providerId,
        };
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/crypto.service.ts
var crypto_service_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var crypto_service_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var crypto_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};











class CryptoService {
    constructor(cryptoFunctionService, encryptService, platformUtilService, logService, stateService) {
        this.cryptoFunctionService = cryptoFunctionService;
        this.encryptService = encryptService;
        this.platformUtilService = platformUtilService;
        this.logService = logService;
        this.stateService = stateService;
    }
    setKey(key, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setCryptoMasterKey(key, { userId: userId });
            yield this.storeKey(key, userId);
        });
    }
    setKeyHash(keyHash) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setKeyHash(keyHash);
        });
    }
    setEncKey(encKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (encKey == null) {
                return;
            }
            yield this.stateService.setDecryptedCryptoSymmetricKey(null);
            yield this.stateService.setEncryptedCryptoSymmetricKey(encKey);
        });
    }
    setEncPrivateKey(encPrivateKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (encPrivateKey == null) {
                return;
            }
            yield this.stateService.setDecryptedPrivateKey(null);
            yield this.stateService.setEncryptedPrivateKey(encPrivateKey);
        });
    }
    setOrgKeys(orgs = [], providerOrgs = []) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const encOrgKeyData = {};
            orgs.forEach((org) => {
                encOrgKeyData[org.id] = {
                    type: "organization",
                    key: org.key,
                };
            });
            providerOrgs.forEach((org) => {
                encOrgKeyData[org.id] = {
                    type: "provider",
                    providerId: org.providerId,
                    key: org.key,
                };
            });
            yield this.stateService.setDecryptedOrganizationKeys(null);
            return yield this.stateService.setEncryptedOrganizationKeys(encOrgKeyData);
        });
    }
    setProviderKeys(providers) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const providerKeys = {};
            providers.forEach((provider) => {
                providerKeys[provider.id] = provider.key;
            });
            yield this.stateService.setDecryptedProviderKeys(null);
            return yield this.stateService.setEncryptedProviderKeys(providerKeys);
        });
    }
    getKey(keySuffix, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const inMemoryKey = yield this.stateService.getCryptoMasterKey({ userId: userId });
            if (inMemoryKey != null) {
                return inMemoryKey;
            }
            keySuffix || (keySuffix = KeySuffixOptions.Auto);
            const symmetricKey = yield this.getKeyFromStorage(keySuffix, userId);
            if (symmetricKey != null) {
                // TODO: Refactor here so get key doesn't also set key
                this.setKey(symmetricKey, userId);
            }
            return symmetricKey;
        });
    }
    getKeyFromStorage(keySuffix, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const key = yield this.retrieveKeyFromStorage(keySuffix, userId);
            if (key != null) {
                const symmetricKey = new SymmetricCryptoKey(Utils.fromB64ToArray(key).buffer);
                if (!(yield this.validateKey(symmetricKey))) {
                    this.logService.warning("Wrong key, throwing away stored key");
                    yield this.clearSecretKeyStore(userId);
                    return null;
                }
                return symmetricKey;
            }
            return null;
        });
    }
    getKeyHash() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getKeyHash();
        });
    }
    compareAndUpdateKeyHash(masterPassword, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const storedKeyHash = yield this.getKeyHash();
            if (masterPassword != null && storedKeyHash != null) {
                const localKeyHash = yield this.hashPassword(masterPassword, key, HashPurpose.LocalAuthorization);
                if (localKeyHash != null && storedKeyHash === localKeyHash) {
                    return true;
                }
                // TODO: remove serverKeyHash check in 1-2 releases after everyone's keyHash has been updated
                const serverKeyHash = yield this.hashPassword(masterPassword, key, HashPurpose.ServerAuthorization);
                if (serverKeyHash != null && storedKeyHash === serverKeyHash) {
                    yield this.setKeyHash(localKeyHash);
                    return true;
                }
            }
            return false;
        });
    }
    getEncKey(key = null) {
        return this.getEncKeyHelper(key);
    }
    getPublicKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const inMemoryPublicKey = yield this.stateService.getPublicKey();
            if (inMemoryPublicKey != null) {
                return inMemoryPublicKey;
            }
            const privateKey = yield this.getPrivateKey();
            if (privateKey == null) {
                return null;
            }
            const publicKey = yield this.cryptoFunctionService.rsaExtractPublicKey(privateKey);
            yield this.stateService.setPublicKey(publicKey);
            return publicKey;
        });
    }
    getPrivateKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const decryptedPrivateKey = yield this.stateService.getDecryptedPrivateKey();
            if (decryptedPrivateKey != null) {
                return decryptedPrivateKey;
            }
            const encPrivateKey = yield this.stateService.getEncryptedPrivateKey();
            if (encPrivateKey == null) {
                return null;
            }
            const privateKey = yield this.decryptToBytes(new EncString(encPrivateKey), null);
            yield this.stateService.setDecryptedPrivateKey(privateKey);
            return privateKey;
        });
    }
    getFingerprint(userId, publicKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (publicKey == null) {
                publicKey = yield this.getPublicKey();
            }
            if (publicKey === null) {
                throw new Error("No public key available.");
            }
            const keyFingerprint = yield this.cryptoFunctionService.hash(publicKey, "sha256");
            const userFingerprint = yield this.cryptoFunctionService.hkdfExpand(keyFingerprint, userId, 32, "sha256");
            return this.hashPhrase(userFingerprint);
        });
    }
    getOrgKeys() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const result = new Map();
            const decryptedOrganizationKeys = yield this.stateService.getDecryptedOrganizationKeys();
            if (decryptedOrganizationKeys != null && decryptedOrganizationKeys.size > 0) {
                return decryptedOrganizationKeys;
            }
            const encOrgKeyData = yield this.stateService.getEncryptedOrganizationKeys();
            if (encOrgKeyData == null) {
                return null;
            }
            let setKey = false;
            for (const orgId of Object.keys(encOrgKeyData)) {
                if (result.has(orgId)) {
                    continue;
                }
                const encOrgKey = BaseEncryptedOrganizationKey.fromData(encOrgKeyData[orgId]);
                const decOrgKey = yield encOrgKey.decrypt(this);
                result.set(orgId, decOrgKey);
                setKey = true;
            }
            if (setKey) {
                yield this.stateService.setDecryptedOrganizationKeys(result);
            }
            return result;
        });
    }
    getOrgKey(orgId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (orgId == null) {
                return null;
            }
            const orgKeys = yield this.getOrgKeys();
            if (orgKeys == null || !orgKeys.has(orgId)) {
                return null;
            }
            return orgKeys.get(orgId);
        });
    }
    getProviderKeys() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const providerKeys = new Map();
            const decryptedProviderKeys = yield this.stateService.getDecryptedProviderKeys();
            if (decryptedProviderKeys != null && decryptedProviderKeys.size > 0) {
                return decryptedProviderKeys;
            }
            const encProviderKeys = yield this.stateService.getEncryptedProviderKeys();
            if (encProviderKeys == null) {
                return null;
            }
            let setKey = false;
            for (const orgId in encProviderKeys) {
                // eslint-disable-next-line
                if (!encProviderKeys.hasOwnProperty(orgId)) {
                    continue;
                }
                const decValue = yield this.rsaDecrypt(encProviderKeys[orgId]);
                providerKeys.set(orgId, new SymmetricCryptoKey(decValue));
                setKey = true;
            }
            if (setKey) {
                yield this.stateService.setDecryptedProviderKeys(providerKeys);
            }
            return providerKeys;
        });
    }
    getProviderKey(providerId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (providerId == null) {
                return null;
            }
            const providerKeys = yield this.getProviderKeys();
            if (providerKeys == null || !providerKeys.has(providerId)) {
                return null;
            }
            return providerKeys.get(providerId);
        });
    }
    hasKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return ((yield this.hasKeyInMemory()) ||
                (yield this.hasKeyStored(KeySuffixOptions.Auto)) ||
                (yield this.hasKeyStored(KeySuffixOptions.Biometric)));
        });
    }
    hasKeyInMemory(userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.stateService.getCryptoMasterKey({ userId: userId })) != null;
        });
    }
    hasKeyStored(keySuffix, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            switch (keySuffix) {
                case KeySuffixOptions.Auto:
                    return (yield this.stateService.getCryptoMasterKeyAuto({ userId: userId })) != null;
                case KeySuffixOptions.Biometric:
                    return (yield this.stateService.hasCryptoMasterKeyBiometric({ userId: userId })) === true;
                default:
                    return false;
            }
        });
    }
    hasEncKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.stateService.getEncryptedCryptoSymmetricKey()) != null;
        });
    }
    clearKey(clearSecretStorage = true, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setCryptoMasterKey(null, { userId: userId });
            if (clearSecretStorage) {
                yield this.clearSecretKeyStore(userId);
            }
        });
    }
    clearStoredKey(keySuffix) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            keySuffix === KeySuffixOptions.Auto
                ? yield this.stateService.setCryptoMasterKeyAuto(null)
                : yield this.stateService.setCryptoMasterKeyBiometric(null);
        });
    }
    clearKeyHash(userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setKeyHash(null, { userId: userId });
        });
    }
    clearEncKey(memoryOnly, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedCryptoSymmetricKey(null, { userId: userId });
            if (!memoryOnly) {
                yield this.stateService.setEncryptedCryptoSymmetricKey(null, { userId: userId });
            }
        });
    }
    clearKeyPair(memoryOnly, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const keysToClear = [
                this.stateService.setDecryptedPrivateKey(null, { userId: userId }),
                this.stateService.setPublicKey(null, { userId: userId }),
            ];
            if (!memoryOnly) {
                keysToClear.push(this.stateService.setEncryptedPrivateKey(null, { userId: userId }));
            }
            return Promise.all(keysToClear);
        });
    }
    clearOrgKeys(memoryOnly, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedOrganizationKeys(null, { userId: userId });
            if (!memoryOnly) {
                yield this.stateService.setEncryptedOrganizationKeys(null, { userId: userId });
            }
        });
    }
    clearProviderKeys(memoryOnly, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedProviderKeys(null, { userId: userId });
            if (!memoryOnly) {
                yield this.stateService.setEncryptedProviderKeys(null, { userId: userId });
            }
        });
    }
    clearPinProtectedKey(userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setEncryptedPinProtected(null, { userId: userId });
        });
    }
    clearKeys(userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearKey(true, userId);
            yield this.clearKeyHash(userId);
            yield this.clearOrgKeys(false, userId);
            yield this.clearProviderKeys(false, userId);
            yield this.clearEncKey(false, userId);
            yield this.clearKeyPair(false, userId);
            yield this.clearPinProtectedKey(userId);
        });
    }
    toggleKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const key = yield this.getKey();
            yield this.setKey(key);
        });
    }
    makeKey(password, salt, kdf, kdfConfig) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            let key = null;
            if (kdf == null || kdf === KdfType.PBKDF2_SHA256) {
                if (kdfConfig.iterations == null) {
                    kdfConfig.iterations = 5000;
                }
                else if (kdfConfig.iterations < 5000) {
                    throw new Error("PBKDF2 iteration minimum is 5000.");
                }
                key = yield this.cryptoFunctionService.pbkdf2(password, salt, "sha256", kdfConfig.iterations);
            }
            else if (kdf == KdfType.Argon2id) {
                if (kdfConfig.iterations == null) {
                    kdfConfig.iterations = DEFAULT_ARGON2_ITERATIONS;
                }
                else if (kdfConfig.iterations < 2) {
                    throw new Error("Argon2 iteration minimum is 2.");
                }
                if (kdfConfig.memory == null) {
                    kdfConfig.memory = DEFAULT_ARGON2_MEMORY;
                }
                else if (kdfConfig.memory < 16) {
                    throw new Error("Argon2 memory minimum is 16 MB");
                }
                else if (kdfConfig.memory > 1024) {
                    throw new Error("Argon2 memory maximum is 1024 MB");
                }
                if (kdfConfig.parallelism == null) {
                    kdfConfig.parallelism = DEFAULT_ARGON2_PARALLELISM;
                }
                else if (kdfConfig.parallelism < 1) {
                    throw new Error("Argon2 parallelism minimum is 1.");
                }
                const saltHash = yield this.cryptoFunctionService.hash(salt, "sha256");
                key = yield this.cryptoFunctionService.argon2(password, saltHash, kdfConfig.iterations, kdfConfig.memory * 1024, // convert to KiB from MiB
                kdfConfig.parallelism);
            }
            else {
                throw new Error("Unknown Kdf.");
            }
            return new SymmetricCryptoKey(key);
        });
    }
    makeKeyFromPin(pin, salt, kdf, kdfConfig, protectedKeyCs = null) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (protectedKeyCs == null) {
                const pinProtectedKey = yield this.stateService.getEncryptedPinProtected();
                if (pinProtectedKey == null) {
                    throw new Error("No PIN protected key found.");
                }
                protectedKeyCs = new EncString(pinProtectedKey);
            }
            const pinKey = yield this.makePinKey(pin, salt, kdf, kdfConfig);
            const decKey = yield this.decryptToBytes(protectedKeyCs, pinKey);
            return new SymmetricCryptoKey(decKey);
        });
    }
    makeShareKey() {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const shareKey = yield this.cryptoFunctionService.randomBytes(64);
            const publicKey = yield this.getPublicKey();
            const encShareKey = yield this.rsaEncrypt(shareKey, publicKey);
            return [encShareKey, new SymmetricCryptoKey(shareKey)];
        });
    }
    makeKeyPair(key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const keyPair = yield this.cryptoFunctionService.rsaGenerateKeyPair(2048);
            const publicB64 = Utils.fromBufferToB64(keyPair[0]);
            const privateEnc = yield this.encrypt(keyPair[1], key);
            return [publicB64, privateEnc];
        });
    }
    makePinKey(pin, salt, kdf, kdfConfig) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const pinKey = yield this.makeKey(pin, salt, kdf, kdfConfig);
            return yield this.stretchKey(pinKey);
        });
    }
    makeSendKey(keyMaterial) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const sendKey = yield this.cryptoFunctionService.hkdf(keyMaterial, "bitwarden-send", "send", 64, "sha256");
            return new SymmetricCryptoKey(sendKey);
        });
    }
    hashPassword(password, key, hashPurpose) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                key = yield this.getKey();
            }
            if (password == null || key == null) {
                throw new Error("Invalid parameters.");
            }
            const iterations = hashPurpose === HashPurpose.LocalAuthorization ? 2 : 1;
            const hash = yield this.cryptoFunctionService.pbkdf2(key.key, password, "sha256", iterations);
            return Utils.fromBufferToB64(hash);
        });
    }
    makeEncKey(key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const theKey = yield this.getKeyForUserEncryption(key);
            const encKey = yield this.cryptoFunctionService.randomBytes(64);
            return this.buildEncKey(theKey, encKey);
        });
    }
    remakeEncKey(key, encKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (encKey == null) {
                encKey = yield this.getEncKey();
            }
            return this.buildEncKey(key, encKey.key);
        });
    }
    /**
     * @deprecated July 25 2022: Get the key you need from CryptoService (getKeyForUserEncryption or getOrgKey)
     * and then call encryptService.encrypt
     */
    encrypt(plainValue, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            key = yield this.getKeyForUserEncryption(key);
            return yield this.encryptService.encrypt(plainValue, key);
        });
    }
    /**
     * @deprecated July 25 2022: Get the key you need from CryptoService (getKeyForUserEncryption or getOrgKey)
     * and then call encryptService.encryptToBytes
     */
    encryptToBytes(plainValue, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            key = yield this.getKeyForUserEncryption(key);
            return this.encryptService.encryptToBytes(plainValue, key);
        });
    }
    rsaEncrypt(data, publicKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (publicKey == null) {
                publicKey = yield this.getPublicKey();
            }
            if (publicKey == null) {
                throw new Error("Public key unavailable.");
            }
            const encBytes = yield this.cryptoFunctionService.rsaEncrypt(data, publicKey, "sha1");
            return new EncString(EncryptionType.Rsa2048_OaepSha1_B64, Utils.fromBufferToB64(encBytes));
        });
    }
    rsaDecrypt(encValue, privateKeyValue) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const headerPieces = encValue.split(".");
            let encType = null;
            let encPieces;
            if (headerPieces.length === 1) {
                encType = EncryptionType.Rsa2048_OaepSha256_B64;
                encPieces = [headerPieces[0]];
            }
            else if (headerPieces.length === 2) {
                try {
                    encType = parseInt(headerPieces[0], null);
                    encPieces = headerPieces[1].split("|");
                }
                catch (e) {
                    this.logService.error(e);
                }
            }
            switch (encType) {
                case EncryptionType.Rsa2048_OaepSha256_B64:
                case EncryptionType.Rsa2048_OaepSha1_B64:
                case EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64: // HmacSha256 types are deprecated
                case EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64:
                    break;
                default:
                    throw new Error("encType unavailable.");
            }
            if (encPieces == null || encPieces.length <= 0) {
                throw new Error("encPieces unavailable.");
            }
            const data = Utils.fromB64ToArray(encPieces[0]).buffer;
            const privateKey = privateKeyValue !== null && privateKeyValue !== void 0 ? privateKeyValue : (yield this.getPrivateKey());
            if (privateKey == null) {
                throw new Error("No private key.");
            }
            let alg = "sha1";
            switch (encType) {
                case EncryptionType.Rsa2048_OaepSha256_B64:
                case EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64:
                    alg = "sha256";
                    break;
                case EncryptionType.Rsa2048_OaepSha1_B64:
                case EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64:
                    break;
                default:
                    throw new Error("encType unavailable.");
            }
            return this.cryptoFunctionService.rsaDecrypt(data, privateKey, alg);
        });
    }
    /**
     * @deprecated July 25 2022: Get the key you need from CryptoService (getKeyForUserEncryption or getOrgKey)
     * and then call encryptService.decryptToBytes
     */
    decryptToBytes(encString, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const keyForEnc = yield this.getKeyForUserEncryption(key);
            return this.encryptService.decryptToBytes(encString, keyForEnc);
        });
    }
    /**
     * @deprecated July 25 2022: Get the key you need from CryptoService (getKeyForUserEncryption or getOrgKey)
     * and then call encryptService.decryptToUtf8
     */
    decryptToUtf8(encString, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            key = yield this.getKeyForUserEncryption(key);
            return yield this.encryptService.decryptToUtf8(encString, key);
        });
    }
    /**
     * @deprecated July 25 2022: Get the key you need from CryptoService (getKeyForUserEncryption or getOrgKey)
     * and then call encryptService.decryptToBytes
     */
    decryptFromBytes(encBuffer, key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (encBuffer == null) {
                throw new Error("No buffer provided for decryption.");
            }
            key = yield this.getKeyForUserEncryption(key);
            return this.encryptService.decryptToBytes(encBuffer, key);
        });
    }
    // EFForg/OpenWireless
    // ref https://github.com/EFForg/OpenWireless/blob/master/app/js/diceware.js
    randomNumber(min, max) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            let rval = 0;
            const range = max - min + 1;
            const bitsNeeded = Math.ceil(Math.log2(range));
            if (bitsNeeded > 53) {
                throw new Error("We cannot generate numbers larger than 53 bits.");
            }
            const bytesNeeded = Math.ceil(bitsNeeded / 8);
            const mask = Math.pow(2, bitsNeeded) - 1;
            // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111
            // Fill a byte array with N random numbers
            const byteArray = new Uint8Array(yield this.cryptoFunctionService.randomBytes(bytesNeeded));
            let p = (bytesNeeded - 1) * 8;
            for (let i = 0; i < bytesNeeded; i++) {
                rval += byteArray[i] * Math.pow(2, p);
                p -= 8;
            }
            // Use & to apply the mask and reduce the number of recursive lookups
            rval = rval & mask;
            if (rval >= range) {
                // Integer out of acceptable range
                return this.randomNumber(min, max);
            }
            // Return an integer that falls within the range
            return min + rval;
        });
    }
    validateKey(key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            try {
                const encPrivateKey = yield this.stateService.getEncryptedPrivateKey();
                const encKey = yield this.getEncKeyHelper(key);
                if (encPrivateKey == null || encKey == null) {
                    return false;
                }
                const privateKey = yield this.decryptToBytes(new EncString(encPrivateKey), encKey);
                yield this.cryptoFunctionService.rsaExtractPublicKey(privateKey);
            }
            catch (e) {
                return false;
            }
            return true;
        });
    }
    // ---HELPERS---
    storeKey(key, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (yield this.shouldStoreKey(KeySuffixOptions.Auto, userId)) {
                yield this.stateService.setCryptoMasterKeyAuto(key.keyB64, { userId: userId });
            }
            else if (yield this.shouldStoreKey(KeySuffixOptions.Biometric, userId)) {
                yield this.stateService.setCryptoMasterKeyBiometric(key.keyB64, { userId: userId });
            }
            else {
                yield this.stateService.setCryptoMasterKeyAuto(null, { userId: userId });
                yield this.stateService.setCryptoMasterKeyBiometric(null, { userId: userId });
            }
        });
    }
    shouldStoreKey(keySuffix, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            let shouldStoreKey = false;
            if (keySuffix === KeySuffixOptions.Auto) {
                const vaultTimeout = yield this.stateService.getVaultTimeout({ userId: userId });
                shouldStoreKey = vaultTimeout == null;
            }
            else if (keySuffix === KeySuffixOptions.Biometric) {
                const biometricUnlock = yield this.stateService.getBiometricUnlock({ userId: userId });
                shouldStoreKey = biometricUnlock && this.platformUtilService.supportsSecureStorage();
            }
            return shouldStoreKey;
        });
    }
    retrieveKeyFromStorage(keySuffix, userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            return keySuffix === KeySuffixOptions.Auto
                ? yield this.stateService.getCryptoMasterKeyAuto({ userId: userId })
                : yield this.stateService.getCryptoMasterKeyBiometric({ userId: userId });
        });
    }
    getKeyForUserEncryption(key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            if (key != null) {
                return key;
            }
            const encKey = yield this.getEncKey();
            if (encKey != null) {
                return encKey;
            }
            // Legacy support: encryption used to be done with the user key (derived from master password).
            // Users who have not migrated will have a null encKey and must use the user key instead.
            return yield this.getKey();
        });
    }
    stretchKey(key) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const newKey = new Uint8Array(64);
            const encKey = yield this.cryptoFunctionService.hkdfExpand(key.key, "enc", 32, "sha256");
            const macKey = yield this.cryptoFunctionService.hkdfExpand(key.key, "mac", 32, "sha256");
            newKey.set(new Uint8Array(encKey));
            newKey.set(new Uint8Array(macKey), 32);
            return new SymmetricCryptoKey(newKey.buffer);
        });
    }
    hashPhrase(hash, minimumEntropy = 64) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const entropyPerWord = Math.log(EFFLongWordList.length) / Math.log(2);
            let numWords = Math.ceil(minimumEntropy / entropyPerWord);
            const hashArr = Array.from(new Uint8Array(hash));
            const entropyAvailable = hashArr.length * 4;
            if (numWords * entropyPerWord > entropyAvailable) {
                throw new Error("Output entropy of hash function is too small");
            }
            const phrase = [];
            let hashNumber = external_big_integer_namespaceObject.fromArray(hashArr, 256);
            while (numWords--) {
                const remainder = hashNumber.mod(EFFLongWordList.length);
                hashNumber = hashNumber.divide(EFFLongWordList.length);
                phrase.push(EFFLongWordList[remainder]);
            }
            return phrase;
        });
    }
    buildEncKey(key, encKey) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            let encKeyEnc = null;
            if (key.key.byteLength === 32) {
                const newKey = yield this.stretchKey(key);
                encKeyEnc = yield this.encrypt(encKey, newKey);
            }
            else if (key.key.byteLength === 64) {
                encKeyEnc = yield this.encrypt(encKey, key);
            }
            else {
                throw new Error("Invalid key size.");
            }
            return [new SymmetricCryptoKey(encKey), encKeyEnc];
        });
    }
    clearSecretKeyStore(userId) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setCryptoMasterKeyAuto(null, { userId: userId });
            yield this.stateService.setCryptoMasterKeyBiometric(null, { userId: userId });
        });
    }
    getEncKeyHelper(key = null) {
        return crypto_service_awaiter(this, void 0, void 0, function* () {
            const inMemoryKey = yield this.stateService.getDecryptedCryptoSymmetricKey();
            if (inMemoryKey != null) {
                return inMemoryKey;
            }
            const encKey = yield this.stateService.getEncryptedCryptoSymmetricKey();
            if (encKey == null) {
                return null;
            }
            if (key == null) {
                key = yield this.getKey();
            }
            if (key == null) {
                return null;
            }
            let decEncKey;
            const encKeyCipher = new EncString(encKey);
            if (encKeyCipher.encryptionType === EncryptionType.AesCbc256_B64) {
                decEncKey = yield this.decryptToBytes(encKeyCipher, key);
            }
            else if (encKeyCipher.encryptionType === EncryptionType.AesCbc256_HmacSha256_B64) {
                const newKey = yield this.stretchKey(key);
                decEncKey = yield this.decryptToBytes(encKeyCipher, newKey);
            }
            else {
                throw new Error("Unsupported encKey type.");
            }
            if (decEncKey == null) {
                return null;
            }
            const symmetricCryptoKey = new SymmetricCryptoKey(decEncKey);
            yield this.stateService.setDecryptedCryptoSymmetricKey(symmetricCryptoKey);
            return symmetricCryptoKey;
        });
    }
}
crypto_service_decorate([
    sequentialize(() => "getEncKey"),
    crypto_service_metadata("design:type", Function),
    crypto_service_metadata("design:paramtypes", [SymmetricCryptoKey]),
    crypto_service_metadata("design:returntype", Promise)
], CryptoService.prototype, "getEncKey", null);
crypto_service_decorate([
    sequentialize(() => "getOrgKeys"),
    crypto_service_metadata("design:type", Function),
    crypto_service_metadata("design:paramtypes", []),
    crypto_service_metadata("design:returntype", Promise)
], CryptoService.prototype, "getOrgKeys", null);
crypto_service_decorate([
    sequentialize(() => "getProviderKeys"),
    crypto_service_metadata("design:type", Function),
    crypto_service_metadata("design:paramtypes", []),
    crypto_service_metadata("design:returntype", Promise)
], CryptoService.prototype, "getProviderKeys", null);

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/enc-array-buffer.ts
var enc_array_buffer_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


const ENC_TYPE_LENGTH = 1;
const IV_LENGTH = 16;
const MAC_LENGTH = 32;
const MIN_DATA_LENGTH = 1;
class EncArrayBuffer {
    constructor(buffer) {
        this.buffer = buffer;
        this.encryptionType = null;
        this.dataBytes = null;
        this.ivBytes = null;
        this.macBytes = null;
        const encBytes = new Uint8Array(buffer);
        const encType = encBytes[0];
        switch (encType) {
            case EncryptionType.AesCbc128_HmacSha256_B64:
            case EncryptionType.AesCbc256_HmacSha256_B64: {
                const minimumLength = ENC_TYPE_LENGTH + IV_LENGTH + MAC_LENGTH + MIN_DATA_LENGTH;
                if (encBytes.length < minimumLength) {
                    this.throwDecryptionError();
                }
                this.ivBytes = encBytes.slice(ENC_TYPE_LENGTH, ENC_TYPE_LENGTH + IV_LENGTH).buffer;
                this.macBytes = encBytes.slice(ENC_TYPE_LENGTH + IV_LENGTH, ENC_TYPE_LENGTH + IV_LENGTH + MAC_LENGTH).buffer;
                this.dataBytes = encBytes.slice(ENC_TYPE_LENGTH + IV_LENGTH + MAC_LENGTH).buffer;
                break;
            }
            case EncryptionType.AesCbc256_B64: {
                const minimumLength = ENC_TYPE_LENGTH + IV_LENGTH + MIN_DATA_LENGTH;
                if (encBytes.length < minimumLength) {
                    this.throwDecryptionError();
                }
                this.ivBytes = encBytes.slice(ENC_TYPE_LENGTH, ENC_TYPE_LENGTH + IV_LENGTH).buffer;
                this.dataBytes = encBytes.slice(ENC_TYPE_LENGTH + IV_LENGTH).buffer;
                break;
            }
            default:
                this.throwDecryptionError();
        }
        this.encryptionType = encType;
    }
    throwDecryptionError() {
        throw new Error("Error parsing encrypted ArrayBuffer: data is corrupted or has an invalid format.");
    }
    static fromResponse(response) {
        return enc_array_buffer_awaiter(this, void 0, void 0, function* () {
            const buffer = yield response.arrayBuffer();
            if (buffer == null) {
                throw new Error("Cannot create EncArrayBuffer from Response - Response is empty");
            }
            return new EncArrayBuffer(buffer);
        });
    }
    static fromB64(b64) {
        const buffer = Utils.fromB64ToArray(b64).buffer;
        return new EncArrayBuffer(buffer);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/encrypted-object.ts
class EncryptedObject {
}

;// CONCATENATED MODULE: ../../libs/common/src/services/cryptography/encrypt.service.implementation.ts
var encrypt_service_implementation_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};






class EncryptServiceImplementation {
    constructor(cryptoFunctionService, logService, logMacFailures) {
        this.cryptoFunctionService = cryptoFunctionService;
        this.logService = logService;
        this.logMacFailures = logMacFailures;
    }
    encrypt(plainValue, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                throw new Error("No encryption key provided.");
            }
            if (plainValue == null) {
                return Promise.resolve(null);
            }
            let plainBuf;
            if (typeof plainValue === "string") {
                plainBuf = Utils.fromUtf8ToArray(plainValue).buffer;
            }
            else {
                plainBuf = plainValue;
            }
            const encObj = yield this.aesEncrypt(plainBuf, key);
            const iv = Utils.fromBufferToB64(encObj.iv);
            const data = Utils.fromBufferToB64(encObj.data);
            const mac = encObj.mac != null ? Utils.fromBufferToB64(encObj.mac) : null;
            return new EncString(encObj.key.encType, data, iv, mac);
        });
    }
    encryptToBytes(plainValue, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                throw new Error("No encryption key provided.");
            }
            const encValue = yield this.aesEncrypt(plainValue, key);
            let macLen = 0;
            if (encValue.mac != null) {
                macLen = encValue.mac.byteLength;
            }
            const encBytes = new Uint8Array(1 + encValue.iv.byteLength + macLen + encValue.data.byteLength);
            encBytes.set([encValue.key.encType]);
            encBytes.set(new Uint8Array(encValue.iv), 1);
            if (encValue.mac != null) {
                encBytes.set(new Uint8Array(encValue.mac), 1 + encValue.iv.byteLength);
            }
            encBytes.set(new Uint8Array(encValue.data), 1 + encValue.iv.byteLength + macLen);
            return new EncArrayBuffer(encBytes.buffer);
        });
    }
    decryptToUtf8(encString, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                throw new Error("No key provided for decryption.");
            }
            key = this.resolveLegacyKey(key, encString);
            if (key.macKey != null && (encString === null || encString === void 0 ? void 0 : encString.mac) == null) {
                this.logService.error("mac required.");
                return null;
            }
            if (key.encType !== encString.encryptionType) {
                this.logService.error("encType unavailable.");
                return null;
            }
            const fastParams = this.cryptoFunctionService.aesDecryptFastParameters(encString.data, encString.iv, encString.mac, key);
            if (fastParams.macKey != null && fastParams.mac != null) {
                const computedMac = yield this.cryptoFunctionService.hmacFast(fastParams.macData, fastParams.macKey, "sha256");
                const macsEqual = yield this.cryptoFunctionService.compareFast(fastParams.mac, computedMac);
                if (!macsEqual) {
                    this.logMacFailed("mac failed.");
                    return null;
                }
            }
            return yield this.cryptoFunctionService.aesDecryptFast(fastParams);
        });
    }
    decryptToBytes(encThing, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                throw new Error("No encryption key provided.");
            }
            if (encThing == null) {
                throw new Error("Nothing provided for decryption.");
            }
            key = this.resolveLegacyKey(key, encThing);
            if (key.macKey != null && encThing.macBytes == null) {
                return null;
            }
            if (key.encType !== encThing.encryptionType) {
                return null;
            }
            if (key.macKey != null && encThing.macBytes != null) {
                const macData = new Uint8Array(encThing.ivBytes.byteLength + encThing.dataBytes.byteLength);
                macData.set(new Uint8Array(encThing.ivBytes), 0);
                macData.set(new Uint8Array(encThing.dataBytes), encThing.ivBytes.byteLength);
                const computedMac = yield this.cryptoFunctionService.hmac(macData.buffer, key.macKey, "sha256");
                if (computedMac === null) {
                    return null;
                }
                const macsMatch = yield this.cryptoFunctionService.compare(encThing.macBytes, computedMac);
                if (!macsMatch) {
                    this.logMacFailed("mac failed.");
                    return null;
                }
            }
            const result = yield this.cryptoFunctionService.aesDecrypt(encThing.dataBytes, encThing.ivBytes, key.encKey);
            return result !== null && result !== void 0 ? result : null;
        });
    }
    decryptItems(items, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            if (items == null || items.length < 1) {
                return [];
            }
            return yield Promise.all(items.map((item) => item.decrypt(key)));
        });
    }
    aesEncrypt(data, key) {
        return encrypt_service_implementation_awaiter(this, void 0, void 0, function* () {
            const obj = new EncryptedObject();
            obj.key = key;
            obj.iv = yield this.cryptoFunctionService.randomBytes(16);
            obj.data = yield this.cryptoFunctionService.aesEncrypt(data, obj.iv, obj.key.encKey);
            if (obj.key.macKey != null) {
                const macData = new Uint8Array(obj.iv.byteLength + obj.data.byteLength);
                macData.set(new Uint8Array(obj.iv), 0);
                macData.set(new Uint8Array(obj.data), obj.iv.byteLength);
                obj.mac = yield this.cryptoFunctionService.hmac(macData.buffer, obj.key.macKey, "sha256");
            }
            return obj;
        });
    }
    logMacFailed(msg) {
        if (this.logMacFailures) {
            this.logService.error(msg);
        }
    }
    /**
     * Transform into new key for the old encrypt-then-mac scheme if required, otherwise return the current key unchanged
     * @param encThing The encrypted object (e.g. encString or encArrayBuffer) that you want to decrypt
     */
    resolveLegacyKey(key, encThing) {
        if (encThing.encryptionType === EncryptionType.AesCbc128_HmacSha256_B64 &&
            key.encType === EncryptionType.AesCbc256_B64) {
            return new SymmetricCryptoKey(key.key, EncryptionType.AesCbc128_HmacSha256_B64);
        }
        return key;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/environment.service.ts
var environment_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class EnvironmentService {
    constructor(stateService) {
        this.stateService = stateService;
        this.urlsSubject = new external_rxjs_namespaceObject.Subject();
        this.urls = this.urlsSubject;
        this.scimUrl = null;
        this.stateService.activeAccount$
            .pipe((0,external_rxjs_namespaceObject.concatMap)(() => environment_service_awaiter(this, void 0, void 0, function* () {
            yield this.setUrlsFromStorage();
        })))
            .subscribe();
    }
    hasBaseUrl() {
        return this.baseUrl != null;
    }
    getNotificationsUrl() {
        if (this.notificationsUrl != null) {
            return this.notificationsUrl;
        }
        if (this.baseUrl != null) {
            return this.baseUrl + "/notifications";
        }
        return "https://notifications.bitwarden.com";
    }
    getWebVaultUrl() {
        if (this.webVaultUrl != null) {
            return this.webVaultUrl;
        }
        if (this.baseUrl) {
            return this.baseUrl;
        }
        return "https://vault.bitwarden.com";
    }
    getSendUrl() {
        return this.getWebVaultUrl() === "https://vault.bitwarden.com"
            ? "https://send.bitwarden.com/#"
            : this.getWebVaultUrl() + "/#/send/";
    }
    getIconsUrl() {
        if (this.iconsUrl != null) {
            return this.iconsUrl;
        }
        if (this.baseUrl) {
            return this.baseUrl + "/icons";
        }
        return "https://icons.bitwarden.net";
    }
    getApiUrl() {
        if (this.apiUrl != null) {
            return this.apiUrl;
        }
        if (this.baseUrl) {
            return this.baseUrl + "/api";
        }
        return "https://api.bitwarden.com";
    }
    getIdentityUrl() {
        if (this.identityUrl != null) {
            return this.identityUrl;
        }
        if (this.baseUrl) {
            return this.baseUrl + "/identity";
        }
        return "https://identity.bitwarden.com";
    }
    getEventsUrl() {
        if (this.eventsUrl != null) {
            return this.eventsUrl;
        }
        if (this.baseUrl) {
            return this.baseUrl + "/events";
        }
        return "https://events.bitwarden.com";
    }
    getKeyConnectorUrl() {
        return this.keyConnectorUrl;
    }
    getScimUrl() {
        if (this.scimUrl != null) {
            return this.scimUrl + "/v2";
        }
        return this.getWebVaultUrl() === "https://vault.bitwarden.com"
            ? "https://scim.bitwarden.com/v2"
            : this.getWebVaultUrl() + "/scim/v2";
    }
    setUrlsFromStorage() {
        return environment_service_awaiter(this, void 0, void 0, function* () {
            const urls = yield this.stateService.getEnvironmentUrls();
            const envUrls = new EnvironmentUrls();
            this.baseUrl = envUrls.base = urls.base;
            this.webVaultUrl = urls.webVault;
            this.apiUrl = envUrls.api = urls.api;
            this.identityUrl = envUrls.identity = urls.identity;
            this.iconsUrl = urls.icons;
            this.notificationsUrl = urls.notifications;
            this.eventsUrl = envUrls.events = urls.events;
            this.keyConnectorUrl = urls.keyConnector;
            // scimUrl is not saved to storage
        });
    }
    setUrls(urls) {
        var _a;
        return environment_service_awaiter(this, void 0, void 0, function* () {
            urls.base = this.formatUrl(urls.base);
            urls.webVault = this.formatUrl(urls.webVault);
            urls.api = this.formatUrl(urls.api);
            urls.identity = this.formatUrl(urls.identity);
            urls.icons = this.formatUrl(urls.icons);
            urls.notifications = this.formatUrl(urls.notifications);
            urls.events = this.formatUrl(urls.events);
            urls.keyConnector = this.formatUrl(urls.keyConnector);
            // scimUrl cannot be cleared
            urls.scim = (_a = this.formatUrl(urls.scim)) !== null && _a !== void 0 ? _a : this.scimUrl;
            yield this.stateService.setEnvironmentUrls({
                base: urls.base,
                api: urls.api,
                identity: urls.identity,
                webVault: urls.webVault,
                icons: urls.icons,
                notifications: urls.notifications,
                events: urls.events,
                keyConnector: urls.keyConnector,
                // scimUrl is not saved to storage
            });
            this.baseUrl = urls.base;
            this.webVaultUrl = urls.webVault;
            this.apiUrl = urls.api;
            this.identityUrl = urls.identity;
            this.iconsUrl = urls.icons;
            this.notificationsUrl = urls.notifications;
            this.eventsUrl = urls.events;
            this.keyConnectorUrl = urls.keyConnector;
            this.scimUrl = urls.scim;
            this.urlsSubject.next(urls);
            return urls;
        });
    }
    getUrls() {
        return {
            base: this.baseUrl,
            webVault: this.webVaultUrl,
            api: this.apiUrl,
            identity: this.identityUrl,
            icons: this.iconsUrl,
            notifications: this.notificationsUrl,
            events: this.eventsUrl,
            keyConnector: this.keyConnectorUrl,
            scim: this.scimUrl,
        };
    }
    formatUrl(url) {
        if (url == null || url === "") {
            return null;
        }
        url = url.replace(/\/+$/g, "");
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "https://" + url;
        }
        return url.trim();
    }
    isCloud() {
        return ["https://api.bitwarden.com", "https://vault.bitwarden.com/api"].includes(this.getApiUrl());
    }
    isSelfHosted() {
        return ![
            "http://vault.bitwarden.com",
            "https://vault.bitwarden.com",
            "http://vault.qa.bitwarden.pw",
            "https://vault.qa.bitwarden.pw",
        ].includes(this.getWebVaultUrl());
    }
}

;// CONCATENATED MODULE: external "papaparse"
const external_papaparse_namespaceObject = require("papaparse");
;// CONCATENATED MODULE: ../../libs/common/src/vault/enums/cipher-reprompt-type.ts
var CipherRepromptType;
(function (CipherRepromptType) {
    CipherRepromptType[CipherRepromptType["None"] = 0] = "None";
    CipherRepromptType[CipherRepromptType["Password"] = 1] = "Password";
})(CipherRepromptType || (CipherRepromptType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/vault/enums/cipher-type.ts
var CipherType;
(function (CipherType) {
    CipherType[CipherType["Login"] = 1] = "Login";
    CipherType[CipherType["SecureNote"] = 2] = "SecureNote";
    CipherType[CipherType["Card"] = 3] = "Card";
    CipherType[CipherType["Identity"] = 4] = "Identity";
})(CipherType || (CipherType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/services/cryptography/initializer-key.ts
var InitializerKey;
(function (InitializerKey) {
    InitializerKey[InitializerKey["Cipher"] = 0] = "Cipher";
    InitializerKey[InitializerKey["CipherView"] = 1] = "CipherView";
})(InitializerKey || (InitializerKey = {}));

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/attachment.data.ts
class AttachmentData {
    constructor(response) {
        if (response == null) {
            return;
        }
        this.id = response.id;
        this.url = response.url;
        this.fileName = response.fileName;
        this.key = response.key;
        this.size = response.size;
        this.sizeName = response.sizeName;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/card.data.ts
class CardData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.cardholderName = data.cardholderName;
        this.brand = data.brand;
        this.number = data.number;
        this.expMonth = data.expMonth;
        this.expYear = data.expYear;
        this.code = data.code;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/field.data.ts
class FieldData {
    constructor(response) {
        if (response == null) {
            return;
        }
        this.type = response.type;
        this.name = response.name;
        this.value = response.value;
        this.linkedId = response.linkedId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/identity.data.ts
class IdentityData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.title = data.title;
        this.firstName = data.firstName;
        this.middleName = data.middleName;
        this.lastName = data.lastName;
        this.address1 = data.address1;
        this.address2 = data.address2;
        this.address3 = data.address3;
        this.city = data.city;
        this.state = data.state;
        this.postalCode = data.postalCode;
        this.country = data.country;
        this.company = data.company;
        this.email = data.email;
        this.phone = data.phone;
        this.ssn = data.ssn;
        this.username = data.username;
        this.passportNumber = data.passportNumber;
        this.licenseNumber = data.licenseNumber;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/login-uri.data.ts
class LoginUriData {
    constructor(data) {
        this.match = null;
        if (data == null) {
            return;
        }
        this.uri = data.uri;
        this.match = data.match;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/login.data.ts

class LoginData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.username = data.username;
        this.password = data.password;
        this.passwordRevisionDate = data.passwordRevisionDate;
        this.totp = data.totp;
        this.autofillOnPageLoad = data.autofillOnPageLoad;
        if (data.uris) {
            this.uris = data.uris.map((u) => new LoginUriData(u));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/password-history.data.ts
class PasswordHistoryData {
    constructor(response) {
        if (response == null) {
            return;
        }
        this.password = response.password;
        this.lastUsedDate = response.lastUsedDate;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/secure-note.data.ts
class SecureNoteData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.type = data.type;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/cipher.data.ts








class CipherData {
    constructor(response, collectionIds) {
        if (response == null) {
            return;
        }
        this.id = response.id;
        this.organizationId = response.organizationId;
        this.folderId = response.folderId;
        this.edit = response.edit;
        this.viewPassword = response.viewPassword;
        this.organizationUseTotp = response.organizationUseTotp;
        this.favorite = response.favorite;
        this.revisionDate = response.revisionDate;
        this.type = response.type;
        this.name = response.name;
        this.notes = response.notes;
        this.collectionIds = collectionIds != null ? collectionIds : response.collectionIds;
        this.creationDate = response.creationDate;
        this.deletedDate = response.deletedDate;
        this.reprompt = response.reprompt;
        switch (this.type) {
            case CipherType.Login:
                this.login = new LoginData(response.login);
                break;
            case CipherType.SecureNote:
                this.secureNote = new SecureNoteData(response.secureNote);
                break;
            case CipherType.Card:
                this.card = new CardData(response.card);
                break;
            case CipherType.Identity:
                this.identity = new IdentityData(response.identity);
                break;
            default:
                break;
        }
        if (response.fields != null) {
            this.fields = response.fields.map((f) => new FieldData(f));
        }
        if (response.attachments != null) {
            this.attachments = response.attachments.map((a) => new AttachmentData(a));
        }
        if (response.passwordHistory != null) {
            this.passwordHistory = response.passwordHistory.map((ph) => new PasswordHistoryData(ph));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/attachment.view.ts

class AttachmentView {
    constructor(a) {
        this.id = null;
        this.url = null;
        this.size = null;
        this.sizeName = null;
        this.fileName = null;
        this.key = null;
        if (!a) {
            return;
        }
        this.id = a.id;
        this.url = a.url;
        this.size = a.size;
        this.sizeName = a.sizeName;
    }
    get fileSize() {
        try {
            if (this.size != null) {
                return parseInt(this.size, null);
            }
        }
        catch (_a) {
            // Invalid file size.
        }
        return 0;
    }
    static fromJSON(obj) {
        const key = obj.key == null ? null : SymmetricCryptoKey.fromJSON(obj.key);
        return Object.assign(new AttachmentView(), obj, { key: key });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/linkedIdType.ts
// LoginView
var LoginLinkedId;
(function (LoginLinkedId) {
    LoginLinkedId[LoginLinkedId["Username"] = 100] = "Username";
    LoginLinkedId[LoginLinkedId["Password"] = 101] = "Password";
})(LoginLinkedId || (LoginLinkedId = {}));
// CardView
var CardLinkedId;
(function (CardLinkedId) {
    CardLinkedId[CardLinkedId["CardholderName"] = 300] = "CardholderName";
    CardLinkedId[CardLinkedId["ExpMonth"] = 301] = "ExpMonth";
    CardLinkedId[CardLinkedId["ExpYear"] = 302] = "ExpYear";
    CardLinkedId[CardLinkedId["Code"] = 303] = "Code";
    CardLinkedId[CardLinkedId["Brand"] = 304] = "Brand";
    CardLinkedId[CardLinkedId["Number"] = 305] = "Number";
})(CardLinkedId || (CardLinkedId = {}));
// IdentityView
var IdentityLinkedId;
(function (IdentityLinkedId) {
    IdentityLinkedId[IdentityLinkedId["Title"] = 400] = "Title";
    IdentityLinkedId[IdentityLinkedId["MiddleName"] = 401] = "MiddleName";
    IdentityLinkedId[IdentityLinkedId["Address1"] = 402] = "Address1";
    IdentityLinkedId[IdentityLinkedId["Address2"] = 403] = "Address2";
    IdentityLinkedId[IdentityLinkedId["Address3"] = 404] = "Address3";
    IdentityLinkedId[IdentityLinkedId["City"] = 405] = "City";
    IdentityLinkedId[IdentityLinkedId["State"] = 406] = "State";
    IdentityLinkedId[IdentityLinkedId["PostalCode"] = 407] = "PostalCode";
    IdentityLinkedId[IdentityLinkedId["Country"] = 408] = "Country";
    IdentityLinkedId[IdentityLinkedId["Company"] = 409] = "Company";
    IdentityLinkedId[IdentityLinkedId["Email"] = 410] = "Email";
    IdentityLinkedId[IdentityLinkedId["Phone"] = 411] = "Phone";
    IdentityLinkedId[IdentityLinkedId["Ssn"] = 412] = "Ssn";
    IdentityLinkedId[IdentityLinkedId["Username"] = 413] = "Username";
    IdentityLinkedId[IdentityLinkedId["PassportNumber"] = 414] = "PassportNumber";
    IdentityLinkedId[IdentityLinkedId["LicenseNumber"] = 415] = "LicenseNumber";
    IdentityLinkedId[IdentityLinkedId["FirstName"] = 416] = "FirstName";
    IdentityLinkedId[IdentityLinkedId["LastName"] = 417] = "LastName";
    IdentityLinkedId[IdentityLinkedId["FullName"] = 418] = "FullName";
})(IdentityLinkedId || (IdentityLinkedId = {}));

;// CONCATENATED MODULE: ../../libs/common/src/misc/linkedFieldOption.decorator.ts
class LinkedMetadata {
    constructor(propertyKey, _i18nKey) {
        this.propertyKey = propertyKey;
        this._i18nKey = _i18nKey;
    }
    get i18nKey() {
        var _a;
        return (_a = this._i18nKey) !== null && _a !== void 0 ? _a : this.propertyKey;
    }
}
/**
 * A decorator used to set metadata used by Linked custom fields. Apply it to a class property or getter to make it
 *    available as a Linked custom field option.
 * @param id - A unique value that is saved in the Field model. It is used to look up the decorated class property.
 * @param i18nKey - The i18n key used to describe the decorated class property in the UI. If it is null, then the name
 *    of the class property will be used as the i18n key.
 */
function linkedFieldOption(id, i18nKey) {
    return (prototype, propertyKey) => {
        if (prototype.linkedFieldOptions == null) {
            prototype.linkedFieldOptions = new Map();
        }
        prototype.linkedFieldOptions.set(id, new LinkedMetadata(propertyKey, i18nKey));
    };
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/item.view.ts
class ItemView {
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/card.view.ts
var card_view_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var card_view_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};



class CardView extends ItemView {
    constructor() {
        super(...arguments);
        this.cardholderName = null;
        this.expMonth = null;
        this.expYear = null;
        this.code = null;
        this._brand = null;
        this._number = null;
        this._subTitle = null;
    }
    get maskedCode() {
        return this.code != null ? "•".repeat(this.code.length) : null;
    }
    get maskedNumber() {
        return this.number != null ? "•".repeat(this.number.length) : null;
    }
    get brand() {
        return this._brand;
    }
    set brand(value) {
        this._brand = value;
        this._subTitle = null;
    }
    get number() {
        return this._number;
    }
    set number(value) {
        this._number = value;
        this._subTitle = null;
    }
    get subTitle() {
        if (this._subTitle == null) {
            this._subTitle = this.brand;
            if (this.number != null && this.number.length >= 4) {
                if (this._subTitle != null && this._subTitle !== "") {
                    this._subTitle += ", ";
                }
                else {
                    this._subTitle = "";
                }
                // Show last 5 on amex, last 4 for all others
                const count = this.number.length >= 5 && this.number.match(new RegExp("^3[47]")) != null ? 5 : 4;
                this._subTitle += "*" + this.number.substr(this.number.length - count);
            }
        }
        return this._subTitle;
    }
    get expiration() {
        if (!this.expMonth && !this.expYear) {
            return null;
        }
        let exp = this.expMonth != null ? ("0" + this.expMonth).slice(-2) : "__";
        exp += " / " + (this.expYear != null ? this.formatYear(this.expYear) : "____");
        return exp;
    }
    formatYear(year) {
        return year.length === 2 ? "20" + year : year;
    }
    static fromJSON(obj) {
        return Object.assign(new CardView(), obj);
    }
}
card_view_decorate([
    linkedFieldOption(CardLinkedId.CardholderName),
    card_view_metadata("design:type", String)
], CardView.prototype, "cardholderName", void 0);
card_view_decorate([
    linkedFieldOption(CardLinkedId.ExpMonth, "expirationMonth"),
    card_view_metadata("design:type", String)
], CardView.prototype, "expMonth", void 0);
card_view_decorate([
    linkedFieldOption(CardLinkedId.ExpYear, "expirationYear"),
    card_view_metadata("design:type", String)
], CardView.prototype, "expYear", void 0);
card_view_decorate([
    linkedFieldOption(CardLinkedId.Code, "securityCode"),
    card_view_metadata("design:type", String)
], CardView.prototype, "code", void 0);
card_view_decorate([
    linkedFieldOption(CardLinkedId.Brand),
    card_view_metadata("design:type", String),
    card_view_metadata("design:paramtypes", [String])
], CardView.prototype, "brand", null);
card_view_decorate([
    linkedFieldOption(CardLinkedId.Number),
    card_view_metadata("design:type", String),
    card_view_metadata("design:paramtypes", [String])
], CardView.prototype, "number", null);

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/field.view.ts
class FieldView {
    constructor(f) {
        this.name = null;
        this.value = null;
        this.type = null;
        this.newField = false; // Marks if the field is new and hasn't been saved
        this.showValue = false;
        this.showCount = false;
        this.linkedId = null;
        if (!f) {
            return;
        }
        this.type = f.type;
        this.linkedId = f.linkedId;
    }
    get maskedValue() {
        return this.value != null ? "••••••••" : null;
    }
    static fromJSON(obj) {
        return Object.assign(new FieldView(), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/identity.view.ts
var identity_view_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var identity_view_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};




class IdentityView extends ItemView {
    constructor() {
        super();
        this.title = null;
        this.middleName = null;
        this.address1 = null;
        this.address2 = null;
        this.address3 = null;
        this.city = null;
        this.state = null;
        this.postalCode = null;
        this.country = null;
        this.company = null;
        this.email = null;
        this.phone = null;
        this.ssn = null;
        this.username = null;
        this.passportNumber = null;
        this.licenseNumber = null;
        this._firstName = null;
        this._lastName = null;
        this._subTitle = null;
    }
    get firstName() {
        return this._firstName;
    }
    set firstName(value) {
        this._firstName = value;
        this._subTitle = null;
    }
    get lastName() {
        return this._lastName;
    }
    set lastName(value) {
        this._lastName = value;
        this._subTitle = null;
    }
    get subTitle() {
        if (this._subTitle == null && (this.firstName != null || this.lastName != null)) {
            this._subTitle = "";
            if (this.firstName != null) {
                this._subTitle = this.firstName;
            }
            if (this.lastName != null) {
                if (this._subTitle !== "") {
                    this._subTitle += " ";
                }
                this._subTitle += this.lastName;
            }
        }
        return this._subTitle;
    }
    get fullName() {
        if (this.title != null ||
            this.firstName != null ||
            this.middleName != null ||
            this.lastName != null) {
            let name = "";
            if (this.title != null) {
                name += this.title + " ";
            }
            if (this.firstName != null) {
                name += this.firstName + " ";
            }
            if (this.middleName != null) {
                name += this.middleName + " ";
            }
            if (this.lastName != null) {
                name += this.lastName;
            }
            return name.trim();
        }
        return null;
    }
    get fullAddress() {
        let address = this.address1;
        if (!Utils.isNullOrWhitespace(this.address2)) {
            if (!Utils.isNullOrWhitespace(address)) {
                address += ", ";
            }
            address += this.address2;
        }
        if (!Utils.isNullOrWhitespace(this.address3)) {
            if (!Utils.isNullOrWhitespace(address)) {
                address += ", ";
            }
            address += this.address3;
        }
        return address;
    }
    get fullAddressPart2() {
        if (this.city == null && this.state == null && this.postalCode == null) {
            return null;
        }
        const city = this.city || "-";
        const state = this.state;
        const postalCode = this.postalCode || "-";
        let addressPart2 = city;
        if (!Utils.isNullOrWhitespace(state)) {
            addressPart2 += ", " + state;
        }
        addressPart2 += ", " + postalCode;
        return addressPart2;
    }
    static fromJSON(obj) {
        return Object.assign(new IdentityView(), obj);
    }
}
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Title),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "title", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.MiddleName),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "middleName", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Address1),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "address1", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Address2),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "address2", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Address3),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "address3", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.City, "cityTown"),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "city", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.State, "stateProvince"),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "state", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.PostalCode, "zipPostalCode"),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "postalCode", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Country),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "country", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Company),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "company", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Email),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "email", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Phone),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "phone", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Ssn),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "ssn", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.Username),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "username", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.PassportNumber),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "passportNumber", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.LicenseNumber),
    identity_view_metadata("design:type", String)
], IdentityView.prototype, "licenseNumber", void 0);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.FirstName),
    identity_view_metadata("design:type", String),
    identity_view_metadata("design:paramtypes", [String])
], IdentityView.prototype, "firstName", null);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.LastName),
    identity_view_metadata("design:type", String),
    identity_view_metadata("design:paramtypes", [String])
], IdentityView.prototype, "lastName", null);
identity_view_decorate([
    linkedFieldOption(IdentityLinkedId.FullName),
    identity_view_metadata("design:type", String),
    identity_view_metadata("design:paramtypes", [])
], IdentityView.prototype, "fullName", null);

;// CONCATENATED MODULE: ../../libs/common/src/enums/uriMatchType.ts
var UriMatchType;
(function (UriMatchType) {
    UriMatchType[UriMatchType["Domain"] = 0] = "Domain";
    UriMatchType[UriMatchType["Host"] = 1] = "Host";
    UriMatchType[UriMatchType["StartsWith"] = 2] = "StartsWith";
    UriMatchType[UriMatchType["Exact"] = 3] = "Exact";
    UriMatchType[UriMatchType["RegularExpression"] = 4] = "RegularExpression";
    UriMatchType[UriMatchType["Never"] = 5] = "Never";
})(UriMatchType || (UriMatchType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/login-uri.view.ts


const CanLaunchWhitelist = [
    "https://",
    "http://",
    "ssh://",
    "ftp://",
    "sftp://",
    "irc://",
    "vnc://",
    // https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-uri
    "rdp://",
    "ms-rd:",
    "chrome://",
    "iosapp://",
    "androidapp://",
];
class LoginUriView {
    constructor(u) {
        this.match = null;
        this._uri = null;
        this._domain = null;
        this._hostname = null;
        this._host = null;
        this._canLaunch = null;
        if (!u) {
            return;
        }
        this.match = u.match;
    }
    get uri() {
        return this._uri;
    }
    set uri(value) {
        this._uri = value;
        this._domain = null;
        this._canLaunch = null;
    }
    get domain() {
        if (this._domain == null && this.uri != null) {
            this._domain = Utils.getDomain(this.uri);
            if (this._domain === "") {
                this._domain = null;
            }
        }
        return this._domain;
    }
    get hostname() {
        if (this.match === UriMatchType.RegularExpression) {
            return null;
        }
        if (this._hostname == null && this.uri != null) {
            this._hostname = Utils.getHostname(this.uri);
            if (this._hostname === "") {
                this._hostname = null;
            }
        }
        return this._hostname;
    }
    get host() {
        if (this.match === UriMatchType.RegularExpression) {
            return null;
        }
        if (this._host == null && this.uri != null) {
            this._host = Utils.getHost(this.uri);
            if (this._host === "") {
                this._host = null;
            }
        }
        return this._host;
    }
    get hostnameOrUri() {
        return this.hostname != null ? this.hostname : this.uri;
    }
    get hostOrUri() {
        return this.host != null ? this.host : this.uri;
    }
    get isWebsite() {
        return (this.uri != null &&
            (this.uri.indexOf("http://") === 0 ||
                this.uri.indexOf("https://") === 0 ||
                (this.uri.indexOf("://") < 0 && !Utils.isNullOrWhitespace(Utils.getDomain(this.uri)))));
    }
    get canLaunch() {
        if (this._canLaunch != null) {
            return this._canLaunch;
        }
        if (this.uri != null && this.match !== UriMatchType.RegularExpression) {
            const uri = this.launchUri;
            for (let i = 0; i < CanLaunchWhitelist.length; i++) {
                if (uri.indexOf(CanLaunchWhitelist[i]) === 0) {
                    this._canLaunch = true;
                    return this._canLaunch;
                }
            }
        }
        this._canLaunch = false;
        return this._canLaunch;
    }
    get launchUri() {
        return this.uri.indexOf("://") < 0 && !Utils.isNullOrWhitespace(Utils.getDomain(this.uri))
            ? "http://" + this.uri
            : this.uri;
    }
    static fromJSON(obj) {
        return Object.assign(new LoginUriView(), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/login.view.ts
var login_view_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var login_view_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};





class LoginView extends ItemView {
    constructor(l) {
        super();
        this.username = null;
        this.password = null;
        this.passwordRevisionDate = null;
        this.totp = null;
        this.uris = null;
        this.autofillOnPageLoad = null;
        if (!l) {
            return;
        }
        this.passwordRevisionDate = l.passwordRevisionDate;
        this.autofillOnPageLoad = l.autofillOnPageLoad;
    }
    get uri() {
        return this.hasUris ? this.uris[0].uri : null;
    }
    get maskedPassword() {
        return this.password != null ? "••••••••" : null;
    }
    get subTitle() {
        return this.username;
    }
    get canLaunch() {
        return this.hasUris && this.uris.some((u) => u.canLaunch);
    }
    get hasTotp() {
        return !Utils.isNullOrWhitespace(this.totp);
    }
    get launchUri() {
        if (this.hasUris) {
            const uri = this.uris.find((u) => u.canLaunch);
            if (uri != null) {
                return uri.launchUri;
            }
        }
        return null;
    }
    get hasUris() {
        return this.uris != null && this.uris.length > 0;
    }
    static fromJSON(obj) {
        var _a;
        const passwordRevisionDate = obj.passwordRevisionDate == null ? null : new Date(obj.passwordRevisionDate);
        const uris = (_a = obj.uris) === null || _a === void 0 ? void 0 : _a.map((uri) => LoginUriView.fromJSON(uri));
        return Object.assign(new LoginView(), obj, {
            passwordRevisionDate: passwordRevisionDate,
            uris: uris,
        });
    }
}
login_view_decorate([
    linkedFieldOption(LoginLinkedId.Username),
    login_view_metadata("design:type", String)
], LoginView.prototype, "username", void 0);
login_view_decorate([
    linkedFieldOption(LoginLinkedId.Password),
    login_view_metadata("design:type", String)
], LoginView.prototype, "password", void 0);

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/password-history.view.ts
class PasswordHistoryView {
    constructor(ph) {
        this.password = null;
        this.lastUsedDate = null;
        if (!ph) {
            return;
        }
        this.lastUsedDate = ph.lastUsedDate;
    }
    static fromJSON(obj) {
        const lastUsedDate = obj.lastUsedDate == null ? null : new Date(obj.lastUsedDate);
        return Object.assign(new PasswordHistoryView(), obj, {
            lastUsedDate: lastUsedDate,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/secure-note.view.ts

class SecureNoteView extends ItemView {
    constructor(n) {
        super();
        this.type = null;
        if (!n) {
            return;
        }
        this.type = n.type;
    }
    get subTitle() {
        return null;
    }
    static fromJSON(obj) {
        return Object.assign(new SecureNoteView(), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/cipher.view.ts










class CipherView {
    constructor(c) {
        var _a;
        this.initializerKey = InitializerKey.CipherView;
        this.id = null;
        this.organizationId = null;
        this.folderId = null;
        this.name = null;
        this.notes = null;
        this.type = null;
        this.favorite = false;
        this.organizationUseTotp = false;
        this.edit = false;
        this.viewPassword = true;
        this.login = new LoginView();
        this.identity = new IdentityView();
        this.card = new CardView();
        this.secureNote = new SecureNoteView();
        this.attachments = null;
        this.fields = null;
        this.passwordHistory = null;
        this.collectionIds = null;
        this.revisionDate = null;
        this.creationDate = null;
        this.deletedDate = null;
        this.reprompt = CipherRepromptType.None;
        if (!c) {
            return;
        }
        this.id = c.id;
        this.organizationId = c.organizationId;
        this.folderId = c.folderId;
        this.favorite = c.favorite;
        this.organizationUseTotp = c.organizationUseTotp;
        this.edit = c.edit;
        this.viewPassword = c.viewPassword;
        this.type = c.type;
        this.localData = c.localData;
        this.collectionIds = c.collectionIds;
        this.revisionDate = c.revisionDate;
        this.creationDate = c.creationDate;
        this.deletedDate = c.deletedDate;
        // Old locally stored ciphers might have reprompt == null. If so set it to None.
        this.reprompt = (_a = c.reprompt) !== null && _a !== void 0 ? _a : CipherRepromptType.None;
    }
    get item() {
        switch (this.type) {
            case CipherType.Login:
                return this.login;
            case CipherType.SecureNote:
                return this.secureNote;
            case CipherType.Card:
                return this.card;
            case CipherType.Identity:
                return this.identity;
            default:
                break;
        }
        return null;
    }
    get subTitle() {
        return this.item.subTitle;
    }
    get hasPasswordHistory() {
        return this.passwordHistory && this.passwordHistory.length > 0;
    }
    get hasAttachments() {
        return this.attachments && this.attachments.length > 0;
    }
    get hasOldAttachments() {
        if (this.hasAttachments) {
            for (let i = 0; i < this.attachments.length; i++) {
                if (this.attachments[i].key == null) {
                    return true;
                }
            }
        }
        return false;
    }
    get hasFields() {
        return this.fields && this.fields.length > 0;
    }
    get passwordRevisionDisplayDate() {
        if (this.type !== CipherType.Login || this.login == null) {
            return null;
        }
        else if (this.login.password == null || this.login.password === "") {
            return null;
        }
        return this.login.passwordRevisionDate;
    }
    get isDeleted() {
        return this.deletedDate != null;
    }
    get linkedFieldOptions() {
        return this.item.linkedFieldOptions;
    }
    linkedFieldValue(id) {
        var _a;
        const linkedFieldOption = (_a = this.linkedFieldOptions) === null || _a === void 0 ? void 0 : _a.get(id);
        if (linkedFieldOption == null) {
            return null;
        }
        const item = this.item;
        return this.item[linkedFieldOption.propertyKey];
    }
    linkedFieldI18nKey(id) {
        var _a;
        return (_a = this.linkedFieldOptions.get(id)) === null || _a === void 0 ? void 0 : _a.i18nKey;
    }
    static fromJSON(obj) {
        var _a, _b, _c;
        const view = new CipherView();
        const revisionDate = obj.revisionDate == null ? null : new Date(obj.revisionDate);
        const deletedDate = obj.deletedDate == null ? null : new Date(obj.deletedDate);
        const attachments = (_a = obj.attachments) === null || _a === void 0 ? void 0 : _a.map((a) => AttachmentView.fromJSON(a));
        const fields = (_b = obj.fields) === null || _b === void 0 ? void 0 : _b.map((f) => FieldView.fromJSON(f));
        const passwordHistory = (_c = obj.passwordHistory) === null || _c === void 0 ? void 0 : _c.map((ph) => PasswordHistoryView.fromJSON(ph));
        Object.assign(view, obj, {
            revisionDate: revisionDate,
            deletedDate: deletedDate,
            attachments: attachments,
            fields: fields,
            passwordHistory: passwordHistory,
        });
        switch (obj.type) {
            case CipherType.Card:
                view.card = CardView.fromJSON(obj.card);
                break;
            case CipherType.Identity:
                view.identity = IdentityView.fromJSON(obj.identity);
                break;
            case CipherType.Login:
                view.login = LoginView.fromJSON(obj.login);
                break;
            case CipherType.SecureNote:
                view.secureNote = SecureNoteView.fromJSON(obj.secureNote);
                break;
            default:
                break;
        }
        return view;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/attachment.ts
var attachment_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};






class Attachment extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.size = obj.size;
        this.buildDomainModel(this, obj, {
            id: null,
            url: null,
            sizeName: null,
            fileName: null,
            key: null,
        }, ["id", "url", "sizeName"]);
    }
    decrypt(orgId, encKey) {
        return attachment_awaiter(this, void 0, void 0, function* () {
            const view = yield this.decryptObj(new AttachmentView(this), {
                fileName: null,
            }, orgId, encKey);
            if (this.key != null) {
                view.key = yield this.decryptAttachmentKey(orgId, encKey);
            }
            return view;
        });
    }
    decryptAttachmentKey(orgId, encKey) {
        return attachment_awaiter(this, void 0, void 0, function* () {
            try {
                if (encKey == null) {
                    encKey = yield this.getKeyForDecryption(orgId);
                }
                const encryptService = Utils.getContainerService().getEncryptService();
                const decValue = yield encryptService.decryptToBytes(this.key, encKey);
                return new SymmetricCryptoKey(decValue);
            }
            catch (e) {
                // TODO: error?
            }
        });
    }
    getKeyForDecryption(orgId) {
        return attachment_awaiter(this, void 0, void 0, function* () {
            const cryptoService = Utils.getContainerService().getCryptoService();
            return orgId != null
                ? yield cryptoService.getOrgKey(orgId)
                : yield cryptoService.getKeyForUserEncryption();
        });
    }
    toAttachmentData() {
        const a = new AttachmentData();
        a.size = this.size;
        this.buildDataModel(this, a, {
            id: null,
            url: null,
            sizeName: null,
            fileName: null,
            key: null,
        }, ["id", "url", "sizeName"]);
        return a;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const key = EncString.fromJSON(obj.key);
        const fileName = EncString.fromJSON(obj.fileName);
        return Object.assign(new Attachment(), obj, {
            key,
            fileName,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/card.ts




class Card extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            cardholderName: null,
            brand: null,
            number: null,
            expMonth: null,
            expYear: null,
            code: null,
        }, []);
    }
    decrypt(orgId, encKey) {
        return this.decryptObj(new CardView(), {
            cardholderName: null,
            brand: null,
            number: null,
            expMonth: null,
            expYear: null,
            code: null,
        }, orgId, encKey);
    }
    toCardData() {
        const c = new CardData();
        this.buildDataModel(this, c, {
            cardholderName: null,
            brand: null,
            number: null,
            expMonth: null,
            expYear: null,
            code: null,
        });
        return c;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const cardholderName = EncString.fromJSON(obj.cardholderName);
        const brand = EncString.fromJSON(obj.brand);
        const number = EncString.fromJSON(obj.number);
        const expMonth = EncString.fromJSON(obj.expMonth);
        const expYear = EncString.fromJSON(obj.expYear);
        const code = EncString.fromJSON(obj.code);
        return Object.assign(new Card(), obj, {
            cardholderName,
            brand,
            number,
            expMonth,
            expYear,
            code,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/field.ts




class Field extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.type = obj.type;
        this.linkedId = obj.linkedId;
        this.buildDomainModel(this, obj, {
            name: null,
            value: null,
        }, []);
    }
    decrypt(orgId, encKey) {
        return this.decryptObj(new FieldView(this), {
            name: null,
            value: null,
        }, orgId, encKey);
    }
    toFieldData() {
        const f = new FieldData();
        this.buildDataModel(this, f, {
            name: null,
            value: null,
            type: null,
            linkedId: null,
        }, ["type", "linkedId"]);
        return f;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const name = EncString.fromJSON(obj.name);
        const value = EncString.fromJSON(obj.value);
        return Object.assign(new Field(), obj, {
            name,
            value,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/identity.ts




class Identity extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            title: null,
            firstName: null,
            middleName: null,
            lastName: null,
            address1: null,
            address2: null,
            address3: null,
            city: null,
            state: null,
            postalCode: null,
            country: null,
            company: null,
            email: null,
            phone: null,
            ssn: null,
            username: null,
            passportNumber: null,
            licenseNumber: null,
        }, []);
    }
    decrypt(orgId, encKey) {
        return this.decryptObj(new IdentityView(), {
            title: null,
            firstName: null,
            middleName: null,
            lastName: null,
            address1: null,
            address2: null,
            address3: null,
            city: null,
            state: null,
            postalCode: null,
            country: null,
            company: null,
            email: null,
            phone: null,
            ssn: null,
            username: null,
            passportNumber: null,
            licenseNumber: null,
        }, orgId, encKey);
    }
    toIdentityData() {
        const i = new IdentityData();
        this.buildDataModel(this, i, {
            title: null,
            firstName: null,
            middleName: null,
            lastName: null,
            address1: null,
            address2: null,
            address3: null,
            city: null,
            state: null,
            postalCode: null,
            country: null,
            company: null,
            email: null,
            phone: null,
            ssn: null,
            username: null,
            passportNumber: null,
            licenseNumber: null,
        });
        return i;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const title = EncString.fromJSON(obj.title);
        const firstName = EncString.fromJSON(obj.firstName);
        const middleName = EncString.fromJSON(obj.middleName);
        const lastName = EncString.fromJSON(obj.lastName);
        const address1 = EncString.fromJSON(obj.address1);
        const address2 = EncString.fromJSON(obj.address2);
        const address3 = EncString.fromJSON(obj.address3);
        const city = EncString.fromJSON(obj.city);
        const state = EncString.fromJSON(obj.state);
        const postalCode = EncString.fromJSON(obj.postalCode);
        const country = EncString.fromJSON(obj.country);
        const company = EncString.fromJSON(obj.company);
        const email = EncString.fromJSON(obj.email);
        const phone = EncString.fromJSON(obj.phone);
        const ssn = EncString.fromJSON(obj.ssn);
        const username = EncString.fromJSON(obj.username);
        const passportNumber = EncString.fromJSON(obj.passportNumber);
        const licenseNumber = EncString.fromJSON(obj.licenseNumber);
        return Object.assign(new Identity(), obj, {
            title,
            firstName,
            middleName,
            lastName,
            address1,
            address2,
            address3,
            city,
            state,
            postalCode,
            country,
            company,
            email,
            phone,
            ssn,
            username,
            passportNumber,
            licenseNumber,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/login-uri.ts




class LoginUri extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.match = obj.match;
        this.buildDomainModel(this, obj, {
            uri: null,
        }, []);
    }
    decrypt(orgId, encKey) {
        return this.decryptObj(new LoginUriView(this), {
            uri: null,
        }, orgId, encKey);
    }
    toLoginUriData() {
        const u = new LoginUriData();
        this.buildDataModel(this, u, {
            uri: null,
            match: null,
        }, ["match"]);
        return u;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const uri = EncString.fromJSON(obj.uri);
        return Object.assign(new LoginUri(), obj, {
            uri,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/login.ts
var login_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class Login extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.passwordRevisionDate =
            obj.passwordRevisionDate != null ? new Date(obj.passwordRevisionDate) : null;
        this.autofillOnPageLoad = obj.autofillOnPageLoad;
        this.buildDomainModel(this, obj, {
            username: null,
            password: null,
            totp: null,
        }, []);
        if (obj.uris) {
            this.uris = [];
            obj.uris.forEach((u) => {
                this.uris.push(new LoginUri(u));
            });
        }
    }
    decrypt(orgId, encKey) {
        return login_awaiter(this, void 0, void 0, function* () {
            const view = yield this.decryptObj(new LoginView(this), {
                username: null,
                password: null,
                totp: null,
            }, orgId, encKey);
            if (this.uris != null) {
                view.uris = [];
                for (let i = 0; i < this.uris.length; i++) {
                    const uri = yield this.uris[i].decrypt(orgId, encKey);
                    view.uris.push(uri);
                }
            }
            return view;
        });
    }
    toLoginData() {
        const l = new LoginData();
        l.passwordRevisionDate =
            this.passwordRevisionDate != null ? this.passwordRevisionDate.toISOString() : null;
        l.autofillOnPageLoad = this.autofillOnPageLoad;
        this.buildDataModel(this, l, {
            username: null,
            password: null,
            totp: null,
        });
        if (this.uris != null && this.uris.length > 0) {
            l.uris = [];
            this.uris.forEach((u) => {
                l.uris.push(u.toLoginUriData());
            });
        }
        return l;
    }
    static fromJSON(obj) {
        var _a;
        if (obj == null) {
            return null;
        }
        const username = EncString.fromJSON(obj.username);
        const password = EncString.fromJSON(obj.password);
        const totp = EncString.fromJSON(obj.totp);
        const passwordRevisionDate = obj.passwordRevisionDate == null ? null : new Date(obj.passwordRevisionDate);
        const uris = (_a = obj.uris) === null || _a === void 0 ? void 0 : _a.map((uri) => LoginUri.fromJSON(uri));
        return Object.assign(new Login(), obj, {
            username,
            password,
            totp,
            passwordRevisionDate: passwordRevisionDate,
            uris: uris,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/password.ts




class Password extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            password: null,
        });
        this.lastUsedDate = new Date(obj.lastUsedDate);
    }
    decrypt(orgId, encKey) {
        return this.decryptObj(new PasswordHistoryView(this), {
            password: null,
        }, orgId, encKey);
    }
    toPasswordHistoryData() {
        const ph = new PasswordHistoryData();
        ph.lastUsedDate = this.lastUsedDate.toISOString();
        this.buildDataModel(this, ph, {
            password: null,
        });
        return ph;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        const password = EncString.fromJSON(obj.password);
        const lastUsedDate = obj.lastUsedDate == null ? null : new Date(obj.lastUsedDate);
        return Object.assign(new Password(), obj, {
            password,
            lastUsedDate,
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/secure-note.ts



class SecureNote extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.type = obj.type;
    }
    decrypt(orgId, encKey) {
        return Promise.resolve(new SecureNoteView(this));
    }
    toSecureNoteData() {
        const n = new SecureNoteData();
        n.type = this.type;
        return n;
    }
    static fromJSON(obj) {
        if (obj == null) {
            return null;
        }
        return Object.assign(new SecureNote(), obj);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/cipher.ts
var cipher_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};













class Cipher extends Domain {
    constructor(obj, localData = null) {
        super();
        this.initializerKey = InitializerKey.Cipher;
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            id: null,
            organizationId: null,
            folderId: null,
            name: null,
            notes: null,
        }, ["id", "organizationId", "folderId"]);
        this.type = obj.type;
        this.favorite = obj.favorite;
        this.organizationUseTotp = obj.organizationUseTotp;
        this.edit = obj.edit;
        if (obj.viewPassword != null) {
            this.viewPassword = obj.viewPassword;
        }
        else {
            this.viewPassword = true; // Default for already synced Ciphers without viewPassword
        }
        this.revisionDate = obj.revisionDate != null ? new Date(obj.revisionDate) : null;
        this.collectionIds = obj.collectionIds;
        this.localData = localData;
        this.creationDate = obj.creationDate != null ? new Date(obj.creationDate) : null;
        this.deletedDate = obj.deletedDate != null ? new Date(obj.deletedDate) : null;
        this.reprompt = obj.reprompt;
        switch (this.type) {
            case CipherType.Login:
                this.login = new Login(obj.login);
                break;
            case CipherType.SecureNote:
                this.secureNote = new SecureNote(obj.secureNote);
                break;
            case CipherType.Card:
                this.card = new Card(obj.card);
                break;
            case CipherType.Identity:
                this.identity = new Identity(obj.identity);
                break;
            default:
                break;
        }
        if (obj.attachments != null) {
            this.attachments = obj.attachments.map((a) => new Attachment(a));
        }
        else {
            this.attachments = null;
        }
        if (obj.fields != null) {
            this.fields = obj.fields.map((f) => new Field(f));
        }
        else {
            this.fields = null;
        }
        if (obj.passwordHistory != null) {
            this.passwordHistory = obj.passwordHistory.map((ph) => new Password(ph));
        }
        else {
            this.passwordHistory = null;
        }
    }
    decrypt(encKey) {
        return cipher_awaiter(this, void 0, void 0, function* () {
            const model = new CipherView(this);
            yield this.decryptObj(model, {
                name: null,
                notes: null,
            }, this.organizationId, encKey);
            switch (this.type) {
                case CipherType.Login:
                    model.login = yield this.login.decrypt(this.organizationId, encKey);
                    break;
                case CipherType.SecureNote:
                    model.secureNote = yield this.secureNote.decrypt(this.organizationId, encKey);
                    break;
                case CipherType.Card:
                    model.card = yield this.card.decrypt(this.organizationId, encKey);
                    break;
                case CipherType.Identity:
                    model.identity = yield this.identity.decrypt(this.organizationId, encKey);
                    break;
                default:
                    break;
            }
            const orgId = this.organizationId;
            if (this.attachments != null && this.attachments.length > 0) {
                const attachments = [];
                yield this.attachments.reduce((promise, attachment) => {
                    return promise
                        .then(() => {
                        return attachment.decrypt(orgId, encKey);
                    })
                        .then((decAttachment) => {
                        attachments.push(decAttachment);
                    });
                }, Promise.resolve());
                model.attachments = attachments;
            }
            if (this.fields != null && this.fields.length > 0) {
                const fields = [];
                yield this.fields.reduce((promise, field) => {
                    return promise
                        .then(() => {
                        return field.decrypt(orgId, encKey);
                    })
                        .then((decField) => {
                        fields.push(decField);
                    });
                }, Promise.resolve());
                model.fields = fields;
            }
            if (this.passwordHistory != null && this.passwordHistory.length > 0) {
                const passwordHistory = [];
                yield this.passwordHistory.reduce((promise, ph) => {
                    return promise
                        .then(() => {
                        return ph.decrypt(orgId, encKey);
                    })
                        .then((decPh) => {
                        passwordHistory.push(decPh);
                    });
                }, Promise.resolve());
                model.passwordHistory = passwordHistory;
            }
            return model;
        });
    }
    toCipherData() {
        const c = new CipherData();
        c.id = this.id;
        c.organizationId = this.organizationId;
        c.folderId = this.folderId;
        c.edit = this.edit;
        c.viewPassword = this.viewPassword;
        c.organizationUseTotp = this.organizationUseTotp;
        c.favorite = this.favorite;
        c.revisionDate = this.revisionDate != null ? this.revisionDate.toISOString() : null;
        c.type = this.type;
        c.collectionIds = this.collectionIds;
        c.creationDate = this.creationDate != null ? this.creationDate.toISOString() : null;
        c.deletedDate = this.deletedDate != null ? this.deletedDate.toISOString() : null;
        c.reprompt = this.reprompt;
        this.buildDataModel(this, c, {
            name: null,
            notes: null,
        });
        switch (c.type) {
            case CipherType.Login:
                c.login = this.login.toLoginData();
                break;
            case CipherType.SecureNote:
                c.secureNote = this.secureNote.toSecureNoteData();
                break;
            case CipherType.Card:
                c.card = this.card.toCardData();
                break;
            case CipherType.Identity:
                c.identity = this.identity.toIdentityData();
                break;
            default:
                break;
        }
        if (this.fields != null) {
            c.fields = this.fields.map((f) => f.toFieldData());
        }
        if (this.attachments != null) {
            c.attachments = this.attachments.map((a) => a.toAttachmentData());
        }
        if (this.passwordHistory != null) {
            c.passwordHistory = this.passwordHistory.map((ph) => ph.toPasswordHistoryData());
        }
        return c;
    }
    static fromJSON(obj) {
        var _a, _b, _c;
        if (obj == null) {
            return null;
        }
        const domain = new Cipher();
        const name = EncString.fromJSON(obj.name);
        const notes = EncString.fromJSON(obj.notes);
        const revisionDate = obj.revisionDate == null ? null : new Date(obj.revisionDate);
        const deletedDate = obj.deletedDate == null ? null : new Date(obj.deletedDate);
        const attachments = (_a = obj.attachments) === null || _a === void 0 ? void 0 : _a.map((a) => Attachment.fromJSON(a));
        const fields = (_b = obj.fields) === null || _b === void 0 ? void 0 : _b.map((f) => Field.fromJSON(f));
        const passwordHistory = (_c = obj.passwordHistory) === null || _c === void 0 ? void 0 : _c.map((ph) => Password.fromJSON(ph));
        Object.assign(domain, obj, {
            name,
            notes,
            revisionDate,
            deletedDate,
            attachments,
            fields,
            passwordHistory,
        });
        switch (obj.type) {
            case CipherType.Card:
                domain.card = Card.fromJSON(obj.card);
                break;
            case CipherType.Identity:
                domain.identity = Identity.fromJSON(obj.identity);
                break;
            case CipherType.Login:
                domain.login = Login.fromJSON(obj.login);
                break;
            case CipherType.SecureNote:
                domain.secureNote = SecureNote.fromJSON(obj.secureNote);
                break;
            default:
                break;
        }
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/card.export.ts



class CardExport {
    constructor(o) {
        var _a, _b, _c, _d, _e, _f;
        if (o == null) {
            return;
        }
        if (o instanceof CardView) {
            this.cardholderName = o.cardholderName;
            this.brand = o.brand;
            this.number = o.number;
            this.expMonth = o.expMonth;
            this.expYear = o.expYear;
            this.code = o.code;
        }
        else {
            this.cardholderName = (_a = o.cardholderName) === null || _a === void 0 ? void 0 : _a.encryptedString;
            this.brand = (_b = o.brand) === null || _b === void 0 ? void 0 : _b.encryptedString;
            this.number = (_c = o.number) === null || _c === void 0 ? void 0 : _c.encryptedString;
            this.expMonth = (_d = o.expMonth) === null || _d === void 0 ? void 0 : _d.encryptedString;
            this.expYear = (_e = o.expYear) === null || _e === void 0 ? void 0 : _e.encryptedString;
            this.code = (_f = o.code) === null || _f === void 0 ? void 0 : _f.encryptedString;
        }
    }
    static template() {
        const req = new CardExport();
        req.cardholderName = "John Doe";
        req.brand = "visa";
        req.number = "4242424242424242";
        req.expMonth = "04";
        req.expYear = "2023";
        req.code = "123";
        return req;
    }
    static toView(req, view = new CardView()) {
        view.cardholderName = req.cardholderName;
        view.brand = req.brand;
        view.number = req.number;
        view.expMonth = req.expMonth;
        view.expYear = req.expYear;
        view.code = req.code;
        return view;
    }
    static toDomain(req, domain = new Card()) {
        domain.cardholderName = req.cardholderName != null ? new EncString(req.cardholderName) : null;
        domain.brand = req.brand != null ? new EncString(req.brand) : null;
        domain.number = req.number != null ? new EncString(req.number) : null;
        domain.expMonth = req.expMonth != null ? new EncString(req.expMonth) : null;
        domain.expYear = req.expYear != null ? new EncString(req.expYear) : null;
        domain.code = req.code != null ? new EncString(req.code) : null;
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/fieldType.ts
var FieldType;
(function (FieldType) {
    FieldType[FieldType["Text"] = 0] = "Text";
    FieldType[FieldType["Hidden"] = 1] = "Hidden";
    FieldType[FieldType["Boolean"] = 2] = "Boolean";
    FieldType[FieldType["Linked"] = 3] = "Linked";
})(FieldType || (FieldType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/export/field.export.ts




class FieldExport {
    constructor(o) {
        var _a, _b;
        if (o == null) {
            return;
        }
        if (o instanceof FieldView) {
            this.name = o.name;
            this.value = o.value;
        }
        else {
            this.name = (_a = o.name) === null || _a === void 0 ? void 0 : _a.encryptedString;
            this.value = (_b = o.value) === null || _b === void 0 ? void 0 : _b.encryptedString;
        }
        this.type = o.type;
        this.linkedId = o.linkedId;
    }
    static template() {
        const req = new FieldExport();
        req.name = "Field name";
        req.value = "Some value";
        req.type = FieldType.Text;
        return req;
    }
    static toView(req, view = new FieldView()) {
        view.type = req.type;
        view.value = req.value;
        view.name = req.name;
        view.linkedId = req.linkedId;
        return view;
    }
    static toDomain(req, domain = new Field()) {
        domain.type = req.type;
        domain.value = req.value != null ? new EncString(req.value) : null;
        domain.name = req.name != null ? new EncString(req.name) : null;
        domain.linkedId = req.linkedId;
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/identity.export.ts



class IdentityExport {
    constructor(o) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
        if (o == null) {
            return;
        }
        if (o instanceof IdentityView) {
            this.title = o.title;
            this.firstName = o.firstName;
            this.middleName = o.middleName;
            this.lastName = o.lastName;
            this.address1 = o.address1;
            this.address2 = o.address2;
            this.address3 = o.address3;
            this.city = o.city;
            this.state = o.state;
            this.postalCode = o.postalCode;
            this.country = o.country;
            this.company = o.company;
            this.email = o.email;
            this.phone = o.phone;
            this.ssn = o.ssn;
            this.username = o.username;
            this.passportNumber = o.passportNumber;
            this.licenseNumber = o.licenseNumber;
        }
        else {
            this.title = (_a = o.title) === null || _a === void 0 ? void 0 : _a.encryptedString;
            this.firstName = (_b = o.firstName) === null || _b === void 0 ? void 0 : _b.encryptedString;
            this.middleName = (_c = o.middleName) === null || _c === void 0 ? void 0 : _c.encryptedString;
            this.lastName = (_d = o.lastName) === null || _d === void 0 ? void 0 : _d.encryptedString;
            this.address1 = (_e = o.address1) === null || _e === void 0 ? void 0 : _e.encryptedString;
            this.address2 = (_f = o.address2) === null || _f === void 0 ? void 0 : _f.encryptedString;
            this.address3 = (_g = o.address3) === null || _g === void 0 ? void 0 : _g.encryptedString;
            this.city = (_h = o.city) === null || _h === void 0 ? void 0 : _h.encryptedString;
            this.state = (_j = o.state) === null || _j === void 0 ? void 0 : _j.encryptedString;
            this.postalCode = (_k = o.postalCode) === null || _k === void 0 ? void 0 : _k.encryptedString;
            this.country = (_l = o.country) === null || _l === void 0 ? void 0 : _l.encryptedString;
            this.company = (_m = o.company) === null || _m === void 0 ? void 0 : _m.encryptedString;
            this.email = (_o = o.email) === null || _o === void 0 ? void 0 : _o.encryptedString;
            this.phone = (_p = o.phone) === null || _p === void 0 ? void 0 : _p.encryptedString;
            this.ssn = (_q = o.ssn) === null || _q === void 0 ? void 0 : _q.encryptedString;
            this.username = (_r = o.username) === null || _r === void 0 ? void 0 : _r.encryptedString;
            this.passportNumber = (_s = o.passportNumber) === null || _s === void 0 ? void 0 : _s.encryptedString;
            this.licenseNumber = (_t = o.licenseNumber) === null || _t === void 0 ? void 0 : _t.encryptedString;
        }
    }
    static template() {
        const req = new IdentityExport();
        req.title = "Mr";
        req.firstName = "John";
        req.middleName = "William";
        req.lastName = "Doe";
        req.address1 = "123 Any St";
        req.address2 = "Apt #123";
        req.address3 = null;
        req.city = "New York";
        req.state = "NY";
        req.postalCode = "10001";
        req.country = "US";
        req.company = "Acme Inc.";
        req.email = "john@company.com";
        req.phone = "5555551234";
        req.ssn = "000-123-4567";
        req.username = "jdoe";
        req.passportNumber = "US-123456789";
        req.licenseNumber = "D123-12-123-12333";
        return req;
    }
    static toView(req, view = new IdentityView()) {
        view.title = req.title;
        view.firstName = req.firstName;
        view.middleName = req.middleName;
        view.lastName = req.lastName;
        view.address1 = req.address1;
        view.address2 = req.address2;
        view.address3 = req.address3;
        view.city = req.city;
        view.state = req.state;
        view.postalCode = req.postalCode;
        view.country = req.country;
        view.company = req.company;
        view.email = req.email;
        view.phone = req.phone;
        view.ssn = req.ssn;
        view.username = req.username;
        view.passportNumber = req.passportNumber;
        view.licenseNumber = req.licenseNumber;
        return view;
    }
    static toDomain(req, domain = new Identity()) {
        domain.title = req.title != null ? new EncString(req.title) : null;
        domain.firstName = req.firstName != null ? new EncString(req.firstName) : null;
        domain.middleName = req.middleName != null ? new EncString(req.middleName) : null;
        domain.lastName = req.lastName != null ? new EncString(req.lastName) : null;
        domain.address1 = req.address1 != null ? new EncString(req.address1) : null;
        domain.address2 = req.address2 != null ? new EncString(req.address2) : null;
        domain.address3 = req.address3 != null ? new EncString(req.address3) : null;
        domain.city = req.city != null ? new EncString(req.city) : null;
        domain.state = req.state != null ? new EncString(req.state) : null;
        domain.postalCode = req.postalCode != null ? new EncString(req.postalCode) : null;
        domain.country = req.country != null ? new EncString(req.country) : null;
        domain.company = req.company != null ? new EncString(req.company) : null;
        domain.email = req.email != null ? new EncString(req.email) : null;
        domain.phone = req.phone != null ? new EncString(req.phone) : null;
        domain.ssn = req.ssn != null ? new EncString(req.ssn) : null;
        domain.username = req.username != null ? new EncString(req.username) : null;
        domain.passportNumber = req.passportNumber != null ? new EncString(req.passportNumber) : null;
        domain.licenseNumber = req.licenseNumber != null ? new EncString(req.licenseNumber) : null;
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/login-uri.export.ts



class LoginUriExport {
    constructor(o) {
        var _a;
        this.match = null;
        if (o == null) {
            return;
        }
        if (o instanceof LoginUriView) {
            this.uri = o.uri;
        }
        else {
            this.uri = (_a = o.uri) === null || _a === void 0 ? void 0 : _a.encryptedString;
        }
        this.match = o.match;
    }
    static template() {
        const req = new LoginUriExport();
        req.uri = "https://google.com";
        req.match = null;
        return req;
    }
    static toView(req, view = new LoginUriView()) {
        view.uri = req.uri;
        view.match = req.match;
        return view;
    }
    static toDomain(req, domain = new LoginUri()) {
        domain.uri = req.uri != null ? new EncString(req.uri) : null;
        domain.match = req.match;
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/login.export.ts




class LoginExport {
    constructor(o) {
        var _a, _b, _c;
        if (o == null) {
            return;
        }
        if (o.uris != null) {
            if (o instanceof LoginView) {
                this.uris = o.uris.map((u) => new LoginUriExport(u));
            }
            else {
                this.uris = o.uris.map((u) => new LoginUriExport(u));
            }
        }
        if (o instanceof LoginView) {
            this.username = o.username;
            this.password = o.password;
            this.totp = o.totp;
        }
        else {
            this.username = (_a = o.username) === null || _a === void 0 ? void 0 : _a.encryptedString;
            this.password = (_b = o.password) === null || _b === void 0 ? void 0 : _b.encryptedString;
            this.totp = (_c = o.totp) === null || _c === void 0 ? void 0 : _c.encryptedString;
        }
    }
    static template() {
        const req = new LoginExport();
        req.uris = [];
        req.username = "jdoe";
        req.password = "myp@ssword123";
        req.totp = "JBSWY3DPEHPK3PXP";
        return req;
    }
    static toView(req, view = new LoginView()) {
        if (req.uris != null) {
            view.uris = req.uris.map((u) => LoginUriExport.toView(u));
        }
        view.username = req.username;
        view.password = req.password;
        view.totp = req.totp;
        return view;
    }
    static toDomain(req, domain = new Login()) {
        if (req.uris != null) {
            domain.uris = req.uris.map((u) => LoginUriExport.toDomain(u));
        }
        domain.username = req.username != null ? new EncString(req.username) : null;
        domain.password = req.password != null ? new EncString(req.password) : null;
        domain.totp = req.totp != null ? new EncString(req.totp) : null;
        return domain;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/secureNoteType.ts
var SecureNoteType;
(function (SecureNoteType) {
    SecureNoteType[SecureNoteType["Generic"] = 0] = "Generic";
})(SecureNoteType || (SecureNoteType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/export/secure-note.export.ts



class SecureNoteExport {
    constructor(o) {
        if (o == null) {
            return;
        }
        this.type = o.type;
    }
    static template() {
        const req = new SecureNoteExport();
        req.type = SecureNoteType.Generic;
        return req;
    }
    static toView(req, view = new SecureNoteView()) {
        view.type = req.type;
        return view;
    }
    static toDomain(req, view = new SecureNote()) {
        view.type = req.type;
        return view;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/cipher.export.ts










class CipherExport {
    static template() {
        const req = new CipherExport();
        req.organizationId = null;
        req.collectionIds = null;
        req.folderId = null;
        req.type = CipherType.Login;
        req.name = "Item name";
        req.notes = "Some notes about this item.";
        req.favorite = false;
        req.fields = [];
        req.login = null;
        req.secureNote = null;
        req.card = null;
        req.identity = null;
        req.reprompt = CipherRepromptType.None;
        return req;
    }
    static toView(req, view = new CipherView()) {
        var _a, _b, _c;
        view.type = req.type;
        view.folderId = req.folderId;
        if (view.organizationId == null) {
            view.organizationId = req.organizationId;
        }
        if (view.collectionIds || req.collectionIds) {
            const set = new Set(((_a = view.collectionIds) !== null && _a !== void 0 ? _a : []).concat((_b = req.collectionIds) !== null && _b !== void 0 ? _b : []));
            view.collectionIds = Array.from(set.values());
        }
        view.name = req.name;
        view.notes = req.notes;
        view.favorite = req.favorite;
        view.reprompt = (_c = req.reprompt) !== null && _c !== void 0 ? _c : CipherRepromptType.None;
        if (req.fields != null) {
            view.fields = req.fields.map((f) => FieldExport.toView(f));
        }
        switch (req.type) {
            case CipherType.Login:
                view.login = LoginExport.toView(req.login);
                break;
            case CipherType.SecureNote:
                view.secureNote = SecureNoteExport.toView(req.secureNote);
                break;
            case CipherType.Card:
                view.card = CardExport.toView(req.card);
                break;
            case CipherType.Identity:
                view.identity = IdentityExport.toView(req.identity);
                break;
        }
        return view;
    }
    static toDomain(req, domain = new Cipher()) {
        var _a;
        domain.type = req.type;
        domain.folderId = req.folderId;
        if (domain.organizationId == null) {
            domain.organizationId = req.organizationId;
        }
        domain.name = req.name != null ? new EncString(req.name) : null;
        domain.notes = req.notes != null ? new EncString(req.notes) : null;
        domain.favorite = req.favorite;
        domain.reprompt = (_a = req.reprompt) !== null && _a !== void 0 ? _a : CipherRepromptType.None;
        if (req.fields != null) {
            domain.fields = req.fields.map((f) => FieldExport.toDomain(f));
        }
        switch (req.type) {
            case CipherType.Login:
                domain.login = LoginExport.toDomain(req.login);
                break;
            case CipherType.SecureNote:
                domain.secureNote = SecureNoteExport.toDomain(req.secureNote);
                break;
            case CipherType.Card:
                domain.card = CardExport.toDomain(req.card);
                break;
            case CipherType.Identity:
                domain.identity = IdentityExport.toDomain(req.identity);
                break;
        }
        return domain;
    }
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        var _a, _b;
        this.organizationId = o.organizationId;
        this.folderId = o.folderId;
        this.type = o.type;
        this.reprompt = o.reprompt;
        if (o instanceof CipherView) {
            this.name = o.name;
            this.notes = o.notes;
        }
        else {
            this.name = (_a = o.name) === null || _a === void 0 ? void 0 : _a.encryptedString;
            this.notes = (_b = o.notes) === null || _b === void 0 ? void 0 : _b.encryptedString;
        }
        this.favorite = o.favorite;
        if (o.fields != null) {
            if (o instanceof CipherView) {
                this.fields = o.fields.map((f) => new FieldExport(f));
            }
            else {
                this.fields = o.fields.map((f) => new FieldExport(f));
            }
        }
        switch (o.type) {
            case CipherType.Login:
                this.login = new LoginExport(o.login);
                break;
            case CipherType.SecureNote:
                this.secureNote = new SecureNoteExport(o.secureNote);
                break;
            case CipherType.Card:
                this.card = new CardExport(o.card);
                break;
            case CipherType.Identity:
                this.identity = new IdentityExport(o.identity);
                break;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/cipher-with-ids.export.ts

class CipherWithIdExport extends CipherExport {
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        this.id = o.id;
        super.build(o);
        this.collectionIds = o.collectionIds;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/collection.export.ts



class CollectionExport {
    static template() {
        const req = new CollectionExport();
        req.organizationId = "00000000-0000-0000-0000-000000000000";
        req.name = "Collection name";
        req.externalId = null;
        return req;
    }
    static toView(req, view = new CollectionView()) {
        view.name = req.name;
        view.externalId = req.externalId;
        if (view.organizationId == null) {
            view.organizationId = req.organizationId;
        }
        return view;
    }
    static toDomain(req, domain = new Collection()) {
        domain.name = req.name != null ? new EncString(req.name) : null;
        domain.externalId = req.externalId;
        if (domain.organizationId == null) {
            domain.organizationId = req.organizationId;
        }
        return domain;
    }
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        var _a;
        this.organizationId = o.organizationId;
        if (o instanceof CollectionView) {
            this.name = o.name;
        }
        else {
            this.name = (_a = o.name) === null || _a === void 0 ? void 0 : _a.encryptedString;
        }
        this.externalId = o.externalId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/collection-with-id.export.ts

class CollectionWithIdExport extends CollectionExport {
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        this.id = o.id;
        super.build(o);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/eventType.ts
var EventType;
(function (EventType) {
    EventType[EventType["User_LoggedIn"] = 1000] = "User_LoggedIn";
    EventType[EventType["User_ChangedPassword"] = 1001] = "User_ChangedPassword";
    EventType[EventType["User_Updated2fa"] = 1002] = "User_Updated2fa";
    EventType[EventType["User_Disabled2fa"] = 1003] = "User_Disabled2fa";
    EventType[EventType["User_Recovered2fa"] = 1004] = "User_Recovered2fa";
    EventType[EventType["User_FailedLogIn"] = 1005] = "User_FailedLogIn";
    EventType[EventType["User_FailedLogIn2fa"] = 1006] = "User_FailedLogIn2fa";
    EventType[EventType["User_ClientExportedVault"] = 1007] = "User_ClientExportedVault";
    EventType[EventType["User_UpdatedTempPassword"] = 1008] = "User_UpdatedTempPassword";
    EventType[EventType["User_MigratedKeyToKeyConnector"] = 1009] = "User_MigratedKeyToKeyConnector";
    EventType[EventType["Cipher_Created"] = 1100] = "Cipher_Created";
    EventType[EventType["Cipher_Updated"] = 1101] = "Cipher_Updated";
    EventType[EventType["Cipher_Deleted"] = 1102] = "Cipher_Deleted";
    EventType[EventType["Cipher_AttachmentCreated"] = 1103] = "Cipher_AttachmentCreated";
    EventType[EventType["Cipher_AttachmentDeleted"] = 1104] = "Cipher_AttachmentDeleted";
    EventType[EventType["Cipher_Shared"] = 1105] = "Cipher_Shared";
    EventType[EventType["Cipher_UpdatedCollections"] = 1106] = "Cipher_UpdatedCollections";
    EventType[EventType["Cipher_ClientViewed"] = 1107] = "Cipher_ClientViewed";
    EventType[EventType["Cipher_ClientToggledPasswordVisible"] = 1108] = "Cipher_ClientToggledPasswordVisible";
    EventType[EventType["Cipher_ClientToggledHiddenFieldVisible"] = 1109] = "Cipher_ClientToggledHiddenFieldVisible";
    EventType[EventType["Cipher_ClientToggledCardCodeVisible"] = 1110] = "Cipher_ClientToggledCardCodeVisible";
    EventType[EventType["Cipher_ClientCopiedPassword"] = 1111] = "Cipher_ClientCopiedPassword";
    EventType[EventType["Cipher_ClientCopiedHiddenField"] = 1112] = "Cipher_ClientCopiedHiddenField";
    EventType[EventType["Cipher_ClientCopiedCardCode"] = 1113] = "Cipher_ClientCopiedCardCode";
    EventType[EventType["Cipher_ClientAutofilled"] = 1114] = "Cipher_ClientAutofilled";
    EventType[EventType["Cipher_SoftDeleted"] = 1115] = "Cipher_SoftDeleted";
    EventType[EventType["Cipher_Restored"] = 1116] = "Cipher_Restored";
    EventType[EventType["Cipher_ClientToggledCardNumberVisible"] = 1117] = "Cipher_ClientToggledCardNumberVisible";
    EventType[EventType["Collection_Created"] = 1300] = "Collection_Created";
    EventType[EventType["Collection_Updated"] = 1301] = "Collection_Updated";
    EventType[EventType["Collection_Deleted"] = 1302] = "Collection_Deleted";
    EventType[EventType["Group_Created"] = 1400] = "Group_Created";
    EventType[EventType["Group_Updated"] = 1401] = "Group_Updated";
    EventType[EventType["Group_Deleted"] = 1402] = "Group_Deleted";
    EventType[EventType["OrganizationUser_Invited"] = 1500] = "OrganizationUser_Invited";
    EventType[EventType["OrganizationUser_Confirmed"] = 1501] = "OrganizationUser_Confirmed";
    EventType[EventType["OrganizationUser_Updated"] = 1502] = "OrganizationUser_Updated";
    EventType[EventType["OrganizationUser_Removed"] = 1503] = "OrganizationUser_Removed";
    EventType[EventType["OrganizationUser_UpdatedGroups"] = 1504] = "OrganizationUser_UpdatedGroups";
    EventType[EventType["OrganizationUser_UnlinkedSso"] = 1505] = "OrganizationUser_UnlinkedSso";
    EventType[EventType["OrganizationUser_ResetPassword_Enroll"] = 1506] = "OrganizationUser_ResetPassword_Enroll";
    EventType[EventType["OrganizationUser_ResetPassword_Withdraw"] = 1507] = "OrganizationUser_ResetPassword_Withdraw";
    EventType[EventType["OrganizationUser_AdminResetPassword"] = 1508] = "OrganizationUser_AdminResetPassword";
    EventType[EventType["OrganizationUser_ResetSsoLink"] = 1509] = "OrganizationUser_ResetSsoLink";
    EventType[EventType["OrganizationUser_FirstSsoLogin"] = 1510] = "OrganizationUser_FirstSsoLogin";
    EventType[EventType["OrganizationUser_Revoked"] = 1511] = "OrganizationUser_Revoked";
    EventType[EventType["OrganizationUser_Restored"] = 1512] = "OrganizationUser_Restored";
    EventType[EventType["Organization_Updated"] = 1600] = "Organization_Updated";
    EventType[EventType["Organization_PurgedVault"] = 1601] = "Organization_PurgedVault";
    EventType[EventType["Organization_ClientExportedVault"] = 1602] = "Organization_ClientExportedVault";
    EventType[EventType["Organization_VaultAccessed"] = 1603] = "Organization_VaultAccessed";
    EventType[EventType["Organization_EnabledSso"] = 1604] = "Organization_EnabledSso";
    EventType[EventType["Organization_DisabledSso"] = 1605] = "Organization_DisabledSso";
    EventType[EventType["Organization_EnabledKeyConnector"] = 1606] = "Organization_EnabledKeyConnector";
    EventType[EventType["Organization_DisabledKeyConnector"] = 1607] = "Organization_DisabledKeyConnector";
    EventType[EventType["Organization_SponsorshipsSynced"] = 1608] = "Organization_SponsorshipsSynced";
    EventType[EventType["Policy_Updated"] = 1700] = "Policy_Updated";
    EventType[EventType["ProviderUser_Invited"] = 1800] = "ProviderUser_Invited";
    EventType[EventType["ProviderUser_Confirmed"] = 1801] = "ProviderUser_Confirmed";
    EventType[EventType["ProviderUser_Updated"] = 1802] = "ProviderUser_Updated";
    EventType[EventType["ProviderUser_Removed"] = 1803] = "ProviderUser_Removed";
    EventType[EventType["ProviderOrganization_Created"] = 1900] = "ProviderOrganization_Created";
    EventType[EventType["ProviderOrganization_Added"] = 1901] = "ProviderOrganization_Added";
    EventType[EventType["ProviderOrganization_Removed"] = 1902] = "ProviderOrganization_Removed";
    EventType[EventType["ProviderOrganization_VaultAccessed"] = 1903] = "ProviderOrganization_VaultAccessed";
})(EventType || (EventType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/export/event.export.ts

class EventExport {
    constructor(event) {
        this.message = event.humanReadableMessage;
        this.appIcon = event.appIcon;
        this.appName = event.appName;
        this.userId = event.userId;
        this.userName = event.userName;
        this.userEmail = event.userEmail;
        this.date = event.date;
        this.ip = event.ip;
        this.type = EventType[event.type];
        this.installationId = event.installationId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/view/folder.view.ts
class FolderView {
    constructor(f) {
        this.id = null;
        this.name = null;
        this.revisionDate = null;
        if (!f) {
            return;
        }
        this.id = f.id;
        this.revisionDate = f.revisionDate;
    }
    static fromJSON(obj) {
        const revisionDate = obj.revisionDate == null ? null : new Date(obj.revisionDate);
        return Object.assign(new FolderView(), obj, { revisionDate });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/folder.ts



class Folder extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            id: null,
            name: null,
        }, ["id"]);
        this.revisionDate = obj.revisionDate != null ? new Date(obj.revisionDate) : null;
    }
    decrypt() {
        return this.decryptObj(new FolderView(this), {
            name: null,
        }, null);
    }
    static fromJSON(obj) {
        const revisionDate = obj.revisionDate == null ? null : new Date(obj.revisionDate);
        return Object.assign(new Folder(), obj, { name: EncString.fromJSON(obj.name), revisionDate });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/folder.export.ts



class FolderExport {
    static template() {
        const req = new FolderExport();
        req.name = "Folder name";
        return req;
    }
    static toView(req, view = new FolderView()) {
        view.name = req.name;
        return view;
    }
    static toDomain(req, domain = new Folder()) {
        domain.name = req.name != null ? new EncString(req.name) : null;
        return domain;
    }
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        var _a;
        if (o instanceof FolderView) {
            this.name = o.name;
        }
        else {
            this.name = (_a = o.name) === null || _a === void 0 ? void 0 : _a.encryptedString;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/export/folder-with-id.export.ts

class FolderWithIdExport extends FolderExport {
    // Use build method instead of ctor so that we can control order of JSON stringify for pretty print
    build(o) {
        this.id = o.id;
        super.build(o);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/export.service.ts
var export_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};













class ExportService {
    constructor(folderService, cipherService, apiService, cryptoService, cryptoFunctionService) {
        this.folderService = folderService;
        this.cipherService = cipherService;
        this.apiService = apiService;
        this.cryptoService = cryptoService;
        this.cryptoFunctionService = cryptoFunctionService;
    }
    getExport(format = "csv", organizationId) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            if (organizationId) {
                return yield this.getOrganizationExport(organizationId, format);
            }
            if (format === "encrypted_json") {
                return this.getEncryptedExport();
            }
            else {
                return this.getDecryptedExport(format);
            }
        });
    }
    getPasswordProtectedExport(password, organizationId) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            const clearText = organizationId
                ? yield this.getOrganizationExport(organizationId, "json")
                : yield this.getExport("json");
            const salt = Utils.fromBufferToB64(yield this.cryptoFunctionService.randomBytes(16));
            const kdfConfig = new KdfConfig(DEFAULT_PBKDF2_ITERATIONS);
            const key = yield this.cryptoService.makePinKey(password, salt, KdfType.PBKDF2_SHA256, kdfConfig);
            const encKeyValidation = yield this.cryptoService.encrypt(Utils.newGuid(), key);
            const encText = yield this.cryptoService.encrypt(clearText, key);
            const jsonDoc = {
                encrypted: true,
                passwordProtected: true,
                salt: salt,
                kdfIterations: kdfConfig.iterations,
                kdfType: KdfType.PBKDF2_SHA256,
                encKeyValidation_DO_NOT_EDIT: encKeyValidation.encryptedString,
                data: encText.encryptedString,
            };
            return JSON.stringify(jsonDoc, null, "  ");
        });
    }
    getOrganizationExport(organizationId, format = "csv") {
        return export_service_awaiter(this, void 0, void 0, function* () {
            if (format === "encrypted_json") {
                return this.getOrganizationEncryptedExport(organizationId);
            }
            else {
                return this.getOrganizationDecryptedExport(organizationId, format);
            }
        });
    }
    getEventExport(events) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            return external_papaparse_namespaceObject.unparse(events.map((e) => new EventExport(e)));
        });
    }
    getFileName(prefix = null, extension = "csv") {
        const now = new Date();
        const dateString = now.getFullYear() +
            "" +
            this.padNumber(now.getMonth() + 1, 2) +
            "" +
            this.padNumber(now.getDate(), 2) +
            this.padNumber(now.getHours(), 2) +
            "" +
            this.padNumber(now.getMinutes(), 2) +
            this.padNumber(now.getSeconds(), 2);
        return "bitwarden" + (prefix ? "_" + prefix : "") + "_export_" + dateString + "." + extension;
    }
    getDecryptedExport(format) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            let decFolders = [];
            let decCiphers = [];
            const promises = [];
            promises.push(this.folderService.getAllDecryptedFromState().then((folders) => {
                decFolders = folders;
            }));
            promises.push(this.cipherService.getAllDecrypted().then((ciphers) => {
                decCiphers = ciphers.filter((f) => f.deletedDate == null);
            }));
            yield Promise.all(promises);
            if (format === "csv") {
                const foldersMap = new Map();
                decFolders.forEach((f) => {
                    if (f.id != null) {
                        foldersMap.set(f.id, f);
                    }
                });
                const exportCiphers = [];
                decCiphers.forEach((c) => {
                    // only export logins and secure notes
                    if (c.type !== CipherType.Login && c.type !== CipherType.SecureNote) {
                        return;
                    }
                    if (c.organizationId != null) {
                        return;
                    }
                    const cipher = {};
                    cipher.folder =
                        c.folderId != null && foldersMap.has(c.folderId) ? foldersMap.get(c.folderId).name : null;
                    cipher.favorite = c.favorite ? 1 : null;
                    this.buildCommonCipher(cipher, c);
                    exportCiphers.push(cipher);
                });
                return external_papaparse_namespaceObject.unparse(exportCiphers);
            }
            else {
                const jsonDoc = {
                    encrypted: false,
                    folders: [],
                    items: [],
                };
                decFolders.forEach((f) => {
                    if (f.id == null) {
                        return;
                    }
                    const folder = new FolderWithIdExport();
                    folder.build(f);
                    jsonDoc.folders.push(folder);
                });
                decCiphers.forEach((c) => {
                    if (c.organizationId != null) {
                        return;
                    }
                    const cipher = new CipherWithIdExport();
                    cipher.build(c);
                    cipher.collectionIds = null;
                    jsonDoc.items.push(cipher);
                });
                return JSON.stringify(jsonDoc, null, "  ");
            }
        });
    }
    getEncryptedExport() {
        return export_service_awaiter(this, void 0, void 0, function* () {
            let folders = [];
            let ciphers = [];
            const promises = [];
            promises.push(this.folderService.getAllFromState().then((f) => {
                folders = f;
            }));
            promises.push(this.cipherService.getAll().then((c) => {
                ciphers = c.filter((f) => f.deletedDate == null);
            }));
            yield Promise.all(promises);
            const encKeyValidation = yield this.cryptoService.encrypt(Utils.newGuid());
            const jsonDoc = {
                encrypted: true,
                encKeyValidation_DO_NOT_EDIT: encKeyValidation.encryptedString,
                folders: [],
                items: [],
            };
            folders.forEach((f) => {
                if (f.id == null) {
                    return;
                }
                const folder = new FolderWithIdExport();
                folder.build(f);
                jsonDoc.folders.push(folder);
            });
            ciphers.forEach((c) => {
                if (c.organizationId != null) {
                    return;
                }
                const cipher = new CipherWithIdExport();
                cipher.build(c);
                cipher.collectionIds = null;
                jsonDoc.items.push(cipher);
            });
            return JSON.stringify(jsonDoc, null, "  ");
        });
    }
    getOrganizationDecryptedExport(organizationId, format) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            const decCollections = [];
            const decCiphers = [];
            const promises = [];
            promises.push(this.apiService.getOrganizationExport(organizationId).then((exportData) => {
                const exportPromises = [];
                if (exportData != null) {
                    if (exportData.collections != null && exportData.collections.length > 0) {
                        exportData.collections.forEach((c) => {
                            const collection = new Collection(new CollectionData(c));
                            exportPromises.push(collection.decrypt().then((decCol) => {
                                decCollections.push(decCol);
                            }));
                        });
                    }
                    if (exportData.ciphers != null && exportData.ciphers.length > 0) {
                        exportData.ciphers
                            .filter((c) => c.deletedDate === null)
                            .forEach((c) => {
                            const cipher = new Cipher(new CipherData(c));
                            exportPromises.push(cipher.decrypt().then((decCipher) => {
                                decCiphers.push(decCipher);
                            }));
                        });
                    }
                }
                return Promise.all(exportPromises);
            }));
            yield Promise.all(promises);
            if (format === "csv") {
                const collectionsMap = new Map();
                decCollections.forEach((c) => {
                    collectionsMap.set(c.id, c);
                });
                const exportCiphers = [];
                decCiphers.forEach((c) => {
                    // only export logins and secure notes
                    if (c.type !== CipherType.Login && c.type !== CipherType.SecureNote) {
                        return;
                    }
                    const cipher = {};
                    cipher.collections = [];
                    if (c.collectionIds != null) {
                        cipher.collections = c.collectionIds
                            .filter((id) => collectionsMap.has(id))
                            .map((id) => collectionsMap.get(id).name);
                    }
                    this.buildCommonCipher(cipher, c);
                    exportCiphers.push(cipher);
                });
                return external_papaparse_namespaceObject.unparse(exportCiphers);
            }
            else {
                const jsonDoc = {
                    encrypted: false,
                    collections: [],
                    items: [],
                };
                decCollections.forEach((c) => {
                    const collection = new CollectionWithIdExport();
                    collection.build(c);
                    jsonDoc.collections.push(collection);
                });
                decCiphers.forEach((c) => {
                    const cipher = new CipherWithIdExport();
                    cipher.build(c);
                    jsonDoc.items.push(cipher);
                });
                return JSON.stringify(jsonDoc, null, "  ");
            }
        });
    }
    getOrganizationEncryptedExport(organizationId) {
        return export_service_awaiter(this, void 0, void 0, function* () {
            const collections = [];
            const ciphers = [];
            const promises = [];
            promises.push(this.apiService.getCollections(organizationId).then((c) => {
                const collectionPromises = [];
                if (c != null && c.data != null && c.data.length > 0) {
                    c.data.forEach((r) => {
                        const collection = new Collection(new CollectionData(r));
                        collections.push(collection);
                    });
                }
                return Promise.all(collectionPromises);
            }));
            promises.push(this.apiService.getCiphersOrganization(organizationId).then((c) => {
                const cipherPromises = [];
                if (c != null && c.data != null && c.data.length > 0) {
                    c.data
                        .filter((item) => item.deletedDate === null)
                        .forEach((item) => {
                        const cipher = new Cipher(new CipherData(item));
                        ciphers.push(cipher);
                    });
                }
                return Promise.all(cipherPromises);
            }));
            yield Promise.all(promises);
            const orgKey = yield this.cryptoService.getOrgKey(organizationId);
            const encKeyValidation = yield this.cryptoService.encrypt(Utils.newGuid(), orgKey);
            const jsonDoc = {
                encrypted: true,
                encKeyValidation_DO_NOT_EDIT: encKeyValidation.encryptedString,
                collections: [],
                items: [],
            };
            collections.forEach((c) => {
                const collection = new CollectionWithIdExport();
                collection.build(c);
                jsonDoc.collections.push(collection);
            });
            ciphers.forEach((c) => {
                const cipher = new CipherWithIdExport();
                cipher.build(c);
                jsonDoc.items.push(cipher);
            });
            return JSON.stringify(jsonDoc, null, "  ");
        });
    }
    padNumber(num, width, padCharacter = "0") {
        const numString = num.toString();
        return numString.length >= width
            ? numString
            : new Array(width - numString.length + 1).join(padCharacter) + numString;
    }
    buildCommonCipher(cipher, c) {
        cipher.type = null;
        cipher.name = c.name;
        cipher.notes = c.notes;
        cipher.fields = null;
        cipher.reprompt = c.reprompt;
        // Login props
        cipher.login_uri = null;
        cipher.login_username = null;
        cipher.login_password = null;
        cipher.login_totp = null;
        if (c.fields) {
            c.fields.forEach((f) => {
                if (!cipher.fields) {
                    cipher.fields = "";
                }
                else {
                    cipher.fields += "\n";
                }
                cipher.fields += (f.name || "") + ": " + f.value;
            });
        }
        switch (c.type) {
            case CipherType.Login:
                cipher.type = "login";
                cipher.login_username = c.login.username;
                cipher.login_password = c.login.password;
                cipher.login_totp = c.login.totp;
                if (c.login.uris) {
                    cipher.login_uri = [];
                    c.login.uris.forEach((u) => {
                        cipher.login_uri.push(u.uri);
                    });
                }
                break;
            case CipherType.SecureNote:
                cipher.type = "note";
                break;
            default:
                return;
        }
        return cipher;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/fileUploadType.ts
var FileUploadType;
(function (FileUploadType) {
    FileUploadType[FileUploadType["Direct"] = 0] = "Direct";
    FileUploadType[FileUploadType["Azure"] = 1] = "Azure";
})(FileUploadType || (FileUploadType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/services/azureFileUpload.service.ts
var azureFileUpload_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

const MAX_SINGLE_BLOB_UPLOAD_SIZE = 256 * 1024 * 1024; // 256 MiB
const MAX_BLOCKS_PER_BLOB = 50000;
class AzureFileUploadService {
    constructor(logService) {
        this.logService = logService;
    }
    upload(url, data, renewalCallback) {
        return azureFileUpload_service_awaiter(this, void 0, void 0, function* () {
            if (data.buffer.byteLength <= MAX_SINGLE_BLOB_UPLOAD_SIZE) {
                return yield this.azureUploadBlob(url, data);
            }
            else {
                return yield this.azureUploadBlocks(url, data, renewalCallback);
            }
        });
    }
    azureUploadBlob(url, data) {
        return azureFileUpload_service_awaiter(this, void 0, void 0, function* () {
            const urlObject = Utils.getUrl(url);
            const headers = new Headers({
                "x-ms-date": new Date().toUTCString(),
                "x-ms-version": urlObject.searchParams.get("sv"),
                "Content-Length": data.buffer.byteLength.toString(),
                "x-ms-blob-type": "BlockBlob",
            });
            const request = new Request(url, {
                body: data.buffer,
                cache: "no-store",
                method: "PUT",
                headers: headers,
            });
            const blobResponse = yield fetch(request);
            if (blobResponse.status !== 201) {
                throw new Error(`Failed to create Azure blob: ${blobResponse.status}`);
            }
        });
    }
    azureUploadBlocks(url, data, renewalCallback) {
        return azureFileUpload_service_awaiter(this, void 0, void 0, function* () {
            const baseUrl = Utils.getUrl(url);
            const blockSize = this.getMaxBlockSize(baseUrl.searchParams.get("sv"));
            let blockIndex = 0;
            const numBlocks = Math.ceil(data.buffer.byteLength / blockSize);
            const blocksStaged = [];
            if (numBlocks > MAX_BLOCKS_PER_BLOB) {
                throw new Error(`Cannot upload file, exceeds maximum size of ${blockSize * MAX_BLOCKS_PER_BLOB}`);
            }
            // eslint-disable-next-line
            try {
                while (blockIndex < numBlocks) {
                    url = yield this.renewUrlIfNecessary(url, renewalCallback);
                    const blockUrl = Utils.getUrl(url);
                    const blockId = this.encodedBlockId(blockIndex);
                    blockUrl.searchParams.append("comp", "block");
                    blockUrl.searchParams.append("blockid", blockId);
                    const start = blockIndex * blockSize;
                    const blockData = data.buffer.slice(start, start + blockSize);
                    const blockHeaders = new Headers({
                        "x-ms-date": new Date().toUTCString(),
                        "x-ms-version": blockUrl.searchParams.get("sv"),
                        "Content-Length": blockData.byteLength.toString(),
                    });
                    const blockRequest = new Request(blockUrl.toString(), {
                        body: blockData,
                        cache: "no-store",
                        method: "PUT",
                        headers: blockHeaders,
                    });
                    const blockResponse = yield fetch(blockRequest);
                    if (blockResponse.status !== 201) {
                        const message = `Unsuccessful block PUT. Received status ${blockResponse.status}`;
                        this.logService.error(message + "\n" + (yield blockResponse.json()));
                        throw new Error(message);
                    }
                    blocksStaged.push(blockId);
                    blockIndex++;
                }
                url = yield this.renewUrlIfNecessary(url, renewalCallback);
                const blockListUrl = Utils.getUrl(url);
                const blockListXml = this.blockListXml(blocksStaged);
                blockListUrl.searchParams.append("comp", "blocklist");
                const headers = new Headers({
                    "x-ms-date": new Date().toUTCString(),
                    "x-ms-version": blockListUrl.searchParams.get("sv"),
                    "Content-Length": blockListXml.length.toString(),
                });
                const request = new Request(blockListUrl.toString(), {
                    body: blockListXml,
                    cache: "no-store",
                    method: "PUT",
                    headers: headers,
                });
                const response = yield fetch(request);
                if (response.status !== 201) {
                    const message = `Unsuccessful block list PUT. Received status ${response.status}`;
                    this.logService.error(message + "\n" + (yield response.json()));
                    throw new Error(message);
                }
            }
            catch (e) {
                throw e;
            }
        });
    }
    renewUrlIfNecessary(url, renewalCallback) {
        var _a;
        return azureFileUpload_service_awaiter(this, void 0, void 0, function* () {
            const urlObject = Utils.getUrl(url);
            const expiry = new Date((_a = urlObject.searchParams.get("se")) !== null && _a !== void 0 ? _a : "");
            if (isNaN(expiry.getTime())) {
                expiry.setTime(Date.now() + 3600000);
            }
            if (expiry.getTime() < Date.now() + 1000) {
                return yield renewalCallback();
            }
            return url;
        });
    }
    encodedBlockId(blockIndex) {
        // Encoded blockId max size is 64, so pre-encoding max size is 48
        const utfBlockId = ("000000000000000000000000000000000000000000000000" + blockIndex.toString()).slice(-48);
        return Utils.fromUtf8ToB64(utfBlockId);
    }
    blockListXml(blockIdList) {
        let xml = '<?xml version="1.0" encoding="utf-8"?><BlockList>';
        blockIdList.forEach((blockId) => {
            xml += `<Latest>${blockId}</Latest>`;
        });
        xml += "</BlockList>";
        return xml;
    }
    getMaxBlockSize(version) {
        if (Version.compare(version, "2019-12-12") >= 0) {
            return 4000 * 1024 * 1024; // 4000 MiB
        }
        else if (Version.compare(version, "2016-05-31") >= 0) {
            return 100 * 1024 * 1024; // 100 MiB
        }
        else {
            return 4 * 1024 * 1024; // 4 MiB
        }
    }
}
class Version {
    constructor(version) {
        this.year = 0;
        this.month = 0;
        this.day = 0;
        try {
            const parts = version.split("-").map((v) => Number.parseInt(v, 10));
            this.year = parts[0];
            this.month = parts[1];
            this.day = parts[2];
        }
        catch (_a) {
            // Ignore error
        }
    }
    /**
     * Compares two Azure Versions against each other
     * @param a Version to compare
     * @param b Version to compare
     * @returns a number less than zero if b is newer than a, 0 if equal,
     * and greater than zero if a is newer than b
     */
    static compare(a, b) {
        if (typeof a === "string") {
            a = new Version(a);
        }
        if (typeof b === "string") {
            b = new Version(b);
        }
        return a.year !== b.year
            ? a.year - b.year
            : a.month !== b.month
                ? a.month - b.month
                : a.day !== b.day
                    ? a.day - b.day
                    : 0;
    }
    /**
     * Compares two Azure Versions against each other
     * @param compareTo Version to compare against
     * @returns a number less than zero if compareTo is newer, 0 if equal,
     * and greater than zero if this is greater than compareTo
     */
    compare(compareTo) {
        return Version.compare(this, compareTo);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/bitwardenFileUpload.service.ts
var bitwardenFileUpload_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class BitwardenFileUploadService {
    upload(encryptedFileName, encryptedFileData, apiCall) {
        return bitwardenFileUpload_service_awaiter(this, void 0, void 0, function* () {
            const fd = new FormData();
            try {
                const blob = new Blob([encryptedFileData.buffer], { type: "application/octet-stream" });
                fd.append("data", blob, encryptedFileName);
            }
            catch (e) {
                if (Utils.isNode && !Utils.isBrowser) {
                    fd.append("data", Buffer.from(encryptedFileData.buffer), {
                        filepath: encryptedFileName,
                        contentType: "application/octet-stream",
                    });
                }
                else {
                    throw e;
                }
            }
            yield apiCall(fd);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/fileUpload.service.ts
var fileUpload_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class FileUploadService {
    constructor(logService, apiService) {
        this.logService = logService;
        this.apiService = apiService;
        this.azureFileUploadService = new AzureFileUploadService(logService);
        this.bitwardenFileUploadService = new BitwardenFileUploadService();
    }
    uploadSendFile(uploadData, fileName, encryptedFileData) {
        return fileUpload_service_awaiter(this, void 0, void 0, function* () {
            try {
                switch (uploadData.fileUploadType) {
                    case FileUploadType.Direct:
                        yield this.bitwardenFileUploadService.upload(fileName.encryptedString, encryptedFileData, (fd) => this.apiService.postSendFile(uploadData.sendResponse.id, uploadData.sendResponse.file.id, fd));
                        break;
                    case FileUploadType.Azure: {
                        const renewalCallback = () => fileUpload_service_awaiter(this, void 0, void 0, function* () {
                            const renewalResponse = yield this.apiService.renewSendFileUploadUrl(uploadData.sendResponse.id, uploadData.sendResponse.file.id);
                            return renewalResponse.url;
                        });
                        yield this.azureFileUploadService.upload(uploadData.url, encryptedFileData, renewalCallback);
                        break;
                    }
                    default:
                        throw new Error("Unknown file upload type");
                }
            }
            catch (e) {
                yield this.apiService.deleteSend(uploadData.sendResponse.id);
                throw e;
            }
        });
    }
    uploadCipherAttachment(admin, uploadData, encryptedFileName, encryptedFileData) {
        return fileUpload_service_awaiter(this, void 0, void 0, function* () {
            const response = admin ? uploadData.cipherMiniResponse : uploadData.cipherResponse;
            try {
                switch (uploadData.fileUploadType) {
                    case FileUploadType.Direct:
                        yield this.bitwardenFileUploadService.upload(encryptedFileName.encryptedString, encryptedFileData, (fd) => this.apiService.postAttachmentFile(response.id, uploadData.attachmentId, fd));
                        break;
                    case FileUploadType.Azure: {
                        const renewalCallback = () => fileUpload_service_awaiter(this, void 0, void 0, function* () {
                            const renewalResponse = yield this.apiService.renewAttachmentUploadUrl(response.id, uploadData.attachmentId);
                            return renewalResponse.url;
                        });
                        yield this.azureFileUploadService.upload(uploadData.url, encryptedFileData, renewalCallback);
                        break;
                    }
                    default:
                        throw new Error("Unknown file upload type.");
                }
            }
            catch (e) {
                if (admin) {
                    yield this.apiService.deleteCipherAttachmentAdmin(response.id, uploadData.attachmentId);
                }
                else {
                    yield this.apiService.deleteCipherAttachment(response.id, uploadData.attachmentId);
                }
                throw e;
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/import/import-api.service.ts
var import_api_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class ImportApiService {
    constructor(apiService) {
        this.apiService = apiService;
    }
    postImportCiphers(request) {
        return import_api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.apiService.send("POST", "/ciphers/import", request, true, false);
        });
    }
    postImportOrganizationCiphers(organizationId, request) {
        return import_api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.apiService.send("POST", "/ciphers/import-organization?organizationId=" + organizationId, request, true, false);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/importOptions.ts
const featuredImportOptions = [
    { id: "bitwardenjson", name: "Bitwarden (json)" },
    { id: "bitwardencsv", name: "Bitwarden (csv)" },
    { id: "chromecsv", name: "Chrome (csv)" },
    { id: "dashlanecsv", name: "Dashlane (csv)" },
    { id: "firefoxcsv", name: "Firefox (csv)" },
    { id: "keepass2xml", name: "KeePass 2 (xml)" },
    { id: "lastpasscsv", name: "LastPass (csv)" },
    { id: "safaricsv", name: "Safari and macOS (csv)" },
    { id: "1password1pux", name: "1Password (1pux)" },
];
const regularImportOptions = [
    { id: "keepassxcsv", name: "KeePassX (csv)" },
    { id: "1password1pif", name: "1Password (1pif)" },
    { id: "1passwordwincsv", name: "1Password 6 and 7 Windows (csv)" },
    { id: "1passwordmaccsv", name: "1Password 6 and 7 Mac (csv)" },
    { id: "dashlanejson", name: "Dashlane (json)" },
    { id: "roboformcsv", name: "RoboForm (csv)" },
    { id: "keepercsv", name: "Keeper (csv)" },
    // Temporarily remove this option for the Feb release
    // { id: "keeperjson", name: "Keeper (json)" },
    { id: "enpasscsv", name: "Enpass (csv)" },
    { id: "enpassjson", name: "Enpass (json)" },
    { id: "safeincloudxml", name: "SafeInCloud (xml)" },
    { id: "pwsafexml", name: "Password Safe (xml)" },
    { id: "stickypasswordxml", name: "Sticky Password (xml)" },
    { id: "msecurecsv", name: "mSecure (csv)" },
    { id: "truekeycsv", name: "True Key (csv)" },
    { id: "passwordbossjson", name: "Password Boss (json)" },
    { id: "zohovaultcsv", name: "Zoho Vault (csv)" },
    { id: "splashidcsv", name: "SplashID (csv)" },
    { id: "passworddragonxml", name: "Password Dragon (xml)" },
    { id: "padlockcsv", name: "Padlock (csv)" },
    { id: "passboltcsv", name: "Passbolt (csv)" },
    { id: "clipperzhtml", name: "Clipperz (html)" },
    { id: "aviracsv", name: "Avira (csv)" },
    { id: "saferpasscsv", name: "SaferPass (csv)" },
    { id: "upmcsv", name: "Universal Password Manager (csv)" },
    { id: "ascendocsv", name: "Ascendo DataVault (csv)" },
    { id: "meldiumcsv", name: "Meldium (csv)" },
    { id: "passkeepcsv", name: "PassKeep (csv)" },
    { id: "operacsv", name: "Opera (csv)" },
    { id: "vivaldicsv", name: "Vivaldi (csv)" },
    { id: "gnomejson", name: "GNOME Passwords and Keys/Seahorse (json)" },
    { id: "blurcsv", name: "Blur (csv)" },
    { id: "passwordagentcsv", name: "Password Agent (csv)" },
    { id: "passpackcsv", name: "Passpack (csv)" },
    { id: "passmanjson", name: "Passman (json)" },
    { id: "avastcsv", name: "Avast Passwords (csv)" },
    { id: "avastjson", name: "Avast Passwords (json)" },
    { id: "fsecurefsk", name: "F-Secure KEY (fsk)" },
    { id: "kasperskytxt", name: "Kaspersky Password Manager (txt)" },
    { id: "remembearcsv", name: "RememBear (csv)" },
    { id: "passwordwallettxt", name: "PasswordWallet (txt)" },
    { id: "mykicsv", name: "Myki (csv)" },
    { id: "securesafecsv", name: "SecureSafe (csv)" },
    { id: "logmeoncecsv", name: "LogMeOnce (csv)" },
    { id: "blackberrycsv", name: "BlackBerry Password Keeper (csv)" },
    { id: "buttercupcsv", name: "Buttercup (csv)" },
    { id: "codebookcsv", name: "Codebook (csv)" },
    { id: "encryptrcsv", name: "Encryptr (csv)" },
    { id: "yoticsv", name: "Yoti (csv)" },
    { id: "nordpasscsv", name: "Nordpass (csv)" },
    { id: "psonojson", name: "Psono (json)" },
    { id: "passkyjson", name: "Passky (json)" },
];

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/import-result.ts
class ImportResult {
    constructor() {
        this.success = false;
        this.missingPassword = false;
        this.ciphers = [];
        this.folders = [];
        this.folderRelationships = [];
        this.collections = [];
        this.collectionRelationships = [];
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/consoleLog.service.ts

class consoleLog_service_ConsoleLogService {
    constructor(isDev, filter = null) {
        this.isDev = isDev;
        this.filter = filter;
        this.timersMap = new Map();
    }
    debug(message) {
        if (!this.isDev) {
            return;
        }
        this.write(LogLevelType.Debug, message);
    }
    info(message) {
        this.write(LogLevelType.Info, message);
    }
    warning(message) {
        this.write(LogLevelType.Warning, message);
    }
    error(message) {
        this.write(LogLevelType.Error, message);
    }
    write(level, message) {
        if (this.filter != null && this.filter(level)) {
            return;
        }
        switch (level) {
            case LogLevelType.Debug:
                // eslint-disable-next-line
                console.log(message);
                break;
            case LogLevelType.Info:
                // eslint-disable-next-line
                console.log(message);
                break;
            case LogLevelType.Warning:
                // eslint-disable-next-line
                console.warn(message);
                break;
            case LogLevelType.Error:
                // eslint-disable-next-line
                console.error(message);
                break;
            default:
                break;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/base-importer.ts













class BaseImporter {
    constructor() {
        this.organizationId = null;
        this.logService = new consoleLog_service_ConsoleLogService(false);
        this.newLineRegex = /(?:\r\n|\r|\n)/;
        this.passwordFieldNames = [
            "password",
            "pass word",
            "passphrase",
            "pass phrase",
            "pass",
            "code",
            "code word",
            "codeword",
            "secret",
            "secret word",
            "personpwd",
            "key",
            "keyword",
            "key word",
            "keyphrase",
            "key phrase",
            "form_pw",
            "wppassword",
            "pin",
            "pwd",
            "pw",
            "pword",
            "passwd",
            "p",
            "serial",
            "serial#",
            "license key",
            "reg #",
            // Non-English names
            "passwort",
        ];
        this.usernameFieldNames = [
            "user",
            "name",
            "user name",
            "username",
            "login name",
            "email",
            "e-mail",
            "id",
            "userid",
            "user id",
            "login",
            "form_loginname",
            "wpname",
            "mail",
            "loginid",
            "login id",
            "log",
            "personlogin",
            "first name",
            "last name",
            "card#",
            "account #",
            "member",
            "member #",
            // Non-English names
            "nom",
            "benutzername",
        ];
        this.notesFieldNames = [
            "note",
            "notes",
            "comment",
            "comments",
            "memo",
            "description",
            "free form",
            "freeform",
            "free text",
            "freetext",
            "free",
            // Non-English names
            "kommentar",
        ];
        this.uriFieldNames = [
            "url",
            "hyper link",
            "hyperlink",
            "link",
            "host",
            "hostname",
            "host name",
            "server",
            "address",
            "hyper ref",
            "href",
            "web",
            "website",
            "web site",
            "site",
            "web-site",
            "uri",
            // Non-English names
            "ort",
            "adresse",
        ];
        this.parseCsvOptions = {
            encoding: "UTF-8",
            skipEmptyLines: false,
        };
    }
    get organization() {
        return this.organizationId != null;
    }
    parseXml(data) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(data, "application/xml");
        return doc != null && doc.querySelector("parsererror") == null ? doc : null;
    }
    parseCsv(data, header, options = {}) {
        const parseOptions = Object.assign({ header: header }, this.parseCsvOptions, options);
        data = this.splitNewLine(data).join("\n").trim();
        const result = external_papaparse_namespaceObject.parse(data, parseOptions);
        if (result.errors != null && result.errors.length > 0) {
            result.errors.forEach((e) => {
                if (e.row != null) {
                    this.logService.warning("Error parsing row " + e.row + ": " + e.message);
                }
            });
        }
        return result.data && result.data.length > 0 ? result.data : null;
    }
    parseSingleRowCsv(rowData) {
        if (this.isNullOrWhitespace(rowData)) {
            return null;
        }
        const parsedRow = this.parseCsv(rowData, false);
        if (parsedRow != null && parsedRow.length > 0 && parsedRow[0].length > 0) {
            return parsedRow[0];
        }
        return null;
    }
    makeUriArray(uri) {
        if (uri == null) {
            return null;
        }
        if (typeof uri === "string") {
            const loginUri = new LoginUriView();
            loginUri.uri = this.fixUri(uri);
            if (this.isNullOrWhitespace(loginUri.uri)) {
                return null;
            }
            loginUri.match = null;
            return [loginUri];
        }
        if (uri.length > 0) {
            const returnArr = [];
            uri.forEach((u) => {
                const loginUri = new LoginUriView();
                loginUri.uri = this.fixUri(u);
                if (this.isNullOrWhitespace(loginUri.uri)) {
                    return;
                }
                loginUri.match = null;
                returnArr.push(loginUri);
            });
            return returnArr.length === 0 ? null : returnArr;
        }
        return null;
    }
    fixUri(uri) {
        if (uri == null) {
            return null;
        }
        uri = uri.trim();
        if (uri.indexOf("://") === -1 && uri.indexOf(".") >= 0) {
            uri = "http://" + uri;
        }
        if (uri.length > 1000) {
            return uri.substring(0, 1000);
        }
        return uri;
    }
    nameFromUrl(url) {
        const hostname = Utils.getHostname(url);
        if (this.isNullOrWhitespace(hostname)) {
            return null;
        }
        return hostname.startsWith("www.") ? hostname.replace("www.", "") : hostname;
    }
    isNullOrWhitespace(str) {
        return Utils.isNullOrWhitespace(str);
    }
    getValueOrDefault(str, defaultValue = null) {
        if (this.isNullOrWhitespace(str)) {
            return defaultValue;
        }
        return str;
    }
    splitNewLine(str) {
        return str.split(this.newLineRegex);
    }
    // ref https://stackoverflow.com/a/5911300
    getCardBrand(cardNum) {
        if (this.isNullOrWhitespace(cardNum)) {
            return null;
        }
        // Visa
        let re = new RegExp("^4");
        if (cardNum.match(re) != null) {
            return "Visa";
        }
        // Mastercard
        // Updated for Mastercard 2017 BINs expansion
        if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(cardNum)) {
            return "Mastercard";
        }
        // AMEX
        re = new RegExp("^3[47]");
        if (cardNum.match(re) != null) {
            return "Amex";
        }
        // Discover
        re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
        if (cardNum.match(re) != null) {
            return "Discover";
        }
        // Diners
        re = new RegExp("^36");
        if (cardNum.match(re) != null) {
            return "Diners Club";
        }
        // Diners - Carte Blanche
        re = new RegExp("^30[0-5]");
        if (cardNum.match(re) != null) {
            return "Diners Club";
        }
        // JCB
        re = new RegExp("^35(2[89]|[3-8][0-9])");
        if (cardNum.match(re) != null) {
            return "JCB";
        }
        // Visa Electron
        re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
        if (cardNum.match(re) != null) {
            return "Visa";
        }
        // Mir
        re = new RegExp("^220[0-4]");
        if (cardNum.match(re) != null) {
            return "Mir";
        }
        return null;
    }
    setCardExpiration(cipher, expiration) {
        if (!this.isNullOrWhitespace(expiration)) {
            expiration = expiration.replace(/\s/g, "");
            const parts = expiration.split("/");
            if (parts.length === 2) {
                let month = null;
                let year = null;
                if (parts[0].length === 1 || parts[0].length === 2) {
                    month = parts[0];
                    if (month.length === 2 && month[0] === "0") {
                        month = month.substr(1, 1);
                    }
                }
                if (parts[1].length === 2 || parts[1].length === 4) {
                    year = month.length === 2 ? "20" + parts[1] : parts[1];
                }
                if (month != null && year != null) {
                    cipher.card.expMonth = month;
                    cipher.card.expYear = year;
                    return true;
                }
            }
        }
        return false;
    }
    moveFoldersToCollections(result) {
        result.folderRelationships.forEach((r) => result.collectionRelationships.push(r));
        result.collections = result.folders.map((f) => {
            const collection = new CollectionView();
            collection.name = f.name;
            return collection;
        });
        result.folderRelationships = [];
        result.folders = [];
    }
    querySelectorDirectChild(parentEl, query) {
        const els = this.querySelectorAllDirectChild(parentEl, query);
        return els.length === 0 ? null : els[0];
    }
    querySelectorAllDirectChild(parentEl, query) {
        return Array.from(parentEl.querySelectorAll(query)).filter((el) => el.parentNode === parentEl);
    }
    initLoginCipher() {
        const cipher = new CipherView();
        cipher.favorite = false;
        cipher.notes = "";
        cipher.fields = [];
        cipher.login = new LoginView();
        cipher.type = CipherType.Login;
        return cipher;
    }
    cleanupCipher(cipher) {
        if (cipher == null) {
            return;
        }
        if (cipher.type !== CipherType.Login) {
            cipher.login = null;
        }
        if (this.isNullOrWhitespace(cipher.name)) {
            cipher.name = "--";
        }
        if (this.isNullOrWhitespace(cipher.notes)) {
            cipher.notes = null;
        }
        else {
            cipher.notes = cipher.notes.trim();
        }
        if (cipher.fields != null && cipher.fields.length === 0) {
            cipher.fields = null;
        }
    }
    processKvp(cipher, key, value, type = FieldType.Text) {
        if (this.isNullOrWhitespace(value)) {
            return;
        }
        if (this.isNullOrWhitespace(key)) {
            key = "";
        }
        if (value.length > 200 || value.trim().search(this.newLineRegex) > -1) {
            if (cipher.notes == null) {
                cipher.notes = "";
            }
            cipher.notes += key + ": " + this.splitNewLine(value).join("\n") + "\n";
        }
        else {
            if (cipher.fields == null) {
                cipher.fields = [];
            }
            const field = new FieldView();
            field.type = type;
            field.name = key;
            field.value = value;
            cipher.fields.push(field);
        }
    }
    processFolder(result, folderName) {
        let folderIndex = result.folders.length;
        const hasFolder = !this.isNullOrWhitespace(folderName);
        let addFolder = hasFolder;
        if (hasFolder) {
            for (let i = 0; i < result.folders.length; i++) {
                if (result.folders[i].name === folderName) {
                    addFolder = false;
                    folderIndex = i;
                    break;
                }
            }
        }
        if (addFolder) {
            const f = new FolderView();
            f.name = folderName;
            result.folders.push(f);
        }
        if (hasFolder) {
            result.folderRelationships.push([result.ciphers.length, folderIndex]);
        }
    }
    convertToNoteIfNeeded(cipher) {
        if (cipher.type === CipherType.Login &&
            this.isNullOrWhitespace(cipher.login.username) &&
            this.isNullOrWhitespace(cipher.login.password) &&
            (cipher.login.uris == null || cipher.login.uris.length === 0)) {
            cipher.type = CipherType.SecureNote;
            cipher.secureNote = new SecureNoteView();
            cipher.secureNote.type = SecureNoteType.Generic;
        }
    }
    processFullName(cipher, fullName) {
        if (this.isNullOrWhitespace(fullName)) {
            return;
        }
        const nameParts = fullName.split(" ");
        if (nameParts.length > 0) {
            cipher.identity.firstName = this.getValueOrDefault(nameParts[0]);
        }
        if (nameParts.length === 2) {
            cipher.identity.lastName = this.getValueOrDefault(nameParts[1]);
        }
        else if (nameParts.length >= 3) {
            cipher.identity.middleName = this.getValueOrDefault(nameParts[1]);
            cipher.identity.lastName = nameParts.slice(2, nameParts.length).join(" ");
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/ascendo-csv-importer.ts


class AscendoCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 2) {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value[value.length - 1]);
            cipher.name = this.getValueOrDefault(value[0], "--");
            if (value.length > 2 && value.length % 2 === 0) {
                for (let i = 0; i < value.length - 2; i += 2) {
                    const val = value[i + 2];
                    const field = value[i + 1];
                    if (this.isNullOrWhitespace(val) || this.isNullOrWhitespace(field)) {
                        continue;
                    }
                    const fieldLower = field.toLowerCase();
                    if (cipher.login.password == null && this.passwordFieldNames.indexOf(fieldLower) > -1) {
                        cipher.login.password = this.getValueOrDefault(val);
                    }
                    else if (cipher.login.username == null &&
                        this.usernameFieldNames.indexOf(fieldLower) > -1) {
                        cipher.login.username = this.getValueOrDefault(val);
                    }
                    else if ((cipher.login.uris == null || cipher.login.uris.length === 0) &&
                        this.uriFieldNames.indexOf(fieldLower) > -1) {
                        cipher.login.uris = this.makeUriArray(val);
                    }
                    else {
                        this.processKvp(cipher, field, val);
                    }
                }
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/avast-csv-importer.ts


class AvastCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.name);
            cipher.login.uris = this.makeUriArray(value.web);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.username = this.getValueOrDefault(value.login);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/avast-json-importer.ts




class AvastJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        if (results.logins != null) {
            results.logins.forEach((value) => {
                const cipher = this.initLoginCipher();
                cipher.name = this.getValueOrDefault(value.custName);
                cipher.notes = this.getValueOrDefault(value.note);
                cipher.login.uris = this.makeUriArray(value.url);
                cipher.login.password = this.getValueOrDefault(value.pwd);
                cipher.login.username = this.getValueOrDefault(value.loginName);
                this.cleanupCipher(cipher);
                result.ciphers.push(cipher);
            });
        }
        if (results.notes != null) {
            results.notes.forEach((value) => {
                const cipher = this.initLoginCipher();
                cipher.type = CipherType.SecureNote;
                cipher.secureNote.type = SecureNoteType.Generic;
                cipher.name = this.getValueOrDefault(value.label);
                cipher.notes = this.getValueOrDefault(value.text);
                this.cleanupCipher(cipher);
                result.ciphers.push(cipher);
            });
        }
        if (results.cards != null) {
            results.cards.forEach((value) => {
                const cipher = this.initLoginCipher();
                cipher.type = CipherType.Card;
                cipher.name = this.getValueOrDefault(value.custName);
                cipher.notes = this.getValueOrDefault(value.note);
                cipher.card.cardholderName = this.getValueOrDefault(value.holderName);
                cipher.card.number = this.getValueOrDefault(value.cardNumber);
                cipher.card.code = this.getValueOrDefault(value.cvv);
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                if (value.expirationDate != null) {
                    if (value.expirationDate.month != null) {
                        cipher.card.expMonth = value.expirationDate.month + "";
                    }
                    if (value.expirationDate.year != null) {
                        cipher.card.expYear = value.expirationDate.year + "";
                    }
                }
                this.cleanupCipher(cipher);
                result.ciphers.push(cipher);
            });
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/avira-csv-importer.ts


class AviraCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.name, this.getValueOrDefault(this.nameFromUrl(value.website), "--"));
            cipher.login.uris = this.makeUriArray(value.website);
            cipher.login.password = this.getValueOrDefault(value.password);
            if (this.isNullOrWhitespace(value.username) &&
                !this.isNullOrWhitespace(value.secondary_username)) {
                cipher.login.username = value.secondary_username;
            }
            else {
                cipher.login.username = this.getValueOrDefault(value.username);
                cipher.notes = this.getValueOrDefault(value.secondary_username);
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/bitwarden-csv-importer.ts











class BitwardenCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (this.organization && !this.isNullOrWhitespace(value.collections)) {
                const collections = value.collections.split(",");
                collections.forEach((col) => {
                    let addCollection = true;
                    let collectionIndex = result.collections.length;
                    for (let i = 0; i < result.collections.length; i++) {
                        if (result.collections[i].name === col) {
                            addCollection = false;
                            collectionIndex = i;
                            break;
                        }
                    }
                    if (addCollection) {
                        const collection = new CollectionView();
                        collection.name = col;
                        result.collections.push(collection);
                    }
                    result.collectionRelationships.push([result.ciphers.length, collectionIndex]);
                });
            }
            else if (!this.organization) {
                this.processFolder(result, value.folder);
            }
            const cipher = new CipherView();
            cipher.favorite =
                !this.organization && this.getValueOrDefault(value.favorite, "0") !== "0" ? true : false;
            cipher.type = CipherType.Login;
            cipher.notes = this.getValueOrDefault(value.notes);
            cipher.name = this.getValueOrDefault(value.name, "--");
            try {
                cipher.reprompt = parseInt(this.getValueOrDefault(value.reprompt, CipherRepromptType.None.toString()), 10);
            }
            catch (e) {
                // eslint-disable-next-line
                console.error("Unable to parse reprompt value", e);
                cipher.reprompt = CipherRepromptType.None;
            }
            if (!this.isNullOrWhitespace(value.fields)) {
                const fields = this.splitNewLine(value.fields);
                for (let i = 0; i < fields.length; i++) {
                    if (this.isNullOrWhitespace(fields[i])) {
                        continue;
                    }
                    const delimPosition = fields[i].lastIndexOf(": ");
                    if (delimPosition === -1) {
                        continue;
                    }
                    if (cipher.fields == null) {
                        cipher.fields = [];
                    }
                    const field = new FieldView();
                    field.name = fields[i].substr(0, delimPosition);
                    field.value = null;
                    field.type = FieldType.Text;
                    if (fields[i].length > delimPosition + 2) {
                        field.value = fields[i].substr(delimPosition + 2);
                    }
                    cipher.fields.push(field);
                }
            }
            const valueType = value.type != null ? value.type.toLowerCase() : null;
            switch (valueType) {
                case "note":
                    cipher.type = CipherType.SecureNote;
                    cipher.secureNote = new SecureNoteView();
                    cipher.secureNote.type = SecureNoteType.Generic;
                    break;
                default: {
                    cipher.type = CipherType.Login;
                    cipher.login = new LoginView();
                    cipher.login.totp = this.getValueOrDefault(value.login_totp || value.totp);
                    cipher.login.username = this.getValueOrDefault(value.login_username || value.username);
                    cipher.login.password = this.getValueOrDefault(value.login_password || value.password);
                    const uris = this.parseSingleRowCsv(value.login_uri || value.uri);
                    cipher.login.uris = this.makeUriArray(uris);
                    break;
                }
            }
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/bitwarden-json-importer.ts
var bitwarden_json_importer_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};






class BitwardenJsonImporter extends BaseImporter {
    constructor(cryptoService, i18nService) {
        super();
        this.cryptoService = cryptoService;
        this.i18nService = i18nService;
    }
    parse(data) {
        var _a;
        return bitwarden_json_importer_awaiter(this, void 0, void 0, function* () {
            this.result = new ImportResult();
            this.results = JSON.parse(data);
            if (this.results == null || this.results.items == null) {
                if ((_a = this.results) === null || _a === void 0 ? void 0 : _a.passwordProtected) {
                    this.result.success = false;
                    this.result.missingPassword = true;
                    this.result.errorMessage = this.i18nService.t("importPasswordRequired");
                    return this.result;
                }
                this.result.success = false;
                return this.result;
            }
            if (this.results.encrypted) {
                yield this.parseEncrypted();
            }
            else {
                this.parseDecrypted();
            }
            return this.result;
        });
    }
    parseEncrypted() {
        return bitwarden_json_importer_awaiter(this, void 0, void 0, function* () {
            if (this.results.encKeyValidation_DO_NOT_EDIT != null) {
                const orgKey = yield this.cryptoService.getOrgKey(this.organizationId);
                const encKeyValidation = new EncString(this.results.encKeyValidation_DO_NOT_EDIT);
                const encKeyValidationDecrypt = yield this.cryptoService.decryptToUtf8(encKeyValidation, orgKey);
                if (encKeyValidationDecrypt === null) {
                    this.result.success = false;
                    this.result.errorMessage = this.i18nService.t("importEncKeyError");
                    return;
                }
            }
            const groupingsMap = new Map();
            if (this.organization && this.results.collections != null) {
                for (const c of this.results.collections) {
                    const collection = CollectionWithIdExport.toDomain(c);
                    if (collection != null) {
                        collection.id = null;
                        collection.organizationId = this.organizationId;
                        const view = yield collection.decrypt();
                        groupingsMap.set(c.id, this.result.collections.length);
                        this.result.collections.push(view);
                    }
                }
            }
            else if (!this.organization && this.results.folders != null) {
                for (const f of this.results.folders) {
                    const folder = FolderWithIdExport.toDomain(f);
                    if (folder != null) {
                        folder.id = null;
                        const view = yield folder.decrypt();
                        groupingsMap.set(f.id, this.result.folders.length);
                        this.result.folders.push(view);
                    }
                }
            }
            for (const c of this.results.items) {
                const cipher = CipherWithIdExport.toDomain(c);
                // reset ids incase they were set for some reason
                cipher.id = null;
                cipher.folderId = null;
                cipher.organizationId = this.organizationId;
                cipher.collectionIds = null;
                // make sure password history is limited
                if (cipher.passwordHistory != null && cipher.passwordHistory.length > 5) {
                    cipher.passwordHistory = cipher.passwordHistory.slice(0, 5);
                }
                if (!this.organization && c.folderId != null && groupingsMap.has(c.folderId)) {
                    this.result.folderRelationships.push([
                        this.result.ciphers.length,
                        groupingsMap.get(c.folderId),
                    ]);
                }
                else if (this.organization && c.collectionIds != null) {
                    c.collectionIds.forEach((cId) => {
                        if (groupingsMap.has(cId)) {
                            this.result.collectionRelationships.push([
                                this.result.ciphers.length,
                                groupingsMap.get(cId),
                            ]);
                        }
                    });
                }
                const view = yield cipher.decrypt();
                this.cleanupCipher(view);
                this.result.ciphers.push(view);
            }
            this.result.success = true;
        });
    }
    parseDecrypted() {
        const groupingsMap = new Map();
        if (this.organization && this.results.collections != null) {
            this.results.collections.forEach((c) => {
                const collection = CollectionWithIdExport.toView(c);
                if (collection != null) {
                    collection.id = null;
                    collection.organizationId = null;
                    groupingsMap.set(c.id, this.result.collections.length);
                    this.result.collections.push(collection);
                }
            });
        }
        else if (!this.organization && this.results.folders != null) {
            this.results.folders.forEach((f) => {
                const folder = FolderWithIdExport.toView(f);
                if (folder != null) {
                    folder.id = null;
                    groupingsMap.set(f.id, this.result.folders.length);
                    this.result.folders.push(folder);
                }
            });
        }
        this.results.items.forEach((c) => {
            const cipher = CipherWithIdExport.toView(c);
            // reset ids incase they were set for some reason
            cipher.id = null;
            cipher.folderId = null;
            cipher.organizationId = null;
            cipher.collectionIds = null;
            // make sure password history is limited
            if (cipher.passwordHistory != null && cipher.passwordHistory.length > 5) {
                cipher.passwordHistory = cipher.passwordHistory.slice(0, 5);
            }
            if (!this.organization && c.folderId != null && groupingsMap.has(c.folderId)) {
                this.result.folderRelationships.push([
                    this.result.ciphers.length,
                    groupingsMap.get(c.folderId),
                ]);
            }
            else if (this.organization && c.collectionIds != null) {
                c.collectionIds.forEach((cId) => {
                    if (groupingsMap.has(cId)) {
                        this.result.collectionRelationships.push([
                            this.result.ciphers.length,
                            groupingsMap.get(cId),
                        ]);
                    }
                });
            }
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
        this.result.success = true;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/bitwarden-password-protected-importer.ts
var bitwarden_password_protected_importer_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class BitwardenPasswordProtectedImporter extends BitwardenJsonImporter {
    constructor(cryptoService, i18nService, password) {
        super(cryptoService, i18nService);
        this.password = password;
    }
    parse(data) {
        const _super = Object.create(null, {
            parse: { get: () => super.parse }
        });
        return bitwarden_password_protected_importer_awaiter(this, void 0, void 0, function* () {
            const result = new ImportResult();
            const parsedData = JSON.parse(data);
            if (this.cannotParseFile(parsedData)) {
                result.success = false;
                return result;
            }
            if (!(yield this.checkPassword(parsedData))) {
                result.success = false;
                result.errorMessage = this.i18nService.t("invalidFilePassword");
                return result;
            }
            const encData = new EncString(parsedData.data);
            const clearTextData = yield this.cryptoService.decryptToUtf8(encData, this.key);
            return yield _super.parse.call(this, clearTextData);
        });
    }
    checkPassword(jdoc) {
        return bitwarden_password_protected_importer_awaiter(this, void 0, void 0, function* () {
            this.key = yield this.cryptoService.makePinKey(this.password, jdoc.salt, KdfType.PBKDF2_SHA256, new KdfConfig(jdoc.kdfIterations));
            const encKeyValidation = new EncString(jdoc.encKeyValidation_DO_NOT_EDIT);
            const encKeyValidationDecrypt = yield this.cryptoService.decryptToUtf8(encKeyValidation, this.key);
            if (encKeyValidationDecrypt === null) {
                return false;
            }
            return true;
        });
    }
    cannotParseFile(jdoc) {
        return (!jdoc ||
            !jdoc.encrypted ||
            !jdoc.passwordProtected ||
            !jdoc.salt ||
            !jdoc.kdfIterations ||
            typeof jdoc.kdfIterations !== "number" ||
            jdoc.kdfType == null ||
            KdfType[jdoc.kdfType] == null ||
            !jdoc.encKeyValidation_DO_NOT_EDIT ||
            !jdoc.data);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/blackberry-csv-importer.ts


class BlackBerryCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.grouping === "list") {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.favorite = value.fav === "1";
            cipher.name = this.getValueOrDefault(value.name);
            cipher.notes = this.getValueOrDefault(value.extra);
            if (value.grouping !== "note") {
                cipher.login.uris = this.makeUriArray(value.url);
                cipher.login.password = this.getValueOrDefault(value.password);
                cipher.login.username = this.getValueOrDefault(value.username);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/blur-csv-importer.ts


class BlurCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.label === "null") {
                value.label = null;
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.label, this.getValueOrDefault(this.nameFromUrl(value.domain), "--"));
            cipher.login.uris = this.makeUriArray(value.domain);
            cipher.login.password = this.getValueOrDefault(value.password);
            if (this.isNullOrWhitespace(value.email) && !this.isNullOrWhitespace(value.username)) {
                cipher.login.username = value.username;
            }
            else {
                cipher.login.username = this.getValueOrDefault(value.email);
                cipher.notes = this.getValueOrDefault(value.username);
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/buttercup-csv-importer.ts


const OfficialProps = ["!group_id", "!group_name", "title", "username", "password", "URL", "id"];
class ButtercupCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            this.processFolder(result, this.getValueOrDefault(value["!group_name"]));
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.title, "--");
            cipher.login.username = this.getValueOrDefault(value.username);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.uris = this.makeUriArray(value.URL);
            let processingCustomFields = false;
            for (const prop in value) {
                // eslint-disable-next-line
                if (value.hasOwnProperty(prop)) {
                    if (!processingCustomFields && OfficialProps.indexOf(prop) === -1) {
                        processingCustomFields = true;
                    }
                    if (processingCustomFields) {
                        this.processKvp(cipher, prop, value[prop]);
                    }
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/chrome-csv-importer.ts


class ChromeCsvImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.androidPatternRegex = new RegExp("^android:\\/\\/.*(?<=@)(.*)(?=\\/)");
    }
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            let name = value.name;
            if (!name && this.androidPatternRegex.test(value.url)) {
                name = value.url.match(this.androidPatternRegex)[1];
            }
            cipher.name = this.getValueOrDefault(name, "--");
            cipher.login.username = this.getValueOrDefault(value.username);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.uris = this.makeUriArray(value.url);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/clipperz-html-importer.ts


class ClipperzHtmlImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const doc = this.parseXml(data);
        if (doc == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const textarea = doc.querySelector("textarea");
        if (textarea == null || this.isNullOrWhitespace(textarea.textContent)) {
            result.errorMessage = "Missing textarea.";
            result.success = false;
            return Promise.resolve(result);
        }
        const entries = JSON.parse(textarea.textContent);
        entries.forEach((entry) => {
            const cipher = this.initLoginCipher();
            if (!this.isNullOrWhitespace(entry.label)) {
                cipher.name = entry.label.split(" ")[0];
            }
            if (entry.data != null && !this.isNullOrWhitespace(entry.data.notes)) {
                cipher.notes = entry.data.notes.split("\\n").join("\n");
            }
            if (entry.currentVersion != null && entry.currentVersion.fields != null) {
                for (const property in entry.currentVersion.fields) {
                    // eslint-disable-next-line
                    if (!entry.currentVersion.fields.hasOwnProperty(property)) {
                        continue;
                    }
                    const field = entry.currentVersion.fields[property];
                    const actionType = field.actionType != null ? field.actionType.toLowerCase() : null;
                    switch (actionType) {
                        case "password":
                            cipher.login.password = this.getValueOrDefault(field.value);
                            break;
                        case "email":
                        case "username":
                        case "user":
                        case "name":
                            cipher.login.username = this.getValueOrDefault(field.value);
                            break;
                        case "url":
                            cipher.login.uris = this.makeUriArray(field.value);
                            break;
                        default: {
                            const labelLower = field.label != null ? field.label.toLowerCase() : null;
                            if (cipher.login.password == null &&
                                this.passwordFieldNames.indexOf(labelLower) > -1) {
                                cipher.login.password = this.getValueOrDefault(field.value);
                            }
                            else if (cipher.login.username == null &&
                                this.usernameFieldNames.indexOf(labelLower) > -1) {
                                cipher.login.username = this.getValueOrDefault(field.value);
                            }
                            else if ((cipher.login.uris == null || cipher.login.uris.length === 0) &&
                                this.uriFieldNames.indexOf(labelLower) > -1) {
                                cipher.login.uris = this.makeUriArray(field.value);
                            }
                            else {
                                this.processKvp(cipher, field.label, field.value);
                            }
                            break;
                        }
                    }
                }
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/codebook-csv-importer.ts


class CodebookCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            this.processFolder(result, this.getValueOrDefault(value.Category));
            const cipher = this.initLoginCipher();
            cipher.favorite = this.getValueOrDefault(value.Favorite) === "True";
            cipher.name = this.getValueOrDefault(value.Entry, "--");
            cipher.notes = this.getValueOrDefault(value.Note);
            cipher.login.username = this.getValueOrDefault(value.Username, value.Email);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.totp = this.getValueOrDefault(value.TOTP);
            cipher.login.uris = this.makeUriArray(value.Website);
            if (!this.isNullOrWhitespace(value.Username)) {
                this.processKvp(cipher, "Email", value.Email);
            }
            this.processKvp(cipher, "Phone", value.Phone);
            this.processKvp(cipher, "PIN", value.PIN);
            this.processKvp(cipher, "Account", value.Account);
            this.processKvp(cipher, "Date", value.Date);
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/dashlane/dashlane-csv-importer.ts







const _mappedCredentialsColums = new Set([
    "title",
    "note",
    "username",
    "password",
    "url",
    "otpSecret",
    "category",
]);
const _mappedPersonalInfoAsIdentiyColumns = new Set([
    "type",
    "title",
    "first_name",
    "middle_name",
    "last_name",
    "login",
    "email",
    "phone_number",
    "address",
    "country",
    "state",
    "city",
    "zip",
    // Skip item_name as we already have set a combined name
    "item_name",
]);
const _mappedSecureNoteColumns = new Set(["title", "note"]);
class DashlaneCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        if (results[0].type != null && results[0].title != null) {
            const personalRecords = results;
            // If personalRecords has only one "name" then create an Identity-Cipher
            if (personalRecords.filter((x) => x.type === "name").length === 1) {
                const cipher = this.initLoginCipher();
                cipher.type = CipherType.Identity;
                cipher.identity = new IdentityView();
                results.forEach((row) => {
                    this.parsePersonalInformationRecordAsIdentity(cipher, row);
                });
                this.cleanupCipher(cipher);
                result.ciphers.push(cipher);
                result.success = true;
                return Promise.resolve(result);
            }
        }
        results.forEach((row) => {
            const cipher = this.initLoginCipher();
            const rowKeys = Object.keys(row);
            if (rowKeys[0] === "username") {
                this.processFolder(result, row.category);
                this.parseCredentialsRecord(cipher, row);
            }
            if (rowKeys[0] === "type" && rowKeys[1] === "account_name") {
                this.parsePaymentRecord(cipher, row);
            }
            if (rowKeys[0] === "type" && rowKeys[1] === "number") {
                this.parseIdRecord(cipher, row);
            }
            if ((rowKeys[0] === "type") != null && rowKeys[1] === "title") {
                this.parsePersonalInformationRecord(cipher, row);
            }
            if (rowKeys[0] === "title" && rowKeys[1] === "note") {
                this.parseSecureNoteRecords(cipher, row);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    parseCredentialsRecord(cipher, row) {
        cipher.type = CipherType.Login;
        cipher.login = new LoginView();
        cipher.name = row.title;
        cipher.notes = row.note;
        cipher.login.username = row.username;
        cipher.login.password = row.password;
        cipher.login.totp = row.otpSecret;
        cipher.login.uris = this.makeUriArray(row.url);
        this.importUnmappedFields(cipher, row, _mappedCredentialsColums);
    }
    parsePaymentRecord(cipher, row) {
        cipher.type = CipherType.Card;
        cipher.card = new CardView();
        cipher.name = row.account_name;
        let mappedValues = [];
        switch (row.type) {
            case "credit_card":
                cipher.card.cardholderName = row.account_name;
                cipher.card.number = row.cc_number;
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                cipher.card.code = row.code;
                this.setCardExpiration(cipher, `${row.expiration_month}/${row.expiration_year}`);
                // If you add more mapped fields please extend this
                mappedValues = [
                    "account_name",
                    "account_holder",
                    "cc_number",
                    "code",
                    "expiration_month",
                    "expiration_year",
                ];
                break;
            case "bank":
                cipher.card.cardholderName = row.account_holder;
                cipher.card.number = row.account_number;
                // If you add more mapped fields please extend this
                mappedValues = ["account_name", "account_holder", "account_number"];
                break;
            default:
                break;
        }
        this.importUnmappedFields(cipher, row, new Set(mappedValues));
    }
    parseIdRecord(cipher, row) {
        cipher.type = CipherType.Identity;
        cipher.identity = new IdentityView();
        const mappedValues = ["name", "number"];
        switch (row.type) {
            case "card":
                cipher.name = `${row.name} ${row.type}`;
                this.processFullName(cipher, row.name);
                cipher.identity.licenseNumber = row.number;
                break;
            case "passport":
                cipher.name = `${row.name} ${row.type}`;
                this.processFullName(cipher, row.name);
                cipher.identity.passportNumber = row.number;
                break;
            case "license":
                cipher.name = `${row.name} ${row.type}`;
                this.processFullName(cipher, row.name);
                cipher.identity.licenseNumber = row.number;
                cipher.identity.state = row.state;
                mappedValues.push("state");
                break;
            case "social_security":
                cipher.name = `${row.name} ${row.type}`;
                this.processFullName(cipher, row.name);
                cipher.identity.ssn = row.number;
                break;
            case "tax_number":
                cipher.name = row.type;
                cipher.identity.licenseNumber = row.number;
                break;
            default:
                break;
        }
        // If you add more mapped fields please extend this
        this.importUnmappedFields(cipher, row, new Set(mappedValues));
    }
    parsePersonalInformationRecord(cipher, row) {
        cipher.type = CipherType.SecureNote;
        cipher.secureNote.type = SecureNoteType.Generic;
        if (row.type === "name") {
            cipher.name = `${row.title} ${row.first_name} ${row.middle_name} ${row.last_name}`
                .replace("  ", " ")
                .trim();
        }
        else {
            cipher.name = row.item_name;
        }
        const dataRow = row;
        Object.keys(row).forEach((key) => {
            this.processKvp(cipher, key, dataRow[key]);
        });
    }
    parsePersonalInformationRecordAsIdentity(cipher, row) {
        switch (row.type) {
            case "name":
                this.processFullName(cipher, `${row.first_name} ${row.middle_name} ${row.last_name}`);
                cipher.identity.title = row.title;
                cipher.name = cipher.identity.fullName;
                cipher.identity.username = row.login;
                break;
            case "email":
                cipher.identity.email = row.email;
                break;
            case "number":
                cipher.identity.phone = row.phone_number;
                break;
            case "address":
                cipher.identity.address1 = row.address;
                cipher.identity.city = row.city;
                cipher.identity.postalCode = row.zip;
                cipher.identity.state = row.state;
                cipher.identity.country = row.country;
                break;
            default:
                break;
        }
        this.importUnmappedFields(cipher, row, _mappedPersonalInfoAsIdentiyColumns);
    }
    parseSecureNoteRecords(cipher, row) {
        cipher.type = CipherType.SecureNote;
        cipher.secureNote.type = SecureNoteType.Generic;
        cipher.name = row.title;
        cipher.notes = row.note;
        this.importUnmappedFields(cipher, row, _mappedSecureNoteColumns);
    }
    importUnmappedFields(cipher, row, mappedValues) {
        const unmappedFields = Object.keys(row).filter((x) => !mappedValues.has(x));
        unmappedFields.forEach((key) => {
            const item = row;
            this.processKvp(cipher, key, item[key]);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/dashlane/dashlane-json-importer.ts








const HandledResults = new Set([
    "ADDRESS",
    "AUTHENTIFIANT",
    "BANKSTATEMENT",
    "IDCARD",
    "IDENTITY",
    "PAYMENTMEANS_CREDITCARD",
    "PAYMENTMEAN_PAYPAL",
    "EMAIL",
]);
class DashlaneJsonImporter extends BaseImporter {
    parse(data) {
        this.result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || results.length === 0) {
            this.result.success = false;
            return Promise.resolve(this.result);
        }
        if (results.ADDRESS != null) {
            this.processAddress(results.ADDRESS);
        }
        if (results.AUTHENTIFIANT != null) {
            this.processAuth(results.AUTHENTIFIANT);
        }
        if (results.BANKSTATEMENT != null) {
            this.processNote(results.BANKSTATEMENT, "BankAccountName");
        }
        if (results.IDCARD != null) {
            this.processNote(results.IDCARD, "Fullname");
        }
        if (results.PAYMENTMEANS_CREDITCARD != null) {
            this.processCard(results.PAYMENTMEANS_CREDITCARD);
        }
        if (results.IDENTITY != null) {
            this.processIdentity(results.IDENTITY);
        }
        for (const key in results) {
            // eslint-disable-next-line
            if (results.hasOwnProperty(key) && !HandledResults.has(key)) {
                this.processNote(results[key], null, "Generic Note");
            }
        }
        this.result.success = true;
        return Promise.resolve(this.result);
    }
    processAuth(results) {
        results.forEach((credential) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(credential.title);
            cipher.login.username = this.getValueOrDefault(credential.login, this.getValueOrDefault(credential.secondaryLogin));
            if (this.isNullOrWhitespace(cipher.login.username)) {
                cipher.login.username = this.getValueOrDefault(credential.email);
            }
            else if (!this.isNullOrWhitespace(credential.email)) {
                cipher.notes = "Email: " + credential.email + "\n";
            }
            cipher.login.password = this.getValueOrDefault(credential.password);
            cipher.login.uris = this.makeUriArray(credential.domain);
            cipher.notes += this.getValueOrDefault(credential.note, "");
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
    }
    processIdentity(results) {
        results.forEach((obj) => {
            const cipher = new CipherView();
            cipher.identity = new IdentityView();
            cipher.type = CipherType.Identity;
            cipher.name = this.getValueOrDefault(obj.fullName, "");
            const nameParts = cipher.name.split(" ");
            if (nameParts.length > 0) {
                cipher.identity.firstName = this.getValueOrDefault(nameParts[0]);
            }
            if (nameParts.length === 2) {
                cipher.identity.lastName = this.getValueOrDefault(nameParts[1]);
            }
            else if (nameParts.length === 3) {
                cipher.identity.middleName = this.getValueOrDefault(nameParts[1]);
                cipher.identity.lastName = this.getValueOrDefault(nameParts[2]);
            }
            cipher.identity.username = this.getValueOrDefault(obj.pseudo);
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
    }
    processAddress(results) {
        results.forEach((obj) => {
            const cipher = new CipherView();
            cipher.identity = new IdentityView();
            cipher.type = CipherType.Identity;
            cipher.name = this.getValueOrDefault(obj.addressName);
            cipher.identity.address1 = this.getValueOrDefault(obj.addressFull);
            cipher.identity.city = this.getValueOrDefault(obj.city);
            cipher.identity.state = this.getValueOrDefault(obj.state);
            cipher.identity.postalCode = this.getValueOrDefault(obj.zipcode);
            cipher.identity.country = this.getValueOrDefault(obj.country);
            if (cipher.identity.country != null) {
                cipher.identity.country = cipher.identity.country.toUpperCase();
            }
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
    }
    processCard(results) {
        results.forEach((obj) => {
            const cipher = new CipherView();
            cipher.card = new CardView();
            cipher.type = CipherType.Card;
            cipher.name = this.getValueOrDefault(obj.bank);
            cipher.card.number = this.getValueOrDefault(obj.cardNumber);
            cipher.card.brand = this.getCardBrand(cipher.card.number);
            cipher.card.cardholderName = this.getValueOrDefault(obj.owner);
            if (!this.isNullOrWhitespace(cipher.card.brand)) {
                if (this.isNullOrWhitespace(cipher.name)) {
                    cipher.name = cipher.card.brand;
                }
                else {
                    cipher.name += " - " + cipher.card.brand;
                }
            }
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
    }
    processNote(results, nameProperty, name = null) {
        results.forEach((obj) => {
            const cipher = new CipherView();
            cipher.secureNote = new SecureNoteView();
            cipher.type = CipherType.SecureNote;
            cipher.secureNote.type = SecureNoteType.Generic;
            if (name != null) {
                cipher.name = name;
            }
            else {
                cipher.name = this.getValueOrDefault(obj[nameProperty]);
            }
            for (const key in obj) {
                // eslint-disable-next-line
                if (obj.hasOwnProperty(key) && key !== nameProperty) {
                    this.processKvp(cipher, key, obj[key].toString());
                }
            }
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/encryptr-csv-importer.ts




class EncryptrCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.Label, "--");
            cipher.notes = this.getValueOrDefault(value.Notes);
            const text = this.getValueOrDefault(value.Text);
            if (!this.isNullOrWhitespace(text)) {
                if (this.isNullOrWhitespace(cipher.notes)) {
                    cipher.notes = text;
                }
                else {
                    cipher.notes += "\n\n" + text;
                }
            }
            const type = value["Entry Type"];
            if (type === "Password") {
                cipher.login.username = this.getValueOrDefault(value.Username);
                cipher.login.password = this.getValueOrDefault(value.Password);
                cipher.login.uris = this.makeUriArray(value["Site URL"]);
            }
            else if (type === "Credit Card") {
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
                cipher.card.cardholderName = this.getValueOrDefault(value["Name on card"]);
                cipher.card.number = this.getValueOrDefault(value["Card Number"]);
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                cipher.card.code = this.getValueOrDefault(value.CVV);
                const expiry = this.getValueOrDefault(value.Expiry);
                if (!this.isNullOrWhitespace(expiry)) {
                    const expParts = expiry.split("/");
                    if (expParts.length > 1) {
                        cipher.card.expMonth = parseInt(expParts[0], null).toString();
                        cipher.card.expYear = (2000 + parseInt(expParts[1], null)).toString();
                    }
                }
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/enpass/enpass-csv-importer.ts






class EnpassCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        let firstRow = true;
        results.forEach((value) => {
            if (value.length < 2 || (firstRow && (value[0] === "Title" || value[0] === "title"))) {
                firstRow = false;
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value[value.length - 1]);
            cipher.name = this.getValueOrDefault(value[0], "--");
            if (value.length === 2 ||
                (!this.containsField(value, "username") &&
                    !this.containsField(value, "password") &&
                    !this.containsField(value, "email") &&
                    !this.containsField(value, "url"))) {
                cipher.type = CipherType.SecureNote;
                cipher.secureNote = new SecureNoteView();
                cipher.secureNote.type = SecureNoteType.Generic;
            }
            if (this.containsField(value, "cardholder") &&
                this.containsField(value, "number") &&
                this.containsField(value, "expiry date")) {
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
            }
            if (value.length > 2 && value.length % 2 === 0) {
                for (let i = 0; i < value.length - 2; i += 2) {
                    const fieldValue = value[i + 2];
                    if (this.isNullOrWhitespace(fieldValue)) {
                        continue;
                    }
                    const fieldName = value[i + 1];
                    const fieldNameLower = fieldName.toLowerCase();
                    if (cipher.type === CipherType.Login) {
                        if (fieldNameLower === "url" &&
                            (cipher.login.uris == null || cipher.login.uris.length === 0)) {
                            cipher.login.uris = this.makeUriArray(fieldValue);
                            continue;
                        }
                        else if ((fieldNameLower === "username" || fieldNameLower === "email") &&
                            this.isNullOrWhitespace(cipher.login.username)) {
                            cipher.login.username = fieldValue;
                            continue;
                        }
                        else if (fieldNameLower === "password" &&
                            this.isNullOrWhitespace(cipher.login.password)) {
                            cipher.login.password = fieldValue;
                            continue;
                        }
                        else if (fieldNameLower === "totp" && this.isNullOrWhitespace(cipher.login.totp)) {
                            cipher.login.totp = fieldValue;
                            continue;
                        }
                    }
                    else if (cipher.type === CipherType.Card) {
                        if (fieldNameLower === "cardholder" &&
                            this.isNullOrWhitespace(cipher.card.cardholderName)) {
                            cipher.card.cardholderName = fieldValue;
                            continue;
                        }
                        else if (fieldNameLower === "number" && this.isNullOrWhitespace(cipher.card.number)) {
                            cipher.card.number = fieldValue;
                            cipher.card.brand = this.getCardBrand(fieldValue);
                            continue;
                        }
                        else if (fieldNameLower === "cvc" && this.isNullOrWhitespace(cipher.card.code)) {
                            cipher.card.code = fieldValue;
                            continue;
                        }
                        else if (fieldNameLower === "expiry date" &&
                            this.isNullOrWhitespace(cipher.card.expMonth) &&
                            this.isNullOrWhitespace(cipher.card.expYear)) {
                            if (this.setCardExpiration(cipher, fieldValue)) {
                                continue;
                            }
                        }
                        else if (fieldNameLower === "type") {
                            // Skip since brand was determined from number above
                            continue;
                        }
                    }
                    this.processKvp(cipher, fieldName, fieldValue);
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
    containsField(fields, name) {
        if (fields == null || name == null) {
            return false;
        }
        return (fields.filter((f) => !this.isNullOrWhitespace(f) && f.toLowerCase() === name.toLowerCase())
            .length > 0);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/enpass/enpass-json-importer.ts






const androidUrlRegex = new RegExp("androidapp://.*==@", "g");
class EnpassJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || results.items == null || results.items.length === 0) {
            result.success = false;
            return Promise.resolve(result);
        }
        const foldersMap = new Map();
        const foldersIndexMap = new Map();
        const folderTree = this.buildFolderTree(results.folders);
        this.flattenFolderTree(null, folderTree, foldersMap);
        foldersMap.forEach((val, key) => {
            foldersIndexMap.set(key, result.folders.length);
            const f = new FolderView();
            f.name = val;
            result.folders.push(f);
        });
        results.items.forEach((item) => {
            if (item.folders != null && item.folders.length > 0 && foldersIndexMap.has(item.folders[0])) {
                result.folderRelationships.push([
                    result.ciphers.length,
                    foldersIndexMap.get(item.folders[0]),
                ]);
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(item.title);
            cipher.favorite = item.favorite > 0;
            if (item.template_type != null && item.fields != null && item.fields.length > 0) {
                if (item.template_type.indexOf("login.") === 0 ||
                    item.template_type.indexOf("password.") === 0) {
                    this.processLogin(cipher, item.fields);
                }
                else if (item.template_type.indexOf("creditcard.") === 0) {
                    this.processCard(cipher, item.fields);
                }
                else if (item.template_type.indexOf("identity.") < 0 &&
                    item.fields.some((f) => f.type === "password" && !this.isNullOrWhitespace(f.value))) {
                    this.processLogin(cipher, item.fields);
                }
                else {
                    this.processNote(cipher, item.fields);
                }
            }
            cipher.notes += "\n" + this.getValueOrDefault(item.note, "");
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
    processLogin(cipher, fields) {
        const urls = [];
        fields.forEach((field) => {
            if (this.isNullOrWhitespace(field.value) || field.type === "section") {
                return;
            }
            if ((field.type === "username" || field.type === "email") &&
                this.isNullOrWhitespace(cipher.login.username)) {
                cipher.login.username = field.value;
            }
            else if (field.type === "password" && this.isNullOrWhitespace(cipher.login.password)) {
                cipher.login.password = field.value;
            }
            else if (field.type === "totp" && this.isNullOrWhitespace(cipher.login.totp)) {
                cipher.login.totp = field.value;
            }
            else if (field.type === "url") {
                urls.push(field.value);
            }
            else if (field.type === ".Android#") {
                let cleanedValue = field.value.startsWith("androidapp://")
                    ? field.value
                    : "androidapp://" + field.value;
                cleanedValue = cleanedValue.replace("android://", "");
                cleanedValue = cleanedValue.replace(androidUrlRegex, "androidapp://");
                urls.push(cleanedValue);
            }
            else {
                this.processKvp(cipher, field.label, field.value, field.sensitive === 1 ? FieldType.Hidden : FieldType.Text);
            }
        });
        cipher.login.uris = this.makeUriArray(urls);
    }
    processCard(cipher, fields) {
        cipher.card = new CardView();
        cipher.type = CipherType.Card;
        fields.forEach((field) => {
            if (this.isNullOrWhitespace(field.value) ||
                field.type === "section" ||
                field.type === "ccType") {
                return;
            }
            if (field.type === "ccName" && this.isNullOrWhitespace(cipher.card.cardholderName)) {
                cipher.card.cardholderName = field.value;
            }
            else if (field.type === "ccNumber" && this.isNullOrWhitespace(cipher.card.number)) {
                cipher.card.number = field.value;
                cipher.card.brand = this.getCardBrand(cipher.card.number);
            }
            else if (field.type === "ccCvc" && this.isNullOrWhitespace(cipher.card.code)) {
                cipher.card.code = field.value;
            }
            else if (field.type === "ccExpiry" && this.isNullOrWhitespace(cipher.card.expYear)) {
                if (!this.setCardExpiration(cipher, field.value)) {
                    this.processKvp(cipher, field.label, field.value, field.sensitive === 1 ? FieldType.Hidden : FieldType.Text);
                }
            }
            else {
                this.processKvp(cipher, field.label, field.value, field.sensitive === 1 ? FieldType.Hidden : FieldType.Text);
            }
        });
    }
    processNote(cipher, fields) {
        fields.forEach((field) => {
            if (this.isNullOrWhitespace(field.value) || field.type === "section") {
                return;
            }
            this.processKvp(cipher, field.label, field.value, field.sensitive === 1 ? FieldType.Hidden : FieldType.Text);
        });
    }
    buildFolderTree(folders) {
        if (folders == null) {
            return [];
        }
        const folderTree = [];
        const map = new Map([]);
        folders.forEach((obj) => {
            map.set(obj.uuid, obj);
            obj.children = [];
        });
        folders.forEach((obj) => {
            if (obj.parent_uuid != null && obj.parent_uuid !== "" && map.has(obj.parent_uuid)) {
                map.get(obj.parent_uuid).children.push(obj);
            }
            else {
                folderTree.push(obj);
            }
        });
        return folderTree;
    }
    flattenFolderTree(titlePrefix, tree, map) {
        if (tree == null) {
            return;
        }
        tree.forEach((f) => {
            if (f.title != null && f.title.trim() !== "") {
                let title = f.title.trim();
                if (titlePrefix != null && titlePrefix.trim() !== "") {
                    title = titlePrefix + "/" + title;
                }
                map.set(f.uuid, title);
                if (f.children != null && f.children.length !== 0) {
                    this.flattenFolderTree(title, f.children, map);
                }
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/firefox-csv-importer.ts


class FirefoxCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results
            .filter((value) => {
            return value.url !== "chrome://FirefoxAccounts";
        })
            .forEach((value) => {
            const cipher = this.initLoginCipher();
            const url = this.getValueOrDefault(value.url, this.getValueOrDefault(value.hostname));
            cipher.name = this.getValueOrDefault(this.nameFromUrl(url), "--");
            cipher.login.username = this.getValueOrDefault(value.username);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.uris = this.makeUriArray(url);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/fsecure/fsecure-fsk-types.ts
var FskEntryTypesEnum;
(function (FskEntryTypesEnum) {
    FskEntryTypesEnum[FskEntryTypesEnum["Login"] = 1] = "Login";
    FskEntryTypesEnum[FskEntryTypesEnum["CreditCard"] = 2] = "CreditCard";
})(FskEntryTypesEnum || (FskEntryTypesEnum = {}));

;// CONCATENATED MODULE: ../../libs/common/src/importers/fsecure/fsecure-fsk-importer.ts





class FSecureFskImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || results.data == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        for (const key in results.data) {
            // eslint-disable-next-line
            if (!results.data.hasOwnProperty(key)) {
                continue;
            }
            const value = results.data[key];
            const cipher = this.parseEntry(value);
            result.ciphers.push(cipher);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    parseEntry(entry) {
        const cipher = this.initLoginCipher();
        cipher.name = this.getValueOrDefault(entry.service);
        cipher.notes = this.getValueOrDefault(entry.notes);
        cipher.favorite = entry.favorite > 0;
        switch (entry.type) {
            case FskEntryTypesEnum.Login:
                this.handleLoginEntry(entry, cipher);
                break;
            case FskEntryTypesEnum.CreditCard:
                this.handleCreditCardEntry(entry, cipher);
                break;
            default:
                return;
                break;
        }
        this.convertToNoteIfNeeded(cipher);
        this.cleanupCipher(cipher);
        return cipher;
    }
    handleLoginEntry(entry, cipher) {
        cipher.login.username = this.getValueOrDefault(entry.username);
        cipher.login.password = this.getValueOrDefault(entry.password);
        cipher.login.uris = this.makeUriArray(entry.url);
    }
    handleCreditCardEntry(entry, cipher) {
        cipher.type = CipherType.Card;
        cipher.card = new CardView();
        cipher.card.cardholderName = this.getValueOrDefault(entry.username);
        cipher.card.number = this.getValueOrDefault(entry.creditNumber);
        cipher.card.brand = this.getCardBrand(cipher.card.number);
        cipher.card.code = this.getValueOrDefault(entry.creditCvv);
        if (!this.isNullOrWhitespace(entry.creditExpiry)) {
            if (!this.setCardExpiration(cipher, entry.creditExpiry)) {
                this.processKvp(cipher, "Expiration", entry.creditExpiry);
            }
        }
        if (!this.isNullOrWhitespace(entry.password)) {
            this.processKvp(cipher, "PIN", entry.password);
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/gnome-json-importer.ts


class GnomeJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || Object.keys(results).length === 0) {
            result.success = false;
            return Promise.resolve(result);
        }
        for (const keyRing in results) {
            if (!results.hasOwnProperty(keyRing) || // eslint-disable-line
                this.isNullOrWhitespace(keyRing) ||
                results[keyRing].length === 0) {
                continue;
            }
            results[keyRing].forEach((value) => {
                if (this.isNullOrWhitespace(value.display_name) ||
                    value.display_name.indexOf("http") !== 0) {
                    return;
                }
                this.processFolder(result, keyRing);
                const cipher = this.initLoginCipher();
                cipher.name = value.display_name.replace("http://", "").replace("https://", "");
                if (cipher.name.length > 30) {
                    cipher.name = cipher.name.substring(0, 30);
                }
                cipher.login.password = this.getValueOrDefault(value.secret);
                cipher.login.uris = this.makeUriArray(value.display_name);
                if (value.attributes != null) {
                    cipher.login.username =
                        value.attributes != null
                            ? this.getValueOrDefault(value.attributes.username_value)
                            : null;
                    for (const attr in value.attributes) {
                        if (!value.attributes.hasOwnProperty(attr) || // eslint-disable-line
                            attr === "username_value" ||
                            attr === "xdg:schema") {
                            continue;
                        }
                        this.processKvp(cipher, attr, value.attributes[attr]);
                    }
                }
                this.convertToNoteIfNeeded(cipher);
                this.cleanupCipher(cipher);
                result.ciphers.push(cipher);
            });
        }
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/import-error.ts
class ImportError extends Error {
    constructor(message, passwordRequired = false) {
        super(message);
        this.passwordRequired = passwordRequired;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/kaspersky-txt-importer.ts


const NotesHeader = "Notes\n\n";
const ApplicationsHeader = "Applications\n\n";
const WebsitesHeader = "Websites\n\n";
const Delimiter = "\n---\n";
class KasperskyTxtImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        let notesData;
        let applicationsData;
        let websitesData;
        let workingData = this.splitNewLine(data).join("\n");
        if (workingData.indexOf(NotesHeader) !== -1) {
            const parts = workingData.split(NotesHeader);
            if (parts.length > 1) {
                workingData = parts[0];
                notesData = parts[1];
            }
        }
        if (workingData.indexOf(ApplicationsHeader) !== -1) {
            const parts = workingData.split(ApplicationsHeader);
            if (parts.length > 1) {
                workingData = parts[0];
                applicationsData = parts[1];
            }
        }
        if (workingData.indexOf(WebsitesHeader) === 0) {
            const parts = workingData.split(WebsitesHeader);
            if (parts.length > 1) {
                workingData = parts[0];
                websitesData = parts[1];
            }
        }
        const notes = this.parseDataCategory(notesData);
        const applications = this.parseDataCategory(applicationsData);
        const websites = this.parseDataCategory(websitesData);
        notes.forEach((n) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(n.get("Name"));
            cipher.notes = this.getValueOrDefault(n.get("Text"));
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        websites.concat(applications).forEach((w) => {
            const cipher = this.initLoginCipher();
            const nameKey = w.has("Website name") ? "Website name" : "Application";
            cipher.name = this.getValueOrDefault(w.get(nameKey), "");
            if (!this.isNullOrWhitespace(w.get("Login name"))) {
                if (!this.isNullOrWhitespace(cipher.name)) {
                    cipher.name += ": ";
                }
                cipher.name += w.get("Login name");
            }
            cipher.notes = this.getValueOrDefault(w.get("Comment"));
            if (w.has("Website URL")) {
                cipher.login.uris = this.makeUriArray(w.get("Website URL"));
            }
            cipher.login.username = this.getValueOrDefault(w.get("Login"));
            cipher.login.password = this.getValueOrDefault(w.get("Password"));
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
    parseDataCategory(data) {
        if (this.isNullOrWhitespace(data) || data.indexOf(Delimiter) === -1) {
            return [];
        }
        const items = [];
        data.split(Delimiter).forEach((p) => {
            if (p.indexOf("\n") === -1) {
                return;
            }
            const item = new Map();
            let itemComment;
            let itemCommentKey;
            p.split("\n").forEach((l) => {
                if (itemComment != null) {
                    itemComment += "\n" + l;
                    return;
                }
                const colonIndex = l.indexOf(":");
                let key;
                let val;
                if (colonIndex === -1) {
                    return;
                }
                else {
                    key = l.substring(0, colonIndex);
                    if (l.length > colonIndex + 1) {
                        val = l.substring(colonIndex + 2);
                    }
                }
                if (key != null) {
                    item.set(key, val);
                }
                if (key === "Comment" || key === "Text") {
                    itemComment = val;
                    itemCommentKey = key;
                }
            });
            if (itemComment != null && itemCommentKey != null) {
                item.set(itemCommentKey, itemComment);
            }
            if (item.size === 0) {
                return;
            }
            items.push(item);
        });
        return items;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/keepass2-xml-importer.ts




class KeePass2XmlImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.result = new ImportResult();
    }
    parse(data) {
        const doc = this.parseXml(data);
        if (doc == null) {
            this.result.success = false;
            return Promise.resolve(this.result);
        }
        //Note: The doc.querySelector("KeePassFile > Root > Group") no longers works on node and we have to breakdown the query by nodes
        const KeePassFileNode = doc.querySelector("KeePassFile");
        if (KeePassFileNode == null) {
            this.result.errorMessage = "Missing `KeePassFile` node.";
            this.result.success = false;
            return Promise.resolve(this.result);
        }
        const RootNode = KeePassFileNode.querySelector("Root");
        if (RootNode == null) {
            this.result.errorMessage = "Missing `KeePassFile > Root` node.";
            this.result.success = false;
            return Promise.resolve(this.result);
        }
        const rootGroup = RootNode.querySelector("Group");
        if (rootGroup == null) {
            this.result.errorMessage = "Missing `KeePassFile > Root > Group` node.";
            this.result.success = false;
            return Promise.resolve(this.result);
        }
        this.traverse(rootGroup, true, "");
        if (this.organization) {
            this.moveFoldersToCollections(this.result);
        }
        this.result.success = true;
        return Promise.resolve(this.result);
    }
    traverse(node, isRootNode, groupPrefixName) {
        const folderIndex = this.result.folders.length;
        let groupName = groupPrefixName;
        if (!isRootNode) {
            if (groupName !== "") {
                groupName += "/";
            }
            const nameEl = this.querySelectorDirectChild(node, "Name");
            groupName += nameEl == null ? "-" : nameEl.textContent;
            const folder = new FolderView();
            folder.name = groupName;
            this.result.folders.push(folder);
        }
        this.querySelectorAllDirectChild(node, "Entry").forEach((entry) => {
            const cipherIndex = this.result.ciphers.length;
            const cipher = this.initLoginCipher();
            this.querySelectorAllDirectChild(entry, "String").forEach((entryString) => {
                const valueEl = this.querySelectorDirectChild(entryString, "Value");
                const value = valueEl != null ? valueEl.textContent : null;
                if (this.isNullOrWhitespace(value)) {
                    return;
                }
                const keyEl = this.querySelectorDirectChild(entryString, "Key");
                const key = keyEl != null ? keyEl.textContent : null;
                if (key === "URL") {
                    cipher.login.uris = this.makeUriArray(value);
                }
                else if (key === "UserName") {
                    cipher.login.username = value;
                }
                else if (key === "Password") {
                    cipher.login.password = value;
                }
                else if (key === "otp") {
                    cipher.login.totp = value.replace("key=", "");
                }
                else if (key === "Title") {
                    cipher.name = value;
                }
                else if (key === "Notes") {
                    cipher.notes += value + "\n";
                }
                else {
                    let type = FieldType.Text;
                    const attrs = valueEl.attributes;
                    if (attrs.length > 0 &&
                        attrs.ProtectInMemory != null &&
                        attrs.ProtectInMemory.value === "True") {
                        type = FieldType.Hidden;
                    }
                    this.processKvp(cipher, key, value, type);
                }
            });
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
            if (!isRootNode) {
                this.result.folderRelationships.push([cipherIndex, folderIndex]);
            }
        });
        this.querySelectorAllDirectChild(node, "Group").forEach((group) => {
            this.traverse(group, false, groupName);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/keepassx-csv-importer.ts


class KeePassXCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (this.isNullOrWhitespace(value.Title)) {
                return;
            }
            value.Group =
                !this.isNullOrWhitespace(value.Group) && value.Group.startsWith("Root/")
                    ? value.Group.replace("Root/", "")
                    : value.Group;
            const groupName = !this.isNullOrWhitespace(value.Group) ? value.Group : null;
            this.processFolder(result, groupName);
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value.Notes);
            cipher.name = this.getValueOrDefault(value.Title, "--");
            cipher.login.username = this.getValueOrDefault(value.Username);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.uris = this.makeUriArray(value.URL);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/keeper/keeper-csv-importer.ts


class KeeperCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 6) {
                return;
            }
            this.processFolder(result, value[0]);
            const cipher = this.initLoginCipher();
            const notes = this.getValueOrDefault(value[5]);
            if (notes) {
                cipher.notes = `${notes}\n`;
            }
            cipher.name = this.getValueOrDefault(value[1], "--");
            cipher.login.username = this.getValueOrDefault(value[2]);
            cipher.login.password = this.getValueOrDefault(value[3]);
            cipher.login.uris = this.makeUriArray(value[4]);
            if (value.length > 7) {
                // we have some custom fields.
                for (let i = 7; i < value.length; i = i + 2) {
                    if (value[i] == "TFC:Keeper") {
                        cipher.login.totp = value[i + 1];
                    }
                    else {
                        this.processKvp(cipher, value[i], value[i + 1]);
                    }
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/lastpass-csv-importer.ts










class LastPassCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipherIndex = result.ciphers.length;
            let folderIndex = result.folders.length;
            let grouping = value.grouping;
            if (grouping != null) {
                // eslint-disable-next-line
                grouping = grouping.replace(/\\/g, "/").replace(/[\x00-\x1F\x7F-\x9F]/g, "");
            }
            const hasFolder = this.getValueOrDefault(grouping, "(none)") !== "(none)";
            let addFolder = hasFolder;
            if (hasFolder) {
                for (let i = 0; i < result.folders.length; i++) {
                    if (result.folders[i].name === grouping) {
                        addFolder = false;
                        folderIndex = i;
                        break;
                    }
                }
            }
            const cipher = this.buildBaseCipher(value);
            if (cipher.type === CipherType.Login) {
                cipher.notes = this.getValueOrDefault(value.extra);
                cipher.login = new LoginView();
                cipher.login.uris = this.makeUriArray(value.url);
                cipher.login.username = this.getValueOrDefault(value.username);
                cipher.login.password = this.getValueOrDefault(value.password);
                cipher.login.totp = this.getValueOrDefault(value.totp);
            }
            else if (cipher.type === CipherType.SecureNote) {
                this.parseSecureNote(value, cipher);
            }
            else if (cipher.type === CipherType.Card) {
                cipher.card = this.parseCard(value);
                cipher.notes = this.getValueOrDefault(value.notes);
            }
            else if (cipher.type === CipherType.Identity) {
                cipher.identity = this.parseIdentity(value);
                cipher.notes = this.getValueOrDefault(value.notes);
                if (!this.isNullOrWhitespace(value.ccnum)) {
                    // there is a card on this identity too
                    const cardCipher = this.buildBaseCipher(value);
                    cardCipher.identity = null;
                    cardCipher.type = CipherType.Card;
                    cardCipher.card = this.parseCard(value);
                    result.ciphers.push(cardCipher);
                }
            }
            result.ciphers.push(cipher);
            if (addFolder) {
                const f = new FolderView();
                f.name = grouping;
                result.folders.push(f);
            }
            if (hasFolder) {
                result.folderRelationships.push([cipherIndex, folderIndex]);
            }
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    buildBaseCipher(value) {
        const cipher = new CipherView();
        // eslint-disable-next-line
        if (value.hasOwnProperty("profilename") && value.hasOwnProperty("profilelanguage")) {
            // form fill
            cipher.favorite = false;
            cipher.name = this.getValueOrDefault(value.profilename, "--");
            cipher.type = CipherType.Card;
            if (!this.isNullOrWhitespace(value.title) ||
                !this.isNullOrWhitespace(value.firstname) ||
                !this.isNullOrWhitespace(value.lastname) ||
                !this.isNullOrWhitespace(value.address1) ||
                !this.isNullOrWhitespace(value.phone) ||
                !this.isNullOrWhitespace(value.username) ||
                !this.isNullOrWhitespace(value.email)) {
                cipher.type = CipherType.Identity;
            }
        }
        else {
            // site or secure note
            cipher.favorite = !this.organization && this.getValueOrDefault(value.fav, "0") === "1";
            cipher.name = this.getValueOrDefault(value.name, "--");
            cipher.type = value.url === "http://sn" ? CipherType.SecureNote : CipherType.Login;
        }
        return cipher;
    }
    parseCard(value) {
        const card = new CardView();
        card.cardholderName = this.getValueOrDefault(value.ccname);
        card.number = this.getValueOrDefault(value.ccnum);
        card.code = this.getValueOrDefault(value.cccsc);
        card.brand = this.getCardBrand(value.ccnum);
        if (!this.isNullOrWhitespace(value.ccexp) && value.ccexp.indexOf("-") > -1) {
            const ccexpParts = value.ccexp.split("-");
            if (ccexpParts.length > 1) {
                card.expYear = ccexpParts[0];
                card.expMonth = ccexpParts[1];
                if (card.expMonth.length === 2 && card.expMonth[0] === "0") {
                    card.expMonth = card.expMonth[1];
                }
            }
        }
        return card;
    }
    parseIdentity(value) {
        const identity = new IdentityView();
        identity.title = this.getValueOrDefault(value.title);
        identity.firstName = this.getValueOrDefault(value.firstname);
        identity.middleName = this.getValueOrDefault(value.middlename);
        identity.lastName = this.getValueOrDefault(value.lastname);
        identity.username = this.getValueOrDefault(value.username);
        identity.company = this.getValueOrDefault(value.company);
        identity.ssn = this.getValueOrDefault(value.ssn);
        identity.address1 = this.getValueOrDefault(value.address1);
        identity.address2 = this.getValueOrDefault(value.address2);
        identity.address3 = this.getValueOrDefault(value.address3);
        identity.city = this.getValueOrDefault(value.city);
        identity.state = this.getValueOrDefault(value.state);
        identity.postalCode = this.getValueOrDefault(value.zip);
        identity.country = this.getValueOrDefault(value.country);
        identity.email = this.getValueOrDefault(value.email);
        identity.phone = this.getValueOrDefault(value.phone);
        if (!this.isNullOrWhitespace(identity.title)) {
            identity.title = identity.title.charAt(0).toUpperCase() + identity.title.slice(1);
        }
        return identity;
    }
    parseSecureNote(value, cipher) {
        const extraParts = this.splitNewLine(value.extra);
        let processedNote = false;
        if (extraParts.length) {
            const typeParts = extraParts[0].split(":");
            if (typeParts.length > 1 &&
                typeParts[0] === "NoteType" &&
                (typeParts[1] === "Credit Card" || typeParts[1] === "Address")) {
                if (typeParts[1] === "Credit Card") {
                    const mappedData = this.parseSecureNoteMapping(cipher, extraParts, {
                        Number: "number",
                        "Name on Card": "cardholderName",
                        "Security Code": "code",
                        // LP provides date in a format like 'June,2020'
                        // Store in expMonth, then parse and modify
                        "Expiration Date": "expMonth",
                    });
                    if (this.isNullOrWhitespace(mappedData.expMonth) || mappedData.expMonth === ",") {
                        // No expiration data
                        mappedData.expMonth = undefined;
                    }
                    else {
                        const [monthString, year] = mappedData.expMonth.split(",");
                        // Parse month name into number
                        if (!this.isNullOrWhitespace(monthString)) {
                            const month = new Date(Date.parse(monthString.trim() + " 1, 2012")).getMonth() + 1;
                            if (isNaN(month)) {
                                mappedData.expMonth = undefined;
                            }
                            else {
                                mappedData.expMonth = month.toString();
                            }
                        }
                        else {
                            mappedData.expMonth = undefined;
                        }
                        if (!this.isNullOrWhitespace(year)) {
                            mappedData.expYear = year;
                        }
                    }
                    cipher.type = CipherType.Card;
                    cipher.card = mappedData;
                }
                else if (typeParts[1] === "Address") {
                    const mappedData = this.parseSecureNoteMapping(cipher, extraParts, {
                        Title: "title",
                        "First Name": "firstName",
                        "Last Name": "lastName",
                        "Middle Name": "middleName",
                        Company: "company",
                        "Address 1": "address1",
                        "Address 2": "address2",
                        "Address 3": "address3",
                        "City / Town": "city",
                        State: "state",
                        "Zip / Postal Code": "postalCode",
                        Country: "country",
                        "Email Address": "email",
                        Username: "username",
                    });
                    cipher.type = CipherType.Identity;
                    cipher.identity = mappedData;
                }
                processedNote = true;
            }
        }
        if (!processedNote) {
            cipher.secureNote = new SecureNoteView();
            cipher.secureNote.type = SecureNoteType.Generic;
            cipher.notes = this.getValueOrDefault(value.extra);
        }
    }
    parseSecureNoteMapping(cipher, extraParts, map) {
        const dataObj = {};
        let processingNotes = false;
        extraParts.forEach((extraPart) => {
            let key = null;
            let val = null;
            if (!processingNotes) {
                if (this.isNullOrWhitespace(extraPart)) {
                    return;
                }
                const colonIndex = extraPart.indexOf(":");
                if (colonIndex === -1) {
                    key = extraPart;
                }
                else {
                    key = extraPart.substring(0, colonIndex);
                    if (extraPart.length > colonIndex) {
                        val = extraPart.substring(colonIndex + 1);
                    }
                }
                if (this.isNullOrWhitespace(key) || this.isNullOrWhitespace(val) || key === "NoteType") {
                    return;
                }
            }
            if (processingNotes) {
                cipher.notes += "\n" + extraPart;
            }
            else if (key === "Notes") {
                if (!this.isNullOrWhitespace(cipher.notes)) {
                    cipher.notes += "\n" + val;
                }
                else {
                    cipher.notes = val;
                }
                processingNotes = true;
                // eslint-disable-next-line
            }
            else if (map.hasOwnProperty(key)) {
                dataObj[map[key]] = val;
            }
            else {
                this.processKvp(cipher, key, val);
            }
        });
        return dataObj;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/logmeonce-csv-importer.ts


class LogMeOnceCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 4) {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[0], "--");
            cipher.login.username = this.getValueOrDefault(value[2]);
            cipher.login.password = this.getValueOrDefault(value[3]);
            cipher.login.uris = this.makeUriArray(value[1]);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/meldium-csv-importer.ts


class MeldiumCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.DisplayName, "--");
            cipher.notes = this.getValueOrDefault(value.Notes);
            cipher.login.username = this.getValueOrDefault(value.UserName);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.uris = this.makeUriArray(value.Url);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/msecure-csv-importer.ts





class MSecureCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 3) {
                return;
            }
            const folderName = this.getValueOrDefault(value[0], "Unassigned") !== "Unassigned" ? value[0] : null;
            this.processFolder(result, folderName);
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[2], "--");
            if (value[1] === "Web Logins" || value[1] === "Login") {
                cipher.login.uris = this.makeUriArray(value[4]);
                cipher.login.username = this.getValueOrDefault(value[5]);
                cipher.login.password = this.getValueOrDefault(value[6]);
                cipher.notes = !this.isNullOrWhitespace(value[3]) ? value[3].split("\\n").join("\n") : null;
            }
            else if (value.length > 3) {
                cipher.type = CipherType.SecureNote;
                cipher.secureNote = new SecureNoteView();
                cipher.secureNote.type = SecureNoteType.Generic;
                for (let i = 3; i < value.length; i++) {
                    if (!this.isNullOrWhitespace(value[i])) {
                        cipher.notes += value[i] + "\n";
                    }
                }
            }
            if (!this.isNullOrWhitespace(value[1]) && cipher.type !== CipherType.Login) {
                cipher.name = value[1] + ": " + cipher.name;
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/myki-csv-importer.ts







const mappedBaseColumns = ["nickname", "additionalInfo"];
const _mappedUserAccountColumns = new Set(mappedBaseColumns.concat(["url", "username", "password", "twofaSecret"]));
const _mappedCreditCardColumns = new Set(mappedBaseColumns.concat(["cardNumber", "cardName", "exp_month", "exp_year", "cvv"]));
const _mappedIdentityColumns = new Set(mappedBaseColumns.concat([
    "title",
    "firstName",
    "middleName",
    "lastName",
    "email",
    "firstAddressLine",
    "secondAddressLine",
    "city",
    "country",
    "zipCode",
]));
const _mappedIdCardColumns = new Set(mappedBaseColumns.concat(["idName", "idNumber", "idCountry"]));
const _mappedTwoFaColumns = new Set(mappedBaseColumns.concat(["authToken"]));
const _mappedUserNoteColumns = new Set(mappedBaseColumns.concat(["content"]));
class MykiCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.nickname, "--");
            cipher.notes = this.getValueOrDefault(value.additionalInfo);
            if (value.url !== undefined) {
                // Accounts
                cipher.login.uris = this.makeUriArray(value.url);
                cipher.login.username = this.getValueOrDefault(value.username);
                cipher.login.password = this.getValueOrDefault(value.password);
                cipher.login.totp = this.getValueOrDefault(value.twofaSecret);
                this.importUnmappedFields(cipher, value, _mappedUserAccountColumns);
            }
            else if (value.authToken !== undefined) {
                // TwoFA
                cipher.login.totp = this.getValueOrDefault(value.authToken);
                this.importUnmappedFields(cipher, value, _mappedTwoFaColumns);
            }
            else if (value.cardNumber !== undefined) {
                // Cards
                cipher.card = new CardView();
                cipher.type = CipherType.Card;
                cipher.card.cardholderName = this.getValueOrDefault(value.cardName);
                cipher.card.number = this.getValueOrDefault(value.cardNumber);
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                cipher.card.expMonth = this.getValueOrDefault(value.exp_month);
                cipher.card.expYear = this.getValueOrDefault(value.exp_year);
                cipher.card.code = this.getValueOrDefault(value.cvv);
                this.importUnmappedFields(cipher, value, _mappedCreditCardColumns);
            }
            else if (value.firstName !== undefined) {
                // Identities
                cipher.identity = new IdentityView();
                cipher.type = CipherType.Identity;
                cipher.identity.title = this.getValueOrDefault(value.title);
                cipher.identity.firstName = this.getValueOrDefault(value.firstName);
                cipher.identity.middleName = this.getValueOrDefault(value.middleName);
                cipher.identity.lastName = this.getValueOrDefault(value.lastName);
                cipher.identity.phone = this.getValueOrDefault(value.number);
                cipher.identity.email = this.getValueOrDefault(value.email);
                cipher.identity.address1 = this.getValueOrDefault(value.firstAddressLine);
                cipher.identity.address2 = this.getValueOrDefault(value.secondAddressLine);
                cipher.identity.city = this.getValueOrDefault(value.city);
                cipher.identity.country = this.getValueOrDefault(value.country);
                cipher.identity.postalCode = this.getValueOrDefault(value.zipCode);
                this.importUnmappedFields(cipher, value, _mappedIdentityColumns);
            }
            else if (value.idType !== undefined) {
                // IdCards
                cipher.identity = new IdentityView();
                cipher.type = CipherType.Identity;
                this.processFullName(cipher, value.idName);
                cipher.identity.country = this.getValueOrDefault(value.idCountry);
                switch (value.idType) {
                    // case "Driver's License":
                    // case "ID Card":
                    // case "Outdoor License":
                    // case "Software License":
                    // case "Tax Number":
                    // case "Bank Account":
                    // case "Insurance Card":
                    // case "Health Card":
                    // case "Membership":
                    // case "Database":
                    // case "Reward Program":
                    // case "Tour Visa":
                    case "Passport":
                        cipher.identity.passportNumber = value.idNumber;
                        break;
                    case "Social Security":
                        cipher.identity.ssn = value.idNumber;
                        break;
                    default:
                        cipher.identity.licenseNumber = value.idNumber;
                        break;
                }
                this.importUnmappedFields(cipher, value, _mappedIdCardColumns);
            }
            else if (value.content !== undefined) {
                // Notes
                cipher.secureNote = new SecureNoteView();
                cipher.type = CipherType.SecureNote;
                cipher.secureNote.type = SecureNoteType.Generic;
                cipher.notes = this.getValueOrDefault(value.content);
                this.importUnmappedFields(cipher, value, _mappedUserNoteColumns);
            }
            else {
                return;
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
    importUnmappedFields(cipher, row, mappedValues) {
        const unmappedFields = Object.keys(row).filter((x) => !mappedValues.has(x));
        unmappedFields.forEach((key) => {
            const item = row;
            this.processKvp(cipher, key, item[key]);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/nordpass-csv-importer.ts






class NordPassCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((record) => {
            const recordType = this.evaluateType(record);
            if (recordType === undefined) {
                return;
            }
            if (!this.organization) {
                this.processFolder(result, record.folder);
            }
            const cipher = new CipherView();
            cipher.name = this.getValueOrDefault(record.name, "--");
            cipher.notes = this.getValueOrDefault(record.note);
            switch (recordType) {
                case CipherType.Login:
                    cipher.type = CipherType.Login;
                    cipher.login = new LoginView();
                    cipher.login.username = this.getValueOrDefault(record.username);
                    cipher.login.password = this.getValueOrDefault(record.password);
                    cipher.login.uris = this.makeUriArray(record.url);
                    break;
                case CipherType.Card:
                    cipher.type = CipherType.Card;
                    cipher.card.cardholderName = this.getValueOrDefault(record.cardholdername);
                    cipher.card.number = this.getValueOrDefault(record.cardnumber);
                    cipher.card.code = this.getValueOrDefault(record.cvc);
                    cipher.card.brand = this.getCardBrand(cipher.card.number);
                    this.setCardExpiration(cipher, record.expirydate);
                    break;
                case CipherType.Identity:
                    cipher.type = CipherType.Identity;
                    this.processFullName(cipher, this.getValueOrDefault(record.full_name));
                    cipher.identity.address1 = this.getValueOrDefault(record.address1);
                    cipher.identity.address2 = this.getValueOrDefault(record.address2);
                    cipher.identity.city = this.getValueOrDefault(record.city);
                    cipher.identity.state = this.getValueOrDefault(record.state);
                    cipher.identity.postalCode = this.getValueOrDefault(record.zipcode);
                    cipher.identity.country = this.getValueOrDefault(record.country);
                    if (cipher.identity.country != null) {
                        cipher.identity.country = cipher.identity.country.toUpperCase();
                    }
                    cipher.identity.email = this.getValueOrDefault(record.email);
                    cipher.identity.phone = this.getValueOrDefault(record.phone_number);
                    break;
                case CipherType.SecureNote:
                    cipher.type = CipherType.SecureNote;
                    cipher.secureNote.type = SecureNoteType.Generic;
                    break;
                default:
                    break;
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    evaluateType(record) {
        if (!this.isNullOrWhitespace(record.username)) {
            return CipherType.Login;
        }
        if (!this.isNullOrWhitespace(record.cardnumber)) {
            return CipherType.Card;
        }
        if (!this.isNullOrWhitespace(record.full_name)) {
            return CipherType.Identity;
        }
        if (!this.isNullOrWhitespace(record.note)) {
            return CipherType.SecureNote;
        }
        return undefined;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/onepassword-1pif-importer.ts









class OnePassword1PifImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.result = new ImportResult();
    }
    parse(data) {
        data.split(this.newLineRegex).forEach((line) => {
            if (this.isNullOrWhitespace(line) || line[0] !== "{") {
                return;
            }
            const item = JSON.parse(line);
            if (item.trashed === true) {
                return;
            }
            const cipher = this.initLoginCipher();
            if (this.isNullOrWhitespace(item.hmac)) {
                this.processStandardItem(item, cipher);
            }
            else {
                this.processWinOpVaultItem(item, cipher);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            this.result.ciphers.push(cipher);
        });
        this.result.success = true;
        return Promise.resolve(this.result);
    }
    processWinOpVaultItem(item, cipher) {
        if (item.overview != null) {
            cipher.name = this.getValueOrDefault(item.overview.title);
            if (item.overview.URLs != null) {
                const urls = [];
                item.overview.URLs.forEach((url) => {
                    if (!this.isNullOrWhitespace(url.u)) {
                        urls.push(url.u);
                    }
                });
                cipher.login.uris = this.makeUriArray(urls);
            }
        }
        if (item.details != null) {
            if (item.details.passwordHistory != null) {
                this.parsePasswordHistory(item.details.passwordHistory, cipher);
            }
            if (!this.isNullOrWhitespace(item.details.ccnum) ||
                !this.isNullOrWhitespace(item.details.cvv)) {
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
            }
            else if (!this.isNullOrWhitespace(item.details.firstname) ||
                !this.isNullOrWhitespace(item.details.address1)) {
                cipher.type = CipherType.Identity;
                cipher.identity = new IdentityView();
            }
            if (cipher.type === CipherType.Login && !this.isNullOrWhitespace(item.details.password)) {
                cipher.login.password = item.details.password;
            }
            if (!this.isNullOrWhitespace(item.details.notesPlain)) {
                cipher.notes = item.details.notesPlain.split(this.newLineRegex).join("\n") + "\n";
            }
            if (item.details.fields != null) {
                this.parseFields(item.details.fields, cipher, "designation", "value", "name");
            }
            if (item.details.sections != null) {
                item.details.sections.forEach((section) => {
                    if (section.fields != null) {
                        this.parseFields(section.fields, cipher, "n", "v", "t");
                    }
                });
            }
        }
    }
    processStandardItem(item, cipher) {
        cipher.favorite = item.openContents && item.openContents.faveIndex ? true : false;
        cipher.name = this.getValueOrDefault(item.title);
        if (item.typeName === "securenotes.SecureNote") {
            cipher.type = CipherType.SecureNote;
            cipher.secureNote = new SecureNoteView();
            cipher.secureNote.type = SecureNoteType.Generic;
        }
        else if (item.typeName === "wallet.financial.CreditCard") {
            cipher.type = CipherType.Card;
            cipher.card = new CardView();
        }
        else if (item.typeName === "identities.Identity") {
            cipher.type = CipherType.Identity;
            cipher.identity = new IdentityView();
        }
        else {
            cipher.login.uris = this.makeUriArray(item.location);
        }
        if (item.secureContents != null) {
            if (item.secureContents.passwordHistory != null) {
                this.parsePasswordHistory(item.secureContents.passwordHistory, cipher);
            }
            if (!this.isNullOrWhitespace(item.secureContents.notesPlain)) {
                cipher.notes = item.secureContents.notesPlain.split(this.newLineRegex).join("\n") + "\n";
            }
            if (cipher.type === CipherType.Login) {
                if (!this.isNullOrWhitespace(item.secureContents.password)) {
                    cipher.login.password = item.secureContents.password;
                }
                if (item.secureContents.URLs != null) {
                    const urls = [];
                    item.secureContents.URLs.forEach((u) => {
                        if (!this.isNullOrWhitespace(u.url)) {
                            urls.push(u.url);
                        }
                    });
                    if (urls.length > 0) {
                        cipher.login.uris = this.makeUriArray(urls);
                    }
                }
            }
            if (item.secureContents.fields != null) {
                this.parseFields(item.secureContents.fields, cipher, "designation", "value", "name");
            }
            if (item.secureContents.sections != null) {
                item.secureContents.sections.forEach((section) => {
                    if (section.fields != null) {
                        this.parseFields(section.fields, cipher, "n", "v", "t");
                    }
                });
            }
        }
    }
    parsePasswordHistory(items, cipher) {
        const maxSize = items.length > 5 ? 5 : items.length;
        cipher.passwordHistory = items
            .filter((h) => !this.isNullOrWhitespace(h.value) && h.time != null)
            .sort((a, b) => b.time - a.time)
            .slice(0, maxSize)
            .map((h) => {
            const ph = new PasswordHistoryView();
            ph.password = h.value;
            ph.lastUsedDate = new Date(("" + h.time).length >= 13 ? h.time : h.time * 1000);
            return ph;
        });
    }
    parseFields(fields, cipher, designationKey, valueKey, nameKey) {
        fields.forEach((field) => {
            if (field[valueKey] == null || field[valueKey].toString().trim() === "") {
                return;
            }
            // TODO: when date FieldType exists, store this as a date field type instead of formatted Text if k is 'date'
            const fieldValue = field.k === "date"
                ? new Date(field[valueKey] * 1000).toUTCString()
                : field[valueKey].toString();
            const fieldDesignation = field[designationKey] != null ? field[designationKey].toString() : null;
            if (cipher.type === CipherType.Login) {
                if (this.isNullOrWhitespace(cipher.login.username) && fieldDesignation === "username") {
                    cipher.login.username = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(cipher.login.password) &&
                    fieldDesignation === "password") {
                    cipher.login.password = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(cipher.login.totp) &&
                    fieldDesignation != null &&
                    fieldDesignation.startsWith("TOTP_")) {
                    cipher.login.totp = fieldValue;
                    return;
                }
            }
            else if (cipher.type === CipherType.Card) {
                if (this.isNullOrWhitespace(cipher.card.number) && fieldDesignation === "ccnum") {
                    cipher.card.number = fieldValue;
                    cipher.card.brand = this.getCardBrand(fieldValue);
                    return;
                }
                else if (this.isNullOrWhitespace(cipher.card.code) && fieldDesignation === "cvv") {
                    cipher.card.code = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(cipher.card.cardholderName) &&
                    fieldDesignation === "cardholder") {
                    cipher.card.cardholderName = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(cipher.card.expiration) &&
                    fieldDesignation === "expiry" &&
                    fieldValue.length === 6) {
                    cipher.card.expMonth = fieldValue.substr(4, 2);
                    if (cipher.card.expMonth[0] === "0") {
                        cipher.card.expMonth = cipher.card.expMonth.substr(1, 1);
                    }
                    cipher.card.expYear = fieldValue.substr(0, 4);
                    return;
                }
                else if (fieldDesignation === "type") {
                    // Skip since brand was determined from number above
                    return;
                }
            }
            else if (cipher.type === CipherType.Identity) {
                const identity = cipher.identity;
                if (this.isNullOrWhitespace(identity.firstName) && fieldDesignation === "firstname") {
                    identity.firstName = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.lastName) && fieldDesignation === "lastname") {
                    identity.lastName = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.middleName) && fieldDesignation === "initial") {
                    identity.middleName = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.phone) && fieldDesignation === "defphone") {
                    identity.phone = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.company) && fieldDesignation === "company") {
                    identity.company = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.email) && fieldDesignation === "email") {
                    identity.email = fieldValue;
                    return;
                }
                else if (this.isNullOrWhitespace(identity.username) && fieldDesignation === "username") {
                    identity.username = fieldValue;
                    return;
                }
                else if (fieldDesignation === "address") {
                    // fieldValue is an object casted into a string, so access the plain value instead
                    const { street, city, country, zip } = field[valueKey];
                    identity.address1 = this.getValueOrDefault(street);
                    identity.city = this.getValueOrDefault(city);
                    if (!this.isNullOrWhitespace(country)) {
                        identity.country = country.toUpperCase();
                    }
                    identity.postalCode = this.getValueOrDefault(zip);
                    return;
                }
            }
            const fieldName = this.isNullOrWhitespace(field[nameKey]) ? "no_name" : field[nameKey];
            if (fieldName === "password" &&
                cipher.passwordHistory != null &&
                cipher.passwordHistory.some((h) => h.password === fieldValue)) {
                return;
            }
            const fieldType = field.k === "concealed" ? FieldType.Hidden : FieldType.Text;
            this.processKvp(cipher, fieldName, fieldValue, fieldType);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/types/onepassword-1pux-importer-types.ts
var CategoryEnum;
(function (CategoryEnum) {
    CategoryEnum["Login"] = "001";
    CategoryEnum["CreditCard"] = "002";
    CategoryEnum["SecureNote"] = "003";
    CategoryEnum["Identity"] = "004";
    CategoryEnum["Password"] = "005";
    CategoryEnum["Document"] = "006";
    CategoryEnum["SoftwareLicense"] = "100";
    CategoryEnum["BankAccount"] = "101";
    CategoryEnum["Database"] = "102";
    CategoryEnum["DriversLicense"] = "103";
    CategoryEnum["OutdoorLicense"] = "104";
    CategoryEnum["Membership"] = "105";
    CategoryEnum["Passport"] = "106";
    CategoryEnum["RewardsProgram"] = "107";
    CategoryEnum["SocialSecurityNumber"] = "108";
    CategoryEnum["WirelessRouter"] = "109";
    CategoryEnum["Server"] = "110";
    CategoryEnum["EmailAccount"] = "111";
    CategoryEnum["API_Credential"] = "112";
    CategoryEnum["MedicalRecord"] = "113";
})(CategoryEnum || (CategoryEnum = {}));
var LoginFieldTypeEnum;
(function (LoginFieldTypeEnum) {
    LoginFieldTypeEnum["TextOrHtml"] = "T";
    LoginFieldTypeEnum["EmailAddress"] = "E";
    LoginFieldTypeEnum["URL"] = "U";
    LoginFieldTypeEnum["Number"] = "N";
    LoginFieldTypeEnum["Password"] = "P";
    LoginFieldTypeEnum["TextArea"] = "A";
    LoginFieldTypeEnum["PhoneNumber"] = "T";
    LoginFieldTypeEnum["CheckBox"] = "C";
})(LoginFieldTypeEnum || (LoginFieldTypeEnum = {}));

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/onepassword-1pux-importer.ts












class OnePassword1PuxImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.result = new ImportResult();
    }
    parse(data) {
        const exportData = JSON.parse(data);
        const account = exportData.accounts[0];
        // TODO Add handling of multiple vaults
        // const personalVaults = account.vaults[0].filter((v) => v.attrs.type === VaultAttributeTypeEnum.Personal);
        account.vaults.forEach((vault) => {
            vault.items.forEach((item) => {
                if (item.trashed === true) {
                    return;
                }
                const cipher = this.initLoginCipher();
                const category = item.categoryUuid;
                switch (category) {
                    case CategoryEnum.Login:
                    case CategoryEnum.Database:
                    case CategoryEnum.Password:
                    case CategoryEnum.WirelessRouter:
                    case CategoryEnum.Server:
                    case CategoryEnum.API_Credential:
                        cipher.type = CipherType.Login;
                        cipher.login = new LoginView();
                        break;
                    case CategoryEnum.CreditCard:
                    case CategoryEnum.BankAccount:
                        cipher.type = CipherType.Card;
                        cipher.card = new CardView();
                        break;
                    case CategoryEnum.SecureNote:
                    case CategoryEnum.SoftwareLicense:
                    case CategoryEnum.EmailAccount:
                    case CategoryEnum.MedicalRecord:
                        // case CategoryEnum.Document:
                        cipher.type = CipherType.SecureNote;
                        cipher.secureNote = new SecureNoteView();
                        cipher.secureNote.type = SecureNoteType.Generic;
                        break;
                    case CategoryEnum.Identity:
                    case CategoryEnum.DriversLicense:
                    case CategoryEnum.OutdoorLicense:
                    case CategoryEnum.Membership:
                    case CategoryEnum.Passport:
                    case CategoryEnum.RewardsProgram:
                    case CategoryEnum.SocialSecurityNumber:
                        cipher.type = CipherType.Identity;
                        cipher.identity = new IdentityView();
                        break;
                    default:
                        break;
                }
                cipher.favorite = item.favIndex === 1 ? true : false;
                this.processOverview(item.overview, cipher);
                this.processLoginFields(item, cipher);
                this.processDetails(category, item.details, cipher);
                this.parsePasswordHistory(item.details.passwordHistory, cipher);
                this.processSections(category, item.details.sections, cipher);
                if (!this.isNullOrWhitespace(item.details.notesPlain)) {
                    cipher.notes = item.details.notesPlain.split(this.newLineRegex).join("\n") + "\n";
                }
                this.convertToNoteIfNeeded(cipher);
                this.cleanupCipher(cipher);
                this.result.ciphers.push(cipher);
            });
        });
        if (this.organization) {
            this.moveFoldersToCollections(this.result);
        }
        this.result.success = true;
        return Promise.resolve(this.result);
    }
    processOverview(overview, cipher) {
        if (overview == null) {
            return;
        }
        cipher.name = this.getValueOrDefault(overview.title);
        if (overview.urls != null) {
            const urls = [];
            overview.urls.forEach((url) => {
                if (!this.isNullOrWhitespace(url.url)) {
                    urls.push(url.url);
                }
            });
            cipher.login.uris = this.makeUriArray(urls);
        }
        if (overview.tags != null && overview.tags.length > 0) {
            const folderName = this.capitalize(overview.tags[0]);
            this.processFolder(this.result, folderName);
        }
    }
    capitalize(inputString) {
        return inputString.trim().replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase()));
    }
    processLoginFields(item, cipher) {
        if (item.details == null) {
            return;
        }
        if (item.details.loginFields == null || item.details.loginFields.length === 0) {
            return;
        }
        item.details.loginFields.forEach((loginField) => {
            if (loginField.designation === "username" && loginField.value !== "") {
                cipher.type = CipherType.Login;
                cipher.login.username = loginField.value;
                return;
            }
            if (loginField.designation === "password" && loginField.value !== "") {
                cipher.type = CipherType.Login;
                cipher.login.password = loginField.value;
                return;
            }
            let fieldValue = loginField.value;
            let fieldType = FieldType.Text;
            switch (loginField.fieldType) {
                case LoginFieldTypeEnum.Password:
                    fieldType = FieldType.Hidden;
                    break;
                case LoginFieldTypeEnum.CheckBox:
                    fieldValue = loginField.value !== "" ? "true" : "false";
                    fieldType = FieldType.Boolean;
                    break;
                default:
                    break;
            }
            this.processKvp(cipher, loginField.name, fieldValue, fieldType);
        });
    }
    processDetails(category, details, cipher) {
        if (category !== CategoryEnum.Password) {
            return;
        }
        if (details == null) {
            return;
        }
        cipher.login.password = details.password;
    }
    processSections(category, sections, cipher) {
        if (sections == null || sections.length === 0) {
            return;
        }
        sections.forEach((section) => {
            if (section.fields == null) {
                return;
            }
            this.parseSectionFields(category, section.fields, cipher);
        });
    }
    parseSectionFields(category, fields, cipher) {
        fields.forEach((field) => {
            const valueKey = Object.keys(field.value)[0];
            const anyField = field;
            if (anyField.value == null ||
                anyField.value[valueKey] == null ||
                anyField.value[valueKey] === "") {
                return;
            }
            const fieldName = this.getFieldName(field.id, field.title);
            const fieldValue = this.extractValue(field.value, valueKey);
            if (cipher.type === CipherType.Login) {
                if (this.fillLogin(field, fieldValue, cipher)) {
                    return;
                }
                switch (category) {
                    case CategoryEnum.Login:
                    case CategoryEnum.Database:
                    case CategoryEnum.EmailAccount:
                    case CategoryEnum.WirelessRouter:
                        break;
                    case CategoryEnum.Server:
                        if (this.isNullOrWhitespace(cipher.login.uri) && field.id === "url") {
                            cipher.login.uris = this.makeUriArray(fieldValue);
                            return;
                        }
                        break;
                    case CategoryEnum.API_Credential:
                        if (this.fillApiCredentials(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    default:
                        break;
                }
            }
            else if (cipher.type === CipherType.Card) {
                if (this.fillCreditCard(field, fieldValue, cipher)) {
                    return;
                }
                if (category === CategoryEnum.BankAccount) {
                    if (this.fillBankAccount(field, fieldValue, cipher)) {
                        return;
                    }
                }
            }
            else if (cipher.type === CipherType.Identity) {
                if (this.fillIdentity(field, fieldValue, cipher, valueKey)) {
                    return;
                }
                if (valueKey === "address") {
                    // fieldValue is an object casted into a string, so access the plain value instead
                    const { street, city, country, zip, state } = field.value.address;
                    cipher.identity.address1 = this.getValueOrDefault(street);
                    cipher.identity.city = this.getValueOrDefault(city);
                    if (!this.isNullOrWhitespace(country)) {
                        cipher.identity.country = country.toUpperCase();
                    }
                    cipher.identity.postalCode = this.getValueOrDefault(zip);
                    cipher.identity.state = this.getValueOrDefault(state);
                    return;
                }
                switch (category) {
                    case CategoryEnum.Identity:
                        break;
                    case CategoryEnum.DriversLicense:
                        if (this.fillDriversLicense(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    case CategoryEnum.OutdoorLicense:
                        if (this.fillOutdoorLicense(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    case CategoryEnum.Membership:
                        if (this.fillMembership(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    case CategoryEnum.Passport:
                        if (this.fillPassport(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    case CategoryEnum.RewardsProgram:
                        if (this.fillRewardsProgram(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    case CategoryEnum.SocialSecurityNumber:
                        if (this.fillSSN(field, fieldValue, cipher)) {
                            return;
                        }
                        break;
                    default:
                        break;
                }
            }
            if (valueKey === "email") {
                // fieldValue is an object casted into a string, so access the plain value instead
                const { email_address, provider } = field.value.email;
                this.processKvp(cipher, fieldName, email_address, FieldType.Text);
                this.processKvp(cipher, "provider", provider, FieldType.Text);
                return;
            }
            // Do not include a password field if it's already in the history
            if (field.title === "password" &&
                cipher.passwordHistory != null &&
                cipher.passwordHistory.some((h) => h.password === fieldValue)) {
                return;
            }
            // TODO ?? If one of the fields is marked as guarded, then activate Password-Reprompt for the entire item
            if (field.guarded && cipher.reprompt === CipherRepromptType.None) {
                cipher.reprompt = CipherRepromptType.Password;
            }
            const fieldType = valueKey === "concealed" ? FieldType.Hidden : FieldType.Text;
            this.processKvp(cipher, fieldName, fieldValue, fieldType);
        });
    }
    getFieldName(id, title) {
        if (this.isNullOrWhitespace(title)) {
            return id;
        }
        // Naive approach of checking if the fields id is usable
        if (id.length > 25 && RegExp(/[0-9]{2}[A-Z]{2}/, "i").test(id)) {
            return title;
        }
        return id;
    }
    extractValue(value, valueKey) {
        if (valueKey === "date") {
            return new Date(value.date * 1000).toUTCString();
        }
        if (valueKey === "monthYear") {
            return value.monthYear.toString();
        }
        return value[valueKey];
    }
    fillLogin(field, fieldValue, cipher) {
        const fieldName = this.getFieldName(field.id, field.title);
        if (this.isNullOrWhitespace(cipher.login.username) && fieldName === "username") {
            cipher.login.username = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.login.password) && fieldName === "password") {
            cipher.login.password = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.login.totp) &&
            field.id != null &&
            field.id.startsWith("TOTP_")) {
            cipher.login.totp = fieldValue;
            return true;
        }
        return false;
    }
    fillApiCredentials(field, fieldValue, cipher) {
        const fieldName = this.getFieldName(field.id, field.title);
        if (this.isNullOrWhitespace(cipher.login.password) && fieldName === "credential") {
            cipher.login.password = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.login.uri) && fieldName === "hostname") {
            cipher.login.uris = this.makeUriArray(fieldValue);
            return true;
        }
        return false;
    }
    fillCreditCard(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.card.number) && field.id === "ccnum") {
            cipher.card.number = fieldValue;
            cipher.card.brand = this.getCardBrand(fieldValue);
            return true;
        }
        if (this.isNullOrWhitespace(cipher.card.code) && field.id === "cvv") {
            cipher.card.code = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.card.cardholderName) && field.id === "cardholder") {
            cipher.card.cardholderName = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.card.expiration) && field.id === "expiry") {
            const monthYear = fieldValue.toString().trim();
            cipher.card.expMonth = monthYear.substring(4, 6);
            if (cipher.card.expMonth[0] === "0") {
                cipher.card.expMonth = cipher.card.expMonth.substring(1, 2);
            }
            cipher.card.expYear = monthYear.substring(0, 4);
            return true;
        }
        if (field.id === "type") {
            // Skip since brand was determined from number above
            return true;
        }
        return false;
    }
    fillBankAccount(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.card.cardholderName) && field.id === "owner") {
            cipher.card.cardholderName = fieldValue;
            return true;
        }
        return false;
    }
    fillIdentity(field, fieldValue, cipher, valueKey) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "firstname") {
            cipher.identity.firstName = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.lastName) && field.id === "lastname") {
            cipher.identity.lastName = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.middleName) && field.id === "initial") {
            cipher.identity.middleName = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.phone) && field.id === "defphone") {
            cipher.identity.phone = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.company) && field.id === "company") {
            cipher.identity.company = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.email)) {
            if (valueKey === "email") {
                const { email_address, provider } = field.value.email;
                cipher.identity.email = this.getValueOrDefault(email_address);
                this.processKvp(cipher, "provider", provider, FieldType.Text);
                return true;
            }
            if (field.id === "email") {
                cipher.identity.email = fieldValue;
                return true;
            }
        }
        if (this.isNullOrWhitespace(cipher.identity.username) && field.id === "username") {
            cipher.identity.username = fieldValue;
            return true;
        }
        return false;
    }
    fillDriversLicense(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "fullname") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.address1) && field.id === "address") {
            cipher.identity.address1 = fieldValue;
            return true;
        }
        // TODO ISO code
        if (this.isNullOrWhitespace(cipher.identity.country) && field.id === "country") {
            cipher.identity.country = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.state) && field.id === "state") {
            cipher.identity.state = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.licenseNumber) && field.id === "number") {
            cipher.identity.licenseNumber = fieldValue;
            return true;
        }
        return false;
    }
    fillOutdoorLicense(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "name") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        // TODO ISO code
        if (this.isNullOrWhitespace(cipher.identity.country) && field.id === "country") {
            cipher.identity.country = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.state) && field.id === "state") {
            cipher.identity.state = fieldValue;
            return true;
        }
        return false;
    }
    fillMembership(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "member_name") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.company) && field.id === "org_name") {
            cipher.identity.company = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.phone) && field.id === "phone") {
            cipher.identity.phone = fieldValue;
            return true;
        }
        return false;
    }
    fillPassport(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "fullname") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        // TODO Iso
        if (this.isNullOrWhitespace(cipher.identity.country) && field.id === "issuing_country") {
            cipher.identity.country = fieldValue;
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.passportNumber) && field.id === "number") {
            cipher.identity.passportNumber = fieldValue;
            return true;
        }
        return false;
    }
    fillRewardsProgram(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "member_name") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.company) && field.id === "company_name") {
            cipher.identity.company = fieldValue;
            return true;
        }
        return false;
    }
    fillSSN(field, fieldValue, cipher) {
        if (this.isNullOrWhitespace(cipher.identity.firstName) && field.id === "name") {
            this.processFullName(cipher, fieldValue);
            return true;
        }
        if (this.isNullOrWhitespace(cipher.identity.ssn) && field.id === "number") {
            cipher.identity.ssn = fieldValue;
            return true;
        }
        return false;
    }
    parsePasswordHistory(historyItems, cipher) {
        if (historyItems == null || historyItems.length === 0) {
            return;
        }
        const maxSize = historyItems.length > 5 ? 5 : historyItems.length;
        cipher.passwordHistory = historyItems
            .filter((h) => !this.isNullOrWhitespace(h.value) && h.time != null)
            .sort((a, b) => b.time - a.time)
            .slice(0, maxSize)
            .map((h) => {
            const ph = new PasswordHistoryView();
            ph.password = h.value;
            ph.lastUsedDate = new Date(("" + h.time).length >= 13 ? h.time : h.time * 1000);
            return ph;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/cipher-import-context.ts
class CipherImportContext {
    constructor(importRecord, property, cipher) {
        this.importRecord = importRecord;
        this.property = property;
        this.cipher = cipher;
        this.lowerProperty = property.toLowerCase();
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/onepassword-csv-importer.ts





const IgnoredProperties = [
    "ainfo",
    "autosubmit",
    "notesplain",
    "ps",
    "scope",
    "tags",
    "title",
    "uuid",
    "notes",
];
class OnePasswordCsvImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.loginPropertyParsers = [
            this.setLoginUsername,
            this.setLoginPassword,
            this.setLoginUris,
        ];
        this.creditCardPropertyParsers = [
            this.setCreditCardNumber,
            this.setCreditCardVerification,
            this.setCreditCardCardholderName,
            this.setCreditCardExpiry,
        ];
        this.identityPropertyParsers = [
            this.setIdentityFirstName,
            this.setIdentityInitial,
            this.setIdentityLastName,
            this.setIdentityUserName,
            this.setIdentityEmail,
            this.setIdentityPhone,
            this.setIdentityCompany,
        ];
    }
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true, {
            quoteChar: '"',
            escapeChar: "\\",
        });
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (this.isNullOrWhitespace(this.getProp(value, "title"))) {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(this.getProp(value, "title"), "--");
            this.setNotes(value, cipher);
            this.setCipherType(value, cipher);
            let altUsername = null;
            for (const property in value) {
                // eslint-disable-next-line
                if (!value.hasOwnProperty(property) || this.isNullOrWhitespace(value[property])) {
                    continue;
                }
                const context = new CipherImportContext(value, property, cipher);
                if (cipher.type === CipherType.Login && this.setKnownLoginValue(context)) {
                    continue;
                }
                else if (cipher.type === CipherType.Card && this.setKnownCreditCardValue(context)) {
                    continue;
                }
                else if (cipher.type === CipherType.Identity && this.setKnownIdentityValue(context)) {
                    continue;
                }
                altUsername = this.setUnknownValue(context, altUsername);
            }
            if (cipher.type === CipherType.Login &&
                !this.isNullOrWhitespace(altUsername) &&
                this.isNullOrWhitespace(cipher.login.username) &&
                altUsername.indexOf("://") === -1) {
                cipher.login.username = altUsername;
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
    getProp(obj, name) {
        const lowerObj = Object.entries(obj).reduce((agg, entry) => {
            agg[entry[0].toLowerCase()] = entry[1];
            return agg;
        }, {});
        return lowerObj[name.toLowerCase()];
    }
    getPropByRegexp(obj, regexp) {
        const matchingKeys = Object.keys(obj).reduce((agg, key) => {
            if (key.match(regexp)) {
                agg.push(key);
            }
            return agg;
        }, []);
        if (matchingKeys.length === 0) {
            return null;
        }
        else {
            return obj[matchingKeys[0]];
        }
    }
    getPropIncluding(obj, name) {
        const includesMap = Object.keys(obj).reduce((agg, entry) => {
            if (entry.toLowerCase().includes(name.toLowerCase())) {
                agg.push(entry);
            }
            return agg;
        }, []);
        if (includesMap.length === 0) {
            return null;
        }
        else {
            return obj[includesMap[0]];
        }
    }
    setNotes(importRecord, cipher) {
        cipher.notes =
            this.getValueOrDefault(this.getProp(importRecord, "notesPlain"), "") +
                "\n" +
                this.getValueOrDefault(this.getProp(importRecord, "notes"), "") +
                "\n";
        cipher.notes.trim();
    }
    setKnownLoginValue(context) {
        return this.loginPropertyParsers.reduce((agg, func) => {
            if (!agg) {
                agg = func.bind(this)(context);
            }
            return agg;
        }, false);
    }
    setKnownCreditCardValue(context) {
        return this.creditCardPropertyParsers.reduce((agg, func) => {
            if (!agg) {
                agg = func.bind(this)(context);
            }
            return agg;
        }, false);
    }
    setKnownIdentityValue(context) {
        return this.identityPropertyParsers.reduce((agg, func) => {
            if (!agg) {
                agg = func.bind(this)(context);
            }
            return agg;
        }, false);
    }
    setUnknownValue(context, altUsername) {
        if (IgnoredProperties.indexOf(context.lowerProperty) === -1 &&
            !context.lowerProperty.startsWith("section:") &&
            !context.lowerProperty.startsWith("section ")) {
            if (altUsername == null && context.lowerProperty === "email") {
                return context.importRecord[context.property];
            }
            else if (context.lowerProperty === "created date" ||
                context.lowerProperty === "modified date") {
                const readableDate = new Date(parseInt(context.importRecord[context.property], 10) * 1000).toUTCString();
                this.processKvp(context.cipher, "1Password " + context.property, readableDate);
                return null;
            }
            if (context.lowerProperty.includes("password") ||
                context.lowerProperty.includes("key") ||
                context.lowerProperty.includes("secret")) {
                this.processKvp(context.cipher, context.property, context.importRecord[context.property], FieldType.Hidden);
            }
            else {
                this.processKvp(context.cipher, context.property, context.importRecord[context.property]);
            }
        }
        return null;
    }
    setIdentityFirstName(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.firstName) &&
            context.lowerProperty.includes("first name")) {
            context.cipher.identity.firstName = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityInitial(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.middleName) &&
            context.lowerProperty.includes("initial")) {
            context.cipher.identity.middleName = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityLastName(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.lastName) &&
            context.lowerProperty.includes("last name")) {
            context.cipher.identity.lastName = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityUserName(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.username) &&
            context.lowerProperty.includes("username")) {
            context.cipher.identity.username = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityCompany(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.company) &&
            context.lowerProperty.includes("company")) {
            context.cipher.identity.company = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityPhone(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.phone) &&
            context.lowerProperty.includes("default phone")) {
            context.cipher.identity.phone = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setIdentityEmail(context) {
        if (this.isNullOrWhitespace(context.cipher.identity.email) &&
            context.lowerProperty.includes("email")) {
            context.cipher.identity.email = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setCreditCardNumber(context) {
        if (this.isNullOrWhitespace(context.cipher.card.number) &&
            context.lowerProperty.includes("number")) {
            context.cipher.card.number = context.importRecord[context.property];
            context.cipher.card.brand = this.getCardBrand(context.cipher.card.number);
            return true;
        }
        return false;
    }
    setCreditCardVerification(context) {
        if (this.isNullOrWhitespace(context.cipher.card.code) &&
            context.lowerProperty.includes("verification number")) {
            context.cipher.card.code = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setCreditCardCardholderName(context) {
        if (this.isNullOrWhitespace(context.cipher.card.cardholderName) &&
            context.lowerProperty.includes("cardholder name")) {
            context.cipher.card.cardholderName = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setCreditCardExpiry(context) {
        if (this.isNullOrWhitespace(context.cipher.card.expiration) &&
            context.lowerProperty.includes("expiry date") &&
            context.importRecord[context.property].length === 7) {
            context.cipher.card.expMonth = context.importRecord[context.property].substr(0, 2);
            if (context.cipher.card.expMonth[0] === "0") {
                context.cipher.card.expMonth = context.cipher.card.expMonth.substr(1, 1);
            }
            context.cipher.card.expYear = context.importRecord[context.property].substr(3, 4);
            return true;
        }
        return false;
    }
    setLoginPassword(context) {
        if (this.isNullOrWhitespace(context.cipher.login.password) &&
            context.lowerProperty === "password") {
            context.cipher.login.password = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setLoginUsername(context) {
        if (this.isNullOrWhitespace(context.cipher.login.username) &&
            context.lowerProperty === "username") {
            context.cipher.login.username = context.importRecord[context.property];
            return true;
        }
        return false;
    }
    setLoginUris(context) {
        if ((context.cipher.login.uris == null || context.cipher.login.uris.length === 0) &&
            context.lowerProperty === "urls") {
            const urls = context.importRecord[context.property].split(this.newLineRegex);
            context.cipher.login.uris = this.makeUriArray(urls);
            return true;
        }
        else if (context.lowerProperty === "url") {
            if (context.cipher.login.uris == null) {
                context.cipher.login.uris = [];
            }
            context.cipher.login.uris.concat(this.makeUriArray(context.importRecord[context.property]));
            return true;
        }
        return false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/onepassword-mac-csv-importer.ts




class OnePasswordMacCsvImporter extends OnePasswordCsvImporter {
    setCipherType(value, cipher) {
        const onePassType = this.getValueOrDefault(this.getProp(value, "type"), "Login");
        switch (onePassType) {
            case "Credit Card":
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
                IgnoredProperties.push("type");
                break;
            case "Identity":
                cipher.type = CipherType.Identity;
                cipher.identity = new IdentityView();
                IgnoredProperties.push("type");
                break;
            case "Login":
            case "Secure Note":
                IgnoredProperties.push("type");
                break;
            default:
                break;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/onepassword/onepassword-win-csv-importer.ts





class OnePasswordWinCsvImporter extends OnePasswordCsvImporter {
    constructor() {
        super();
        this.identityPropertyParsers.push(this.setIdentityAddress);
    }
    setCipherType(value, cipher) {
        cipher.type = CipherType.Login;
        cipher.login = new LoginView();
        if (!this.isNullOrWhitespace(this.getPropByRegexp(value, /\d+: number/i)) &&
            !this.isNullOrWhitespace(this.getPropByRegexp(value, /\d+: expiry date/i))) {
            cipher.type = CipherType.Card;
            cipher.card = new CardView();
        }
        if (!this.isNullOrWhitespace(this.getPropByRegexp(value, /name \d+: first name/i)) ||
            !this.isNullOrWhitespace(this.getPropByRegexp(value, /name \d+: initial/i)) ||
            !this.isNullOrWhitespace(this.getPropByRegexp(value, /name \d+: last name/i)) ||
            !this.isNullOrWhitespace(this.getPropByRegexp(value, /internet \d+: email/i))) {
            cipher.type = CipherType.Identity;
            cipher.identity = new IdentityView();
        }
    }
    setIdentityAddress(context) {
        if (context.lowerProperty.match(/address \d+: address/i)) {
            this.processKvp(context.cipher, "address", context.importRecord[context.property]);
            return true;
        }
        return false;
    }
    setCreditCardExpiry(context) {
        if (this.isNullOrWhitespace(context.cipher.card.expiration) &&
            context.lowerProperty.includes("expiry date")) {
            const expSplit = context.importRecord[context.property].split("/");
            context.cipher.card.expMonth = expSplit[0];
            if (context.cipher.card.expMonth[0] === "0" && context.cipher.card.expMonth.length === 2) {
                context.cipher.card.expMonth = context.cipher.card.expMonth.substr(1, 1);
            }
            context.cipher.card.expYear = expSplit[2].length > 4 ? expSplit[2].substr(0, 4) : expSplit[2];
            return true;
        }
        return false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/padlock-csv-importer.ts



class PadlockCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        let headers = null;
        results.forEach((value) => {
            if (headers == null) {
                headers = value.map((v) => v);
                return;
            }
            if (value.length < 2 || value.length !== headers.length) {
                return;
            }
            if (!this.isNullOrWhitespace(value[1])) {
                if (this.organization) {
                    const tags = value[1].split(",");
                    tags.forEach((tag) => {
                        tag = tag.trim();
                        let addCollection = true;
                        let collectionIndex = result.collections.length;
                        for (let i = 0; i < result.collections.length; i++) {
                            if (result.collections[i].name === tag) {
                                addCollection = false;
                                collectionIndex = i;
                                break;
                            }
                        }
                        if (addCollection) {
                            const collection = new CollectionView();
                            collection.name = tag;
                            result.collections.push(collection);
                        }
                        result.collectionRelationships.push([result.ciphers.length, collectionIndex]);
                    });
                }
                else {
                    const tags = value[1].split(",");
                    const tag = tags.length > 0 ? tags[0].trim() : null;
                    this.processFolder(result, tag);
                }
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[0], "--");
            for (let i = 2; i < value.length; i++) {
                const header = headers[i].trim().toLowerCase();
                if (this.isNullOrWhitespace(value[i]) || this.isNullOrWhitespace(header)) {
                    continue;
                }
                if (this.usernameFieldNames.indexOf(header) > -1) {
                    cipher.login.username = value[i];
                }
                else if (this.passwordFieldNames.indexOf(header) > -1) {
                    cipher.login.password = value[i];
                }
                else if (this.uriFieldNames.indexOf(header) > -1) {
                    cipher.login.uris = this.makeUriArray(value[i]);
                }
                else {
                    this.processKvp(cipher, headers[i], value[i]);
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passkeep-csv-importer.ts


class PassKeepCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            this.processFolder(result, this.getValue("category", value));
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValue("description", value);
            cipher.name = this.getValueOrDefault(this.getValue("title", value), "--");
            cipher.login.username = this.getValue("username", value);
            cipher.login.password = this.getValue("password", value);
            cipher.login.uris = this.makeUriArray(this.getValue("site", value));
            this.processKvp(cipher, "Password 2", this.getValue("password2", value));
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    getValue(key, value) {
        return this.getValueOrDefault(value[key], this.getValueOrDefault(value[" " + key]));
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passky/passky-json-importer.ts


class PasskyJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const passkyExport = JSON.parse(data);
        if (passkyExport == null ||
            passkyExport.passwords == null ||
            passkyExport.passwords.length === 0) {
            result.success = false;
            return Promise.resolve(result);
        }
        if (passkyExport.encrypted == true) {
            result.success = false;
            result.errorMessage = "Unable to import an encrypted passky backup.";
            return Promise.resolve(result);
        }
        passkyExport.passwords.forEach((record) => {
            const cipher = this.initLoginCipher();
            cipher.name = record.website;
            cipher.login.username = record.username;
            cipher.login.password = record.password;
            cipher.login.uris = this.makeUriArray(record.website);
            cipher.notes = record.message;
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passman-json-importer.ts


class PassmanJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || results.length === 0) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((credential) => {
            if (credential.tags != null && credential.tags.length > 0) {
                const folderName = credential.tags[0].text;
                this.processFolder(result, folderName);
            }
            const cipher = this.initLoginCipher();
            cipher.name = credential.label;
            cipher.login.username = this.getValueOrDefault(credential.username);
            if (this.isNullOrWhitespace(cipher.login.username)) {
                cipher.login.username = this.getValueOrDefault(credential.email);
            }
            else if (!this.isNullOrWhitespace(credential.email)) {
                cipher.notes = "Email: " + credential.email + "\n";
            }
            cipher.login.password = this.getValueOrDefault(credential.password);
            cipher.login.uris = this.makeUriArray(credential.url);
            cipher.notes += this.getValueOrDefault(credential.description, "");
            if (credential.otp != null) {
                cipher.login.totp = this.getValueOrDefault(credential.otp.secret);
            }
            if (credential.custom_fields != null) {
                credential.custom_fields.forEach((customField) => {
                    switch (customField.field_type) {
                        case "text":
                        case "password":
                            this.processKvp(cipher, customField.label, customField.value);
                            break;
                    }
                });
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passpack-csv-importer.ts



class PasspackCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const tagsJson = !this.isNullOrWhitespace(value.Tags) ? JSON.parse(value.Tags) : null;
            const tags = tagsJson != null && tagsJson.tags != null && tagsJson.tags.length > 0
                ? tagsJson.tags
                    .map((tagJson) => {
                    try {
                        const t = JSON.parse(tagJson);
                        return this.getValueOrDefault(t.tag);
                    }
                    catch (_a) {
                        // Ignore error
                    }
                    return null;
                })
                    .filter((t) => !this.isNullOrWhitespace(t))
                : null;
            if (this.organization && tags != null && tags.length > 0) {
                tags.forEach((tag) => {
                    let addCollection = true;
                    let collectionIndex = result.collections.length;
                    for (let i = 0; i < result.collections.length; i++) {
                        if (result.collections[i].name === tag) {
                            addCollection = false;
                            collectionIndex = i;
                            break;
                        }
                    }
                    if (addCollection) {
                        const collection = new CollectionView();
                        collection.name = tag;
                        result.collections.push(collection);
                    }
                    result.collectionRelationships.push([result.ciphers.length, collectionIndex]);
                });
            }
            else if (!this.organization && tags != null && tags.length > 0) {
                this.processFolder(result, tags[0]);
            }
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value.Notes, "");
            cipher.notes += "\n\n" + this.getValueOrDefault(value["Shared Notes"], "") + "\n";
            cipher.name = this.getValueOrDefault(value["Entry Name"], "--");
            cipher.login.username = this.getValueOrDefault(value["User ID"]);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.uris = this.makeUriArray(value.URL);
            if (value.__parsed_extra != null && value.__parsed_extra.length > 0) {
                value.__parsed_extra.forEach((extra) => {
                    if (!this.isNullOrWhitespace(extra)) {
                        cipher.notes += "\n" + extra;
                    }
                });
            }
            const fieldsJson = !this.isNullOrWhitespace(value["Extra Fields"])
                ? JSON.parse(value["Extra Fields"])
                : null;
            const fields = fieldsJson != null && fieldsJson.extraFields != null && fieldsJson.extraFields.length > 0
                ? fieldsJson.extraFields.map((fieldJson) => {
                    try {
                        return JSON.parse(fieldJson);
                    }
                    catch (_a) {
                        // Ignore error
                    }
                    return null;
                })
                : null;
            if (fields != null) {
                fields.forEach((f) => {
                    if (f != null) {
                        this.processKvp(cipher, f.name, f.data);
                    }
                });
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passwordagent-csv-importer.ts


class PasswordAgentCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        let newVersion = true;
        results.forEach((value) => {
            if (value.length !== 5 && value.length < 9) {
                return;
            }
            const altFormat = value.length === 10 && value[0] === "0";
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[altFormat ? 1 : 0], "--");
            cipher.login.username = this.getValueOrDefault(value[altFormat ? 2 : 1]);
            cipher.login.password = this.getValueOrDefault(value[altFormat ? 3 : 2]);
            if (value.length === 5) {
                newVersion = false;
                cipher.notes = this.getValueOrDefault(value[4]);
                cipher.login.uris = this.makeUriArray(value[3]);
            }
            else {
                const folder = this.getValueOrDefault(value[altFormat ? 9 : 8], "(None)");
                let folderName = folder !== "(None)" ? folder.split("\\").join("/") : null;
                if (folderName != null) {
                    folderName = folder.split(" > ").join("/");
                    folderName = folder.split(">").join("/");
                }
                this.processFolder(result, folderName);
                cipher.notes = this.getValueOrDefault(value[altFormat ? 5 : 3]);
                cipher.login.uris = this.makeUriArray(value[4]);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (newVersion && this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passwordboss-json-importer.ts





class PasswordBossJsonImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = JSON.parse(data);
        if (results == null || results.items == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const foldersMap = new Map();
        results.folders.forEach((value) => {
            foldersMap.set(value.id, value.name);
        });
        const foldersIndexMap = new Map();
        foldersMap.forEach((val, key) => {
            foldersIndexMap.set(key, result.folders.length);
            const f = new FolderView();
            f.name = val;
            result.folders.push(f);
        });
        results.items.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.name, "--");
            cipher.login.uris = this.makeUriArray(value.login_url);
            if (value.folder != null && foldersIndexMap.has(value.folder)) {
                result.folderRelationships.push([result.ciphers.length, foldersIndexMap.get(value.folder)]);
            }
            if (value.identifiers == null) {
                return;
            }
            if (!this.isNullOrWhitespace(value.identifiers.notes)) {
                cipher.notes = value.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n");
            }
            if (value.type === "CreditCard") {
                cipher.card = new CardView();
                cipher.type = CipherType.Card;
            }
            for (const property in value.identifiers) {
                // eslint-disable-next-line
                if (!value.identifiers.hasOwnProperty(property)) {
                    continue;
                }
                const valObj = value.identifiers[property];
                const val = valObj != null ? valObj.toString() : null;
                if (this.isNullOrWhitespace(val) ||
                    property === "notes" ||
                    property === "ignoreItemInSecurityScore") {
                    continue;
                }
                if (property === "custom_fields") {
                    valObj.forEach((cf) => {
                        this.processKvp(cipher, cf.name, cf.value);
                    });
                    continue;
                }
                if (cipher.type === CipherType.Card) {
                    if (property === "cardNumber") {
                        cipher.card.number = val;
                        cipher.card.brand = this.getCardBrand(val);
                        continue;
                    }
                    else if (property === "nameOnCard") {
                        cipher.card.cardholderName = val;
                        continue;
                    }
                    else if (property === "security_code") {
                        cipher.card.code = val;
                        continue;
                    }
                    else if (property === "expires") {
                        try {
                            const expDate = new Date(val);
                            cipher.card.expYear = expDate.getFullYear().toString();
                            cipher.card.expMonth = (expDate.getMonth() + 1).toString();
                        }
                        catch (_a) {
                            // Ignore error
                        }
                        continue;
                    }
                    else if (property === "cardType") {
                        continue;
                    }
                }
                else {
                    if ((property === "username" || property === "email") &&
                        this.isNullOrWhitespace(cipher.login.username)) {
                        cipher.login.username = val;
                        continue;
                    }
                    else if (property === "password") {
                        cipher.login.password = val;
                        continue;
                    }
                    else if (property === "totp") {
                        cipher.login.totp = val;
                        continue;
                    }
                    else if ((cipher.login.uris == null || cipher.login.uris.length === 0) &&
                        this.uriFieldNames.indexOf(property) > -1) {
                        cipher.login.uris = this.makeUriArray(val);
                        continue;
                    }
                }
                this.processKvp(cipher, property, val);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passworddragon-xml-importer.ts


class PasswordDragonXmlImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const doc = this.parseXml(data);
        if (doc == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const records = doc.querySelectorAll("PasswordManager > record");
        Array.from(records).forEach((record) => {
            const category = this.querySelectorDirectChild(record, "Category");
            const categoryText = category != null &&
                !this.isNullOrWhitespace(category.textContent) &&
                category.textContent !== "Unfiled"
                ? category.textContent
                : null;
            this.processFolder(result, categoryText);
            const accountName = this.querySelectorDirectChild(record, "Account-Name");
            const userId = this.querySelectorDirectChild(record, "User-Id");
            const password = this.querySelectorDirectChild(record, "Password");
            const url = this.querySelectorDirectChild(record, "URL");
            const notes = this.querySelectorDirectChild(record, "Notes");
            const cipher = this.initLoginCipher();
            cipher.name =
                accountName != null ? this.getValueOrDefault(accountName.textContent, "--") : "--";
            cipher.notes = notes != null ? this.getValueOrDefault(notes.textContent) : "";
            cipher.login.username = userId != null ? this.getValueOrDefault(userId.textContent) : null;
            cipher.login.password =
                password != null ? this.getValueOrDefault(password.textContent) : null;
            cipher.login.uris = url != null ? this.makeUriArray(url.textContent) : null;
            const attributes = [];
            for (let i = 1; i <= 10; i++) {
                attributes.push("Attribute-" + i);
            }
            this.querySelectorAllDirectChild(record, attributes.join(",")).forEach((attr) => {
                if (this.isNullOrWhitespace(attr.textContent) || attr.textContent === "null") {
                    return;
                }
                this.processKvp(cipher, attr.tagName, attr.textContent);
            });
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passwordsafe-xml-importer.ts


class PasswordSafeXmlImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const doc = this.parseXml(data);
        if (doc == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const passwordSafe = doc.querySelector("passwordsafe");
        if (passwordSafe == null) {
            result.errorMessage = "Missing `passwordsafe` node.";
            result.success = false;
            return Promise.resolve(result);
        }
        const notesDelimiter = passwordSafe.getAttribute("delimiter");
        const entries = doc.querySelectorAll("passwordsafe > entry");
        Array.from(entries).forEach((entry) => {
            const group = this.querySelectorDirectChild(entry, "group");
            const groupText = group != null && !this.isNullOrWhitespace(group.textContent)
                ? group.textContent.split(".").join("/")
                : null;
            this.processFolder(result, groupText);
            const title = this.querySelectorDirectChild(entry, "title");
            const username = this.querySelectorDirectChild(entry, "username");
            const email = this.querySelectorDirectChild(entry, "email");
            const password = this.querySelectorDirectChild(entry, "password");
            const url = this.querySelectorDirectChild(entry, "url");
            const notes = this.querySelectorDirectChild(entry, "notes");
            const cipher = this.initLoginCipher();
            cipher.name = title != null ? this.getValueOrDefault(title.textContent, "--") : "--";
            cipher.notes =
                notes != null
                    ? this.getValueOrDefault(notes.textContent, "").split(notesDelimiter).join("\n")
                    : null;
            cipher.login.username =
                username != null ? this.getValueOrDefault(username.textContent) : null;
            cipher.login.password =
                password != null ? this.getValueOrDefault(password.textContent) : null;
            cipher.login.uris = url != null ? this.makeUriArray(url.textContent) : null;
            if (this.isNullOrWhitespace(cipher.login.username) && email != null) {
                cipher.login.username = this.getValueOrDefault(email.textContent);
            }
            else if (email != null && !this.isNullOrWhitespace(email.textContent)) {
                cipher.notes = this.isNullOrWhitespace(cipher.notes)
                    ? "Email: " + email.textContent
                    : cipher.notes + "\n" + "Email: " + email.textContent;
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/passwordwallet-txt-importer.ts


class PasswordWalletTxtImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 1) {
                return;
            }
            if (value.length > 5) {
                this.processFolder(result, value[5]);
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[0], "--");
            if (value.length > 4) {
                cipher.notes = this.getValueOrDefault(value[4], "").split("¬").join("\n");
            }
            if (value.length > 2) {
                cipher.login.username = this.getValueOrDefault(value[2]);
            }
            if (value.length > 3) {
                cipher.login.password = this.getValueOrDefault(value[3]);
            }
            if (value.length > 1) {
                cipher.login.uris = this.makeUriArray(value[1]);
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/psono/psono-json-importer.ts






class PsonoJsonImporter extends BaseImporter {
    constructor() {
        super(...arguments);
        this.WEBSITE_mappedValues = new Set([
            "type",
            "name",
            "website_password_title",
            "website_password_notes",
            "website_password_username",
            "website_password_password",
            "website_password_url",
            "autosubmit",
            "website_password_auto_submit",
            "urlfilter",
            "website_password_url_filter",
        ]);
        this.APP_PWD_mappedValues = new Set([
            "type",
            "name",
            "application_password_title",
            "application_password_notes",
            "application_password_username",
            "application_password_password",
        ]);
        this.BOOKMARK_mappedValues = new Set([
            "type",
            "name",
            "bookmark_title",
            "bookmark_notes",
            "bookmark_url",
        ]);
        this.NOTES_mappedValues = new Set(["type", "name", "note_title", "note_notes"]);
        this.TOTP_mappedValues = new Set(["type", "name", "totp_title", "totp_notes", "totp_code"]);
        this.ENV_VARIABLES_mappedValues = new Set([
            "type",
            "name",
            "environment_variables_title",
            "environment_variables_notes",
            "environment_variables_variables",
        ]);
        this.GPG_mappedValues = new Set([
            "type",
            "name",
            "mail_gpg_own_key_title",
            "mail_gpg_own_key_public",
            "mail_gpg_own_key_name",
            "mail_gpg_own_key_email",
            "mail_gpg_own_key_private",
        ]);
    }
    parse(data) {
        const result = new ImportResult();
        const psonoExport = JSON.parse(data);
        if (psonoExport == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        this.parseFolders(result, psonoExport.folders);
        this.handleItemParsing(result, psonoExport.items);
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    parseFolders(result, folders) {
        if (folders == null || folders.length === 0) {
            return;
        }
        folders.forEach((folder) => {
            if (folder.items == null || folder.items.length == 0) {
                return;
            }
            this.processFolder(result, folder.name);
            this.handleItemParsing(result, folder.items);
        });
    }
    handleItemParsing(result, items) {
        if (items == null || items.length === 0) {
            return;
        }
        items.forEach((record) => {
            const cipher = this.parsePsonoItem(record);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
    }
    parsePsonoItem(item) {
        const cipher = this.initLoginCipher();
        switch (item.type) {
            case "website_password":
                this.parseWebsiteLogins(item, cipher);
                break;
            case "application_password":
                this.parseApplicationPasswords(item, cipher);
                break;
            case "environment_variables":
                this.parseEnvironmentVariables(item, cipher);
                break;
            case "totp":
                this.parseTOTP(item, cipher);
                break;
            case "bookmark":
                this.parseBookmarks(item, cipher);
                break;
            // Skipping this until we can save GPG into notes/custom fields
            // case "mail_gpg_own_key":
            //   this.parseGPG(item, cipher);
            //   break;
            case "note":
                this.parseNotes(item, cipher);
                break;
            default:
                break;
        }
        return cipher;
    }
    parseWebsiteLogins(entry, cipher) {
        if (entry == null || entry.type != "website_password") {
            return;
        }
        cipher.name = entry.website_password_title;
        cipher.notes = entry.website_password_notes;
        cipher.login.username = entry.website_password_username;
        cipher.login.password = entry.website_password_password;
        cipher.login.uris = this.makeUriArray(entry.website_password_url);
        this.processKvp(cipher, "website_password_auto_submit", entry.website_password_auto_submit.toString(), FieldType.Boolean);
        this.processKvp(cipher, "website_password_url_filter", entry.website_password_url_filter);
        this.importUnmappedFields(cipher, entry, this.WEBSITE_mappedValues);
    }
    parseApplicationPasswords(entry, cipher) {
        if (entry == null || entry.type != "application_password") {
            return;
        }
        cipher.name = entry.application_password_title;
        cipher.notes = entry.application_password_notes;
        cipher.login.username = entry.application_password_username;
        cipher.login.password = entry.application_password_password;
        this.importUnmappedFields(cipher, entry, this.APP_PWD_mappedValues);
    }
    parseBookmarks(entry, cipher) {
        if (entry == null || entry.type != "bookmark") {
            return;
        }
        cipher.name = entry.bookmark_title;
        cipher.notes = entry.bookmark_notes;
        cipher.login.uris = this.makeUriArray(entry.bookmark_url);
        this.importUnmappedFields(cipher, entry, this.BOOKMARK_mappedValues);
    }
    parseNotes(entry, cipher) {
        if (entry == null || entry.type != "note") {
            return;
        }
        cipher.type = CipherType.SecureNote;
        cipher.secureNote = new SecureNoteView();
        cipher.secureNote.type = SecureNoteType.Generic;
        cipher.name = entry.note_title;
        cipher.notes = entry.note_notes;
        this.importUnmappedFields(cipher, entry, this.NOTES_mappedValues);
    }
    parseTOTP(entry, cipher) {
        if (entry == null || entry.type != "totp") {
            return;
        }
        cipher.name = entry.totp_title;
        cipher.notes = entry.totp_notes;
        cipher.login.totp = entry.totp_code;
        this.importUnmappedFields(cipher, entry, this.TOTP_mappedValues);
    }
    parseEnvironmentVariables(entry, cipher) {
        if (entry == null || entry.type != "environment_variables") {
            return;
        }
        cipher.type = CipherType.SecureNote;
        cipher.secureNote = new SecureNoteView();
        cipher.secureNote.type = SecureNoteType.Generic;
        cipher.name = entry.environment_variables_title;
        cipher.notes = entry.environment_variables_notes;
        entry.environment_variables_variables.forEach((KvPair) => {
            this.processKvp(cipher, KvPair.key, KvPair.value);
        });
        this.importUnmappedFields(cipher, entry, this.ENV_VARIABLES_mappedValues);
    }
    parseGPG(entry, cipher) {
        if (entry == null || entry.type != "mail_gpg_own_key") {
            return;
        }
        cipher.type = CipherType.SecureNote;
        cipher.secureNote = new SecureNoteView();
        cipher.secureNote.type = SecureNoteType.Generic;
        cipher.name = entry.mail_gpg_own_key_title;
        cipher.notes = entry.mail_gpg_own_key_public;
        this.processKvp(cipher, "mail_gpg_own_key_name", entry.mail_gpg_own_key_name);
        this.processKvp(cipher, "mail_gpg_own_key_email", entry.mail_gpg_own_key_email);
        this.processKvp(cipher, "mail_gpg_own_key_private", entry.mail_gpg_own_key_private, FieldType.Hidden);
        this.importUnmappedFields(cipher, entry, this.GPG_mappedValues);
    }
    importUnmappedFields(cipher, entry, mappedValues) {
        const unmappedFields = Object.keys(entry).filter((x) => !mappedValues.has(x));
        unmappedFields.forEach((key) => {
            const item = entry;
            this.processKvp(cipher, key, item[key].toString());
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/remembear-csv-importer.ts




class RememBearCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.trash === "true") {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.name);
            cipher.notes = this.getValueOrDefault(value.notes);
            if (value.type === "LoginItem") {
                cipher.login.uris = this.makeUriArray(value.website);
                cipher.login.password = this.getValueOrDefault(value.password);
                cipher.login.username = this.getValueOrDefault(value.username);
            }
            else if (value.type === "CreditCardItem") {
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
                cipher.card.cardholderName = this.getValueOrDefault(value.cardholder);
                cipher.card.number = this.getValueOrDefault(value.number);
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                cipher.card.code = this.getValueOrDefault(value.verification);
                try {
                    const expMonth = this.getValueOrDefault(value.expiryMonth);
                    if (expMonth != null) {
                        const expMonthNumber = parseInt(expMonth, null);
                        if (expMonthNumber != null && expMonthNumber >= 1 && expMonthNumber <= 12) {
                            cipher.card.expMonth = expMonthNumber.toString();
                        }
                    }
                }
                catch (_a) {
                    // Ignore error
                }
                try {
                    const expYear = this.getValueOrDefault(value.expiryYear);
                    if (expYear != null) {
                        const expYearNumber = parseInt(expYear, null);
                        if (expYearNumber != null) {
                            cipher.card.expYear = expYearNumber.toString();
                        }
                    }
                }
                catch (_b) {
                    // Ignore error
                }
                const pin = this.getValueOrDefault(value.pin);
                if (pin != null) {
                    this.processKvp(cipher, "PIN", pin);
                }
                const zip = this.getValueOrDefault(value.zipCode);
                if (zip != null) {
                    this.processKvp(cipher, "Zip Code", zip);
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/roboform-csv-importer.ts


class RoboFormCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        let i = 1;
        results.forEach((value) => {
            const folder = !this.isNullOrWhitespace(value.Folder) && value.Folder.startsWith("/")
                ? value.Folder.replace("/", "")
                : value.Folder;
            const folderName = !this.isNullOrWhitespace(folder) ? folder : null;
            this.processFolder(result, folderName);
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value.Note);
            cipher.name = this.getValueOrDefault(value.Name, "--");
            cipher.login.username = this.getValueOrDefault(value.Login);
            cipher.login.password = this.getValueOrDefault(value.Pwd);
            cipher.login.uris = this.makeUriArray(value.Url);
            if (!this.isNullOrWhitespace(value.Rf_fields)) {
                let fields = [value.Rf_fields];
                if (value.__parsed_extra != null && value.__parsed_extra.length > 0) {
                    fields = fields.concat(value.__parsed_extra);
                }
                fields.forEach((field) => {
                    const parts = field.split(":");
                    if (parts.length < 3) {
                        return;
                    }
                    const key = parts[0] === "-no-name-" ? null : parts[0];
                    const val = parts.length === 4 && parts[2] === "rck" ? parts[1] : parts[2];
                    this.processKvp(cipher, key, val);
                });
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            if (i === results.length &&
                cipher.name === "--" &&
                this.isNullOrWhitespace(cipher.login.password)) {
                return;
            }
            result.ciphers.push(cipher);
            i++;
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/safari-csv-importer.ts


class SafariCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            var _a;
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.Title, "--");
            cipher.login.username = this.getValueOrDefault(value.Username);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.uris = this.makeUriArray((_a = value.Url) !== null && _a !== void 0 ? _a : value.URL);
            cipher.login.totp = this.getValueOrDefault(value.OTPAuth);
            cipher.notes = this.getValueOrDefault(value.Notes);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/safeincloud-xml-importer.ts







class SafeInCloudXmlImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const doc = this.parseXml(data);
        if (doc == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const db = doc.querySelector("database");
        if (db == null) {
            result.errorMessage = "Missing `database` node.";
            result.success = false;
            return Promise.resolve(result);
        }
        const foldersMap = new Map();
        Array.from(doc.querySelectorAll("database > label")).forEach((labelEl) => {
            const name = labelEl.getAttribute("name");
            const id = labelEl.getAttribute("id");
            if (!this.isNullOrWhitespace(name) && !this.isNullOrWhitespace(id)) {
                foldersMap.set(id, result.folders.length);
                const folder = new FolderView();
                folder.name = name;
                result.folders.push(folder);
            }
        });
        Array.from(doc.querySelectorAll("database > card")).forEach((cardEl) => {
            if (cardEl.getAttribute("template") === "true" || cardEl.getAttribute("deleted") === "true") {
                return;
            }
            const labelIdEl = this.querySelectorDirectChild(cardEl, "label_id");
            if (labelIdEl != null) {
                const labelId = labelIdEl.textContent;
                if (!this.isNullOrWhitespace(labelId) && foldersMap.has(labelId)) {
                    result.folderRelationships.push([result.ciphers.length, foldersMap.get(labelId)]);
                }
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(cardEl.getAttribute("title"), "--");
            if (cardEl.getAttribute("star") === "true") {
                cipher.favorite = true;
            }
            const cardType = cardEl.getAttribute("type");
            if (cardType === "note") {
                cipher.type = CipherType.SecureNote;
                cipher.secureNote = new SecureNoteView();
                cipher.secureNote.type = SecureNoteType.Generic;
            }
            else {
                Array.from(this.querySelectorAllDirectChild(cardEl, "field")).forEach((fieldEl) => {
                    const text = fieldEl.textContent;
                    if (this.isNullOrWhitespace(text)) {
                        return;
                    }
                    const name = fieldEl.getAttribute("name");
                    const fieldType = this.getValueOrDefault(fieldEl.getAttribute("type"), "").toLowerCase();
                    if (fieldType === "login") {
                        cipher.login.username = text;
                    }
                    else if (fieldType === "password" || fieldType === "secret") {
                        // safeInCloud allows for more than one password. we just insert them here and find the one used as password later
                        this.processKvp(cipher, name, text, FieldType.Hidden);
                    }
                    else if (fieldType === "one_time_password") {
                        cipher.login.totp = text;
                    }
                    else if (fieldType === "notes") {
                        cipher.notes += text + "\n";
                    }
                    else if (fieldType === "weblogin" || fieldType === "website") {
                        cipher.login.uris = this.makeUriArray(text);
                    }
                    else {
                        this.processKvp(cipher, name, text);
                    }
                });
            }
            Array.from(this.querySelectorAllDirectChild(cardEl, "notes")).forEach((notesEl) => {
                cipher.notes += notesEl.textContent + "\n";
            });
            this.setPassword(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    // Choose a password from all passwords. Take one that has password in its name, or the first one if there is no such entry
    // if its name is password, we can safely remove it form the fields. otherwise, it would maybe be best to keep it as a hidden field
    setPassword(cipher) {
        const candidates = cipher.fields.filter((field) => field.type === FieldType.Hidden);
        if (!candidates.length) {
            return;
        }
        let choice;
        for (const field of candidates) {
            if (this.passwordFieldNames.includes(field.name.toLowerCase())) {
                choice = field;
                cipher.fields = cipher.fields.filter((f) => f !== choice);
                break;
            }
        }
        if (!choice) {
            choice = candidates[0];
        }
        cipher.login.password = choice.value;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/saferpass-csv-importer.ts


class SaferPassCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(this.nameFromUrl(value.url), "--");
            cipher.notes = this.getValueOrDefault(value.notes);
            cipher.login.username = this.getValueOrDefault(value.username);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.uris = this.makeUriArray(value.url);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/securesafe-csv-importer.ts


class SecureSafeCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.Title);
            cipher.notes = this.getValueOrDefault(value.Comment);
            cipher.login.uris = this.makeUriArray(value.Url);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.username = this.getValueOrDefault(value.Username);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/splashid-csv-importer.ts


class SplashIdCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length < 3) {
                return;
            }
            this.processFolder(result, this.getValueOrDefault(value[value.length - 1]));
            const cipher = this.initLoginCipher();
            cipher.notes = this.getValueOrDefault(value[value.length - 2], "");
            cipher.name = this.getValueOrDefault(value[1], "--");
            if (value[0] === "Web Logins" || value[0] === "Servers" || value[0] === "Email Accounts") {
                cipher.login.username = this.getValueOrDefault(value[2]);
                cipher.login.password = this.getValueOrDefault(value[3]);
                cipher.login.uris = this.makeUriArray(value[4]);
                this.parseFieldsToNotes(cipher, 5, value);
            }
            else {
                this.parseFieldsToNotes(cipher, 2, value);
            }
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    parseFieldsToNotes(cipher, startIndex, value) {
        // last 3 rows do not get parsed
        for (let i = startIndex; i < value.length - 3; i++) {
            if (this.isNullOrWhitespace(value[i])) {
                continue;
            }
            cipher.notes += value[i] + "\n";
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/stickypassword-xml-importer.ts


class StickyPasswordXmlImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const doc = this.parseXml(data);
        if (doc == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        const loginNodes = doc.querySelectorAll("root > Database > Logins > Login");
        Array.from(loginNodes).forEach((loginNode) => {
            const accountId = loginNode.getAttribute("ID");
            if (this.isNullOrWhitespace(accountId)) {
                return;
            }
            const usernameText = loginNode.getAttribute("Name");
            const passwordText = loginNode.getAttribute("Password");
            let titleText = null;
            let linkText = null;
            let notesText = null;
            let groupId = null;
            let groupText = null;
            const accountLogin = doc.querySelector("root > Database > Accounts > Account > " +
                'LoginLinks > Login[SourceLoginID="' +
                accountId +
                '"]');
            if (accountLogin != null) {
                const account = accountLogin.parentElement.parentElement;
                if (account != null) {
                    titleText = account.getAttribute("Name");
                    linkText = account.getAttribute("Link");
                    groupId = account.getAttribute("ParentID");
                    notesText = account.getAttribute("Comments");
                    if (!this.isNullOrWhitespace(notesText)) {
                        notesText = notesText.split("/n").join("\n");
                    }
                }
            }
            if (!this.isNullOrWhitespace(groupId)) {
                groupText = this.buildGroupText(doc, groupId, "");
                this.processFolder(result, groupText);
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(titleText, "--");
            cipher.notes = this.getValueOrDefault(notesText);
            cipher.login.username = this.getValueOrDefault(usernameText);
            cipher.login.password = this.getValueOrDefault(passwordText);
            cipher.login.uris = this.makeUriArray(linkText);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    buildGroupText(doc, groupId, groupText) {
        const group = doc.querySelector('root > Database > Groups > Group[ID="' + groupId + '"]');
        if (group == null) {
            return groupText;
        }
        if (!this.isNullOrWhitespace(groupText)) {
            groupText = "/" + groupText;
        }
        groupText = group.getAttribute("Name") + groupText;
        return this.buildGroupText(doc, group.getAttribute("ParentID"), groupText);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/truekey-csv-importer.ts






const PropertiesToIgnore = [
    "kind",
    "autologin",
    "favorite",
    "hexcolor",
    "protectedwithpassword",
    "subdomainonly",
    "type",
    "tk_export_version",
    "note",
    "title",
    "document_content",
];
class TrueKeyCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.favorite = this.getValueOrDefault(value.favorite, "").toLowerCase() === "true";
            cipher.name = this.getValueOrDefault(value.name, "--");
            cipher.notes = this.getValueOrDefault(value.memo, "");
            cipher.login.username = this.getValueOrDefault(value.login);
            cipher.login.password = this.getValueOrDefault(value.password);
            cipher.login.uris = this.makeUriArray(value.url);
            if (value.kind !== "login") {
                cipher.name = this.getValueOrDefault(value.title, "--");
                cipher.notes = this.getValueOrDefault(value.note, "");
            }
            if (value.kind === "cc") {
                cipher.type = CipherType.Card;
                cipher.card = new CardView();
                cipher.card.cardholderName = this.getValueOrDefault(value.cardholder);
                cipher.card.number = this.getValueOrDefault(value.number);
                cipher.card.brand = this.getCardBrand(cipher.card.number);
                if (!this.isNullOrWhitespace(value.expiryDate)) {
                    try {
                        const expDate = new Date(value.expiryDate);
                        cipher.card.expYear = expDate.getFullYear().toString();
                        cipher.card.expMonth = (expDate.getMonth() + 1).toString();
                    }
                    catch (_a) {
                        // Ignore error
                    }
                }
            }
            else if (value.kind !== "login") {
                cipher.type = CipherType.SecureNote;
                cipher.secureNote = new SecureNoteView();
                cipher.secureNote.type = SecureNoteType.Generic;
                if (!this.isNullOrWhitespace(cipher.notes)) {
                    cipher.notes = this.getValueOrDefault(value.document_content, "");
                }
                for (const property in value) {
                    if (value.hasOwnProperty(property) && // eslint-disable-line
                        PropertiesToIgnore.indexOf(property.toLowerCase()) < 0 &&
                        !this.isNullOrWhitespace(value[property])) {
                        this.processKvp(cipher, property, value[property]);
                    }
                }
            }
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/upm-csv-importer.ts


class UpmCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, false);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (value.length !== 5) {
                return;
            }
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value[0], "--");
            cipher.notes = this.getValueOrDefault(value[4]);
            cipher.login.username = this.getValueOrDefault(value[1]);
            cipher.login.password = this.getValueOrDefault(value[2]);
            cipher.login.uris = this.makeUriArray(value[3]);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/yoti-csv-importer.ts


class YotiCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            const cipher = this.initLoginCipher();
            cipher.name = this.getValueOrDefault(value.Name, "--");
            cipher.login.username = this.getValueOrDefault(value["User name"]);
            cipher.login.password = this.getValueOrDefault(value.Password);
            cipher.login.uris = this.makeUriArray(value.URL);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        result.success = true;
        return Promise.resolve(result);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/importers/zohovault-csv-importer.ts


class ZohoVaultCsvImporter extends BaseImporter {
    parse(data) {
        const result = new ImportResult();
        const results = this.parseCsv(data, true);
        if (results == null) {
            result.success = false;
            return Promise.resolve(result);
        }
        results.forEach((value) => {
            if (this.isNullOrWhitespace(value["Password Name"]) &&
                this.isNullOrWhitespace(value["Secret Name"])) {
                return;
            }
            this.processFolder(result, this.getValueOrDefault(value.ChamberName));
            const cipher = this.initLoginCipher();
            cipher.favorite = this.getValueOrDefault(value.Favorite, "0") === "1";
            cipher.notes = this.getValueOrDefault(value.Notes);
            cipher.name = this.getValueOrDefault(value["Password Name"], this.getValueOrDefault(value["Secret Name"], "--"));
            cipher.login.uris = this.makeUriArray(this.getValueOrDefault(value["Password URL"], this.getValueOrDefault(value["Secret URL"])));
            this.parseData(cipher, value.SecretData);
            this.parseData(cipher, value.CustomData);
            this.convertToNoteIfNeeded(cipher);
            this.cleanupCipher(cipher);
            result.ciphers.push(cipher);
        });
        if (this.organization) {
            this.moveFoldersToCollections(result);
        }
        result.success = true;
        return Promise.resolve(result);
    }
    parseData(cipher, data) {
        if (this.isNullOrWhitespace(data)) {
            return;
        }
        const dataLines = this.splitNewLine(data);
        dataLines.forEach((line) => {
            const delimPosition = line.indexOf(":");
            if (delimPosition < 0) {
                return;
            }
            const field = line.substring(0, delimPosition);
            const value = line.length > delimPosition ? line.substring(delimPosition + 1) : null;
            if (this.isNullOrWhitespace(field) ||
                this.isNullOrWhitespace(value) ||
                field === "SecretType") {
                return;
            }
            const fieldLower = field.toLowerCase();
            if (cipher.login.username == null && this.usernameFieldNames.indexOf(fieldLower) > -1) {
                cipher.login.username = value;
            }
            else if (cipher.login.password == null &&
                this.passwordFieldNames.indexOf(fieldLower) > -1) {
                cipher.login.password = value;
            }
            else {
                this.processKvp(cipher, field, value);
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/collection.request.ts
class CollectionRequest {
    constructor(collection) {
        this.groups = [];
        this.users = [];
        if (collection == null) {
            return;
        }
        this.name = collection.name ? collection.name.encryptedString : null;
        this.externalId = collection.externalId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/import-ciphers.request.ts
class ImportCiphersRequest {
    constructor() {
        this.ciphers = [];
        this.folders = [];
        this.folderRelationships = [];
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/import-organization-ciphers.request.ts
class ImportOrganizationCiphersRequest {
    constructor() {
        this.ciphers = [];
        this.collections = [];
        this.collectionRelationships = [];
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/kvp.request.ts
class KvpRequest {
    constructor(key, value) {
        this.key = key;
        this.value = value;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/card.api.ts

class CardApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.cardholderName = this.getResponseProperty("CardholderName");
        this.brand = this.getResponseProperty("Brand");
        this.number = this.getResponseProperty("Number");
        this.expMonth = this.getResponseProperty("ExpMonth");
        this.expYear = this.getResponseProperty("ExpYear");
        this.code = this.getResponseProperty("Code");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/field.api.ts

class FieldApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.type = this.getResponseProperty("Type");
        this.name = this.getResponseProperty("Name");
        this.value = this.getResponseProperty("Value");
        this.linkedId = this.getResponseProperty("linkedId");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/identity.api.ts

class IdentityApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.title = this.getResponseProperty("Title");
        this.firstName = this.getResponseProperty("FirstName");
        this.middleName = this.getResponseProperty("MiddleName");
        this.lastName = this.getResponseProperty("LastName");
        this.address1 = this.getResponseProperty("Address1");
        this.address2 = this.getResponseProperty("Address2");
        this.address3 = this.getResponseProperty("Address3");
        this.city = this.getResponseProperty("City");
        this.state = this.getResponseProperty("State");
        this.postalCode = this.getResponseProperty("PostalCode");
        this.country = this.getResponseProperty("Country");
        this.company = this.getResponseProperty("Company");
        this.email = this.getResponseProperty("Email");
        this.phone = this.getResponseProperty("Phone");
        this.ssn = this.getResponseProperty("SSN");
        this.username = this.getResponseProperty("Username");
        this.passportNumber = this.getResponseProperty("PassportNumber");
        this.licenseNumber = this.getResponseProperty("LicenseNumber");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/login-uri.api.ts

class LoginUriApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        this.match = null;
        if (data == null) {
            return;
        }
        this.uri = this.getResponseProperty("Uri");
        const match = this.getResponseProperty("Match");
        this.match = match != null ? match : null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/login.api.ts


class LoginApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.username = this.getResponseProperty("Username");
        this.password = this.getResponseProperty("Password");
        this.passwordRevisionDate = this.getResponseProperty("PasswordRevisionDate");
        this.totp = this.getResponseProperty("Totp");
        this.autofillOnPageLoad = this.getResponseProperty("AutofillOnPageLoad");
        const uris = this.getResponseProperty("Uris");
        if (uris != null) {
            this.uris = uris.map((u) => new LoginUriApi(u));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/secure-note.api.ts

class SecureNoteApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.type = this.getResponseProperty("Type");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/attachment.request.ts
class AttachmentRequest {
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher.request.ts








class CipherRequest {
    constructor(cipher) {
        this.type = cipher.type;
        this.folderId = cipher.folderId;
        this.organizationId = cipher.organizationId;
        this.name = cipher.name ? cipher.name.encryptedString : null;
        this.notes = cipher.notes ? cipher.notes.encryptedString : null;
        this.favorite = cipher.favorite;
        this.lastKnownRevisionDate = cipher.revisionDate;
        this.reprompt = cipher.reprompt;
        switch (this.type) {
            case CipherType.Login:
                this.login = new LoginApi();
                this.login.uris = null;
                this.login.username = cipher.login.username ? cipher.login.username.encryptedString : null;
                this.login.password = cipher.login.password ? cipher.login.password.encryptedString : null;
                this.login.passwordRevisionDate =
                    cipher.login.passwordRevisionDate != null
                        ? cipher.login.passwordRevisionDate.toISOString()
                        : null;
                this.login.totp = cipher.login.totp ? cipher.login.totp.encryptedString : null;
                this.login.autofillOnPageLoad = cipher.login.autofillOnPageLoad;
                if (cipher.login.uris != null) {
                    this.login.uris = cipher.login.uris.map((u) => {
                        const uri = new LoginUriApi();
                        uri.uri = u.uri != null ? u.uri.encryptedString : null;
                        uri.match = u.match != null ? u.match : null;
                        return uri;
                    });
                }
                break;
            case CipherType.SecureNote:
                this.secureNote = new SecureNoteApi();
                this.secureNote.type = cipher.secureNote.type;
                break;
            case CipherType.Card:
                this.card = new CardApi();
                this.card.cardholderName =
                    cipher.card.cardholderName != null ? cipher.card.cardholderName.encryptedString : null;
                this.card.brand = cipher.card.brand != null ? cipher.card.brand.encryptedString : null;
                this.card.number = cipher.card.number != null ? cipher.card.number.encryptedString : null;
                this.card.expMonth =
                    cipher.card.expMonth != null ? cipher.card.expMonth.encryptedString : null;
                this.card.expYear =
                    cipher.card.expYear != null ? cipher.card.expYear.encryptedString : null;
                this.card.code = cipher.card.code != null ? cipher.card.code.encryptedString : null;
                break;
            case CipherType.Identity:
                this.identity = new IdentityApi();
                this.identity.title =
                    cipher.identity.title != null ? cipher.identity.title.encryptedString : null;
                this.identity.firstName =
                    cipher.identity.firstName != null ? cipher.identity.firstName.encryptedString : null;
                this.identity.middleName =
                    cipher.identity.middleName != null ? cipher.identity.middleName.encryptedString : null;
                this.identity.lastName =
                    cipher.identity.lastName != null ? cipher.identity.lastName.encryptedString : null;
                this.identity.address1 =
                    cipher.identity.address1 != null ? cipher.identity.address1.encryptedString : null;
                this.identity.address2 =
                    cipher.identity.address2 != null ? cipher.identity.address2.encryptedString : null;
                this.identity.address3 =
                    cipher.identity.address3 != null ? cipher.identity.address3.encryptedString : null;
                this.identity.city =
                    cipher.identity.city != null ? cipher.identity.city.encryptedString : null;
                this.identity.state =
                    cipher.identity.state != null ? cipher.identity.state.encryptedString : null;
                this.identity.postalCode =
                    cipher.identity.postalCode != null ? cipher.identity.postalCode.encryptedString : null;
                this.identity.country =
                    cipher.identity.country != null ? cipher.identity.country.encryptedString : null;
                this.identity.company =
                    cipher.identity.company != null ? cipher.identity.company.encryptedString : null;
                this.identity.email =
                    cipher.identity.email != null ? cipher.identity.email.encryptedString : null;
                this.identity.phone =
                    cipher.identity.phone != null ? cipher.identity.phone.encryptedString : null;
                this.identity.ssn =
                    cipher.identity.ssn != null ? cipher.identity.ssn.encryptedString : null;
                this.identity.username =
                    cipher.identity.username != null ? cipher.identity.username.encryptedString : null;
                this.identity.passportNumber =
                    cipher.identity.passportNumber != null
                        ? cipher.identity.passportNumber.encryptedString
                        : null;
                this.identity.licenseNumber =
                    cipher.identity.licenseNumber != null
                        ? cipher.identity.licenseNumber.encryptedString
                        : null;
                break;
            default:
                break;
        }
        if (cipher.fields != null) {
            this.fields = cipher.fields.map((f) => {
                const field = new FieldApi();
                field.type = f.type;
                field.name = f.name ? f.name.encryptedString : null;
                field.value = f.value ? f.value.encryptedString : null;
                field.linkedId = f.linkedId;
                return field;
            });
        }
        if (cipher.passwordHistory != null) {
            this.passwordHistory = [];
            cipher.passwordHistory.forEach((ph) => {
                this.passwordHistory.push({
                    lastUsedDate: ph.lastUsedDate,
                    password: ph.password ? ph.password.encryptedString : null,
                });
            });
        }
        if (cipher.attachments != null) {
            this.attachments = {};
            this.attachments2 = {};
            cipher.attachments.forEach((attachment) => {
                const fileName = attachment.fileName ? attachment.fileName.encryptedString : null;
                this.attachments[attachment.id] = fileName;
                const attachmentRequest = new AttachmentRequest();
                attachmentRequest.fileName = fileName;
                if (attachment.key != null) {
                    attachmentRequest.key = attachment.key.encryptedString;
                }
                this.attachments2[attachment.id] = attachmentRequest;
            });
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/folder.request.ts
class FolderRequest {
    constructor(folder) {
        this.name = folder.name ? folder.name.encryptedString : null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/import/import.service.ts
var import_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





































































class ImportService {
    constructor(cipherService, folderService, importApiService, i18nService, collectionService, cryptoService) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.importApiService = importApiService;
        this.i18nService = i18nService;
        this.collectionService = collectionService;
        this.cryptoService = cryptoService;
        this.featuredImportOptions = featuredImportOptions;
        this.regularImportOptions = regularImportOptions;
    }
    getImportOptions() {
        return this.featuredImportOptions.concat(this.regularImportOptions);
    }
    import(importer, fileContents, organizationId = null) {
        return import_service_awaiter(this, void 0, void 0, function* () {
            const importResult = yield importer.parse(fileContents);
            if (importResult.success) {
                if (importResult.folders.length === 0 && importResult.ciphers.length === 0) {
                    return new ImportError(this.i18nService.t("importNothingError"));
                }
                else if (importResult.ciphers.length > 0) {
                    const halfway = Math.floor(importResult.ciphers.length / 2);
                    const last = importResult.ciphers.length - 1;
                    if (this.badData(importResult.ciphers[0]) &&
                        this.badData(importResult.ciphers[halfway]) &&
                        this.badData(importResult.ciphers[last])) {
                        return new ImportError(this.i18nService.t("importFormatError"));
                    }
                }
                try {
                    yield this.postImport(importResult, organizationId);
                }
                catch (error) {
                    const errorResponse = new ErrorResponse(error, 400);
                    return this.handleServerError(errorResponse, importResult);
                }
                return null;
            }
            else {
                if (!Utils.isNullOrWhitespace(importResult.errorMessage)) {
                    return new ImportError(importResult.errorMessage, importResult.missingPassword);
                }
                else {
                    return new ImportError(this.i18nService.t("importFormatError"), importResult.missingPassword);
                }
            }
        });
    }
    getImporter(format, organizationId = null, password = null) {
        const importer = this.getImporterInstance(format, password);
        if (importer == null) {
            return null;
        }
        importer.organizationId = organizationId;
        return importer;
    }
    getImporterInstance(format, password) {
        if (format == null) {
            return null;
        }
        switch (format) {
            case "bitwardencsv":
                return new BitwardenCsvImporter();
            case "bitwardenjson":
                return new BitwardenJsonImporter(this.cryptoService, this.i18nService);
            case "bitwardenpasswordprotected":
                return new BitwardenPasswordProtectedImporter(this.cryptoService, this.i18nService, password);
            case "lastpasscsv":
            case "passboltcsv":
                return new LastPassCsvImporter();
            case "keepassxcsv":
                return new KeePassXCsvImporter();
            case "aviracsv":
                return new AviraCsvImporter();
            case "blurcsv":
                return new BlurCsvImporter();
            case "safeincloudxml":
                return new SafeInCloudXmlImporter();
            case "padlockcsv":
                return new PadlockCsvImporter();
            case "keepass2xml":
                return new KeePass2XmlImporter();
            case "chromecsv":
            case "operacsv":
            case "vivaldicsv":
                return new ChromeCsvImporter();
            case "firefoxcsv":
                return new FirefoxCsvImporter();
            case "upmcsv":
                return new UpmCsvImporter();
            case "saferpasscsv":
                return new SaferPassCsvImporter();
            case "safaricsv":
                return new SafariCsvImporter();
            case "meldiumcsv":
                return new MeldiumCsvImporter();
            case "1password1pif":
                return new OnePassword1PifImporter();
            case "1password1pux":
                return new OnePassword1PuxImporter();
            case "1passwordwincsv":
                return new OnePasswordWinCsvImporter();
            case "1passwordmaccsv":
                return new OnePasswordMacCsvImporter();
            case "keepercsv":
                return new KeeperCsvImporter();
            // case "keeperjson":
            //   return new KeeperJsonImporter();
            case "passworddragonxml":
                return new PasswordDragonXmlImporter();
            case "enpasscsv":
                return new EnpassCsvImporter();
            case "enpassjson":
                return new EnpassJsonImporter();
            case "pwsafexml":
                return new PasswordSafeXmlImporter();
            case "dashlanecsv":
                return new DashlaneCsvImporter();
            case "dashlanejson":
                return new DashlaneJsonImporter();
            case "msecurecsv":
                return new MSecureCsvImporter();
            case "stickypasswordxml":
                return new StickyPasswordXmlImporter();
            case "truekeycsv":
                return new TrueKeyCsvImporter();
            case "clipperzhtml":
                return new ClipperzHtmlImporter();
            case "roboformcsv":
                return new RoboFormCsvImporter();
            case "ascendocsv":
                return new AscendoCsvImporter();
            case "passwordbossjson":
                return new PasswordBossJsonImporter();
            case "zohovaultcsv":
                return new ZohoVaultCsvImporter();
            case "splashidcsv":
                return new SplashIdCsvImporter();
            case "passkeepcsv":
                return new PassKeepCsvImporter();
            case "gnomejson":
                return new GnomeJsonImporter();
            case "passwordagentcsv":
                return new PasswordAgentCsvImporter();
            case "passpackcsv":
                return new PasspackCsvImporter();
            case "passmanjson":
                return new PassmanJsonImporter();
            case "avastcsv":
                return new AvastCsvImporter();
            case "avastjson":
                return new AvastJsonImporter();
            case "fsecurefsk":
                return new FSecureFskImporter();
            case "kasperskytxt":
                return new KasperskyTxtImporter();
            case "remembearcsv":
                return new RememBearCsvImporter();
            case "passwordwallettxt":
                return new PasswordWalletTxtImporter();
            case "mykicsv":
                return new MykiCsvImporter();
            case "securesafecsv":
                return new SecureSafeCsvImporter();
            case "logmeoncecsv":
                return new LogMeOnceCsvImporter();
            case "blackberrycsv":
                return new BlackBerryCsvImporter();
            case "buttercupcsv":
                return new ButtercupCsvImporter();
            case "codebookcsv":
                return new CodebookCsvImporter();
            case "encryptrcsv":
                return new EncryptrCsvImporter();
            case "yoticsv":
                return new YotiCsvImporter();
            case "nordpasscsv":
                return new NordPassCsvImporter();
            case "psonojson":
                return new PsonoJsonImporter();
            case "passkyjson":
                return new PasskyJsonImporter();
            default:
                return null;
        }
    }
    postImport(importResult, organizationId = null) {
        return import_service_awaiter(this, void 0, void 0, function* () {
            if (organizationId == null) {
                const request = new ImportCiphersRequest();
                for (let i = 0; i < importResult.ciphers.length; i++) {
                    const c = yield this.cipherService.encrypt(importResult.ciphers[i]);
                    request.ciphers.push(new CipherRequest(c));
                }
                if (importResult.folders != null) {
                    for (let i = 0; i < importResult.folders.length; i++) {
                        const f = yield this.folderService.encrypt(importResult.folders[i]);
                        request.folders.push(new FolderRequest(f));
                    }
                }
                if (importResult.folderRelationships != null) {
                    importResult.folderRelationships.forEach((r) => request.folderRelationships.push(new KvpRequest(r[0], r[1])));
                }
                return yield this.importApiService.postImportCiphers(request);
            }
            else {
                const request = new ImportOrganizationCiphersRequest();
                for (let i = 0; i < importResult.ciphers.length; i++) {
                    importResult.ciphers[i].organizationId = organizationId;
                    const c = yield this.cipherService.encrypt(importResult.ciphers[i]);
                    request.ciphers.push(new CipherRequest(c));
                }
                if (importResult.collections != null) {
                    for (let i = 0; i < importResult.collections.length; i++) {
                        importResult.collections[i].organizationId = organizationId;
                        const c = yield this.collectionService.encrypt(importResult.collections[i]);
                        request.collections.push(new CollectionRequest(c));
                    }
                }
                if (importResult.collectionRelationships != null) {
                    importResult.collectionRelationships.forEach((r) => request.collectionRelationships.push(new KvpRequest(r[0], r[1])));
                }
                return yield this.importApiService.postImportOrganizationCiphers(organizationId, request);
            }
        });
    }
    badData(c) {
        return ((c.name == null || c.name === "--") &&
            c.type === CipherType.Login &&
            c.login != null &&
            Utils.isNullOrWhitespace(c.login.password));
    }
    handleServerError(errorResponse, importResult) {
        if (errorResponse.validationErrors == null) {
            return new ImportError(errorResponse.message);
        }
        let errorMessage = "";
        Object.entries(errorResponse.validationErrors).forEach(([key, value], index) => {
            let item;
            let itemType;
            const i = Number(key.match(/[0-9]+/)[0]);
            switch (key.match(/^\w+/)[0]) {
                case "Ciphers":
                    item = importResult.ciphers[i];
                    itemType = CipherType[item.type];
                    break;
                case "Folders":
                    item = importResult.folders[i];
                    itemType = "Folder";
                    break;
                case "Collections":
                    item = importResult.collections[i];
                    itemType = "Collection";
                    break;
                default:
                    return;
            }
            if (index > 0) {
                errorMessage += "\n\n";
            }
            if (itemType !== "Folder" && itemType !== "Collection") {
                errorMessage += "[" + (i + 1) + "] ";
            }
            errorMessage += "[" + itemType + '] "' + item.name + '": ' + value;
        });
        return new ImportError(errorMessage);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/organizationUserType.ts
var OrganizationUserType;
(function (OrganizationUserType) {
    OrganizationUserType[OrganizationUserType["Owner"] = 0] = "Owner";
    OrganizationUserType[OrganizationUserType["Admin"] = 1] = "Admin";
    OrganizationUserType[OrganizationUserType["User"] = 2] = "User";
    OrganizationUserType[OrganizationUserType["Manager"] = 3] = "Manager";
    OrganizationUserType[OrganizationUserType["Custom"] = 4] = "Custom";
})(OrganizationUserType || (OrganizationUserType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/request/account/set-key-connector-key.request.ts
class SetKeyConnectorKeyRequest {
    constructor(key, kdf, kdfConfig, orgIdentifier, keys) {
        this.key = key;
        this.kdf = kdf;
        this.kdfIterations = kdfConfig.iterations;
        this.kdfMemory = kdfConfig.memory;
        this.kdfParallelism = kdfConfig.parallelism;
        this.orgIdentifier = orgIdentifier;
        this.keys = keys;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/key-connector-user-key.request.ts
class KeyConnectorUserKeyRequest {
    constructor(key) {
        this.key = key;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/keyConnector.service.ts
var keyConnector_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};







class KeyConnectorService {
    constructor(stateService, cryptoService, apiService, tokenService, logService, organizationService, cryptoFunctionService, logoutCallback) {
        this.stateService = stateService;
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.tokenService = tokenService;
        this.logService = logService;
        this.organizationService = organizationService;
        this.cryptoFunctionService = cryptoFunctionService;
        this.logoutCallback = logoutCallback;
    }
    setUsesKeyConnector(usesKeyConnector) {
        return this.stateService.setUsesKeyConnector(usesKeyConnector);
    }
    getUsesKeyConnector() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getUsesKeyConnector();
        });
    }
    userNeedsMigration() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            const loggedInUsingSso = yield this.tokenService.getIsExternal();
            const requiredByOrganization = (yield this.getManagingOrganization()) != null;
            const userIsNotUsingKeyConnector = !(yield this.getUsesKeyConnector());
            return loggedInUsingSso && requiredByOrganization && userIsNotUsingKeyConnector;
        });
    }
    migrateUser() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            const organization = yield this.getManagingOrganization();
            const key = yield this.cryptoService.getKey();
            const keyConnectorRequest = new KeyConnectorUserKeyRequest(key.encKeyB64);
            try {
                yield this.apiService.postUserKeyToKeyConnector(organization.keyConnectorUrl, keyConnectorRequest);
            }
            catch (e) {
                this.handleKeyConnectorError(e);
            }
            yield this.apiService.postConvertToKeyConnector();
        });
    }
    getAndSetKey(url) {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            try {
                const userKeyResponse = yield this.apiService.getUserKeyFromKeyConnector(url);
                const keyArr = Utils.fromB64ToArray(userKeyResponse.key);
                const k = new SymmetricCryptoKey(keyArr);
                yield this.cryptoService.setKey(k);
            }
            catch (e) {
                this.handleKeyConnectorError(e);
            }
        });
    }
    getManagingOrganization() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            const orgs = yield this.organizationService.getAll();
            return orgs.find((o) => o.keyConnectorEnabled &&
                o.type !== OrganizationUserType.Admin &&
                o.type !== OrganizationUserType.Owner &&
                !o.isProviderUser);
        });
    }
    convertNewSsoUserToKeyConnector(tokenResponse, orgId) {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            const { kdf, kdfIterations, kdfMemory, kdfParallelism, keyConnectorUrl } = tokenResponse;
            const password = yield this.cryptoFunctionService.randomBytes(64);
            const kdfConfig = new KdfConfig(kdfIterations, kdfMemory, kdfParallelism);
            const k = yield this.cryptoService.makeKey(Utils.fromBufferToB64(password), yield this.tokenService.getEmail(), kdf, kdfConfig);
            const keyConnectorRequest = new KeyConnectorUserKeyRequest(k.encKeyB64);
            yield this.cryptoService.setKey(k);
            const encKey = yield this.cryptoService.makeEncKey(k);
            yield this.cryptoService.setEncKey(encKey[1].encryptedString);
            const [pubKey, privKey] = yield this.cryptoService.makeKeyPair();
            try {
                yield this.apiService.postUserKeyToKeyConnector(keyConnectorUrl, keyConnectorRequest);
            }
            catch (e) {
                this.handleKeyConnectorError(e);
            }
            const keys = new KeysRequest(pubKey, privKey.encryptedString);
            const setPasswordRequest = new SetKeyConnectorKeyRequest(encKey[1].encryptedString, kdf, kdfConfig, orgId, keys);
            yield this.apiService.postSetKeyConnectorKey(setPasswordRequest);
        });
    }
    setConvertAccountRequired(status) {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setConvertAccountToKeyConnector(status);
        });
    }
    getConvertAccountRequired() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getConvertAccountToKeyConnector();
        });
    }
    removeConvertAccountRequired() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setConvertAccountToKeyConnector(null);
        });
    }
    clear() {
        return keyConnector_service_awaiter(this, void 0, void 0, function* () {
            yield this.removeConvertAccountRequired();
        });
    }
    handleKeyConnectorError(e) {
        this.logService.error(e);
        if (this.logoutCallback != null) {
            this.logoutCallback(false);
        }
        throw new Error("Key Connector error");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/storage.service.ts
class AbstractStorageService {
}
class AbstractMemoryStorageService extends AbstractStorageService {
    constructor() {
        super(...arguments);
        this.type = AbstractMemoryStorageService.TYPE;
    }
}
// Used to identify the service in the session sync decorator framework
AbstractMemoryStorageService.TYPE = "MemoryStorageService";

;// CONCATENATED MODULE: ../../libs/common/src/services/memoryStorage.service.ts
var memoryStorage_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class MemoryStorageService extends AbstractMemoryStorageService {
    constructor() {
        super(...arguments);
        this.store = new Map();
    }
    get(key) {
        if (this.store.has(key)) {
            const obj = this.store.get(key);
            return Promise.resolve(obj);
        }
        return Promise.resolve(null);
    }
    has(key) {
        return memoryStorage_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.get(key)) != null;
        });
    }
    save(key, obj) {
        if (obj == null) {
            return this.remove(key);
        }
        this.store.set(key, obj);
        return Promise.resolve();
    }
    remove(key) {
        this.store.delete(key);
        return Promise.resolve();
    }
    getBypassCache(key) {
        return this.get(key);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/noopMessaging.service.ts
class NoopMessagingService {
    send(subscriber, arg = {}) {
        // Do nothing...
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/permissions.api.ts

class PermissionsApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return this;
        }
        this.accessEventLogs = this.getResponseProperty("AccessEventLogs");
        this.accessImportExport = this.getResponseProperty("AccessImportExport");
        this.accessReports = this.getResponseProperty("AccessReports");
        this.createNewCollections = this.getResponseProperty("CreateNewCollections");
        this.editAnyCollection = this.getResponseProperty("EditAnyCollection");
        this.deleteAnyCollection = this.getResponseProperty("DeleteAnyCollection");
        this.editAssignedCollections = this.getResponseProperty("EditAssignedCollections");
        this.deleteAssignedCollections = this.getResponseProperty("DeleteAssignedCollections");
        this.manageCiphers = this.getResponseProperty("ManageCiphers");
        this.manageGroups = this.getResponseProperty("ManageGroups");
        this.manageSso = this.getResponseProperty("ManageSso");
        this.managePolicies = this.getResponseProperty("ManagePolicies");
        this.manageUsers = this.getResponseProperty("ManageUsers");
        this.manageResetPassword = this.getResponseProperty("ManageResetPassword");
        this.manageScim = this.getResponseProperty("ManageScim");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/selection-read-only.response.ts

class SelectionReadOnlyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.readOnly = this.getResponseProperty("ReadOnly");
        this.hidePasswords = this.getResponseProperty("HidePasswords");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/organization-user/responses/organization-user.response.ts



class OrganizationUserResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.collections = [];
        this.groups = [];
        this.id = this.getResponseProperty("Id");
        this.userId = this.getResponseProperty("UserId");
        this.type = this.getResponseProperty("Type");
        this.status = this.getResponseProperty("Status");
        this.permissions = new PermissionsApi(this.getResponseProperty("Permissions"));
        this.externalId = this.getResponseProperty("ExternalId");
        this.accessAll = this.getResponseProperty("AccessAll");
        this.accessSecretsManager = this.getResponseProperty("AccessSecretsManager");
        this.resetPasswordEnrolled = this.getResponseProperty("ResetPasswordEnrolled");
        const collections = this.getResponseProperty("Collections");
        if (collections != null) {
            this.collections = collections.map((c) => new SelectionReadOnlyResponse(c));
        }
        const groups = this.getResponseProperty("Groups");
        if (groups != null) {
            this.groups = groups;
        }
    }
}
class OrganizationUserUserDetailsResponse extends OrganizationUserResponse {
    constructor(response) {
        var _a;
        super(response);
        this.name = this.getResponseProperty("Name");
        this.email = this.getResponseProperty("Email");
        this.twoFactorEnabled = this.getResponseProperty("TwoFactorEnabled");
        this.usesKeyConnector = (_a = this.getResponseProperty("UsesKeyConnector")) !== null && _a !== void 0 ? _a : false;
    }
}
class OrganizationUserDetailsResponse extends OrganizationUserResponse {
    constructor(response) {
        super(response);
    }
}
class OrganizationUserResetPasswordDetailsReponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.kdf = this.getResponseProperty("Kdf");
        this.kdfIterations = this.getResponseProperty("KdfIterations");
        this.kdfMemory = this.getResponseProperty("KdfMemory");
        this.kdfParallelism = this.getResponseProperty("KdfParallelism");
        this.resetPasswordKey = this.getResponseProperty("ResetPasswordKey");
        this.encryptedPrivateKey = this.getResponseProperty("EncryptedPrivateKey");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/organization-user/responses/organization-user-bulk.response.ts

class OrganizationUserBulkResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.error = this.getResponseProperty("Error");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/organization-user/responses/organization-user-bulk-public-key.response.ts

class OrganizationUserBulkPublicKeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.userId = this.getResponseProperty("UserId");
        this.key = this.getResponseProperty("Key");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/list.response.ts

class ListResponse extends BaseResponse {
    constructor(response, t) {
        super(response);
        const data = this.getResponseProperty("Data");
        this.data = data == null ? [] : data.map((dr) => new t(dr));
        this.continuationToken = this.getResponseProperty("ContinuationToken");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/organization-user/requests/organization-user-bulk.request.ts
class OrganizationUserBulkRequest {
    constructor(ids) {
        this.ids = ids == null ? [] : ids;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/organization-user/organization-user.service.implementation.ts
var organization_user_service_implementation_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class OrganizationUserServiceImplementation {
    constructor(apiService) {
        this.apiService = apiService;
    }
    getOrganizationUser(organizationId, id, options) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const params = new URLSearchParams();
            if (options === null || options === void 0 ? void 0 : options.includeGroups) {
                params.set("includeGroups", "true");
            }
            const r = yield this.apiService.send("GET", `/organizations/${organizationId}/users/${id}?${params.toString()}`, null, true, true);
            return new OrganizationUserDetailsResponse(r);
        });
    }
    getOrganizationUserGroups(organizationId, id) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + organizationId + "/users/" + id + "/groups", null, true, true);
            return r;
        });
    }
    getAllUsers(organizationId, options) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const params = new URLSearchParams();
            if (options === null || options === void 0 ? void 0 : options.includeCollections) {
                params.set("includeCollections", "true");
            }
            if (options === null || options === void 0 ? void 0 : options.includeGroups) {
                params.set("includeGroups", "true");
            }
            const r = yield this.apiService.send("GET", `/organizations/${organizationId}/users?${params.toString()}`, null, true, true);
            return new ListResponse(r, OrganizationUserUserDetailsResponse);
        });
    }
    getOrganizationUserResetPasswordDetails(organizationId, id) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + organizationId + "/users/" + id + "/reset-password-details", null, true, true);
            return new OrganizationUserResetPasswordDetailsReponse(r);
        });
    }
    postOrganizationUserInvite(organizationId, request) {
        return this.apiService.send("POST", "/organizations/" + organizationId + "/users/invite", request, true, false);
    }
    postOrganizationUserReinvite(organizationId, id) {
        return this.apiService.send("POST", "/organizations/" + organizationId + "/users/" + id + "/reinvite", null, true, false);
    }
    postManyOrganizationUserReinvite(organizationId, ids) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + organizationId + "/users/reinvite", new OrganizationUserBulkRequest(ids), true, true);
            return new ListResponse(r, OrganizationUserBulkResponse);
        });
    }
    postOrganizationUserAccept(organizationId, id, request) {
        return this.apiService.send("POST", "/organizations/" + organizationId + "/users/" + id + "/accept", request, true, false);
    }
    postOrganizationUserConfirm(organizationId, id, request) {
        return this.apiService.send("POST", "/organizations/" + organizationId + "/users/" + id + "/confirm", request, true, false);
    }
    postOrganizationUsersPublicKey(organizationId, ids) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + organizationId + "/users/public-keys", new OrganizationUserBulkRequest(ids), true, true);
            return new ListResponse(r, OrganizationUserBulkPublicKeyResponse);
        });
    }
    postOrganizationUserBulkConfirm(organizationId, request) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + organizationId + "/users/confirm", request, true, true);
            return new ListResponse(r, OrganizationUserBulkResponse);
        });
    }
    putOrganizationUser(organizationId, id, request) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + id, request, true, false);
    }
    putOrganizationUserGroups(organizationId, id, request) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + id + "/groups", request, true, false);
    }
    putOrganizationUserResetPasswordEnrollment(organizationId, userId, request) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + userId + "/reset-password-enrollment", request, true, false);
    }
    putOrganizationUserResetPassword(organizationId, id, request) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + id + "/reset-password", request, true, false);
    }
    deleteOrganizationUser(organizationId, id) {
        return this.apiService.send("DELETE", "/organizations/" + organizationId + "/users/" + id, null, true, false);
    }
    deleteManyOrganizationUsers(organizationId, ids) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("DELETE", "/organizations/" + organizationId + "/users", new OrganizationUserBulkRequest(ids), true, true);
            return new ListResponse(r, OrganizationUserBulkResponse);
        });
    }
    revokeOrganizationUser(organizationId, id) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + id + "/revoke", null, true, false);
    }
    revokeManyOrganizationUsers(organizationId, ids) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("PUT", "/organizations/" + organizationId + "/users/revoke", new OrganizationUserBulkRequest(ids), true, true);
            return new ListResponse(r, OrganizationUserBulkResponse);
        });
    }
    restoreOrganizationUser(organizationId, id) {
        return this.apiService.send("PUT", "/organizations/" + organizationId + "/users/" + id + "/restore", null, true, false);
    }
    restoreManyOrganizationUsers(organizationId, ids) {
        return organization_user_service_implementation_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("PUT", "/organizations/" + organizationId + "/users/restore", new OrganizationUserBulkRequest(ids), true, true);
            return new ListResponse(r, OrganizationUserBulkResponse);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/api-key.response.ts

class ApiKeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.apiKey = this.getResponseProperty("ApiKey");
        this.revisionDate = new Date(this.getResponseProperty("RevisionDate"));
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/billing.response.ts

class BillingResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.invoices = [];
        this.transactions = [];
        this.balance = this.getResponseProperty("Balance");
        const paymentSource = this.getResponseProperty("PaymentSource");
        const transactions = this.getResponseProperty("Transactions");
        const invoices = this.getResponseProperty("Invoices");
        this.paymentSource = paymentSource == null ? null : new BillingSourceResponse(paymentSource);
        if (transactions != null) {
            this.transactions = transactions.map((t) => new BillingTransactionResponse(t));
        }
        if (invoices != null) {
            this.invoices = invoices.map((i) => new BillingInvoiceResponse(i));
        }
    }
    get hasNoHistory() {
        return this.invoices.length == 0 && this.transactions.length == 0;
    }
}
class BillingSourceResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.type = this.getResponseProperty("Type");
        this.cardBrand = this.getResponseProperty("CardBrand");
        this.description = this.getResponseProperty("Description");
        this.needsVerification = this.getResponseProperty("NeedsVerification");
    }
}
class BillingInvoiceResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.url = this.getResponseProperty("Url");
        this.pdfUrl = this.getResponseProperty("PdfUrl");
        this.number = this.getResponseProperty("Number");
        this.paid = this.getResponseProperty("Paid");
        this.date = this.getResponseProperty("Date");
        this.amount = this.getResponseProperty("Amount");
    }
}
class BillingTransactionResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.createdDate = this.getResponseProperty("CreatedDate");
        this.amount = this.getResponseProperty("Amount");
        this.refunded = this.getResponseProperty("Refunded");
        this.partiallyRefunded = this.getResponseProperty("PartiallyRefunded");
        this.refundedAmount = this.getResponseProperty("RefundedAmount");
        this.type = this.getResponseProperty("Type");
        this.paymentMethodType = this.getResponseProperty("PaymentMethodType");
        this.details = this.getResponseProperty("Details");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-api-key-information.response.ts

class OrganizationApiKeyInformationResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.keyType = this.getResponseProperty("KeyType");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-auto-enroll-status.response.ts

class OrganizationAutoEnrollStatusResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.resetPasswordEnabled = this.getResponseProperty("ResetPasswordEnabled");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/keys.response.ts

class KeysResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.privateKey = this.getResponseProperty("PrivateKey");
        this.publicKey = this.getResponseProperty("PublicKey");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-keys.response.ts

class OrganizationKeysResponse extends KeysResponse {
    constructor(response) {
        super(response);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/plan.response.ts

class PlanResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.type = this.getResponseProperty("Type");
        this.product = this.getResponseProperty("Product");
        this.name = this.getResponseProperty("Name");
        this.isAnnual = this.getResponseProperty("IsAnnual");
        this.nameLocalizationKey = this.getResponseProperty("NameLocalizationKey");
        this.descriptionLocalizationKey = this.getResponseProperty("DescriptionLocalizationKey");
        this.canBeUsedByBusiness = this.getResponseProperty("CanBeUsedByBusiness");
        this.baseSeats = this.getResponseProperty("BaseSeats");
        this.baseStorageGb = this.getResponseProperty("BaseStorageGb");
        this.maxCollections = this.getResponseProperty("MaxCollections");
        this.maxUsers = this.getResponseProperty("MaxUsers");
        this.hasAdditionalSeatsOption = this.getResponseProperty("HasAdditionalSeatsOption");
        this.maxAdditionalSeats = this.getResponseProperty("MaxAdditionalSeats");
        this.hasAdditionalStorageOption = this.getResponseProperty("HasAdditionalStorageOption");
        this.maxAdditionalStorage = this.getResponseProperty("MaxAdditionalStorage");
        this.hasPremiumAccessOption = this.getResponseProperty("HasPremiumAccessOption");
        this.trialPeriodDays = this.getResponseProperty("TrialPeriodDays");
        this.hasSelfHost = this.getResponseProperty("HasSelfHost");
        this.hasPolicies = this.getResponseProperty("HasPolicies");
        this.hasGroups = this.getResponseProperty("HasGroups");
        this.hasDirectory = this.getResponseProperty("HasDirectory");
        this.hasEvents = this.getResponseProperty("HasEvents");
        this.hasTotp = this.getResponseProperty("HasTotp");
        this.has2fa = this.getResponseProperty("Has2fa");
        this.hasApi = this.getResponseProperty("HasApi");
        this.hasSso = this.getResponseProperty("HasSso");
        this.hasResetPassword = this.getResponseProperty("HasResetPassword");
        this.usersGetPremium = this.getResponseProperty("UsersGetPremium");
        this.upgradeSortOrder = this.getResponseProperty("UpgradeSortOrder");
        this.displaySortOrder = this.getResponseProperty("SortOrder");
        this.legacyYear = this.getResponseProperty("LegacyYear");
        this.disabled = this.getResponseProperty("Disabled");
        this.stripePlanId = this.getResponseProperty("StripePlanId");
        this.stripeSeatPlanId = this.getResponseProperty("StripeSeatPlanId");
        this.stripeStoragePlanId = this.getResponseProperty("StripeStoragePlanId");
        this.stripePremiumAccessPlanId = this.getResponseProperty("StripePremiumAccessPlanId");
        this.basePrice = this.getResponseProperty("BasePrice");
        this.seatPrice = this.getResponseProperty("SeatPrice");
        this.additionalStoragePricePerGb = this.getResponseProperty("AdditionalStoragePricePerGb");
        this.premiumAccessOptionPrice = this.getResponseProperty("PremiumAccessOptionPrice");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization.response.ts


class OrganizationResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.identifier = this.getResponseProperty("Identifier");
        this.name = this.getResponseProperty("Name");
        this.businessName = this.getResponseProperty("BusinessName");
        this.businessAddress1 = this.getResponseProperty("BusinessAddress1");
        this.businessAddress2 = this.getResponseProperty("BusinessAddress2");
        this.businessAddress3 = this.getResponseProperty("BusinessAddress3");
        this.businessCountry = this.getResponseProperty("BusinessCountry");
        this.businessTaxNumber = this.getResponseProperty("BusinessTaxNumber");
        this.billingEmail = this.getResponseProperty("BillingEmail");
        const plan = this.getResponseProperty("Plan");
        this.plan = plan == null ? null : new PlanResponse(plan);
        this.planType = this.getResponseProperty("PlanType");
        this.seats = this.getResponseProperty("Seats");
        this.maxAutoscaleSeats = this.getResponseProperty("MaxAutoscaleSeats");
        this.maxCollections = this.getResponseProperty("MaxCollections");
        this.maxStorageGb = this.getResponseProperty("MaxStorageGb");
        this.useGroups = this.getResponseProperty("UseGroups");
        this.useDirectory = this.getResponseProperty("UseDirectory");
        this.useEvents = this.getResponseProperty("UseEvents");
        this.useTotp = this.getResponseProperty("UseTotp");
        this.use2fa = this.getResponseProperty("Use2fa");
        this.useApi = this.getResponseProperty("UseApi");
        this.useResetPassword = this.getResponseProperty("UseResetPassword");
        this.hasPublicAndPrivateKeys = this.getResponseProperty("HasPublicAndPrivateKeys");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/subscription.response.ts

class SubscriptionResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.storageName = this.getResponseProperty("StorageName");
        this.storageGb = this.getResponseProperty("StorageGb");
        this.maxStorageGb = this.getResponseProperty("MaxStorageGb");
        this.license = this.getResponseProperty("License");
        this.expiration = this.getResponseProperty("Expiration");
        this.usingInAppPurchase = this.getResponseProperty("UsingInAppPurchase");
        const subscription = this.getResponseProperty("Subscription");
        const upcomingInvoice = this.getResponseProperty("UpcomingInvoice");
        this.subscription = subscription == null ? null : new BillingSubscriptionResponse(subscription);
        this.upcomingInvoice =
            upcomingInvoice == null
                ? null
                : new BillingSubscriptionUpcomingInvoiceResponse(upcomingInvoice);
    }
}
class BillingSubscriptionResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.items = [];
        this.trialEndDate = this.getResponseProperty("TrialStartDate");
        this.trialEndDate = this.getResponseProperty("TrialEndDate");
        this.periodStartDate = this.getResponseProperty("PeriodStartDate");
        this.periodEndDate = this.getResponseProperty("PeriodEndDate");
        this.cancelledDate = this.getResponseProperty("CancelledDate");
        this.cancelAtEndDate = this.getResponseProperty("CancelAtEndDate");
        this.status = this.getResponseProperty("Status");
        this.cancelled = this.getResponseProperty("Cancelled");
        const items = this.getResponseProperty("Items");
        if (items != null) {
            this.items = items.map((i) => new BillingSubscriptionItemResponse(i));
        }
    }
}
class BillingSubscriptionItemResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.name = this.getResponseProperty("Name");
        this.amount = this.getResponseProperty("Amount");
        this.quantity = this.getResponseProperty("Quantity");
        this.interval = this.getResponseProperty("Interval");
        this.sponsoredSubscriptionItem = this.getResponseProperty("SponsoredSubscriptionItem");
    }
}
class BillingSubscriptionUpcomingInvoiceResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.date = this.getResponseProperty("Date");
        this.amount = this.getResponseProperty("Amount");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-subscription.response.ts


class OrganizationSubscriptionResponse extends OrganizationResponse {
    constructor(response) {
        super(response);
        this.storageName = this.getResponseProperty("StorageName");
        this.storageGb = this.getResponseProperty("StorageGb");
        const subscription = this.getResponseProperty("Subscription");
        this.subscription = subscription == null ? null : new BillingSubscriptionResponse(subscription);
        const upcomingInvoice = this.getResponseProperty("UpcomingInvoice");
        this.upcomingInvoice =
            upcomingInvoice == null
                ? null
                : new BillingSubscriptionUpcomingInvoiceResponse(upcomingInvoice);
        this.expiration = this.getResponseProperty("Expiration");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/ssoEnums.ts
var SsoType;
(function (SsoType) {
    SsoType[SsoType["None"] = 0] = "None";
    SsoType[SsoType["OpenIdConnect"] = 1] = "OpenIdConnect";
    SsoType[SsoType["Saml2"] = 2] = "Saml2";
})(SsoType || (SsoType = {}));
var OpenIdConnectRedirectBehavior;
(function (OpenIdConnectRedirectBehavior) {
    OpenIdConnectRedirectBehavior[OpenIdConnectRedirectBehavior["RedirectGet"] = 0] = "RedirectGet";
    OpenIdConnectRedirectBehavior[OpenIdConnectRedirectBehavior["FormPost"] = 1] = "FormPost";
})(OpenIdConnectRedirectBehavior || (OpenIdConnectRedirectBehavior = {}));
var Saml2BindingType;
(function (Saml2BindingType) {
    Saml2BindingType[Saml2BindingType["HttpRedirect"] = 1] = "HttpRedirect";
    Saml2BindingType[Saml2BindingType["HttpPost"] = 2] = "HttpPost";
})(Saml2BindingType || (Saml2BindingType = {}));
var Saml2NameIdFormat;
(function (Saml2NameIdFormat) {
    Saml2NameIdFormat[Saml2NameIdFormat["NotConfigured"] = 0] = "NotConfigured";
    Saml2NameIdFormat[Saml2NameIdFormat["Unspecified"] = 1] = "Unspecified";
    Saml2NameIdFormat[Saml2NameIdFormat["EmailAddress"] = 2] = "EmailAddress";
    Saml2NameIdFormat[Saml2NameIdFormat["X509SubjectName"] = 3] = "X509SubjectName";
    Saml2NameIdFormat[Saml2NameIdFormat["WindowsDomainQualifiedName"] = 4] = "WindowsDomainQualifiedName";
    Saml2NameIdFormat[Saml2NameIdFormat["KerberosPrincipalName"] = 5] = "KerberosPrincipalName";
    Saml2NameIdFormat[Saml2NameIdFormat["EntityIdentifier"] = 6] = "EntityIdentifier";
    Saml2NameIdFormat[Saml2NameIdFormat["Persistent"] = 7] = "Persistent";
    Saml2NameIdFormat[Saml2NameIdFormat["Transient"] = 8] = "Transient";
})(Saml2NameIdFormat || (Saml2NameIdFormat = {}));
var Saml2SigningBehavior;
(function (Saml2SigningBehavior) {
    Saml2SigningBehavior[Saml2SigningBehavior["IfIdpWantAuthnRequestsSigned"] = 0] = "IfIdpWantAuthnRequestsSigned";
    Saml2SigningBehavior[Saml2SigningBehavior["Always"] = 1] = "Always";
    Saml2SigningBehavior[Saml2SigningBehavior["Never"] = 3] = "Never";
})(Saml2SigningBehavior || (Saml2SigningBehavior = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/api/sso-config.api.ts


class SsoConfigApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.configType = this.getResponseProperty("ConfigType");
        this.keyConnectorEnabled = this.getResponseProperty("KeyConnectorEnabled");
        this.keyConnectorUrl = this.getResponseProperty("KeyConnectorUrl");
        this.authority = this.getResponseProperty("Authority");
        this.clientId = this.getResponseProperty("ClientId");
        this.clientSecret = this.getResponseProperty("ClientSecret");
        this.metadataAddress = this.getResponseProperty("MetadataAddress");
        this.redirectBehavior = this.getResponseProperty("RedirectBehavior");
        this.getClaimsFromUserInfoEndpoint = this.getResponseProperty("GetClaimsFromUserInfoEndpoint");
        this.additionalScopes = this.getResponseProperty("AdditionalScopes");
        this.additionalUserIdClaimTypes = this.getResponseProperty("AdditionalUserIdClaimTypes");
        this.additionalEmailClaimTypes = this.getResponseProperty("AdditionalEmailClaimTypes");
        this.additionalNameClaimTypes = this.getResponseProperty("AdditionalNameClaimTypes");
        this.acrValues = this.getResponseProperty("AcrValues");
        this.expectedReturnAcrValue = this.getResponseProperty("ExpectedReturnAcrValue");
        this.spNameIdFormat = this.getResponseProperty("SpNameIdFormat");
        this.spOutboundSigningAlgorithm = this.getResponseProperty("SpOutboundSigningAlgorithm");
        this.spSigningBehavior = this.getResponseProperty("SpSigningBehavior");
        this.spMinIncomingSigningAlgorithm = this.getResponseProperty("SpMinIncomingSigningAlgorithm");
        this.spWantAssertionsSigned = this.getResponseProperty("SpWantAssertionsSigned");
        this.spValidateCertificates = this.getResponseProperty("SpValidateCertificates");
        this.idpEntityId = this.getResponseProperty("IdpEntityId");
        this.idpBindingType = this.getResponseProperty("IdpBindingType");
        this.idpSingleSignOnServiceUrl = this.getResponseProperty("IdpSingleSignOnServiceUrl");
        this.idpSingleLogoutServiceUrl = this.getResponseProperty("IdpSingleLogoutServiceUrl");
        this.idpX509PublicCert = this.getResponseProperty("IdpX509PublicCert");
        this.idpOutboundSigningAlgorithm = this.getResponseProperty("IdpOutboundSigningAlgorithm");
        this.idpAllowUnsolicitedAuthnResponse = this.getResponseProperty("IdpAllowUnsolicitedAuthnResponse");
        this.idpDisableOutboundLogoutRequests = this.getResponseProperty("IdpDisableOutboundLogoutRequests");
        this.idpWantAuthnRequestsSigned = this.getResponseProperty("IdpWantAuthnRequestsSigned");
    }
    static fromView(view, api = new SsoConfigApi()) {
        api.configType = view.configType;
        api.keyConnectorEnabled = view.keyConnectorEnabled;
        api.keyConnectorUrl = view.keyConnectorUrl;
        if (api.configType === SsoType.OpenIdConnect) {
            api.authority = view.openId.authority;
            api.clientId = view.openId.clientId;
            api.clientSecret = view.openId.clientSecret;
            api.metadataAddress = view.openId.metadataAddress;
            api.redirectBehavior = view.openId.redirectBehavior;
            api.getClaimsFromUserInfoEndpoint = view.openId.getClaimsFromUserInfoEndpoint;
            api.additionalScopes = view.openId.additionalScopes;
            api.additionalUserIdClaimTypes = view.openId.additionalUserIdClaimTypes;
            api.additionalEmailClaimTypes = view.openId.additionalEmailClaimTypes;
            api.additionalNameClaimTypes = view.openId.additionalNameClaimTypes;
            api.acrValues = view.openId.acrValues;
            api.expectedReturnAcrValue = view.openId.expectedReturnAcrValue;
        }
        else if (api.configType === SsoType.Saml2) {
            api.spNameIdFormat = view.saml.spNameIdFormat;
            api.spOutboundSigningAlgorithm = view.saml.spOutboundSigningAlgorithm;
            api.spSigningBehavior = view.saml.spSigningBehavior;
            api.spMinIncomingSigningAlgorithm = view.saml.spMinIncomingSigningAlgorithm;
            api.spWantAssertionsSigned = view.saml.spWantAssertionsSigned;
            api.spValidateCertificates = view.saml.spValidateCertificates;
            api.idpEntityId = view.saml.idpEntityId;
            api.idpBindingType = view.saml.idpBindingType;
            api.idpSingleSignOnServiceUrl = view.saml.idpSingleSignOnServiceUrl;
            api.idpSingleLogoutServiceUrl = view.saml.idpSingleLogoutServiceUrl;
            api.idpX509PublicCert = view.saml.idpX509PublicCert;
            api.idpOutboundSigningAlgorithm = view.saml.idpOutboundSigningAlgorithm;
            api.idpAllowUnsolicitedAuthnResponse = view.saml.idpAllowUnsolicitedAuthnResponse;
            api.idpWantAuthnRequestsSigned = view.saml.idpWantAuthnRequestsSigned;
            // Value is inverted in the api model (disable instead of allow)
            api.idpDisableOutboundLogoutRequests = !view.saml.idpAllowOutboundLogoutRequests;
        }
        return api;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization/organization-sso.response.ts


class OrganizationSsoResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.identifier = this.getResponseProperty("Identifier");
        this.data =
            this.getResponseProperty("Data") != null
                ? new SsoConfigApi(this.getResponseProperty("Data"))
                : null;
        this.urls = new SsoUrls(this.getResponseProperty("Urls"));
    }
}
class SsoUrls extends BaseResponse {
    constructor(response) {
        super(response);
        this.callbackPath = this.getResponseProperty("CallbackPath");
        this.signedOutCallbackPath = this.getResponseProperty("SignedOutCallbackPath");
        this.spEntityId = this.getResponseProperty("SpEntityId");
        this.spMetadataUrl = this.getResponseProperty("SpMetadataUrl");
        this.spAcsUrl = this.getResponseProperty("SpAcsUrl");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/profile-organization.response.ts


class ProfileOrganizationResponse extends BaseResponse {
    constructor(response) {
        var _a, _b, _c, _d;
        super(response);
        this.id = this.getResponseProperty("Id");
        this.name = this.getResponseProperty("Name");
        this.usePolicies = this.getResponseProperty("UsePolicies");
        this.useGroups = this.getResponseProperty("UseGroups");
        this.useDirectory = this.getResponseProperty("UseDirectory");
        this.useEvents = this.getResponseProperty("UseEvents");
        this.useTotp = this.getResponseProperty("UseTotp");
        this.use2fa = this.getResponseProperty("Use2fa");
        this.useApi = this.getResponseProperty("UseApi");
        this.useSso = this.getResponseProperty("UseSso");
        this.useKeyConnector = (_a = this.getResponseProperty("UseKeyConnector")) !== null && _a !== void 0 ? _a : false;
        this.useScim = (_b = this.getResponseProperty("UseScim")) !== null && _b !== void 0 ? _b : false;
        this.useCustomPermissions = (_c = this.getResponseProperty("UseCustomPermissions")) !== null && _c !== void 0 ? _c : false;
        this.useResetPassword = this.getResponseProperty("UseResetPassword");
        this.useSecretsManager = this.getResponseProperty("UseSecretsManager");
        this.selfHost = this.getResponseProperty("SelfHost");
        this.usersGetPremium = this.getResponseProperty("UsersGetPremium");
        this.seats = this.getResponseProperty("Seats");
        this.maxCollections = this.getResponseProperty("MaxCollections");
        this.maxStorageGb = this.getResponseProperty("MaxStorageGb");
        this.key = this.getResponseProperty("Key");
        this.hasPublicAndPrivateKeys = this.getResponseProperty("HasPublicAndPrivateKeys");
        this.status = this.getResponseProperty("Status");
        this.type = this.getResponseProperty("Type");
        this.enabled = this.getResponseProperty("Enabled");
        this.ssoBound = this.getResponseProperty("SsoBound");
        this.identifier = this.getResponseProperty("Identifier");
        this.permissions = new PermissionsApi(this.getResponseProperty("permissions"));
        this.resetPasswordEnrolled = this.getResponseProperty("ResetPasswordEnrolled");
        this.userId = this.getResponseProperty("UserId");
        this.providerId = this.getResponseProperty("ProviderId");
        this.providerName = this.getResponseProperty("ProviderName");
        this.familySponsorshipFriendlyName = this.getResponseProperty("FamilySponsorshipFriendlyName");
        this.familySponsorshipAvailable = this.getResponseProperty("FamilySponsorshipAvailable");
        this.planProductType = this.getResponseProperty("PlanProductType");
        this.keyConnectorEnabled = (_d = this.getResponseProperty("KeyConnectorEnabled")) !== null && _d !== void 0 ? _d : false;
        this.keyConnectorUrl = this.getResponseProperty("KeyConnectorUrl");
        const familySponsorshipLastSyncDateString = this.getResponseProperty("FamilySponsorshipLastSyncDate");
        if (familySponsorshipLastSyncDateString) {
            this.familySponsorshipLastSyncDate = new Date(familySponsorshipLastSyncDateString);
        }
        const familySponsorshipValidUntilString = this.getResponseProperty("FamilySponsorshipValidUntil");
        if (familySponsorshipValidUntilString) {
            this.familySponsorshipValidUntil = new Date(familySponsorshipValidUntilString);
        }
        this.familySponsorshipToDelete = this.getResponseProperty("FamilySponsorshipToDelete");
        this.accessSecretsManager = this.getResponseProperty("AccessSecretsManager");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/profile-provider-organization.response.ts

class ProfileProviderOrganizationResponse extends ProfileOrganizationResponse {
    constructor(response) {
        super(response);
        this.keyConnectorEnabled = false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/profile-provider.response.ts


class ProfileProviderResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.name = this.getResponseProperty("Name");
        this.key = this.getResponseProperty("Key");
        this.status = this.getResponseProperty("Status");
        this.type = this.getResponseProperty("Type");
        this.enabled = this.getResponseProperty("Enabled");
        this.permissions = new PermissionsApi(this.getResponseProperty("permissions"));
        this.userId = this.getResponseProperty("UserId");
        this.useEvents = this.getResponseProperty("UseEvents");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/profile.response.ts




class ProfileResponse extends BaseResponse {
    constructor(response) {
        var _a, _b;
        super(response);
        this.organizations = [];
        this.providers = [];
        this.providerOrganizations = [];
        this.id = this.getResponseProperty("Id");
        this.name = this.getResponseProperty("Name");
        this.email = this.getResponseProperty("Email");
        this.emailVerified = this.getResponseProperty("EmailVerified");
        this.masterPasswordHint = this.getResponseProperty("MasterPasswordHint");
        this.premiumPersonally = this.getResponseProperty("Premium");
        this.premiumFromOrganization = this.getResponseProperty("PremiumFromOrganization");
        this.culture = this.getResponseProperty("Culture");
        this.twoFactorEnabled = this.getResponseProperty("TwoFactorEnabled");
        this.key = this.getResponseProperty("Key");
        this.avatarColor = this.getResponseProperty("AvatarColor");
        this.privateKey = this.getResponseProperty("PrivateKey");
        this.securityStamp = this.getResponseProperty("SecurityStamp");
        this.forcePasswordReset = (_a = this.getResponseProperty("ForcePasswordReset")) !== null && _a !== void 0 ? _a : false;
        this.usesKeyConnector = (_b = this.getResponseProperty("UsesKeyConnector")) !== null && _b !== void 0 ? _b : false;
        const organizations = this.getResponseProperty("Organizations");
        if (organizations != null) {
            this.organizations = organizations.map((o) => new ProfileOrganizationResponse(o));
        }
        const providers = this.getResponseProperty("Providers");
        if (providers != null) {
            this.providers = providers.map((o) => new ProfileProviderResponse(o));
        }
        const providerOrganizations = this.getResponseProperty("ProviderOrganizations");
        if (providerOrganizations != null) {
            this.providerOrganizations = providerOrganizations.map((o) => new ProfileProviderOrganizationResponse(o));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/payment.response.ts


class PaymentResponse extends BaseResponse {
    constructor(response) {
        super(response);
        const userProfile = this.getResponseProperty("UserProfile");
        if (userProfile != null) {
            this.userProfile = new ProfileResponse(userProfile);
        }
        this.paymentIntentClientSecret = this.getResponseProperty("PaymentIntentClientSecret");
        this.success = this.getResponseProperty("Success");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/tax-info.response.ts

class TaxInfoResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.taxId = this.getResponseProperty("TaxIdNumber");
        this.taxIdType = this.getResponseProperty("TaxIdType");
        this.line1 = this.getResponseProperty("Line1");
        this.line2 = this.getResponseProperty("Line2");
        this.city = this.getResponseProperty("City");
        this.state = this.getResponseProperty("State");
        this.postalCode = this.getResponseProperty("PostalCode");
        this.country = this.getResponseProperty("Country");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/organization/organization-api.service.ts
var organization_api_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};











class OrganizationApiService {
    constructor(apiService, syncService) {
        this.apiService = apiService;
        this.syncService = syncService;
    }
    get(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id, null, true, true);
            return new OrganizationResponse(r);
        });
    }
    getBilling(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id + "/billing", null, true, true);
            return new BillingResponse(r);
        });
    }
    getSubscription(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id + "/subscription", null, true, true);
            return new OrganizationSubscriptionResponse(r);
        });
    }
    getLicense(id, installationId) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("GET", "/organizations/" + id + "/license?installationId=" + installationId, null, true, true);
        });
    }
    getAutoEnrollStatus(identifier) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + identifier + "/auto-enroll-status", null, true, true);
            return new OrganizationAutoEnrollStatusResponse(r);
        });
    }
    create(request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations", request, true, true);
            // Forcing a sync will notify organization service that they need to repull
            yield this.syncService.fullSync(true);
            return new OrganizationResponse(r);
        });
    }
    createLicense(data) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/licenses/self-hosted", data, true, true);
            return new OrganizationResponse(r);
        });
    }
    save(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("PUT", "/organizations/" + id, request, true, true);
            const data = new OrganizationResponse(r);
            yield this.syncService.fullSync(true);
            return data;
        });
    }
    updatePayment(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/organizations/" + id + "/payment", request, true, false);
        });
    }
    upgrade(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/upgrade", request, true, true);
            return new PaymentResponse(r);
        });
    }
    updateSubscription(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/organizations/" + id + "/subscription", request, true, false);
        });
    }
    updateSeats(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/seat", request, true, true);
            return new PaymentResponse(r);
        });
    }
    updateStorage(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/storage", request, true, true);
            return new PaymentResponse(r);
        });
    }
    verifyBank(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.send("POST", "/organizations/" + id + "/verify-bank", request, true, false);
        });
    }
    cancel(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/organizations/" + id + "/cancel", null, true, false);
        });
    }
    reinstate(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/organizations/" + id + "/reinstate", null, true, false);
        });
    }
    leave(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.send("POST", "/organizations/" + id + "/leave", null, true, false);
            yield this.syncService.fullSync(true);
        });
    }
    delete(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.send("DELETE", "/organizations/" + id, request, true, false);
            yield this.syncService.fullSync(true);
        });
    }
    updateLicense(id, data) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.send("POST", "/organizations/licenses/self-hosted/" + id, data, true, false);
        });
    }
    importDirectory(organizationId, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/organizations/" + organizationId + "/import", request, true, false);
        });
    }
    getOrCreateApiKey(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/api-key", request, true, true);
            return new ApiKeyResponse(r);
        });
    }
    getApiKeyInformation(id, organizationApiKeyType = null) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const uri = organizationApiKeyType === null
                ? "/organizations/" + id + "/api-key-information"
                : "/organizations/" + id + "/api-key-information/" + organizationApiKeyType;
            const r = yield this.apiService.send("GET", uri, null, true, true);
            return new ListResponse(r, OrganizationApiKeyInformationResponse);
        });
    }
    rotateApiKey(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/rotate-api-key", request, true, true);
            return new ApiKeyResponse(r);
        });
    }
    getTaxInfo(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id + "/tax", null, true, true);
            return new TaxInfoResponse(r);
        });
    }
    updateTaxInfo(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            // Can't broadcast anything because the response doesn't have content
            return this.apiService.send("PUT", "/organizations/" + id + "/tax", request, true, false);
        });
    }
    getKeys(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id + "/keys", null, true, true);
            return new OrganizationKeysResponse(r);
        });
    }
    updateKeys(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/keys", request, true, true);
            // Not broadcasting anything because data on this response doesn't correspond to `Organization`
            return new OrganizationKeysResponse(r);
        });
    }
    getSso(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/organizations/" + id + "/sso", null, true, true);
            return new OrganizationSsoResponse(r);
        });
    }
    updateSso(id, request) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/organizations/" + id + "/sso", request, true, true);
            // Not broadcasting anything because data on this response doesn't correspond to `Organization`
            return new OrganizationSsoResponse(r);
        });
    }
    selfHostedSyncLicense(id) {
        return organization_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.send("POST", "/organizations/licenses/self-hosted/" + id + "/sync/", null, true, false);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/organizationUserStatusType.ts
var OrganizationUserStatusType;
(function (OrganizationUserStatusType) {
    OrganizationUserStatusType[OrganizationUserStatusType["Invited"] = 0] = "Invited";
    OrganizationUserStatusType[OrganizationUserStatusType["Accepted"] = 1] = "Accepted";
    OrganizationUserStatusType[OrganizationUserStatusType["Confirmed"] = 2] = "Confirmed";
    OrganizationUserStatusType[OrganizationUserStatusType["Revoked"] = -1] = "Revoked";
})(OrganizationUserStatusType || (OrganizationUserStatusType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/organization.ts


class Organization {
    constructor(obj) {
        if (obj == null) {
            return;
        }
        this.id = obj.id;
        this.name = obj.name;
        this.status = obj.status;
        this.type = obj.type;
        this.enabled = obj.enabled;
        this.usePolicies = obj.usePolicies;
        this.useGroups = obj.useGroups;
        this.useDirectory = obj.useDirectory;
        this.useEvents = obj.useEvents;
        this.useTotp = obj.useTotp;
        this.use2fa = obj.use2fa;
        this.useApi = obj.useApi;
        this.useSso = obj.useSso;
        this.useKeyConnector = obj.useKeyConnector;
        this.useScim = obj.useScim;
        this.useCustomPermissions = obj.useCustomPermissions;
        this.useResetPassword = obj.useResetPassword;
        this.useSecretsManager = obj.useSecretsManager;
        this.selfHost = obj.selfHost;
        this.usersGetPremium = obj.usersGetPremium;
        this.seats = obj.seats;
        this.maxCollections = obj.maxCollections;
        this.maxStorageGb = obj.maxStorageGb;
        this.ssoBound = obj.ssoBound;
        this.identifier = obj.identifier;
        this.permissions = obj.permissions;
        this.resetPasswordEnrolled = obj.resetPasswordEnrolled;
        this.userId = obj.userId;
        this.hasPublicAndPrivateKeys = obj.hasPublicAndPrivateKeys;
        this.providerId = obj.providerId;
        this.providerName = obj.providerName;
        this.isProviderUser = obj.isProviderUser;
        this.familySponsorshipFriendlyName = obj.familySponsorshipFriendlyName;
        this.familySponsorshipAvailable = obj.familySponsorshipAvailable;
        this.planProductType = obj.planProductType;
        this.keyConnectorEnabled = obj.keyConnectorEnabled;
        this.keyConnectorUrl = obj.keyConnectorUrl;
        this.familySponsorshipLastSyncDate = obj.familySponsorshipLastSyncDate;
        this.familySponsorshipValidUntil = obj.familySponsorshipValidUntil;
        this.familySponsorshipToDelete = obj.familySponsorshipToDelete;
        this.accessSecretsManager = obj.accessSecretsManager;
    }
    get canAccess() {
        if (this.type === OrganizationUserType.Owner) {
            return true;
        }
        return this.enabled && this.status === OrganizationUserStatusType.Confirmed;
    }
    get isManager() {
        return (this.type === OrganizationUserType.Manager ||
            this.type === OrganizationUserType.Owner ||
            this.type === OrganizationUserType.Admin);
    }
    get isAdmin() {
        return this.type === OrganizationUserType.Owner || this.type === OrganizationUserType.Admin;
    }
    get isOwner() {
        return this.type === OrganizationUserType.Owner || this.isProviderUser;
    }
    get canAccessEventLogs() {
        return (this.isAdmin || this.permissions.accessEventLogs) && this.useEvents;
    }
    get canAccessImportExport() {
        return this.isAdmin || this.permissions.accessImportExport;
    }
    get canAccessReports() {
        return this.isAdmin || this.permissions.accessReports;
    }
    get canCreateNewCollections() {
        return this.isManager || this.permissions.createNewCollections;
    }
    get canEditAnyCollection() {
        return this.isAdmin || this.permissions.editAnyCollection;
    }
    get canUseAdminCollections() {
        return this.canEditAnyCollection;
    }
    get canDeleteAnyCollection() {
        return this.isAdmin || this.permissions.deleteAnyCollection;
    }
    get canViewAllCollections() {
        return this.canCreateNewCollections || this.canEditAnyCollection || this.canDeleteAnyCollection;
    }
    get canEditAssignedCollections() {
        return this.isManager || this.permissions.editAssignedCollections;
    }
    get canDeleteAssignedCollections() {
        return this.isManager || this.permissions.deleteAssignedCollections;
    }
    get canViewAssignedCollections() {
        return this.canDeleteAssignedCollections || this.canEditAssignedCollections;
    }
    get canManageGroups() {
        return (this.isAdmin || this.permissions.manageGroups) && this.useGroups;
    }
    get canManageSso() {
        return (this.isAdmin || this.permissions.manageSso) && this.useSso;
    }
    get canManageScim() {
        return (this.isAdmin || this.permissions.manageScim) && this.useScim;
    }
    get canManagePolicies() {
        return (this.isAdmin || this.permissions.managePolicies) && this.usePolicies;
    }
    get canManageUsers() {
        return this.isAdmin || this.permissions.manageUsers;
    }
    get canManageUsersPassword() {
        return this.isAdmin || this.permissions.manageResetPassword;
    }
    get isExemptFromPolicies() {
        return this.canManagePolicies;
    }
    get canManageBilling() {
        return this.isOwner && (this.isProviderUser || !this.hasProvider);
    }
    get hasProvider() {
        return this.providerId != null || this.providerName != null;
    }
    get canAccessSecretsManager() {
        return this.useSecretsManager && this.accessSecretsManager;
    }
    static fromJSON(json) {
        if (json == null) {
            return null;
        }
        return Object.assign(new Organization(), json, {
            familySponsorshipLastSyncDate: new Date(json.familySponsorshipLastSyncDate),
            familySponsorshipValidUntil: new Date(json.familySponsorshipValidUntil),
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/organization/organization.service.ts
var organization_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class OrganizationService {
    constructor(stateService) {
        this.stateService = stateService;
        this._organizations = new external_rxjs_namespaceObject.BehaviorSubject([]);
        this.organizations$ = this._organizations.asObservable();
        this.stateService.activeAccountUnlocked$
            .pipe((0,external_rxjs_namespaceObject.concatMap)((unlocked) => organization_service_awaiter(this, void 0, void 0, function* () {
            if (!unlocked) {
                this._organizations.next([]);
                return;
            }
            const data = yield this.stateService.getOrganizations();
            this.updateObservables(data);
        })))
            .subscribe();
    }
    getAll(userId) {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            const organizationsMap = yield this.stateService.getOrganizations({ userId: userId });
            return Object.values(organizationsMap || {}).map((o) => new Organization(o));
        });
    }
    canManageSponsorships() {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            const organizations = this._organizations.getValue();
            return organizations.some((o) => o.familySponsorshipAvailable || o.familySponsorshipFriendlyName !== null);
        });
    }
    hasOrganizations() {
        const organizations = this._organizations.getValue();
        return organizations.length > 0;
    }
    upsert(organization) {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            let organizations = yield this.stateService.getOrganizations();
            if (organizations == null) {
                organizations = {};
            }
            organizations[organization.id] = organization;
            yield this.replace(organizations);
        });
    }
    delete(id) {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            const organizations = yield this.stateService.getOrganizations();
            if (organizations == null) {
                return;
            }
            if (organizations[id] == null) {
                return;
            }
            delete organizations[id];
            yield this.replace(organizations);
        });
    }
    get(id) {
        const organizations = this._organizations.getValue();
        return organizations.find((organization) => organization.id === id);
    }
    /**
     * @deprecated For the CLI only
     * @param id id of the organization
     */
    getFromState(id) {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            const organizationsMap = yield this.stateService.getOrganizations();
            const organization = organizationsMap[id];
            if (organization == null) {
                return null;
            }
            return new Organization(organization);
        });
    }
    getByIdentifier(identifier) {
        const organizations = this._organizations.getValue();
        return organizations.find((organization) => organization.identifier === identifier);
    }
    replace(organizations) {
        return organization_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setOrganizations(organizations);
            this.updateObservables(organizations);
        });
    }
    updateObservables(organizationsMap) {
        const organizations = Object.values(organizationsMap || {}).map((o) => new Organization(o));
        this._organizations.next(organizations);
    }
}

;// CONCATENATED MODULE: external "zxcvbn"
const external_zxcvbn_namespaceObject = require("zxcvbn");
;// CONCATENATED MODULE: ../../libs/common/src/enums/policyType.ts
var PolicyType;
(function (PolicyType) {
    PolicyType[PolicyType["TwoFactorAuthentication"] = 0] = "TwoFactorAuthentication";
    PolicyType[PolicyType["MasterPassword"] = 1] = "MasterPassword";
    PolicyType[PolicyType["PasswordGenerator"] = 2] = "PasswordGenerator";
    PolicyType[PolicyType["SingleOrg"] = 3] = "SingleOrg";
    PolicyType[PolicyType["RequireSso"] = 4] = "RequireSso";
    PolicyType[PolicyType["PersonalOwnership"] = 5] = "PersonalOwnership";
    PolicyType[PolicyType["DisableSend"] = 6] = "DisableSend";
    PolicyType[PolicyType["SendOptions"] = 7] = "SendOptions";
    PolicyType[PolicyType["ResetPassword"] = 8] = "ResetPassword";
    PolicyType[PolicyType["MaximumVaultTimeout"] = 9] = "MaximumVaultTimeout";
    PolicyType[PolicyType["DisablePersonalVaultExport"] = 10] = "DisablePersonalVaultExport";
})(PolicyType || (PolicyType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/generated-password-history.ts
class GeneratedPasswordHistory {
    constructor(password, date) {
        this.password = password;
        this.date = date;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/password-generator-policy-options.ts

class PasswordGeneratorPolicyOptions extends Domain {
    constructor() {
        super(...arguments);
        this.defaultType = "";
        this.minLength = 0;
        this.useUppercase = false;
        this.useLowercase = false;
        this.useNumbers = false;
        this.numberCount = 0;
        this.useSpecial = false;
        this.specialCount = 0;
        this.minNumberWords = 0;
        this.capitalize = false;
        this.includeNumber = false;
    }
    inEffect() {
        return (this.defaultType !== "" ||
            this.minLength > 0 ||
            this.numberCount > 0 ||
            this.specialCount > 0 ||
            this.useUppercase ||
            this.useLowercase ||
            this.useNumbers ||
            this.useSpecial ||
            this.minNumberWords > 0 ||
            this.capitalize ||
            this.includeNumber);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/passwordGeneration.service.ts
var passwordGeneration_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};






const DefaultOptions = {
    length: 14,
    ambiguous: false,
    number: true,
    minNumber: 1,
    uppercase: true,
    minUppercase: 0,
    lowercase: true,
    minLowercase: 0,
    special: false,
    minSpecial: 1,
    type: "password",
    numWords: 3,
    wordSeparator: "-",
    capitalize: false,
    includeNumber: false,
};
const MaxPasswordsInHistory = 100;
class PasswordGenerationService {
    constructor(cryptoService, policyService, stateService) {
        this.cryptoService = cryptoService;
        this.policyService = policyService;
        this.stateService = stateService;
    }
    generatePassword(options) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            // overload defaults with given options
            const o = Object.assign({}, DefaultOptions, options);
            if (o.type === "passphrase") {
                return this.generatePassphrase(options);
            }
            // sanitize
            this.sanitizePasswordLength(o, true);
            const minLength = o.minUppercase + o.minLowercase + o.minNumber + o.minSpecial;
            if (o.length < minLength) {
                o.length = minLength;
            }
            const positions = [];
            if (o.lowercase && o.minLowercase > 0) {
                for (let i = 0; i < o.minLowercase; i++) {
                    positions.push("l");
                }
            }
            if (o.uppercase && o.minUppercase > 0) {
                for (let i = 0; i < o.minUppercase; i++) {
                    positions.push("u");
                }
            }
            if (o.number && o.minNumber > 0) {
                for (let i = 0; i < o.minNumber; i++) {
                    positions.push("n");
                }
            }
            if (o.special && o.minSpecial > 0) {
                for (let i = 0; i < o.minSpecial; i++) {
                    positions.push("s");
                }
            }
            while (positions.length < o.length) {
                positions.push("a");
            }
            // shuffle
            yield this.shuffleArray(positions);
            // build out the char sets
            let allCharSet = "";
            let lowercaseCharSet = "abcdefghijkmnopqrstuvwxyz";
            if (o.ambiguous) {
                lowercaseCharSet += "l";
            }
            if (o.lowercase) {
                allCharSet += lowercaseCharSet;
            }
            let uppercaseCharSet = "ABCDEFGHJKLMNPQRSTUVWXYZ";
            if (o.ambiguous) {
                uppercaseCharSet += "IO";
            }
            if (o.uppercase) {
                allCharSet += uppercaseCharSet;
            }
            let numberCharSet = "23456789";
            if (o.ambiguous) {
                numberCharSet += "01";
            }
            if (o.number) {
                allCharSet += numberCharSet;
            }
            const specialCharSet = "!@#$%^&*";
            if (o.special) {
                allCharSet += specialCharSet;
            }
            let password = "";
            for (let i = 0; i < o.length; i++) {
                let positionChars;
                switch (positions[i]) {
                    case "l":
                        positionChars = lowercaseCharSet;
                        break;
                    case "u":
                        positionChars = uppercaseCharSet;
                        break;
                    case "n":
                        positionChars = numberCharSet;
                        break;
                    case "s":
                        positionChars = specialCharSet;
                        break;
                    case "a":
                        positionChars = allCharSet;
                        break;
                    default:
                        break;
                }
                const randomCharIndex = yield this.cryptoService.randomNumber(0, positionChars.length - 1);
                password += positionChars.charAt(randomCharIndex);
            }
            return password;
        });
    }
    generatePassphrase(options) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            const o = Object.assign({}, DefaultOptions, options);
            if (o.numWords == null || o.numWords <= 2) {
                o.numWords = DefaultOptions.numWords;
            }
            if (o.wordSeparator == null || o.wordSeparator.length === 0 || o.wordSeparator.length > 1) {
                o.wordSeparator = " ";
            }
            if (o.capitalize == null) {
                o.capitalize = false;
            }
            if (o.includeNumber == null) {
                o.includeNumber = false;
            }
            const listLength = EFFLongWordList.length - 1;
            const wordList = new Array(o.numWords);
            for (let i = 0; i < o.numWords; i++) {
                const wordIndex = yield this.cryptoService.randomNumber(0, listLength);
                if (o.capitalize) {
                    wordList[i] = this.capitalize(EFFLongWordList[wordIndex]);
                }
                else {
                    wordList[i] = EFFLongWordList[wordIndex];
                }
            }
            if (o.includeNumber) {
                yield this.appendRandomNumberToRandomWord(wordList);
            }
            return wordList.join(o.wordSeparator);
        });
    }
    getOptions() {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            let options = yield this.stateService.getPasswordGenerationOptions();
            if (options == null) {
                options = Object.assign({}, DefaultOptions);
            }
            else {
                options = Object.assign({}, DefaultOptions, options);
            }
            yield this.stateService.setPasswordGenerationOptions(options);
            const enforcedOptions = yield this.enforcePasswordGeneratorPoliciesOnOptions(options);
            options = enforcedOptions[0];
            return [options, enforcedOptions[1]];
        });
    }
    enforcePasswordGeneratorPoliciesOnOptions(options) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            let enforcedPolicyOptions = yield this.getPasswordGeneratorPolicyOptions();
            if (enforcedPolicyOptions != null) {
                if (options.length < enforcedPolicyOptions.minLength) {
                    options.length = enforcedPolicyOptions.minLength;
                }
                if (enforcedPolicyOptions.useUppercase) {
                    options.uppercase = true;
                }
                if (enforcedPolicyOptions.useLowercase) {
                    options.lowercase = true;
                }
                if (enforcedPolicyOptions.useNumbers) {
                    options.number = true;
                }
                if (options.minNumber < enforcedPolicyOptions.numberCount) {
                    options.minNumber = enforcedPolicyOptions.numberCount;
                }
                if (enforcedPolicyOptions.useSpecial) {
                    options.special = true;
                }
                if (options.minSpecial < enforcedPolicyOptions.specialCount) {
                    options.minSpecial = enforcedPolicyOptions.specialCount;
                }
                // Must normalize these fields because the receiving call expects all options to pass the current rules
                if (options.minSpecial + options.minNumber > options.length) {
                    options.minSpecial = options.length - options.minNumber;
                }
                if (options.numWords < enforcedPolicyOptions.minNumberWords) {
                    options.numWords = enforcedPolicyOptions.minNumberWords;
                }
                if (enforcedPolicyOptions.capitalize) {
                    options.capitalize = true;
                }
                if (enforcedPolicyOptions.includeNumber) {
                    options.includeNumber = true;
                }
                // Force default type if password/passphrase selected via policy
                if (enforcedPolicyOptions.defaultType === "password" ||
                    enforcedPolicyOptions.defaultType === "passphrase") {
                    options.type = enforcedPolicyOptions.defaultType;
                }
            }
            else {
                // UI layer expects an instantiated object to prevent more explicit null checks
                enforcedPolicyOptions = new PasswordGeneratorPolicyOptions();
            }
            return [options, enforcedPolicyOptions];
        });
    }
    getPasswordGeneratorPolicyOptions() {
        var _a;
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            const policies = yield ((_a = this.policyService) === null || _a === void 0 ? void 0 : _a.getAll(PolicyType.PasswordGenerator));
            let enforcedOptions = null;
            if (policies == null || policies.length === 0) {
                return enforcedOptions;
            }
            policies.forEach((currentPolicy) => {
                if (!currentPolicy.enabled || currentPolicy.data == null) {
                    return;
                }
                if (enforcedOptions == null) {
                    enforcedOptions = new PasswordGeneratorPolicyOptions();
                }
                // Password wins in multi-org collisions
                if (currentPolicy.data.defaultType != null && enforcedOptions.defaultType !== "password") {
                    enforcedOptions.defaultType = currentPolicy.data.defaultType;
                }
                if (currentPolicy.data.minLength != null &&
                    currentPolicy.data.minLength > enforcedOptions.minLength) {
                    enforcedOptions.minLength = currentPolicy.data.minLength;
                }
                if (currentPolicy.data.useUpper) {
                    enforcedOptions.useUppercase = true;
                }
                if (currentPolicy.data.useLower) {
                    enforcedOptions.useLowercase = true;
                }
                if (currentPolicy.data.useNumbers) {
                    enforcedOptions.useNumbers = true;
                }
                if (currentPolicy.data.minNumbers != null &&
                    currentPolicy.data.minNumbers > enforcedOptions.numberCount) {
                    enforcedOptions.numberCount = currentPolicy.data.minNumbers;
                }
                if (currentPolicy.data.useSpecial) {
                    enforcedOptions.useSpecial = true;
                }
                if (currentPolicy.data.minSpecial != null &&
                    currentPolicy.data.minSpecial > enforcedOptions.specialCount) {
                    enforcedOptions.specialCount = currentPolicy.data.minSpecial;
                }
                if (currentPolicy.data.minNumberWords != null &&
                    currentPolicy.data.minNumberWords > enforcedOptions.minNumberWords) {
                    enforcedOptions.minNumberWords = currentPolicy.data.minNumberWords;
                }
                if (currentPolicy.data.capitalize) {
                    enforcedOptions.capitalize = true;
                }
                if (currentPolicy.data.includeNumber) {
                    enforcedOptions.includeNumber = true;
                }
            });
            return enforcedOptions;
        });
    }
    saveOptions(options) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setPasswordGenerationOptions(options);
        });
    }
    getHistory() {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            const hasKey = yield this.cryptoService.hasKey();
            if (!hasKey) {
                return new Array();
            }
            if ((yield this.stateService.getDecryptedPasswordGenerationHistory()) == null) {
                const encrypted = yield this.stateService.getEncryptedPasswordGenerationHistory();
                const decrypted = yield this.decryptHistory(encrypted);
                yield this.stateService.setDecryptedPasswordGenerationHistory(decrypted);
            }
            const passwordGenerationHistory = yield this.stateService.getDecryptedPasswordGenerationHistory();
            return passwordGenerationHistory != null
                ? passwordGenerationHistory
                : new Array();
        });
    }
    addHistory(password) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            // Cannot add new history if no key is available
            const hasKey = yield this.cryptoService.hasKey();
            if (!hasKey) {
                return;
            }
            const currentHistory = yield this.getHistory();
            // Prevent duplicates
            if (this.matchesPrevious(password, currentHistory)) {
                return;
            }
            currentHistory.unshift(new GeneratedPasswordHistory(password, Date.now()));
            // Remove old items.
            if (currentHistory.length > MaxPasswordsInHistory) {
                currentHistory.pop();
            }
            const newHistory = yield this.encryptHistory(currentHistory);
            yield this.stateService.setDecryptedPasswordGenerationHistory(currentHistory);
            return yield this.stateService.setEncryptedPasswordGenerationHistory(newHistory);
        });
    }
    clear(userId) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setEncryptedPasswordGenerationHistory(null, { userId: userId });
            yield this.stateService.setDecryptedPasswordGenerationHistory(null, { userId: userId });
        });
    }
    passwordStrength(password, userInputs = null) {
        if (password == null || password.length === 0) {
            return null;
        }
        let globalUserInputs = ["bitwarden", "bit", "warden"];
        if (userInputs != null && userInputs.length > 0) {
            globalUserInputs = globalUserInputs.concat(userInputs);
        }
        // Use a hash set to get rid of any duplicate user inputs
        const finalUserInputs = Array.from(new Set(globalUserInputs));
        const result = external_zxcvbn_namespaceObject(password, finalUserInputs);
        return result;
    }
    normalizeOptions(options, enforcedPolicyOptions) {
        options.minLowercase = 0;
        options.minUppercase = 0;
        if (!options.length || options.length < 5) {
            options.length = 5;
        }
        else if (options.length > 128) {
            options.length = 128;
        }
        if (options.length < enforcedPolicyOptions.minLength) {
            options.length = enforcedPolicyOptions.minLength;
        }
        if (!options.minNumber) {
            options.minNumber = 0;
        }
        else if (options.minNumber > options.length) {
            options.minNumber = options.length;
        }
        else if (options.minNumber > 9) {
            options.minNumber = 9;
        }
        if (options.minNumber < enforcedPolicyOptions.numberCount) {
            options.minNumber = enforcedPolicyOptions.numberCount;
        }
        if (!options.minSpecial) {
            options.minSpecial = 0;
        }
        else if (options.minSpecial > options.length) {
            options.minSpecial = options.length;
        }
        else if (options.minSpecial > 9) {
            options.minSpecial = 9;
        }
        if (options.minSpecial < enforcedPolicyOptions.specialCount) {
            options.minSpecial = enforcedPolicyOptions.specialCount;
        }
        if (options.minSpecial + options.minNumber > options.length) {
            options.minSpecial = options.length - options.minNumber;
        }
        if (options.numWords == null || options.length < 3) {
            options.numWords = 3;
        }
        else if (options.numWords > 20) {
            options.numWords = 20;
        }
        if (options.numWords < enforcedPolicyOptions.minNumberWords) {
            options.numWords = enforcedPolicyOptions.minNumberWords;
        }
        if (options.wordSeparator != null && options.wordSeparator.length > 1) {
            options.wordSeparator = options.wordSeparator[0];
        }
        this.sanitizePasswordLength(options, false);
    }
    capitalize(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
    appendRandomNumberToRandomWord(wordList) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            if (wordList == null || wordList.length <= 0) {
                return;
            }
            const index = yield this.cryptoService.randomNumber(0, wordList.length - 1);
            const num = yield this.cryptoService.randomNumber(0, 9);
            wordList[index] = wordList[index] + num;
        });
    }
    encryptHistory(history) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            if (history == null || history.length === 0) {
                return Promise.resolve([]);
            }
            const promises = history.map((item) => passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
                const encrypted = yield this.cryptoService.encrypt(item.password);
                return new GeneratedPasswordHistory(encrypted.encryptedString, item.date);
            }));
            return yield Promise.all(promises);
        });
    }
    decryptHistory(history) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            if (history == null || history.length === 0) {
                return Promise.resolve([]);
            }
            const promises = history.map((item) => passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
                const decrypted = yield this.cryptoService.decryptToUtf8(new EncString(item.password));
                return new GeneratedPasswordHistory(decrypted, item.date);
            }));
            return yield Promise.all(promises);
        });
    }
    matchesPrevious(password, history) {
        if (history == null || history.length === 0) {
            return false;
        }
        return history[history.length - 1].password === password;
    }
    // ref: https://stackoverflow.com/a/12646864/1090359
    shuffleArray(array) {
        return passwordGeneration_service_awaiter(this, void 0, void 0, function* () {
            for (let i = array.length - 1; i > 0; i--) {
                const j = yield this.cryptoService.randomNumber(0, i);
                [array[i], array[j]] = [array[j], array[i]];
            }
        });
    }
    sanitizePasswordLength(options, forGeneration) {
        let minUppercaseCalc = 0;
        let minLowercaseCalc = 0;
        let minNumberCalc = options.minNumber;
        let minSpecialCalc = options.minSpecial;
        if (options.uppercase && options.minUppercase <= 0) {
            minUppercaseCalc = 1;
        }
        else if (!options.uppercase) {
            minUppercaseCalc = 0;
        }
        if (options.lowercase && options.minLowercase <= 0) {
            minLowercaseCalc = 1;
        }
        else if (!options.lowercase) {
            minLowercaseCalc = 0;
        }
        if (options.number && options.minNumber <= 0) {
            minNumberCalc = 1;
        }
        else if (!options.number) {
            minNumberCalc = 0;
        }
        if (options.special && options.minSpecial <= 0) {
            minSpecialCalc = 1;
        }
        else if (!options.special) {
            minSpecialCalc = 0;
        }
        // This should never happen but is a final safety net
        if (!options.length || options.length < 1) {
            options.length = 10;
        }
        const minLength = minUppercaseCalc + minLowercaseCalc + minNumberCalc + minSpecialCalc;
        // Normalize and Generation both require this modification
        if (options.length < minLength) {
            options.length = minLength;
        }
        // Apply other changes if the options object passed in is for generation
        if (forGeneration) {
            options.minUppercase = minUppercaseCalc;
            options.minLowercase = minLowercaseCalc;
            options.minNumber = minNumberCalc;
            options.minSpecial = minSpecialCalc;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/policy.data.ts
class PolicyData {
    constructor(response) {
        this.id = response.id;
        this.organizationId = response.organizationId;
        this.type = response.type;
        this.data = response.data;
        this.enabled = response.enabled;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/master-password-policy-options.ts

class MasterPasswordPolicyOptions extends Domain {
    constructor() {
        super(...arguments);
        this.minComplexity = 0;
        this.minLength = 0;
        this.requireUpper = false;
        this.requireLower = false;
        this.requireNumbers = false;
        this.requireSpecial = false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/policy.ts

class Policy extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.id = obj.id;
        this.organizationId = obj.organizationId;
        this.type = obj.type;
        this.data = obj.data;
        this.enabled = obj.enabled;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/reset-password-policy-options.ts

class ResetPasswordPolicyOptions extends Domain {
    constructor() {
        super(...arguments);
        this.autoEnrollEnabled = false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/policy/policy.service.ts
var policy_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};









class PolicyService {
    constructor(stateService, organizationService) {
        this.stateService = stateService;
        this.organizationService = organizationService;
        this._policies = new external_rxjs_namespaceObject.BehaviorSubject([]);
        this.policies$ = this._policies.asObservable();
        this.stateService.activeAccountUnlocked$
            .pipe((0,external_rxjs_namespaceObject.concatMap)((unlocked) => policy_service_awaiter(this, void 0, void 0, function* () {
            if (Utils.global.bitwardenContainerService == null) {
                return;
            }
            if (!unlocked) {
                this._policies.next([]);
                return;
            }
            const data = yield this.stateService.getEncryptedPolicies();
            yield this.updateObservables(data);
        })))
            .subscribe();
    }
    /**
     * @deprecated Do not call this, use the policies$ observable collection
     */
    getAll(type, userId) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            let response = [];
            const decryptedPolicies = yield this.stateService.getDecryptedPolicies({ userId: userId });
            if (decryptedPolicies != null) {
                response = decryptedPolicies;
            }
            else {
                const diskPolicies = yield this.stateService.getEncryptedPolicies({ userId: userId });
                for (const id in diskPolicies) {
                    if (Object.prototype.hasOwnProperty.call(diskPolicies, id)) {
                        response.push(new Policy(diskPolicies[id]));
                    }
                }
                yield this.stateService.setDecryptedPolicies(response, { userId: userId });
            }
            if (type != null) {
                return response.filter((policy) => policy.type === type);
            }
            else {
                return response;
            }
        });
    }
    masterPasswordPolicyOptions$(policies) {
        const observable = policies ? (0,external_rxjs_namespaceObject.of)(policies) : this.policies$;
        return observable.pipe((0,external_rxjs_namespaceObject.map)((obsPolicies) => {
            let enforcedOptions = null;
            const filteredPolicies = obsPolicies.filter((p) => p.type === PolicyType.MasterPassword);
            if (filteredPolicies == null || filteredPolicies.length === 0) {
                return enforcedOptions;
            }
            filteredPolicies.forEach((currentPolicy) => {
                if (!currentPolicy.enabled || currentPolicy.data == null) {
                    return;
                }
                if (enforcedOptions == null) {
                    enforcedOptions = new MasterPasswordPolicyOptions();
                }
                if (currentPolicy.data.minComplexity != null &&
                    currentPolicy.data.minComplexity > enforcedOptions.minComplexity) {
                    enforcedOptions.minComplexity = currentPolicy.data.minComplexity;
                }
                if (currentPolicy.data.minLength != null &&
                    currentPolicy.data.minLength > enforcedOptions.minLength) {
                    enforcedOptions.minLength = currentPolicy.data.minLength;
                }
                if (currentPolicy.data.requireUpper) {
                    enforcedOptions.requireUpper = true;
                }
                if (currentPolicy.data.requireLower) {
                    enforcedOptions.requireLower = true;
                }
                if (currentPolicy.data.requireNumbers) {
                    enforcedOptions.requireNumbers = true;
                }
                if (currentPolicy.data.requireSpecial) {
                    enforcedOptions.requireSpecial = true;
                }
            });
            return enforcedOptions;
        }));
    }
    policyAppliesToActiveUser$(policyType, policyFilter) {
        return this.policies$.pipe((0,external_rxjs_namespaceObject.concatMap)((policies) => policy_service_awaiter(this, void 0, void 0, function* () {
            const userId = yield this.stateService.getUserId();
            return yield this.checkPoliciesThatApplyToUser(policies, policyType, policyFilter, userId);
        })));
    }
    evaluateMasterPassword(passwordStrength, newPassword, enforcedPolicyOptions) {
        if (enforcedPolicyOptions == null) {
            return true;
        }
        if (enforcedPolicyOptions.minComplexity > 0 &&
            enforcedPolicyOptions.minComplexity > passwordStrength) {
            return false;
        }
        if (enforcedPolicyOptions.minLength > 0 &&
            enforcedPolicyOptions.minLength > newPassword.length) {
            return false;
        }
        if (enforcedPolicyOptions.requireUpper && newPassword.toLocaleLowerCase() === newPassword) {
            return false;
        }
        if (enforcedPolicyOptions.requireLower && newPassword.toLocaleUpperCase() === newPassword) {
            return false;
        }
        if (enforcedPolicyOptions.requireNumbers && !/[0-9]/.test(newPassword)) {
            return false;
        }
        // eslint-disable-next-line
        if (enforcedPolicyOptions.requireSpecial && !/[!@#$%\^&*]/g.test(newPassword)) {
            return false;
        }
        return true;
    }
    getResetPasswordPolicyOptions(policies, orgId) {
        var _a, _b, _c;
        const resetPasswordPolicyOptions = new ResetPasswordPolicyOptions();
        if (policies == null || orgId == null) {
            return [resetPasswordPolicyOptions, false];
        }
        const policy = policies.find((p) => p.organizationId === orgId && p.type === PolicyType.ResetPassword && p.enabled);
        resetPasswordPolicyOptions.autoEnrollEnabled = (_b = (_a = policy === null || policy === void 0 ? void 0 : policy.data) === null || _a === void 0 ? void 0 : _a.autoEnrollEnabled) !== null && _b !== void 0 ? _b : false;
        return [resetPasswordPolicyOptions, (_c = policy === null || policy === void 0 ? void 0 : policy.enabled) !== null && _c !== void 0 ? _c : false];
    }
    mapPoliciesFromToken(policiesResponse) {
        if (policiesResponse == null || policiesResponse.data == null) {
            return null;
        }
        const policiesData = policiesResponse.data.map((p) => new PolicyData(p));
        return policiesData.map((p) => new Policy(p));
    }
    policyAppliesToUser(policyType, policyFilter, userId) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            const policies = yield this.getAll(policyType, userId);
            return this.checkPoliciesThatApplyToUser(policies, policyType, policyFilter, userId);
        });
    }
    upsert(policy) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            let policies = yield this.stateService.getEncryptedPolicies();
            if (policies == null) {
                policies = {};
            }
            policies[policy.id] = policy;
            yield this.updateObservables(policies);
            yield this.stateService.setDecryptedPolicies(null);
            yield this.stateService.setEncryptedPolicies(policies);
        });
    }
    replace(policies) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            yield this.updateObservables(policies);
            yield this.stateService.setDecryptedPolicies(null);
            yield this.stateService.setEncryptedPolicies(policies);
        });
    }
    clear(userId) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            if (userId == null || userId == (yield this.stateService.getUserId())) {
                this._policies.next([]);
            }
            yield this.stateService.setDecryptedPolicies(null, { userId: userId });
            yield this.stateService.setEncryptedPolicies(null, { userId: userId });
        });
    }
    isExcemptFromPolicies(organization, policyType) {
        if (policyType === PolicyType.MaximumVaultTimeout) {
            return organization.type === OrganizationUserType.Owner;
        }
        return organization.isExemptFromPolicies;
    }
    updateObservables(policiesMap) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            const policies = Object.values(policiesMap || {}).map((f) => new Policy(f));
            this._policies.next(policies);
        });
    }
    checkPoliciesThatApplyToUser(policies, policyType, policyFilter, userId) {
        return policy_service_awaiter(this, void 0, void 0, function* () {
            const organizations = yield this.organizationService.getAll(userId);
            const filteredPolicies = policies.filter((p) => p.type === policyType && p.enabled && (policyFilter == null || policyFilter(p)));
            const policySet = new Set(filteredPolicies.map((p) => p.organizationId));
            return organizations.some((o) => o.status >= OrganizationUserStatusType.Accepted &&
                o.usePolicies &&
                policySet.has(o.id) &&
                !this.isExcemptFromPolicies(o, policyType));
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/providerUserStatusType.ts
var ProviderUserStatusType;
(function (ProviderUserStatusType) {
    ProviderUserStatusType[ProviderUserStatusType["Invited"] = 0] = "Invited";
    ProviderUserStatusType[ProviderUserStatusType["Accepted"] = 1] = "Accepted";
    ProviderUserStatusType[ProviderUserStatusType["Confirmed"] = 2] = "Confirmed";
    ProviderUserStatusType[ProviderUserStatusType["Revoked"] = -1] = "Revoked";
})(ProviderUserStatusType || (ProviderUserStatusType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/enums/providerUserType.ts
var ProviderUserType;
(function (ProviderUserType) {
    ProviderUserType[ProviderUserType["ProviderAdmin"] = 0] = "ProviderAdmin";
    ProviderUserType[ProviderUserType["ServiceUser"] = 1] = "ServiceUser";
})(ProviderUserType || (ProviderUserType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/provider.ts


class Provider {
    constructor(obj) {
        if (obj == null) {
            return;
        }
        this.id = obj.id;
        this.name = obj.name;
        this.status = obj.status;
        this.type = obj.type;
        this.enabled = obj.enabled;
        this.userId = obj.userId;
        this.useEvents = obj.useEvents;
    }
    get canAccess() {
        if (this.isProviderAdmin) {
            return true;
        }
        return this.enabled && this.status === ProviderUserStatusType.Confirmed;
    }
    get canCreateOrganizations() {
        return this.enabled && this.isProviderAdmin;
    }
    get canManageUsers() {
        return this.isProviderAdmin;
    }
    get canAccessEventLogs() {
        return this.isProviderAdmin;
    }
    get isProviderAdmin() {
        return this.type === ProviderUserType.ProviderAdmin;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/provider.service.ts
var provider_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class ProviderService {
    constructor(stateService) {
        this.stateService = stateService;
    }
    get(id) {
        return provider_service_awaiter(this, void 0, void 0, function* () {
            const providers = yield this.stateService.getProviders();
            // eslint-disable-next-line
            if (providers == null || !providers.hasOwnProperty(id)) {
                return null;
            }
            return new Provider(providers[id]);
        });
    }
    getAll() {
        return provider_service_awaiter(this, void 0, void 0, function* () {
            const providers = yield this.stateService.getProviders();
            const response = [];
            for (const id in providers) {
                // eslint-disable-next-line
                if (providers.hasOwnProperty(id)) {
                    response.push(new Provider(providers[id]));
                }
            }
            return response;
        });
    }
    save(providers) {
        return provider_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setProviders(providers);
        });
    }
}

;// CONCATENATED MODULE: external "lunr"
const external_lunr_namespaceObject = require("lunr");
;// CONCATENATED MODULE: ../../libs/common/src/services/search.service.ts
var search_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




class SearchService {
    constructor(cipherService, logService, i18nService) {
        this.cipherService = cipherService;
        this.logService = logService;
        this.i18nService = i18nService;
        this.indexedEntityId = null;
        this.indexing = false;
        this.index = null;
        this.immediateSearchLocales = ["zh-CN", "zh-TW", "ja", "ko", "vi"];
        this.defaultSearchableMinLength = 2;
        this.searchableMinLength = this.defaultSearchableMinLength;
        this.i18nService.locale$.subscribe((locale) => {
            if (this.immediateSearchLocales.indexOf(locale) !== -1) {
                this.searchableMinLength = 1;
            }
            else {
                this.searchableMinLength = this.defaultSearchableMinLength;
            }
        });
        // Currently have to ensure this is only done a single time. Lunr allows you to register a function
        // multiple times but they will add a warning message to the console. The way they do that breaks when ran on a service worker.
        if (!SearchService.registeredPipeline) {
            SearchService.registeredPipeline = true;
            //register lunr pipeline function
            external_lunr_namespaceObject.Pipeline.registerFunction(this.normalizeAccentsPipelineFunction, "normalizeAccents");
        }
    }
    clearIndex() {
        this.indexedEntityId = null;
        this.index = null;
    }
    isSearchable(query) {
        query = SearchService.normalizeSearchQuery(query);
        const notSearchable = query == null ||
            (this.index == null && query.length < this.searchableMinLength) ||
            (this.index != null && query.length < this.searchableMinLength && query.indexOf(">") !== 0);
        return !notSearchable;
    }
    indexCiphers(indexedEntityId, ciphers) {
        return search_service_awaiter(this, void 0, void 0, function* () {
            if (this.indexing) {
                return;
            }
            this.indexing = true;
            this.indexedEntityId = indexedEntityId;
            this.index = null;
            const builder = new external_lunr_namespaceObject.Builder();
            builder.pipeline.add(this.normalizeAccentsPipelineFunction);
            builder.ref("id");
            builder.field("shortid", { boost: 100, extractor: (c) => c.id.substr(0, 8) });
            builder.field("name", {
                boost: 10,
            });
            builder.field("subtitle", {
                boost: 5,
                extractor: (c) => {
                    if (c.subTitle != null && c.type === CipherType.Card) {
                        return c.subTitle.replace(/\*/g, "");
                    }
                    return c.subTitle;
                },
            });
            builder.field("notes");
            builder.field("login.username", {
                extractor: (c) => c.type === CipherType.Login && c.login != null ? c.login.username : null,
            });
            builder.field("login.uris", { boost: 2, extractor: (c) => this.uriExtractor(c) });
            builder.field("fields", { extractor: (c) => this.fieldExtractor(c, false) });
            builder.field("fields_joined", { extractor: (c) => this.fieldExtractor(c, true) });
            builder.field("attachments", {
                extractor: (c) => this.attachmentExtractor(c, false),
            });
            builder.field("attachments_joined", {
                extractor: (c) => this.attachmentExtractor(c, true),
            });
            builder.field("organizationid", { extractor: (c) => c.organizationId });
            ciphers = ciphers || (yield this.cipherService.getAllDecrypted());
            ciphers.forEach((c) => builder.add(c));
            this.index = builder.build();
            this.indexing = false;
            this.logService.info("Finished search indexing");
        });
    }
    searchCiphers(query, filter = null, ciphers = null) {
        return search_service_awaiter(this, void 0, void 0, function* () {
            const results = [];
            if (query != null) {
                query = SearchService.normalizeSearchQuery(query.trim().toLowerCase());
            }
            if (query === "") {
                query = null;
            }
            if (ciphers == null) {
                ciphers = yield this.cipherService.getAllDecrypted();
            }
            if (filter != null && Array.isArray(filter) && filter.length > 0) {
                ciphers = ciphers.filter((c) => filter.every((f) => f == null || f(c)));
            }
            else if (filter != null) {
                ciphers = ciphers.filter(filter);
            }
            if (!this.isSearchable(query)) {
                return ciphers;
            }
            if (this.indexing) {
                yield new Promise((r) => setTimeout(r, 250));
                if (this.indexing) {
                    yield new Promise((r) => setTimeout(r, 500));
                }
            }
            const index = this.getIndexForSearch();
            if (index == null) {
                // Fall back to basic search if index is not available
                return this.searchCiphersBasic(ciphers, query);
            }
            const ciphersMap = new Map();
            ciphers.forEach((c) => ciphersMap.set(c.id, c));
            let searchResults = null;
            const isQueryString = query != null && query.length > 1 && query.indexOf(">") === 0;
            if (isQueryString) {
                try {
                    searchResults = index.search(query.substr(1).trim());
                }
                catch (e) {
                    this.logService.error(e);
                }
            }
            else {
                const soWild = external_lunr_namespaceObject.Query.wildcard.LEADING | external_lunr_namespaceObject.Query.wildcard.TRAILING;
                searchResults = index.query((q) => {
                    external_lunr_namespaceObject.tokenizer(query).forEach((token) => {
                        const t = token.toString();
                        q.term(t, { fields: ["name"], wildcard: soWild });
                        q.term(t, { fields: ["subtitle"], wildcard: soWild });
                        q.term(t, { fields: ["login.uris"], wildcard: soWild });
                        q.term(t, {});
                    });
                });
            }
            if (searchResults != null) {
                searchResults.forEach((r) => {
                    if (ciphersMap.has(r.ref)) {
                        results.push(ciphersMap.get(r.ref));
                    }
                });
            }
            return results;
        });
    }
    searchCiphersBasic(ciphers, query, deleted = false) {
        query = SearchService.normalizeSearchQuery(query.trim().toLowerCase());
        return ciphers.filter((c) => {
            if (deleted !== c.isDeleted) {
                return false;
            }
            if (c.name != null && c.name.toLowerCase().indexOf(query) > -1) {
                return true;
            }
            if (query.length >= 8 && c.id.startsWith(query)) {
                return true;
            }
            if (c.subTitle != null && c.subTitle.toLowerCase().indexOf(query) > -1) {
                return true;
            }
            if (c.login &&
                c.login.hasUris &&
                c.login.uris.some((loginUri) => { var _a; return ((_a = loginUri === null || loginUri === void 0 ? void 0 : loginUri.uri) === null || _a === void 0 ? void 0 : _a.toLowerCase().indexOf(query)) > -1; })) {
                return true;
            }
            return false;
        });
    }
    searchSends(sends, query) {
        query = SearchService.normalizeSearchQuery(query.trim().toLocaleLowerCase());
        if (query === null) {
            return sends;
        }
        const sendsMatched = [];
        const lowPriorityMatched = [];
        sends.forEach((s) => {
            var _a, _b, _c;
            if (s.name != null && s.name.toLowerCase().indexOf(query) > -1) {
                sendsMatched.push(s);
            }
            else if (query.length >= 8 &&
                (s.id.startsWith(query) ||
                    s.accessId.toLocaleLowerCase().startsWith(query) ||
                    (((_a = s.file) === null || _a === void 0 ? void 0 : _a.id) != null && s.file.id.startsWith(query)))) {
                lowPriorityMatched.push(s);
            }
            else if (s.notes != null && s.notes.toLowerCase().indexOf(query) > -1) {
                lowPriorityMatched.push(s);
            }
            else if (((_b = s.text) === null || _b === void 0 ? void 0 : _b.text) != null && s.text.text.toLowerCase().indexOf(query) > -1) {
                lowPriorityMatched.push(s);
            }
            else if (((_c = s.file) === null || _c === void 0 ? void 0 : _c.fileName) != null && s.file.fileName.toLowerCase().indexOf(query) > -1) {
                lowPriorityMatched.push(s);
            }
        });
        return sendsMatched.concat(lowPriorityMatched);
    }
    getIndexForSearch() {
        return this.index;
    }
    fieldExtractor(c, joined) {
        if (!c.hasFields) {
            return null;
        }
        let fields = [];
        c.fields.forEach((f) => {
            if (f.name != null) {
                fields.push(f.name);
            }
            if (f.type === FieldType.Text && f.value != null) {
                fields.push(f.value);
            }
        });
        fields = fields.filter((f) => f.trim() !== "");
        if (fields.length === 0) {
            return null;
        }
        return joined ? fields.join(" ") : fields;
    }
    attachmentExtractor(c, joined) {
        if (!c.hasAttachments) {
            return null;
        }
        let attachments = [];
        c.attachments.forEach((a) => {
            if (a != null && a.fileName != null) {
                if (joined && a.fileName.indexOf(".") > -1) {
                    attachments.push(a.fileName.substr(0, a.fileName.lastIndexOf(".")));
                }
                else {
                    attachments.push(a.fileName);
                }
            }
        });
        attachments = attachments.filter((f) => f.trim() !== "");
        if (attachments.length === 0) {
            return null;
        }
        return joined ? attachments.join(" ") : attachments;
    }
    uriExtractor(c) {
        if (c.type !== CipherType.Login || c.login == null || !c.login.hasUris) {
            return null;
        }
        const uris = [];
        c.login.uris.forEach((u) => {
            if (u.uri == null || u.uri === "") {
                return;
            }
            if (u.hostname != null) {
                uris.push(u.hostname);
                return;
            }
            let uri = u.uri;
            if (u.match !== UriMatchType.RegularExpression) {
                const protocolIndex = uri.indexOf("://");
                if (protocolIndex > -1) {
                    uri = uri.substr(protocolIndex + 3);
                }
                const queryIndex = uri.search(/\?|&|#/);
                if (queryIndex > -1) {
                    uri = uri.substring(0, queryIndex);
                }
            }
            uris.push(uri);
        });
        return uris.length > 0 ? uris : null;
    }
    normalizeAccentsPipelineFunction(token) {
        const searchableFields = ["name", "login.username", "subtitle", "notes"];
        const fields = token.metadata["fields"];
        const checkFields = fields.every((i) => searchableFields.includes(i));
        if (checkFields) {
            return SearchService.normalizeSearchQuery(token.toString());
        }
        return token;
    }
    // Remove accents/diacritics characters from text. This regex is equivalent to the Diacritic unicode property escape, i.e. it will match all diacritic characters.
    static normalizeSearchQuery(query) {
        return query === null || query === void 0 ? void 0 : query.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    }
}
SearchService.registeredPipeline = false;

;// CONCATENATED MODULE: ../../libs/common/src/enums/sendType.ts
var SendType;
(function (SendType) {
    SendType[SendType["Text"] = 0] = "Text";
    SendType[SendType["File"] = 1] = "File";
})(SendType || (SendType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/data/send-file.data.ts
class SendFileData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.id = data.id;
        this.fileName = data.fileName;
        this.size = data.size;
        this.sizeName = data.sizeName;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/send-text.data.ts
class SendTextData {
    constructor(data) {
        if (data == null) {
            return;
        }
        this.text = data.text;
        this.hidden = data.hidden;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/send.data.ts



class SendData {
    constructor(response) {
        if (response == null) {
            return;
        }
        this.id = response.id;
        this.accessId = response.accessId;
        this.type = response.type;
        this.name = response.name;
        this.notes = response.notes;
        this.key = response.key;
        this.maxAccessCount = response.maxAccessCount;
        this.accessCount = response.accessCount;
        this.revisionDate = response.revisionDate;
        this.expirationDate = response.expirationDate;
        this.deletionDate = response.deletionDate;
        this.password = response.password;
        this.disabled = response.disable;
        this.hideEmail = response.hideEmail;
        switch (this.type) {
            case SendType.Text:
                this.text = new SendTextData(response.text);
                break;
            case SendType.File:
                this.file = new SendFileData(response.file);
                break;
            default:
                break;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/view/send-file.view.ts
class SendFileView {
    constructor(f) {
        this.id = null;
        this.size = null;
        this.sizeName = null;
        this.fileName = null;
        if (!f) {
            return;
        }
        this.id = f.id;
        this.size = f.size;
        this.sizeName = f.sizeName;
    }
    get fileSize() {
        try {
            if (this.size != null) {
                return parseInt(this.size, null);
            }
        }
        catch (_a) {
            // Invalid file size.
        }
        return 0;
    }
    static fromJSON(json) {
        if (json == null) {
            return null;
        }
        return Object.assign(new SendFileView(), json);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/view/send-text.view.ts
class SendTextView {
    constructor(t) {
        this.text = null;
        if (!t) {
            return;
        }
        this.hidden = t.hidden;
    }
    get maskedText() {
        return this.text != null ? "••••••••" : null;
    }
    static fromJSON(json) {
        if (json == null) {
            return null;
        }
        return Object.assign(new SendTextView(), json);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/view/send.view.ts




class SendView {
    constructor(s) {
        this.id = null;
        this.accessId = null;
        this.name = null;
        this.notes = null;
        this.type = null;
        this.text = new SendTextView();
        this.file = new SendFileView();
        this.maxAccessCount = null;
        this.accessCount = 0;
        this.revisionDate = null;
        this.deletionDate = null;
        this.expirationDate = null;
        this.password = null;
        this.disabled = false;
        this.hideEmail = false;
        if (!s) {
            return;
        }
        this.id = s.id;
        this.accessId = s.accessId;
        this.type = s.type;
        this.maxAccessCount = s.maxAccessCount;
        this.accessCount = s.accessCount;
        this.revisionDate = s.revisionDate;
        this.deletionDate = s.deletionDate;
        this.expirationDate = s.expirationDate;
        this.disabled = s.disabled;
        this.password = s.password;
        this.hideEmail = s.hideEmail;
    }
    get urlB64Key() {
        return Utils.fromBufferToUrlB64(this.key);
    }
    get maxAccessCountReached() {
        if (this.maxAccessCount == null) {
            return false;
        }
        return this.accessCount >= this.maxAccessCount;
    }
    get expired() {
        if (this.expirationDate == null) {
            return false;
        }
        return this.expirationDate <= new Date();
    }
    get pendingDelete() {
        return this.deletionDate <= new Date();
    }
    toJSON() {
        return Utils.merge(this, {
            key: Utils.fromBufferToB64(this.key),
        });
    }
    static fromJSON(json) {
        var _a;
        if (json == null) {
            return null;
        }
        return Object.assign(new SendView(), json, {
            key: (_a = Utils.fromB64ToArray(json.key)) === null || _a === void 0 ? void 0 : _a.buffer,
            cryptoKey: SymmetricCryptoKey.fromJSON(json.cryptoKey),
            text: SendTextView.fromJSON(json.text),
            file: SendFileView.fromJSON(json.file),
            revisionDate: json.revisionDate == null ? null : new Date(json.revisionDate),
            deletionDate: json.deletionDate == null ? null : new Date(json.deletionDate),
            expirationDate: json.expirationDate == null ? null : new Date(json.expirationDate),
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/send-file.ts
var send_file_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class SendFile extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.size = obj.size;
        this.buildDomainModel(this, obj, {
            id: null,
            sizeName: null,
            fileName: null,
        }, ["id", "sizeName"]);
    }
    decrypt(key) {
        return send_file_awaiter(this, void 0, void 0, function* () {
            const view = yield this.decryptObj(new SendFileView(this), {
                fileName: null,
            }, null, key);
            return view;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/send-text.ts


class SendText extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.hidden = obj.hidden;
        this.buildDomainModel(this, obj, {
            text: null,
        }, []);
    }
    decrypt(key) {
        return this.decryptObj(new SendTextView(this), {
            text: null,
        }, null, key);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/send.ts
var send_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};






class Send extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            id: null,
            accessId: null,
            name: null,
            notes: null,
            key: null,
        }, ["id", "accessId"]);
        this.type = obj.type;
        this.maxAccessCount = obj.maxAccessCount;
        this.accessCount = obj.accessCount;
        this.password = obj.password;
        this.disabled = obj.disabled;
        this.revisionDate = obj.revisionDate != null ? new Date(obj.revisionDate) : null;
        this.deletionDate = obj.deletionDate != null ? new Date(obj.deletionDate) : null;
        this.expirationDate = obj.expirationDate != null ? new Date(obj.expirationDate) : null;
        this.hideEmail = obj.hideEmail;
        switch (this.type) {
            case SendType.Text:
                this.text = new SendText(obj.text);
                break;
            case SendType.File:
                this.file = new SendFile(obj.file);
                break;
            default:
                break;
        }
    }
    decrypt() {
        return send_awaiter(this, void 0, void 0, function* () {
            const model = new SendView(this);
            const cryptoService = Utils.getContainerService().getCryptoService();
            try {
                model.key = yield cryptoService.decryptToBytes(this.key, null);
                model.cryptoKey = yield cryptoService.makeSendKey(model.key);
            }
            catch (e) {
                // TODO: error?
            }
            yield this.decryptObj(model, {
                name: null,
                notes: null,
            }, null, model.cryptoKey);
            switch (this.type) {
                case SendType.File:
                    model.file = yield this.file.decrypt(model.cryptoKey);
                    break;
                case SendType.Text:
                    model.text = yield this.text.decrypt(model.cryptoKey);
                    break;
                default:
                    break;
            }
            return model;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/send-file.api.ts

class SendFileApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.id = this.getResponseProperty("Id");
        this.fileName = this.getResponseProperty("FileName");
        this.size = this.getResponseProperty("Size");
        this.sizeName = this.getResponseProperty("SizeName");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/api/send-text.api.ts

class SendTextApi extends BaseResponse {
    constructor(data = null) {
        super(data);
        if (data == null) {
            return;
        }
        this.text = this.getResponseProperty("Text");
        this.hidden = this.getResponseProperty("Hidden") || false;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/send.request.ts



class SendRequest {
    constructor(send, fileLength) {
        this.type = send.type;
        this.fileLength = fileLength;
        this.name = send.name ? send.name.encryptedString : null;
        this.notes = send.notes ? send.notes.encryptedString : null;
        this.maxAccessCount = send.maxAccessCount;
        this.expirationDate = send.expirationDate != null ? send.expirationDate.toISOString() : null;
        this.deletionDate = send.deletionDate != null ? send.deletionDate.toISOString() : null;
        this.key = send.key != null ? send.key.encryptedString : null;
        this.password = send.password;
        this.disabled = send.disabled;
        this.hideEmail = send.hideEmail;
        switch (this.type) {
            case SendType.Text:
                this.text = new SendTextApi();
                this.text.text = send.text.text != null ? send.text.text.encryptedString : null;
                this.text.hidden = send.text.hidden;
                break;
            case SendType.File:
                this.file = new SendFileApi();
                this.file.fileName = send.file.fileName != null ? send.file.fileName.encryptedString : null;
                break;
            default:
                break;
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/send.service.ts
var send_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};









class SendService {
    constructor(cryptoService, apiService, fileUploadService, i18nService, cryptoFunctionService, stateService) {
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.fileUploadService = fileUploadService;
        this.i18nService = i18nService;
        this.cryptoFunctionService = cryptoFunctionService;
        this.stateService = stateService;
    }
    clearCache() {
        return send_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedSends(null);
        });
    }
    encrypt(model, file, password, key) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            let fileData = null;
            const send = new Send();
            send.id = model.id;
            send.type = model.type;
            send.disabled = model.disabled;
            send.hideEmail = model.hideEmail;
            send.maxAccessCount = model.maxAccessCount;
            if (model.key == null) {
                model.key = yield this.cryptoFunctionService.randomBytes(16);
                model.cryptoKey = yield this.cryptoService.makeSendKey(model.key);
            }
            if (password != null) {
                const passwordHash = yield this.cryptoFunctionService.pbkdf2(password, model.key, "sha256", SEND_KDF_ITERATIONS);
                send.password = Utils.fromBufferToB64(passwordHash);
            }
            send.key = yield this.cryptoService.encrypt(model.key, key);
            send.name = yield this.cryptoService.encrypt(model.name, model.cryptoKey);
            send.notes = yield this.cryptoService.encrypt(model.notes, model.cryptoKey);
            if (send.type === SendType.Text) {
                send.text = new SendText();
                send.text.text = yield this.cryptoService.encrypt(model.text.text, model.cryptoKey);
                send.text.hidden = model.text.hidden;
            }
            else if (send.type === SendType.File) {
                send.file = new SendFile();
                if (file != null) {
                    if (file instanceof ArrayBuffer) {
                        const [name, data] = yield this.encryptFileData(model.file.fileName, file, model.cryptoKey);
                        send.file.fileName = name;
                        fileData = data;
                    }
                    else {
                        fileData = yield this.parseFile(send, file, model.cryptoKey);
                    }
                }
            }
            return [send, fileData];
        });
    }
    get(id) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const sends = yield this.stateService.getEncryptedSends();
            // eslint-disable-next-line
            if (sends == null || !sends.hasOwnProperty(id)) {
                return null;
            }
            return new Send(sends[id]);
        });
    }
    getAll() {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const sends = yield this.stateService.getEncryptedSends();
            const response = [];
            for (const id in sends) {
                // eslint-disable-next-line
                if (sends.hasOwnProperty(id)) {
                    response.push(new Send(sends[id]));
                }
            }
            return response;
        });
    }
    getAllDecrypted() {
        return send_service_awaiter(this, void 0, void 0, function* () {
            let decSends = yield this.stateService.getDecryptedSends();
            if (decSends != null) {
                return decSends;
            }
            decSends = [];
            const hasKey = yield this.cryptoService.hasKey();
            if (!hasKey) {
                throw new Error("No key.");
            }
            const promises = [];
            const sends = yield this.getAll();
            sends.forEach((send) => {
                promises.push(send.decrypt().then((f) => decSends.push(f)));
            });
            yield Promise.all(promises);
            decSends.sort(Utils.getSortFunction(this.i18nService, "name"));
            yield this.stateService.setDecryptedSends(decSends);
            return decSends;
        });
    }
    saveWithServer(sendData) {
        var _a;
        return send_service_awaiter(this, void 0, void 0, function* () {
            const request = new SendRequest(sendData[0], (_a = sendData[1]) === null || _a === void 0 ? void 0 : _a.buffer.byteLength);
            let response;
            if (sendData[0].id == null) {
                if (sendData[0].type === SendType.Text) {
                    response = yield this.apiService.postSend(request);
                }
                else {
                    try {
                        const uploadDataResponse = yield this.apiService.postFileTypeSend(request);
                        response = uploadDataResponse.sendResponse;
                        yield this.fileUploadService.uploadSendFile(uploadDataResponse, sendData[0].file.fileName, sendData[1]);
                    }
                    catch (e) {
                        if (e instanceof ErrorResponse && e.statusCode === 404) {
                            response = yield this.legacyServerSendFileUpload(sendData, request);
                        }
                        else if (e instanceof ErrorResponse) {
                            throw new Error(e.getSingleMessage());
                        }
                        else {
                            throw e;
                        }
                    }
                }
                sendData[0].id = response.id;
                sendData[0].accessId = response.accessId;
            }
            else {
                response = yield this.apiService.putSend(sendData[0].id, request);
            }
            const data = new SendData(response);
            yield this.upsert(data);
        });
    }
    /**
     * @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
     * This method still exists for backward compatibility with old server versions.
     */
    legacyServerSendFileUpload(sendData, request) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const fd = new FormData();
            try {
                const blob = new Blob([sendData[1].buffer], { type: "application/octet-stream" });
                fd.append("model", JSON.stringify(request));
                fd.append("data", blob, sendData[0].file.fileName.encryptedString);
            }
            catch (e) {
                if (Utils.isNode && !Utils.isBrowser) {
                    fd.append("model", JSON.stringify(request));
                    fd.append("data", Buffer.from(sendData[1].buffer), {
                        filepath: sendData[0].file.fileName.encryptedString,
                        contentType: "application/octet-stream",
                    });
                }
                else {
                    throw e;
                }
            }
            return yield this.apiService.postSendFileLegacy(fd);
        });
    }
    upsert(send) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            let sends = yield this.stateService.getEncryptedSends();
            if (sends == null) {
                sends = {};
            }
            if (send instanceof SendData) {
                const s = send;
                sends[s.id] = s;
            }
            else {
                send.forEach((s) => {
                    sends[s.id] = s;
                });
            }
            yield this.replace(sends);
        });
    }
    replace(sends) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedSends(null);
            yield this.stateService.setEncryptedSends(sends);
        });
    }
    clear() {
        return send_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedSends(null);
            yield this.stateService.setEncryptedSends(null);
        });
    }
    delete(id) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const sends = yield this.stateService.getEncryptedSends();
            if (sends == null) {
                return;
            }
            if (typeof id === "string") {
                if (sends[id] == null) {
                    return;
                }
                delete sends[id];
            }
            else {
                id.forEach((i) => {
                    delete sends[i];
                });
            }
            yield this.replace(sends);
        });
    }
    deleteWithServer(id) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.deleteSend(id);
            yield this.delete(id);
        });
    }
    removePasswordWithServer(id) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.apiService.putSendRemovePassword(id);
            const data = new SendData(response);
            yield this.upsert(data);
        });
    }
    parseFile(send, file, key) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onload = (evt) => send_service_awaiter(this, void 0, void 0, function* () {
                try {
                    const [name, data] = yield this.encryptFileData(file.name, evt.target.result, key);
                    send.file.fileName = name;
                    resolve(data);
                }
                catch (e) {
                    reject(e);
                }
            });
            reader.onerror = () => {
                reject("Error reading file.");
            };
        });
    }
    encryptFileData(fileName, data, key) {
        return send_service_awaiter(this, void 0, void 0, function* () {
            const encFileName = yield this.cryptoService.encrypt(fileName, key);
            const encFileData = yield this.cryptoService.encryptToBytes(data, key);
            return [encFileName, encFileData];
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/settings.service.ts
var settings_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class SettingsService {
    constructor(stateService) {
        this.stateService = stateService;
        this._settings = new external_rxjs_namespaceObject.BehaviorSubject({});
        this.settings$ = this._settings.asObservable();
        this.stateService.activeAccountUnlocked$
            .pipe((0,external_rxjs_namespaceObject.concatMap)((unlocked) => settings_service_awaiter(this, void 0, void 0, function* () {
            if (Utils.global.bitwardenContainerService == null) {
                return;
            }
            if (!unlocked) {
                this._settings.next({});
                return;
            }
            const data = yield this.stateService.getSettings();
            this._settings.next(data);
        })))
            .subscribe();
    }
    setEquivalentDomains(equivalentDomains) {
        var _a;
        return settings_service_awaiter(this, void 0, void 0, function* () {
            const settings = (_a = this._settings.getValue()) !== null && _a !== void 0 ? _a : {};
            settings.equivalentDomains = equivalentDomains;
            this._settings.next(settings);
            yield this.stateService.setSettings(settings);
        });
    }
    clear(userId) {
        return settings_service_awaiter(this, void 0, void 0, function* () {
            if (userId == null || userId == (yield this.stateService.getUserId())) {
                this._settings.next({});
            }
            yield this.stateService.setSettings(null, { userId: userId });
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/storageLocation.ts
var StorageLocation;
(function (StorageLocation) {
    StorageLocation["Both"] = "both";
    StorageLocation["Disk"] = "disk";
    StorageLocation["Memory"] = "memory";
})(StorageLocation || (StorageLocation = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/data/event.data.ts
class EventData {
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/provider.data.ts
class ProviderData {
    constructor(response) {
        this.id = response.id;
        this.name = response.name;
        this.status = response.status;
        this.type = response.type;
        this.enabled = response.enabled;
        this.userId = response.userId;
        this.useEvents = response.useEvents;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/state.ts
class State {
    constructor(globals) {
        this.accounts = {};
        this.authenticatedAccounts = [];
        this.accountActivity = {};
        this.globals = globals;
    }
    // TODO, make Jsonify<State,TGlobalState,TAccount> work. It currently doesn't because Globals doesn't implement Jsonify.
    static fromJSON(obj, accountDeserializer) {
        if (obj == null) {
            return null;
        }
        return Object.assign(new State(null), obj, {
            accounts: State.buildAccountMapFromJSON(obj === null || obj === void 0 ? void 0 : obj.accounts, accountDeserializer),
        });
    }
    static buildAccountMapFromJSON(jsonAccounts, accountDeserializer) {
        if (!jsonAccounts) {
            return {};
        }
        const accounts = {};
        for (const userId in jsonAccounts) {
            accounts[userId] = accountDeserializer(jsonAccounts[userId]);
        }
        return accounts;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/data/folder.data.ts
class FolderData {
    constructor(response) {
        this.name = response.name;
        this.id = response.id;
        this.revisionDate = response.revisionDate;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/state.service.ts
var state_service_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var state_service_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var state_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





















const keys = {
    state: "state",
    global: "global",
    authenticatedAccounts: "authenticatedAccounts",
    activeUserId: "activeUserId",
    tempAccountSettings: "tempAccountSettings",
    accountActivity: "accountActivity",
};
const partialKeys = {
    autoKey: "_masterkey_auto",
    biometricKey: "_masterkey_biometric",
    masterKey: "_masterkey",
};
const DDG_SHARED_KEY = "DuckDuckGoSharedKey";
class StateService {
    constructor(storageService, secureStorageService, memoryStorageService, logService, stateMigrationService, stateFactory, useAccountCache = true) {
        this.storageService = storageService;
        this.secureStorageService = secureStorageService;
        this.memoryStorageService = memoryStorageService;
        this.logService = logService;
        this.stateMigrationService = stateMigrationService;
        this.stateFactory = stateFactory;
        this.useAccountCache = useAccountCache;
        this.accountsSubject = new external_rxjs_namespaceObject.BehaviorSubject({});
        this.accounts$ = this.accountsSubject.asObservable();
        this.activeAccountSubject = new external_rxjs_namespaceObject.BehaviorSubject(null);
        this.activeAccount$ = this.activeAccountSubject.asObservable();
        this.activeAccountUnlockedSubject = new external_rxjs_namespaceObject.BehaviorSubject(false);
        this.activeAccountUnlocked$ = this.activeAccountUnlockedSubject.asObservable();
        this.hasBeenInited = false;
        this.isRecoveredSession = false;
        this.accountDiskCache = new external_rxjs_namespaceObject.BehaviorSubject({});
        // default account serializer, must be overridden by child class
        this.accountDeserializer = Account.fromJSON;
        // If the account gets changed, verify the new account is unlocked
        this.activeAccountSubject
            .pipe((0,external_rxjs_namespaceObject.concatMap)((userId) => state_service_awaiter(this, void 0, void 0, function* () {
            if (userId == null && this.activeAccountUnlockedSubject.getValue() == false) {
                return;
            }
            else if (userId == null) {
                this.activeAccountUnlockedSubject.next(false);
            }
            // FIXME: This should be refactored into AuthService or a similar service,
            //  as checking for the existance of the crypto key is a low level
            //  implementation detail.
            this.activeAccountUnlockedSubject.next((yield this.getCryptoMasterKey()) != null);
        })))
            .subscribe();
    }
    init() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (this.hasBeenInited) {
                return;
            }
            if (yield this.stateMigrationService.needsMigration()) {
                yield this.stateMigrationService.migrate();
            }
            yield this.state().then((state) => state_service_awaiter(this, void 0, void 0, function* () {
                if (state == null) {
                    yield this.setState(new State(this.createGlobals()));
                }
                else {
                    this.isRecoveredSession = true;
                }
            }));
            yield this.initAccountState();
            this.hasBeenInited = true;
        });
    }
    initAccountState() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (this.isRecoveredSession) {
                return;
            }
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                var _a;
                state.authenticatedAccounts =
                    (_a = (yield this.storageService.get(keys.authenticatedAccounts))) !== null && _a !== void 0 ? _a : [];
                for (const i in state.authenticatedAccounts) {
                    if (i != null) {
                        yield this.syncAccountFromDisk(state.authenticatedAccounts[i]);
                    }
                }
                const storedActiveUser = yield this.storageService.get(keys.activeUserId);
                if (storedActiveUser != null) {
                    state.activeUserId = storedActiveUser;
                }
                yield this.pushAccounts();
                this.activeAccountSubject.next(state.activeUserId);
                return state;
            }));
        });
    }
    syncAccountFromDisk(userId) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (userId == null) {
                return;
            }
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                if (state.accounts == null) {
                    state.accounts = {};
                }
                state.accounts[userId] = this.createAccount();
                const diskAccount = yield this.getAccountFromDisk({ userId: userId });
                state.accounts[userId].profile = diskAccount.profile;
                return state;
            }));
        });
    }
    addAccount(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            account = yield this.setAccountEnvironmentUrls(account);
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                state.authenticatedAccounts.push(account.profile.userId);
                yield this.storageService.save(keys.authenticatedAccounts, state.authenticatedAccounts);
                state.accounts[account.profile.userId] = account;
                return state;
            }));
            yield this.scaffoldNewAccountStorage(account);
            yield this.setLastActive(new Date().getTime(), { userId: account.profile.userId });
            yield this.setActiveUser(account.profile.userId);
            this.activeAccountSubject.next(account.profile.userId);
        });
    }
    setActiveUser(userId) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            this.clearDecryptedDataForActiveUser();
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                state.activeUserId = userId;
                yield this.storageService.save(keys.activeUserId, userId);
                this.activeAccountSubject.next(state.activeUserId);
                return state;
            }));
            yield this.pushAccounts();
        });
    }
    clean(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultInMemoryOptions());
            yield this.deAuthenticateAccount(options.userId);
            if (options.userId === ((_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId)) {
                yield this.dynamicallySetActiveUser();
            }
            yield this.removeAccountFromDisk(options === null || options === void 0 ? void 0 : options.userId);
            this.removeAccountFromMemory(options === null || options === void 0 ? void 0 : options.userId);
            yield this.pushAccounts();
        });
    }
    getAccessToken(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            return (_b = (_a = (yield this.getAccount(options))) === null || _a === void 0 ? void 0 : _a.tokens) === null || _b === void 0 ? void 0 : _b.accessToken;
        });
    }
    setAccessToken(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            const account = yield this.getAccount(options);
            account.tokens.accessToken = value;
            yield this.saveAccount(account, options);
        });
    }
    getAddEditCipherInfo(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.addEditCipherInfo;
        });
    }
    setAddEditCipherInfo(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.addEditCipherInfo = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getAlwaysShowDock(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.alwaysShowDock) !== null && _b !== void 0 ? _b : false);
        });
    }
    setAlwaysShowDock(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.alwaysShowDock = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getApiKeyClientId(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            return (_b = (_a = (yield this.getAccount(options))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.apiKeyClientId;
        });
    }
    setApiKeyClientId(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            const account = yield this.getAccount(options);
            account.profile.apiKeyClientId = value;
            yield this.saveAccount(account, options);
        });
    }
    getApiKeyClientSecret(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            return (_b = (_a = (yield this.getAccount(options))) === null || _a === void 0 ? void 0 : _a.keys) === null || _b === void 0 ? void 0 : _b.apiKeyClientSecret;
        });
    }
    setApiKeyClientSecret(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            const account = yield this.getAccount(options);
            account.keys.apiKeyClientSecret = value;
            yield this.saveAccount(account, options);
        });
    }
    getAutoConfirmFingerPrints(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.autoConfirmFingerPrints) !== null && _c !== void 0 ? _c : false);
        });
    }
    setAutoConfirmFingerprints(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.autoConfirmFingerPrints = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getAutoFillOnPageLoadDefault(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.autoFillOnPageLoadDefault) !== null && _c !== void 0 ? _c : true);
        });
    }
    setAutoFillOnPageLoadDefault(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.autoFillOnPageLoadDefault = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getBiometricAwaitingAcceptance(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.biometricAwaitingAcceptance) !== null && _b !== void 0 ? _b : false);
        });
    }
    setBiometricAwaitingAcceptance(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.biometricAwaitingAcceptance = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getBiometricFingerprintValidated(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.biometricFingerprintValidated) !== null && _b !== void 0 ? _b : false);
        });
    }
    setBiometricFingerprintValidated(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.biometricFingerprintValidated = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getBiometricText(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.biometricText;
        });
    }
    setBiometricText(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.biometricText = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getBiometricUnlock(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.biometricUnlock) !== null && _c !== void 0 ? _c : false);
        });
    }
    setBiometricUnlock(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.biometricUnlock = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getCanAccessPremium(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (!(yield this.getIsAuthenticated(options))) {
                return false;
            }
            return ((yield this.getHasPremiumPersonally(options)) ||
                (yield this.getHasPremiumFromOrganization(options)));
        });
    }
    getHasPremiumPersonally(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            return (_a = account === null || account === void 0 ? void 0 : account.profile) === null || _a === void 0 ? void 0 : _a.hasPremiumPersonally;
        });
    }
    setHasPremiumPersonally(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.hasPremiumPersonally = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getHasPremiumFromOrganization(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            if ((_a = account.profile) === null || _a === void 0 ? void 0 : _a.hasPremiumFromOrganization) {
                return true;
            }
            // TODO: older server versions won't send the hasPremiumFromOrganization flag, so we're keeping the old logic
            // for backwards compatibility. It can be removed after everyone has upgraded.
            const organizations = yield this.getOrganizations(options);
            if (organizations == null) {
                return false;
            }
            for (const id of Object.keys(organizations)) {
                const o = organizations[id];
                if (o.enabled && o.usersGetPremium && !o.isProviderUser) {
                    return true;
                }
            }
            return false;
        });
    }
    setHasPremiumFromOrganization(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.hasPremiumFromOrganization = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getClearClipboard(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.clearClipboard) !== null && _c !== void 0 ? _c : null);
        });
    }
    setClearClipboard(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.clearClipboard = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getCollapsedGroupings(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.collapsedGroupings;
        });
    }
    setCollapsedGroupings(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.collapsedGroupings = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getConvertAccountToKeyConnector(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.convertAccountToKeyConnector;
        });
    }
    setConvertAccountToKeyConnector(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.convertAccountToKeyConnector = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getCryptoMasterKey(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            return (_a = account === null || account === void 0 ? void 0 : account.keys) === null || _a === void 0 ? void 0 : _a.cryptoMasterKey;
        });
    }
    setCryptoMasterKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.cryptoMasterKey = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            if (options.userId == this.activeAccountSubject.getValue()) {
                const nextValue = value != null;
                // Avoid emitting if we are already unlocked
                if (this.activeAccountUnlockedSubject.getValue() != nextValue) {
                    this.activeAccountUnlockedSubject.next(nextValue);
                }
            }
        });
    }
    getCryptoMasterKeyAuto(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(this.reconcileOptions(options, { keySuffix: "auto" }), yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return null;
            }
            return yield this.secureStorageService.get(`${options.userId}${partialKeys.autoKey}`, options);
        });
    }
    setCryptoMasterKeyAuto(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(this.reconcileOptions(options, { keySuffix: "auto" }), yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return;
            }
            yield this.saveSecureStorageKey(partialKeys.autoKey, value, options);
        });
    }
    getCryptoMasterKeyB64(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return null;
            }
            return yield this.secureStorageService.get(`${options === null || options === void 0 ? void 0 : options.userId}${partialKeys.masterKey}`, options);
        });
    }
    setCryptoMasterKeyB64(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return;
            }
            yield this.saveSecureStorageKey(partialKeys.masterKey, value, options);
        });
    }
    getCryptoMasterKeyBiometric(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(this.reconcileOptions(options, { keySuffix: "biometric" }), yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return null;
            }
            return yield this.secureStorageService.get(`${options.userId}${partialKeys.biometricKey}`, options);
        });
    }
    hasCryptoMasterKeyBiometric(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(this.reconcileOptions(options, { keySuffix: "biometric" }), yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return false;
            }
            return yield this.secureStorageService.has(`${options.userId}${partialKeys.biometricKey}`, options);
        });
    }
    setCryptoMasterKeyBiometric(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(this.reconcileOptions(options, { keySuffix: "biometric" }), yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return;
            }
            yield this.saveSecureStorageKey(partialKeys.biometricKey, value, options);
        });
    }
    getDecryptedCiphers(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.ciphers) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedCiphers(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.ciphers.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedCollections(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.collections) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedCollections(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.collections.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedCryptoSymmetricKey(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            return (_b = (_a = account === null || account === void 0 ? void 0 : account.keys) === null || _a === void 0 ? void 0 : _a.cryptoSymmetricKey) === null || _b === void 0 ? void 0 : _b.decrypted;
        });
    }
    setDecryptedCryptoSymmetricKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.cryptoSymmetricKey.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedOrganizationKeys(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            return Utils.recordToMap((_b = (_a = account === null || account === void 0 ? void 0 : account.keys) === null || _a === void 0 ? void 0 : _a.organizationKeys) === null || _b === void 0 ? void 0 : _b.decrypted);
        });
    }
    setDecryptedOrganizationKeys(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.organizationKeys.decrypted = Utils.mapToRecord(value);
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedPasswordGenerationHistory(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.passwordGenerationHistory) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedPasswordGenerationHistory(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.passwordGenerationHistory.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedPinProtected(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.pinProtected) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedPinProtected(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.settings.pinProtected.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedPolicies(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.policies) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedPolicies(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.policies.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedPrivateKey(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.keys) === null || _b === void 0 ? void 0 : _b.privateKey.decrypted;
        });
    }
    setDecryptedPrivateKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.privateKey.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedProviderKeys(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            return Utils.recordToMap((_b = (_a = account === null || account === void 0 ? void 0 : account.keys) === null || _a === void 0 ? void 0 : _a.providerKeys) === null || _b === void 0 ? void 0 : _b.decrypted);
        });
    }
    setDecryptedProviderKeys(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.providerKeys.decrypted = Utils.mapToRecord(value);
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDecryptedSends(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.sends) === null || _c === void 0 ? void 0 : _c.decrypted;
        });
    }
    setDecryptedSends(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.data.sends.decrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getDefaultUriMatch(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.defaultUriMatch;
        });
    }
    setDefaultUriMatch(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.defaultUriMatch = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableAddLoginNotification(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableAddLoginNotification) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableAddLoginNotification(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableAddLoginNotification = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableAutoBiometricsPrompt(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableAutoBiometricsPrompt) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableAutoBiometricsPrompt(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableAutoBiometricsPrompt = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableAutoTotpCopy(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableAutoTotpCopy) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableAutoTotpCopy(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableAutoTotpCopy = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableBadgeCounter(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableBadgeCounter) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableBadgeCounter(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableBadgeCounter = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableChangedPasswordNotification(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableChangedPasswordNotification) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableChangedPasswordNotification(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableChangedPasswordNotification = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableContextMenuItem(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableContextMenuItem) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableContextMenuItem(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableContextMenuItem = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDisableFavicon(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.disableFavicon) !== null && _b !== void 0 ? _b : false);
        });
    }
    setDisableFavicon(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.disableFavicon = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getDisableGa(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.disableGa) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDisableGa(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.disableGa = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDontShowCardsCurrentTab(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.dontShowCardsCurrentTab) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDontShowCardsCurrentTab(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.dontShowCardsCurrentTab = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDontShowIdentitiesCurrentTab(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.dontShowIdentitiesCurrentTab) !== null && _c !== void 0 ? _c : false);
        });
    }
    setDontShowIdentitiesCurrentTab(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.dontShowIdentitiesCurrentTab = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getDuckDuckGoSharedKey(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return null;
            }
            return yield this.secureStorageService.get(DDG_SHARED_KEY, options);
        });
    }
    setDuckDuckGoSharedKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultSecureStorageOptions());
            if ((options === null || options === void 0 ? void 0 : options.userId) == null) {
                return;
            }
            value == null
                ? yield this.secureStorageService.remove(DDG_SHARED_KEY, options)
                : yield this.secureStorageService.save(DDG_SHARED_KEY, value, options);
        });
    }
    getEmail(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.email;
        });
    }
    setEmail(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.profile.email = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getEmailVerified(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile.emailVerified) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEmailVerified(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.emailVerified = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableAlwaysOnTop(options) {
        var _a, _b, _c, _d;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const accountPreference = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.enableAlwaysOnTop;
            const globalPreference = (_c = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _c === void 0 ? void 0 : _c.enableAlwaysOnTop;
            return (_d = accountPreference !== null && accountPreference !== void 0 ? accountPreference : globalPreference) !== null && _d !== void 0 ? _d : false;
        });
    }
    setEnableAlwaysOnTop(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.enableAlwaysOnTop = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableAlwaysOnTop = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableAutoFillOnPageLoad(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.enableAutoFillOnPageLoad) !== null && _c !== void 0 ? _c : false);
        });
    }
    setEnableAutoFillOnPageLoad(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.enableAutoFillOnPageLoad = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableBiometric(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableBiometrics) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableBiometric(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableBiometrics = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableBrowserIntegration(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableBrowserIntegration) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableBrowserIntegration(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableBrowserIntegration = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableBrowserIntegrationFingerprint(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableBrowserIntegrationFingerprint) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableBrowserIntegrationFingerprint(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableBrowserIntegrationFingerprint = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableCloseToTray(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableCloseToTray) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableCloseToTray(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableCloseToTray = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableDuckDuckGoBrowserIntegration(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableDuckDuckGoBrowserIntegration) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableDuckDuckGoBrowserIntegration(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableDuckDuckGoBrowserIntegration = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableFullWidth(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.enableFullWidth) !== null && _c !== void 0 ? _c : false);
        });
    }
    setEnableFullWidth(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.enableFullWidth = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getEnableMinimizeToTray(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableMinimizeToTray) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableMinimizeToTray(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableMinimizeToTray = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableStartToTray(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableStartToTray) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableStartToTray(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableStartToTray = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEnableTray(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.enableTray) !== null && _b !== void 0 ? _b : false);
        });
    }
    setEnableTray(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.enableTray = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedCiphers(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.ciphers) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedCiphers(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.data.ciphers.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getEncryptedCollections(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.collections) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedCollections(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.data.collections.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getEncryptedCryptoSymmetricKey(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.keys.cryptoSymmetricKey.encrypted;
        });
    }
    setEncryptedCryptoSymmetricKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.keys.cryptoSymmetricKey.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedFolders(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.folders) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedFolders(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.data.folders.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getEncryptedOrganizationKeys(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.keys) === null || _b === void 0 ? void 0 : _b.organizationKeys.encrypted;
        });
    }
    setEncryptedOrganizationKeys(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.keys.organizationKeys.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedPasswordGenerationHistory(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.passwordGenerationHistory) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedPasswordGenerationHistory(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.data.passwordGenerationHistory.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedPinProtected(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.pinProtected) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedPinProtected(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.pinProtected.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedPolicies(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.policies) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedPolicies(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.data.policies.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedPrivateKey(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            return (_b = (_a = account === null || account === void 0 ? void 0 : account.keys) === null || _a === void 0 ? void 0 : _a.privateKey) === null || _b === void 0 ? void 0 : _b.encrypted;
        });
    }
    setEncryptedPrivateKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.keys.privateKey.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedProviderKeys(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.keys) === null || _b === void 0 ? void 0 : _b.providerKeys) === null || _c === void 0 ? void 0 : _c.encrypted;
        });
    }
    setEncryptedProviderKeys(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.keys.providerKeys.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEncryptedSends(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.sends.encrypted;
        });
    }
    setEncryptedSends(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.data.sends.encrypted = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getEntityId(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.entityId;
        });
    }
    setEntityId(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.profile.entityId = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getEntityType(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.entityType;
        });
    }
    setEntityType(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.profile.entityType = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getEnvironmentUrls(options) {
        var _a, _b, _c, _d;
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (((_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) == null) {
                return yield this.getGlobalEnvironmentUrls(options);
            }
            options = this.reconcileOptions(options, yield this.defaultOnDiskOptions());
            return (_d = (_c = (_b = (yield this.getAccount(options))) === null || _b === void 0 ? void 0 : _b.settings) === null || _c === void 0 ? void 0 : _c.environmentUrls) !== null && _d !== void 0 ? _d : new EnvironmentUrls();
        });
    }
    setEnvironmentUrls(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            // Global values are set on each change and the current global settings are passed to any newly authed accounts.
            // This is to allow setting environement values before an account is active, while still allowing individual accounts to have their own environments.
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.environmentUrls = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEquivalentDomains(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.equivalentDomains;
        });
    }
    setEquivalentDomains(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.equivalentDomains = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEventCollection(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.eventCollection;
        });
    }
    setEventCollection(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.data.eventCollection = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getEverBeenUnlocked(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.everBeenUnlocked) !== null && _c !== void 0 ? _c : false);
        });
    }
    setEverBeenUnlocked(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.profile.everBeenUnlocked = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getForcePasswordReset(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.forcePasswordReset) !== null && _c !== void 0 ? _c : false);
        });
    }
    setForcePasswordReset(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.profile.forcePasswordReset = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getInstalledVersion(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.installedVersion;
        });
    }
    setInstalledVersion(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.installedVersion = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getIsAuthenticated(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.getAccessToken(options)) != null && (yield this.getUserId(options)) != null;
        });
    }
    getKdfConfig(options) {
        var _a, _b, _c, _d, _e, _f;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const iterations = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.kdfIterations;
            const memory = (_d = (_c = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _c === void 0 ? void 0 : _c.profile) === null || _d === void 0 ? void 0 : _d.kdfMemory;
            const parallelism = (_f = (_e = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _e === void 0 ? void 0 : _e.profile) === null || _f === void 0 ? void 0 : _f.kdfParallelism;
            return new KdfConfig(iterations, memory, parallelism);
        });
    }
    setKdfConfig(config, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.kdfIterations = config.iterations;
            account.profile.kdfMemory = config.memory;
            account.profile.kdfParallelism = config.parallelism;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getKdfType(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.kdfType;
        });
    }
    setKdfType(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.kdfType = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getKeyHash(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.keyHash;
        });
    }
    setKeyHash(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.keyHash = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getLastActive(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultOnDiskOptions());
            const accountActivity = yield this.storageService.get(keys.accountActivity, options);
            if (accountActivity == null || Object.keys(accountActivity).length < 1) {
                return null;
            }
            return accountActivity[options.userId];
        });
    }
    setLastActive(value, options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultOnDiskOptions());
            if (options.userId == null) {
                return;
            }
            const accountActivity = (_a = (yield this.storageService.get(keys.accountActivity, options))) !== null && _a !== void 0 ? _a : {};
            accountActivity[options.userId] = value;
            yield this.storageService.save(keys.accountActivity, accountActivity, options);
        });
    }
    getLastSync(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.lastSync;
        });
    }
    setLastSync(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.profile.lastSync = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getLocalData(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.localData;
        });
    }
    setLocalData(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.data.localData = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getLocale(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.locale;
        });
    }
    setLocale(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.locale = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getMainWindowSize(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.mainWindowSize;
        });
    }
    setMainWindowSize(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            globals.mainWindowSize = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getMinimizeOnCopyToClipboard(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_c = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.minimizeOnCopyToClipboard) !== null && _c !== void 0 ? _c : false);
        });
    }
    setMinimizeOnCopyToClipboard(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.minimizeOnCopyToClipboard = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getNeverDomains(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.neverDomains;
        });
    }
    setNeverDomains(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.neverDomains = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getNoAutoPromptBiometrics(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.noAutoPromptBiometrics) !== null && _b !== void 0 ? _b : false);
        });
    }
    setNoAutoPromptBiometrics(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.noAutoPromptBiometrics = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getNoAutoPromptBiometricsText(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.noAutoPromptBiometricsText;
        });
    }
    setNoAutoPromptBiometricsText(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.noAutoPromptBiometricsText = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getOpenAtLogin(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return ((_b = (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.openAtLogin) !== null && _b !== void 0 ? _b : false);
        });
    }
    setOpenAtLogin(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.openAtLogin = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getOrganizationInvitation(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.organizationInvitation;
        });
    }
    setOrganizationInvitation(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            globals.organizationInvitation = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    /**
     * @deprecated Do not call this directly, use OrganizationService
     */
    getOrganizations(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.organizations;
        });
    }
    /**
     * @deprecated Do not call this directly, use OrganizationService
     */
    setOrganizations(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.data.organizations = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getPasswordGenerationOptions(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.passwordGenerationOptions;
        });
    }
    setPasswordGenerationOptions(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.passwordGenerationOptions = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getUsernameGenerationOptions(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.usernameGenerationOptions;
        });
    }
    setUsernameGenerationOptions(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.usernameGenerationOptions = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getGeneratorOptions(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.generatorOptions;
        });
    }
    setGeneratorOptions(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.generatorOptions = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getProtectedPin(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.protectedPin;
        });
    }
    setProtectedPin(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.settings.protectedPin = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getProviders(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.providers;
        });
    }
    setProviders(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.data.providers = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getPublicKey(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const keys = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.keys;
            return keys === null || keys === void 0 ? void 0 : keys.publicKey;
        });
    }
    setPublicKey(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.keys.publicKey = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getRefreshToken(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            return (_b = (_a = (yield this.getAccount(options))) === null || _a === void 0 ? void 0 : _a.tokens) === null || _b === void 0 ? void 0 : _b.refreshToken;
        });
    }
    setRefreshToken(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = yield this.getTimeoutBasedStorageOptions(options);
            const account = yield this.getAccount(options);
            account.tokens.refreshToken = value;
            yield this.saveAccount(account, options);
        });
    }
    getRememberedEmail(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.rememberedEmail;
        });
    }
    setRememberedEmail(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.rememberedEmail = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getSecurityStamp(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.tokens) === null || _b === void 0 ? void 0 : _b.securityStamp;
        });
    }
    setSecurityStamp(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
            account.tokens.securityStamp = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultInMemoryOptions()));
        });
    }
    getSettings(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.settings;
        });
    }
    setSettings(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
            account.settings.settings = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    getSsoCodeVerifier(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.ssoCodeVerifier;
        });
    }
    setSsoCodeVerifier(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.ssoCodeVerifier = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getSsoOrgIdentifier(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.ssoOrganizationIdentifier;
        });
    }
    setSsoOrganizationIdentifier(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.ssoOrganizationIdentifier = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getSsoState(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.ssoState;
        });
    }
    setSsoState(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.ssoState = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getTheme(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.theme;
        });
    }
    setTheme(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.theme = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getTwoFactorToken(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.twoFactorToken;
        });
    }
    setTwoFactorToken(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            globals.twoFactorToken = value;
            yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getUserId(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.userId;
        });
    }
    getUsesKeyConnector(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions())))) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.usesKeyConnector;
        });
    }
    setUsesKeyConnector(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            account.profile.usesKeyConnector = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    getVaultTimeout(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const accountVaultTimeout = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.vaultTimeout;
            return accountVaultTimeout;
        });
    }
    setVaultTimeout(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.vaultTimeout = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getVaultTimeoutAction(options) {
        var _a, _b, _c;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const accountVaultTimeoutAction = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.vaultTimeoutAction;
            const globalVaultTimeoutAction = (_c = (yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _c === void 0 ? void 0 : _c.vaultTimeoutAction;
            return accountVaultTimeoutAction !== null && accountVaultTimeoutAction !== void 0 ? accountVaultTimeoutAction : globalVaultTimeoutAction;
        });
    }
    setVaultTimeoutAction(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.vaultTimeoutAction = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getApproveLoginRequests(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const approveLoginRequests = (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.approveLoginRequests;
            return approveLoginRequests;
        });
    }
    setApproveLoginRequests(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.approveLoginRequests = value;
            yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getStateVersion() {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_a = (yield this.getGlobals(yield this.defaultOnDiskLocalOptions())).stateVersion) !== null && _a !== void 0 ? _a : 1;
        });
    }
    setStateVersion(value) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(yield this.defaultOnDiskOptions());
            globals.stateVersion = value;
            yield this.saveGlobals(globals, yield this.defaultOnDiskOptions());
        });
    }
    getWindow() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(yield this.defaultOnDiskOptions());
            return (globals === null || globals === void 0 ? void 0 : globals.window) != null && Object.keys(globals.window).length > 0
                ? globals.window
                : new WindowState();
        });
    }
    setWindow(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals(this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
            globals.window = value;
            return yield this.saveGlobals(globals, this.reconcileOptions(options, yield this.defaultOnDiskOptions()));
        });
    }
    setServerConfig(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.serverConfig = value;
            return yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getServerConfig(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.serverConfig;
        });
    }
    getAvatarColor(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions())))) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.avatarColor;
        });
    }
    setAvatarColor(value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const account = yield this.getAccount(this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
            account.settings.avatarColor = value;
            return yield this.saveAccount(account, this.reconcileOptions(options, yield this.defaultOnDiskLocalOptions()));
        });
    }
    getGlobals(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            let globals;
            if (this.useMemory(options.storageLocation)) {
                globals = yield this.getGlobalsFromMemory();
            }
            if (this.useDisk && globals == null) {
                globals = yield this.getGlobalsFromDisk(options);
            }
            return globals !== null && globals !== void 0 ? globals : this.createGlobals();
        });
    }
    saveGlobals(globals, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return this.useMemory(options.storageLocation)
                ? this.saveGlobalsToMemory(globals)
                : yield this.saveGlobalsToDisk(globals, options);
        });
    }
    getGlobalsFromMemory() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.state()).globals;
        });
    }
    getGlobalsFromDisk(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return yield this.storageService.get(keys.global, options);
        });
    }
    saveGlobalsToMemory(globals) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                state.globals = globals;
                return state;
            }));
        });
    }
    saveGlobalsToDisk(globals, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (options.useSecureStorage) {
                yield this.secureStorageService.save(keys.global, globals, options);
            }
            else {
                yield this.storageService.save(keys.global, globals, options);
            }
        });
    }
    getAccount(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            try {
                let account;
                if (this.useMemory(options.storageLocation)) {
                    account = yield this.getAccountFromMemory(options);
                }
                if (this.useDisk(options.storageLocation) && account == null) {
                    account = yield this.getAccountFromDisk(options);
                }
                return account;
            }
            catch (e) {
                this.logService.error(e);
            }
        });
    }
    getAccountFromMemory(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return yield this.state().then((state) => state_service_awaiter(this, void 0, void 0, function* () {
                if (state.accounts == null) {
                    return null;
                }
                return state.accounts[yield this.getUserIdFromMemory(options)];
            }));
        });
    }
    getUserIdFromMemory(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return yield this.state().then((state) => {
                var _a, _b;
                return (options === null || options === void 0 ? void 0 : options.userId) != null
                    ? (_b = (_a = state.accounts[options.userId]) === null || _a === void 0 ? void 0 : _a.profile) === null || _b === void 0 ? void 0 : _b.userId
                    : state.activeUserId;
            });
        });
    }
    getAccountFromDisk(options) {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            if ((options === null || options === void 0 ? void 0 : options.userId) == null && ((_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) == null) {
                return null;
            }
            if (this.useAccountCache) {
                const cachedAccount = this.accountDiskCache.value[options.userId];
                if (cachedAccount != null) {
                    return cachedAccount;
                }
            }
            const account = (options === null || options === void 0 ? void 0 : options.useSecureStorage)
                ? (_b = (yield this.secureStorageService.get(options.userId, options))) !== null && _b !== void 0 ? _b : (yield this.storageService.get(options.userId, this.reconcileOptions(options, { htmlStorageLocation: HtmlStorageLocation.Local })))
                : yield this.storageService.get(options.userId, options);
            this.setDiskCache(options.userId, account);
            return account;
        });
    }
    useMemory(storageLocation) {
        return storageLocation === StorageLocation.Memory || storageLocation === StorageLocation.Both;
    }
    useDisk(storageLocation) {
        return storageLocation === StorageLocation.Disk || storageLocation === StorageLocation.Both;
    }
    saveAccount(account, options = {
        storageLocation: StorageLocation.Both,
        useSecureStorage: false,
    }) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return this.useMemory(options.storageLocation)
                ? yield this.saveAccountToMemory(account)
                : yield this.saveAccountToDisk(account, options);
        });
    }
    saveAccountToDisk(account, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const storageLocation = options.useSecureStorage
                ? this.secureStorageService
                : this.storageService;
            yield storageLocation.save(`${options.userId}`, account, options);
            this.deleteDiskCache(options.userId);
        });
    }
    saveAccountToMemory(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            if (this.getAccountFromMemory({ userId: account.profile.userId }) !== null) {
                yield this.updateState((state) => {
                    return new Promise((resolve) => {
                        state.accounts[account.profile.userId] = account;
                        resolve(state);
                    });
                });
            }
            yield this.pushAccounts();
        });
    }
    scaffoldNewAccountStorage(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            // We don't want to manipulate the referenced in memory account
            const deepClone = JSON.parse(JSON.stringify(account));
            yield this.scaffoldNewAccountLocalStorage(deepClone);
            yield this.scaffoldNewAccountSessionStorage(deepClone);
            yield this.scaffoldNewAccountMemoryStorage(deepClone);
        });
    }
    // TODO: There is a tech debt item for splitting up these methods - only Web uses multiple storage locations in its storageService.
    // For now these methods exist with some redundancy to facilitate this special web requirement.
    scaffoldNewAccountLocalStorage(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const storedAccount = yield this.getAccount(this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskLocalOptions()));
            // EnvironmentUrls are set before authenticating and should override whatever is stored from any previous session
            const environmentUrls = account.settings.environmentUrls;
            if ((storedAccount === null || storedAccount === void 0 ? void 0 : storedAccount.settings) != null) {
                account.settings = storedAccount.settings;
            }
            else if (yield this.storageService.has(keys.tempAccountSettings)) {
                account.settings = yield this.storageService.get(keys.tempAccountSettings);
                yield this.storageService.remove(keys.tempAccountSettings);
            }
            account.settings.environmentUrls = environmentUrls;
            if (account.settings.vaultTimeoutAction === "logOut" && account.settings.vaultTimeout != null) {
                account.tokens.accessToken = null;
                account.tokens.refreshToken = null;
                account.profile.apiKeyClientId = null;
                account.keys.apiKeyClientSecret = null;
            }
            yield this.saveAccount(account, this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskLocalOptions()));
        });
    }
    scaffoldNewAccountMemoryStorage(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const storedAccount = yield this.getAccount(this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskMemoryOptions()));
            if ((storedAccount === null || storedAccount === void 0 ? void 0 : storedAccount.settings) != null) {
                storedAccount.settings.environmentUrls = account.settings.environmentUrls;
                account.settings = storedAccount.settings;
            }
            yield this.storageService.save(account.profile.userId, account, yield this.defaultOnDiskMemoryOptions());
            yield this.saveAccount(account, this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskMemoryOptions()));
        });
    }
    scaffoldNewAccountSessionStorage(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const storedAccount = yield this.getAccount(this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskOptions()));
            if ((storedAccount === null || storedAccount === void 0 ? void 0 : storedAccount.settings) != null) {
                storedAccount.settings.environmentUrls = account.settings.environmentUrls;
                account.settings = storedAccount.settings;
            }
            yield this.storageService.save(account.profile.userId, account, yield this.defaultOnDiskMemoryOptions());
            yield this.saveAccount(account, this.reconcileOptions({ userId: account.profile.userId }, yield this.defaultOnDiskOptions()));
        });
    }
    //
    pushAccounts() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.pruneInMemoryAccounts();
            yield this.state().then((state) => {
                if (state.accounts == null || Object.keys(state.accounts).length < 1) {
                    this.accountsSubject.next({});
                    return;
                }
                this.accountsSubject.next(state.accounts);
            });
        });
    }
    reconcileOptions(requestedOptions, defaultOptions) {
        var _a, _b, _c, _d, _e;
        if (requestedOptions == null) {
            return defaultOptions;
        }
        requestedOptions.userId = (_a = requestedOptions === null || requestedOptions === void 0 ? void 0 : requestedOptions.userId) !== null && _a !== void 0 ? _a : defaultOptions.userId;
        requestedOptions.storageLocation =
            (_b = requestedOptions === null || requestedOptions === void 0 ? void 0 : requestedOptions.storageLocation) !== null && _b !== void 0 ? _b : defaultOptions.storageLocation;
        requestedOptions.useSecureStorage =
            (_c = requestedOptions === null || requestedOptions === void 0 ? void 0 : requestedOptions.useSecureStorage) !== null && _c !== void 0 ? _c : defaultOptions.useSecureStorage;
        requestedOptions.htmlStorageLocation =
            (_d = requestedOptions === null || requestedOptions === void 0 ? void 0 : requestedOptions.htmlStorageLocation) !== null && _d !== void 0 ? _d : defaultOptions.htmlStorageLocation;
        requestedOptions.keySuffix = (_e = requestedOptions === null || requestedOptions === void 0 ? void 0 : requestedOptions.keySuffix) !== null && _e !== void 0 ? _e : defaultOptions.keySuffix;
        return requestedOptions;
    }
    defaultInMemoryOptions() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return {
                storageLocation: StorageLocation.Memory,
                userId: (yield this.state()).activeUserId,
            };
        });
    }
    defaultOnDiskOptions() {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return {
                storageLocation: StorageLocation.Disk,
                htmlStorageLocation: HtmlStorageLocation.Session,
                userId: (_b = (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) !== null && _b !== void 0 ? _b : (yield this.getActiveUserIdFromStorage()),
                useSecureStorage: false,
            };
        });
    }
    defaultOnDiskLocalOptions() {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return {
                storageLocation: StorageLocation.Disk,
                htmlStorageLocation: HtmlStorageLocation.Local,
                userId: (_b = (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) !== null && _b !== void 0 ? _b : (yield this.getActiveUserIdFromStorage()),
                useSecureStorage: false,
            };
        });
    }
    defaultOnDiskMemoryOptions() {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return {
                storageLocation: StorageLocation.Disk,
                htmlStorageLocation: HtmlStorageLocation.Memory,
                userId: (_b = (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) !== null && _b !== void 0 ? _b : (yield this.getUserId()),
                useSecureStorage: false,
            };
        });
    }
    defaultSecureStorageOptions() {
        var _a, _b;
        return state_service_awaiter(this, void 0, void 0, function* () {
            return {
                storageLocation: StorageLocation.Disk,
                useSecureStorage: true,
                userId: (_b = (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId) !== null && _b !== void 0 ? _b : (yield this.getActiveUserIdFromStorage()),
            };
        });
    }
    getActiveUserIdFromStorage() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return yield this.storageService.get(keys.activeUserId);
        });
    }
    removeAccountFromLocalStorage(userId = null) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            userId = userId !== null && userId !== void 0 ? userId : (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId;
            const storedAccount = yield this.getAccount(this.reconcileOptions({ userId: userId }, yield this.defaultOnDiskLocalOptions()));
            yield this.saveAccount(this.resetAccount(storedAccount), this.reconcileOptions({ userId: userId }, yield this.defaultOnDiskLocalOptions()));
        });
    }
    removeAccountFromSessionStorage(userId = null) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            userId = userId !== null && userId !== void 0 ? userId : (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId;
            const storedAccount = yield this.getAccount(this.reconcileOptions({ userId: userId }, yield this.defaultOnDiskOptions()));
            yield this.saveAccount(this.resetAccount(storedAccount), this.reconcileOptions({ userId: userId }, yield this.defaultOnDiskOptions()));
        });
    }
    removeAccountFromSecureStorage(userId = null) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            userId = userId !== null && userId !== void 0 ? userId : (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.activeUserId;
            yield this.setCryptoMasterKeyAuto(null, { userId: userId });
            yield this.setCryptoMasterKeyBiometric(null, { userId: userId });
            yield this.setCryptoMasterKeyB64(null, { userId: userId });
        });
    }
    removeAccountFromMemory(userId = null) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                userId = userId !== null && userId !== void 0 ? userId : state.activeUserId;
                delete state.accounts[userId];
                this.deleteDiskCache(userId);
                return state;
            }));
        });
    }
    pruneInMemoryAccounts() {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            // We preserve settings for logged out accounts, but we don't want to consider them when thinking about active account state
            for (const userId in (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.accounts) {
                if (!(yield this.getIsAuthenticated({ userId: userId }))) {
                    yield this.removeAccountFromMemory(userId);
                }
            }
        });
    }
    // settings persist even on reset, and are not effected by this method
    resetAccount(account) {
        const persistentAccountInformation = { settings: account.settings };
        return Object.assign(this.createAccount(), persistentAccountInformation);
    }
    setAccountEnvironmentUrls(account) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            account.settings.environmentUrls = yield this.getGlobalEnvironmentUrls();
            return account;
        });
    }
    getGlobalEnvironmentUrls(options) {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            options = this.reconcileOptions(options, yield this.defaultOnDiskOptions());
            return (_a = (yield this.getGlobals(options)).environmentUrls) !== null && _a !== void 0 ? _a : new EnvironmentUrls();
        });
    }
    clearDecryptedDataForActiveUser() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                var _a;
                const userId = state === null || state === void 0 ? void 0 : state.activeUserId;
                if (userId != null && ((_a = state === null || state === void 0 ? void 0 : state.accounts[userId]) === null || _a === void 0 ? void 0 : _a.data) != null) {
                    state.accounts[userId].data = new AccountData();
                }
                return state;
            }));
        });
    }
    createAccount(init = null) {
        return this.stateFactory.createAccount(init);
    }
    createGlobals(init = null) {
        return this.stateFactory.createGlobal(init);
    }
    deAuthenticateAccount(userId) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.setAccessToken(null, { userId: userId });
            yield this.setLastActive(null, { userId: userId });
            yield this.updateState((state) => state_service_awaiter(this, void 0, void 0, function* () {
                state.authenticatedAccounts = state.authenticatedAccounts.filter((id) => id !== userId);
                yield this.storageService.save(keys.authenticatedAccounts, state.authenticatedAccounts);
                return state;
            }));
        });
    }
    removeAccountFromDisk(userId) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.removeAccountFromSessionStorage(userId);
            yield this.removeAccountFromLocalStorage(userId);
            yield this.removeAccountFromSecureStorage(userId);
        });
    }
    dynamicallySetActiveUser() {
        var _a;
        return state_service_awaiter(this, void 0, void 0, function* () {
            const accounts = (_a = (yield this.state())) === null || _a === void 0 ? void 0 : _a.accounts;
            if (accounts == null || Object.keys(accounts).length < 1) {
                yield this.setActiveUser(null);
                return;
            }
            for (const userId in accounts) {
                if (userId == null) {
                    continue;
                }
                if (yield this.getIsAuthenticated({ userId: userId })) {
                    yield this.setActiveUser(userId);
                    break;
                }
                yield this.setActiveUser(null);
            }
        });
    }
    getTimeoutBasedStorageOptions(options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const timeoutAction = yield this.getVaultTimeoutAction({ userId: options === null || options === void 0 ? void 0 : options.userId });
            const timeout = yield this.getVaultTimeout({ userId: options === null || options === void 0 ? void 0 : options.userId });
            const defaultOptions = timeoutAction === "logOut" && timeout != null
                ? yield this.defaultInMemoryOptions()
                : yield this.defaultOnDiskOptions();
            return this.reconcileOptions(options, defaultOptions);
        });
    }
    saveSecureStorageKey(key, value, options) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            return value == null
                ? yield this.secureStorageService.remove(`${options.userId}${key}`, options)
                : yield this.secureStorageService.save(`${options.userId}${key}`, value, options);
        });
    }
    state() {
        return state_service_awaiter(this, void 0, void 0, function* () {
            const state = yield this.memoryStorageService.get(keys.state, {
                deserializer: (s) => State.fromJSON(s, this.accountDeserializer),
            });
            return state;
        });
    }
    setState(state) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.memoryStorageService.save(keys.state, state);
        });
    }
    updateState(stateUpdater) {
        return state_service_awaiter(this, void 0, void 0, function* () {
            yield this.state().then((state) => state_service_awaiter(this, void 0, void 0, function* () {
                const updatedState = yield stateUpdater(state);
                if (updatedState == null) {
                    throw new Error("Attempted to update state to null value");
                }
                yield this.setState(updatedState);
            }));
        });
    }
    setDiskCache(key, value, options) {
        if (this.useAccountCache) {
            this.accountDiskCache.value[key] = value;
            this.accountDiskCache.next(this.accountDiskCache.value);
        }
    }
    deleteDiskCache(key) {
        if (this.useAccountCache) {
            delete this.accountDiskCache.value[key];
            this.accountDiskCache.next(this.accountDiskCache.value);
        }
    }
}
state_service_decorate([
    withPrototypeForArrayMembers(CipherView, CipherView.fromJSON),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getDecryptedCiphers", null);
state_service_decorate([
    withPrototypeForArrayMembers(CollectionView),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getDecryptedCollections", null);
state_service_decorate([
    withPrototypeForArrayMembers(GeneratedPasswordHistory),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getDecryptedPasswordGenerationHistory", null);
state_service_decorate([
    withPrototypeForArrayMembers(Policy),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getDecryptedPolicies", null);
state_service_decorate([
    withPrototypeForArrayMembers(SendView),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getDecryptedSends", null);
state_service_decorate([
    withPrototypeForObjectValues(CipherData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedCiphers", null);
state_service_decorate([
    withPrototypeForObjectValues(CollectionData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedCollections", null);
state_service_decorate([
    withPrototypeForObjectValues(FolderData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedFolders", null);
state_service_decorate([
    withPrototypeForArrayMembers(GeneratedPasswordHistory),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedPasswordGenerationHistory", null);
state_service_decorate([
    withPrototypeForObjectValues(PolicyData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedPolicies", null);
state_service_decorate([
    withPrototypeForObjectValues(SendData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEncryptedSends", null);
state_service_decorate([
    withPrototypeForArrayMembers(EventData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getEventCollection", null);
state_service_decorate([
    withPrototypeForObjectValues(ProviderData),
    state_service_metadata("design:type", Function),
    state_service_metadata("design:paramtypes", [Object]),
    state_service_metadata("design:returntype", Promise)
], StateService.prototype, "getProviders", null);
function withPrototypeForArrayMembers(memberConstructor, memberConverter = (i) => i) {
    return (target, propertyKey, descriptor) => {
        const originalMethod = descriptor.value;
        return {
            value: function (...args) {
                const originalResult = originalMethod.apply(this, args);
                if (!(originalResult instanceof Promise)) {
                    throw new Error(`Error applying prototype to stored value -- result is not a promise for method ${String(propertyKey)}`);
                }
                return originalResult.then((result) => {
                    if (result == null) {
                        return null;
                    }
                    else if (!(result instanceof Array)) {
                        throw new Error(`Attempted to retrieve non array type from state as an array for method ${String(propertyKey)}`);
                    }
                    else {
                        return result.map((r) => {
                            return r == null ||
                                r.constructor.name === memberConstructor.prototype.constructor.name
                                ? r
                                : memberConverter(Object.create(memberConstructor.prototype, Object.getOwnPropertyDescriptors(r)));
                        });
                    }
                });
            },
        };
    };
}
function withPrototypeForObjectValues(valuesConstructor, valuesConverter = (i) => i) {
    return (target, propertyKey, descriptor) => {
        const originalMethod = descriptor.value;
        return {
            value: function (...args) {
                const originalResult = originalMethod.apply(this, args);
                if (!(originalResult instanceof Promise)) {
                    throw new Error(`Error applying prototype to stored value -- result is not a promise for method ${String(propertyKey)}`);
                }
                return originalResult.then((result) => {
                    if (result == null) {
                        return null;
                    }
                    else {
                        for (const [key, val] of Object.entries(result)) {
                            result[key] =
                                val == null || val.constructor.name === valuesConstructor.prototype.constructor.name
                                    ? valuesConverter(val)
                                    : valuesConverter(Object.create(valuesConstructor.prototype, Object.getOwnPropertyDescriptors(val)));
                        }
                        return result;
                    }
                });
            },
        };
    };
}

;// CONCATENATED MODULE: ../../libs/common/src/services/token.service.ts
var token_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class TokenService {
    constructor(stateService) {
        this.stateService = stateService;
    }
    static decodeToken(token) {
        if (token == null) {
            throw new Error("Token not provided.");
        }
        const parts = token.split(".");
        if (parts.length !== 3) {
            throw new Error("JWT must have 3 parts");
        }
        const decoded = Utils.fromUrlB64ToUtf8(parts[1]);
        if (decoded == null) {
            throw new Error("Cannot decode the token");
        }
        const decodedToken = JSON.parse(decoded);
        return decodedToken;
    }
    setTokens(accessToken, refreshToken, clientIdClientSecret) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            yield this.setToken(accessToken);
            yield this.setRefreshToken(refreshToken);
            if (clientIdClientSecret != null) {
                yield this.setClientId(clientIdClientSecret[0]);
                yield this.setClientSecret(clientIdClientSecret[1]);
            }
        });
    }
    setClientId(clientId) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setApiKeyClientId(clientId);
        });
    }
    getClientId() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getApiKeyClientId();
        });
    }
    setClientSecret(clientSecret) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setApiKeyClientSecret(clientSecret);
        });
    }
    getClientSecret() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getApiKeyClientSecret();
        });
    }
    setToken(token) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setAccessToken(token);
        });
    }
    getToken() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getAccessToken();
        });
    }
    setRefreshToken(refreshToken) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setRefreshToken(refreshToken);
        });
    }
    getRefreshToken() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getRefreshToken();
        });
    }
    setTwoFactorToken(tokenResponse) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setTwoFactorToken(tokenResponse.twoFactorToken);
        });
    }
    getTwoFactorToken() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getTwoFactorToken();
        });
    }
    clearTwoFactorToken() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.setTwoFactorToken(null);
        });
    }
    clearToken(userId) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setAccessToken(null, { userId: userId });
            yield this.stateService.setRefreshToken(null, { userId: userId });
            yield this.stateService.setApiKeyClientId(null, { userId: userId });
            yield this.stateService.setApiKeyClientSecret(null, { userId: userId });
        });
    }
    // jwthelper methods
    // ref https://github.com/auth0/angular-jwt/blob/master/src/angularJwt/services/jwt.js
    decodeToken(token) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            token = token !== null && token !== void 0 ? token : (yield this.stateService.getAccessToken());
            if (token == null) {
                throw new Error("Token not found.");
            }
            return TokenService.decodeToken(token);
        });
    }
    getTokenExpirationDate() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.exp === "undefined") {
                return null;
            }
            const d = new Date(0); // The 0 here is the key, which sets the date to the epoch
            d.setUTCSeconds(decoded.exp);
            return d;
        });
    }
    tokenSecondsRemaining(offsetSeconds = 0) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const d = yield this.getTokenExpirationDate();
            if (d == null) {
                return 0;
            }
            const msRemaining = d.valueOf() - (new Date().valueOf() + offsetSeconds * 1000);
            return Math.round(msRemaining / 1000);
        });
    }
    tokenNeedsRefresh(minutes = 5) {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const sRemaining = yield this.tokenSecondsRemaining();
            return sRemaining < 60 * minutes;
        });
    }
    getUserId() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.sub === "undefined") {
                throw new Error("No user id found");
            }
            return decoded.sub;
        });
    }
    getEmail() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.email === "undefined") {
                throw new Error("No email found");
            }
            return decoded.email;
        });
    }
    getEmailVerified() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.email_verified === "undefined") {
                throw new Error("No email verification found");
            }
            return decoded.email_verified;
        });
    }
    getName() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.name === "undefined") {
                return null;
            }
            return decoded.name;
        });
    }
    getIssuer() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            if (typeof decoded.iss === "undefined") {
                throw new Error("No issuer found");
            }
            return decoded.iss;
        });
    }
    getIsExternal() {
        return token_service_awaiter(this, void 0, void 0, function* () {
            const decoded = yield this.decodeToken();
            return Array.isArray(decoded.amr) && decoded.amr.includes("external");
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/stateMigration.service.ts
var stateMigration_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




// Originally (before January 2022) storage was handled as a flat key/value pair store.
// With the move to a typed object for state storage these keys should no longer be in use anywhere outside of this migration.
const v1Keys = {
    accessToken: "accessToken",
    alwaysShowDock: "alwaysShowDock",
    autoConfirmFingerprints: "autoConfirmFingerprints",
    autoFillOnPageLoadDefault: "autoFillOnPageLoadDefault",
    biometricAwaitingAcceptance: "biometricAwaitingAcceptance",
    biometricFingerprintValidated: "biometricFingerprintValidated",
    biometricText: "biometricText",
    biometricUnlock: "biometric",
    clearClipboard: "clearClipboardKey",
    clientId: "apikey_clientId",
    clientSecret: "apikey_clientSecret",
    collapsedGroupings: "collapsedGroupings",
    convertAccountToKeyConnector: "convertAccountToKeyConnector",
    defaultUriMatch: "defaultUriMatch",
    disableAddLoginNotification: "disableAddLoginNotification",
    disableAutoBiometricsPrompt: "noAutoPromptBiometrics",
    disableAutoTotpCopy: "disableAutoTotpCopy",
    disableBadgeCounter: "disableBadgeCounter",
    disableChangedPasswordNotification: "disableChangedPasswordNotification",
    disableContextMenuItem: "disableContextMenuItem",
    disableFavicon: "disableFavicon",
    disableGa: "disableGa",
    dontShowCardsCurrentTab: "dontShowCardsCurrentTab",
    dontShowIdentitiesCurrentTab: "dontShowIdentitiesCurrentTab",
    emailVerified: "emailVerified",
    enableAlwaysOnTop: "enableAlwaysOnTopKey",
    enableAutoFillOnPageLoad: "enableAutoFillOnPageLoad",
    enableBiometric: "enabledBiometric",
    enableBrowserIntegration: "enableBrowserIntegration",
    enableBrowserIntegrationFingerprint: "enableBrowserIntegrationFingerprint",
    enableCloseToTray: "enableCloseToTray",
    enableFullWidth: "enableFullWidth",
    enableMinimizeToTray: "enableMinimizeToTray",
    enableStartToTray: "enableStartToTrayKey",
    enableTray: "enableTray",
    encKey: "encKey",
    encOrgKeys: "encOrgKeys",
    encPrivate: "encPrivateKey",
    encProviderKeys: "encProviderKeys",
    entityId: "entityId",
    entityType: "entityType",
    environmentUrls: "environmentUrls",
    equivalentDomains: "equivalentDomains",
    eventCollection: "eventCollection",
    forcePasswordReset: "forcePasswordReset",
    history: "generatedPasswordHistory",
    installedVersion: "installedVersion",
    kdf: "kdf",
    kdfIterations: "kdfIterations",
    key: "key",
    keyHash: "keyHash",
    lastActive: "lastActive",
    localData: "sitesLocalData",
    locale: "locale",
    mainWindowSize: "mainWindowSize",
    minimizeOnCopyToClipboard: "minimizeOnCopyToClipboardKey",
    neverDomains: "neverDomains",
    noAutoPromptBiometricsText: "noAutoPromptBiometricsText",
    openAtLogin: "openAtLogin",
    passwordGenerationOptions: "passwordGenerationOptions",
    pinProtected: "pinProtectedKey",
    protectedPin: "protectedPin",
    refreshToken: "refreshToken",
    ssoCodeVerifier: "ssoCodeVerifier",
    ssoIdentifier: "ssoOrgIdentifier",
    ssoState: "ssoState",
    stamp: "securityStamp",
    theme: "theme",
    userEmail: "userEmail",
    userId: "userId",
    usesConnector: "usesKeyConnector",
    vaultTimeoutAction: "vaultTimeoutAction",
    vaultTimeout: "lockOption",
    rememberedEmail: "rememberedEmail",
};
const v1KeyPrefixes = {
    ciphers: "ciphers_",
    collections: "collections_",
    folders: "folders_",
    lastSync: "lastSync_",
    policies: "policies_",
    twoFactorToken: "twoFactorToken_",
    organizations: "organizations_",
    providers: "providers_",
    sends: "sends_",
    settings: "settings_",
};
const stateMigration_service_keys = {
    global: "global",
    authenticatedAccounts: "authenticatedAccounts",
    activeUserId: "activeUserId",
    tempAccountSettings: "tempAccountSettings",
    accountActivity: "accountActivity",
};
const stateMigration_service_partialKeys = {
    autoKey: "_masterkey_auto",
    biometricKey: "_masterkey_biometric",
    masterKey: "_masterkey",
};
class StateMigrationService {
    constructor(storageService, secureStorageService, stateFactory) {
        this.storageService = storageService;
        this.secureStorageService = secureStorageService;
        this.stateFactory = stateFactory;
    }
    needsMigration() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const currentStateVersion = yield this.getCurrentStateVersion();
            return currentStateVersion == null || currentStateVersion < StateVersion.Latest;
        });
    }
    migrate() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            let currentStateVersion = yield this.getCurrentStateVersion();
            while (currentStateVersion < StateVersion.Latest) {
                switch (currentStateVersion) {
                    case StateVersion.One:
                        yield this.migrateStateFrom1To2();
                        break;
                    case StateVersion.Two:
                        yield this.migrateStateFrom2To3();
                        break;
                    case StateVersion.Three:
                        yield this.migrateStateFrom3To4();
                        break;
                    case StateVersion.Four: {
                        const authenticatedAccounts = yield this.getAuthenticatedAccounts();
                        for (const account of authenticatedAccounts) {
                            const migratedAccount = yield this.migrateAccountFrom4To5(account);
                            yield this.set(account.profile.userId, migratedAccount);
                        }
                        yield this.setCurrentStateVersion(StateVersion.Five);
                        break;
                    }
                    case StateVersion.Five: {
                        const authenticatedAccounts = yield this.getAuthenticatedAccounts();
                        for (const account of authenticatedAccounts) {
                            const migratedAccount = yield this.migrateAccountFrom5To6(account);
                            yield this.set(account.profile.userId, migratedAccount);
                        }
                        yield this.setCurrentStateVersion(StateVersion.Six);
                        break;
                    }
                }
                currentStateVersion += 1;
            }
        });
    }
    migrateStateFrom1To2() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22;
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const clearV1Keys = (clearingUserId) => stateMigration_service_awaiter(this, void 0, void 0, function* () {
                for (const key in v1Keys) {
                    if (key == null) {
                        continue;
                    }
                    yield this.set(v1Keys[key], null);
                }
                if (clearingUserId != null) {
                    for (const keyPrefix in v1KeyPrefixes) {
                        if (keyPrefix == null) {
                            continue;
                        }
                        yield this.set(v1KeyPrefixes[keyPrefix] + userId, null);
                    }
                }
            });
            // Some processes, like biometrics, may have already defined a value before migrations are run.
            // We don't want to null out those values if they don't exist in the old storage scheme (like for new installs)
            // So, the OOO for migration is that we:
            // 1. Check for an existing storage value from the old storage structure OR
            // 2. Check for a value already set by processes that run before migration OR
            // 3. Assign the default value
            const globals = (_a = (yield this.get(stateMigration_service_keys.global))) !== null && _a !== void 0 ? _a : this.stateFactory.createGlobal(null);
            globals.stateVersion = StateVersion.Two;
            globals.environmentUrls =
                (_b = (yield this.get(v1Keys.environmentUrls))) !== null && _b !== void 0 ? _b : globals.environmentUrls;
            globals.locale = (_c = (yield this.get(v1Keys.locale))) !== null && _c !== void 0 ? _c : globals.locale;
            globals.noAutoPromptBiometrics =
                (_d = (yield this.get(v1Keys.disableAutoBiometricsPrompt))) !== null && _d !== void 0 ? _d : globals.noAutoPromptBiometrics;
            globals.noAutoPromptBiometricsText =
                (_e = (yield this.get(v1Keys.noAutoPromptBiometricsText))) !== null && _e !== void 0 ? _e : globals.noAutoPromptBiometricsText;
            globals.ssoCodeVerifier =
                (_f = (yield this.get(v1Keys.ssoCodeVerifier))) !== null && _f !== void 0 ? _f : globals.ssoCodeVerifier;
            globals.ssoOrganizationIdentifier =
                (_g = (yield this.get(v1Keys.ssoIdentifier))) !== null && _g !== void 0 ? _g : globals.ssoOrganizationIdentifier;
            globals.ssoState = (_h = (yield this.get(v1Keys.ssoState))) !== null && _h !== void 0 ? _h : globals.ssoState;
            globals.rememberedEmail =
                (_j = (yield this.get(v1Keys.rememberedEmail))) !== null && _j !== void 0 ? _j : globals.rememberedEmail;
            globals.theme = (_k = (yield this.get(v1Keys.theme))) !== null && _k !== void 0 ? _k : globals.theme;
            globals.vaultTimeout = (_l = (yield this.get(v1Keys.vaultTimeout))) !== null && _l !== void 0 ? _l : globals.vaultTimeout;
            globals.vaultTimeoutAction =
                (_m = (yield this.get(v1Keys.vaultTimeoutAction))) !== null && _m !== void 0 ? _m : globals.vaultTimeoutAction;
            globals.window = (_o = (yield this.get(v1Keys.mainWindowSize))) !== null && _o !== void 0 ? _o : globals.window;
            globals.enableTray = (_p = (yield this.get(v1Keys.enableTray))) !== null && _p !== void 0 ? _p : globals.enableTray;
            globals.enableMinimizeToTray =
                (_q = (yield this.get(v1Keys.enableMinimizeToTray))) !== null && _q !== void 0 ? _q : globals.enableMinimizeToTray;
            globals.enableCloseToTray =
                (_r = (yield this.get(v1Keys.enableCloseToTray))) !== null && _r !== void 0 ? _r : globals.enableCloseToTray;
            globals.enableStartToTray =
                (_s = (yield this.get(v1Keys.enableStartToTray))) !== null && _s !== void 0 ? _s : globals.enableStartToTray;
            globals.openAtLogin = (_t = (yield this.get(v1Keys.openAtLogin))) !== null && _t !== void 0 ? _t : globals.openAtLogin;
            globals.alwaysShowDock =
                (_u = (yield this.get(v1Keys.alwaysShowDock))) !== null && _u !== void 0 ? _u : globals.alwaysShowDock;
            globals.enableBrowserIntegration =
                (_v = (yield this.get(v1Keys.enableBrowserIntegration))) !== null && _v !== void 0 ? _v : globals.enableBrowserIntegration;
            globals.enableBrowserIntegrationFingerprint =
                (_w = (yield this.get(v1Keys.enableBrowserIntegrationFingerprint))) !== null && _w !== void 0 ? _w : globals.enableBrowserIntegrationFingerprint;
            const userId = (_x = (yield this.get(v1Keys.userId))) !== null && _x !== void 0 ? _x : (yield this.get(v1Keys.entityId));
            const defaultAccount = this.stateFactory.createAccount(null);
            const accountSettings = {
                autoConfirmFingerPrints: (_y = (yield this.get(v1Keys.autoConfirmFingerprints))) !== null && _y !== void 0 ? _y : defaultAccount.settings.autoConfirmFingerPrints,
                autoFillOnPageLoadDefault: (_z = (yield this.get(v1Keys.autoFillOnPageLoadDefault))) !== null && _z !== void 0 ? _z : defaultAccount.settings.autoFillOnPageLoadDefault,
                biometricUnlock: (_0 = (yield this.get(v1Keys.biometricUnlock))) !== null && _0 !== void 0 ? _0 : defaultAccount.settings.biometricUnlock,
                clearClipboard: (_1 = (yield this.get(v1Keys.clearClipboard))) !== null && _1 !== void 0 ? _1 : defaultAccount.settings.clearClipboard,
                defaultUriMatch: (_2 = (yield this.get(v1Keys.defaultUriMatch))) !== null && _2 !== void 0 ? _2 : defaultAccount.settings.defaultUriMatch,
                disableAddLoginNotification: (_3 = (yield this.get(v1Keys.disableAddLoginNotification))) !== null && _3 !== void 0 ? _3 : defaultAccount.settings.disableAddLoginNotification,
                disableAutoBiometricsPrompt: (_4 = (yield this.get(v1Keys.disableAutoBiometricsPrompt))) !== null && _4 !== void 0 ? _4 : defaultAccount.settings.disableAutoBiometricsPrompt,
                disableAutoTotpCopy: (_5 = (yield this.get(v1Keys.disableAutoTotpCopy))) !== null && _5 !== void 0 ? _5 : defaultAccount.settings.disableAutoTotpCopy,
                disableBadgeCounter: (_6 = (yield this.get(v1Keys.disableBadgeCounter))) !== null && _6 !== void 0 ? _6 : defaultAccount.settings.disableBadgeCounter,
                disableChangedPasswordNotification: (_7 = (yield this.get(v1Keys.disableChangedPasswordNotification))) !== null && _7 !== void 0 ? _7 : defaultAccount.settings.disableChangedPasswordNotification,
                disableContextMenuItem: (_8 = (yield this.get(v1Keys.disableContextMenuItem))) !== null && _8 !== void 0 ? _8 : defaultAccount.settings.disableContextMenuItem,
                disableGa: (_9 = (yield this.get(v1Keys.disableGa))) !== null && _9 !== void 0 ? _9 : defaultAccount.settings.disableGa,
                dontShowCardsCurrentTab: (_10 = (yield this.get(v1Keys.dontShowCardsCurrentTab))) !== null && _10 !== void 0 ? _10 : defaultAccount.settings.dontShowCardsCurrentTab,
                dontShowIdentitiesCurrentTab: (_11 = (yield this.get(v1Keys.dontShowIdentitiesCurrentTab))) !== null && _11 !== void 0 ? _11 : defaultAccount.settings.dontShowIdentitiesCurrentTab,
                enableAlwaysOnTop: (_12 = (yield this.get(v1Keys.enableAlwaysOnTop))) !== null && _12 !== void 0 ? _12 : defaultAccount.settings.enableAlwaysOnTop,
                enableAutoFillOnPageLoad: (_13 = (yield this.get(v1Keys.enableAutoFillOnPageLoad))) !== null && _13 !== void 0 ? _13 : defaultAccount.settings.enableAutoFillOnPageLoad,
                enableBiometric: (_14 = (yield this.get(v1Keys.enableBiometric))) !== null && _14 !== void 0 ? _14 : defaultAccount.settings.enableBiometric,
                enableFullWidth: (_15 = (yield this.get(v1Keys.enableFullWidth))) !== null && _15 !== void 0 ? _15 : defaultAccount.settings.enableFullWidth,
                environmentUrls: (_16 = globals.environmentUrls) !== null && _16 !== void 0 ? _16 : defaultAccount.settings.environmentUrls,
                equivalentDomains: (_17 = (yield this.get(v1Keys.equivalentDomains))) !== null && _17 !== void 0 ? _17 : defaultAccount.settings.equivalentDomains,
                minimizeOnCopyToClipboard: (_18 = (yield this.get(v1Keys.minimizeOnCopyToClipboard))) !== null && _18 !== void 0 ? _18 : defaultAccount.settings.minimizeOnCopyToClipboard,
                neverDomains: (_19 = (yield this.get(v1Keys.neverDomains))) !== null && _19 !== void 0 ? _19 : defaultAccount.settings.neverDomains,
                passwordGenerationOptions: (_20 = (yield this.get(v1Keys.passwordGenerationOptions))) !== null && _20 !== void 0 ? _20 : defaultAccount.settings.passwordGenerationOptions,
                pinProtected: Object.assign(new EncryptionPair(), {
                    decrypted: null,
                    encrypted: yield this.get(v1Keys.pinProtected),
                }),
                protectedPin: yield this.get(v1Keys.protectedPin),
                settings: userId == null
                    ? null
                    : yield this.get(v1KeyPrefixes.settings + userId),
                vaultTimeout: (_21 = (yield this.get(v1Keys.vaultTimeout))) !== null && _21 !== void 0 ? _21 : defaultAccount.settings.vaultTimeout,
                vaultTimeoutAction: (_22 = (yield this.get(v1Keys.vaultTimeoutAction))) !== null && _22 !== void 0 ? _22 : defaultAccount.settings.vaultTimeoutAction,
            };
            // (userId == null) = no logged in user (so no known userId) and we need to temporarily store account specific settings in state to migrate on first auth
            // (userId != null) = we have a currently authed user (so known userId) with encrypted data and other key settings we can move, no need to temporarily store account settings
            if (userId == null) {
                yield this.set(stateMigration_service_keys.tempAccountSettings, accountSettings);
                yield this.set(stateMigration_service_keys.global, globals);
                yield this.set(stateMigration_service_keys.authenticatedAccounts, []);
                yield this.set(stateMigration_service_keys.activeUserId, null);
                yield clearV1Keys();
                return;
            }
            globals.twoFactorToken = yield this.get(v1KeyPrefixes.twoFactorToken + userId);
            yield this.set(stateMigration_service_keys.global, globals);
            yield this.set(userId, {
                data: {
                    addEditCipherInfo: null,
                    ciphers: {
                        decrypted: null,
                        encrypted: yield this.get(v1KeyPrefixes.ciphers + userId),
                    },
                    collapsedGroupings: null,
                    collections: {
                        decrypted: null,
                        encrypted: yield this.get(v1KeyPrefixes.collections + userId),
                    },
                    eventCollection: yield this.get(v1Keys.eventCollection),
                    folders: {
                        decrypted: null,
                        encrypted: yield this.get(v1KeyPrefixes.folders + userId),
                    },
                    localData: null,
                    organizations: yield this.get(v1KeyPrefixes.organizations + userId),
                    passwordGenerationHistory: {
                        decrypted: null,
                        encrypted: yield this.get(v1Keys.history),
                    },
                    policies: {
                        decrypted: null,
                        encrypted: yield this.get(v1KeyPrefixes.policies + userId),
                    },
                    providers: yield this.get(v1KeyPrefixes.providers + userId),
                    sends: {
                        decrypted: null,
                        encrypted: yield this.get(v1KeyPrefixes.sends + userId),
                    },
                },
                keys: {
                    apiKeyClientSecret: yield this.get(v1Keys.clientSecret),
                    cryptoMasterKey: null,
                    cryptoMasterKeyAuto: null,
                    cryptoMasterKeyB64: null,
                    cryptoMasterKeyBiometric: null,
                    cryptoSymmetricKey: {
                        encrypted: yield this.get(v1Keys.encKey),
                        decrypted: null,
                    },
                    legacyEtmKey: null,
                    organizationKeys: {
                        decrypted: null,
                        encrypted: yield this.get(v1Keys.encOrgKeys),
                    },
                    privateKey: {
                        decrypted: null,
                        encrypted: yield this.get(v1Keys.encPrivate),
                    },
                    providerKeys: {
                        decrypted: null,
                        encrypted: yield this.get(v1Keys.encProviderKeys),
                    },
                    publicKey: null,
                },
                profile: {
                    apiKeyClientId: yield this.get(v1Keys.clientId),
                    authenticationStatus: null,
                    convertAccountToKeyConnector: yield this.get(v1Keys.convertAccountToKeyConnector),
                    email: yield this.get(v1Keys.userEmail),
                    emailVerified: yield this.get(v1Keys.emailVerified),
                    entityId: null,
                    entityType: null,
                    everBeenUnlocked: null,
                    forcePasswordReset: null,
                    hasPremiumPersonally: null,
                    kdfIterations: yield this.get(v1Keys.kdfIterations),
                    kdfType: yield this.get(v1Keys.kdf),
                    keyHash: yield this.get(v1Keys.keyHash),
                    lastSync: null,
                    userId: userId,
                    usesKeyConnector: null,
                },
                settings: accountSettings,
                tokens: {
                    accessToken: yield this.get(v1Keys.accessToken),
                    decodedToken: null,
                    refreshToken: yield this.get(v1Keys.refreshToken),
                    securityStamp: null,
                },
            });
            yield this.set(stateMigration_service_keys.authenticatedAccounts, [userId]);
            yield this.set(stateMigration_service_keys.activeUserId, userId);
            const accountActivity = {
                [userId]: yield this.get(v1Keys.lastActive),
            };
            accountActivity[userId] = yield this.get(v1Keys.lastActive);
            yield this.set(stateMigration_service_keys.accountActivity, accountActivity);
            yield clearV1Keys(userId);
            if (yield this.secureStorageService.has(v1Keys.key, { keySuffix: "biometric" })) {
                yield this.secureStorageService.save(`${userId}${stateMigration_service_partialKeys.biometricKey}`, yield this.secureStorageService.get(v1Keys.key, { keySuffix: "biometric" }), { keySuffix: "biometric" });
                yield this.secureStorageService.remove(v1Keys.key, { keySuffix: "biometric" });
            }
            if (yield this.secureStorageService.has(v1Keys.key, { keySuffix: "auto" })) {
                yield this.secureStorageService.save(`${userId}${stateMigration_service_partialKeys.autoKey}`, yield this.secureStorageService.get(v1Keys.key, { keySuffix: "auto" }), { keySuffix: "auto" });
                yield this.secureStorageService.remove(v1Keys.key, { keySuffix: "auto" });
            }
            if (yield this.secureStorageService.has(v1Keys.key)) {
                yield this.secureStorageService.save(`${userId}${stateMigration_service_partialKeys.masterKey}`, yield this.secureStorageService.get(v1Keys.key));
                yield this.secureStorageService.remove(v1Keys.key);
            }
        });
    }
    migrateStateFrom2To3() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const authenticatedUserIds = yield this.get(stateMigration_service_keys.authenticatedAccounts);
            yield Promise.all(authenticatedUserIds.map((userId) => stateMigration_service_awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                const account = yield this.get(userId);
                if (((_a = account === null || account === void 0 ? void 0 : account.profile) === null || _a === void 0 ? void 0 : _a.hasPremiumPersonally) === null &&
                    ((_b = account.tokens) === null || _b === void 0 ? void 0 : _b.accessToken) != null) {
                    const decodedToken = yield TokenService.decodeToken(account.tokens.accessToken);
                    account.profile.hasPremiumPersonally = decodedToken.premium;
                    yield this.set(userId, account);
                }
            })));
            const globals = yield this.getGlobals();
            globals.stateVersion = StateVersion.Three;
            yield this.set(stateMigration_service_keys.global, globals);
        });
    }
    migrateStateFrom3To4() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const authenticatedUserIds = yield this.get(stateMigration_service_keys.authenticatedAccounts);
            yield Promise.all(authenticatedUserIds.map((userId) => stateMigration_service_awaiter(this, void 0, void 0, function* () {
                var _a;
                const account = yield this.get(userId);
                if (((_a = account === null || account === void 0 ? void 0 : account.profile) === null || _a === void 0 ? void 0 : _a.everBeenUnlocked) != null) {
                    delete account.profile.everBeenUnlocked;
                    return this.set(userId, account);
                }
            })));
            const globals = yield this.getGlobals();
            globals.stateVersion = StateVersion.Four;
            yield this.set(stateMigration_service_keys.global, globals);
        });
    }
    migrateAccountFrom4To5(account) {
        var _a, _b;
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const encryptedOrgKeys = (_b = (_a = account.keys) === null || _a === void 0 ? void 0 : _a.organizationKeys) === null || _b === void 0 ? void 0 : _b.encrypted;
            if (encryptedOrgKeys != null) {
                for (const [orgId, encKey] of Object.entries(encryptedOrgKeys)) {
                    encryptedOrgKeys[orgId] = {
                        type: "organization",
                        key: encKey, // Account v4 does not reflect the current account model so we have to cast
                    };
                }
            }
            return account;
        });
    }
    migrateAccountFrom5To6(account) {
        var _a;
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            (_a = account.keys) === null || _a === void 0 ? true : delete _a.legacyEtmKey;
            return account;
        });
    }
    get options() {
        return { htmlStorageLocation: HtmlStorageLocation.Local };
    }
    get(key) {
        return this.storageService.get(key, this.options);
    }
    set(key, value) {
        if (value == null) {
            return this.storageService.remove(key, this.options);
        }
        return this.storageService.save(key, value, this.options);
    }
    getGlobals() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            return yield this.get(stateMigration_service_keys.global);
        });
    }
    getCurrentStateVersion() {
        var _a, _b;
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            return (_b = (_a = (yield this.getGlobals())) === null || _a === void 0 ? void 0 : _a.stateVersion) !== null && _b !== void 0 ? _b : StateVersion.One;
        });
    }
    setCurrentStateVersion(newVersion) {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const globals = yield this.getGlobals();
            globals.stateVersion = newVersion;
            yield this.set(stateMigration_service_keys.global, globals);
        });
    }
    getAuthenticatedAccounts() {
        return stateMigration_service_awaiter(this, void 0, void 0, function* () {
            const authenticatedUserIds = yield this.get(stateMigration_service_keys.authenticatedAccounts);
            return Promise.all(authenticatedUserIds.map((id) => this.get(id)));
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/totp.service.ts
var totp_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

const B32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const SteamChars = "23456789BCDFGHJKMNPQRTVWXY";
class TotpService {
    constructor(cryptoFunctionService, logService) {
        this.cryptoFunctionService = cryptoFunctionService;
        this.logService = logService;
    }
    getCode(key) {
        return totp_service_awaiter(this, void 0, void 0, function* () {
            if (key == null) {
                return null;
            }
            let period = 30;
            let alg = "sha1";
            let digits = 6;
            let keyB32 = key;
            const isOtpAuth = key.toLowerCase().indexOf("otpauth://") === 0;
            const isSteamAuth = !isOtpAuth && key.toLowerCase().indexOf("steam://") === 0;
            if (isOtpAuth) {
                const params = Utils.getQueryParams(key);
                if (params.has("digits") && params.get("digits") != null) {
                    try {
                        const digitParams = parseInt(params.get("digits").trim(), null);
                        if (digitParams > 10) {
                            digits = 10;
                        }
                        else if (digitParams > 0) {
                            digits = digitParams;
                        }
                    }
                    catch (_a) {
                        this.logService.error("Invalid digits param.");
                    }
                }
                if (params.has("period") && params.get("period") != null) {
                    try {
                        const periodParam = parseInt(params.get("period").trim(), null);
                        if (periodParam > 0) {
                            period = periodParam;
                        }
                    }
                    catch (_b) {
                        this.logService.error("Invalid period param.");
                    }
                }
                if (params.has("secret") && params.get("secret") != null) {
                    keyB32 = params.get("secret");
                }
                if (params.has("algorithm") && params.get("algorithm") != null) {
                    const algParam = params.get("algorithm").toLowerCase();
                    if (algParam === "sha1" || algParam === "sha256" || algParam === "sha512") {
                        alg = algParam;
                    }
                }
            }
            else if (isSteamAuth) {
                keyB32 = key.substr("steam://".length);
                digits = 5;
            }
            const epoch = Math.round(new Date().getTime() / 1000.0);
            const timeHex = this.leftPad(this.decToHex(Math.floor(epoch / period)), 16, "0");
            const timeBytes = Utils.fromHexToArray(timeHex);
            const keyBytes = this.b32ToBytes(keyB32);
            if (!keyBytes.length || !timeBytes.length) {
                return null;
            }
            const hash = yield this.sign(keyBytes, timeBytes, alg);
            if (hash.length === 0) {
                return null;
            }
            const offset = hash[hash.length - 1] & 0xf;
            const binary = ((hash[offset] & 0x7f) << 24) |
                ((hash[offset + 1] & 0xff) << 16) |
                ((hash[offset + 2] & 0xff) << 8) |
                (hash[offset + 3] & 0xff);
            let otp = "";
            if (isSteamAuth) {
                let fullCode = binary & 0x7fffffff;
                for (let i = 0; i < digits; i++) {
                    otp += SteamChars[fullCode % SteamChars.length];
                    fullCode = Math.trunc(fullCode / SteamChars.length);
                }
            }
            else {
                otp = (binary % Math.pow(10, digits)).toString();
                otp = this.leftPad(otp, digits, "0");
            }
            return otp;
        });
    }
    getTimeInterval(key) {
        let period = 30;
        if (key != null && key.toLowerCase().indexOf("otpauth://") === 0) {
            const params = Utils.getQueryParams(key);
            if (params.has("period") && params.get("period") != null) {
                try {
                    period = parseInt(params.get("period").trim(), null);
                }
                catch (_a) {
                    this.logService.error("Invalid period param.");
                }
            }
        }
        return period;
    }
    // Helpers
    leftPad(s, l, p) {
        if (l + 1 >= s.length) {
            s = Array(l + 1 - s.length).join(p) + s;
        }
        return s;
    }
    decToHex(d) {
        return (d < 15.5 ? "0" : "") + Math.round(d).toString(16);
    }
    b32ToHex(s) {
        s = s.toUpperCase();
        let cleanedInput = "";
        for (let i = 0; i < s.length; i++) {
            if (B32Chars.indexOf(s[i]) < 0) {
                continue;
            }
            cleanedInput += s[i];
        }
        s = cleanedInput;
        let bits = "";
        let hex = "";
        for (let i = 0; i < s.length; i++) {
            const byteIndex = B32Chars.indexOf(s.charAt(i));
            if (byteIndex < 0) {
                continue;
            }
            bits += this.leftPad(byteIndex.toString(2), 5, "0");
        }
        for (let i = 0; i + 4 <= bits.length; i += 4) {
            const chunk = bits.substr(i, 4);
            hex = hex + parseInt(chunk, 2).toString(16);
        }
        return hex;
    }
    b32ToBytes(s) {
        return Utils.fromHexToArray(this.b32ToHex(s));
    }
    sign(keyBytes, timeBytes, alg) {
        return totp_service_awaiter(this, void 0, void 0, function* () {
            const signature = yield this.cryptoFunctionService.hmac(timeBytes.buffer, keyBytes.buffer, alg);
            return new Uint8Array(signature);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/twoFactor.service.ts

const TwoFactorProviders = {
    [TwoFactorProviderType.Authenticator]: {
        type: TwoFactorProviderType.Authenticator,
        name: null,
        description: null,
        priority: 1,
        sort: 1,
        premium: false,
    },
    [TwoFactorProviderType.Yubikey]: {
        type: TwoFactorProviderType.Yubikey,
        name: null,
        description: null,
        priority: 3,
        sort: 2,
        premium: true,
    },
    [TwoFactorProviderType.Duo]: {
        type: TwoFactorProviderType.Duo,
        name: "Duo",
        description: null,
        priority: 2,
        sort: 3,
        premium: true,
    },
    [TwoFactorProviderType.OrganizationDuo]: {
        type: TwoFactorProviderType.OrganizationDuo,
        name: "Duo (Organization)",
        description: null,
        priority: 10,
        sort: 4,
        premium: false,
    },
    [TwoFactorProviderType.Email]: {
        type: TwoFactorProviderType.Email,
        name: null,
        description: null,
        priority: 0,
        sort: 6,
        premium: false,
    },
    [TwoFactorProviderType.WebAuthn]: {
        type: TwoFactorProviderType.WebAuthn,
        name: null,
        description: null,
        priority: 4,
        sort: 5,
        premium: true,
    },
};
class TwoFactorService {
    constructor(i18nService, platformUtilsService) {
        this.i18nService = i18nService;
        this.platformUtilsService = platformUtilsService;
        this.selectedTwoFactorProviderType = null;
    }
    init() {
        TwoFactorProviders[TwoFactorProviderType.Email].name = this.i18nService.t("emailTitle");
        TwoFactorProviders[TwoFactorProviderType.Email].description = this.i18nService.t("emailDesc");
        TwoFactorProviders[TwoFactorProviderType.Authenticator].name =
            this.i18nService.t("authenticatorAppTitle");
        TwoFactorProviders[TwoFactorProviderType.Authenticator].description =
            this.i18nService.t("authenticatorAppDesc");
        TwoFactorProviders[TwoFactorProviderType.Duo].description = this.i18nService.t("duoDesc");
        TwoFactorProviders[TwoFactorProviderType.OrganizationDuo].name =
            "Duo (" + this.i18nService.t("organization") + ")";
        TwoFactorProviders[TwoFactorProviderType.OrganizationDuo].description =
            this.i18nService.t("duoOrganizationDesc");
        TwoFactorProviders[TwoFactorProviderType.WebAuthn].name = this.i18nService.t("webAuthnTitle");
        TwoFactorProviders[TwoFactorProviderType.WebAuthn].description =
            this.i18nService.t("webAuthnDesc");
        TwoFactorProviders[TwoFactorProviderType.Yubikey].name = this.i18nService.t("yubiKeyTitle");
        TwoFactorProviders[TwoFactorProviderType.Yubikey].description =
            this.i18nService.t("yubiKeyDesc");
    }
    getSupportedProviders(win) {
        const providers = [];
        if (this.twoFactorProvidersData == null) {
            return providers;
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.OrganizationDuo) &&
            this.platformUtilsService.supportsDuo()) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.OrganizationDuo]);
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.Authenticator)) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.Authenticator]);
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.Yubikey)) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.Yubikey]);
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.Duo) &&
            this.platformUtilsService.supportsDuo()) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.Duo]);
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.WebAuthn) &&
            this.platformUtilsService.supportsWebAuthn(win)) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.WebAuthn]);
        }
        if (this.twoFactorProvidersData.has(TwoFactorProviderType.Email)) {
            providers.push(TwoFactorProviders[TwoFactorProviderType.Email]);
        }
        return providers;
    }
    getDefaultProvider(webAuthnSupported) {
        if (this.twoFactorProvidersData == null) {
            return null;
        }
        if (this.selectedTwoFactorProviderType != null &&
            this.twoFactorProvidersData.has(this.selectedTwoFactorProviderType)) {
            return this.selectedTwoFactorProviderType;
        }
        let providerType = null;
        let providerPriority = -1;
        this.twoFactorProvidersData.forEach((_value, type) => {
            const provider = TwoFactorProviders[type];
            if (provider != null && provider.priority > providerPriority) {
                if (type === TwoFactorProviderType.WebAuthn && !webAuthnSupported) {
                    return;
                }
                providerType = type;
                providerPriority = provider.priority;
            }
        });
        return providerType;
    }
    setSelectedProvider(type) {
        this.selectedTwoFactorProviderType = type;
    }
    clearSelectedProvider() {
        this.selectedTwoFactorProviderType = null;
    }
    setProviders(response) {
        this.twoFactorProvidersData = response.twoFactorProviders2;
    }
    clearProviders() {
        this.twoFactorProvidersData = null;
    }
    getProviders() {
        return this.twoFactorProvidersData;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/userVerification/userVerification-api.service.ts
var userVerification_api_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class UserVerificationApiService {
    constructor(apiService) {
        this.apiService = apiService;
    }
    postAccountVerifyOTP(request) {
        return this.apiService.send("POST", "/accounts/verify-otp", request, true, false);
    }
    postAccountRequestOTP() {
        return userVerification_api_service_awaiter(this, void 0, void 0, function* () {
            return this.apiService.send("POST", "/accounts/request-otp", null, true, false);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/enums/verificationType.ts
var VerificationType;
(function (VerificationType) {
    VerificationType[VerificationType["MasterPassword"] = 0] = "MasterPassword";
    VerificationType[VerificationType["OTP"] = 1] = "OTP";
})(VerificationType || (VerificationType = {}));

;// CONCATENATED MODULE: ../../libs/common/src/models/request/account/verify-otp.request.ts
class VerifyOTPRequest {
    constructor(OTP) {
        this.OTP = OTP;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/secret-verification.request.ts
class SecretVerificationRequest {
}

;// CONCATENATED MODULE: ../../libs/common/src/services/userVerification/userVerification.service.ts
var userVerification_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



/**
 * Used for general-purpose user verification throughout the app.
 * Use it to verify the input collected by UserVerificationComponent.
 */
class UserVerificationService {
    constructor(cryptoService, i18nService, userVerificationApiService) {
        this.cryptoService = cryptoService;
        this.i18nService = i18nService;
        this.userVerificationApiService = userVerificationApiService;
    }
    /**
     * Create a new request model to be used for server-side verification
     * @param verification User-supplied verification data (Master Password or OTP)
     * @param requestClass The request model to create
     * @param alreadyHashed Whether the master password is already hashed
     */
    buildRequest(verification, requestClass, alreadyHashed) {
        return userVerification_service_awaiter(this, void 0, void 0, function* () {
            this.validateInput(verification);
            const request = requestClass != null ? new requestClass() : new SecretVerificationRequest();
            if (verification.type === VerificationType.OTP) {
                request.otp = verification.secret;
            }
            else {
                request.masterPasswordHash = alreadyHashed
                    ? verification.secret
                    : yield this.cryptoService.hashPassword(verification.secret, null);
            }
            return request;
        });
    }
    /**
     * Used to verify the Master Password client-side, or send the OTP to the server for verification (with no other data)
     * Generally used for client-side verification only.
     * @param verification User-supplied verification data (Master Password or OTP)
     */
    verifyUser(verification) {
        return userVerification_service_awaiter(this, void 0, void 0, function* () {
            this.validateInput(verification);
            if (verification.type === VerificationType.OTP) {
                const request = new VerifyOTPRequest(verification.secret);
                try {
                    yield this.userVerificationApiService.postAccountVerifyOTP(request);
                }
                catch (e) {
                    throw new Error(this.i18nService.t("invalidVerificationCode"));
                }
            }
            else {
                const passwordValid = yield this.cryptoService.compareAndUpdateKeyHash(verification.secret, null);
                if (!passwordValid) {
                    throw new Error(this.i18nService.t("invalidMasterPassword"));
                }
            }
            return true;
        });
    }
    requestOTP() {
        return userVerification_service_awaiter(this, void 0, void 0, function* () {
            yield this.userVerificationApiService.postAccountRequestOTP();
        });
    }
    validateInput(verification) {
        if ((verification === null || verification === void 0 ? void 0 : verification.secret) == null || verification.secret === "") {
            if (verification.type === VerificationType.OTP) {
                throw new Error(this.i18nService.t("verificationCodeRequired"));
            }
            else {
                throw new Error(this.i18nService.t("masterPasswordRequired"));
            }
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/vaultTimeout/vaultTimeout.service.ts
var vaultTimeout_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class VaultTimeoutService {
    constructor(cipherService, folderService, collectionService, cryptoService, platformUtilsService, messagingService, searchService, keyConnectorService, stateService, authService, vaultTimeoutSettingsService, lockedCallback = null, loggedOutCallback = null) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.collectionService = collectionService;
        this.cryptoService = cryptoService;
        this.platformUtilsService = platformUtilsService;
        this.messagingService = messagingService;
        this.searchService = searchService;
        this.keyConnectorService = keyConnectorService;
        this.stateService = stateService;
        this.authService = authService;
        this.vaultTimeoutSettingsService = vaultTimeoutSettingsService;
        this.lockedCallback = lockedCallback;
        this.loggedOutCallback = loggedOutCallback;
        this.inited = false;
    }
    init(checkOnInterval) {
        if (this.inited) {
            return;
        }
        this.inited = true;
        if (checkOnInterval) {
            this.startCheck();
        }
    }
    startCheck() {
        this.checkVaultTimeout();
        setInterval(() => this.checkVaultTimeout(), 10 * 1000); // check every 10 seconds
    }
    checkVaultTimeout() {
        return vaultTimeout_service_awaiter(this, void 0, void 0, function* () {
            if (yield this.platformUtilsService.isViewOpen()) {
                return;
            }
            const accounts = yield (0,external_rxjs_namespaceObject.firstValueFrom)(this.stateService.accounts$);
            for (const userId in accounts) {
                if (userId != null && (yield this.shouldLock(userId))) {
                    yield this.executeTimeoutAction(userId);
                }
            }
        });
    }
    lock(userId) {
        return vaultTimeout_service_awaiter(this, void 0, void 0, function* () {
            const authed = yield this.stateService.getIsAuthenticated({ userId: userId });
            if (!authed) {
                return;
            }
            if (yield this.keyConnectorService.getUsesKeyConnector()) {
                const pinSet = yield this.vaultTimeoutSettingsService.isPinLockSet();
                const pinLock = (pinSet[0] && (yield this.stateService.getDecryptedPinProtected()) != null) || pinSet[1];
                if (!pinLock && !(yield this.vaultTimeoutSettingsService.isBiometricLockSet())) {
                    yield this.logOut(userId);
                }
            }
            if (userId == null || userId === (yield this.stateService.getUserId())) {
                this.searchService.clearIndex();
                yield this.folderService.clearCache();
            }
            yield this.stateService.setEverBeenUnlocked(true, { userId: userId });
            yield this.stateService.setCryptoMasterKeyAuto(null, { userId: userId });
            yield this.cryptoService.clearKey(false, userId);
            yield this.cryptoService.clearOrgKeys(true, userId);
            yield this.cryptoService.clearKeyPair(true, userId);
            yield this.cryptoService.clearEncKey(true, userId);
            yield this.cipherService.clearCache(userId);
            yield this.collectionService.clearCache(userId);
            this.messagingService.send("locked", { userId: userId });
            if (this.lockedCallback != null) {
                yield this.lockedCallback(userId);
            }
        });
    }
    logOut(userId) {
        return vaultTimeout_service_awaiter(this, void 0, void 0, function* () {
            if (this.loggedOutCallback != null) {
                yield this.loggedOutCallback(false, userId);
            }
        });
    }
    shouldLock(userId) {
        return vaultTimeout_service_awaiter(this, void 0, void 0, function* () {
            const authStatus = yield this.authService.getAuthStatus(userId);
            if (authStatus === AuthenticationStatus.Locked ||
                authStatus === AuthenticationStatus.LoggedOut) {
                return false;
            }
            const vaultTimeout = yield this.vaultTimeoutSettingsService.getVaultTimeout(userId);
            if (vaultTimeout == null || vaultTimeout < 0) {
                return false;
            }
            const lastActive = yield this.stateService.getLastActive({ userId: userId });
            if (lastActive == null) {
                return false;
            }
            const vaultTimeoutSeconds = vaultTimeout * 60;
            const diffSeconds = (new Date().getTime() - lastActive) / 1000;
            return diffSeconds >= vaultTimeoutSeconds;
        });
    }
    executeTimeoutAction(userId) {
        return vaultTimeout_service_awaiter(this, void 0, void 0, function* () {
            const timeoutAction = yield this.stateService.getVaultTimeoutAction({ userId: userId });
            timeoutAction === "logOut" ? yield this.logOut(userId) : yield this.lock(userId);
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/vaultTimeout/vaultTimeoutSettings.service.ts
var vaultTimeoutSettings_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class VaultTimeoutSettingsService {
    constructor(cryptoService, tokenService, policyService, stateService) {
        this.cryptoService = cryptoService;
        this.tokenService = tokenService;
        this.policyService = policyService;
        this.stateService = stateService;
    }
    setVaultTimeoutOptions(timeout, action) {
        return vaultTimeoutSettings_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setVaultTimeout(timeout);
            // We swap these tokens from being on disk for lock actions, and in memory for logout actions
            // Get them here to set them to their new location after changing the timeout action and clearing if needed
            const token = yield this.tokenService.getToken();
            const refreshToken = yield this.tokenService.getRefreshToken();
            const clientId = yield this.tokenService.getClientId();
            const clientSecret = yield this.tokenService.getClientSecret();
            const currentAction = yield this.stateService.getVaultTimeoutAction();
            if ((timeout != null || timeout === 0) && action === "logOut" && action !== currentAction) {
                // if we have a vault timeout and the action is log out, reset tokens
                yield this.tokenService.clearToken();
            }
            yield this.stateService.setVaultTimeoutAction(action);
            yield this.tokenService.setToken(token);
            yield this.tokenService.setRefreshToken(refreshToken);
            yield this.tokenService.setClientId(clientId);
            yield this.tokenService.setClientSecret(clientSecret);
            yield this.cryptoService.toggleKey();
        });
    }
    isPinLockSet() {
        return vaultTimeoutSettings_service_awaiter(this, void 0, void 0, function* () {
            const protectedPin = yield this.stateService.getProtectedPin();
            const pinProtectedKey = yield this.stateService.getEncryptedPinProtected();
            return [protectedPin != null, pinProtectedKey != null];
        });
    }
    isBiometricLockSet() {
        return vaultTimeoutSettings_service_awaiter(this, void 0, void 0, function* () {
            return yield this.stateService.getBiometricUnlock();
        });
    }
    getVaultTimeout(userId) {
        return vaultTimeoutSettings_service_awaiter(this, void 0, void 0, function* () {
            const vaultTimeout = yield this.stateService.getVaultTimeout({ userId: userId });
            if (yield this.policyService.policyAppliesToUser(PolicyType.MaximumVaultTimeout, null, userId)) {
                const policy = yield this.policyService.getAll(PolicyType.MaximumVaultTimeout, userId);
                // Remove negative values, and ensure it's smaller than maximum allowed value according to policy
                let timeout = Math.min(vaultTimeout, policy[0].data.minutes);
                if (vaultTimeout == null || timeout < 0) {
                    timeout = policy[0].data.minutes;
                }
                // We really shouldn't need to set the value here, but multiple services relies on this value being correct.
                if (vaultTimeout !== timeout) {
                    yield this.stateService.setVaultTimeout(timeout, { userId: userId });
                }
                return timeout;
            }
            return vaultTimeout;
        });
    }
    clear(userId) {
        return vaultTimeoutSettings_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setEverBeenUnlocked(false, { userId: userId });
            yield this.stateService.setDecryptedPinProtected(null, { userId: userId });
            yield this.stateService.setProtectedPin(null, { userId: userId });
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/domain/sorted-ciphers-cache.ts
const CacheTTL = 3000;
class SortedCiphersCache {
    constructor(comparator) {
        this.comparator = comparator;
        this.sortedCiphersByUrl = new Map();
        this.timeouts = new Map();
    }
    isCached(url) {
        return this.sortedCiphersByUrl.has(url);
    }
    addCiphers(url, ciphers) {
        ciphers.sort(this.comparator);
        this.sortedCiphersByUrl.set(url, new Ciphers(ciphers));
        this.resetTimer(url);
    }
    getLastUsed(url) {
        this.resetTimer(url);
        return this.isCached(url) ? this.sortedCiphersByUrl.get(url).getLastUsed() : null;
    }
    getLastLaunched(url) {
        return this.isCached(url) ? this.sortedCiphersByUrl.get(url).getLastLaunched() : null;
    }
    getNext(url) {
        this.resetTimer(url);
        return this.isCached(url) ? this.sortedCiphersByUrl.get(url).getNext() : null;
    }
    updateLastUsedIndex(url) {
        if (this.isCached(url)) {
            this.sortedCiphersByUrl.get(url).updateLastUsedIndex();
        }
    }
    clear() {
        this.sortedCiphersByUrl.clear();
        this.timeouts.clear();
    }
    resetTimer(url) {
        clearTimeout(this.timeouts.get(url));
        this.timeouts.set(url, setTimeout(() => {
            this.sortedCiphersByUrl.delete(url);
            this.timeouts.delete(url);
        }, CacheTTL));
    }
}
class Ciphers {
    constructor(ciphers) {
        this.ciphers = ciphers;
        this.lastUsedIndex = -1;
    }
    getLastUsed() {
        this.lastUsedIndex = Math.max(this.lastUsedIndex, 0);
        return this.ciphers[this.lastUsedIndex];
    }
    getLastLaunched() {
        const usedCiphers = this.ciphers.filter((cipher) => { var _a; return (_a = cipher.localData) === null || _a === void 0 ? void 0 : _a.lastLaunched; });
        const sortedCiphers = usedCiphers.sort((x, y) => y.localData.lastLaunched.valueOf() - x.localData.lastLaunched.valueOf());
        return sortedCiphers[0];
    }
    getNextIndex() {
        return (this.lastUsedIndex + 1) % this.ciphers.length;
    }
    getNext() {
        return this.ciphers[this.getNextIndex()];
    }
    updateLastUsedIndex() {
        this.lastUsedIndex = this.getNextIndex();
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-bulk-delete.request.ts
class CipherBulkDeleteRequest {
    constructor(ids, organizationId) {
        this.ids = ids == null ? [] : ids;
        this.organizationId = organizationId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-bulk-move.request.ts
class CipherBulkMoveRequest {
    constructor(ids, folderId) {
        this.ids = ids == null ? [] : ids;
        this.folderId = folderId;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-bulk-restore.request.ts
class CipherBulkRestoreRequest {
    constructor(ids) {
        this.ids = ids == null ? [] : ids;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-with-id.request.ts

class CipherWithIdRequest extends CipherRequest {
    constructor(cipher) {
        super(cipher);
        this.id = cipher.id;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-bulk-share.request.ts

class CipherBulkShareRequest {
    constructor(ciphers, collectionIds) {
        if (ciphers != null) {
            this.ciphers = [];
            ciphers.forEach((c) => {
                this.ciphers.push(new CipherWithIdRequest(c));
            });
        }
        this.collectionIds = collectionIds;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-collections.request.ts
class CipherCollectionsRequest {
    constructor(collectionIds) {
        this.collectionIds = collectionIds == null ? [] : collectionIds;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-create.request.ts

class CipherCreateRequest {
    constructor(cipher) {
        this.cipher = new CipherRequest(cipher);
        this.collectionIds = cipher.collectionIds;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-partial.request.ts
class CipherPartialRequest {
    constructor(cipher) {
        this.folderId = cipher.folderId;
        this.favorite = cipher.favorite;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/request/cipher-share.request.ts

class CipherShareRequest {
    constructor(cipher) {
        this.cipher = new CipherRequest(cipher);
        this.collectionIds = cipher.collectionIds;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/services/cipher.service.ts
var cipher_service_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var cipher_service_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var cipher_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





























const DomainMatchBlacklist = new Map([
    ["google.com", new Set(["script.google.com"])],
]);
class CipherService {
    constructor(cryptoService, settingsService, apiService, fileUploadService, i18nService, searchService, logService, stateService, encryptService) {
        this.cryptoService = cryptoService;
        this.settingsService = settingsService;
        this.apiService = apiService;
        this.fileUploadService = fileUploadService;
        this.i18nService = i18nService;
        this.searchService = searchService;
        this.logService = logService;
        this.stateService = stateService;
        this.encryptService = encryptService;
        this.sortedCiphersCache = new SortedCiphersCache(this.sortCiphersByLastUsed);
    }
    getDecryptedCipherCache() {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const decryptedCiphers = yield this.stateService.getDecryptedCiphers();
            return decryptedCiphers;
        });
    }
    setDecryptedCipherCache(value) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedCiphers(value);
            if (this.searchService != null) {
                if (value == null) {
                    this.searchService().clearIndex();
                }
                else {
                    this.searchService().indexCiphers();
                }
            }
        });
    }
    clearCache(userId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearDecryptedCiphersState(userId);
        });
    }
    encrypt(model, key, originalCipher = null) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            // Adjust password history
            if (model.id != null) {
                if (originalCipher == null) {
                    originalCipher = yield this.get(model.id);
                }
                if (originalCipher != null) {
                    const existingCipher = yield originalCipher.decrypt();
                    model.passwordHistory = existingCipher.passwordHistory || [];
                    if (model.type === CipherType.Login && existingCipher.type === CipherType.Login) {
                        if (existingCipher.login.password != null &&
                            existingCipher.login.password !== "" &&
                            existingCipher.login.password !== model.login.password) {
                            const ph = new PasswordHistoryView();
                            ph.password = existingCipher.login.password;
                            ph.lastUsedDate = model.login.passwordRevisionDate = new Date();
                            model.passwordHistory.splice(0, 0, ph);
                        }
                        else {
                            model.login.passwordRevisionDate = existingCipher.login.passwordRevisionDate;
                        }
                    }
                    if (existingCipher.hasFields) {
                        const existingHiddenFields = existingCipher.fields.filter((f) => f.type === FieldType.Hidden &&
                            f.name != null &&
                            f.name !== "" &&
                            f.value != null &&
                            f.value !== "");
                        const hiddenFields = model.fields == null
                            ? []
                            : model.fields.filter((f) => f.type === FieldType.Hidden && f.name != null && f.name !== "");
                        existingHiddenFields.forEach((ef) => {
                            const matchedField = hiddenFields.find((f) => f.name === ef.name);
                            if (matchedField == null || matchedField.value !== ef.value) {
                                const ph = new PasswordHistoryView();
                                ph.password = ef.name + ": " + ef.value;
                                ph.lastUsedDate = new Date();
                                model.passwordHistory.splice(0, 0, ph);
                            }
                        });
                    }
                }
                if (model.passwordHistory != null && model.passwordHistory.length === 0) {
                    model.passwordHistory = null;
                }
                else if (model.passwordHistory != null && model.passwordHistory.length > 5) {
                    // only save last 5 history
                    model.passwordHistory = model.passwordHistory.slice(0, 5);
                }
            }
            const cipher = new Cipher();
            cipher.id = model.id;
            cipher.folderId = model.folderId;
            cipher.favorite = model.favorite;
            cipher.organizationId = model.organizationId;
            cipher.type = model.type;
            cipher.collectionIds = model.collectionIds;
            cipher.revisionDate = model.revisionDate;
            cipher.reprompt = model.reprompt;
            cipher.edit = model.edit;
            if (key == null && cipher.organizationId != null) {
                key = yield this.cryptoService.getOrgKey(cipher.organizationId);
                if (key == null) {
                    throw new Error("Cannot encrypt cipher for organization. No key.");
                }
            }
            yield Promise.all([
                this.encryptObjProperty(model, cipher, {
                    name: null,
                    notes: null,
                }, key),
                this.encryptCipherData(cipher, model, key),
                this.encryptFields(model.fields, key).then((fields) => {
                    cipher.fields = fields;
                }),
                this.encryptPasswordHistories(model.passwordHistory, key).then((ph) => {
                    cipher.passwordHistory = ph;
                }),
                this.encryptAttachments(model.attachments, key).then((attachments) => {
                    cipher.attachments = attachments;
                }),
            ]);
            return cipher;
        });
    }
    encryptAttachments(attachmentsModel, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if (attachmentsModel == null || attachmentsModel.length === 0) {
                return null;
            }
            const promises = [];
            const encAttachments = [];
            attachmentsModel.forEach((model) => cipher_service_awaiter(this, void 0, void 0, function* () {
                const attachment = new Attachment();
                attachment.id = model.id;
                attachment.size = model.size;
                attachment.sizeName = model.sizeName;
                attachment.url = model.url;
                const promise = this.encryptObjProperty(model, attachment, {
                    fileName: null,
                }, key).then(() => cipher_service_awaiter(this, void 0, void 0, function* () {
                    if (model.key != null) {
                        attachment.key = yield this.cryptoService.encrypt(model.key.key, key);
                    }
                    encAttachments.push(attachment);
                }));
                promises.push(promise);
            }));
            yield Promise.all(promises);
            return encAttachments;
        });
    }
    encryptFields(fieldsModel, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if (!fieldsModel || !fieldsModel.length) {
                return null;
            }
            const self = this;
            const encFields = [];
            yield fieldsModel.reduce((promise, field) => cipher_service_awaiter(this, void 0, void 0, function* () {
                yield promise;
                const encField = yield self.encryptField(field, key);
                encFields.push(encField);
            }), Promise.resolve());
            return encFields;
        });
    }
    encryptField(fieldModel, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const field = new Field();
            field.type = fieldModel.type;
            field.linkedId = fieldModel.linkedId;
            // normalize boolean type field values
            if (fieldModel.type === FieldType.Boolean && fieldModel.value !== "true") {
                fieldModel.value = "false";
            }
            yield this.encryptObjProperty(fieldModel, field, {
                name: null,
                value: null,
            }, key);
            return field;
        });
    }
    encryptPasswordHistories(phModels, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if (!phModels || !phModels.length) {
                return null;
            }
            const self = this;
            const encPhs = [];
            yield phModels.reduce((promise, ph) => cipher_service_awaiter(this, void 0, void 0, function* () {
                yield promise;
                const encPh = yield self.encryptPasswordHistory(ph, key);
                encPhs.push(encPh);
            }), Promise.resolve());
            return encPhs;
        });
    }
    encryptPasswordHistory(phModel, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ph = new Password();
            ph.lastUsedDate = phModel.lastUsedDate;
            yield this.encryptObjProperty(phModel, ph, {
                password: null,
            }, key);
            return ph;
        });
    }
    get(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.stateService.getEncryptedCiphers();
            // eslint-disable-next-line
            if (ciphers == null || !ciphers.hasOwnProperty(id)) {
                return null;
            }
            const localData = yield this.stateService.getLocalData();
            return new Cipher(ciphers[id], localData ? localData[id] : null);
        });
    }
    getAll() {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const localData = yield this.stateService.getLocalData();
            const ciphers = yield this.stateService.getEncryptedCiphers();
            const response = [];
            for (const id in ciphers) {
                // eslint-disable-next-line
                if (ciphers.hasOwnProperty(id)) {
                    response.push(new Cipher(ciphers[id], localData ? localData[id] : null));
                }
            }
            return response;
        });
    }
    getAllDecrypted() {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if ((yield this.getDecryptedCipherCache()) != null) {
                yield this.reindexCiphers();
                return yield this.getDecryptedCipherCache();
            }
            const hasKey = yield this.cryptoService.hasKey();
            if (!hasKey) {
                throw new Error("No key.");
            }
            const ciphers = yield this.getAll();
            const orgKeys = yield this.cryptoService.getOrgKeys();
            const userKey = yield this.cryptoService.getKeyForUserEncryption();
            // Group ciphers by orgId or under 'null' for the user's ciphers
            const grouped = ciphers.reduce((agg, c) => {
                var _a;
                var _b;
                (_a = agg[_b = c.organizationId]) !== null && _a !== void 0 ? _a : (agg[_b] = []);
                agg[c.organizationId].push(c);
                return agg;
            }, {});
            const decCiphers = (yield Promise.all(Object.entries(grouped).map(([orgId, groupedCiphers]) => { var _a; return this.encryptService.decryptItems(groupedCiphers, (_a = orgKeys.get(orgId)) !== null && _a !== void 0 ? _a : userKey); })))
                .flat()
                .sort(this.getLocaleSortingFunction());
            yield this.setDecryptedCipherCache(decCiphers);
            return decCiphers;
        });
    }
    reindexCiphers() {
        var _a;
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const userId = yield this.stateService.getUserId();
            const reindexRequired = this.searchService != null && ((_a = this.searchService().indexedEntityId) !== null && _a !== void 0 ? _a : userId) !== userId;
            if (reindexRequired) {
                yield this.searchService().indexCiphers(userId, yield this.getDecryptedCipherCache());
            }
        });
    }
    getAllDecryptedForGrouping(groupingId, folder = true) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.getAllDecrypted();
            return ciphers.filter((cipher) => {
                if (cipher.isDeleted) {
                    return false;
                }
                if (folder && cipher.folderId === groupingId) {
                    return true;
                }
                else if (!folder &&
                    cipher.collectionIds != null &&
                    cipher.collectionIds.indexOf(groupingId) > -1) {
                    return true;
                }
                return false;
            });
        });
    }
    getAllDecryptedForUrl(url, includeOtherTypes, defaultMatch = null) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if (url == null && includeOtherTypes == null) {
                return Promise.resolve([]);
            }
            const domain = Utils.getDomain(url);
            const eqDomainsPromise = domain == null
                ? Promise.resolve([])
                : (0,external_rxjs_namespaceObject.firstValueFrom)(this.settingsService.settings$).then((settings) => {
                    var _a;
                    let matches = [];
                    (_a = settings === null || settings === void 0 ? void 0 : settings.equivalentDomains) === null || _a === void 0 ? void 0 : _a.forEach((eqDomain) => {
                        if (eqDomain.length && eqDomain.indexOf(domain) >= 0) {
                            matches = matches.concat(eqDomain);
                        }
                    });
                    if (!matches.length) {
                        matches.push(domain);
                    }
                    return matches;
                });
            const result = yield Promise.all([eqDomainsPromise, this.getAllDecrypted()]);
            const matchingDomains = result[0];
            const ciphers = result[1];
            if (defaultMatch == null) {
                defaultMatch = yield this.stateService.getDefaultUriMatch();
                if (defaultMatch == null) {
                    defaultMatch = UriMatchType.Domain;
                }
            }
            return ciphers.filter((cipher) => {
                if (cipher.deletedDate != null) {
                    return false;
                }
                if (includeOtherTypes != null && includeOtherTypes.indexOf(cipher.type) > -1) {
                    return true;
                }
                if (url != null && cipher.type === CipherType.Login && cipher.login.uris != null) {
                    for (let i = 0; i < cipher.login.uris.length; i++) {
                        const u = cipher.login.uris[i];
                        if (u.uri == null) {
                            continue;
                        }
                        const match = u.match == null ? defaultMatch : u.match;
                        switch (match) {
                            case UriMatchType.Domain:
                                if (domain != null && u.domain != null && matchingDomains.indexOf(u.domain) > -1) {
                                    if (DomainMatchBlacklist.has(u.domain)) {
                                        const domainUrlHost = Utils.getHost(url);
                                        if (!DomainMatchBlacklist.get(u.domain).has(domainUrlHost)) {
                                            return true;
                                        }
                                    }
                                    else {
                                        return true;
                                    }
                                }
                                break;
                            case UriMatchType.Host: {
                                const urlHost = Utils.getHost(url);
                                if (urlHost != null && urlHost === Utils.getHost(u.uri)) {
                                    return true;
                                }
                                break;
                            }
                            case UriMatchType.Exact:
                                if (url === u.uri) {
                                    return true;
                                }
                                break;
                            case UriMatchType.StartsWith:
                                if (url.startsWith(u.uri)) {
                                    return true;
                                }
                                break;
                            case UriMatchType.RegularExpression:
                                try {
                                    const regex = new RegExp(u.uri, "i");
                                    if (regex.test(url)) {
                                        return true;
                                    }
                                }
                                catch (e) {
                                    this.logService.error(e);
                                }
                                break;
                            case UriMatchType.Never:
                            default:
                                break;
                        }
                    }
                }
                return false;
            });
        });
    }
    getAllFromApiForOrganization(organizationId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.apiService.getCiphersOrganization(organizationId);
            if ((response === null || response === void 0 ? void 0 : response.data) == null || response.data.length < 1) {
                return [];
            }
            const ciphers = response.data.map((cr) => new Cipher(new CipherData(cr)));
            const key = yield this.cryptoService.getOrgKey(organizationId);
            const decCiphers = yield this.encryptService.decryptItems(ciphers, key);
            decCiphers.sort(this.getLocaleSortingFunction());
            return decCiphers;
        });
    }
    getLastUsedForUrl(url, autofillOnPageLoad = false) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            return this.getCipherForUrl(url, true, false, autofillOnPageLoad);
        });
    }
    getLastLaunchedForUrl(url, autofillOnPageLoad = false) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            return this.getCipherForUrl(url, false, true, autofillOnPageLoad);
        });
    }
    getNextCipherForUrl(url) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            return this.getCipherForUrl(url, false, false, false);
        });
    }
    updateLastUsedIndexForUrl(url) {
        this.sortedCiphersCache.updateLastUsedIndex(url);
    }
    updateLastUsedDate(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            let ciphersLocalData = yield this.stateService.getLocalData();
            if (!ciphersLocalData) {
                ciphersLocalData = {};
            }
            if (ciphersLocalData[id]) {
                ciphersLocalData[id].lastUsedDate = new Date().getTime();
            }
            else {
                ciphersLocalData[id] = {
                    lastUsedDate: new Date().getTime(),
                };
            }
            yield this.stateService.setLocalData(ciphersLocalData);
            const decryptedCipherCache = yield this.stateService.getDecryptedCiphers();
            if (!decryptedCipherCache) {
                return;
            }
            for (let i = 0; i < decryptedCipherCache.length; i++) {
                const cached = decryptedCipherCache[i];
                if (cached.id === id) {
                    cached.localData = ciphersLocalData[id];
                    break;
                }
            }
            yield this.stateService.setDecryptedCiphers(decryptedCipherCache);
        });
    }
    updateLastLaunchedDate(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            let ciphersLocalData = yield this.stateService.getLocalData();
            if (!ciphersLocalData) {
                ciphersLocalData = {};
            }
            if (ciphersLocalData[id]) {
                ciphersLocalData[id].lastLaunched = new Date().getTime();
            }
            else {
                ciphersLocalData[id] = {
                    lastUsedDate: new Date().getTime(),
                };
            }
            yield this.stateService.setLocalData(ciphersLocalData);
            const decryptedCipherCache = yield this.stateService.getDecryptedCiphers();
            if (!decryptedCipherCache) {
                return;
            }
            for (let i = 0; i < decryptedCipherCache.length; i++) {
                const cached = decryptedCipherCache[i];
                if (cached.id === id) {
                    cached.localData = ciphersLocalData[id];
                    break;
                }
            }
            yield this.stateService.setDecryptedCiphers(decryptedCipherCache);
        });
    }
    saveNeverDomain(domain) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            if (domain == null) {
                return;
            }
            let domains = yield this.stateService.getNeverDomains();
            if (!domains) {
                domains = {};
            }
            domains[domain] = null;
            yield this.stateService.setNeverDomains(domains);
        });
    }
    createWithServer(cipher) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            let response;
            if (cipher.collectionIds != null) {
                const request = new CipherCreateRequest(cipher);
                response = yield this.apiService.postCipherCreate(request);
            }
            else {
                const request = new CipherRequest(cipher);
                response = yield this.apiService.postCipher(request);
            }
            cipher.id = response.id;
            const data = new CipherData(response, cipher.collectionIds);
            yield this.upsert(data);
        });
    }
    updateWithServer(cipher) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            let response;
            if (cipher.edit) {
                const request = new CipherRequest(cipher);
                response = yield this.apiService.putCipher(cipher.id, request);
            }
            else {
                const request = new CipherPartialRequest(cipher);
                response = yield this.apiService.putPartialCipher(cipher.id, request);
            }
            const data = new CipherData(response, cipher.collectionIds);
            yield this.upsert(data);
        });
    }
    shareWithServer(cipher, organizationId, collectionIds) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const attachmentPromises = [];
            if (cipher.attachments != null) {
                cipher.attachments.forEach((attachment) => {
                    if (attachment.key == null) {
                        attachmentPromises.push(this.shareAttachmentWithServer(attachment, cipher.id, organizationId));
                    }
                });
            }
            yield Promise.all(attachmentPromises);
            cipher.organizationId = organizationId;
            cipher.collectionIds = collectionIds;
            const encCipher = yield this.encrypt(cipher);
            const request = new CipherShareRequest(encCipher);
            const response = yield this.apiService.putShareCipher(cipher.id, request);
            const data = new CipherData(response, collectionIds);
            yield this.upsert(data);
        });
    }
    shareManyWithServer(ciphers, organizationId, collectionIds) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const promises = [];
            const encCiphers = [];
            for (const cipher of ciphers) {
                cipher.organizationId = organizationId;
                cipher.collectionIds = collectionIds;
                promises.push(this.encrypt(cipher).then((c) => {
                    encCiphers.push(c);
                }));
            }
            yield Promise.all(promises);
            const request = new CipherBulkShareRequest(encCiphers, collectionIds);
            try {
                yield this.apiService.putShareCiphers(request);
            }
            catch (e) {
                for (const cipher of ciphers) {
                    cipher.organizationId = null;
                    cipher.collectionIds = null;
                }
                throw e;
            }
            yield this.upsert(encCiphers.map((c) => c.toCipherData()));
        });
    }
    saveAttachmentWithServer(cipher, unencryptedFile, admin = false) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsArrayBuffer(unencryptedFile);
            reader.onload = (evt) => cipher_service_awaiter(this, void 0, void 0, function* () {
                try {
                    const cData = yield this.saveAttachmentRawWithServer(cipher, unencryptedFile.name, evt.target.result, admin);
                    resolve(cData);
                }
                catch (e) {
                    reject(e);
                }
            });
            reader.onerror = () => {
                reject("Error reading file.");
            };
        });
    }
    saveAttachmentRawWithServer(cipher, filename, data, admin = false) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const key = yield this.cryptoService.getOrgKey(cipher.organizationId);
            const encFileName = yield this.cryptoService.encrypt(filename, key);
            const dataEncKey = yield this.cryptoService.makeEncKey(key);
            const encData = yield this.cryptoService.encryptToBytes(data, dataEncKey[0]);
            const request = {
                key: dataEncKey[1].encryptedString,
                fileName: encFileName.encryptedString,
                fileSize: encData.buffer.byteLength,
                adminRequest: admin,
            };
            let response;
            try {
                const uploadDataResponse = yield this.apiService.postCipherAttachment(cipher.id, request);
                response = admin ? uploadDataResponse.cipherMiniResponse : uploadDataResponse.cipherResponse;
                yield this.fileUploadService.uploadCipherAttachment(admin, uploadDataResponse, encFileName, encData);
            }
            catch (e) {
                if ((e instanceof ErrorResponse && e.statusCode === 404) ||
                    e.statusCode === 405) {
                    response = yield this.legacyServerAttachmentFileUpload(admin, cipher.id, encFileName, encData, dataEncKey[1]);
                }
                else if (e instanceof ErrorResponse) {
                    throw new Error(e.getSingleMessage());
                }
                else {
                    throw e;
                }
            }
            const cData = new CipherData(response, cipher.collectionIds);
            if (!admin) {
                yield this.upsert(cData);
            }
            return new Cipher(cData);
        });
    }
    /**
     * @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
     * This method still exists for backward compatibility with old server versions.
     */
    legacyServerAttachmentFileUpload(admin, cipherId, encFileName, encData, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const fd = new FormData();
            try {
                const blob = new Blob([encData.buffer], { type: "application/octet-stream" });
                fd.append("key", key.encryptedString);
                fd.append("data", blob, encFileName.encryptedString);
            }
            catch (e) {
                if (Utils.isNode && !Utils.isBrowser) {
                    fd.append("key", key.encryptedString);
                    fd.append("data", Buffer.from(encData.buffer), {
                        filepath: encFileName.encryptedString,
                        contentType: "application/octet-stream",
                    });
                }
                else {
                    throw e;
                }
            }
            let response;
            try {
                if (admin) {
                    response = yield this.apiService.postCipherAttachmentAdminLegacy(cipherId, fd);
                }
                else {
                    response = yield this.apiService.postCipherAttachmentLegacy(cipherId, fd);
                }
            }
            catch (e) {
                throw new Error(e.getSingleMessage());
            }
            return response;
        });
    }
    saveCollectionsWithServer(cipher) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const request = new CipherCollectionsRequest(cipher.collectionIds);
            yield this.apiService.putCipherCollections(cipher.id, request);
            const data = cipher.toCipherData();
            yield this.upsert(data);
        });
    }
    upsert(cipher) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            let ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers == null) {
                ciphers = {};
            }
            if (cipher instanceof CipherData) {
                const c = cipher;
                ciphers[c.id] = c;
            }
            else {
                cipher.forEach((c) => {
                    ciphers[c.id] = c;
                });
            }
            yield this.replace(ciphers);
        });
    }
    replace(ciphers) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearDecryptedCiphersState();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    clear(userId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.clearEncryptedCiphersState(userId);
            yield this.clearCache(userId);
        });
    }
    moveManyWithServer(ids, folderId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.putMoveCiphers(new CipherBulkMoveRequest(ids, folderId));
            let ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers == null) {
                ciphers = {};
            }
            ids.forEach((id) => {
                // eslint-disable-next-line
                if (ciphers.hasOwnProperty(id)) {
                    ciphers[id].folderId = folderId;
                }
            });
            yield this.clearCache();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    delete(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers == null) {
                return;
            }
            if (typeof id === "string") {
                if (ciphers[id] == null) {
                    return;
                }
                delete ciphers[id];
            }
            else {
                id.forEach((i) => {
                    delete ciphers[i];
                });
            }
            yield this.clearCache();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    deleteWithServer(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.deleteCipher(id);
            yield this.delete(id);
        });
    }
    deleteManyWithServer(ids) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.deleteManyCiphers(new CipherBulkDeleteRequest(ids));
            yield this.delete(ids);
        });
    }
    deleteAttachment(id, attachmentId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.stateService.getEncryptedCiphers();
            // eslint-disable-next-line
            if (ciphers == null || !ciphers.hasOwnProperty(id) || ciphers[id].attachments == null) {
                return;
            }
            for (let i = 0; i < ciphers[id].attachments.length; i++) {
                if (ciphers[id].attachments[i].id === attachmentId) {
                    ciphers[id].attachments.splice(i, 1);
                }
            }
            yield this.clearCache();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    deleteAttachmentWithServer(id, attachmentId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            try {
                yield this.apiService.deleteCipherAttachment(id, attachmentId);
            }
            catch (e) {
                return Promise.reject(e.getSingleMessage());
            }
            yield this.deleteAttachment(id, attachmentId);
        });
    }
    sortCiphersByLastUsed(a, b) {
        const aLastUsed = a.localData && a.localData.lastUsedDate ? a.localData.lastUsedDate : null;
        const bLastUsed = b.localData && b.localData.lastUsedDate ? b.localData.lastUsedDate : null;
        const bothNotNull = aLastUsed != null && bLastUsed != null;
        if (bothNotNull && aLastUsed < bLastUsed) {
            return 1;
        }
        if (aLastUsed != null && bLastUsed == null) {
            return -1;
        }
        if (bothNotNull && aLastUsed > bLastUsed) {
            return -1;
        }
        if (bLastUsed != null && aLastUsed == null) {
            return 1;
        }
        return 0;
    }
    sortCiphersByLastUsedThenName(a, b) {
        const result = this.sortCiphersByLastUsed(a, b);
        if (result !== 0) {
            return result;
        }
        return this.getLocaleSortingFunction()(a, b);
    }
    getLocaleSortingFunction() {
        return (a, b) => {
            let aName = a.name;
            let bName = b.name;
            if (aName == null && bName != null) {
                return -1;
            }
            if (aName != null && bName == null) {
                return 1;
            }
            if (aName == null && bName == null) {
                return 0;
            }
            const result = this.i18nService.collator
                ? this.i18nService.collator.compare(aName, bName)
                : aName.localeCompare(bName);
            if (result !== 0 || a.type !== CipherType.Login || b.type !== CipherType.Login) {
                return result;
            }
            if (a.login.username != null) {
                aName += a.login.username;
            }
            if (b.login.username != null) {
                bName += b.login.username;
            }
            return this.i18nService.collator
                ? this.i18nService.collator.compare(aName, bName)
                : aName.localeCompare(bName);
        };
    }
    softDelete(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers == null) {
                return;
            }
            const setDeletedDate = (cipherId) => {
                if (ciphers[cipherId] == null) {
                    return;
                }
                ciphers[cipherId].deletedDate = new Date().toISOString();
            };
            if (typeof id === "string") {
                setDeletedDate(id);
            }
            else {
                id.forEach(setDeletedDate);
            }
            yield this.clearCache();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    softDeleteWithServer(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.putDeleteCipher(id);
            yield this.softDelete(id);
        });
    }
    softDeleteManyWithServer(ids) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.apiService.putDeleteManyCiphers(new CipherBulkDeleteRequest(ids));
            yield this.softDelete(ids);
        });
    }
    restore(cipher) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers == null) {
                return;
            }
            const clearDeletedDate = (c) => {
                if (ciphers[c.id] == null) {
                    return;
                }
                ciphers[c.id].deletedDate = null;
                ciphers[c.id].revisionDate = c.revisionDate;
            };
            if (cipher.constructor.name === Array.name) {
                cipher.forEach(clearDeletedDate);
            }
            else {
                clearDeletedDate(cipher);
            }
            yield this.clearCache();
            yield this.stateService.setEncryptedCiphers(ciphers);
        });
    }
    restoreWithServer(id) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.apiService.putRestoreCipher(id);
            yield this.restore({ id: id, revisionDate: response.revisionDate });
        });
    }
    restoreManyWithServer(ids) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.apiService.putRestoreManyCiphers(new CipherBulkRestoreRequest(ids));
            const restores = [];
            for (const cipher of response.data) {
                restores.push({ id: cipher.id, revisionDate: cipher.revisionDate });
            }
            yield this.restore(restores);
        });
    }
    // Helpers
    shareAttachmentWithServer(attachmentView, cipherId, organizationId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const attachmentResponse = yield this.apiService.nativeFetch(new Request(attachmentView.url, { cache: "no-store" }));
            if (attachmentResponse.status !== 200) {
                throw Error("Failed to download attachment: " + attachmentResponse.status.toString());
            }
            const encBuf = yield EncArrayBuffer.fromResponse(attachmentResponse);
            const decBuf = yield this.cryptoService.decryptFromBytes(encBuf, null);
            const key = yield this.cryptoService.getOrgKey(organizationId);
            const encFileName = yield this.cryptoService.encrypt(attachmentView.fileName, key);
            const dataEncKey = yield this.cryptoService.makeEncKey(key);
            const encData = yield this.cryptoService.encryptToBytes(decBuf, dataEncKey[0]);
            const fd = new FormData();
            try {
                const blob = new Blob([encData.buffer], { type: "application/octet-stream" });
                fd.append("key", dataEncKey[1].encryptedString);
                fd.append("data", blob, encFileName.encryptedString);
            }
            catch (e) {
                if (Utils.isNode && !Utils.isBrowser) {
                    fd.append("key", dataEncKey[1].encryptedString);
                    fd.append("data", Buffer.from(encData.buffer), {
                        filepath: encFileName.encryptedString,
                        contentType: "application/octet-stream",
                    });
                }
                else {
                    throw e;
                }
            }
            try {
                yield this.apiService.postShareCipherAttachment(cipherId, attachmentView.id, fd, organizationId);
            }
            catch (e) {
                throw new Error(e.getSingleMessage());
            }
        });
    }
    encryptObjProperty(model, obj, map, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const promises = [];
            const self = this;
            for (const prop in map) {
                // eslint-disable-next-line
                if (!map.hasOwnProperty(prop)) {
                    continue;
                }
                (function (theProp, theObj) {
                    const p = Promise.resolve()
                        .then(() => {
                        const modelProp = model[map[theProp] || theProp];
                        if (modelProp && modelProp !== "") {
                            return self.cryptoService.encrypt(modelProp, key);
                        }
                        return null;
                    })
                        .then((val) => {
                        theObj[theProp] = val;
                    });
                    promises.push(p);
                })(prop, obj);
            }
            yield Promise.all(promises);
        });
    }
    encryptCipherData(cipher, model, key) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            switch (cipher.type) {
                case CipherType.Login:
                    cipher.login = new Login();
                    cipher.login.passwordRevisionDate = model.login.passwordRevisionDate;
                    cipher.login.autofillOnPageLoad = model.login.autofillOnPageLoad;
                    yield this.encryptObjProperty(model.login, cipher.login, {
                        username: null,
                        password: null,
                        totp: null,
                    }, key);
                    if (model.login.uris != null) {
                        cipher.login.uris = [];
                        for (let i = 0; i < model.login.uris.length; i++) {
                            const loginUri = new LoginUri();
                            loginUri.match = model.login.uris[i].match;
                            yield this.encryptObjProperty(model.login.uris[i], loginUri, {
                                uri: null,
                            }, key);
                            cipher.login.uris.push(loginUri);
                        }
                    }
                    return;
                case CipherType.SecureNote:
                    cipher.secureNote = new SecureNote();
                    cipher.secureNote.type = model.secureNote.type;
                    return;
                case CipherType.Card:
                    cipher.card = new Card();
                    yield this.encryptObjProperty(model.card, cipher.card, {
                        cardholderName: null,
                        brand: null,
                        number: null,
                        expMonth: null,
                        expYear: null,
                        code: null,
                    }, key);
                    return;
                case CipherType.Identity:
                    cipher.identity = new Identity();
                    yield this.encryptObjProperty(model.identity, cipher.identity, {
                        title: null,
                        firstName: null,
                        middleName: null,
                        lastName: null,
                        address1: null,
                        address2: null,
                        address3: null,
                        city: null,
                        state: null,
                        postalCode: null,
                        country: null,
                        company: null,
                        email: null,
                        phone: null,
                        ssn: null,
                        username: null,
                        passportNumber: null,
                        licenseNumber: null,
                    }, key);
                    return;
                default:
                    throw new Error("Unknown cipher type.");
            }
        });
    }
    getCipherForUrl(url, lastUsed, lastLaunched, autofillOnPageLoad) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            const cacheKey = autofillOnPageLoad ? "autofillOnPageLoad-" + url : url;
            if (!this.sortedCiphersCache.isCached(cacheKey)) {
                let ciphers = yield this.getAllDecryptedForUrl(url);
                if (!ciphers) {
                    return null;
                }
                if (autofillOnPageLoad) {
                    const autofillOnPageLoadDefault = yield this.stateService.getAutoFillOnPageLoadDefault();
                    ciphers = ciphers.filter((cipher) => cipher.login.autofillOnPageLoad ||
                        (cipher.login.autofillOnPageLoad == null && autofillOnPageLoadDefault !== false));
                    if (ciphers.length === 0) {
                        return null;
                    }
                }
                this.sortedCiphersCache.addCiphers(cacheKey, ciphers);
            }
            if (lastLaunched) {
                return this.sortedCiphersCache.getLastLaunched(cacheKey);
            }
            else if (lastUsed) {
                return this.sortedCiphersCache.getLastUsed(cacheKey);
            }
            else {
                return this.sortedCiphersCache.getNext(cacheKey);
            }
        });
    }
    clearEncryptedCiphersState(userId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setEncryptedCiphers(null, { userId: userId });
        });
    }
    clearDecryptedCiphersState(userId) {
        return cipher_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setDecryptedCiphers(null, { userId: userId });
            this.clearSortedCiphers();
        });
    }
    clearSortedCiphers() {
        this.sortedCiphersCache.clear();
    }
}
cipher_service_decorate([
    sequentialize(() => "getAllDecrypted"),
    cipher_service_metadata("design:type", Function),
    cipher_service_metadata("design:paramtypes", []),
    cipher_service_metadata("design:returntype", Promise)
], CipherService.prototype, "getAllDecrypted", null);

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/folder.response.ts

class FolderResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.name = this.getResponseProperty("Name");
        this.revisionDate = this.getResponseProperty("RevisionDate");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/services/folder/folder-api.service.ts
var folder_api_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class FolderApiService {
    constructor(folderService, apiService) {
        this.folderService = folderService;
        this.apiService = apiService;
    }
    save(folder) {
        return folder_api_service_awaiter(this, void 0, void 0, function* () {
            const request = new FolderRequest(folder);
            let response;
            if (folder.id == null) {
                response = yield this.postFolder(request);
                folder.id = response.id;
            }
            else {
                response = yield this.putFolder(folder.id, request);
            }
            const data = new FolderData(response);
            yield this.folderService.upsert(data);
        });
    }
    delete(id) {
        return folder_api_service_awaiter(this, void 0, void 0, function* () {
            yield this.deleteFolder(id);
            yield this.folderService.delete(id);
        });
    }
    get(id) {
        return folder_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("GET", "/folders/" + id, null, true, true);
            return new FolderResponse(r);
        });
    }
    postFolder(request) {
        return folder_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("POST", "/folders", request, true, true);
            return new FolderResponse(r);
        });
    }
    putFolder(id, request) {
        return folder_api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.apiService.send("PUT", "/folders/" + id, request, true, true);
            return new FolderResponse(r);
        });
    }
    deleteFolder(id) {
        return this.apiService.send("DELETE", "/folders/" + id, null, true, false);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/services/folder/folder.service.ts
var folder_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class FolderService {
    constructor(cryptoService, i18nService, cipherService, stateService) {
        this.cryptoService = cryptoService;
        this.i18nService = i18nService;
        this.cipherService = cipherService;
        this.stateService = stateService;
        this._folders = new external_rxjs_namespaceObject.BehaviorSubject([]);
        this._folderViews = new external_rxjs_namespaceObject.BehaviorSubject([]);
        this.folders$ = this._folders.asObservable();
        this.folderViews$ = this._folderViews.asObservable();
        this.stateService.activeAccountUnlocked$
            .pipe((0,external_rxjs_namespaceObject.concatMap)((unlocked) => folder_service_awaiter(this, void 0, void 0, function* () {
            if (Utils.global.bitwardenContainerService == null) {
                return;
            }
            if (!unlocked) {
                this._folders.next([]);
                this._folderViews.next([]);
                return;
            }
            const data = yield this.stateService.getEncryptedFolders();
            yield this.updateObservables(data);
        })))
            .subscribe();
    }
    clearCache() {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            this._folderViews.next([]);
        });
    }
    // TODO: This should be moved to EncryptService or something
    encrypt(model, key) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const folder = new Folder();
            folder.id = model.id;
            folder.name = yield this.cryptoService.encrypt(model.name, key);
            return folder;
        });
    }
    get(id) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const folders = this._folders.getValue();
            return folders.find((folder) => folder.id === id);
        });
    }
    getAllFromState() {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const folders = yield this.stateService.getEncryptedFolders();
            const response = [];
            for (const id in folders) {
                // eslint-disable-next-line
                if (folders.hasOwnProperty(id)) {
                    response.push(new Folder(folders[id]));
                }
            }
            return response;
        });
    }
    /**
     * @deprecated For the CLI only
     * @param id id of the folder
     */
    getFromState(id) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const foldersMap = yield this.stateService.getEncryptedFolders();
            const folder = foldersMap[id];
            if (folder == null) {
                return null;
            }
            return new Folder(folder);
        });
    }
    /**
     * @deprecated Only use in CLI!
     */
    getAllDecryptedFromState() {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const data = yield this.stateService.getEncryptedFolders();
            const folders = Object.values(data || {}).map((f) => new Folder(f));
            return this.decryptFolders(folders);
        });
    }
    upsert(folder) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            let folders = yield this.stateService.getEncryptedFolders();
            if (folders == null) {
                folders = {};
            }
            if (folder instanceof FolderData) {
                const f = folder;
                folders[f.id] = f;
            }
            else {
                folder.forEach((f) => {
                    folders[f.id] = f;
                });
            }
            yield this.updateObservables(folders);
            yield this.stateService.setEncryptedFolders(folders);
        });
    }
    replace(folders) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            yield this.updateObservables(folders);
            yield this.stateService.setEncryptedFolders(folders);
        });
    }
    clear(userId) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            if (userId == null || userId == (yield this.stateService.getUserId())) {
                this._folders.next([]);
                this._folderViews.next([]);
            }
            yield this.stateService.setEncryptedFolders(null, { userId: userId });
        });
    }
    delete(id) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const folders = yield this.stateService.getEncryptedFolders();
            if (folders == null) {
                return;
            }
            if (typeof id === "string") {
                if (folders[id] == null) {
                    return;
                }
                delete folders[id];
            }
            else {
                id.forEach((i) => {
                    delete folders[i];
                });
            }
            yield this.updateObservables(folders);
            yield this.stateService.setEncryptedFolders(folders);
            // Items in a deleted folder are re-assigned to "No Folder"
            const ciphers = yield this.stateService.getEncryptedCiphers();
            if (ciphers != null) {
                const updates = [];
                for (const cId in ciphers) {
                    if (ciphers[cId].folderId === id) {
                        ciphers[cId].folderId = null;
                        updates.push(ciphers[cId]);
                    }
                }
                if (updates.length > 0) {
                    this.cipherService.upsert(updates);
                }
            }
        });
    }
    updateObservables(foldersMap) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const folders = Object.values(foldersMap || {}).map((f) => new Folder(f));
            this._folders.next(folders);
            if (yield this.cryptoService.hasKey()) {
                this._folderViews.next(yield this.decryptFolders(folders));
            }
        });
    }
    decryptFolders(folders) {
        return folder_service_awaiter(this, void 0, void 0, function* () {
            const decryptFolderPromises = folders.map((f) => f.decrypt());
            const decryptedFolders = yield Promise.all(decryptFolderPromises);
            decryptedFolders.sort(Utils.getSortFunction(this.i18nService, "name"));
            const noneFolder = new FolderView();
            noneFolder.name = this.i18nService.t("noneFolder");
            decryptedFolders.push(noneFolder);
            return decryptedFolders;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/services/sync/sync-notifier.service.ts

/**
 * This class should most likely have 0 dependencies because it will hopefully
 * be rolled into SyncService once upon a time.
 */
class SyncNotifierService {
    constructor() {
        this._sync = new external_rxjs_namespaceObject.Subject();
        this.sync$ = this._sync.asObservable();
    }
    next(event) {
        this._sync.next(event);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/data/organization.data.ts
class OrganizationData {
    constructor(response) {
        this.id = response.id;
        this.name = response.name;
        this.status = response.status;
        this.type = response.type;
        this.enabled = response.enabled;
        this.usePolicies = response.usePolicies;
        this.useGroups = response.useGroups;
        this.useDirectory = response.useDirectory;
        this.useEvents = response.useEvents;
        this.useTotp = response.useTotp;
        this.use2fa = response.use2fa;
        this.useApi = response.useApi;
        this.useSso = response.useSso;
        this.useKeyConnector = response.useKeyConnector;
        this.useScim = response.useScim;
        this.useCustomPermissions = response.useCustomPermissions;
        this.useResetPassword = response.useResetPassword;
        this.useSecretsManager = response.useSecretsManager;
        this.selfHost = response.selfHost;
        this.usersGetPremium = response.usersGetPremium;
        this.seats = response.seats;
        this.maxCollections = response.maxCollections;
        this.maxStorageGb = response.maxStorageGb;
        this.ssoBound = response.ssoBound;
        this.identifier = response.identifier;
        this.permissions = response.permissions;
        this.resetPasswordEnrolled = response.resetPasswordEnrolled;
        this.userId = response.userId;
        this.hasPublicAndPrivateKeys = response.hasPublicAndPrivateKeys;
        this.providerId = response.providerId;
        this.providerName = response.providerName;
        this.familySponsorshipFriendlyName = response.familySponsorshipFriendlyName;
        this.familySponsorshipAvailable = response.familySponsorshipAvailable;
        this.planProductType = response.planProductType;
        this.keyConnectorEnabled = response.keyConnectorEnabled;
        this.keyConnectorUrl = response.keyConnectorUrl;
        this.familySponsorshipLastSyncDate = response.familySponsorshipLastSyncDate;
        this.familySponsorshipValidUntil = response.familySponsorshipValidUntil;
        this.familySponsorshipToDelete = response.familySponsorshipToDelete;
        this.accessSecretsManager = response.accessSecretsManager;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/services/sync/sync.service.ts
var sync_service_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var sync_service_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var sync_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};








class SyncService {
    constructor(apiService, settingsService, folderService, cipherService, cryptoService, collectionService, messagingService, policyService, sendService, logService, keyConnectorService, stateService, providerService, folderApiService, organizationService, logoutCallback) {
        this.apiService = apiService;
        this.settingsService = settingsService;
        this.folderService = folderService;
        this.cipherService = cipherService;
        this.cryptoService = cryptoService;
        this.collectionService = collectionService;
        this.messagingService = messagingService;
        this.policyService = policyService;
        this.sendService = sendService;
        this.logService = logService;
        this.keyConnectorService = keyConnectorService;
        this.stateService = stateService;
        this.providerService = providerService;
        this.folderApiService = folderApiService;
        this.organizationService = organizationService;
        this.logoutCallback = logoutCallback;
        this.syncInProgress = false;
    }
    getLastSync() {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            if ((yield this.stateService.getUserId()) == null) {
                return null;
            }
            const lastSync = yield this.stateService.getLastSync();
            if (lastSync) {
                return new Date(lastSync);
            }
            return null;
        });
    }
    setLastSync(date, userId) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            yield this.stateService.setLastSync(date.toJSON(), { userId: userId });
        });
    }
    fullSync(forceSync, allowThrowOnError = false) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            const isAuthenticated = yield this.stateService.getIsAuthenticated();
            if (!isAuthenticated) {
                return this.syncCompleted(false);
            }
            const now = new Date();
            let needsSync = false;
            try {
                needsSync = yield this.needsSyncing(forceSync);
            }
            catch (e) {
                if (allowThrowOnError) {
                    throw e;
                }
            }
            if (!needsSync) {
                yield this.setLastSync(now);
                return this.syncCompleted(false);
            }
            try {
                yield this.apiService.refreshIdentityToken();
                const response = yield this.apiService.getSync();
                yield this.syncProfile(response.profile);
                yield this.syncFolders(response.folders);
                yield this.syncCollections(response.collections);
                yield this.syncCiphers(response.ciphers);
                yield this.syncSends(response.sends);
                yield this.syncSettings(response.domains);
                yield this.syncPolicies(response.policies);
                yield this.setLastSync(now);
                return this.syncCompleted(true);
            }
            catch (e) {
                if (allowThrowOnError) {
                    throw e;
                }
                else {
                    return this.syncCompleted(false);
                }
            }
        });
    }
    syncUpsertFolder(notification, isEdit) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                try {
                    const localFolder = yield this.folderService.get(notification.id);
                    if ((!isEdit && localFolder == null) ||
                        (isEdit && localFolder != null && localFolder.revisionDate < notification.revisionDate)) {
                        const remoteFolder = yield this.folderApiService.get(notification.id);
                        if (remoteFolder != null) {
                            yield this.folderService.upsert(new FolderData(remoteFolder));
                            this.messagingService.send("syncedUpsertedFolder", { folderId: notification.id });
                            return this.syncCompleted(true);
                        }
                    }
                }
                catch (e) {
                    this.logService.error(e);
                }
            }
            return this.syncCompleted(false);
        });
    }
    syncDeleteFolder(notification) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                yield this.folderService.delete(notification.id);
                this.messagingService.send("syncedDeletedFolder", { folderId: notification.id });
                this.syncCompleted(true);
                return true;
            }
            return this.syncCompleted(false);
        });
    }
    syncUpsertCipher(notification, isEdit) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                try {
                    let shouldUpdate = true;
                    const localCipher = yield this.cipherService.get(notification.id);
                    if (localCipher != null && localCipher.revisionDate >= notification.revisionDate) {
                        shouldUpdate = false;
                    }
                    let checkCollections = false;
                    if (shouldUpdate) {
                        if (isEdit) {
                            shouldUpdate = localCipher != null;
                            checkCollections = true;
                        }
                        else {
                            if (notification.collectionIds == null || notification.organizationId == null) {
                                shouldUpdate = localCipher == null;
                            }
                            else {
                                shouldUpdate = false;
                                checkCollections = true;
                            }
                        }
                    }
                    if (!shouldUpdate &&
                        checkCollections &&
                        notification.organizationId != null &&
                        notification.collectionIds != null &&
                        notification.collectionIds.length > 0) {
                        const collections = yield this.collectionService.getAll();
                        if (collections != null) {
                            for (let i = 0; i < collections.length; i++) {
                                if (notification.collectionIds.indexOf(collections[i].id) > -1) {
                                    shouldUpdate = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (shouldUpdate) {
                        const remoteCipher = yield this.apiService.getFullCipherDetails(notification.id);
                        if (remoteCipher != null) {
                            yield this.cipherService.upsert(new CipherData(remoteCipher));
                            this.messagingService.send("syncedUpsertedCipher", { cipherId: notification.id });
                            return this.syncCompleted(true);
                        }
                    }
                }
                catch (e) {
                    if (e != null && e.statusCode === 404 && isEdit) {
                        yield this.cipherService.delete(notification.id);
                        this.messagingService.send("syncedDeletedCipher", { cipherId: notification.id });
                        return this.syncCompleted(true);
                    }
                }
            }
            return this.syncCompleted(false);
        });
    }
    syncDeleteCipher(notification) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                yield this.cipherService.delete(notification.id);
                this.messagingService.send("syncedDeletedCipher", { cipherId: notification.id });
                return this.syncCompleted(true);
            }
            return this.syncCompleted(false);
        });
    }
    syncUpsertSend(notification, isEdit) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                try {
                    const localSend = yield this.sendService.get(notification.id);
                    if ((!isEdit && localSend == null) ||
                        (isEdit && localSend != null && localSend.revisionDate < notification.revisionDate)) {
                        const remoteSend = yield this.apiService.getSend(notification.id);
                        if (remoteSend != null) {
                            yield this.sendService.upsert(new SendData(remoteSend));
                            this.messagingService.send("syncedUpsertedSend", { sendId: notification.id });
                            return this.syncCompleted(true);
                        }
                    }
                }
                catch (e) {
                    this.logService.error(e);
                }
            }
            return this.syncCompleted(false);
        });
    }
    syncDeleteSend(notification) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            this.syncStarted();
            if (yield this.stateService.getIsAuthenticated()) {
                yield this.sendService.delete(notification.id);
                this.messagingService.send("syncedDeletedSend", { sendId: notification.id });
                this.syncCompleted(true);
                return true;
            }
            return this.syncCompleted(false);
        });
    }
    // Helpers
    syncStarted() {
        this.syncInProgress = true;
        this.messagingService.send("syncStarted");
    }
    syncCompleted(successfully) {
        this.syncInProgress = false;
        this.messagingService.send("syncCompleted", { successfully: successfully });
        return successfully;
    }
    needsSyncing(forceSync) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            if (forceSync) {
                return true;
            }
            const lastSync = yield this.getLastSync();
            if (lastSync == null || lastSync.getTime() === 0) {
                return true;
            }
            const response = yield this.apiService.getAccountRevisionDate();
            if (new Date(response) <= lastSync) {
                return false;
            }
            return true;
        });
    }
    syncProfile(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const stamp = yield this.stateService.getSecurityStamp();
            if (stamp != null && stamp !== response.securityStamp) {
                if (this.logoutCallback != null) {
                    yield this.logoutCallback(true);
                }
                throw new Error("Stamp has changed");
            }
            yield this.cryptoService.setEncKey(response.key);
            yield this.cryptoService.setEncPrivateKey(response.privateKey);
            yield this.cryptoService.setProviderKeys(response.providers);
            yield this.cryptoService.setOrgKeys(response.organizations, response.providerOrganizations);
            yield this.stateService.setAvatarColor(response.avatarColor);
            yield this.stateService.setSecurityStamp(response.securityStamp);
            yield this.stateService.setEmailVerified(response.emailVerified);
            yield this.stateService.setHasPremiumPersonally(response.premiumPersonally);
            yield this.stateService.setHasPremiumFromOrganization(response.premiumFromOrganization);
            yield this.stateService.setForcePasswordReset(response.forcePasswordReset);
            yield this.keyConnectorService.setUsesKeyConnector(response.usesKeyConnector);
            const organizations = {};
            response.organizations.forEach((o) => {
                organizations[o.id] = new OrganizationData(o);
            });
            const providers = {};
            response.providers.forEach((p) => {
                providers[p.id] = new ProviderData(p);
            });
            response.providerOrganizations.forEach((o) => {
                if (organizations[o.id] == null) {
                    organizations[o.id] = new OrganizationData(o);
                    organizations[o.id].isProviderUser = true;
                }
            });
            yield this.organizationService.replace(organizations);
            yield this.providerService.save(providers);
            if (yield this.keyConnectorService.userNeedsMigration()) {
                yield this.keyConnectorService.setConvertAccountRequired(true);
                this.messagingService.send("convertAccountToKeyConnector");
            }
            else {
                this.keyConnectorService.removeConvertAccountRequired();
            }
        });
    }
    syncFolders(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const folders = {};
            response.forEach((f) => {
                folders[f.id] = new FolderData(f);
            });
            return yield this.folderService.replace(folders);
        });
    }
    syncCollections(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const collections = {};
            response.forEach((c) => {
                collections[c.id] = new CollectionData(c);
            });
            return yield this.collectionService.replace(collections);
        });
    }
    syncCiphers(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const ciphers = {};
            response.forEach((c) => {
                ciphers[c.id] = new CipherData(c);
            });
            return yield this.cipherService.replace(ciphers);
        });
    }
    syncSends(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const sends = {};
            response.forEach((s) => {
                sends[s.id] = new SendData(s);
            });
            return yield this.sendService.replace(sends);
        });
    }
    syncSettings(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            let eqDomains = [];
            if (response != null && response.equivalentDomains != null) {
                eqDomains = eqDomains.concat(response.equivalentDomains);
            }
            if (response != null && response.globalEquivalentDomains != null) {
                response.globalEquivalentDomains.forEach((global) => {
                    if (global.domains.length > 0) {
                        eqDomains.push(global.domains);
                    }
                });
            }
            return this.settingsService.setEquivalentDomains(eqDomains);
        });
    }
    syncPolicies(response) {
        return sync_service_awaiter(this, void 0, void 0, function* () {
            const policies = {};
            if (response != null) {
                response.forEach((p) => {
                    policies[p.id] = new PolicyData(p);
                });
            }
            return yield this.policyService.replace(policies);
        });
    }
}
sync_service_decorate([
    sequentialize(() => "fullSync"),
    sync_service_metadata("design:type", Function),
    sync_service_metadata("design:paramtypes", [Boolean, Object]),
    sync_service_metadata("design:returntype", Promise)
], SyncService.prototype, "fullSync", null);

;// CONCATENATED MODULE: external "crypto"
const external_crypto_namespaceObject = require("crypto");
;// CONCATENATED MODULE: external "argon2"
const external_argon2_namespaceObject = require("argon2");
;// CONCATENATED MODULE: external "node-forge"
const external_node_forge_namespaceObject = require("node-forge");
;// CONCATENATED MODULE: ../../libs/common/src/models/domain/decrypt-parameters.ts
class DecryptParameters {
}

;// CONCATENATED MODULE: ../../libs/node/src/services/node-crypto-function.service.ts
var node_crypto_function_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class NodeCryptoFunctionService {
    pbkdf2(password, salt, algorithm, iterations) {
        const len = algorithm === "sha256" ? 32 : 64;
        const nodePassword = this.toNodeValue(password);
        const nodeSalt = this.toNodeValue(salt);
        return new Promise((resolve, reject) => {
            external_crypto_namespaceObject.pbkdf2(nodePassword, nodeSalt, iterations, len, algorithm, (error, key) => {
                if (error != null) {
                    reject(error);
                }
                else {
                    resolve(this.toArrayBuffer(key));
                }
            });
        });
    }
    argon2(password, salt, iterations, memory, parallelism) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            const nodePassword = this.toNodeValue(password);
            const nodeSalt = this.toNodeBuffer(this.toArrayBuffer(salt));
            const hash = yield external_argon2_namespaceObject.hash(nodePassword, {
                salt: nodeSalt,
                raw: true,
                hashLength: 32,
                timeCost: iterations,
                memoryCost: memory,
                parallelism: parallelism,
                type: external_argon2_namespaceObject.argon2id,
            });
            return this.toArrayBuffer(hash);
        });
    }
    // ref: https://tools.ietf.org/html/rfc5869
    hkdf(ikm, salt, info, outputByteSize, algorithm) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            const saltBuf = this.toArrayBuffer(salt);
            const prk = yield this.hmac(ikm, saltBuf, algorithm);
            return this.hkdfExpand(prk, info, outputByteSize, algorithm);
        });
    }
    // ref: https://tools.ietf.org/html/rfc5869
    hkdfExpand(prk, info, outputByteSize, algorithm) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            const hashLen = algorithm === "sha256" ? 32 : 64;
            if (outputByteSize > 255 * hashLen) {
                throw new Error("outputByteSize is too large.");
            }
            const prkArr = new Uint8Array(prk);
            if (prkArr.length < hashLen) {
                throw new Error("prk is too small.");
            }
            const infoBuf = this.toArrayBuffer(info);
            const infoArr = new Uint8Array(infoBuf);
            let runningOkmLength = 0;
            let previousT = new Uint8Array(0);
            const n = Math.ceil(outputByteSize / hashLen);
            const okm = new Uint8Array(n * hashLen);
            for (let i = 0; i < n; i++) {
                const t = new Uint8Array(previousT.length + infoArr.length + 1);
                t.set(previousT);
                t.set(infoArr, previousT.length);
                t.set([i + 1], t.length - 1);
                previousT = new Uint8Array(yield this.hmac(t.buffer, prk, algorithm));
                okm.set(previousT, runningOkmLength);
                runningOkmLength += previousT.length;
                if (runningOkmLength >= outputByteSize) {
                    break;
                }
            }
            return okm.slice(0, outputByteSize).buffer;
        });
    }
    hash(value, algorithm) {
        const nodeValue = this.toNodeValue(value);
        const hash = external_crypto_namespaceObject.createHash(algorithm);
        hash.update(nodeValue);
        return Promise.resolve(this.toArrayBuffer(hash.digest()));
    }
    hmac(value, key, algorithm) {
        const nodeValue = this.toNodeBuffer(value);
        const nodeKey = this.toNodeBuffer(key);
        const hmac = external_crypto_namespaceObject.createHmac(algorithm, nodeKey);
        hmac.update(nodeValue);
        return Promise.resolve(this.toArrayBuffer(hmac.digest()));
    }
    compare(a, b) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            const key = yield this.randomBytes(32);
            const mac1 = yield this.hmac(a, key, "sha256");
            const mac2 = yield this.hmac(b, key, "sha256");
            if (mac1.byteLength !== mac2.byteLength) {
                return false;
            }
            const arr1 = new Uint8Array(mac1);
            const arr2 = new Uint8Array(mac2);
            for (let i = 0; i < arr2.length; i++) {
                if (arr1[i] !== arr2[i]) {
                    return false;
                }
            }
            return true;
        });
    }
    hmacFast(value, key, algorithm) {
        return this.hmac(value, key, algorithm);
    }
    compareFast(a, b) {
        return this.compare(a, b);
    }
    aesEncrypt(data, iv, key) {
        const nodeData = this.toNodeBuffer(data);
        const nodeIv = this.toNodeBuffer(iv);
        const nodeKey = this.toNodeBuffer(key);
        const cipher = external_crypto_namespaceObject.createCipheriv("aes-256-cbc", nodeKey, nodeIv);
        const encBuf = Buffer.concat([cipher.update(nodeData), cipher.final()]);
        return Promise.resolve(this.toArrayBuffer(encBuf));
    }
    aesDecryptFastParameters(data, iv, mac, key) {
        const p = new DecryptParameters();
        p.encKey = key.encKey;
        p.data = Utils.fromB64ToArray(data).buffer;
        p.iv = Utils.fromB64ToArray(iv).buffer;
        const macData = new Uint8Array(p.iv.byteLength + p.data.byteLength);
        macData.set(new Uint8Array(p.iv), 0);
        macData.set(new Uint8Array(p.data), p.iv.byteLength);
        p.macData = macData.buffer;
        if (key.macKey != null) {
            p.macKey = key.macKey;
        }
        if (mac != null) {
            p.mac = Utils.fromB64ToArray(mac).buffer;
        }
        return p;
    }
    aesDecryptFast(parameters) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            const decBuf = yield this.aesDecrypt(parameters.data, parameters.iv, parameters.encKey);
            return Utils.fromBufferToUtf8(decBuf);
        });
    }
    aesDecrypt(data, iv, key) {
        const nodeData = this.toNodeBuffer(data);
        const nodeIv = this.toNodeBuffer(iv);
        const nodeKey = this.toNodeBuffer(key);
        const decipher = external_crypto_namespaceObject.createDecipheriv("aes-256-cbc", nodeKey, nodeIv);
        const decBuf = Buffer.concat([decipher.update(nodeData), decipher.final()]);
        return Promise.resolve(this.toArrayBuffer(decBuf));
    }
    rsaEncrypt(data, publicKey, algorithm) {
        if (algorithm === "sha256") {
            throw new Error("Node crypto does not support RSA-OAEP SHA-256");
        }
        const pem = this.toPemPublicKey(publicKey);
        const decipher = external_crypto_namespaceObject.publicEncrypt(pem, this.toNodeBuffer(data));
        return Promise.resolve(this.toArrayBuffer(decipher));
    }
    rsaDecrypt(data, privateKey, algorithm) {
        if (algorithm === "sha256") {
            throw new Error("Node crypto does not support RSA-OAEP SHA-256");
        }
        const pem = this.toPemPrivateKey(privateKey);
        const decipher = external_crypto_namespaceObject.privateDecrypt(pem, this.toNodeBuffer(data));
        return Promise.resolve(this.toArrayBuffer(decipher));
    }
    rsaExtractPublicKey(privateKey) {
        const privateKeyByteString = Utils.fromBufferToByteString(privateKey);
        const privateKeyAsn1 = external_node_forge_namespaceObject.asn1.fromDer(privateKeyByteString);
        const forgePrivateKey = external_node_forge_namespaceObject.pki.privateKeyFromAsn1(privateKeyAsn1);
        const forgePublicKey = external_node_forge_namespaceObject.pki.setRsaPublicKey(forgePrivateKey.n, forgePrivateKey.e);
        const publicKeyAsn1 = external_node_forge_namespaceObject.pki.publicKeyToAsn1(forgePublicKey);
        const publicKeyByteString = external_node_forge_namespaceObject.asn1.toDer(publicKeyAsn1).data;
        const publicKeyArray = Utils.fromByteStringToArray(publicKeyByteString);
        return Promise.resolve(publicKeyArray.buffer);
    }
    rsaGenerateKeyPair(length) {
        return node_crypto_function_service_awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                external_node_forge_namespaceObject.pki.rsa.generateKeyPair({
                    bits: length,
                    workers: -1,
                    e: 0x10001, // 65537
                }, (error, keyPair) => {
                    if (error != null) {
                        reject(error);
                        return;
                    }
                    const publicKeyAsn1 = external_node_forge_namespaceObject.pki.publicKeyToAsn1(keyPair.publicKey);
                    const publicKeyByteString = external_node_forge_namespaceObject.asn1.toDer(publicKeyAsn1).getBytes();
                    const publicKey = Utils.fromByteStringToArray(publicKeyByteString);
                    const privateKeyAsn1 = external_node_forge_namespaceObject.pki.privateKeyToAsn1(keyPair.privateKey);
                    const privateKeyPkcs8 = external_node_forge_namespaceObject.pki.wrapRsaPrivateKey(privateKeyAsn1);
                    const privateKeyByteString = external_node_forge_namespaceObject.asn1.toDer(privateKeyPkcs8).getBytes();
                    const privateKey = Utils.fromByteStringToArray(privateKeyByteString);
                    resolve([publicKey.buffer, privateKey.buffer]);
                });
            });
        });
    }
    randomBytes(length) {
        return new Promise((resolve, reject) => {
            external_crypto_namespaceObject.randomBytes(length, (error, bytes) => {
                if (error != null) {
                    reject(error);
                }
                else {
                    resolve(this.toArrayBuffer(bytes));
                }
            });
        });
    }
    toNodeValue(value) {
        let nodeValue;
        if (typeof value === "string") {
            nodeValue = value;
        }
        else {
            nodeValue = this.toNodeBuffer(value);
        }
        return nodeValue;
    }
    toNodeBuffer(value) {
        return Buffer.from(new Uint8Array(value));
    }
    toArrayBuffer(value) {
        let buf;
        if (typeof value === "string") {
            buf = Utils.fromUtf8ToArray(value).buffer;
        }
        else {
            buf = new Uint8Array(value).buffer;
        }
        return buf;
    }
    toPemPrivateKey(key) {
        const byteString = Utils.fromBufferToByteString(key);
        const asn1 = external_node_forge_namespaceObject.asn1.fromDer(byteString);
        const privateKey = external_node_forge_namespaceObject.pki.privateKeyFromAsn1(asn1);
        const rsaPrivateKey = external_node_forge_namespaceObject.pki.privateKeyToAsn1(privateKey);
        const privateKeyInfo = external_node_forge_namespaceObject.pki.wrapRsaPrivateKey(rsaPrivateKey);
        return external_node_forge_namespaceObject.pki.privateKeyInfoToPem(privateKeyInfo);
    }
    toPemPublicKey(key) {
        const byteString = Utils.fromBufferToByteString(key);
        const asn1 = external_node_forge_namespaceObject.asn1.fromDer(byteString);
        const publicKey = external_node_forge_namespaceObject.pki.publicKeyFromAsn1(asn1);
        return external_node_forge_namespaceObject.pki.publicKeyToPem(publicKey);
    }
}

;// CONCATENATED MODULE: external "chalk"
const external_chalk_namespaceObject = require("chalk");
;// CONCATENATED MODULE: ./src/models/response.ts
class Response {
    static error(error, data) {
        const res = new Response();
        res.success = false;
        if (typeof error === "string") {
            res.message = error;
        }
        else {
            res.message =
                error.message != null
                    ? error.message
                    : error.toString() === "[object Object]"
                        ? JSON.stringify(error)
                        : error.toString();
        }
        res.data = data;
        return res;
    }
    static notFound() {
        return Response.error("Not found.");
    }
    static badRequest(message) {
        return Response.error(message);
    }
    static multipleResults(ids) {
        let msg = "More than one result was found. Try getting a specific object by `id` instead. " +
            "The following objects were found:";
        ids.forEach((id) => {
            msg += "\n" + id;
        });
        return Response.error(msg, ids);
    }
    static success(data) {
        const res = new Response();
        res.success = true;
        res.data = data;
        return res;
    }
}

;// CONCATENATED MODULE: ./src/models/response/message.response.ts
class MessageResponse {
    constructor(title, message) {
        this.noColor = false;
        this.object = "message";
        this.title = title;
        this.message = message;
    }
}

;// CONCATENATED MODULE: ./src/commands/completion.command.ts
var completion_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



const validShells = ["zsh"];
class CompletionCommand {
    run(options) {
        return completion_command_awaiter(this, void 0, void 0, function* () {
            const shell = options.shell;
            if (!shell) {
                return Response.badRequest("`shell` option was not provided.");
            }
            if (!validShells.includes(shell)) {
                return Response.badRequest("Unsupported shell.");
            }
            let content = "";
            if (shell === "zsh") {
                content = this.zshCompletion("bw", external_commander_namespaceObject).render();
            }
            const res = new MessageResponse(content, null);
            return Response.success(res);
        });
    }
    zshCompletion(rootName, rootCommand) {
        return {
            render: () => {
                return [
                    `#compdef _${rootName} ${rootName}`,
                    "",
                    this.renderCommandBlock(rootName, rootCommand),
                ].join("\n");
            },
        };
    }
    renderCommandBlock(name, command) {
        const { commands = [], options = [] } = command;
        const hasOptions = options.length > 0;
        const hasCommands = commands.length > 0;
        const args = options
            .map(({ long, short, description }) => {
            const aliases = [short, long].filter(Boolean);
            const opts = aliases.join(",");
            const desc = `[${description.replace(`'`, `'"'"'`)}]`;
            return aliases.length > 1
                ? `'(${aliases.join(" ")})'{${opts}}'${desc}'`
                : `'${opts}${desc}'`;
        })
            .concat(`'(-h --help)'{-h,--help}'[output usage information]'`, hasCommands ? '"1: :->cmnds"' : null, '"*::arg:->args"')
            .filter(Boolean);
        const commandBlockFunctionParts = [];
        if (hasCommands) {
            commandBlockFunctionParts.push("local -a commands");
        }
        if (hasOptions) {
            commandBlockFunctionParts.push(`_arguments -C \\\n    ${args.join(` \\\n    `)}`);
        }
        if (hasCommands) {
            commandBlockFunctionParts.push(`case $state in
    cmnds)
      commands=(
        ${commands
                .map(({ _name, _description }) => `"${_name}:${_description}"`)
                .join("\n        ")}
      )
      _describe "command" commands
      ;;
  esac

  case "$words[1]" in
    ${commands
                .map(({ _name }) => [`${_name})`, `_${name}_${_name}`, ";;"].join("\n      "))
                .join("\n    ")}
  esac`);
        }
        const commandBlocParts = [
            `function _${name} {\n  ${commandBlockFunctionParts.join("\n\n  ")}\n}`,
        ];
        if (hasCommands) {
            commandBlocParts.push(commands.map((c) => this.renderCommandBlock(`${name}_${c._name}`, c)).join("\n\n"));
        }
        return commandBlocParts.join("\n\n");
    }
}

;// CONCATENATED MODULE: ./src/models/response/string.response.ts
class StringResponse {
    constructor(data) {
        this.object = "string";
        this.data = data;
    }
}

;// CONCATENATED MODULE: ./src/commands/config.command.ts
var config_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class ConfigCommand {
    constructor(environmentService) {
        this.environmentService = environmentService;
    }
    run(setting, value, options) {
        return config_command_awaiter(this, void 0, void 0, function* () {
            setting = setting.toLowerCase();
            switch (setting) {
                case "server":
                    return yield this.getOrSetServer(value, options);
                default:
                    return Response.badRequest("Unknown setting.");
            }
        });
    }
    getOrSetServer(url, options) {
        return config_command_awaiter(this, void 0, void 0, function* () {
            if ((url == null || url.trim() === "") &&
                !options.webVault &&
                !options.api &&
                !options.identity &&
                !options.icons &&
                !options.notifications &&
                !options.events) {
                const stringRes = new StringResponse(this.environmentService.hasBaseUrl()
                    ? this.environmentService.getUrls().base
                    : "https://bitwarden.com");
                return Response.success(stringRes);
            }
            url = url === "null" || url === "bitwarden.com" || url === "https://bitwarden.com" ? null : url;
            yield this.environmentService.setUrls({
                base: url,
                webVault: options.webVault || null,
                api: options.api || null,
                identity: options.identity || null,
                icons: options.icons || null,
                notifications: options.notifications || null,
                events: options.events || null,
                keyConnector: options.keyConnector || null,
            });
            const res = new MessageResponse("Saved setting `config`.", null);
            return Response.success(res);
        });
    }
}

;// CONCATENATED MODULE: external "inquirer"
const external_inquirer_namespaceObject = require("inquirer");
;// CONCATENATED MODULE: external "jszip"
const external_jszip_namespaceObject = require("jszip");
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");
;// CONCATENATED MODULE: ../../libs/common/src/misc/nodeUtils.ts



class NodeUtils {
    static mkdirpSync(targetDir, mode = "700", relative = false, relativeDir = null) {
        const initialDir = external_path_namespaceObject.isAbsolute(targetDir) ? external_path_namespaceObject.sep : "";
        const baseDir = relative ? (relativeDir != null ? relativeDir : __dirname) : ".";
        targetDir.split(external_path_namespaceObject.sep).reduce((parentDir, childDir) => {
            const dir = external_path_namespaceObject.resolve(baseDir, parentDir, childDir);
            if (!external_fs_namespaceObject.existsSync(dir)) {
                external_fs_namespaceObject.mkdirSync(dir, mode);
            }
            return dir;
        }, initialDir);
    }
    static readFirstLine(fileName) {
        return new Promise((resolve, reject) => {
            const readStream = external_fs_namespaceObject.createReadStream(fileName, { encoding: "utf8" });
            const readInterface = external_readline_namespaceObject.createInterface(readStream);
            readInterface
                .on("line", (line) => {
                readStream.close();
                resolve(line);
            })
                .on("error", (err) => reject(err));
        });
    }
    // https://stackoverflow.com/a/31394257
    static bufferToArrayBuffer(buf) {
        return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
    }
}

;// CONCATENATED MODULE: ./src/utils.ts
var utils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};








class CliUtils {
    static writeLn(s, finalLine = false, error = false) {
        const stream = error ? process.stderr : process.stdout;
        if (finalLine && (process.platform === "win32" || !stream.isTTY)) {
            stream.write(s);
        }
        else {
            stream.write(s + "\n");
        }
    }
    static readFile(input) {
        return new Promise((resolve, reject) => {
            let p = null;
            if (input != null && input !== "") {
                const osInput = external_path_namespaceObject.join(input);
                if (osInput.indexOf(external_path_namespaceObject.sep) === -1) {
                    p = external_path_namespaceObject.join(process.cwd(), osInput);
                }
                else {
                    p = osInput;
                }
            }
            else {
                reject("You must specify a file path.");
            }
            external_fs_namespaceObject.readFile(p, "utf8", (err, data) => {
                if (err != null) {
                    reject(err.message);
                }
                resolve(data);
            });
        });
    }
    static extract1PuxContent(input) {
        return new Promise((resolve, reject) => {
            let p = null;
            if (input != null && input !== "") {
                const osInput = external_path_namespaceObject.join(input);
                if (osInput.indexOf(external_path_namespaceObject.sep) === -1) {
                    p = external_path_namespaceObject.join(process.cwd(), osInput);
                }
                else {
                    p = osInput;
                }
            }
            else {
                reject("You must specify a file path.");
            }
            external_fs_namespaceObject.readFile(p, function (err, data) {
                if (err) {
                    reject(err);
                }
                external_jszip_namespaceObject.loadAsync(data).then((zip) => {
                    resolve(zip.file("export.data").async("string"));
                }, (reason) => {
                    reject(reason);
                });
            });
        });
    }
    /**
     * Save the given data to a file and determine the target file if necessary.
     * If output is non-empty, it is used as target filename. Otherwise the target filename is
     * built from the current working directory and the given defaultFileName.
     *
     * @param data to be written to the file.
     * @param output file to write to or empty to choose automatically.
     * @param defaultFileName to use when no explicit output filename is given.
     * @return the chosen output file.
     */
    static saveFile(data, output, defaultFileName) {
        let p = null;
        let mkdir = false;
        if (output != null && output !== "") {
            const osOutput = external_path_namespaceObject.join(output);
            if (osOutput.indexOf(external_path_namespaceObject.sep) === -1) {
                p = external_path_namespaceObject.join(process.cwd(), osOutput);
            }
            else {
                mkdir = true;
                if (osOutput.endsWith(external_path_namespaceObject.sep)) {
                    p = external_path_namespaceObject.join(osOutput, defaultFileName);
                }
                else {
                    p = osOutput;
                }
            }
        }
        else {
            p = external_path_namespaceObject.join(process.cwd(), defaultFileName);
        }
        p = external_path_namespaceObject.resolve(p);
        if (mkdir) {
            const dir = p.substring(0, p.lastIndexOf(external_path_namespaceObject.sep));
            if (!external_fs_namespaceObject.existsSync(dir)) {
                NodeUtils.mkdirpSync(dir, "700");
            }
        }
        return new Promise((resolve, reject) => {
            external_fs_namespaceObject.writeFile(p, data, { encoding: "utf8", mode: 0o600 }, (err) => {
                if (err != null) {
                    reject("Cannot save file to " + p);
                }
                resolve(p);
            });
        });
    }
    /**
     * Process the given data and write it to a file if possible. If the user requested RAW output and
     * no output name is given, the file is directly written to stdout. The resulting Response contains
     * an otherwise empty message then to prevent writing other information to stdout.
     *
     * If an output is given or no RAW output is requested, the rules from [saveFile] apply.
     *
     * @param data to be written to the file or stdout.
     * @param output file to write to or empty to choose automatically.
     * @param defaultFileName to use when no explicit output filename is given.
     * @return an empty [Response] if written to stdout or a [Response] with the chosen output file otherwise.
     */
    static saveResultToFile(data, output, defaultFileName) {
        return utils_awaiter(this, void 0, void 0, function* () {
            if ((output == null || output === "") && process.env.BW_RAW === "true") {
                // No output is given and the user expects raw output. Since the command result is about content,
                // we directly return the command result to stdout (and suppress further messages).
                process.stdout.write(data);
                return Response.success();
            }
            const filePath = yield this.saveFile(data, output, defaultFileName);
            const res = new MessageResponse("Saved " + filePath, null);
            res.raw = filePath;
            return Response.success(res);
        });
    }
    static readStdin() {
        return new Promise((resolve, reject) => {
            let input = "";
            if (process.stdin.isTTY) {
                resolve(input);
                return;
            }
            process.stdin.setEncoding("utf8");
            process.stdin.on("readable", () => {
                // eslint-disable-next-line
                while (true) {
                    const chunk = process.stdin.read();
                    if (chunk == null) {
                        break;
                    }
                    input += chunk;
                }
            });
            process.stdin.on("end", () => {
                resolve(input);
            });
        });
    }
    static searchFolders(folders, search) {
        search = search.toLowerCase();
        return folders.filter((f) => {
            if (f.name != null && f.name.toLowerCase().indexOf(search) > -1) {
                return true;
            }
            return false;
        });
    }
    static searchCollections(collections, search) {
        search = search.toLowerCase();
        return collections.filter((c) => {
            if (c.name != null && c.name.toLowerCase().indexOf(search) > -1) {
                return true;
            }
            return false;
        });
    }
    static searchOrganizations(organizations, search) {
        search = search.toLowerCase();
        return organizations.filter((o) => {
            if (o.name != null && o.name.toLowerCase().indexOf(search) > -1) {
                return true;
            }
            return false;
        });
    }
    /**
     * Gets a password from all available sources. In order of priority these are:
     *   * passwordfile
     *   * passwordenv
     *   * user interaction
     *
     * Returns password string if successful, Response if not.
     */
    static getPassword(password, options, logService) {
        return utils_awaiter(this, void 0, void 0, function* () {
            if (Utils.isNullOrEmpty(password)) {
                if (options === null || options === void 0 ? void 0 : options.passwordFile) {
                    password = yield NodeUtils.readFirstLine(options.passwordFile);
                }
                else if (options === null || options === void 0 ? void 0 : options.passwordEnv) {
                    if (process.env[options.passwordEnv]) {
                        password = process.env[options.passwordEnv];
                    }
                    else if (logService) {
                        logService.warning(`Warning: Provided passwordenv ${options.passwordEnv} is not set`);
                    }
                }
            }
            if (Utils.isNullOrEmpty(password)) {
                if (process.env.BW_NOINTERACTION !== "true") {
                    const answer = yield external_inquirer_namespaceObject.createPromptModule({
                        output: process.stderr,
                    })({
                        type: "password",
                        name: "password",
                        message: "Master password:",
                    });
                    password = answer.password;
                }
                else {
                    return Response.badRequest("Master password is required. Try again in interactive mode or provide a password file or environment variable.");
                }
            }
            return password;
        });
    }
    static convertBooleanOption(optionValue) {
        return optionValue || optionValue === "" ? true : false;
    }
}

;// CONCATENATED MODULE: ./src/commands/encode.command.ts
var encode_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class EncodeCommand {
    run() {
        return encode_command_awaiter(this, void 0, void 0, function* () {
            if (process.stdin.isTTY) {
                return Response.badRequest("No stdin was piped in.");
            }
            const input = yield CliUtils.readStdin();
            const b64 = Buffer.from(input, "utf8").toString("base64");
            const res = new StringResponse(b64);
            return Response.success(res);
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/generate.command.ts
var generate_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class GenerateCommand {
    constructor(passwordGenerationService, stateService) {
        this.passwordGenerationService = passwordGenerationService;
        this.stateService = stateService;
    }
    run(cmdOptions) {
        return generate_command_awaiter(this, void 0, void 0, function* () {
            const normalizedOptions = new Options(cmdOptions);
            const options = {
                uppercase: normalizedOptions.uppercase,
                lowercase: normalizedOptions.lowercase,
                number: normalizedOptions.number,
                special: normalizedOptions.special,
                length: normalizedOptions.length,
                type: normalizedOptions.type,
                wordSeparator: normalizedOptions.separator,
                numWords: normalizedOptions.words,
                capitalize: normalizedOptions.capitalize,
                includeNumber: normalizedOptions.includeNumber,
            };
            const enforcedOptions = (yield this.stateService.getIsAuthenticated())
                ? (yield this.passwordGenerationService.enforcePasswordGeneratorPoliciesOnOptions(options))[0]
                : options;
            const password = yield this.passwordGenerationService.generatePassword(enforcedOptions);
            const res = new StringResponse(password);
            return Response.success(res);
        });
    }
}
class Options {
    constructor(passedOptions) {
        this.uppercase = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.uppercase);
        this.lowercase = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.lowercase);
        this.number = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.number);
        this.special = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.special);
        this.capitalize = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.capitalize);
        this.includeNumber = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.includeNumber);
        this.length = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.length) != null ? parseInt(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.length, null) : 14;
        this.type = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.passphrase) ? "passphrase" : "password";
        this.separator = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.separator) == null ? "-" : passedOptions.separator + "";
        this.words = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.words) != null ? parseInt(passedOptions.words, null) : 3;
        if (!this.uppercase && !this.lowercase && !this.special && !this.number) {
            this.lowercase = true;
            this.uppercase = true;
            this.number = true;
        }
        if (this.length < 5) {
            this.length = 5;
        }
        if (this.words < 3) {
            this.words = 3;
        }
        if (this.separator === "space") {
            this.separator = " ";
        }
        else if (this.separator != null && this.separator.length > 1) {
            this.separator = this.separator[0];
        }
    }
}

;// CONCATENATED MODULE: ./src/commands/lock.command.ts
var lock_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class LockCommand {
    constructor(vaultTimeoutService) {
        this.vaultTimeoutService = vaultTimeoutService;
    }
    run() {
        return lock_command_awaiter(this, void 0, void 0, function* () {
            yield this.vaultTimeoutService.lock();
            process.env.BW_SESSION = null;
            const res = new MessageResponse("Your vault is locked.", null);
            return Response.success(res);
        });
    }
}

;// CONCATENATED MODULE: external "http"
const external_http_namespaceObject = require("http");
;// CONCATENATED MODULE: ../../libs/common/src/models/domain/log-in-credentials.ts

class PasswordLogInCredentials {
    constructor(email, masterPassword, captchaToken, twoFactor) {
        this.email = email;
        this.masterPassword = masterPassword;
        this.captchaToken = captchaToken;
        this.twoFactor = twoFactor;
        this.type = authenticationType_AuthenticationType.Password;
    }
}
class SsoLogInCredentials {
    constructor(code, codeVerifier, redirectUrl, orgId, twoFactor) {
        this.code = code;
        this.codeVerifier = codeVerifier;
        this.redirectUrl = redirectUrl;
        this.orgId = orgId;
        this.twoFactor = twoFactor;
        this.type = authenticationType_AuthenticationType.Sso;
    }
}
class UserApiLogInCredentials {
    constructor(clientId, clientSecret) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.type = authenticationType_AuthenticationType.UserApi;
    }
}
class PasswordlessLogInCredentials {
    constructor(email, accessCode, authRequestId, decKey, localPasswordHash, twoFactor) {
        this.email = email;
        this.accessCode = accessCode;
        this.authRequestId = authRequestId;
        this.decKey = decKey;
        this.localPasswordHash = localPasswordHash;
        this.twoFactor = twoFactor;
        this.type = AuthenticationType.Passwordless;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/two-factor-email.request.ts

class TwoFactorEmailRequest extends SecretVerificationRequest {
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/organization-user/requests/organization-user-reset-password.request.ts
class OrganizationUserResetPasswordRequest {
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/update-temp-password.request.ts

class UpdateTempPasswordRequest extends OrganizationUserResetPasswordRequest {
}

;// CONCATENATED MODULE: ./src/commands/login.command.ts
var login_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};













class LoginCommand {
    constructor(authService, apiService, cryptoFunctionService, environmentService, passwordGenerationService, platformUtilsService, stateService, cryptoService, policyService, twoFactorService, syncService, keyConnectorService, logoutCallback) {
        this.authService = authService;
        this.apiService = apiService;
        this.cryptoFunctionService = cryptoFunctionService;
        this.environmentService = environmentService;
        this.passwordGenerationService = passwordGenerationService;
        this.platformUtilsService = platformUtilsService;
        this.stateService = stateService;
        this.cryptoService = cryptoService;
        this.policyService = policyService;
        this.twoFactorService = twoFactorService;
        this.syncService = syncService;
        this.keyConnectorService = keyConnectorService;
        this.logoutCallback = logoutCallback;
        this.ssoRedirectUri = null;
    }
    run(email, password, options) {
        return login_command_awaiter(this, void 0, void 0, function* () {
            this.options = options;
            this.email = email;
            this.canInteract = process.env.BW_NOINTERACTION !== "true";
            let ssoCodeVerifier = null;
            let ssoCode = null;
            let orgIdentifier = null;
            let clientId = null;
            let clientSecret = null;
            let selectedProvider = null;
            if (options.apikey != null) {
                const apiIdentifiers = yield this.apiIdentifiers();
                clientId = apiIdentifiers.clientId;
                clientSecret = apiIdentifiers.clientSecret;
            }
            else if (options.sso != null && this.canInteract) {
                const passwordOptions = {
                    type: "password",
                    length: 64,
                    uppercase: true,
                    lowercase: true,
                    numbers: true,
                    special: false,
                };
                const state = yield this.passwordGenerationService.generatePassword(passwordOptions);
                ssoCodeVerifier = yield this.passwordGenerationService.generatePassword(passwordOptions);
                const codeVerifierHash = yield this.cryptoFunctionService.hash(ssoCodeVerifier, "sha256");
                const codeChallenge = Utils.fromBufferToUrlB64(codeVerifierHash);
                try {
                    const ssoParams = yield this.openSsoPrompt(codeChallenge, state);
                    ssoCode = ssoParams.ssoCode;
                    orgIdentifier = ssoParams.orgIdentifier;
                }
                catch (_a) {
                    return Response.badRequest("Something went wrong. Try again.");
                }
            }
            else {
                if ((email == null || email === "") && this.canInteract) {
                    const answer = yield external_inquirer_namespaceObject.createPromptModule({
                        output: process.stderr,
                    })({
                        type: "input",
                        name: "email",
                        message: "Email address:",
                    });
                    email = answer.email;
                }
                if (email == null || email.trim() === "") {
                    return Response.badRequest("Email address is required.");
                }
                if (email.indexOf("@") === -1) {
                    return Response.badRequest("Email address is invalid.");
                }
                this.email = email;
                if (password == null || password === "") {
                    if (options.passwordfile) {
                        password = yield NodeUtils.readFirstLine(options.passwordfile);
                    }
                    else if (options.passwordenv && process.env[options.passwordenv]) {
                        password = process.env[options.passwordenv];
                    }
                    else if (this.canInteract) {
                        const answer = yield external_inquirer_namespaceObject.createPromptModule({
                            output: process.stderr,
                        })({
                            type: "password",
                            name: "password",
                            message: "Master password:",
                        });
                        password = answer.password;
                    }
                }
                if (password == null || password === "") {
                    return Response.badRequest("Master password is required.");
                }
            }
            let twoFactorToken = options.code;
            let twoFactorMethod = null;
            try {
                if (options.method != null) {
                    twoFactorMethod = parseInt(options.method, null);
                }
            }
            catch (e) {
                return Response.error("Invalid two-step login method.");
            }
            const twoFactor = twoFactorToken == null
                ? null
                : new TokenTwoFactorRequest(twoFactorMethod, twoFactorToken, false);
            try {
                yield this.validatedParams();
                let response = null;
                if (clientId != null && clientSecret != null) {
                    if (!clientId.startsWith("user")) {
                        return Response.error("Invalid API Key; Organization API Key currently not supported");
                    }
                    response = yield this.authService.logIn(new UserApiLogInCredentials(clientId, clientSecret));
                }
                else if (ssoCode != null && ssoCodeVerifier != null) {
                    response = yield this.authService.logIn(new SsoLogInCredentials(ssoCode, ssoCodeVerifier, this.ssoRedirectUri, orgIdentifier, twoFactor));
                }
                else {
                    response = yield this.authService.logIn(new PasswordLogInCredentials(email, password, null, twoFactor));
                }
                if (response.captchaSiteKey) {
                    const credentials = new PasswordLogInCredentials(email, password);
                    const handledResponse = yield this.handleCaptchaRequired(twoFactor, credentials);
                    // Error Response
                    if (handledResponse instanceof Response) {
                        return handledResponse;
                    }
                    else {
                        response = handledResponse;
                    }
                }
                if (response.requiresTwoFactor) {
                    const twoFactorProviders = this.twoFactorService.getSupportedProviders(null);
                    if (twoFactorProviders.length === 0) {
                        return Response.badRequest("No providers available for this client.");
                    }
                    if (twoFactorMethod != null) {
                        try {
                            selectedProvider = twoFactorProviders.filter((p) => p.type === twoFactorMethod)[0];
                        }
                        catch (e) {
                            return Response.error("Invalid two-step login method.");
                        }
                    }
                    if (selectedProvider == null) {
                        if (twoFactorProviders.length === 1) {
                            selectedProvider = twoFactorProviders[0];
                        }
                        else if (this.canInteract) {
                            const twoFactorOptions = twoFactorProviders.map((p) => p.name);
                            twoFactorOptions.push(new external_inquirer_namespaceObject.Separator());
                            twoFactorOptions.push("Cancel");
                            const answer = yield external_inquirer_namespaceObject.createPromptModule({
                                output: process.stderr,
                            })({
                                type: "list",
                                name: "method",
                                message: "Two-step login method:",
                                choices: twoFactorOptions,
                            });
                            const i = twoFactorOptions.indexOf(answer.method);
                            if (i === twoFactorOptions.length - 1) {
                                return Response.error("Login failed.");
                            }
                            selectedProvider = twoFactorProviders[i];
                        }
                        if (selectedProvider == null) {
                            return Response.error("Login failed. No provider selected.");
                        }
                    }
                    if (twoFactorToken == null &&
                        response.twoFactorProviders.size > 1 &&
                        selectedProvider.type === TwoFactorProviderType.Email) {
                        const emailReq = new TwoFactorEmailRequest();
                        emailReq.email = this.authService.email;
                        emailReq.masterPasswordHash = this.authService.masterPasswordHash;
                        yield this.apiService.postTwoFactorEmail(emailReq);
                    }
                    if (twoFactorToken == null) {
                        if (this.canInteract) {
                            const answer = yield external_inquirer_namespaceObject.createPromptModule({
                                output: process.stderr,
                            })({
                                type: "input",
                                name: "token",
                                message: "Two-step login code:",
                            });
                            twoFactorToken = answer.token;
                        }
                        if (twoFactorToken == null || twoFactorToken === "") {
                            return Response.badRequest("Code is required.");
                        }
                    }
                    response = yield this.authService.logInTwoFactor(new TokenTwoFactorRequest(selectedProvider.type, twoFactorToken), null);
                }
                if (response.captchaSiteKey) {
                    const twoFactorRequest = new TokenTwoFactorRequest(selectedProvider.type, twoFactorToken);
                    const handledResponse = yield this.handleCaptchaRequired(twoFactorRequest);
                    // Error Response
                    if (handledResponse instanceof Response) {
                        return handledResponse;
                    }
                    else {
                        response = handledResponse;
                    }
                }
                if (response.requiresTwoFactor) {
                    return Response.error("Login failed.");
                }
                if (response.resetMasterPassword) {
                    return Response.error("In order to log in with SSO from the CLI, you must first log in" +
                        " through the web vault to set your master password.");
                }
                // Handle Updating Temp Password if NOT using an API Key for authentication
                if (response.forcePasswordReset && clientId == null && clientSecret == null) {
                    return yield this.updateTempPassword();
                }
                return yield this.handleSuccessResponse();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    validatedParams() {
        return login_command_awaiter(this, void 0, void 0, function* () {
            const key = yield this.cryptoFunctionService.randomBytes(64);
            process.env.BW_SESSION = Utils.fromBufferToB64(key);
        });
    }
    handleSuccessResponse() {
        return login_command_awaiter(this, void 0, void 0, function* () {
            yield this.syncService.fullSync(true);
            const usesKeyConnector = yield this.keyConnectorService.getUsesKeyConnector();
            if ((this.options.sso != null || this.options.apikey != null) &&
                this.canInteract &&
                !usesKeyConnector) {
                const res = new MessageResponse("You are logged in!", "\n" + "To unlock your vault, use the `unlock` command. ex:\n" + "$ bw unlock");
                return Response.success(res);
            }
            const res = new MessageResponse("You are logged in!", "\n" +
                "To unlock your vault, set your session key to the `BW_SESSION` environment variable. ex:\n" +
                '$ export BW_SESSION="' +
                process.env.BW_SESSION +
                '"\n' +
                '> $env:BW_SESSION="' +
                process.env.BW_SESSION +
                '"\n\n' +
                "You can also pass the session key to any command with the `--session` option. ex:\n" +
                "$ bw list items --session " +
                process.env.BW_SESSION);
            res.raw = process.env.BW_SESSION;
            return Response.success(res);
        });
    }
    updateTempPassword(error) {
        return login_command_awaiter(this, void 0, void 0, function* () {
            // If no interaction available, alert user to use web vault
            if (!this.canInteract) {
                yield this.logoutCallback();
                this.authService.logOut(() => {
                    /* Do nothing */
                });
                return Response.error(new MessageResponse("An organization administrator recently changed your master password. In order to access the vault, you must update your master password now via the web vault. You have been logged out.", null));
            }
            if (this.email == null || this.email === "undefined") {
                this.email = yield this.stateService.getEmail();
            }
            // Get New Master Password
            const baseMessage = "An organization administrator recently changed your master password. In order to access the vault, you must update your master password now.\n" +
                "Master password: ";
            const firstMessage = error != null ? error + baseMessage : baseMessage;
            const mp = yield external_inquirer_namespaceObject.createPromptModule({ output: process.stderr })({
                type: "password",
                name: "password",
                message: firstMessage,
            });
            const masterPassword = mp.password;
            // Master Password Validation
            if (masterPassword == null || masterPassword === "") {
                return this.updateTempPassword("Master password is required.\n");
            }
            if (masterPassword.length < 8) {
                return this.updateTempPassword("Master password must be at least 8 characters long.\n");
            }
            // Strength & Policy Validation
            const strengthResult = this.passwordGenerationService.passwordStrength(masterPassword, this.getPasswordStrengthUserInput());
            // Get New Master Password Re-type
            const reTypeMessage = "Re-type New Master password (Strength: " + strengthResult.score + ")";
            const retype = yield external_inquirer_namespaceObject.createPromptModule({ output: process.stderr })({
                type: "password",
                name: "password",
                message: reTypeMessage,
            });
            const masterPasswordRetype = retype.password;
            // Re-type Validation
            if (masterPassword !== masterPasswordRetype) {
                return this.updateTempPassword("Master password confirmation does not match.\n");
            }
            // Get Hint (optional)
            const hint = yield external_inquirer_namespaceObject.createPromptModule({ output: process.stderr })({
                type: "input",
                name: "input",
                message: "Master Password Hint (optional):",
            });
            const masterPasswordHint = hint.input;
            // Retrieve details for key generation
            const enforcedPolicyOptions = yield (0,external_rxjs_namespaceObject.firstValueFrom)(this.policyService.masterPasswordPolicyOptions$());
            const kdf = yield this.stateService.getKdfType();
            const kdfConfig = yield this.stateService.getKdfConfig();
            if (enforcedPolicyOptions != null &&
                !this.policyService.evaluateMasterPassword(strengthResult.score, masterPassword, enforcedPolicyOptions)) {
                return this.updateTempPassword("Your new master password does not meet the policy requirements.\n");
            }
            try {
                // Create new key and hash new password
                const newKey = yield this.cryptoService.makeKey(masterPassword, this.email.trim().toLowerCase(), kdf, kdfConfig);
                const newPasswordHash = yield this.cryptoService.hashPassword(masterPassword, newKey);
                // Grab user's current enc key
                const userEncKey = yield this.cryptoService.getEncKey();
                // Create new encKey for the User
                const newEncKey = yield this.cryptoService.remakeEncKey(newKey, userEncKey);
                // Create request
                const request = new UpdateTempPasswordRequest();
                request.key = newEncKey[1].encryptedString;
                request.newMasterPasswordHash = newPasswordHash;
                request.masterPasswordHint = masterPasswordHint;
                // Update user's password
                yield this.apiService.putUpdateTempPassword(request);
                return this.handleSuccessResponse();
            }
            catch (e) {
                yield this.logoutCallback();
                this.authService.logOut(() => {
                    /* Do nothing */
                });
                return Response.error(e);
            }
        });
    }
    handleCaptchaRequired(twoFactorRequest, credentials = null) {
        return login_command_awaiter(this, void 0, void 0, function* () {
            const badCaptcha = Response.badRequest("Your authentication request has been flagged and will require user interaction to proceed.\n" +
                "Please use your API key to validate this request and ensure BW_CLIENTSECRET is correct, if set.\n" +
                "(https://bitwarden.com/help/cli-auth-challenges)");
            try {
                const captchaClientSecret = yield this.apiClientSecret(true);
                if (Utils.isNullOrWhitespace(captchaClientSecret)) {
                    return badCaptcha;
                }
                let authResultResponse = null;
                if (credentials != null) {
                    credentials.captchaToken = captchaClientSecret;
                    credentials.twoFactor = twoFactorRequest;
                    authResultResponse = yield this.authService.logIn(credentials);
                }
                else {
                    authResultResponse = yield this.authService.logInTwoFactor(twoFactorRequest, captchaClientSecret);
                }
                return authResultResponse;
            }
            catch (e) {
                if (e instanceof ErrorResponse ||
                    (e.constructor.name === ErrorResponse.name &&
                        e.message.includes("Captcha is invalid"))) {
                    return badCaptcha;
                }
                else {
                    return Response.error(e);
                }
            }
        });
    }
    getPasswordStrengthUserInput() {
        let userInput = [];
        const atPosition = this.email.indexOf("@");
        if (atPosition > -1) {
            userInput = userInput.concat(this.email
                .substr(0, atPosition)
                .trim()
                .toLowerCase()
                .split(/[^A-Za-z0-9]/));
        }
        return userInput;
    }
    apiClientId() {
        return login_command_awaiter(this, void 0, void 0, function* () {
            let clientId = null;
            const storedClientId = process.env.BW_CLIENTID;
            if (storedClientId == null) {
                if (this.canInteract) {
                    const answer = yield external_inquirer_namespaceObject.createPromptModule({
                        output: process.stderr,
                    })({
                        type: "input",
                        name: "clientId",
                        message: "client_id:",
                    });
                    clientId = answer.clientId;
                }
                else {
                    clientId = null;
                }
            }
            else {
                clientId = storedClientId;
            }
            return clientId;
        });
    }
    apiClientSecret(isAdditionalAuthentication = false) {
        return login_command_awaiter(this, void 0, void 0, function* () {
            const additionalAuthenticationMessage = "Additional authentication required.\nAPI key ";
            let clientSecret = null;
            const storedClientSecret = this.clientSecret || process.env.BW_CLIENTSECRET;
            if (this.canInteract && storedClientSecret == null) {
                const answer = yield external_inquirer_namespaceObject.createPromptModule({
                    output: process.stderr,
                })({
                    type: "input",
                    name: "clientSecret",
                    message: (isAdditionalAuthentication ? additionalAuthenticationMessage : "") + "client_secret:",
                });
                clientSecret = answer.clientSecret;
            }
            else {
                clientSecret = storedClientSecret;
            }
            return clientSecret;
        });
    }
    apiIdentifiers() {
        return login_command_awaiter(this, void 0, void 0, function* () {
            return {
                clientId: yield this.apiClientId(),
                clientSecret: yield this.apiClientSecret(),
            };
        });
    }
    openSsoPrompt(codeChallenge, state) {
        return login_command_awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const callbackServer = external_http_namespaceObject.createServer((req, res) => {
                    const urlString = "http://localhost" + req.url;
                    const url = new URL(urlString);
                    const code = url.searchParams.get("code");
                    const receivedState = url.searchParams.get("state");
                    const orgIdentifier = this.getOrgIdentifierFromState(receivedState);
                    res.setHeader("Content-Type", "text/html");
                    if (code != null && receivedState != null && this.checkState(receivedState, state)) {
                        res.writeHead(200);
                        res.end("<html><head><title>Success | Bitwarden CLI</title></head><body>" +
                            "<h1>Successfully authenticated with the Bitwarden CLI</h1>" +
                            "<p>You may now close this tab and return to the terminal.</p>" +
                            "</body></html>");
                        callbackServer.close(() => resolve({
                            ssoCode: code,
                            orgIdentifier: orgIdentifier,
                        }));
                    }
                    else {
                        res.writeHead(400);
                        res.end("<html><head><title>Failed | Bitwarden CLI</title></head><body>" +
                            "<h1>Something went wrong logging into the Bitwarden CLI</h1>" +
                            "<p>You may now close this tab and return to the terminal.</p>" +
                            "</body></html>");
                        callbackServer.close(() => reject());
                    }
                });
                let foundPort = false;
                const webUrl = this.environmentService.getWebVaultUrl();
                for (let port = 8065; port <= 8070; port++) {
                    try {
                        this.ssoRedirectUri = "http://localhost:" + port;
                        callbackServer.listen(port, () => {
                            this.platformUtilsService.launchUri(webUrl +
                                "/#/sso?clientId=" +
                                "cli" +
                                "&redirectUri=" +
                                encodeURIComponent(this.ssoRedirectUri) +
                                "&state=" +
                                state +
                                "&codeChallenge=" +
                                codeChallenge);
                        });
                        foundPort = true;
                        break;
                    }
                    catch (_a) {
                        // Ignore error since we run the same command up to 5 times.
                    }
                }
                if (!foundPort) {
                    reject();
                }
            });
        });
    }
    getOrgIdentifierFromState(state) {
        if (state === null || state === undefined) {
            return null;
        }
        const stateSplit = state.split("_identifier=");
        return stateSplit.length > 1 ? stateSplit[1] : null;
    }
    checkState(state, checkState) {
        if (state === null || state === undefined) {
            return false;
        }
        if (checkState === null || checkState === undefined) {
            return false;
        }
        const stateSplit = state.split("_identifier=");
        const checkStateSplit = checkState.split("_identifier=");
        return stateSplit[0] === checkStateSplit[0];
    }
}

;// CONCATENATED MODULE: ./src/commands/logout.command.ts
var logout_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class LogoutCommand {
    constructor(authService, i18nService, logoutCallback) {
        this.authService = authService;
        this.i18nService = i18nService;
        this.logoutCallback = logoutCallback;
    }
    run() {
        return logout_command_awaiter(this, void 0, void 0, function* () {
            yield this.logoutCallback();
            this.authService.logOut(() => {
                /* Do nothing */
            });
            const res = new MessageResponse("You have logged out.", null);
            return Response.success(res);
        });
    }
}

;// CONCATENATED MODULE: external "@koa/multer"
const multer_namespaceObject = require("@koa/multer");
;// CONCATENATED MODULE: external "@koa/router"
const router_namespaceObject = require("@koa/router");
;// CONCATENATED MODULE: external "koa"
const external_koa_namespaceObject = require("koa");
;// CONCATENATED MODULE: external "koa-bodyparser"
const external_koa_bodyparser_namespaceObject = require("koa-bodyparser");
;// CONCATENATED MODULE: external "koa-json"
const external_koa_json_namespaceObject = require("koa-json");
;// CONCATENATED MODULE: ./src/models/response/file.response.ts
class FileResponse {
    constructor(data, fileName) {
        this.object = "file";
        this.data = data;
        this.fileName = fileName;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/selection-read-only.request.ts
class SelectionReadOnlyRequest {
    constructor(id, readOnly, hidePasswords) {
        this.id = id;
        this.readOnly = readOnly;
        this.hidePasswords = hidePasswords;
    }
}

;// CONCATENATED MODULE: ./src/models/response/collection.response.ts

class CollectionResponse extends CollectionWithIdExport {
    constructor(o) {
        super();
        this.object = "collection";
        this.build(o);
    }
}

;// CONCATENATED MODULE: ./src/models/response/organization-collection.response.ts

class OrganizationCollectionResponse extends CollectionResponse {
    constructor(o, groups) {
        super(o);
        this.object = "org-collection";
        this.groups = groups;
    }
}

;// CONCATENATED MODULE: ./src/models/response/login.response.ts

class LoginResponse extends LoginExport {
    constructor(o) {
        super(o);
        this.passwordRevisionDate = o.passwordRevisionDate != null ? o.passwordRevisionDate : null;
    }
}

;// CONCATENATED MODULE: ./src/vault/models/attachment.response.ts
class AttachmentResponse {
    constructor(o) {
        this.id = o.id;
        this.fileName = o.fileName;
        this.size = o.size;
        this.sizeName = o.sizeName;
        this.url = o.url;
    }
}

;// CONCATENATED MODULE: ./src/vault/models/password-history.response.ts
class PasswordHistoryResponse {
    constructor(o) {
        this.lastUsedDate = o.lastUsedDate;
        this.password = o.password;
    }
}

;// CONCATENATED MODULE: ./src/vault/models/cipher.response.ts





class CipherResponse extends CipherWithIdExport {
    constructor(o) {
        super();
        this.object = "item";
        this.build(o);
        if (o.attachments != null) {
            this.attachments = o.attachments.map((a) => new AttachmentResponse(a));
        }
        this.revisionDate = o.revisionDate;
        if (o.creationDate != null) {
            this.creationDate = o.creationDate;
        }
        this.deletedDate = o.deletedDate;
        if (o.passwordHistory != null) {
            this.passwordHistory = o.passwordHistory.map((h) => new PasswordHistoryResponse(h));
        }
        if (o.type === CipherType.Login && o.login != null) {
            this.login = new LoginResponse(o.login);
        }
    }
}

;// CONCATENATED MODULE: ./src/vault/models/folder.response.ts

class folder_response_FolderResponse extends FolderWithIdExport {
    constructor(o) {
        super();
        this.object = "folder";
        this.build(o);
    }
}

;// CONCATENATED MODULE: ./src/vault/create.command.ts
var create_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};













class CreateCommand {
    constructor(cipherService, folderService, stateService, cryptoService, apiService, folderApiService) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.stateService = stateService;
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.folderApiService = folderApiService;
    }
    run(object, requestJson, cmdOptions, additionalData = null) {
        return create_command_awaiter(this, void 0, void 0, function* () {
            let req = null;
            if (object !== "attachment") {
                if (process.env.BW_SERVE !== "true" && (requestJson == null || requestJson === "")) {
                    requestJson = yield CliUtils.readStdin();
                }
                if (requestJson == null || requestJson === "") {
                    return Response.badRequest("`requestJson` was not provided.");
                }
                if (typeof requestJson !== "string") {
                    req = requestJson;
                }
                else {
                    try {
                        const reqJson = Buffer.from(requestJson, "base64").toString();
                        req = JSON.parse(reqJson);
                    }
                    catch (e) {
                        return Response.badRequest("Error parsing the encoded request data.");
                    }
                }
            }
            const normalizedOptions = new create_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "item":
                    return yield this.createCipher(req);
                case "attachment":
                    return yield this.createAttachment(normalizedOptions, additionalData);
                case "folder":
                    return yield this.createFolder(req);
                case "org-collection":
                    return yield this.createOrganizationCollection(req, normalizedOptions);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    createCipher(req) {
        return create_command_awaiter(this, void 0, void 0, function* () {
            const cipher = yield this.cipherService.encrypt(CipherExport.toView(req));
            try {
                yield this.cipherService.createWithServer(cipher);
                const newCipher = yield this.cipherService.get(cipher.id);
                const decCipher = yield newCipher.decrypt();
                const res = new CipherResponse(decCipher);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    createAttachment(options, additionalData) {
        return create_command_awaiter(this, void 0, void 0, function* () {
            if (options.itemId == null || options.itemId === "") {
                return Response.badRequest("`itemid` option is required.");
            }
            let fileBuf = null;
            let fileName = null;
            if (process.env.BW_SERVE === "true") {
                fileBuf = additionalData.fileBuffer;
                fileName = additionalData.fileName;
            }
            else {
                if (options.file == null || options.file === "") {
                    return Response.badRequest("`file` option is required.");
                }
                const filePath = external_path_namespaceObject.resolve(options.file);
                if (!external_fs_namespaceObject.existsSync(options.file)) {
                    return Response.badRequest("Cannot find file at " + filePath);
                }
                fileBuf = external_fs_namespaceObject.readFileSync(filePath);
                fileName = external_path_namespaceObject.basename(filePath);
            }
            if (fileBuf == null) {
                return Response.badRequest("File not provided.");
            }
            if (fileName == null || fileName.trim() === "") {
                return Response.badRequest("File name not provided.");
            }
            const itemId = options.itemId.toLowerCase();
            const cipher = yield this.cipherService.get(itemId);
            if (cipher == null) {
                return Response.notFound();
            }
            if (cipher.organizationId == null && !(yield this.stateService.getCanAccessPremium())) {
                return Response.error("Premium status is required to use this feature.");
            }
            const encKey = yield this.cryptoService.getEncKey();
            if (encKey == null) {
                return Response.error("You must update your encryption key before you can use this feature. " +
                    "See https://help.bitwarden.com/article/update-encryption-key/");
            }
            try {
                yield this.cipherService.saveAttachmentRawWithServer(cipher, fileName, new Uint8Array(fileBuf).buffer);
                const updatedCipher = yield this.cipherService.get(cipher.id);
                const decCipher = yield updatedCipher.decrypt();
                return Response.success(new CipherResponse(decCipher));
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    createFolder(req) {
        return create_command_awaiter(this, void 0, void 0, function* () {
            const folder = yield this.folderService.encrypt(FolderExport.toView(req));
            try {
                yield this.folderApiService.save(folder);
                const newFolder = yield this.folderService.get(folder.id);
                const decFolder = yield newFolder.decrypt();
                const res = new folder_response_FolderResponse(decFolder);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    createOrganizationCollection(req, options) {
        return create_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` option is required.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            if (options.organizationId !== req.organizationId) {
                return Response.badRequest("`organizationid` option does not match request object.");
            }
            try {
                const orgKey = yield this.cryptoService.getOrgKey(req.organizationId);
                if (orgKey == null) {
                    throw new Error("No encryption key for this organization.");
                }
                const groups = req.groups == null
                    ? null
                    : req.groups.map((g) => new SelectionReadOnlyRequest(g.id, g.readOnly, g.hidePasswords));
                const request = new CollectionRequest();
                request.name = (yield this.cryptoService.encrypt(req.name, orgKey)).encryptedString;
                request.externalId = req.externalId;
                request.groups = groups;
                const response = yield this.apiService.postCollection(req.organizationId, request);
                const view = CollectionExport.toView(req);
                view.id = response.id;
                const res = new OrganizationCollectionResponse(view, groups);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}
class create_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
        this.itemId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemId);
        this.file = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.file;
    }
}

;// CONCATENATED MODULE: ./src/vault/delete.command.ts
var delete_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class DeleteCommand {
    constructor(cipherService, folderService, stateService, apiService, folderApiService) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.stateService = stateService;
        this.apiService = apiService;
        this.folderApiService = folderApiService;
    }
    run(object, id, cmdOptions) {
        return delete_command_awaiter(this, void 0, void 0, function* () {
            if (id != null) {
                id = id.toLowerCase();
            }
            const normalizedOptions = new delete_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "item":
                    return yield this.deleteCipher(id, normalizedOptions);
                case "attachment":
                    return yield this.deleteAttachment(id, normalizedOptions);
                case "folder":
                    return yield this.deleteFolder(id);
                case "org-collection":
                    return yield this.deleteOrganizationCollection(id, normalizedOptions);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    deleteCipher(id, options) {
        return delete_command_awaiter(this, void 0, void 0, function* () {
            const cipher = yield this.cipherService.get(id);
            if (cipher == null) {
                return Response.notFound();
            }
            try {
                if (options.permanent) {
                    yield this.cipherService.deleteWithServer(id);
                }
                else {
                    yield this.cipherService.softDeleteWithServer(id);
                }
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    deleteAttachment(id, options) {
        return delete_command_awaiter(this, void 0, void 0, function* () {
            if (options.itemId == null || options.itemId === "") {
                return Response.badRequest("`itemid` option is required.");
            }
            const itemId = options.itemId.toLowerCase();
            const cipher = yield this.cipherService.get(itemId);
            if (cipher == null) {
                return Response.notFound();
            }
            if (cipher.attachments == null || cipher.attachments.length === 0) {
                return Response.error("No attachments available for this item.");
            }
            const attachments = cipher.attachments.filter((a) => a.id.toLowerCase() === id);
            if (attachments.length === 0) {
                return Response.error("Attachment `" + id + "` was not found.");
            }
            if (cipher.organizationId == null && !(yield this.stateService.getCanAccessPremium())) {
                return Response.error("Premium status is required to use this feature.");
            }
            try {
                yield this.cipherService.deleteAttachmentWithServer(cipher.id, attachments[0].id);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    deleteFolder(id) {
        return delete_command_awaiter(this, void 0, void 0, function* () {
            const folder = yield this.folderService.getFromState(id);
            if (folder == null) {
                return Response.notFound();
            }
            try {
                yield this.folderApiService.delete(id);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    deleteOrganizationCollection(id, options) {
        return delete_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` options is required.");
            }
            if (!Utils.isGuid(id)) {
                return Response.badRequest("`" + id + "` is not a GUID.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            try {
                yield this.apiService.deleteCollection(options.organizationId, id);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}
class delete_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
        this.itemId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemId);
        this.permanent = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.permanent);
    }
}

;// CONCATENATED MODULE: ./src/vault/sync.command.ts
var sync_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




class SyncCommand {
    constructor(syncService) {
        this.syncService = syncService;
    }
    run(cmdOptions) {
        return sync_command_awaiter(this, void 0, void 0, function* () {
            const normalizedOptions = new sync_command_Options(cmdOptions);
            if (normalizedOptions.last) {
                return yield this.getLastSync();
            }
            try {
                yield this.syncService.fullSync(normalizedOptions.force, true);
                const res = new MessageResponse("Syncing complete.", null);
                return Response.success(res);
            }
            catch (e) {
                return Response.error("Syncing failed: " + e.toString());
            }
        });
    }
    getLastSync() {
        return sync_command_awaiter(this, void 0, void 0, function* () {
            const lastSyncDate = yield this.syncService.getLastSync();
            const res = new StringResponse(lastSyncDate == null ? null : lastSyncDate.toISOString());
            return Response.success(res);
        });
    }
}
class sync_command_Options {
    constructor(passedOptions) {
        this.last = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.last);
        this.force = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.force);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/abstractions/organization-user/requests/organization-user-confirm.request.ts
class OrganizationUserConfirmRequest {
}

;// CONCATENATED MODULE: ./src/commands/confirm.command.ts
var confirm_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class ConfirmCommand {
    constructor(apiService, cryptoService, organizationUserService) {
        this.apiService = apiService;
        this.cryptoService = cryptoService;
        this.organizationUserService = organizationUserService;
    }
    run(object, id, cmdOptions) {
        return confirm_command_awaiter(this, void 0, void 0, function* () {
            if (id != null) {
                id = id.toLowerCase();
            }
            const normalizedOptions = new confirm_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "org-member":
                    return yield this.confirmOrganizationMember(id, normalizedOptions);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    confirmOrganizationMember(id, options) {
        return confirm_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("--organizationid <organizationid> required.");
            }
            if (!Utils.isGuid(id)) {
                return Response.badRequest("`" + id + "` is not a GUID.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            try {
                const orgKey = yield this.cryptoService.getOrgKey(options.organizationId);
                if (orgKey == null) {
                    throw new Error("No encryption key for this organization.");
                }
                const orgUser = yield this.organizationUserService.getOrganizationUser(options.organizationId, id);
                if (orgUser == null) {
                    throw new Error("Member id does not exist for this organization.");
                }
                const publicKeyResponse = yield this.apiService.getUserPublicKey(orgUser.userId);
                const publicKey = Utils.fromB64ToArray(publicKeyResponse.publicKey);
                const key = yield this.cryptoService.rsaEncrypt(orgKey.key, publicKey.buffer);
                const req = new OrganizationUserConfirmRequest();
                req.key = key.encryptedString;
                yield this.organizationUserService.postOrganizationUserConfirm(options.organizationId, id, req);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}
class confirm_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
    }
}

;// CONCATENATED MODULE: ./src/commands/edit.command.ts
var edit_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};











class EditCommand {
    constructor(cipherService, folderService, cryptoService, apiService, folderApiService) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.cryptoService = cryptoService;
        this.apiService = apiService;
        this.folderApiService = folderApiService;
    }
    run(object, id, requestJson, cmdOptions) {
        return edit_command_awaiter(this, void 0, void 0, function* () {
            if (process.env.BW_SERVE !== "true" && (requestJson == null || requestJson === "")) {
                requestJson = yield CliUtils.readStdin();
            }
            if (requestJson == null || requestJson === "") {
                return Response.badRequest("`requestJson` was not provided.");
            }
            let req = null;
            if (typeof requestJson !== "string") {
                req = requestJson;
            }
            else {
                try {
                    const reqJson = Buffer.from(requestJson, "base64").toString();
                    req = JSON.parse(reqJson);
                }
                catch (e) {
                    return Response.badRequest("Error parsing the encoded request data.");
                }
            }
            if (id != null) {
                id = id.toLowerCase();
            }
            const normalizedOptions = new edit_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "item":
                    return yield this.editCipher(id, req);
                case "item-collections":
                    return yield this.editCipherCollections(id, req);
                case "folder":
                    return yield this.editFolder(id, req);
                case "org-collection":
                    return yield this.editOrganizationCollection(id, req, normalizedOptions);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    editCipher(id, req) {
        return edit_command_awaiter(this, void 0, void 0, function* () {
            const cipher = yield this.cipherService.get(id);
            if (cipher == null) {
                return Response.notFound();
            }
            let cipherView = yield cipher.decrypt();
            if (cipherView.isDeleted) {
                return Response.badRequest("You may not edit a deleted item. Use the restore command first.");
            }
            cipherView = CipherExport.toView(req, cipherView);
            const encCipher = yield this.cipherService.encrypt(cipherView);
            try {
                yield this.cipherService.updateWithServer(encCipher);
                const updatedCipher = yield this.cipherService.get(cipher.id);
                const decCipher = yield updatedCipher.decrypt();
                const res = new CipherResponse(decCipher);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    editCipherCollections(id, req) {
        return edit_command_awaiter(this, void 0, void 0, function* () {
            const cipher = yield this.cipherService.get(id);
            if (cipher == null) {
                return Response.notFound();
            }
            if (cipher.organizationId == null) {
                return Response.badRequest("Item does not belong to an organization. Consider moving it first.");
            }
            cipher.collectionIds = req;
            try {
                yield this.cipherService.saveCollectionsWithServer(cipher);
                const updatedCipher = yield this.cipherService.get(cipher.id);
                const decCipher = yield updatedCipher.decrypt();
                const res = new CipherResponse(decCipher);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    editFolder(id, req) {
        return edit_command_awaiter(this, void 0, void 0, function* () {
            const folder = yield this.folderService.getFromState(id);
            if (folder == null) {
                return Response.notFound();
            }
            let folderView = yield folder.decrypt();
            folderView = FolderExport.toView(req, folderView);
            const encFolder = yield this.folderService.encrypt(folderView);
            try {
                yield this.folderApiService.save(encFolder);
                const updatedFolder = yield this.folderService.get(folder.id);
                const decFolder = yield updatedFolder.decrypt();
                const res = new folder_response_FolderResponse(decFolder);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    editOrganizationCollection(id, req, options) {
        return edit_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` option is required.");
            }
            if (!Utils.isGuid(id)) {
                return Response.badRequest("`" + id + "` is not a GUID.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            if (options.organizationId !== req.organizationId) {
                return Response.badRequest("`organizationid` option does not match request object.");
            }
            try {
                const orgKey = yield this.cryptoService.getOrgKey(req.organizationId);
                if (orgKey == null) {
                    throw new Error("No encryption key for this organization.");
                }
                const groups = req.groups == null
                    ? null
                    : req.groups.map((g) => new SelectionReadOnlyRequest(g.id, g.readOnly, g.hidePasswords));
                const request = new CollectionRequest();
                request.name = (yield this.cryptoService.encrypt(req.name, orgKey)).encryptedString;
                request.externalId = req.externalId;
                request.groups = groups;
                const response = yield this.apiService.putCollection(req.organizationId, id, request);
                const view = CollectionExport.toView(req);
                view.id = response.id;
                const res = new OrganizationCollectionResponse(view, groups);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}
class edit_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
    }
}

;// CONCATENATED MODULE: ./src/models/selection-read-only.ts
class SelectionReadOnly {
    constructor(id, readOnly, hidePasswords) {
        this.id = id;
        this.readOnly = readOnly;
        this.hidePasswords = hidePasswords || false;
    }
    static template() {
        return new SelectionReadOnly("00000000-0000-0000-0000-000000000000", false, false);
    }
}

;// CONCATENATED MODULE: ./src/models/request/organization-collection.request.ts


class OrganizationCollectionRequest extends CollectionExport {
    static template() {
        const req = new OrganizationCollectionRequest();
        req.organizationId = "00000000-0000-0000-0000-000000000000";
        req.name = "Collection name";
        req.externalId = null;
        req.groups = [SelectionReadOnly.template(), SelectionReadOnly.template()];
        return req;
    }
}

;// CONCATENATED MODULE: ./src/models/response/organization.response.ts
class organization_response_OrganizationResponse {
    constructor(o) {
        this.object = "organization";
        this.id = o.id;
        this.name = o.name;
        this.status = o.status;
        this.type = o.type;
        this.enabled = o.enabled;
    }
}

;// CONCATENATED MODULE: ./src/models/response/send-file.response.ts

class SendFileResponse {
    constructor(o) {
        if (o == null) {
            return;
        }
        this.id = o.id;
        this.size = o.size;
        this.sizeName = o.sizeName;
        this.fileName = o.fileName;
    }
    static template(fileName = "file attachment location") {
        const req = new SendFileResponse();
        req.fileName = fileName;
        return req;
    }
    static toView(file, view = new SendFileView()) {
        if (file == null) {
            return null;
        }
        view.id = file.id;
        view.size = file.size;
        view.sizeName = file.sizeName;
        view.fileName = file.fileName;
        return view;
    }
}

;// CONCATENATED MODULE: ./src/models/response/send-text.response.ts

class SendTextResponse {
    constructor(o) {
        if (o == null) {
            return;
        }
        this.text = o.text;
        this.hidden = o.hidden;
    }
    static template(text = "Text contained in the send.", hidden = false) {
        const req = new SendTextResponse();
        req.text = text;
        req.hidden = hidden;
        return req;
    }
    static toView(text, view = new SendTextView()) {
        if (text == null) {
            return null;
        }
        view.text = text.text;
        view.hidden = text.hidden;
        return view;
    }
}

;// CONCATENATED MODULE: ./src/models/response/send.response.ts





const dateProperties = [
    Utils.nameOf("deletionDate"),
    Utils.nameOf("expirationDate"),
];
class SendResponse {
    constructor(o, webVaultUrl) {
        this.object = "send";
        if (o == null) {
            return;
        }
        this.id = o.id;
        this.accessId = o.accessId;
        let sendLinkBaseUrl = webVaultUrl;
        if (sendLinkBaseUrl == null) {
            sendLinkBaseUrl = "https://send.bitwarden.com/#";
        }
        else {
            sendLinkBaseUrl += "/#/send/";
        }
        this.accessUrl = sendLinkBaseUrl + this.accessId + "/" + o.urlB64Key;
        this.name = o.name;
        this.notes = o.notes;
        this.key = Utils.fromBufferToB64(o.key);
        this.type = o.type;
        this.maxAccessCount = o.maxAccessCount;
        this.accessCount = o.accessCount;
        this.revisionDate = o.revisionDate;
        this.deletionDate = o.deletionDate;
        this.expirationDate = o.expirationDate;
        this.passwordSet = o.password != null;
        this.disabled = o.disabled;
        this.hideEmail = o.hideEmail;
        if (o.type === SendType.Text && o.text != null) {
            this.text = new SendTextResponse(o.text);
        }
        if (o.type === SendType.File && o.file != null) {
            this.file = new SendFileResponse(o.file);
        }
    }
    static template(sendType, deleteInDays = 7) {
        const req = new SendResponse();
        req.name = "Send name";
        req.notes = "Some notes about this send.";
        req.type = sendType === SendType.File ? SendType.File : SendType.Text;
        req.text = sendType === SendType.Text ? SendTextResponse.template() : null;
        req.file = sendType === SendType.File ? SendFileResponse.template() : null;
        req.maxAccessCount = null;
        req.deletionDate = this.getStandardDeletionDate(deleteInDays);
        req.expirationDate = null;
        req.password = null;
        req.disabled = false;
        req.hideEmail = false;
        return req;
    }
    static toView(send, view = new SendView()) {
        if (send == null) {
            return null;
        }
        view.id = send.id;
        view.accessId = send.accessId;
        view.name = send.name;
        view.notes = send.notes;
        view.key = send.key == null ? null : Utils.fromB64ToArray(send.key);
        view.type = send.type;
        view.file = SendFileResponse.toView(send.file);
        view.text = SendTextResponse.toView(send.text);
        view.maxAccessCount = send.maxAccessCount;
        view.accessCount = send.accessCount;
        view.revisionDate = send.revisionDate;
        view.deletionDate = send.deletionDate;
        view.expirationDate = send.expirationDate;
        view.password = send.password;
        view.disabled = send.disabled;
        view.hideEmail = send.hideEmail;
        return view;
    }
    static fromJson(json) {
        return JSON.parse(json, (key, value) => {
            if (dateProperties.includes(key)) {
                return value == null ? null : new Date(value);
            }
            return value;
        });
    }
    static getStandardDeletionDate(days) {
        const d = new Date();
        d.setTime(d.getTime() + days * 86400000); // ms per day
        return d;
    }
}

;// CONCATENATED MODULE: ./src/models/response/template.response.ts
class TemplateResponse {
    constructor(template) {
        this.object = "template";
        this.template = template;
    }
}

;// CONCATENATED MODULE: external "node-fetch"
const external_node_fetch_namespaceObject = require("node-fetch");
var external_node_fetch_default = /*#__PURE__*/__webpack_require__.n(external_node_fetch_namespaceObject);
;// CONCATENATED MODULE: ./src/commands/download.command.ts
var download_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class DownloadCommand {
    constructor(cryptoService) {
        this.cryptoService = cryptoService;
    }
    saveAttachmentToFile(url, key, fileName, output) {
        return download_command_awaiter(this, void 0, void 0, function* () {
            const response = yield external_node_fetch_default()(new external_node_fetch_namespaceObject.Request(url, { headers: { cache: "no-cache" } }));
            if (response.status !== 200) {
                return Response.error("A " + response.status + " error occurred while downloading the attachment.");
            }
            try {
                const encBuf = yield EncArrayBuffer.fromResponse(response);
                const decBuf = yield this.cryptoService.decryptFromBytes(encBuf, key);
                if (process.env.BW_SERVE === "true") {
                    const res = new FileResponse(Buffer.from(decBuf), fileName);
                    return Response.success(res);
                }
                else {
                    return yield CliUtils.saveResultToFile(Buffer.from(decBuf), output, fileName);
                }
            }
            catch (e) {
                if (typeof e === "string") {
                    return Response.error(e);
                }
                else {
                    return Response.error("An error occurred while saving the attachment.");
                }
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/get.command.ts
var get_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




























class GetCommand extends DownloadCommand {
    constructor(cipherService, folderService, collectionService, totpService, auditService, cryptoService, stateService, searchService, apiService, organizationService) {
        super(cryptoService);
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.collectionService = collectionService;
        this.totpService = totpService;
        this.auditService = auditService;
        this.stateService = stateService;
        this.searchService = searchService;
        this.apiService = apiService;
        this.organizationService = organizationService;
    }
    run(object, id, cmdOptions) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            if (id != null) {
                id = id.toLowerCase();
            }
            const normalizedOptions = new get_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "item":
                    return yield this.getCipher(id);
                case "username":
                    return yield this.getUsername(id);
                case "password":
                    return yield this.getPassword(id);
                case "uri":
                    return yield this.getUri(id);
                case "totp":
                    return yield this.getTotp(id);
                case "notes":
                    return yield this.getNotes(id);
                case "exposed":
                    return yield this.getExposed(id);
                case "attachment":
                    return yield this.getAttachment(id, normalizedOptions);
                case "folder":
                    return yield this.getFolder(id);
                case "collection":
                    return yield this.getCollection(id);
                case "org-collection":
                    return yield this.getOrganizationCollection(id, normalizedOptions);
                case "organization":
                    return yield this.getOrganization(id);
                case "template":
                    return yield this.getTemplate(id);
                case "fingerprint":
                    return yield this.getFingerprint(id);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    getCipherView(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let decCipher = null;
            if (Utils.isGuid(id)) {
                const cipher = yield this.cipherService.get(id);
                if (cipher != null) {
                    decCipher = yield cipher.decrypt();
                }
            }
            else if (id.trim() !== "") {
                let ciphers = yield this.cipherService.getAllDecrypted();
                ciphers = this.searchService.searchCiphersBasic(ciphers, id);
                if (ciphers.length > 1) {
                    return ciphers;
                }
                if (ciphers.length > 0) {
                    decCipher = ciphers[0];
                }
            }
            return decCipher;
        });
    }
    getCipher(id, filter) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let decCipher = yield this.getCipherView(id);
            if (decCipher == null) {
                return Response.notFound();
            }
            if (Array.isArray(decCipher)) {
                if (filter != null) {
                    decCipher = decCipher.filter(filter);
                    if (decCipher.length === 1) {
                        decCipher = decCipher[0];
                    }
                }
                if (Array.isArray(decCipher)) {
                    return Response.multipleResults(decCipher.map((c) => c.id));
                }
            }
            const res = new CipherResponse(decCipher);
            return Response.success(res);
        });
    }
    getUsername(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const cipherResponse = yield this.getCipher(id, (c) => c.type === CipherType.Login && !Utils.isNullOrWhitespace(c.login.username));
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = cipherResponse.data;
            if (cipher.type !== CipherType.Login) {
                return Response.badRequest("Not a login.");
            }
            if (Utils.isNullOrWhitespace(cipher.login.username)) {
                return Response.error("No username available for this login.");
            }
            const res = new StringResponse(cipher.login.username);
            return Response.success(res);
        });
    }
    getPassword(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const cipherResponse = yield this.getCipher(id, (c) => c.type === CipherType.Login && !Utils.isNullOrWhitespace(c.login.password));
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = cipherResponse.data;
            if (cipher.type !== CipherType.Login) {
                return Response.badRequest("Not a login.");
            }
            if (Utils.isNullOrWhitespace(cipher.login.password)) {
                return Response.error("No password available for this login.");
            }
            const res = new StringResponse(cipher.login.password);
            return Response.success(res);
        });
    }
    getUri(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const cipherResponse = yield this.getCipher(id, (c) => c.type === CipherType.Login &&
                c.login.uris != null &&
                c.login.uris.length > 0 &&
                c.login.uris[0].uri !== "");
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = cipherResponse.data;
            if (cipher.type !== CipherType.Login) {
                return Response.badRequest("Not a login.");
            }
            if (cipher.login.uris == null ||
                cipher.login.uris.length === 0 ||
                cipher.login.uris[0].uri === "") {
                return Response.error("No uri available for this login.");
            }
            const res = new StringResponse(cipher.login.uris[0].uri);
            return Response.success(res);
        });
    }
    getTotp(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const cipherResponse = yield this.getCipher(id, (c) => c.type === CipherType.Login && !Utils.isNullOrWhitespace(c.login.totp));
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = cipherResponse.data;
            if (cipher.type !== CipherType.Login) {
                return Response.badRequest("Not a login.");
            }
            if (Utils.isNullOrWhitespace(cipher.login.totp)) {
                return Response.error("No TOTP available for this login.");
            }
            const totp = yield this.totpService.getCode(cipher.login.totp);
            if (totp == null) {
                return Response.error("Couldn't generate TOTP code.");
            }
            const canAccessPremium = yield this.stateService.getCanAccessPremium();
            if (!canAccessPremium) {
                const originalCipher = yield this.cipherService.get(cipher.id);
                if (originalCipher == null ||
                    originalCipher.organizationId == null ||
                    !originalCipher.organizationUseTotp) {
                    return Response.error("Premium status is required to use this feature.");
                }
            }
            const res = new StringResponse(totp);
            return Response.success(res);
        });
    }
    getNotes(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const cipherResponse = yield this.getCipher(id, (c) => !Utils.isNullOrWhitespace(c.notes));
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = cipherResponse.data;
            if (Utils.isNullOrWhitespace(cipher.notes)) {
                return Response.error("No notes available for this item.");
            }
            const res = new StringResponse(cipher.notes);
            return Response.success(res);
        });
    }
    getExposed(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            const passwordResponse = yield this.getPassword(id);
            if (!passwordResponse.success) {
                return passwordResponse;
            }
            const exposedNumber = yield this.auditService.passwordLeaked(passwordResponse.data.data);
            const res = new StringResponse(exposedNumber.toString());
            return Response.success(res);
        });
    }
    getAttachment(id, options) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            if (options.itemId == null || options.itemId === "") {
                return Response.badRequest("--itemid <itemid> required.");
            }
            const itemId = options.itemId.toLowerCase();
            const cipherResponse = yield this.getCipher(itemId);
            if (!cipherResponse.success) {
                return cipherResponse;
            }
            const cipher = yield this.getCipherView(itemId);
            if (cipher == null ||
                Array.isArray(cipher) ||
                cipher.attachments == null ||
                cipher.attachments.length === 0) {
                return Response.error("No attachments available for this item.");
            }
            let attachments = cipher.attachments.filter((a) => a.id.toLowerCase() === id ||
                (a.fileName != null && a.fileName.toLowerCase().indexOf(id) > -1));
            if (attachments.length === 0) {
                return Response.error("Attachment `" + id + "` was not found.");
            }
            const exactMatches = attachments.filter((a) => a.fileName.toLowerCase() === id);
            if (exactMatches.length === 1) {
                attachments = exactMatches;
            }
            if (attachments.length > 1) {
                return Response.multipleResults(attachments.map((a) => a.id));
            }
            if (!(yield this.stateService.getCanAccessPremium())) {
                const originalCipher = yield this.cipherService.get(cipher.id);
                if (originalCipher == null || originalCipher.organizationId == null) {
                    return Response.error("Premium status is required to use this feature.");
                }
            }
            let url;
            try {
                const attachmentDownloadResponse = yield this.apiService.getAttachmentData(cipher.id, attachments[0].id);
                url = attachmentDownloadResponse.url;
            }
            catch (e) {
                if (e instanceof ErrorResponse && e.statusCode === 404) {
                    url = attachments[0].url;
                }
                else if (e instanceof ErrorResponse) {
                    throw new Error(e.getSingleMessage());
                }
                else {
                    throw e;
                }
            }
            const key = attachments[0].key != null
                ? attachments[0].key
                : yield this.cryptoService.getOrgKey(cipher.organizationId);
            return yield this.saveAttachmentToFile(url, key, attachments[0].fileName, options.output);
        });
    }
    getFolder(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let decFolder = null;
            if (Utils.isGuid(id)) {
                const folder = yield this.folderService.getFromState(id);
                if (folder != null) {
                    decFolder = yield folder.decrypt();
                }
            }
            else if (id.trim() !== "") {
                let folders = yield this.folderService.getAllDecryptedFromState();
                folders = CliUtils.searchFolders(folders, id);
                if (folders.length > 1) {
                    return Response.multipleResults(folders.map((f) => f.id));
                }
                if (folders.length > 0) {
                    decFolder = folders[0];
                }
            }
            if (decFolder == null) {
                return Response.notFound();
            }
            const res = new folder_response_FolderResponse(decFolder);
            return Response.success(res);
        });
    }
    getCollection(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let decCollection = null;
            if (Utils.isGuid(id)) {
                const collection = yield this.collectionService.get(id);
                if (collection != null) {
                    decCollection = yield collection.decrypt();
                }
            }
            else if (id.trim() !== "") {
                let collections = yield this.collectionService.getAllDecrypted();
                collections = CliUtils.searchCollections(collections, id);
                if (collections.length > 1) {
                    return Response.multipleResults(collections.map((c) => c.id));
                }
                if (collections.length > 0) {
                    decCollection = collections[0];
                }
            }
            if (decCollection == null) {
                return Response.notFound();
            }
            const res = new CollectionResponse(decCollection);
            return Response.success(res);
        });
    }
    getOrganizationCollection(id, options) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` option is required.");
            }
            if (!Utils.isGuid(id)) {
                return Response.badRequest("`" + id + "` is not a GUID.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            try {
                const orgKey = yield this.cryptoService.getOrgKey(options.organizationId);
                if (orgKey == null) {
                    throw new Error("No encryption key for this organization.");
                }
                const response = yield this.apiService.getCollectionAccessDetails(options.organizationId, id);
                const decCollection = new CollectionView(response);
                decCollection.name = yield this.cryptoService.decryptToUtf8(new EncString(response.name), orgKey);
                const groups = response.groups == null
                    ? null
                    : response.groups.map((g) => new SelectionReadOnly(g.id, g.readOnly, g.hidePasswords));
                const res = new OrganizationCollectionResponse(decCollection, groups);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    getOrganization(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let org = null;
            if (Utils.isGuid(id)) {
                org = yield this.organizationService.getFromState(id);
            }
            else if (id.trim() !== "") {
                let orgs = yield this.organizationService.getAll();
                orgs = CliUtils.searchOrganizations(orgs, id);
                if (orgs.length > 1) {
                    return Response.multipleResults(orgs.map((c) => c.id));
                }
                if (orgs.length > 0) {
                    org = orgs[0];
                }
            }
            if (org == null) {
                return Response.notFound();
            }
            const res = new organization_response_OrganizationResponse(org);
            return Response.success(res);
        });
    }
    getTemplate(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let template = null;
            switch (id.toLowerCase()) {
                case "item":
                    template = CipherExport.template();
                    break;
                case "item.field":
                    template = FieldExport.template();
                    break;
                case "item.login":
                    template = LoginExport.template();
                    break;
                case "item.login.uri":
                    template = LoginUriExport.template();
                    break;
                case "item.card":
                    template = CardExport.template();
                    break;
                case "item.identity":
                    template = IdentityExport.template();
                    break;
                case "item.securenote":
                    template = SecureNoteExport.template();
                    break;
                case "folder":
                    template = FolderExport.template();
                    break;
                case "collection":
                    template = CollectionExport.template();
                    break;
                case "item-collections":
                    template = ["collection-id1", "collection-id2"];
                    break;
                case "org-collection":
                    template = OrganizationCollectionRequest.template();
                    break;
                case "send.text":
                    template = SendResponse.template(SendType.Text);
                    break;
                case "send.file":
                    template = SendResponse.template(SendType.File);
                    break;
                default:
                    return Response.badRequest("Unknown template object.");
            }
            const res = new TemplateResponse(template);
            return Response.success(res);
        });
    }
    getFingerprint(id) {
        return get_command_awaiter(this, void 0, void 0, function* () {
            let fingerprint = null;
            if (id === "me") {
                fingerprint = yield this.cryptoService.getFingerprint(yield this.stateService.getUserId());
            }
            else if (Utils.isGuid(id)) {
                try {
                    const response = yield this.apiService.getUserPublicKey(id);
                    const pubKey = Utils.fromB64ToArray(response.publicKey);
                    fingerprint = yield this.cryptoService.getFingerprint(id, pubKey.buffer);
                }
                catch (_a) {
                    // eslint-disable-next-line
                }
            }
            if (fingerprint == null) {
                return Response.notFound();
            }
            const res = new StringResponse(fingerprint.join("-"));
            return Response.success(res);
        });
    }
}
class get_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
        this.itemId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemId);
        this.output = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.output;
    }
}

;// CONCATENATED MODULE: ./src/models/response/list.response.ts
class list_response_ListResponse {
    constructor(data) {
        this.object = "list";
        this.data = data;
    }
}

;// CONCATENATED MODULE: ./src/models/response/organization-user.response.ts
class organization_user_response_OrganizationUserResponse {
    constructor() {
        this.object = "org-member";
    }
}

;// CONCATENATED MODULE: ./src/commands/list.command.ts
var list_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};











class ListCommand {
    constructor(cipherService, folderService, collectionService, organizationService, searchService, organizationUserService, apiService) {
        this.cipherService = cipherService;
        this.folderService = folderService;
        this.collectionService = collectionService;
        this.organizationService = organizationService;
        this.searchService = searchService;
        this.organizationUserService = organizationUserService;
        this.apiService = apiService;
    }
    run(object, cmdOptions) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            const normalizedOptions = new list_command_Options(cmdOptions);
            switch (object.toLowerCase()) {
                case "items":
                    return yield this.listCiphers(normalizedOptions);
                case "folders":
                    return yield this.listFolders(normalizedOptions);
                case "collections":
                    return yield this.listCollections(normalizedOptions);
                case "org-collections":
                    return yield this.listOrganizationCollections(normalizedOptions);
                case "org-members":
                    return yield this.listOrganizationMembers(normalizedOptions);
                case "organizations":
                    return yield this.listOrganizations(normalizedOptions);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    listCiphers(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            let ciphers;
            options.trash = options.trash || false;
            if (options.url != null && options.url.trim() !== "") {
                ciphers = yield this.cipherService.getAllDecryptedForUrl(options.url);
            }
            else {
                ciphers = yield this.cipherService.getAllDecrypted();
            }
            if (options.folderId != null ||
                options.collectionId != null ||
                options.organizationId != null) {
                ciphers = ciphers.filter((c) => {
                    if (options.trash !== c.isDeleted) {
                        return false;
                    }
                    if (options.folderId != null) {
                        if (options.folderId === "notnull" && c.folderId != null) {
                            return true;
                        }
                        const folderId = options.folderId === "null" ? null : options.folderId;
                        if (folderId === c.folderId) {
                            return true;
                        }
                    }
                    if (options.organizationId != null) {
                        if (options.organizationId === "notnull" && c.organizationId != null) {
                            return true;
                        }
                        const organizationId = options.organizationId === "null" ? null : options.organizationId;
                        if (organizationId === c.organizationId) {
                            return true;
                        }
                    }
                    if (options.collectionId != null) {
                        if (options.collectionId === "notnull" &&
                            c.collectionIds != null &&
                            c.collectionIds.length > 0) {
                            return true;
                        }
                        const collectionId = options.collectionId === "null" ? null : options.collectionId;
                        if (collectionId == null && (c.collectionIds == null || c.collectionIds.length === 0)) {
                            return true;
                        }
                        if (collectionId != null &&
                            c.collectionIds != null &&
                            c.collectionIds.indexOf(collectionId) > -1) {
                            return true;
                        }
                    }
                    return false;
                });
            }
            else if (options.search == null || options.search.trim() === "") {
                ciphers = ciphers.filter((c) => options.trash === c.isDeleted);
            }
            if (options.search != null && options.search.trim() !== "") {
                ciphers = this.searchService.searchCiphersBasic(ciphers, options.search, options.trash);
            }
            const res = new list_response_ListResponse(ciphers.map((o) => new CipherResponse(o)));
            return Response.success(res);
        });
    }
    listFolders(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            let folders = yield this.folderService.getAllDecryptedFromState();
            if (options.search != null && options.search.trim() !== "") {
                folders = CliUtils.searchFolders(folders, options.search);
            }
            const res = new list_response_ListResponse(folders.map((o) => new folder_response_FolderResponse(o)));
            return Response.success(res);
        });
    }
    listCollections(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            let collections = yield this.collectionService.getAllDecrypted();
            if (options.organizationId != null) {
                collections = collections.filter((c) => {
                    if (options.organizationId === c.organizationId) {
                        return true;
                    }
                    return false;
                });
            }
            if (options.search != null && options.search.trim() !== "") {
                collections = CliUtils.searchCollections(collections, options.search);
            }
            const res = new list_response_ListResponse(collections.map((o) => new CollectionResponse(o)));
            return Response.success(res);
        });
    }
    listOrganizationCollections(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` option is required.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            const organization = yield this.organizationService.getFromState(options.organizationId);
            if (organization == null) {
                return Response.error("Organization not found.");
            }
            try {
                let response;
                if (organization.canViewAllCollections) {
                    response = yield this.apiService.getCollections(options.organizationId);
                }
                else {
                    response = yield this.apiService.getUserCollections();
                }
                const collections = response.data
                    .filter((c) => c.organizationId === options.organizationId)
                    .map((r) => new Collection(new CollectionData(r)));
                let decCollections = yield this.collectionService.decryptMany(collections);
                if (options.search != null && options.search.trim() !== "") {
                    decCollections = CliUtils.searchCollections(decCollections, options.search);
                }
                const res = new list_response_ListResponse(decCollections.map((o) => new CollectionResponse(o)));
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    listOrganizationMembers(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationId == null || options.organizationId === "") {
                return Response.badRequest("`organizationid` option is required.");
            }
            if (!Utils.isGuid(options.organizationId)) {
                return Response.badRequest("`" + options.organizationId + "` is not a GUID.");
            }
            const organization = yield this.organizationService.getFromState(options.organizationId);
            if (organization == null) {
                return Response.error("Organization not found.");
            }
            try {
                const response = yield this.organizationUserService.getAllUsers(options.organizationId);
                const res = new list_response_ListResponse(response.data.map((r) => {
                    const u = new organization_user_response_OrganizationUserResponse();
                    u.email = r.email;
                    u.name = r.name;
                    u.id = r.id;
                    u.status = r.status;
                    u.type = r.type;
                    u.twoFactorEnabled = r.twoFactorEnabled;
                    return u;
                }));
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    listOrganizations(options) {
        return list_command_awaiter(this, void 0, void 0, function* () {
            let organizations = yield this.organizationService.getAll();
            if (options.search != null && options.search.trim() !== "") {
                organizations = CliUtils.searchOrganizations(organizations, options.search);
            }
            const res = new list_response_ListResponse(organizations.map((o) => new organization_response_OrganizationResponse(o)));
            return Response.success(res);
        });
    }
}
class list_command_Options {
    constructor(passedOptions) {
        this.organizationId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.organizationId);
        this.collectionId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.collectionid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.collectionId);
        this.folderId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.folderid) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.folderId);
        this.search = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.search;
        this.url = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.url;
        this.trash = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.trash);
    }
}

;// CONCATENATED MODULE: ./src/commands/restore.command.ts
var restore_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class RestoreCommand {
    constructor(cipherService) {
        this.cipherService = cipherService;
    }
    run(object, id) {
        return restore_command_awaiter(this, void 0, void 0, function* () {
            if (id != null) {
                id = id.toLowerCase();
            }
            switch (object.toLowerCase()) {
                case "item":
                    return yield this.restoreCipher(id);
                default:
                    return Response.badRequest("Unknown object.");
            }
        });
    }
    restoreCipher(id) {
        return restore_command_awaiter(this, void 0, void 0, function* () {
            const cipher = yield this.cipherService.get(id);
            if (cipher == null) {
                return Response.notFound();
            }
            if (cipher.deletedDate == null) {
                return Response.badRequest("Cipher is not in trash.");
            }
            try {
                yield this.cipherService.restoreWithServer(id);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/send/create.command.ts
var send_create_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};








class SendCreateCommand {
    constructor(sendService, stateService, environmentService) {
        this.sendService = sendService;
        this.stateService = stateService;
        this.environmentService = environmentService;
    }
    run(requestJson, cmdOptions) {
        return send_create_command_awaiter(this, void 0, void 0, function* () {
            let req = null;
            if (process.env.BW_SERVE !== "true" && (requestJson == null || requestJson === "")) {
                requestJson = yield CliUtils.readStdin();
            }
            if (requestJson == null || requestJson === "") {
                return Response.badRequest("`requestJson` was not provided.");
            }
            if (typeof requestJson !== "string") {
                req = requestJson;
                req.deletionDate = req.deletionDate == null ? null : new Date(req.deletionDate);
                req.expirationDate = req.expirationDate == null ? null : new Date(req.expirationDate);
            }
            else {
                try {
                    const reqJson = Buffer.from(requestJson, "base64").toString();
                    req = SendResponse.fromJson(reqJson);
                    if (req == null) {
                        throw new Error("Null request");
                    }
                }
                catch (e) {
                    return Response.badRequest("Error parsing the encoded request data.");
                }
            }
            if (req.deletionDate == null ||
                isNaN(new Date(req.deletionDate).getTime()) ||
                new Date(req.deletionDate) <= new Date()) {
                return Response.badRequest("Must specify a valid deletion date after the current time");
            }
            if (req.expirationDate != null && isNaN(new Date(req.expirationDate).getTime())) {
                return Response.badRequest("Unable to parse expirationDate: " + req.expirationDate);
            }
            const normalizedOptions = new send_create_command_Options(cmdOptions);
            return this.createSend(req, normalizedOptions);
        });
    }
    createSend(req, options) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        return send_create_command_awaiter(this, void 0, void 0, function* () {
            const filePath = (_b = (_a = req.file) === null || _a === void 0 ? void 0 : _a.fileName) !== null && _b !== void 0 ? _b : options.file;
            const text = (_d = (_c = req.text) === null || _c === void 0 ? void 0 : _c.text) !== null && _d !== void 0 ? _d : options.text;
            const hidden = (_f = (_e = req.text) === null || _e === void 0 ? void 0 : _e.hidden) !== null && _f !== void 0 ? _f : options.hidden;
            const password = (_g = req.password) !== null && _g !== void 0 ? _g : options.password;
            const maxAccessCount = (_h = req.maxAccessCount) !== null && _h !== void 0 ? _h : options.maxAccessCount;
            req.key = null;
            req.maxAccessCount = maxAccessCount;
            switch (req.type) {
                case SendType.File:
                    if (process.env.BW_SERVE === "true") {
                        return Response.error("Creating a file-based Send is unsupported through the `serve` command at this time.");
                    }
                    if (!(yield this.stateService.getCanAccessPremium())) {
                        return Response.error("Premium status is required to use this feature.");
                    }
                    if (filePath == null) {
                        return Response.badRequest("Must specify a file to Send either with the --file option or in the request JSON.");
                    }
                    req.file.fileName = external_path_namespaceObject.basename(filePath);
                    break;
                case SendType.Text:
                    if (text == null) {
                        return Response.badRequest("Must specify text content to Send either with the --text option or in the request JSON.");
                    }
                    req.text = new SendTextResponse();
                    req.text.text = text;
                    req.text.hidden = hidden;
                    break;
                default:
                    return Response.badRequest("Unknown Send type " + SendType[req.type] + ". Valid types are: file, text");
            }
            try {
                let fileBuffer = null;
                if (req.type === SendType.File) {
                    fileBuffer = NodeUtils.bufferToArrayBuffer(external_fs_namespaceObject.readFileSync(filePath));
                }
                const sendView = SendResponse.toView(req);
                const [encSend, fileData] = yield this.sendService.encrypt(sendView, fileBuffer, password);
                // Add dates from template
                encSend.deletionDate = sendView.deletionDate;
                encSend.expirationDate = sendView.expirationDate;
                yield this.sendService.saveWithServer([encSend, fileData]);
                const newSend = yield this.sendService.get(encSend.id);
                const decSend = yield newSend.decrypt();
                const res = new SendResponse(decSend, this.environmentService.getWebVaultUrl());
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}
class send_create_command_Options {
    constructor(passedOptions) {
        this.file = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.file;
        this.text = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.text;
        this.password = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.password;
        this.hidden = CliUtils.convertBooleanOption(passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.hidden);
        this.maxAccessCount =
            (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.maxAccessCount) != null ? parseInt(passedOptions.maxAccessCount, null) : null;
    }
}

;// CONCATENATED MODULE: ./src/commands/send/delete.command.ts
var send_delete_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

class SendDeleteCommand {
    constructor(sendService) {
        this.sendService = sendService;
    }
    run(id) {
        return send_delete_command_awaiter(this, void 0, void 0, function* () {
            const send = yield this.sendService.get(id);
            if (send == null) {
                return Response.notFound();
            }
            try {
                yield this.sendService.deleteWithServer(id);
                return Response.success();
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/send/edit.command.ts
var send_edit_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




class SendEditCommand {
    constructor(sendService, stateService, getCommand) {
        this.sendService = sendService;
        this.stateService = stateService;
        this.getCommand = getCommand;
    }
    run(requestJson, cmdOptions) {
        return send_edit_command_awaiter(this, void 0, void 0, function* () {
            if (process.env.BW_SERVE !== "true" && (requestJson == null || requestJson === "")) {
                requestJson = yield CliUtils.readStdin();
            }
            if (requestJson == null || requestJson === "") {
                return Response.badRequest("`requestJson` was not provided.");
            }
            let req = null;
            if (typeof requestJson !== "string") {
                req = requestJson;
                req.deletionDate = req.deletionDate == null ? null : new Date(req.deletionDate);
                req.expirationDate = req.expirationDate == null ? null : new Date(req.expirationDate);
            }
            else {
                try {
                    const reqJson = Buffer.from(requestJson, "base64").toString();
                    req = SendResponse.fromJson(reqJson);
                }
                catch (e) {
                    return Response.badRequest("Error parsing the encoded request data.");
                }
            }
            const normalizedOptions = new send_edit_command_Options(cmdOptions);
            req.id = normalizedOptions.itemId || req.id;
            if (req.id != null) {
                req.id = req.id.toLowerCase();
            }
            const send = yield this.sendService.get(req.id);
            if (send == null) {
                return Response.notFound();
            }
            if (send.type !== req.type) {
                return Response.badRequest("Cannot change a Send's type");
            }
            if (send.type === SendType.File && !(yield this.stateService.getCanAccessPremium())) {
                return Response.error("Premium status is required to use this feature.");
            }
            let sendView = yield send.decrypt();
            sendView = SendResponse.toView(req, sendView);
            if (typeof req.password !== "string" || req.password === "") {
                req.password = null;
            }
            try {
                const [encSend, encFileData] = yield this.sendService.encrypt(sendView, null, req.password);
                // Add dates from template
                encSend.deletionDate = sendView.deletionDate;
                encSend.expirationDate = sendView.expirationDate;
                yield this.sendService.saveWithServer([encSend, encFileData]);
            }
            catch (e) {
                return Response.error(e);
            }
            return yield this.getCommand.run(send.id, {});
        });
    }
}
class send_edit_command_Options {
    constructor(passedOptions) {
        this.itemId = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemId) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.itemid);
    }
}

;// CONCATENATED MODULE: ./src/commands/send/get.command.ts
var send_get_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




class SendGetCommand extends DownloadCommand {
    constructor(sendService, environmentService, searchService, cryptoService) {
        super(cryptoService);
        this.sendService = sendService;
        this.environmentService = environmentService;
        this.searchService = searchService;
    }
    run(id, options) {
        return send_get_command_awaiter(this, void 0, void 0, function* () {
            const serveCommand = process.env.BW_SERVE === "true";
            if (serveCommand && !Utils.isGuid(id)) {
                return Response.badRequest("`" + id + "` is not a GUID.");
            }
            let sends = yield this.getSendView(id);
            if (sends == null) {
                return Response.notFound();
            }
            const webVaultUrl = this.environmentService.getWebVaultUrl();
            let filter = (s) => true;
            let selector = (s) => send_get_command_awaiter(this, void 0, void 0, function* () { return Response.success(new SendResponse(s, webVaultUrl)); });
            if (!serveCommand && (options === null || options === void 0 ? void 0 : options.text) != null) {
                filter = (s) => {
                    return filter(s) && s.text != null;
                };
                selector = (s) => send_get_command_awaiter(this, void 0, void 0, function* () {
                    // Write to stdout and response success so we get the text string only to stdout
                    process.stdout.write(s.text.text);
                    return Response.success();
                });
            }
            if (Array.isArray(sends)) {
                if (filter != null) {
                    sends = sends.filter(filter);
                }
                if (sends.length > 1) {
                    return Response.multipleResults(sends.map((s) => s.id));
                }
                if (sends.length > 0) {
                    return selector(sends[0]);
                }
                else {
                    return Response.notFound();
                }
            }
            return selector(sends);
        });
    }
    getSendView(id) {
        return send_get_command_awaiter(this, void 0, void 0, function* () {
            if (Utils.isGuid(id)) {
                const send = yield this.sendService.get(id);
                if (send != null) {
                    return yield send.decrypt();
                }
            }
            else if (id.trim() !== "") {
                let sends = yield this.sendService.getAllDecrypted();
                sends = this.searchService.searchSends(sends, id);
                if (sends.length > 1) {
                    return sends;
                }
                else if (sends.length > 0) {
                    return sends[0];
                }
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/send/list.command.ts
var send_list_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class SendListCommand {
    constructor(sendService, environmentService, searchService) {
        this.sendService = sendService;
        this.environmentService = environmentService;
        this.searchService = searchService;
    }
    run(cmdOptions) {
        return send_list_command_awaiter(this, void 0, void 0, function* () {
            let sends = yield this.sendService.getAllDecrypted();
            const normalizedOptions = new send_list_command_Options(cmdOptions);
            if (normalizedOptions.search != null && normalizedOptions.search.trim() !== "") {
                sends = this.searchService.searchSends(sends, normalizedOptions.search);
            }
            const webVaultUrl = this.environmentService.getWebVaultUrl();
            const res = new list_response_ListResponse(sends.map((s) => new SendResponse(s, webVaultUrl)));
            return Response.success(res);
        });
    }
}
class send_list_command_Options {
    constructor(passedOptions) {
        this.search = passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.search;
    }
}

;// CONCATENATED MODULE: ./src/commands/send/remove-password.command.ts
var remove_password_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


class SendRemovePasswordCommand {
    constructor(sendService) {
        this.sendService = sendService;
    }
    run(id) {
        return remove_password_command_awaiter(this, void 0, void 0, function* () {
            try {
                yield this.sendService.removePasswordWithServer(id);
                const updatedSend = yield this.sendService.get(id);
                const decSend = yield updatedSend.decrypt();
                const res = new SendResponse(decSend);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/share.command.ts
var share_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class ShareCommand {
    constructor(cipherService) {
        this.cipherService = cipherService;
    }
    run(id, organizationId, requestJson) {
        return share_command_awaiter(this, void 0, void 0, function* () {
            if (process.env.BW_SERVE !== "true" && (requestJson == null || requestJson === "")) {
                requestJson = yield CliUtils.readStdin();
            }
            if (requestJson == null || requestJson === "") {
                return Response.badRequest("`requestJson` was not provided.");
            }
            let req = [];
            if (typeof requestJson !== "string") {
                req = requestJson;
            }
            else {
                try {
                    const reqJson = Buffer.from(requestJson, "base64").toString();
                    req = JSON.parse(reqJson);
                    if (req == null || req.length === 0) {
                        return Response.badRequest("You must provide at least one collection id for this item.");
                    }
                }
                catch (e) {
                    return Response.badRequest("Error parsing the encoded request data.");
                }
            }
            if (id != null) {
                id = id.toLowerCase();
            }
            if (organizationId != null) {
                organizationId = organizationId.toLowerCase();
            }
            const cipher = yield this.cipherService.get(id);
            if (cipher == null) {
                return Response.notFound();
            }
            if (cipher.organizationId != null) {
                return Response.badRequest("This item already belongs to an organization.");
            }
            const cipherView = yield cipher.decrypt();
            try {
                yield this.cipherService.shareWithServer(cipherView, organizationId, req);
                const updatedCipher = yield this.cipherService.get(cipher.id);
                const decCipher = yield updatedCipher.decrypt();
                const res = new CipherResponse(decCipher);
                return Response.success(res);
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/status.command.ts
var status_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class StatusCommand {
    constructor(envService, syncService, stateService, authService) {
        this.envService = envService;
        this.syncService = syncService;
        this.stateService = stateService;
        this.authService = authService;
    }
    run() {
        return status_command_awaiter(this, void 0, void 0, function* () {
            try {
                const baseUrl = this.baseUrl();
                const status = yield this.status();
                const lastSync = yield this.syncService.getLastSync();
                const userId = yield this.stateService.getUserId();
                const email = yield this.stateService.getEmail();
                return Response.success(new TemplateResponse({
                    serverUrl: baseUrl,
                    lastSync: lastSync,
                    userEmail: email,
                    userId: userId,
                    status: status,
                }));
            }
            catch (e) {
                return Response.error(e);
            }
        });
    }
    baseUrl() {
        return this.envService.getUrls().base;
    }
    status() {
        return status_command_awaiter(this, void 0, void 0, function* () {
            const authStatus = yield this.authService.getAuthStatus();
            if (authStatus === AuthenticationStatus.Unlocked) {
                return "unlocked";
            }
            else if (authStatus === AuthenticationStatus.Locked) {
                return "locked";
            }
            else {
                return "unauthenticated";
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/convert-to-key-connector.command.ts
var convert_to_key_connector_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class ConvertToKeyConnectorCommand {
    constructor(keyConnectorService, environmentService, syncService, organizationApiService, logout) {
        this.keyConnectorService = keyConnectorService;
        this.environmentService = environmentService;
        this.syncService = syncService;
        this.organizationApiService = organizationApiService;
        this.logout = logout;
    }
    run() {
        return convert_to_key_connector_command_awaiter(this, void 0, void 0, function* () {
            // If no interaction available, alert user to use web vault
            const canInteract = process.env.BW_NOINTERACTION !== "true";
            if (!canInteract) {
                yield this.logout();
                return Response.error(new MessageResponse("An organization you are a member of is using Key Connector. " +
                    "In order to access the vault, you must opt-in to Key Connector now via the web vault. You have been logged out.", null));
            }
            const organization = yield this.keyConnectorService.getManagingOrganization();
            const answer = yield external_inquirer_namespaceObject.createPromptModule({ output: process.stderr })({
                type: "list",
                name: "convert",
                message: organization.name +
                    " is using a self-hosted key server. A master password is no longer required to log in for members of this organization. ",
                choices: [
                    {
                        name: "Remove master password and unlock",
                        value: "remove",
                    },
                    {
                        name: "Leave organization and unlock",
                        value: "leave",
                    },
                    {
                        name: "Log out",
                        value: "exit",
                    },
                ],
            });
            if (answer.convert === "remove") {
                try {
                    yield this.keyConnectorService.migrateUser();
                }
                catch (e) {
                    yield this.logout();
                    throw e;
                }
                yield this.keyConnectorService.removeConvertAccountRequired();
                yield this.keyConnectorService.setUsesKeyConnector(true);
                // Update environment URL - required for api key login
                const urls = this.environmentService.getUrls();
                urls.keyConnector = organization.keyConnectorUrl;
                yield this.environmentService.setUrls(urls);
                return Response.success();
            }
            else if (answer.convert === "leave") {
                yield this.organizationApiService.leave(organization.id);
                yield this.keyConnectorService.removeConvertAccountRequired();
                return Response.success();
            }
            else {
                yield this.logout();
                return Response.error("You have been logged out.");
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/unlock.command.ts
var unlock_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};







class UnlockCommand {
    constructor(cryptoService, stateService, cryptoFunctionService, apiService, logService, keyConnectorService, environmentService, syncService, organizationApiService, logout) {
        this.cryptoService = cryptoService;
        this.stateService = stateService;
        this.cryptoFunctionService = cryptoFunctionService;
        this.apiService = apiService;
        this.logService = logService;
        this.keyConnectorService = keyConnectorService;
        this.environmentService = environmentService;
        this.syncService = syncService;
        this.organizationApiService = organizationApiService;
        this.logout = logout;
    }
    run(password, cmdOptions) {
        return unlock_command_awaiter(this, void 0, void 0, function* () {
            const normalizedOptions = new unlock_command_Options(cmdOptions);
            const passwordResult = yield CliUtils.getPassword(password, normalizedOptions, this.logService);
            if (passwordResult instanceof Response) {
                return passwordResult;
            }
            else {
                password = passwordResult;
            }
            yield this.setNewSessionKey();
            const email = yield this.stateService.getEmail();
            const kdf = yield this.stateService.getKdfType();
            const kdfConfig = yield this.stateService.getKdfConfig();
            const key = yield this.cryptoService.makeKey(password, email, kdf, kdfConfig);
            const storedKeyHash = yield this.cryptoService.getKeyHash();
            let passwordValid = false;
            if (key != null) {
                if (storedKeyHash != null) {
                    passwordValid = yield this.cryptoService.compareAndUpdateKeyHash(password, key);
                }
                else {
                    const serverKeyHash = yield this.cryptoService.hashPassword(password, key, HashPurpose.ServerAuthorization);
                    const request = new SecretVerificationRequest();
                    request.masterPasswordHash = serverKeyHash;
                    try {
                        yield this.apiService.postAccountVerifyPassword(request);
                        passwordValid = true;
                        const localKeyHash = yield this.cryptoService.hashPassword(password, key, HashPurpose.LocalAuthorization);
                        yield this.cryptoService.setKeyHash(localKeyHash);
                    }
                    catch (_a) {
                        // Ignore
                    }
                }
            }
            if (passwordValid) {
                yield this.cryptoService.setKey(key);
                if (yield this.keyConnectorService.getConvertAccountRequired()) {
                    const convertToKeyConnectorCommand = new ConvertToKeyConnectorCommand(this.keyConnectorService, this.environmentService, this.syncService, this.organizationApiService, this.logout);
                    const convertResponse = yield convertToKeyConnectorCommand.run();
                    if (!convertResponse.success) {
                        return convertResponse;
                    }
                }
                return this.successResponse();
            }
            else {
                return Response.error("Invalid master password.");
            }
        });
    }
    setNewSessionKey() {
        return unlock_command_awaiter(this, void 0, void 0, function* () {
            const key = yield this.cryptoFunctionService.randomBytes(64);
            process.env.BW_SESSION = Utils.fromBufferToB64(key);
        });
    }
    successResponse() {
        return unlock_command_awaiter(this, void 0, void 0, function* () {
            const res = new MessageResponse("Your vault is now unlocked!", "\n" +
                "To unlock your vault, set your session key to the `BW_SESSION` environment variable. ex:\n" +
                '$ export BW_SESSION="' +
                process.env.BW_SESSION +
                '"\n' +
                '> $env:BW_SESSION="' +
                process.env.BW_SESSION +
                '"\n\n' +
                "You can also pass the session key to any command with the `--session` option. ex:\n" +
                "$ bw list items --session " +
                process.env.BW_SESSION);
            res.raw = process.env.BW_SESSION;
            return Response.success(res);
        });
    }
}
class unlock_command_Options {
    constructor(passedOptions) {
        this.passwordEnv = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.passwordenv) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.passwordEnv);
        this.passwordFile = (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.passwordfile) || (passedOptions === null || passedOptions === void 0 ? void 0 : passedOptions.passwordFile);
    }
}

;// CONCATENATED MODULE: ./src/commands/serve.command.ts
var serve_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




























class ServeCommand {
    constructor(main) {
        this.main = main;
        this.getCommand = new GetCommand(this.main.cipherService, this.main.folderService, this.main.collectionService, this.main.totpService, this.main.auditService, this.main.cryptoService, this.main.stateService, this.main.searchService, this.main.apiService, this.main.organizationService);
        this.listCommand = new ListCommand(this.main.cipherService, this.main.folderService, this.main.collectionService, this.main.organizationService, this.main.searchService, this.main.organizationUserService, this.main.apiService);
        this.createCommand = new CreateCommand(this.main.cipherService, this.main.folderService, this.main.stateService, this.main.cryptoService, this.main.apiService, this.main.folderApiService);
        this.editCommand = new EditCommand(this.main.cipherService, this.main.folderService, this.main.cryptoService, this.main.apiService, this.main.folderApiService);
        this.generateCommand = new GenerateCommand(this.main.passwordGenerationService, this.main.stateService);
        this.syncCommand = new SyncCommand(this.main.syncService);
        this.statusCommand = new StatusCommand(this.main.environmentService, this.main.syncService, this.main.stateService, this.main.authService);
        this.deleteCommand = new DeleteCommand(this.main.cipherService, this.main.folderService, this.main.stateService, this.main.apiService, this.main.folderApiService);
        this.confirmCommand = new ConfirmCommand(this.main.apiService, this.main.cryptoService, this.main.organizationUserService);
        this.restoreCommand = new RestoreCommand(this.main.cipherService);
        this.shareCommand = new ShareCommand(this.main.cipherService);
        this.lockCommand = new LockCommand(this.main.vaultTimeoutService);
        this.unlockCommand = new UnlockCommand(this.main.cryptoService, this.main.stateService, this.main.cryptoFunctionService, this.main.apiService, this.main.logService, this.main.keyConnectorService, this.main.environmentService, this.main.syncService, this.main.organizationApiService, () => serve_command_awaiter(this, void 0, void 0, function* () { return yield this.main.logout(); }));
        this.sendCreateCommand = new SendCreateCommand(this.main.sendService, this.main.stateService, this.main.environmentService);
        this.sendDeleteCommand = new SendDeleteCommand(this.main.sendService);
        this.sendGetCommand = new SendGetCommand(this.main.sendService, this.main.environmentService, this.main.searchService, this.main.cryptoService);
        this.sendEditCommand = new SendEditCommand(this.main.sendService, this.main.stateService, this.sendGetCommand);
        this.sendListCommand = new SendListCommand(this.main.sendService, this.main.environmentService, this.main.searchService);
        this.sendRemovePasswordCommand = new SendRemovePasswordCommand(this.main.sendService);
    }
    run(options) {
        return serve_command_awaiter(this, void 0, void 0, function* () {
            const protectOrigin = !options.disableOriginProtection;
            const port = options.port || 8087;
            const hostname = options.hostname || "localhost";
            this.main.logService.info(`Starting server on ${hostname}:${port} with ${protectOrigin ? "origin protection" : "no origin protection"}`);
            const server = new external_koa_namespaceObject();
            const router = new router_namespaceObject();
            process.env.BW_SERVE = "true";
            process.env.BW_NOINTERACTION = "true";
            server
                .use((ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (protectOrigin && ctx.headers.origin != undefined) {
                    ctx.status = 403;
                    this.main.logService.warning(`Blocking request from "${Utils.isNullOrEmpty(ctx.headers.origin)
                        ? "(Origin header value missing)"
                        : ctx.headers.origin}"`);
                    return;
                }
                yield next();
            }))
                .use(external_koa_bodyparser_namespaceObject())
                .use(external_koa_json_namespaceObject({ pretty: false, param: "pretty" }));
            router.get("/generate", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                const response = yield this.generateCommand.run(ctx.request.query);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.get("/status", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                const response = yield this.statusCommand.run();
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.get("/list/object/:object", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                let response = null;
                if (ctx.params.object === "send") {
                    response = yield this.sendListCommand.run(ctx.request.query);
                }
                else {
                    response = yield this.listCommand.run(ctx.params.object, ctx.request.query);
                }
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.get("/send/list", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.sendListCommand.run(ctx.request.query);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/sync", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                const response = yield this.syncCommand.run(ctx.request.query);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/lock", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                const response = yield this.lockCommand.run();
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/unlock", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                const response = yield this.unlockCommand.run(ctx.request.body.password == null ? null : ctx.request.body.password, ctx.request.query);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/confirm/:object/:id", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.confirmCommand.run(ctx.params.object, ctx.params.id, ctx.request.query);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/restore/:object/:id", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.restoreCommand.run(ctx.params.object, ctx.params.id);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/move/:id/:organizationId", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.shareCommand.run(ctx.params.id, ctx.params.organizationId, ctx.request.body // TODO: Check the format of this body for an array of collection ids
                );
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/attachment", multer_namespaceObject().single("file"), (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.createCommand.run("attachment", ctx.request.body, ctx.request.query, {
                    fileBuffer: ctx.request.file.buffer,
                    fileName: ctx.request.file.originalname,
                });
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/send/:id/remove-password", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                const response = yield this.sendRemovePasswordCommand.run(ctx.params.id);
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.post("/object/:object", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                let response = null;
                if (ctx.params.object === "send") {
                    response = yield this.sendCreateCommand.run(ctx.request.body, ctx.request.query);
                }
                else {
                    response = yield this.createCommand.run(ctx.params.object, ctx.request.body, ctx.request.query);
                }
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.put("/object/:object/:id", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                let response = null;
                if (ctx.params.object === "send") {
                    ctx.request.body.id = ctx.params.id;
                    response = yield this.sendEditCommand.run(ctx.request.body, ctx.request.query);
                }
                else {
                    response = yield this.editCommand.run(ctx.params.object, ctx.params.id, ctx.request.body, ctx.request.query);
                }
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.get("/object/:object/:id", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                let response = null;
                if (ctx.params.object === "send") {
                    response = yield this.sendGetCommand.run(ctx.params.id, null);
                }
                else {
                    response = yield this.getCommand.run(ctx.params.object, ctx.params.id, ctx.request.query);
                }
                this.processResponse(ctx.response, response);
                yield next();
            }));
            router.delete("/object/:object/:id", (ctx, next) => serve_command_awaiter(this, void 0, void 0, function* () {
                if (yield this.errorIfLocked(ctx.response)) {
                    yield next();
                    return;
                }
                let response = null;
                if (ctx.params.object === "send") {
                    response = yield this.sendDeleteCommand.run(ctx.params.id);
                }
                else {
                    response = yield this.deleteCommand.run(ctx.params.object, ctx.params.id, ctx.request.query);
                }
                this.processResponse(ctx.response, response);
                yield next();
            }));
            server
                .use(router.routes())
                .use(router.allowedMethods())
                .listen(port, hostname === "all" ? null : hostname, () => {
                this.main.logService.info("Listening on " + hostname + ":" + port);
            });
        });
    }
    processResponse(res, commandResponse) {
        if (!commandResponse.success) {
            res.status = 400;
        }
        if (commandResponse.data instanceof FileResponse) {
            res.body = commandResponse.data.data;
            res.attachment(commandResponse.data.fileName);
            res.set("Content-Type", "application/octet-stream");
            res.set("Content-Length", commandResponse.data.data.length.toString());
        }
        else {
            res.body = commandResponse;
        }
    }
    errorIfLocked(res) {
        return serve_command_awaiter(this, void 0, void 0, function* () {
            const authed = yield this.main.stateService.getIsAuthenticated();
            if (!authed) {
                this.processResponse(res, Response.error("You are not logged in."));
                return true;
            }
            if (yield this.main.cryptoService.hasKeyInMemory()) {
                return false;
            }
            else if (yield this.main.cryptoService.hasKeyStored(KeySuffixOptions.Auto)) {
                // load key into memory
                yield this.main.cryptoService.getKey();
                return false;
            }
            this.processResponse(res, Response.error("Vault is locked."));
            return true;
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/update.command.ts
var update_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



const CLIENTS_RELEASE_LIST_ENDPOINT = "https://api.github.com/repos/bitwarden/clients/releases";
const DEFAULT_DOWNLOAD_URL = "https://github.com/bitwarden/clients/releases";
const UPDATE_COMMAND = "npm install -g @bitwarden/cli";
class UpdateCommand {
    constructor(platformUtilsService) {
        this.platformUtilsService = platformUtilsService;
        this.inPkg = false;
        this.inPkg = !!process.pkg;
    }
    run() {
        return update_command_awaiter(this, void 0, void 0, function* () {
            const response = yield external_node_fetch_default()(CLIENTS_RELEASE_LIST_ENDPOINT);
            if (response.status !== 200) {
                return Response.error("Error contacting update API: " + response.status);
            }
            const responseJson = yield response.json();
            const cliRelease = responseJson.find((r) => r.tag_name.includes("cli"));
            if (cliRelease === undefined || cliRelease === null) {
                return Response.error("Could not find latest CLI version.");
            }
            const currentVersion = yield this.platformUtilsService.getApplicationVersion();
            if (cliRelease.tag_name === "cli-v" + currentVersion) {
                const response = new MessageResponse(null, null);
                response.title = "No update available.";
                response.noColor = true;
                return Response.success(response);
            }
            const res = this.getFoundUpdateResponse(cliRelease);
            return Response.success(res);
        });
    }
    getFoundUpdateResponse(release) {
        const downloadUrl = this.getDownloadUrl(release.assets);
        const response = new MessageResponse(null, null);
        response.title = "A new version is available: " + release.tag_name;
        response.raw = downloadUrl;
        response.message = this.getMessage(release, downloadUrl);
        return response;
    }
    getMessage(release, downloadUrl) {
        let message = "";
        if (release.body != null && release.body !== "") {
            message = release.body + "\n\n";
        }
        message += "You can download this update at " + downloadUrl;
        if (this.inPkg) {
            message +=
                "\n\nIf you installed this CLI through a package manager " +
                    "you should probably update using its update command instead.";
        }
        else {
            message +=
                "\n\nIf you installed this CLI through NPM " +
                    "you should update using `" +
                    UPDATE_COMMAND +
                    "`";
        }
        return message;
    }
    getDownloadUrl(assets) {
        if (assets == null) {
            return DEFAULT_DOWNLOAD_URL;
        }
        let downloadUrl = DEFAULT_DOWNLOAD_URL;
        for (const a of assets) {
            const download = a.browser_download_url;
            if (download == null) {
                continue;
            }
            if (download.indexOf(".zip") === -1) {
                continue;
            }
            if (process.platform === "win32" && download.indexOf("bw-windows") > -1) {
                downloadUrl = download;
                break;
            }
            else if (process.platform === "darwin" && download.indexOf("bw-macos") > -1) {
                downloadUrl = download;
                break;
            }
            else if (process.platform === "linux" && download.indexOf("bw-linux") > -1) {
                downloadUrl = download;
                break;
            }
        }
        return downloadUrl;
    }
}

;// CONCATENATED MODULE: ./src/program.ts
var program_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



















const writeLn = CliUtils.writeLn;
class Program {
    constructor(main) {
        this.main = main;
    }
    register() {
        return program_awaiter(this, void 0, void 0, function* () {
            external_commander_namespaceObject.option("--pretty", "Format output. JSON is tabbed with two spaces.")
                .option("--raw", "Return raw output instead of a descriptive message.")
                .option("--response", "Return a JSON formatted version of response output.")
                .option("--cleanexit", "Exit with a success exit code (0) unless an error is thrown.")
                .option("--quiet", "Don't return anything to stdout.")
                .option("--nointeraction", "Do not prompt for interactive user input.")
                .option("--session <session>", "Pass session key instead of reading from env.")
                .version(yield this.main.platformUtilsService.getApplicationVersion(), "-v, --version");
            external_commander_namespaceObject.on("option:pretty", () => {
                process.env.BW_PRETTY = "true";
            });
            external_commander_namespaceObject.on("option:raw", () => {
                process.env.BW_RAW = "true";
            });
            external_commander_namespaceObject.on("option:quiet", () => {
                process.env.BW_QUIET = "true";
            });
            external_commander_namespaceObject.on("option:response", () => {
                process.env.BW_RESPONSE = "true";
            });
            external_commander_namespaceObject.on("option:cleanexit", () => {
                process.env.BW_CLEANEXIT = "true";
            });
            external_commander_namespaceObject.on("option:nointeraction", () => {
                process.env.BW_NOINTERACTION = "true";
            });
            external_commander_namespaceObject.on("option:session", (key) => {
                process.env.BW_SESSION = key;
            });
            external_commander_namespaceObject.on("command:*", () => {
                writeLn(external_chalk_namespaceObject.redBright("Invalid command: " + external_commander_namespaceObject.args.join(" ")), false, true);
                writeLn("See --help for a list of available commands.", true, true);
                process.exitCode = 1;
            });
            external_commander_namespaceObject.on("--help", () => {
                writeLn("\n  Examples:");
                writeLn("");
                writeLn("    bw login");
                writeLn("    bw lock");
                writeLn("    bw unlock myPassword321");
                writeLn("    bw list --help");
                writeLn("    bw list items --search google");
                writeLn("    bw get item 99ee88d2-6046-4ea7-92c2-acac464b1412");
                writeLn("    bw get password google.com");
                writeLn('    echo \'{"name":"My Folder"}\' | bw encode');
                writeLn("    bw create folder eyJuYW1lIjoiTXkgRm9sZGVyIn0K");
                writeLn("    bw edit folder c7c7b60b-9c61-40f2-8ccd-36c49595ed72 eyJuYW1lIjoiTXkgRm9sZGVyMiJ9Cg==");
                writeLn("    bw delete item 99ee88d2-6046-4ea7-92c2-acac464b1412");
                writeLn("    bw generate -lusn --length 18");
                writeLn("    bw config server https://bitwarden.example.com");
                writeLn("    bw send -f ./file.ext");
                writeLn('    bw send "text to send"');
                writeLn('    echo "text to send" | bw send');
                writeLn("    bw receive https://vault.bitwarden.com/#/send/rg3iuoS_Akm2gqy6ADRHmg/Ht7dYjsqjmgqUM3rjzZDSQ");
                writeLn("", true);
            });
            external_commander_namespaceObject.command("login [email] [password]")
                .description("Log into a user account.")
                .option("--method <method>", "Two-step login method.")
                .option("--code <code>", "Two-step login code.")
                .option("--sso", "Log in with Single-Sign On.")
                .option("--apikey", "Log in with an Api Key.")
                .option("--passwordenv <passwordenv>", "Environment variable storing your password")
                .option("--passwordfile <passwordfile>", "Path to a file containing your password as its first line")
                .option("--check", "Check login status.", () => program_awaiter(this, void 0, void 0, function* () {
                const authed = yield this.main.stateService.getIsAuthenticated();
                if (authed) {
                    const res = new MessageResponse("You are logged in!", null);
                    this.processResponse(Response.success(res), true);
                }
                this.processResponse(Response.error("You are not logged in."), true);
            }))
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    See docs for valid `method` enum values.");
                writeLn("");
                writeLn("    Pass `--raw` option to only return the session key.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw login");
                writeLn("    bw login john@example.com myPassword321 --raw");
                writeLn("    bw login john@example.com myPassword321 --method 1 --code 249213");
                writeLn("    bw login --sso");
                writeLn("", true);
            })
                .action((email, password, options) => program_awaiter(this, void 0, void 0, function* () {
                if (!options.check) {
                    yield this.exitIfAuthed();
                    const command = new LoginCommand(this.main.authService, this.main.apiService, this.main.cryptoFunctionService, this.main.environmentService, this.main.passwordGenerationService, this.main.platformUtilsService, this.main.stateService, this.main.cryptoService, this.main.policyService, this.main.twoFactorService, this.main.syncService, this.main.keyConnectorService, () => program_awaiter(this, void 0, void 0, function* () { return yield this.main.logout(); }));
                    const response = yield command.run(email, password, options);
                    this.processResponse(response);
                }
            }));
            external_commander_namespaceObject.command("logout")
                .description("Log out of the current user account.")
                .on("--help", () => {
                writeLn("\n  Examples:");
                writeLn("");
                writeLn("    bw logout");
                writeLn("", true);
            })
                .action((cmd) => program_awaiter(this, void 0, void 0, function* () {
                yield this.exitIfNotAuthed();
                const command = new LogoutCommand(this.main.authService, this.main.i18nService, () => program_awaiter(this, void 0, void 0, function* () { return yield this.main.logout(); }));
                const response = yield command.run();
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("lock")
                .description("Lock the vault and destroy active session keys.")
                .on("--help", () => {
                writeLn("\n  Examples:");
                writeLn("");
                writeLn("    bw lock");
                writeLn("", true);
            })
                .action((cmd) => program_awaiter(this, void 0, void 0, function* () {
                yield this.exitIfNotAuthed();
                if (yield this.main.keyConnectorService.getUsesKeyConnector()) {
                    const logoutCommand = new LogoutCommand(this.main.authService, this.main.i18nService, () => program_awaiter(this, void 0, void 0, function* () { return yield this.main.logout(); }));
                    yield logoutCommand.run();
                    this.processResponse(Response.error("You cannot lock your vault because you are using Key Connector. " +
                        "To protect your vault, you have been logged out."), true);
                    return;
                }
                const command = new LockCommand(this.main.vaultTimeoutService);
                const response = yield command.run();
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("unlock [password]")
                .description("Unlock the vault and return a new session key.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    After unlocking, any previous session keys will no longer be valid.");
                writeLn("");
                writeLn("    Pass `--raw` option to only return the session key.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw unlock");
                writeLn("    bw unlock myPassword321");
                writeLn("    bw unlock myPassword321 --raw");
                writeLn("", true);
            })
                .option("--check", "Check lock status.", () => program_awaiter(this, void 0, void 0, function* () {
                yield this.exitIfNotAuthed();
                const authStatus = yield this.main.authService.getAuthStatus();
                if (authStatus === AuthenticationStatus.Unlocked) {
                    const res = new MessageResponse("Vault is unlocked!", null);
                    this.processResponse(Response.success(res), true);
                }
                else {
                    this.processResponse(Response.error("Vault is locked."), true);
                }
            }))
                .option("--passwordenv <passwordenv>", "Environment variable storing your password")
                .option("--passwordfile <passwordfile>", "Path to a file containing your password as its first line")
                .action((password, cmd) => program_awaiter(this, void 0, void 0, function* () {
                if (!cmd.check) {
                    yield this.exitIfNotAuthed();
                    const command = new UnlockCommand(this.main.cryptoService, this.main.stateService, this.main.cryptoFunctionService, this.main.apiService, this.main.logService, this.main.keyConnectorService, this.main.environmentService, this.main.syncService, this.main.organizationApiService, () => program_awaiter(this, void 0, void 0, function* () { return yield this.main.logout(); }));
                    const response = yield command.run(password, cmd);
                    this.processResponse(response);
                }
            }));
            external_commander_namespaceObject.command("sync")
                .description("Pull the latest vault data from server.")
                .option("-f, --force", "Force a full sync.")
                .option("--last", "Get the last sync date.")
                .on("--help", () => {
                writeLn("\n  Examples:");
                writeLn("");
                writeLn("    bw sync");
                writeLn("    bw sync -f");
                writeLn("    bw sync --last");
                writeLn("", true);
            })
                .action((cmd) => program_awaiter(this, void 0, void 0, function* () {
                yield this.exitIfNotAuthed();
                const command = new SyncCommand(this.main.syncService);
                const response = yield command.run(cmd);
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("generate")
                .description("Generate a password/passphrase.")
                .option("-u, --uppercase", "Include uppercase characters.")
                .option("-l, --lowercase", "Include lowercase characters.")
                .option("-n, --number", "Include numeric characters.")
                .option("-s, --special", "Include special characters.")
                .option("-p, --passphrase", "Generate a passphrase.")
                .option("--length <length>", "Length of the password.")
                .option("--words <words>", "Number of words.")
                .option("--separator <separator>", "Word separator.")
                .option("-c, --capitalize", "Title case passphrase.")
                .option("--includeNumber", "Passphrase includes number.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    Default options are `-uln --length 14`.");
                writeLn("");
                writeLn("    Minimum `length` is 5.");
                writeLn("");
                writeLn("    Minimum `words` is 3.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw generate");
                writeLn("    bw generate -u -l --length 18");
                writeLn("    bw generate -ulns --length 25");
                writeLn("    bw generate -ul");
                writeLn("    bw generate -p --separator _");
                writeLn("    bw generate -p --words 5 --separator space");
                writeLn("", true);
            })
                .action((options) => program_awaiter(this, void 0, void 0, function* () {
                const command = new GenerateCommand(this.main.passwordGenerationService, this.main.stateService);
                const response = yield command.run(options);
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("encode")
                .description("Base 64 encode stdin.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    Use to create `encodedJson` for `create` and `edit` commands.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn('    echo \'{"name":"My Folder"}\' | bw encode');
                writeLn("", true);
            })
                .action(() => program_awaiter(this, void 0, void 0, function* () {
                const command = new EncodeCommand();
                const response = yield command.run();
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("config <setting> [value]")
                .description("Configure CLI settings.")
                .option("--web-vault <url>", "Provides a custom web vault URL that differs from the base URL.")
                .option("--api <url>", "Provides a custom API URL that differs from the base URL.")
                .option("--identity <url>", "Provides a custom identity URL that differs from the base URL.")
                .option("--icons <url>", "Provides a custom icons service URL that differs from the base URL.")
                .option("--notifications <url>", "Provides a custom notifications URL that differs from the base URL.")
                .option("--events <url>", "Provides a custom events URL that differs from the base URL.")
                .option("--key-connector <url>", "Provides the URL for your Key Connector server.")
                .on("--help", () => {
                writeLn("\n  Settings:");
                writeLn("");
                writeLn("    server - On-premises hosted installation URL.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw config server");
                writeLn("    bw config server https://bw.company.com");
                writeLn("    bw config server bitwarden.com");
                writeLn("    bw config server --api http://localhost:4000 --identity http://localhost:33656");
                writeLn("", true);
            })
                .action((setting, value, options) => program_awaiter(this, void 0, void 0, function* () {
                const command = new ConfigCommand(this.main.environmentService);
                const response = yield command.run(setting, value, options);
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("update")
                .description("Check for updates.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    Returns the URL to download the newest version of this CLI tool.");
                writeLn("");
                writeLn("    Use the `--raw` option to return only the download URL for the update.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw update");
                writeLn("    bw update --raw");
                writeLn("", true);
            })
                .action(() => program_awaiter(this, void 0, void 0, function* () {
                const command = new UpdateCommand(this.main.platformUtilsService);
                const response = yield command.run();
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("completion")
                .description("Generate shell completions.")
                .option("--shell <shell>", "Shell to generate completions for.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    Valid shells are `zsh`.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw completion --shell zsh");
                writeLn("", true);
            })
                .action((options, cmd) => program_awaiter(this, void 0, void 0, function* () {
                const command = new CompletionCommand();
                const response = yield command.run(options);
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("status")
                .description("Show server, last sync, user information, and vault status.")
                .on("--help", () => {
                writeLn("");
                writeLn("");
                writeLn("  Example return value:");
                writeLn("");
                writeLn("    {");
                writeLn('      "serverUrl": "https://bitwarden.example.com",');
                writeLn('      "lastSync": "2020-06-16T06:33:51.419Z",');
                writeLn('      "userEmail": "user@example.com,');
                writeLn('      "userId": "00000000-0000-0000-0000-000000000000",');
                writeLn('      "status": "locked"');
                writeLn("    }");
                writeLn("");
                writeLn("  Notes:");
                writeLn("");
                writeLn("  `status` is one of:");
                writeLn("    - `unauthenticated` when you are not logged in");
                writeLn("    - `locked` when you are logged in and the vault is locked");
                writeLn("    - `unlocked` when you are logged in and the vault is unlocked");
                writeLn("", true);
            })
                .action(() => program_awaiter(this, void 0, void 0, function* () {
                const command = new StatusCommand(this.main.environmentService, this.main.syncService, this.main.stateService, this.main.authService);
                const response = yield command.run();
                this.processResponse(response);
            }));
            external_commander_namespaceObject.command("serve")
                .description("Start a RESTful API webserver.")
                .option("--hostname <hostname>", "The hostname to bind your API webserver to.")
                .option("--port <port>", "The port to run your API webserver on.")
                .option("--disable-origin-protection", "If set, allows requests with origin header. Warning, this option exists for backwards compatibility reasons and exposes your environment to known CSRF attacks.")
                .on("--help", () => {
                writeLn("\n  Notes:");
                writeLn("");
                writeLn("    Default hostname is `localhost`.");
                writeLn("    Use hostname `all` for no hostname binding.");
                writeLn("    Default port is `8087`.");
                writeLn("");
                writeLn("  Examples:");
                writeLn("");
                writeLn("    bw serve");
                writeLn("    bw serve --port 8080");
                writeLn("    bw serve --hostname bwapi.mydomain.com --port 80");
                writeLn("", true);
            })
                .action((cmd) => program_awaiter(this, void 0, void 0, function* () {
                yield this.exitIfNotAuthed();
                const command = new ServeCommand(this.main);
                yield command.run(cmd);
            }));
        });
    }
    processResponse(response, exitImmediately = false) {
        if (!response.success) {
            if (process.env.BW_QUIET !== "true") {
                if (process.env.BW_RESPONSE === "true") {
                    writeLn(this.getJson(response), true, false);
                }
                else {
                    writeLn(external_chalk_namespaceObject.redBright(response.message), true, true);
                }
            }
            const exitCode = process.env.BW_CLEANEXIT ? 0 : 1;
            if (exitImmediately) {
                process.exit(exitCode);
            }
            else {
                process.exitCode = exitCode;
            }
            return;
        }
        if (process.env.BW_RESPONSE === "true") {
            writeLn(this.getJson(response), true, false);
        }
        else if (response.data != null) {
            let out = null;
            if (response.data.object === "template") {
                out = this.getJson(response.data.template);
            }
            if (out == null) {
                if (response.data.object === "string") {
                    const data = response.data.data;
                    if (data != null) {
                        out = data;
                    }
                }
                else if (response.data.object === "list") {
                    out = this.getJson(response.data.data);
                }
                else if (response.data.object === "message") {
                    out = this.getMessage(response);
                }
                else {
                    out = this.getJson(response.data);
                }
            }
            if (out != null && process.env.BW_QUIET !== "true") {
                writeLn(out, true, false);
            }
        }
        if (exitImmediately) {
            process.exit(0);
        }
        else {
            process.exitCode = 0;
        }
    }
    getJson(obj) {
        if (process.env.BW_PRETTY === "true") {
            return JSON.stringify(obj, null, "  ");
        }
        else {
            return JSON.stringify(obj);
        }
    }
    getMessage(response) {
        const message = response.data;
        if (process.env.BW_RAW === "true") {
            return message.raw;
        }
        let out = "";
        if (message.title != null) {
            if (message.noColor) {
                out = message.title;
            }
            else {
                out = external_chalk_namespaceObject.greenBright(message.title);
            }
        }
        if (message.message != null) {
            if (message.title != null) {
                out += "\n";
            }
            out += message.message;
        }
        return out.trim() === "" ? null : out;
    }
    exitIfAuthed() {
        return program_awaiter(this, void 0, void 0, function* () {
            const authed = yield this.main.stateService.getIsAuthenticated();
            if (authed) {
                const email = yield this.main.stateService.getEmail();
                this.processResponse(Response.error("You are already logged in as " + email + "."), true);
            }
        });
    }
    exitIfNotAuthed() {
        return program_awaiter(this, void 0, void 0, function* () {
            const authed = yield this.main.stateService.getIsAuthenticated();
            if (!authed) {
                this.processResponse(Response.error("You are not logged in."), true);
            }
        });
    }
    exitIfLocked() {
        return program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfNotAuthed();
            if (yield this.main.cryptoService.hasKeyInMemory()) {
                return;
            }
            else if (yield this.main.cryptoService.hasKeyStored(KeySuffixOptions.Auto)) {
                // load key into memory
                yield this.main.cryptoService.getKey();
            }
            else if (process.env.BW_NOINTERACTION !== "true") {
                // must unlock
                if (yield this.main.keyConnectorService.getUsesKeyConnector()) {
                    const response = Response.error("Your vault is locked. You must unlock your vault using your session key.\n" +
                        "If you do not have your session key, you can get a new one by logging out and logging in again.");
                    this.processResponse(response, true);
                }
                else {
                    const command = new UnlockCommand(this.main.cryptoService, this.main.stateService, this.main.cryptoFunctionService, this.main.apiService, this.main.logService, this.main.keyConnectorService, this.main.environmentService, this.main.syncService, this.main.organizationApiService, this.main.logout);
                    const response = yield command.run(null, null);
                    if (!response.success) {
                        this.processResponse(response, true);
                    }
                }
            }
            else {
                this.processResponse(Response.error("Vault is locked."), true);
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/view/send-access.view.ts


class SendAccessView {
    constructor(s) {
        this.id = null;
        this.name = null;
        this.type = null;
        this.text = new SendTextView();
        this.file = new SendFileView();
        this.expirationDate = null;
        this.creatorIdentifier = null;
        if (!s) {
            return;
        }
        this.id = s.id;
        this.type = s.type;
        this.expirationDate = s.expirationDate;
        this.creatorIdentifier = s.creatorIdentifier;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/domain/send-access.ts
var send_access_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class SendAccess extends Domain {
    constructor(obj) {
        super();
        if (obj == null) {
            return;
        }
        this.buildDomainModel(this, obj, {
            id: null,
            name: null,
            expirationDate: null,
            creatorIdentifier: null,
        }, ["id", "expirationDate", "creatorIdentifier"]);
        this.type = obj.type;
        switch (this.type) {
            case SendType.Text:
                this.text = new SendText(obj.text);
                break;
            case SendType.File:
                this.file = new SendFile(obj.file);
                break;
            default:
                break;
        }
    }
    decrypt(key) {
        return send_access_awaiter(this, void 0, void 0, function* () {
            const model = new SendAccessView(this);
            yield this.decryptObj(model, {
                name: null,
            }, null, key);
            switch (this.type) {
                case SendType.File:
                    model.file = yield this.file.decrypt(key);
                    break;
                case SendType.Text:
                    model.text = yield this.text.decrypt(key);
                    break;
                default:
                    break;
            }
            return model;
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/request/send-access.request.ts
class SendAccessRequest {
}

;// CONCATENATED MODULE: ./src/models/response/send-access.response.ts



class SendAccessResponse {
    constructor(o) {
        this.object = "send-access";
        if (o == null) {
            return;
        }
        this.id = o.id;
        this.name = o.name;
        this.type = o.type;
        if (o.type === SendType.Text && o.text != null) {
            this.text = new SendTextResponse(o.text);
        }
        if (o.type === SendType.File && o.file != null) {
            this.file = new SendFileResponse(o.file);
        }
    }
    static template() {
        const req = new SendAccessResponse();
        req.name = "Send name";
        req.type = SendType.Text;
        req.text = null;
        req.file = null;
        return req;
    }
}

;// CONCATENATED MODULE: ./src/commands/send/receive.command.ts
var receive_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};










class SendReceiveCommand extends DownloadCommand {
    constructor(apiService, cryptoService, cryptoFunctionService, platformUtilsService, environmentService) {
        super(cryptoService);
        this.apiService = apiService;
        this.cryptoFunctionService = cryptoFunctionService;
        this.platformUtilsService = platformUtilsService;
        this.environmentService = environmentService;
    }
    run(url, options) {
        var _a, _b;
        return receive_command_awaiter(this, void 0, void 0, function* () {
            this.canInteract = process.env.BW_NOINTERACTION !== "true";
            let urlObject;
            try {
                urlObject = new URL(url);
            }
            catch (e) {
                return Response.badRequest("Failed to parse the provided Send url");
            }
            const apiUrl = this.getApiUrl(urlObject);
            const [id, key] = this.getIdAndKey(urlObject);
            if (Utils.isNullOrWhitespace(id) || Utils.isNullOrWhitespace(key)) {
                return Response.badRequest("Failed to parse url, the url provided is not a valid Send url");
            }
            const keyArray = Utils.fromUrlB64ToArray(key);
            this.sendAccessRequest = new SendAccessRequest();
            let password = options.password;
            if (password == null || password === "") {
                if (options.passwordfile) {
                    password = yield NodeUtils.readFirstLine(options.passwordfile);
                }
                else if (options.passwordenv && process.env[options.passwordenv]) {
                    password = process.env[options.passwordenv];
                }
            }
            if (password != null && password !== "") {
                this.sendAccessRequest.password = yield this.getUnlockedPassword(password, keyArray);
            }
            const response = yield this.sendRequest(apiUrl, id, keyArray);
            if (response instanceof Response) {
                // Error scenario
                return response;
            }
            if (options.obj != null) {
                return Response.success(new SendAccessResponse(response));
            }
            switch (response.type) {
                case SendType.Text:
                    // Write to stdout and response success so we get the text string only to stdout
                    process.stdout.write((_a = response === null || response === void 0 ? void 0 : response.text) === null || _a === void 0 ? void 0 : _a.text);
                    return Response.success();
                case SendType.File: {
                    const downloadData = yield this.apiService.getSendFileDownloadData(response, this.sendAccessRequest, apiUrl);
                    return yield this.saveAttachmentToFile(downloadData.url, this.decKey, (_b = response === null || response === void 0 ? void 0 : response.file) === null || _b === void 0 ? void 0 : _b.fileName, options.output);
                }
                default:
                    return Response.success(new SendAccessResponse(response));
            }
        });
    }
    getIdAndKey(url) {
        const result = url.hash.slice(1).split("/").slice(-2);
        return [result[0], result[1]];
    }
    getApiUrl(url) {
        const urls = this.environmentService.getUrls();
        if (url.origin === "https://send.bitwarden.com") {
            return "https://vault.bitwarden.com/api";
        }
        else if (url.origin === urls.api) {
            return url.origin;
        }
        else if (this.platformUtilsService.isDev() && url.origin === urls.webVault) {
            return urls.api;
        }
        else {
            return url.origin + "/api";
        }
    }
    getUnlockedPassword(password, keyArray) {
        return receive_command_awaiter(this, void 0, void 0, function* () {
            const passwordHash = yield this.cryptoFunctionService.pbkdf2(password, keyArray, "sha256", 100000);
            return Utils.fromBufferToB64(passwordHash);
        });
    }
    sendRequest(url, id, key) {
        return receive_command_awaiter(this, void 0, void 0, function* () {
            try {
                const sendResponse = yield this.apiService.postSendAccess(id, this.sendAccessRequest, url);
                const sendAccess = new SendAccess(sendResponse);
                this.decKey = yield this.cryptoService.makeSendKey(key);
                return yield sendAccess.decrypt(this.decKey);
            }
            catch (e) {
                if (e instanceof ErrorResponse) {
                    if (e.statusCode === 401) {
                        if (this.canInteract) {
                            const answer = yield external_inquirer_namespaceObject.createPromptModule({
                                output: process.stderr,
                            })({
                                type: "password",
                                name: "password",
                                message: "Send password:",
                            });
                            // reattempt with new password
                            this.sendAccessRequest.password = yield this.getUnlockedPassword(answer.password, key);
                            return yield this.sendRequest(url, id, key);
                        }
                        return Response.badRequest("Incorrect or missing password");
                    }
                    else if (e.statusCode === 405) {
                        return Response.badRequest("Bad Request");
                    }
                    else if (e.statusCode === 404) {
                        return Response.notFound();
                    }
                }
                return Response.error(e);
            }
        });
    }
}

;// CONCATENATED MODULE: ./src/send.program.ts
var send_program_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




















const send_program_writeLn = CliUtils.writeLn;
class SendProgram extends Program {
    constructor(main) {
        super(main);
    }
    register() {
        return send_program_awaiter(this, void 0, void 0, function* () {
            external_commander_namespaceObject.addCommand(this.sendCommand());
            // receive is accessible both at `bw receive` and `bw send receive`
            external_commander_namespaceObject.addCommand(this.receiveCommand());
        });
    }
    sendCommand() {
        return new external_commander_namespaceObject.Command("send")
            .arguments("<data>")
            .description("Work with Bitwarden sends. A Send can be quickly created using this command or subcommands can be used to fine-tune the Send", {
            data: "The data to Send. Specify as a filepath with the --file option",
        })
            .option("-f, --file", "Specifies that <data> is a filepath")
            .option("-d, --deleteInDays <days>", "The number of days in the future to set deletion date, defaults to 7", "7")
            .option("-a, --maxAccessCount <amount>", "The amount of max possible accesses.")
            .option("--hidden", "Hide <data> in web by default. Valid only if --file is not set.")
            .option("-n, --name <name>", "The name of the Send. Defaults to a guid for text Sends and the filename for files.")
            .option("--notes <notes>", "Notes to add to the Send.")
            .option("--fullObject", "Specifies that the full Send object should be returned rather than just the access url.")
            .addCommand(this.listCommand())
            .addCommand(this.templateCommand())
            .addCommand(this.getCommand())
            .addCommand(this.receiveCommand())
            .addCommand(this.createCommand())
            .addCommand(this.editCommand())
            .addCommand(this.removePasswordCommand())
            .addCommand(this.deleteCommand())
            .action((data, options) => send_program_awaiter(this, void 0, void 0, function* () {
            const encodedJson = this.makeSendJson(data, options);
            let response;
            if (encodedJson instanceof Response) {
                response = encodedJson;
            }
            else {
                response = yield this.runCreate(encodedJson, options);
            }
            this.processResponse(response);
        }));
    }
    receiveCommand() {
        return new external_commander_namespaceObject.Command("receive")
            .arguments("<url>")
            .description("Access a Bitwarden Send from a url")
            .option("--password <password>", "Password needed to access the Send.")
            .option("--passwordenv <passwordenv>", "Environment variable storing the Send's password")
            .option("--passwordfile <passwordfile>", "Path to a file containing the Sends password as its first line")
            .option("--obj", "Return the Send's json object rather than the Send's content")
            .option("--output <location>", "Specify a file path to save a File-type Send to")
            .on("--help", () => {
            send_program_writeLn("");
            send_program_writeLn("If a password is required, the provided password is used or the user is prompted.");
            send_program_writeLn("", true);
        })
            .action((url, options) => send_program_awaiter(this, void 0, void 0, function* () {
            const cmd = new SendReceiveCommand(this.main.apiService, this.main.cryptoService, this.main.cryptoFunctionService, this.main.platformUtilsService, this.main.environmentService);
            const response = yield cmd.run(url, options);
            this.processResponse(response);
        }));
    }
    listCommand() {
        return new external_commander_namespaceObject.Command("list")
            .description("List all the Sends owned by you")
            .on("--help", () => {
            send_program_writeLn(external_chalk_namespaceObject("This is in the list command"));
        })
            .action((options) => send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const cmd = new SendListCommand(this.main.sendService, this.main.environmentService, this.main.searchService);
            const response = yield cmd.run(options);
            this.processResponse(response);
        }));
    }
    templateCommand() {
        return new external_commander_namespaceObject.Command("template")
            .arguments("<object>")
            .description("Get json templates for send objects", {
            object: "Valid objects are: send.text, send.file",
        })
            .action((object) => send_program_awaiter(this, void 0, void 0, function* () {
            const cmd = new GetCommand(this.main.cipherService, this.main.folderService, this.main.collectionService, this.main.totpService, this.main.auditService, this.main.cryptoService, this.main.stateService, this.main.searchService, this.main.apiService, this.main.organizationService);
            const response = yield cmd.run("template", object, null);
            this.processResponse(response);
        }));
    }
    getCommand() {
        return new external_commander_namespaceObject.Command("get")
            .arguments("<id>")
            .description("Get Sends owned by you.")
            .option("--output <output>", "Output directory or filename for attachment.")
            .option("--text", "Specifies to return the text content of a Send")
            .on("--help", () => {
            send_program_writeLn("");
            send_program_writeLn("  Id:");
            send_program_writeLn("");
            send_program_writeLn("    Search term or Send's globally unique `id`.");
            send_program_writeLn("");
            send_program_writeLn("    If raw output is specified and no output filename or directory is given for");
            send_program_writeLn("    an attachment query, the attachment content is written to stdout.");
            send_program_writeLn("");
            send_program_writeLn("  Examples:");
            send_program_writeLn("");
            send_program_writeLn("    bw send get searchText");
            send_program_writeLn("    bw send get id");
            send_program_writeLn("    bw send get searchText --text");
            send_program_writeLn("    bw send get searchText --file");
            send_program_writeLn("    bw send get searchText --file --output ../Photos/photo.jpg");
            send_program_writeLn("    bw send get searchText --file --raw");
            send_program_writeLn("", true);
        })
            .action((id, options) => send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const cmd = new SendGetCommand(this.main.sendService, this.main.environmentService, this.main.searchService, this.main.cryptoService);
            const response = yield cmd.run(id, options);
            this.processResponse(response);
        }));
    }
    createCommand() {
        return new external_commander_namespaceObject.Command("create")
            .arguments("[encodedJson]")
            .description("create a Send", {
            encodedJson: "JSON object to upload. Can also be piped in through stdin.",
        })
            .option("--file <path>", "file to Send. Can also be specified in parent's JSON.")
            .option("--text <text>", "text to Send. Can also be specified in parent's JSON.")
            .option("--hidden", "text hidden flag. Valid only with the --text option.")
            .option("--password <password>", "optional password to access this Send. Can also be specified in JSON")
            .on("--help", () => {
            send_program_writeLn("");
            send_program_writeLn("Note:");
            send_program_writeLn("  Options specified in JSON take precedence over command options");
            send_program_writeLn("", true);
        })
            .action((encodedJson, options, args) => send_program_awaiter(this, void 0, void 0, function* () {
            // Work-around to support `--fullObject` option for `send create --fullObject`
            // Calling `option('--fullObject', ...)` above won't work due to Commander doesn't like same option
            // to be defind on both parent-command and sub-command
            const { fullObject = false } = args.parent.opts();
            const mergedOptions = Object.assign(Object.assign({}, options), { fullObject: fullObject });
            const response = yield this.runCreate(encodedJson, mergedOptions);
            this.processResponse(response);
        }));
    }
    editCommand() {
        return new external_commander_namespaceObject.Command("edit")
            .arguments("[encodedJson]")
            .description("edit a Send", {
            encodedJson: "Updated JSON object to save. If not provided, encodedJson is read from stdin.",
        })
            .option("--itemid <itemid>", "Overrides the itemId provided in [encodedJson]")
            .on("--help", () => {
            send_program_writeLn("");
            send_program_writeLn("Note:");
            send_program_writeLn("  You cannot update a File-type Send's file. Just delete and remake it");
            send_program_writeLn("", true);
        })
            .action((encodedJson, options) => send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const getCmd = new SendGetCommand(this.main.sendService, this.main.environmentService, this.main.searchService, this.main.cryptoService);
            const cmd = new SendEditCommand(this.main.sendService, this.main.stateService, getCmd);
            const response = yield cmd.run(encodedJson, options);
            this.processResponse(response);
        }));
    }
    deleteCommand() {
        return new external_commander_namespaceObject.Command("delete")
            .arguments("<id>")
            .description("delete a Send", {
            id: "The id of the Send to delete.",
        })
            .action((id) => send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const cmd = new SendDeleteCommand(this.main.sendService);
            const response = yield cmd.run(id);
            this.processResponse(response);
        }));
    }
    removePasswordCommand() {
        return new external_commander_namespaceObject.Command("remove-password")
            .arguments("<id>")
            .description("removes the saved password from a Send.", {
            id: "The id of the Send to alter.",
        })
            .action((id) => send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const cmd = new SendRemovePasswordCommand(this.main.sendService);
            const response = yield cmd.run(id);
            this.processResponse(response);
        }));
    }
    makeSendJson(data, options) {
        var _a;
        let sendFile = null;
        let sendText = null;
        let name = Utils.newGuid();
        let type = SendType.Text;
        if (options.file != null) {
            data = external_path_namespaceObject.resolve(data);
            if (!external_fs_namespaceObject.existsSync(data)) {
                return Response.badRequest("data path does not exist");
            }
            sendFile = SendFileResponse.template(data);
            name = external_path_namespaceObject.basename(data);
            type = SendType.File;
        }
        else {
            sendText = SendTextResponse.template(data, options.hidden);
        }
        const template = Utils.assign(SendResponse.template(null, options.deleteInDays), {
            name: (_a = options.name) !== null && _a !== void 0 ? _a : name,
            notes: options.notes,
            file: sendFile,
            text: sendText,
            type: type,
        });
        return Buffer.from(JSON.stringify(template), "utf8").toString("base64");
    }
    runCreate(encodedJson, options) {
        return send_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const cmd = new SendCreateCommand(this.main.sendService, this.main.stateService, this.main.environmentService);
            return yield cmd.run(encodedJson, options);
        });
    }
}

;// CONCATENATED MODULE: external "child_process"
const external_child_process_namespaceObject = require("child_process");
;// CONCATENATED MODULE: ../../libs/common/src/enums/deviceType.ts
var DeviceType;
(function (DeviceType) {
    DeviceType[DeviceType["Android"] = 0] = "Android";
    DeviceType[DeviceType["iOS"] = 1] = "iOS";
    DeviceType[DeviceType["ChromeExtension"] = 2] = "ChromeExtension";
    DeviceType[DeviceType["FirefoxExtension"] = 3] = "FirefoxExtension";
    DeviceType[DeviceType["OperaExtension"] = 4] = "OperaExtension";
    DeviceType[DeviceType["EdgeExtension"] = 5] = "EdgeExtension";
    DeviceType[DeviceType["WindowsDesktop"] = 6] = "WindowsDesktop";
    DeviceType[DeviceType["MacOsDesktop"] = 7] = "MacOsDesktop";
    DeviceType[DeviceType["LinuxDesktop"] = 8] = "LinuxDesktop";
    DeviceType[DeviceType["ChromeBrowser"] = 9] = "ChromeBrowser";
    DeviceType[DeviceType["FirefoxBrowser"] = 10] = "FirefoxBrowser";
    DeviceType[DeviceType["OperaBrowser"] = 11] = "OperaBrowser";
    DeviceType[DeviceType["EdgeBrowser"] = 12] = "EdgeBrowser";
    DeviceType[DeviceType["IEBrowser"] = 13] = "IEBrowser";
    DeviceType[DeviceType["UnknownBrowser"] = 14] = "UnknownBrowser";
    DeviceType[DeviceType["AndroidAmazon"] = 15] = "AndroidAmazon";
    DeviceType[DeviceType["UWP"] = 16] = "UWP";
    DeviceType[DeviceType["SafariBrowser"] = 17] = "SafariBrowser";
    DeviceType[DeviceType["VivaldiBrowser"] = 18] = "VivaldiBrowser";
    DeviceType[DeviceType["VivaldiExtension"] = 19] = "VivaldiExtension";
    DeviceType[DeviceType["SafariExtension"] = 20] = "SafariExtension";
})(DeviceType || (DeviceType = {}));

;// CONCATENATED MODULE: ./src/services/cli-platform-utils.service.ts
var cli_platform_utils_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


// eslint-disable-next-line
const cli_platform_utils_service_open = __webpack_require__(634);
class CliPlatformUtilsService {
    constructor(clientType, packageJson) {
        this.packageJson = packageJson;
        this.deviceCache = null;
        this.clientType = clientType;
    }
    getDevice() {
        if (!this.deviceCache) {
            switch (process.platform) {
                case "win32":
                    this.deviceCache = DeviceType.WindowsDesktop;
                    break;
                case "darwin":
                    this.deviceCache = DeviceType.MacOsDesktop;
                    break;
                case "linux":
                default:
                    this.deviceCache = DeviceType.LinuxDesktop;
                    break;
            }
        }
        return this.deviceCache;
    }
    getDeviceString() {
        const device = DeviceType[this.getDevice()].toLowerCase();
        return device.replace("desktop", "");
    }
    getClientType() {
        return this.clientType;
    }
    isFirefox() {
        return false;
    }
    isChrome() {
        return false;
    }
    isEdge() {
        return false;
    }
    isOpera() {
        return false;
    }
    isVivaldi() {
        return false;
    }
    isSafari() {
        return false;
    }
    isMacAppStore() {
        return false;
    }
    isViewOpen() {
        return Promise.resolve(false);
    }
    launchUri(uri, options) {
        if (process.platform === "linux") {
            external_child_process_namespaceObject.spawnSync("xdg-open", [uri]);
        }
        else {
            cli_platform_utils_service_open(uri);
        }
    }
    getApplicationVersion() {
        return Promise.resolve(this.packageJson.version);
    }
    getApplicationVersionNumber() {
        return cli_platform_utils_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.getApplicationVersion()).split(RegExp("[+|-]"))[0].trim();
        });
    }
    getApplicationVersionSync() {
        return this.packageJson.version;
    }
    supportsWebAuthn(win) {
        return false;
    }
    supportsDuo() {
        return false;
    }
    showToast(type, title, text, options) {
        throw new Error("Not implemented.");
    }
    showDialog(text, title, confirmText, cancelText, type) {
        throw new Error("Not implemented.");
    }
    isDev() {
        return "production" === "development";
    }
    isSelfHost() {
        return false;
    }
    copyToClipboard(text, options) {
        throw new Error("Not implemented.");
    }
    readFromClipboard(options) {
        throw new Error("Not implemented.");
    }
    supportsBiometric() {
        return Promise.resolve(false);
    }
    authenticateBiometric() {
        return Promise.resolve(false);
    }
    supportsSecureStorage() {
        return false;
    }
}

;// CONCATENATED MODULE: ./src/services/console-log.service.ts

class ConsoleLogService extends consoleLog_service_ConsoleLogService {
    constructor(isDev, filter = null) {
        super(isDev, filter);
    }
    write(level, message) {
        if (this.filter != null && this.filter(level)) {
            return;
        }
        if (process.env.BW_RESPONSE === "true") {
            // eslint-disable-next-line
            console.error(message);
            return;
        }
        super.write(level, message);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/translation.service.ts
var translation_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class TranslationService {
    constructor(systemLanguage, localesDirectory, getLocalesJson) {
        this.systemLanguage = systemLanguage;
        this.localesDirectory = localesDirectory;
        this.getLocalesJson = getLocalesJson;
        // First locale is the default (English)
        this.supportedTranslationLocales = ["en"];
        this.defaultLocale = "en";
        this.localeNames = new Map([
            ["af", "Afrikaans"],
            ["ar", "العربية الفصحى"],
            ["az", "Azərbaycanca"],
            ["be", "Беларуская"],
            ["bg", "български"],
            ["bn", "বাংলা"],
            ["bs", "bosanski jezik"],
            ["ca", "català"],
            ["cs", "čeština"],
            ["da", "dansk"],
            ["de", "Deutsch"],
            ["el", "Ελληνικά"],
            ["en", "English"],
            ["en-GB", "English (British)"],
            ["en-IN", "English (India)"],
            ["eo", "Esperanto"],
            ["es", "español"],
            ["et", "eesti"],
            ["eu", "euskara"],
            ["fa", "فارسی"],
            ["fi", "suomi"],
            ["fil", "Wikang Filipino"],
            ["fr", "français"],
            ["he", "עברית"],
            ["hi", "हिन्दी"],
            ["hr", "hrvatski"],
            ["hu", "magyar"],
            ["id", "Bahasa Indonesia"],
            ["it", "italiano"],
            ["ja", "日本語"],
            ["ka", "ქართული"],
            ["km", "ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ"],
            ["kn", "ಕನ್ನಡ"],
            ["ko", "한국어"],
            ["lt", "lietuvių kalba"],
            ["lv", "Latvietis"],
            ["me", "црногорски"],
            ["ml", "മലയാളം"],
            ["nb", "norsk (bokmål)"],
            ["nl", "Nederlands"],
            ["nn", "Norsk Nynorsk"],
            ["pl", "polski"],
            ["pt-BR", "português do Brasil"],
            ["pt-PT", "português"],
            ["ro", "română"],
            ["ru", "русский"],
            ["si", "සිංහල"],
            ["sk", "slovenčina"],
            ["sl", "Slovenski jezik, Slovenščina"],
            ["sr", "Српски"],
            ["sv", "svenska"],
            ["th", "ไทย"],
            ["tr", "Türkçe"],
            ["uk", "українська"],
            ["vi", "Tiếng Việt"],
            ["zh-CN", "中文（中国大陆）"],
            ["zh-TW", "中文（台灣）"],
        ]);
        this.defaultMessages = {};
        this.localeMessages = {};
        this.systemLanguage = systemLanguage.replace("_", "-");
    }
    init(locale) {
        return translation_service_awaiter(this, void 0, void 0, function* () {
            if (this.inited) {
                throw new Error("i18n already initialized.");
            }
            if (this.supportedTranslationLocales == null || this.supportedTranslationLocales.length === 0) {
                throw new Error("supportedTranslationLocales not set.");
            }
            this.inited = true;
            this.translationLocale = locale != null ? locale : this.systemLanguage;
            try {
                this.collator = new Intl.Collator(this.translationLocale, {
                    numeric: true,
                    sensitivity: "base",
                });
            }
            catch (_a) {
                this.collator = null;
            }
            if (this.supportedTranslationLocales.indexOf(this.translationLocale) === -1) {
                this.translationLocale = this.translationLocale.slice(0, 2);
                if (this.supportedTranslationLocales.indexOf(this.translationLocale) === -1) {
                    this.translationLocale = this.defaultLocale;
                }
            }
            if (this.localesDirectory != null) {
                yield this.loadMessages(this.translationLocale, this.localeMessages);
                if (this.translationLocale !== this.defaultLocale) {
                    yield this.loadMessages(this.defaultLocale, this.defaultMessages);
                }
            }
        });
    }
    t(id, p1, p2, p3) {
        return this.translate(id, p1, p2, p3);
    }
    translate(id, p1, p2, p3) {
        let result;
        // eslint-disable-next-line
        if (this.localeMessages.hasOwnProperty(id) && this.localeMessages[id]) {
            result = this.localeMessages[id];
            // eslint-disable-next-line
        }
        else if (this.defaultMessages.hasOwnProperty(id) && this.defaultMessages[id]) {
            result = this.defaultMessages[id];
        }
        else {
            result = "";
        }
        if (result !== "") {
            if (p1 != null) {
                result = result.split("__$1__").join(p1.toString());
            }
            if (p2 != null) {
                result = result.split("__$2__").join(p2.toString());
            }
            if (p3 != null) {
                result = result.split("__$3__").join(p3.toString());
            }
        }
        return result;
    }
    loadMessages(locale, messagesObj) {
        return translation_service_awaiter(this, void 0, void 0, function* () {
            const formattedLocale = locale.replace("-", "_");
            const locales = yield this.getLocalesJson(formattedLocale);
            for (const prop in locales) {
                // eslint-disable-next-line
                if (!locales.hasOwnProperty(prop)) {
                    continue;
                }
                messagesObj[prop] = locales[prop].message;
                if (locales[prop].placeholders) {
                    for (const placeProp in locales[prop].placeholders) {
                        if (!locales[prop].placeholders.hasOwnProperty(placeProp) || // eslint-disable-line
                            !locales[prop].placeholders[placeProp].content) {
                            continue;
                        }
                        const replaceToken = "\\$" + placeProp.toUpperCase() + "\\$";
                        let replaceContent = locales[prop].placeholders[placeProp].content;
                        if (replaceContent === "$1" || replaceContent === "$2" || replaceContent === "$3") {
                            replaceContent = "__$" + replaceContent + "__";
                        }
                        messagesObj[prop] = messagesObj[prop].replace(new RegExp(replaceToken, "g"), replaceContent);
                    }
                }
            }
        });
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/i18n.service.ts


class i18n_service_I18nService extends TranslationService {
    constructor(systemLanguage, localesDirectory, getLocalesJson) {
        super(systemLanguage, localesDirectory, getLocalesJson);
        this.systemLanguage = systemLanguage;
        this.localesDirectory = localesDirectory;
        this.getLocalesJson = getLocalesJson;
        this._locale = new external_rxjs_namespaceObject.ReplaySubject(1);
        this.locale$ = this._locale.asObservable();
    }
    get translationLocale() {
        return this._translationLocale;
    }
    set translationLocale(locale) {
        this._translationLocale = locale;
        this._locale.next(locale);
    }
}

;// CONCATENATED MODULE: ./src/services/i18n.service.ts



class I18nService extends i18n_service_I18nService {
    constructor(systemLanguage, localesDirectory) {
        super(systemLanguage, localesDirectory, (formattedLocale) => {
            const filePath = external_path_namespaceObject.join(__dirname, this.localesDirectory + "/" + formattedLocale + "/messages.json");
            const localesJson = external_fs_namespaceObject.readFileSync(filePath, "utf8");
            const locales = JSON.parse(localesJson.replace(/^\uFEFF/, "")); // strip the BOM
            return Promise.resolve(locales);
        });
        this.supportedTranslationLocales = ["en"];
    }
}

;// CONCATENATED MODULE: external "lowdb"
const external_lowdb_namespaceObject = require("lowdb");
;// CONCATENATED MODULE: external "lowdb/adapters/FileSync"
const FileSync_namespaceObject = require("lowdb/adapters/FileSync");
;// CONCATENATED MODULE: external "proper-lockfile"
const external_proper_lockfile_namespaceObject = require("proper-lockfile");
;// CONCATENATED MODULE: ./src/services/lowdb-storage.service.ts
var lowdb_storage_service_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var lowdb_storage_service_metadata = (undefined && undefined.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var lowdb_storage_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};








const retries = {
    retries: 50,
    minTimeout: 100,
    maxTimeout: 250,
    factor: 2,
};
class LowdbStorageService {
    constructor(logService, defaults, dir, allowCache = false, requireLock = false) {
        this.logService = logService;
        this.dir = dir;
        this.allowCache = allowCache;
        this.requireLock = requireLock;
        this.ready = false;
        this.defaults = defaults;
    }
    init() {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            if (this.ready) {
                return;
            }
            this.logService.info("Initializing lowdb storage service.");
            let adapter;
            if (Utils.isNode && this.dir != null) {
                if (!external_fs_namespaceObject.existsSync(this.dir)) {
                    this.logService.warning(`Could not find dir, "${this.dir}"; creating it instead.`);
                    NodeUtils.mkdirpSync(this.dir, "700");
                    this.logService.info(`Created dir "${this.dir}".`);
                }
                this.dataFilePath = external_path_namespaceObject.join(this.dir, "data.json");
                if (!external_fs_namespaceObject.existsSync(this.dataFilePath)) {
                    this.logService.warning(`Could not find data file, "${this.dataFilePath}"; creating it instead.`);
                    external_fs_namespaceObject.writeFileSync(this.dataFilePath, "", { mode: 0o600 });
                    external_fs_namespaceObject.chmodSync(this.dataFilePath, 0o600);
                    this.logService.info(`Created data file "${this.dataFilePath}" with chmod 600.`);
                }
                else {
                    this.logService.info(`db file "${this.dataFilePath} already exists"; using existing db`);
                }
                yield this.lockDbFile(() => {
                    adapter = new FileSync_namespaceObject(this.dataFilePath);
                });
            }
            try {
                this.logService.info("Attempting to create lowdb storage adapter.");
                this.db = external_lowdb_namespaceObject(adapter);
                this.logService.info("Successfully created lowdb storage adapter.");
            }
            catch (e) {
                if (e instanceof SyntaxError) {
                    this.logService.warning(`Error creating lowdb storage adapter, "${e.message}"; emptying data file.`);
                    if (external_fs_namespaceObject.existsSync(this.dataFilePath)) {
                        const backupPath = this.dataFilePath + ".bak";
                        this.logService.warning(`Writing backup of data file to ${backupPath}`);
                        yield external_fs_namespaceObject.copyFile(this.dataFilePath, backupPath, () => {
                            this.logService.warning(`Error while creating data file backup, "${e.message}". No backup may have been created.`);
                        });
                    }
                    adapter.write({});
                    this.db = external_lowdb_namespaceObject(adapter);
                }
                else {
                    this.logService.error(`Error creating lowdb storage adapter, "${e.message}".`);
                    throw e;
                }
            }
            if (this.defaults != null) {
                this.lockDbFile(() => {
                    this.logService.info("Writing defaults.");
                    this.readForNoCache();
                    this.db.defaults(this.defaults).write();
                    this.logService.info("Successfully wrote defaults to db.");
                });
            }
            this.ready = true;
        });
    }
    get(key) {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            yield this.waitForReady();
            return this.lockDbFile(() => {
                this.readForNoCache();
                const val = this.db.get(key).value();
                this.logService.debug(`Successfully read ${key} from db`);
                if (val == null) {
                    return null;
                }
                return val;
            });
        });
    }
    has(key) {
        return this.get(key).then((v) => v != null);
    }
    save(key, obj) {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            yield this.waitForReady();
            return this.lockDbFile(() => {
                this.readForNoCache();
                this.db.set(key, obj).write();
                this.logService.debug(`Successfully wrote ${key} to db`);
                return;
            });
        });
    }
    remove(key) {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            yield this.waitForReady();
            return this.lockDbFile(() => {
                this.readForNoCache();
                this.db.unset(key).write();
                this.logService.debug(`Successfully removed ${key} from db`);
                return;
            });
        });
    }
    lockDbFile(action) {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            if (this.requireLock && !Utils.isNullOrWhitespace(this.dataFilePath)) {
                this.logService.info("acquiring db file lock");
                return yield external_proper_lockfile_namespaceObject.lock(this.dataFilePath, { retries: retries }).then((release) => {
                    try {
                        return action();
                    }
                    finally {
                        release();
                    }
                });
            }
            else {
                return action();
            }
        });
    }
    readForNoCache() {
        if (!this.allowCache) {
            this.db.read();
        }
    }
    waitForReady() {
        return lowdb_storage_service_awaiter(this, void 0, void 0, function* () {
            if (!this.ready) {
                yield this.init();
            }
        });
    }
}
lowdb_storage_service_decorate([
    sequentialize(() => "lowdbStorageInit"),
    lowdb_storage_service_metadata("design:type", Function),
    lowdb_storage_service_metadata("design:paramtypes", []),
    lowdb_storage_service_metadata("design:returntype", Promise)
], LowdbStorageService.prototype, "init", null);

;// CONCATENATED MODULE: external "form-data"
const external_form_data_namespaceObject = require("form-data");
;// CONCATENATED MODULE: external "https-proxy-agent"
const external_https_proxy_agent_namespaceObject = require("https-proxy-agent");
;// CONCATENATED MODULE: ../../libs/common/src/models/response/auth-request.response.ts

const RequestTimeOut = 60000 * 15; //15 Minutes
class AuthRequestResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.publicKey = this.getResponseProperty("PublicKey");
        this.requestDeviceType = this.getResponseProperty("RequestDeviceType");
        this.requestIpAddress = this.getResponseProperty("RequestIpAddress");
        this.key = this.getResponseProperty("Key");
        this.masterPasswordHash = this.getResponseProperty("MasterPasswordHash");
        this.creationDate = this.getResponseProperty("CreationDate");
        this.requestApproved = this.getResponseProperty("RequestApproved");
        this.requestFingerprint = this.getResponseProperty("RequestFingerprint");
        this.responseDate = this.getResponseProperty("ResponseDate");
        const requestDate = new Date(this.creationDate);
        const requestDateUTC = Date.UTC(requestDate.getUTCFullYear(), requestDate.getUTCMonth(), requestDate.getDate(), requestDate.getUTCHours(), requestDate.getUTCMinutes(), requestDate.getUTCSeconds(), requestDate.getUTCMilliseconds());
        const dateNow = new Date(Date.now());
        const dateNowUTC = Date.UTC(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds(), dateNow.getUTCMilliseconds());
        this.isExpired = dateNowUTC - requestDateUTC >= RequestTimeOut;
        this.isAnswered = this.requestApproved != null && this.responseDate != null;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/authentication/register.response.ts

class RegisterResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.captchaBypassToken = this.getResponseProperty("CaptchaBypassToken");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/billing-history.response.ts


class BillingHistoryResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.invoices = [];
        this.transactions = [];
        const transactions = this.getResponseProperty("Transactions");
        const invoices = this.getResponseProperty("Invoices");
        if (transactions != null) {
            this.transactions = transactions.map((t) => new BillingTransactionResponse(t));
        }
        if (invoices != null) {
            this.invoices = invoices.map((i) => new BillingInvoiceResponse(i));
        }
    }
    get hasNoHistory() {
        return this.invoices.length == 0 && this.transactions.length == 0;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/billing-payment.response.ts


class BillingPaymentResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.balance = this.getResponseProperty("Balance");
        const paymentSource = this.getResponseProperty("PaymentSource");
        this.paymentSource = paymentSource == null ? null : new BillingSourceResponse(paymentSource);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/breach-account.response.ts

class BreachAccountResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.addedDate = this.getResponseProperty("AddedDate");
        this.breachDate = this.getResponseProperty("BreachDate");
        this.dataClasses = this.getResponseProperty("DataClasses");
        this.description = this.getResponseProperty("Description");
        this.domain = this.getResponseProperty("Domain");
        this.isActive = this.getResponseProperty("IsActive");
        this.isVerified = this.getResponseProperty("IsVerified");
        this.logoPath = this.getResponseProperty("LogoPath");
        this.modifiedDate = this.getResponseProperty("ModifiedDate");
        this.name = this.getResponseProperty("Name");
        this.pwnCount = this.getResponseProperty("PwnCount");
        this.title = this.getResponseProperty("Title");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/collection.response.ts


class collection_response_CollectionResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.name = this.getResponseProperty("Name");
        this.externalId = this.getResponseProperty("ExternalId");
    }
}
class CollectionDetailsResponse extends collection_response_CollectionResponse {
    constructor(response) {
        super(response);
        this.readOnly = this.getResponseProperty("ReadOnly") || false;
    }
}
class CollectionAccessDetailsResponse extends collection_response_CollectionResponse {
    constructor(response) {
        super(response);
        this.groups = [];
        this.users = [];
        this.assigned = this.getResponseProperty("Assigned") || false;
        const groups = this.getResponseProperty("Groups");
        if (groups != null) {
            this.groups = groups.map((g) => new SelectionReadOnlyResponse(g));
        }
        const users = this.getResponseProperty("Users");
        if (users != null) {
            this.users = users.map((g) => new SelectionReadOnlyResponse(g));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/device-verification.response.ts

class DeviceVerificationResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.isDeviceVerificationSectionEnabled = this.getResponseProperty("IsDeviceVerificationSectionEnabled");
        this.unknownDeviceVerificationEnabled = this.getResponseProperty("UnknownDeviceVerificationEnabled");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/global-domain.response.ts

class GlobalDomainResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.type = this.getResponseProperty("Type");
        this.domains = this.getResponseProperty("Domains");
        this.excluded = this.getResponseProperty("Excluded");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/domains.response.ts


class DomainsResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.globalEquivalentDomains = [];
        this.equivalentDomains = this.getResponseProperty("EquivalentDomains");
        const globalEquivalentDomains = this.getResponseProperty("GlobalEquivalentDomains");
        if (globalEquivalentDomains != null) {
            this.globalEquivalentDomains = globalEquivalentDomains.map((d) => new GlobalDomainResponse(d));
        }
        else {
            this.globalEquivalentDomains = [];
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/attachment.response.ts

class attachment_response_AttachmentResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.url = this.getResponseProperty("Url");
        this.fileName = this.getResponseProperty("FileName");
        this.key = this.getResponseProperty("Key");
        this.size = this.getResponseProperty("Size");
        this.sizeName = this.getResponseProperty("SizeName");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/password-history.response.ts

class password_history_response_PasswordHistoryResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.password = this.getResponseProperty("Password");
        this.lastUsedDate = this.getResponseProperty("LastUsedDate");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/cipher.response.ts









class cipher_response_CipherResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.folderId = this.getResponseProperty("FolderId") || null;
        this.type = this.getResponseProperty("Type");
        this.name = this.getResponseProperty("Name");
        this.notes = this.getResponseProperty("Notes");
        this.favorite = this.getResponseProperty("Favorite") || false;
        this.edit = !!this.getResponseProperty("Edit");
        if (this.getResponseProperty("ViewPassword") == null) {
            this.viewPassword = true;
        }
        else {
            this.viewPassword = this.getResponseProperty("ViewPassword");
        }
        this.organizationUseTotp = this.getResponseProperty("OrganizationUseTotp");
        this.revisionDate = this.getResponseProperty("RevisionDate");
        this.collectionIds = this.getResponseProperty("CollectionIds");
        this.creationDate = this.getResponseProperty("CreationDate");
        this.deletedDate = this.getResponseProperty("DeletedDate");
        const login = this.getResponseProperty("Login");
        if (login != null) {
            this.login = new LoginApi(login);
        }
        const card = this.getResponseProperty("Card");
        if (card != null) {
            this.card = new CardApi(card);
        }
        const identity = this.getResponseProperty("Identity");
        if (identity != null) {
            this.identity = new IdentityApi(identity);
        }
        const secureNote = this.getResponseProperty("SecureNote");
        if (secureNote != null) {
            this.secureNote = new SecureNoteApi(secureNote);
        }
        const fields = this.getResponseProperty("Fields");
        if (fields != null) {
            this.fields = fields.map((f) => new FieldApi(f));
        }
        const attachments = this.getResponseProperty("Attachments");
        if (attachments != null) {
            this.attachments = attachments.map((a) => new attachment_response_AttachmentResponse(a));
        }
        const passwordHistory = this.getResponseProperty("PasswordHistory");
        if (passwordHistory != null) {
            this.passwordHistory = passwordHistory.map((h) => new password_history_response_PasswordHistoryResponse(h));
        }
        this.reprompt = this.getResponseProperty("Reprompt") || CipherRepromptType.None;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/emergency-access.response.ts


class EmergencyAccessGranteeDetailsResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.granteeId = this.getResponseProperty("GranteeId");
        this.name = this.getResponseProperty("Name");
        this.email = this.getResponseProperty("Email");
        this.type = this.getResponseProperty("Type");
        this.status = this.getResponseProperty("Status");
        this.waitTimeDays = this.getResponseProperty("WaitTimeDays");
        this.creationDate = this.getResponseProperty("CreationDate");
        this.avatarColor = this.getResponseProperty("AvatarColor");
    }
}
class EmergencyAccessGrantorDetailsResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.grantorId = this.getResponseProperty("GrantorId");
        this.name = this.getResponseProperty("Name");
        this.email = this.getResponseProperty("Email");
        this.type = this.getResponseProperty("Type");
        this.status = this.getResponseProperty("Status");
        this.waitTimeDays = this.getResponseProperty("WaitTimeDays");
        this.creationDate = this.getResponseProperty("CreationDate");
        this.avatarColor = this.getResponseProperty("AvatarColor");
    }
}
class EmergencyAccessTakeoverResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.keyEncrypted = this.getResponseProperty("KeyEncrypted");
        this.kdf = this.getResponseProperty("Kdf");
        this.kdfIterations = this.getResponseProperty("KdfIterations");
        this.kdfMemory = this.getResponseProperty("KdfMemory");
        this.kdfParallelism = this.getResponseProperty("KdfParallelism");
    }
}
class EmergencyAccessViewResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.ciphers = [];
        this.keyEncrypted = this.getResponseProperty("KeyEncrypted");
        const ciphers = this.getResponseProperty("Ciphers");
        if (ciphers != null) {
            this.ciphers = ciphers.map((c) => new cipher_response_CipherResponse(c));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/event.response.ts

class EventResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.type = this.getResponseProperty("Type");
        this.userId = this.getResponseProperty("UserId");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.providerId = this.getResponseProperty("ProviderId");
        this.cipherId = this.getResponseProperty("CipherId");
        this.collectionId = this.getResponseProperty("CollectionId");
        this.groupId = this.getResponseProperty("GroupId");
        this.policyId = this.getResponseProperty("PolicyId");
        this.organizationUserId = this.getResponseProperty("OrganizationUserId");
        this.providerUserId = this.getResponseProperty("ProviderUserId");
        this.providerOrganizationId = this.getResponseProperty("ProviderOrganizationId");
        this.actingUserId = this.getResponseProperty("ActingUserId");
        this.date = this.getResponseProperty("Date");
        this.deviceType = this.getResponseProperty("DeviceType");
        this.ipAddress = this.getResponseProperty("IpAddress");
        this.installationId = this.getResponseProperty("InstallationId");
        this.systemUser = this.getResponseProperty("SystemUser");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/key-connector-user-key.response.ts

class KeyConnectorUserKeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.key = this.getResponseProperty("Key");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-connection.response.ts

class OrganizationConnectionResponse extends BaseResponse {
    constructor(response, configType) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.type = this.getResponseProperty("Type");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.enabled = this.getResponseProperty("Enabled");
        const rawConfig = this.getResponseProperty("Config");
        this.config = rawConfig == null ? null : new configType(rawConfig);
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-export.response.ts



class OrganizationExportResponse extends BaseResponse {
    constructor(response) {
        super(response);
        const collections = this.getResponseProperty("Collections");
        if (collections != null) {
            this.collections = collections.map((c) => new collection_response_CollectionResponse(c));
        }
        const ciphers = this.getResponseProperty("Ciphers");
        if (ciphers != null) {
            this.ciphers = ciphers.map((c) => new cipher_response_CipherResponse(c));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/organization-sponsorship-sync-status.response.ts

class OrganizationSponsorshipSyncStatusResponse extends BaseResponse {
    constructor(response) {
        super(response);
        const lastSyncDate = this.getResponseProperty("LastSyncDate");
        if (lastSyncDate) {
            this.lastSyncDate = new Date(lastSyncDate);
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/policy.response.ts

class PolicyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.type = this.getResponseProperty("Type");
        this.data = this.getResponseProperty("Data");
        this.enabled = this.getResponseProperty("Enabled");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/prelogin.response.ts

class PreloginResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.kdf = this.getResponseProperty("Kdf");
        this.kdfIterations = this.getResponseProperty("KdfIterations");
        this.kdfMemory = this.getResponseProperty("KdfMemory");
        this.kdfParallelism = this.getResponseProperty("KdfParallelism");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/provider/provider-organization.response.ts

class ProviderOrganizationResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.providerId = this.getResponseProperty("ProviderId");
        this.organizationId = this.getResponseProperty("OrganizationId");
        this.key = this.getResponseProperty("Key");
        this.settings = this.getResponseProperty("Settings");
        this.creationDate = this.getResponseProperty("CreationDate");
        this.revisionDate = this.getResponseProperty("RevisionDate");
        this.userCount = this.getResponseProperty("UserCount");
        this.seats = this.getResponseProperty("Seats");
        this.plan = this.getResponseProperty("Plan");
    }
}
class ProviderOrganizationOrganizationDetailsResponse extends ProviderOrganizationResponse {
    constructor(response) {
        super(response);
        this.organizationName = this.getResponseProperty("OrganizationName");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/provider/provider-user-bulk-public-key.response.ts

class ProviderUserBulkPublicKeyResponse extends OrganizationUserBulkPublicKeyResponse {
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/provider/provider-user-bulk.response.ts

class ProviderUserBulkResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.error = this.getResponseProperty("Error");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/provider/provider-user.response.ts


class ProviderUserResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.userId = this.getResponseProperty("UserId");
        this.type = this.getResponseProperty("Type");
        this.status = this.getResponseProperty("Status");
        this.permissions = new PermissionsApi(this.getResponseProperty("Permissions"));
    }
}
class ProviderUserUserDetailsResponse extends ProviderUserResponse {
    constructor(response) {
        super(response);
        this.name = this.getResponseProperty("Name");
        this.email = this.getResponseProperty("Email");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/provider/provider.response.ts

class ProviderResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.name = this.getResponseProperty("Name");
        this.businessName = this.getResponseProperty("BusinessName");
        this.billingEmail = this.getResponseProperty("BillingEmail");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/send-access.response.ts



class send_access_response_SendAccessResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.type = this.getResponseProperty("Type");
        this.name = this.getResponseProperty("Name");
        const text = this.getResponseProperty("Text");
        if (text != null) {
            this.text = new SendTextApi(text);
        }
        const file = this.getResponseProperty("File");
        if (file != null) {
            this.file = new SendFileApi(file);
        }
        this.expirationDate = this.getResponseProperty("ExpirationDate");
        this.creatorIdentifier = this.getResponseProperty("CreatorIdentifier");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/send-file-download-data.response.ts

class SendFileDownloadDataResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = null;
        this.url = null;
        this.id = this.getResponseProperty("Id");
        this.url = this.getResponseProperty("Url");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/send.response.ts



class send_response_SendResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.accessId = this.getResponseProperty("AccessId");
        this.type = this.getResponseProperty("Type");
        this.name = this.getResponseProperty("Name");
        this.notes = this.getResponseProperty("Notes");
        this.key = this.getResponseProperty("Key");
        this.maxAccessCount = this.getResponseProperty("MaxAccessCount");
        this.accessCount = this.getResponseProperty("AccessCount");
        this.revisionDate = this.getResponseProperty("RevisionDate");
        this.expirationDate = this.getResponseProperty("ExpirationDate");
        this.deletionDate = this.getResponseProperty("DeletionDate");
        this.password = this.getResponseProperty("Password");
        this.disable = this.getResponseProperty("Disabled") || false;
        this.hideEmail = this.getResponseProperty("HideEmail") || false;
        const text = this.getResponseProperty("Text");
        if (text != null) {
            this.text = new SendTextApi(text);
        }
        const file = this.getResponseProperty("File");
        if (file != null) {
            this.file = new SendFileApi(file);
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/send-file-upload-data.response.ts


class SendFileUploadDataResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.url = null;
        this.fileUploadType = this.getResponseProperty("FileUploadType");
        const sendResponse = this.getResponseProperty("SendResponse");
        this.sendResponse = sendResponse == null ? null : new send_response_SendResponse(sendResponse);
        this.url = this.getResponseProperty("Url");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/sso-pre-validate.response.ts

class SsoPreValidateResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.token = this.getResponseProperty("Token");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/tax-rate.response.ts

class TaxRateResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.id = this.getResponseProperty("Id");
        this.country = this.getResponseProperty("Country");
        this.state = this.getResponseProperty("State");
        this.postalCode = this.getResponseProperty("PostalCode");
        this.rate = this.getResponseProperty("Rate");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-authenticator.response.ts

class TwoFactorAuthenticatorResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.key = this.getResponseProperty("Key");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-duo.response.ts

class TwoFactorDuoResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.host = this.getResponseProperty("Host");
        this.secretKey = this.getResponseProperty("SecretKey");
        this.integrationKey = this.getResponseProperty("IntegrationKey");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-email.response.ts

class TwoFactorEmailResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.email = this.getResponseProperty("Email");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-provider.response.ts

class TwoFactorProviderResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.type = this.getResponseProperty("Type");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-recover.response.ts

class TwoFactorRecoverResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.code = this.getResponseProperty("Code");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-web-authn.response.ts


class TwoFactorWebAuthnResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        const keys = this.getResponseProperty("Keys");
        this.keys = keys == null ? null : keys.map((k) => new KeyResponse(k));
    }
}
class KeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.name = this.getResponseProperty("Name");
        this.id = this.getResponseProperty("Id");
        this.migrated = this.getResponseProperty("Migrated");
    }
}
class ChallengeResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.attestation = this.getResponseProperty("attestation");
        this.authenticatorSelection = this.getResponseProperty("authenticatorSelection");
        this.challenge = Utils.fromUrlB64ToArray(this.getResponseProperty("challenge"));
        this.excludeCredentials = this.getResponseProperty("excludeCredentials").map((c) => {
            c.id = Utils.fromUrlB64ToArray(c.id).buffer;
            return c;
        });
        this.extensions = this.getResponseProperty("extensions");
        this.pubKeyCredParams = this.getResponseProperty("pubKeyCredParams");
        this.rp = this.getResponseProperty("rp");
        this.timeout = this.getResponseProperty("timeout");
        const user = this.getResponseProperty("user");
        user.id = Utils.fromUrlB64ToArray(user.id);
        this.user = user;
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/two-factor-yubi-key.response.ts

class TwoFactorYubiKeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.enabled = this.getResponseProperty("Enabled");
        this.key1 = this.getResponseProperty("Key1");
        this.key2 = this.getResponseProperty("Key2");
        this.key3 = this.getResponseProperty("Key3");
        this.key4 = this.getResponseProperty("Key4");
        this.key5 = this.getResponseProperty("Key5");
        this.nfc = this.getResponseProperty("Nfc");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/models/response/user-key.response.ts

class UserKeyResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.userId = this.getResponseProperty("UserId");
        this.publicKey = this.getResponseProperty("PublicKey");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/attachment-upload-data.response.ts


class AttachmentUploadDataResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.url = null;
        this.attachmentId = this.getResponseProperty("AttachmentId");
        this.fileUploadType = this.getResponseProperty("FileUploadType");
        const cipherResponse = this.getResponseProperty("CipherResponse");
        const cipherMiniResponse = this.getResponseProperty("CipherMiniResponse");
        this.cipherResponse = cipherResponse == null ? null : new cipher_response_CipherResponse(cipherResponse);
        this.cipherMiniResponse =
            cipherMiniResponse == null ? null : new cipher_response_CipherResponse(cipherMiniResponse);
        this.url = this.getResponseProperty("Url");
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/vault/models/response/sync.response.ts








class SyncResponse extends BaseResponse {
    constructor(response) {
        super(response);
        this.folders = [];
        this.collections = [];
        this.ciphers = [];
        this.policies = [];
        this.sends = [];
        const profile = this.getResponseProperty("Profile");
        if (profile != null) {
            this.profile = new ProfileResponse(profile);
        }
        const folders = this.getResponseProperty("Folders");
        if (folders != null) {
            this.folders = folders.map((f) => new FolderResponse(f));
        }
        const collections = this.getResponseProperty("Collections");
        if (collections != null) {
            this.collections = collections.map((c) => new CollectionDetailsResponse(c));
        }
        const ciphers = this.getResponseProperty("Ciphers");
        if (ciphers != null) {
            this.ciphers = ciphers.map((c) => new cipher_response_CipherResponse(c));
        }
        const domains = this.getResponseProperty("Domains");
        if (domains != null) {
            this.domains = new DomainsResponse(domains);
        }
        const policies = this.getResponseProperty("Policies");
        if (policies != null) {
            this.policies = policies.map((p) => new PolicyResponse(p));
        }
        const sends = this.getResponseProperty("Sends");
        if (sends != null) {
            this.sends = sends.map((s) => new send_response_SendResponse(s));
        }
    }
}

;// CONCATENATED MODULE: ../../libs/common/src/services/api.service.ts
var api_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
























































/**
 * @deprecated The `ApiService` class is deprecated and calls should be extracted into individual
 * api services. The `send` method is still allowed to be used within api services. For background
 * of this decision please read https://contributing.bitwarden.com/architecture/adr/refactor-api-service.
 */
class ApiService {
    constructor(tokenService, platformUtilsService, environmentService, appIdService, logoutCallback, customUserAgent = null) {
        this.tokenService = tokenService;
        this.platformUtilsService = platformUtilsService;
        this.environmentService = environmentService;
        this.appIdService = appIdService;
        this.logoutCallback = logoutCallback;
        this.customUserAgent = customUserAgent;
        this.isWebClient = false;
        this.isDesktopClient = false;
        this.device = platformUtilsService.getDevice();
        this.deviceType = this.device.toString();
        this.isWebClient =
            this.device === DeviceType.IEBrowser ||
                this.device === DeviceType.ChromeBrowser ||
                this.device === DeviceType.EdgeBrowser ||
                this.device === DeviceType.FirefoxBrowser ||
                this.device === DeviceType.OperaBrowser ||
                this.device === DeviceType.SafariBrowser ||
                this.device === DeviceType.UnknownBrowser ||
                this.device === DeviceType.VivaldiBrowser;
        this.isDesktopClient =
            this.device === DeviceType.WindowsDesktop ||
                this.device === DeviceType.MacOsDesktop ||
                this.device === DeviceType.LinuxDesktop;
    }
    // Auth APIs
    postIdentityToken(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const headers = new Headers({
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
                Accept: "application/json",
                "Device-Type": this.deviceType,
            });
            if (this.customUserAgent != null) {
                headers.set("User-Agent", this.customUserAgent);
            }
            request.alterIdentityTokenHeaders(headers);
            const identityToken = request instanceof UserApiTokenRequest
                ? request.toIdentityToken()
                : request.toIdentityToken(this.platformUtilsService.getClientType());
            const response = yield this.fetch(new Request(this.environmentService.getIdentityUrl() + "/connect/token", {
                body: this.qsStringify(identityToken),
                credentials: this.getCredentials(),
                cache: "no-store",
                headers: headers,
                method: "POST",
            }));
            let responseJson = null;
            if (this.isJsonResponse(response)) {
                responseJson = yield response.json();
            }
            if (responseJson != null) {
                if (response.status === 200) {
                    return new IdentityTokenResponse(responseJson);
                }
                else if (response.status === 400 &&
                    responseJson.TwoFactorProviders2 &&
                    Object.keys(responseJson.TwoFactorProviders2).length) {
                    yield this.tokenService.clearTwoFactorToken();
                    return new IdentityTwoFactorResponse(responseJson);
                }
                else if (response.status === 400 &&
                    responseJson.HCaptcha_SiteKey &&
                    Object.keys(responseJson.HCaptcha_SiteKey).length) {
                    return new IdentityCaptchaResponse(responseJson);
                }
            }
            return Promise.reject(new ErrorResponse(responseJson, response.status, true));
        });
    }
    refreshIdentityToken() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            try {
                yield this.doAuthRefresh();
            }
            catch (e) {
                return Promise.reject(null);
            }
        });
    }
    postAuthRequest(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/auth-requests/", request, false, true);
            return new AuthRequestResponse(r);
        });
    }
    getAuthResponse(id, accessCode) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = `/auth-requests/${id}/response?code=${accessCode}`;
            const r = yield this.send("GET", path, null, false, true);
            return new AuthRequestResponse(r);
        });
    }
    getAuthRequest(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = `/auth-requests/${id}`;
            const r = yield this.send("GET", path, null, true, true);
            return new AuthRequestResponse(r);
        });
    }
    putAuthRequest(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = `/auth-requests/${id}`;
            const r = yield this.send("PUT", path, request, true, true);
            return new AuthRequestResponse(r);
        });
    }
    getAuthRequests() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = `/auth-requests/`;
            const r = yield this.send("GET", path, null, true, true);
            return new ListResponse(r, AuthRequestResponse);
        });
    }
    getLastAuthRequest() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const requests = yield this.getAuthRequests();
            const activeRequests = requests.data.filter((m) => !m.isAnswered && !m.isExpired);
            const lastRequest = activeRequests.sort((a, b) => a.creationDate.localeCompare(b.creationDate))[activeRequests.length - 1];
            return lastRequest;
        });
    }
    // Account APIs
    getProfile() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/profile", null, true, true);
            return new ProfileResponse(r);
        });
    }
    getUserSubscription() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/subscription", null, true, true);
            return new SubscriptionResponse(r);
        });
    }
    getTaxInfo() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/tax", null, true, true);
            return new TaxInfoResponse(r);
        });
    }
    putProfile(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/accounts/profile", request, true, true);
            return new ProfileResponse(r);
        });
    }
    putAvatar(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/accounts/avatar", request, true, true);
            return new ProfileResponse(r);
        });
    }
    putTaxInfo(request) {
        return this.send("PUT", "/accounts/tax", request, true, false);
    }
    postPrelogin(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/prelogin", request, false, true, this.environmentService.getIdentityUrl());
            return new PreloginResponse(r);
        });
    }
    postEmailToken(request) {
        return this.send("POST", "/accounts/email-token", request, true, false);
    }
    postEmail(request) {
        return this.send("POST", "/accounts/email", request, true, false);
    }
    postPassword(request) {
        return this.send("POST", "/accounts/password", request, true, false);
    }
    setPassword(request) {
        return this.send("POST", "/accounts/set-password", request, true, false);
    }
    postSetKeyConnectorKey(request) {
        return this.send("POST", "/accounts/set-key-connector-key", request, true, false);
    }
    postSecurityStamp(request) {
        return this.send("POST", "/accounts/security-stamp", request, true, false);
    }
    getAccountRevisionDate() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/revision-date", null, true, true);
            return r;
        });
    }
    postPasswordHint(request) {
        return this.send("POST", "/accounts/password-hint", request, false, false);
    }
    postRegister(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/register", request, false, true, this.environmentService.getIdentityUrl());
            return new RegisterResponse(r);
        });
    }
    postPremium(data) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/premium", data, true, true);
            return new PaymentResponse(r);
        });
    }
    postIapCheck(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return this.send("POST", "/accounts/iap-check", request, true, false);
        });
    }
    postReinstatePremium() {
        return this.send("POST", "/accounts/reinstate-premium", null, true, false);
    }
    postCancelPremium() {
        return this.send("POST", "/accounts/cancel-premium", null, true, false);
    }
    postAccountStorage(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/storage", request, true, true);
            return new PaymentResponse(r);
        });
    }
    postAccountPayment(request) {
        return this.send("POST", "/accounts/payment", request, true, false);
    }
    postAccountLicense(data) {
        return this.send("POST", "/accounts/license", data, true, false);
    }
    postAccountKeys(request) {
        return this.send("POST", "/accounts/keys", request, true, false);
    }
    postAccountKey(request) {
        return this.send("POST", "/accounts/key", request, true, false);
    }
    postAccountVerifyEmail() {
        return this.send("POST", "/accounts/verify-email", null, true, false);
    }
    postAccountVerifyEmailToken(request) {
        return this.send("POST", "/accounts/verify-email-token", request, false, false);
    }
    postAccountVerifyPassword(request) {
        return this.send("POST", "/accounts/verify-password", request, true, false);
    }
    postAccountRecoverDelete(request) {
        return this.send("POST", "/accounts/delete-recover", request, false, false);
    }
    postAccountRecoverDeleteToken(request) {
        return this.send("POST", "/accounts/delete-recover-token", request, false, false);
    }
    postAccountKdf(request) {
        return this.send("POST", "/accounts/kdf", request, true, false);
    }
    deleteSsoUser(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return this.send("DELETE", "/accounts/sso/" + organizationId, null, true, false);
        });
    }
    getSsoUserIdentifier() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return this.send("GET", "/accounts/sso/user-identifier", null, true, true);
        });
    }
    postUserApiKey(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/api-key", request, true, true);
            return new ApiKeyResponse(r);
        });
    }
    postUserRotateApiKey(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/accounts/rotate-api-key", request, true, true);
            return new ApiKeyResponse(r);
        });
    }
    putUpdateTempPassword(request) {
        return this.send("PUT", "/accounts/update-temp-password", request, true, false);
    }
    postConvertToKeyConnector() {
        return this.send("POST", "/accounts/convert-to-key-connector", null, true, false);
    }
    // Account Billing APIs
    getUserBillingHistory() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/billing/history", null, true, true);
            return new BillingHistoryResponse(r);
        });
    }
    getUserBillingPayment() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/accounts/billing/payment-method", null, true, true);
            return new BillingPaymentResponse(r);
        });
    }
    // Send APIs
    getSend(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/sends/" + id, null, true, true);
            return new send_response_SendResponse(r);
        });
    }
    postSendAccess(id, request, apiUrl) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const addSendIdHeader = (headers) => {
                headers.set("Send-Id", id);
            };
            const r = yield this.send("POST", "/sends/access/" + id, request, false, true, apiUrl, addSendIdHeader);
            return new send_access_response_SendAccessResponse(r);
        });
    }
    getSendFileDownloadData(send, request, apiUrl) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const addSendIdHeader = (headers) => {
                headers.set("Send-Id", send.id);
            };
            const r = yield this.send("POST", "/sends/" + send.id + "/access/file/" + send.file.id, request, false, true, apiUrl, addSendIdHeader);
            return new SendFileDownloadDataResponse(r);
        });
    }
    getSends() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/sends", null, true, true);
            return new ListResponse(r, send_response_SendResponse);
        });
    }
    postSend(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/sends", request, true, true);
            return new send_response_SendResponse(r);
        });
    }
    postFileTypeSend(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/sends/file/v2", request, true, true);
            return new SendFileUploadDataResponse(r);
        });
    }
    renewSendFileUploadUrl(sendId, fileId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/sends/" + sendId + "/file/" + fileId, null, true, true);
            return new SendFileUploadDataResponse(r);
        });
    }
    postSendFile(sendId, fileId, data) {
        return this.send("POST", "/sends/" + sendId + "/file/" + fileId, data, true, false);
    }
    /**
     * @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
     * This method still exists for backward compatibility with old server versions.
     */
    postSendFileLegacy(data) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/sends/file", data, true, true);
            return new send_response_SendResponse(r);
        });
    }
    putSend(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/sends/" + id, request, true, true);
            return new send_response_SendResponse(r);
        });
    }
    putSendRemovePassword(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/sends/" + id + "/remove-password", null, true, true);
            return new send_response_SendResponse(r);
        });
    }
    deleteSend(id) {
        return this.send("DELETE", "/sends/" + id, null, true, false);
    }
    // Cipher APIs
    getCipher(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/ciphers/" + id, null, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    getFullCipherDetails(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/ciphers/" + id + "/details", null, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    getCipherAdmin(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/ciphers/" + id + "/admin", null, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    getCiphersOrganization(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/ciphers/organization-details?organizationId=" + organizationId, null, true, true);
            return new ListResponse(r, cipher_response_CipherResponse);
        });
    }
    postCipher(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    postCipherCreate(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers/create", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    postCipherAdmin(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers/admin", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putCipher(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id, request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putPartialCipher(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id + "/partial", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putCipherAdmin(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id + "/admin", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    deleteCipher(id) {
        return this.send("DELETE", "/ciphers/" + id, null, true, false);
    }
    deleteCipherAdmin(id) {
        return this.send("DELETE", "/ciphers/" + id + "/admin", null, true, false);
    }
    deleteManyCiphers(request) {
        return this.send("DELETE", "/ciphers", request, true, false);
    }
    deleteManyCiphersAdmin(request) {
        return this.send("DELETE", "/ciphers/admin", request, true, false);
    }
    putMoveCiphers(request) {
        return this.send("PUT", "/ciphers/move", request, true, false);
    }
    putShareCipher(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id + "/share", request, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putShareCiphers(request) {
        return this.send("PUT", "/ciphers/share", request, true, false);
    }
    putCipherCollections(id, request) {
        return this.send("PUT", "/ciphers/" + id + "/collections", request, true, false);
    }
    putCipherCollectionsAdmin(id, request) {
        return this.send("PUT", "/ciphers/" + id + "/collections-admin", request, true, false);
    }
    postPurgeCiphers(request, organizationId = null) {
        let path = "/ciphers/purge";
        if (organizationId != null) {
            path += "?organizationId=" + organizationId;
        }
        return this.send("POST", path, request, true, false);
    }
    putDeleteCipher(id) {
        return this.send("PUT", "/ciphers/" + id + "/delete", null, true, false);
    }
    putDeleteCipherAdmin(id) {
        return this.send("PUT", "/ciphers/" + id + "/delete-admin", null, true, false);
    }
    putDeleteManyCiphers(request) {
        return this.send("PUT", "/ciphers/delete", request, true, false);
    }
    putDeleteManyCiphersAdmin(request) {
        return this.send("PUT", "/ciphers/delete-admin", request, true, false);
    }
    putRestoreCipher(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id + "/restore", null, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putRestoreCipherAdmin(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/" + id + "/restore-admin", null, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    putRestoreManyCiphers(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/ciphers/restore", request, true, true);
            return new ListResponse(r, cipher_response_CipherResponse);
        });
    }
    // Attachments APIs
    getAttachmentData(cipherId, attachmentId, emergencyAccessId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = (emergencyAccessId != null ? "/emergency-access/" + emergencyAccessId + "/" : "/ciphers/") +
                cipherId +
                "/attachment/" +
                attachmentId;
            const r = yield this.send("GET", path, null, true, true);
            return new attachment_response_AttachmentResponse(r);
        });
    }
    postCipherAttachment(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers/" + id + "/attachment/v2", request, true, true);
            return new AttachmentUploadDataResponse(r);
        });
    }
    /**
     * @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
     * This method still exists for backward compatibility with old server versions.
     */
    postCipherAttachmentLegacy(id, data) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers/" + id + "/attachment", data, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    /**
     * @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
     * This method still exists for backward compatibility with old server versions.
     */
    postCipherAttachmentAdminLegacy(id, data) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/ciphers/" + id + "/attachment-admin", data, true, true);
            return new cipher_response_CipherResponse(r);
        });
    }
    deleteCipherAttachment(id, attachmentId) {
        return this.send("DELETE", "/ciphers/" + id + "/attachment/" + attachmentId, null, true, false);
    }
    deleteCipherAttachmentAdmin(id, attachmentId) {
        return this.send("DELETE", "/ciphers/" + id + "/attachment/" + attachmentId + "/admin", null, true, false);
    }
    postShareCipherAttachment(id, attachmentId, data, organizationId) {
        return this.send("POST", "/ciphers/" + id + "/attachment/" + attachmentId + "/share?organizationId=" + organizationId, data, true, false);
    }
    renewAttachmentUploadUrl(id, attachmentId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/ciphers/" + id + "/attachment/" + attachmentId + "/renew", null, true, true);
            return new AttachmentUploadDataResponse(r);
        });
    }
    postAttachmentFile(id, attachmentId, data) {
        return this.send("POST", "/ciphers/" + id + "/attachment/" + attachmentId, data, true, false);
    }
    // Collections APIs
    getCollectionAccessDetails(organizationId, id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/collections/" + id + "/details", null, true, true);
            return new CollectionAccessDetailsResponse(r);
        });
    }
    getUserCollections() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/collections", null, true, true);
            return new ListResponse(r, collection_response_CollectionResponse);
        });
    }
    getCollections(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/collections", null, true, true);
            return new ListResponse(r, collection_response_CollectionResponse);
        });
    }
    getManyCollectionsWithAccessDetails(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/collections/details", null, true, true);
            return new ListResponse(r, CollectionAccessDetailsResponse);
        });
    }
    getCollectionUsers(organizationId, id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/collections/" + id + "/users", null, true, true);
            return r.map((dr) => new SelectionReadOnlyResponse(dr));
        });
    }
    postCollection(organizationId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/organizations/" + organizationId + "/collections", request, true, true);
            return new collection_response_CollectionResponse(r);
        });
    }
    putCollection(organizationId, id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/organizations/" + organizationId + "/collections/" + id, request, true, true);
            return new collection_response_CollectionResponse(r);
        });
    }
    putCollectionUsers(organizationId, id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            yield this.send("PUT", "/organizations/" + organizationId + "/collections/" + id + "/users", request, true, false);
        });
    }
    deleteCollection(organizationId, id) {
        return this.send("DELETE", "/organizations/" + organizationId + "/collections/" + id, null, true, false);
    }
    deleteManyCollections(request) {
        return this.send("DELETE", "/organizations/" + request.organizationId + "/collections", request, true, false);
    }
    deleteCollectionUser(organizationId, id, organizationUserId) {
        return this.send("DELETE", "/organizations/" + organizationId + "/collections/" + id + "/user/" + organizationUserId, null, true, false);
    }
    // Groups APIs
    getGroupUsers(organizationId, id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/groups/" + id + "/users", null, true, true);
            return r;
        });
    }
    putGroupUsers(organizationId, id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            yield this.send("PUT", "/organizations/" + organizationId + "/groups/" + id + "/users", request, true, false);
        });
    }
    deleteGroupUser(organizationId, id, organizationUserId) {
        return this.send("DELETE", "/organizations/" + organizationId + "/groups/" + id + "/user/" + organizationUserId, null, true, false);
    }
    // Plan APIs
    getPlans() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/plans/", null, false, true);
            return new ListResponse(r, PlanResponse);
        });
    }
    postPublicImportDirectory(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return this.send("POST", "/public/organization/import", request, true, false);
        });
    }
    getTaxRates() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/plans/sales-tax-rates/", null, true, true);
            return new ListResponse(r, TaxRateResponse);
        });
    }
    // Settings APIs
    getSettingsDomains() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/settings/domains", null, true, true);
            return new DomainsResponse(r);
        });
    }
    putSettingsDomains(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/settings/domains", request, true, true);
            return new DomainsResponse(r);
        });
    }
    // Sync APIs
    getSync() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = this.isDesktopClient || this.isWebClient ? "/sync?excludeDomains=true" : "/sync";
            const r = yield this.send("GET", path, null, true, true);
            return new SyncResponse(r);
        });
    }
    // Two-factor APIs
    getTwoFactorProviders() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/two-factor", null, true, true);
            return new ListResponse(r, TwoFactorProviderResponse);
        });
    }
    getTwoFactorOrganizationProviders(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/two-factor", null, true, true);
            return new ListResponse(r, TwoFactorProviderResponse);
        });
    }
    getTwoFactorAuthenticator(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-authenticator", request, true, true);
            return new TwoFactorAuthenticatorResponse(r);
        });
    }
    getTwoFactorEmail(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-email", request, true, true);
            return new TwoFactorEmailResponse(r);
        });
    }
    getTwoFactorDuo(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-duo", request, true, true);
            return new TwoFactorDuoResponse(r);
        });
    }
    getTwoFactorOrganizationDuo(organizationId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/organizations/" + organizationId + "/two-factor/get-duo", request, true, true);
            return new TwoFactorDuoResponse(r);
        });
    }
    getTwoFactorYubiKey(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-yubikey", request, true, true);
            return new TwoFactorYubiKeyResponse(r);
        });
    }
    getTwoFactorWebAuthn(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-webauthn", request, true, true);
            return new TwoFactorWebAuthnResponse(r);
        });
    }
    getTwoFactorWebAuthnChallenge(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-webauthn-challenge", request, true, true);
            return new ChallengeResponse(r);
        });
    }
    getTwoFactorRecover(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/two-factor/get-recover", request, true, true);
            return new TwoFactorRecoverResponse(r);
        });
    }
    putTwoFactorAuthenticator(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/authenticator", request, true, true);
            return new TwoFactorAuthenticatorResponse(r);
        });
    }
    putTwoFactorEmail(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/email", request, true, true);
            return new TwoFactorEmailResponse(r);
        });
    }
    putTwoFactorDuo(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/duo", request, true, true);
            return new TwoFactorDuoResponse(r);
        });
    }
    putTwoFactorOrganizationDuo(organizationId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/organizations/" + organizationId + "/two-factor/duo", request, true, true);
            return new TwoFactorDuoResponse(r);
        });
    }
    putTwoFactorYubiKey(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/yubikey", request, true, true);
            return new TwoFactorYubiKeyResponse(r);
        });
    }
    putTwoFactorWebAuthn(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const response = request.deviceResponse.response;
            const data = Object.assign({}, request);
            data.deviceResponse = {
                id: request.deviceResponse.id,
                rawId: btoa(request.deviceResponse.id),
                type: request.deviceResponse.type,
                extensions: request.deviceResponse.getClientExtensionResults(),
                response: {
                    AttestationObject: Utils.fromBufferToB64(response.attestationObject),
                    clientDataJson: Utils.fromBufferToB64(response.clientDataJSON),
                },
            };
            const r = yield this.send("PUT", "/two-factor/webauthn", data, true, true);
            return new TwoFactorWebAuthnResponse(r);
        });
    }
    deleteTwoFactorWebAuthn(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("DELETE", "/two-factor/webauthn", request, true, true);
            return new TwoFactorWebAuthnResponse(r);
        });
    }
    putTwoFactorDisable(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/disable", request, true, true);
            return new TwoFactorProviderResponse(r);
        });
    }
    putTwoFactorOrganizationDisable(organizationId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/organizations/" + organizationId + "/two-factor/disable", request, true, true);
            return new TwoFactorProviderResponse(r);
        });
    }
    postTwoFactorRecover(request) {
        return this.send("POST", "/two-factor/recover", request, false, false);
    }
    postTwoFactorEmailSetup(request) {
        return this.send("POST", "/two-factor/send-email", request, true, false);
    }
    postTwoFactorEmail(request) {
        return this.send("POST", "/two-factor/send-email-login", request, false, false);
    }
    getDeviceVerificationSettings() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/two-factor/get-device-verification-settings", null, true, true);
            return new DeviceVerificationResponse(r);
        });
    }
    putDeviceVerificationSettings(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/two-factor/device-verification-settings", request, true, true);
            return new DeviceVerificationResponse(r);
        });
    }
    getKnownDevice(email, deviceIdentifier) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const path = `/devices/knowndevice/${email}/${deviceIdentifier}`;
            const r = yield this.send("GET", path, null, false, true);
            return r;
        });
    }
    // Emergency Access APIs
    getEmergencyAccessTrusted() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/emergency-access/trusted", null, true, true);
            return new ListResponse(r, EmergencyAccessGranteeDetailsResponse);
        });
    }
    getEmergencyAccessGranted() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/emergency-access/granted", null, true, true);
            return new ListResponse(r, EmergencyAccessGrantorDetailsResponse);
        });
    }
    getEmergencyAccess(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/emergency-access/" + id, null, true, true);
            return new EmergencyAccessGranteeDetailsResponse(r);
        });
    }
    getEmergencyGrantorPolicies(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/emergency-access/" + id + "/policies", null, true, true);
            return new ListResponse(r, PolicyResponse);
        });
    }
    putEmergencyAccess(id, request) {
        return this.send("PUT", "/emergency-access/" + id, request, true, false);
    }
    deleteEmergencyAccess(id) {
        return this.send("DELETE", "/emergency-access/" + id, null, true, false);
    }
    postEmergencyAccessInvite(request) {
        return this.send("POST", "/emergency-access/invite", request, true, false);
    }
    postEmergencyAccessReinvite(id) {
        return this.send("POST", "/emergency-access/" + id + "/reinvite", null, true, false);
    }
    postEmergencyAccessAccept(id, request) {
        return this.send("POST", "/emergency-access/" + id + "/accept", request, true, false);
    }
    postEmergencyAccessConfirm(id, request) {
        return this.send("POST", "/emergency-access/" + id + "/confirm", request, true, false);
    }
    postEmergencyAccessInitiate(id) {
        return this.send("POST", "/emergency-access/" + id + "/initiate", null, true, false);
    }
    postEmergencyAccessApprove(id) {
        return this.send("POST", "/emergency-access/" + id + "/approve", null, true, false);
    }
    postEmergencyAccessReject(id) {
        return this.send("POST", "/emergency-access/" + id + "/reject", null, true, false);
    }
    postEmergencyAccessTakeover(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/emergency-access/" + id + "/takeover", null, true, true);
            return new EmergencyAccessTakeoverResponse(r);
        });
    }
    postEmergencyAccessPassword(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            yield this.send("POST", "/emergency-access/" + id + "/password", request, true, true);
        });
    }
    postEmergencyAccessView(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/emergency-access/" + id + "/view", null, true, true);
            return new EmergencyAccessViewResponse(r);
        });
    }
    // Organization APIs
    getCloudCommunicationsEnabled() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/connections/enabled", null, true, true);
            return r;
        });
    }
    getOrganizationConnection(id, type, configType) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", `/organizations/connections/${id}/${type}`, null, true, true);
            return new OrganizationConnectionResponse(r, configType);
        });
    }
    createOrganizationConnection(request, configType) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/organizations/connections/", request, true, true);
            return new OrganizationConnectionResponse(r, configType);
        });
    }
    updateOrganizationConnection(request, configType, organizationConnectionId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/organizations/connections/" + organizationConnectionId, request, true, true);
            return new OrganizationConnectionResponse(r, configType);
        });
    }
    deleteOrganizationConnection(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return this.send("DELETE", "/organizations/connections/" + id, null, true, false);
        });
    }
    // Provider APIs
    postProviderSetup(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/providers/" + id + "/setup", request, true, true);
            return new ProviderResponse(r);
        });
    }
    getProvider(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/providers/" + id, null, true, true);
            return new ProviderResponse(r);
        });
    }
    putProvider(id, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("PUT", "/providers/" + id, request, true, true);
            return new ProviderResponse(r);
        });
    }
    // Provider User APIs
    getProviderUsers(providerId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/providers/" + providerId + "/users", null, true, true);
            return new ListResponse(r, ProviderUserUserDetailsResponse);
        });
    }
    getProviderUser(providerId, id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/providers/" + providerId + "/users/" + id, null, true, true);
            return new ProviderUserResponse(r);
        });
    }
    postProviderUserInvite(providerId, request) {
        return this.send("POST", "/providers/" + providerId + "/users/invite", request, true, false);
    }
    postProviderUserReinvite(providerId, id) {
        return this.send("POST", "/providers/" + providerId + "/users/" + id + "/reinvite", null, true, false);
    }
    postManyProviderUserReinvite(providerId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/providers/" + providerId + "/users/reinvite", request, true, true);
            return new ListResponse(r, ProviderUserBulkResponse);
        });
    }
    postProviderUserBulkConfirm(providerId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/providers/" + providerId + "/users/confirm", request, true, true);
            return new ListResponse(r, ProviderUserBulkResponse);
        });
    }
    deleteManyProviderUsers(providerId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("DELETE", "/providers/" + providerId + "/users", request, true, true);
            return new ListResponse(r, ProviderUserBulkResponse);
        });
    }
    postProviderUserAccept(providerId, id, request) {
        return this.send("POST", "/providers/" + providerId + "/users/" + id + "/accept", request, true, false);
    }
    postProviderUserConfirm(providerId, id, request) {
        return this.send("POST", "/providers/" + providerId + "/users/" + id + "/confirm", request, true, false);
    }
    postProviderUsersPublicKey(providerId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/providers/" + providerId + "/users/public-keys", request, true, true);
            return new ListResponse(r, ProviderUserBulkPublicKeyResponse);
        });
    }
    putProviderUser(providerId, id, request) {
        return this.send("PUT", "/providers/" + providerId + "/users/" + id, request, true, false);
    }
    deleteProviderUser(providerId, id) {
        return this.send("DELETE", "/providers/" + providerId + "/users/" + id, null, true, false);
    }
    // Provider Organization APIs
    getProviderClients(providerId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/providers/" + providerId + "/organizations", null, true, true);
            return new ListResponse(r, ProviderOrganizationOrganizationDetailsResponse);
        });
    }
    postProviderAddOrganization(providerId, request) {
        return this.send("POST", "/providers/" + providerId + "/organizations/add", request, true, false);
    }
    postProviderCreateOrganization(providerId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/providers/" + providerId + "/organizations", request, true, true);
            return new ProviderOrganizationResponse(r);
        });
    }
    deleteProviderOrganization(providerId, id) {
        return this.send("DELETE", "/providers/" + providerId + "/organizations/" + id, null, true, false);
    }
    // Event APIs
    getEvents(start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    getEventsCipher(id, start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/ciphers/" + id + "/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    getEventsOrganization(id, start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/organizations/" + id + "/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    getEventsOrganizationUser(organizationId, id, start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/organizations/" + organizationId + "/users/" + id + "/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    getEventsProvider(id, start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/providers/" + id + "/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    getEventsProviderUser(providerId, id, start, end, token) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", this.addEventParameters("/providers/" + providerId + "/users/" + id + "/events", start, end, token), null, true, true);
            return new ListResponse(r, EventResponse);
        });
    }
    postEventsCollect(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const authHeader = yield this.getActiveBearerToken();
            const headers = new Headers({
                "Device-Type": this.deviceType,
                Authorization: "Bearer " + authHeader,
                "Content-Type": "application/json; charset=utf-8",
            });
            if (this.customUserAgent != null) {
                headers.set("User-Agent", this.customUserAgent);
            }
            const response = yield this.fetch(new Request(this.environmentService.getEventsUrl() + "/collect", {
                cache: "no-store",
                credentials: this.getCredentials(),
                method: "POST",
                body: JSON.stringify(request),
                headers: headers,
            }));
            if (response.status !== 200) {
                return Promise.reject("Event post failed.");
            }
        });
    }
    // User APIs
    getUserPublicKey(id) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/users/" + id + "/public-key", null, true, true);
            return new UserKeyResponse(r);
        });
    }
    // HIBP APIs
    getHibpBreach(username) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/hibp/breach?username=" + username, null, true, true);
            return r.map((a) => new BreachAccountResponse(a));
        });
    }
    // Misc
    postBitPayInvoice(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/bitpay-invoice", request, true, true);
            return r;
        });
    }
    postSetupPayment() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/setup-payment", null, true, true);
            return r;
        });
    }
    // Key Connector
    getUserKeyFromKeyConnector(keyConnectorUrl) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const authHeader = yield this.getActiveBearerToken();
            const response = yield this.fetch(new Request(keyConnectorUrl + "/user-keys", {
                cache: "no-store",
                method: "GET",
                headers: new Headers({
                    Accept: "application/json",
                    Authorization: "Bearer " + authHeader,
                }),
            }));
            if (response.status !== 200) {
                const error = yield this.handleError(response, false, true);
                return Promise.reject(error);
            }
            return new KeyConnectorUserKeyResponse(yield response.json());
        });
    }
    postUserKeyToKeyConnector(keyConnectorUrl, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const authHeader = yield this.getActiveBearerToken();
            const response = yield this.fetch(new Request(keyConnectorUrl + "/user-keys", {
                cache: "no-store",
                method: "POST",
                headers: new Headers({
                    Accept: "application/json",
                    Authorization: "Bearer " + authHeader,
                    "Content-Type": "application/json; charset=utf-8",
                }),
                body: JSON.stringify(request),
            }));
            if (response.status !== 200) {
                const error = yield this.handleError(response, false, true);
                return Promise.reject(error);
            }
        });
    }
    getKeyConnectorAlive(keyConnectorUrl) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.fetch(new Request(keyConnectorUrl + "/alive", {
                cache: "no-store",
                method: "GET",
                headers: new Headers({
                    Accept: "application/json",
                    "Content-Type": "application/json; charset=utf-8",
                }),
            }));
            if (response.status !== 200) {
                const error = yield this.handleError(response, false, true);
                return Promise.reject(error);
            }
        });
    }
    getOrganizationExport(organizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("GET", "/organizations/" + organizationId + "/export", null, true, true);
            return new OrganizationExportResponse(r);
        });
    }
    // Helpers
    getActiveBearerToken() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            let accessToken = yield this.tokenService.getToken();
            if (yield this.tokenService.tokenNeedsRefresh()) {
                yield this.doAuthRefresh();
                accessToken = yield this.tokenService.getToken();
            }
            return accessToken;
        });
    }
    fetch(request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            if (request.method === "GET") {
                request.headers.set("Cache-Control", "no-store");
                request.headers.set("Pragma", "no-cache");
            }
            request.headers.set("Bitwarden-Client-Name", this.platformUtilsService.getClientType());
            request.headers.set("Bitwarden-Client-Version", yield this.platformUtilsService.getApplicationVersionNumber());
            return this.nativeFetch(request);
        });
    }
    nativeFetch(request) {
        return fetch(request);
    }
    preValidateSso(identifier) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            if (identifier == null || identifier === "") {
                throw new Error("Organization Identifier was not provided.");
            }
            const headers = new Headers({
                Accept: "application/json",
                "Device-Type": this.deviceType,
            });
            if (this.customUserAgent != null) {
                headers.set("User-Agent", this.customUserAgent);
            }
            const path = `/account/prevalidate?domainHint=${encodeURIComponent(identifier)}`;
            const response = yield this.fetch(new Request(this.environmentService.getIdentityUrl() + path, {
                cache: "no-store",
                credentials: this.getCredentials(),
                headers: headers,
                method: "GET",
            }));
            if (response.status === 200) {
                const body = yield response.json();
                return new SsoPreValidateResponse(body);
            }
            else {
                const error = yield this.handleError(response, false, true);
                return Promise.reject(error);
            }
        });
    }
    postCreateSponsorship(sponsoredOrgId, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.send("POST", "/organization/sponsorship/" +
                (this.platformUtilsService.isSelfHost() ? "self-hosted/" : "") +
                sponsoredOrgId +
                "/families-for-enterprise", request, true, false);
        });
    }
    getSponsorshipSyncStatus(sponsoredOrgId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const response = yield this.send("GET", "/organization/sponsorship/" + sponsoredOrgId + "/sync-status", null, true, true);
            return new OrganizationSponsorshipSyncStatusResponse(response);
        });
    }
    deleteRevokeSponsorship(sponsoringOrganizationId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.send("DELETE", "/organization/sponsorship/" +
                (this.platformUtilsService.isSelfHost() ? "self-hosted/" : "") +
                sponsoringOrganizationId, null, true, false);
        });
    }
    deleteRemoveSponsorship(sponsoringOrgId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.send("DELETE", "/organization/sponsorship/sponsored/" + sponsoringOrgId, null, true, false);
        });
    }
    postPreValidateSponsorshipToken(sponsorshipToken) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const r = yield this.send("POST", "/organization/sponsorship/validate-token?sponsorshipToken=" +
                encodeURIComponent(sponsorshipToken), null, true, true);
            return r;
        });
    }
    postRedeemSponsorship(sponsorshipToken, request) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.send("POST", "/organization/sponsorship/redeem?sponsorshipToken=" + encodeURIComponent(sponsorshipToken), request, true, false);
        });
    }
    postResendSponsorshipOffer(sponsoringOrgId) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            return yield this.send("POST", "/organization/sponsorship/" + sponsoringOrgId + "/families-for-enterprise/resend", null, true, false);
        });
    }
    doAuthRefresh() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const refreshToken = yield this.tokenService.getRefreshToken();
            if (refreshToken != null && refreshToken !== "") {
                return this.doRefreshToken();
            }
            const clientId = yield this.tokenService.getClientId();
            const clientSecret = yield this.tokenService.getClientSecret();
            if (!Utils.isNullOrWhitespace(clientId) && !Utils.isNullOrWhitespace(clientSecret)) {
                return this.doApiTokenRefresh();
            }
            throw new Error("Cannot refresh token, no refresh token or api keys are stored");
        });
    }
    doRefreshToken() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const refreshToken = yield this.tokenService.getRefreshToken();
            if (refreshToken == null || refreshToken === "") {
                throw new Error();
            }
            const headers = new Headers({
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
                Accept: "application/json",
                "Device-Type": this.deviceType,
            });
            if (this.customUserAgent != null) {
                headers.set("User-Agent", this.customUserAgent);
            }
            const decodedToken = yield this.tokenService.decodeToken();
            const response = yield this.fetch(new Request(this.environmentService.getIdentityUrl() + "/connect/token", {
                body: this.qsStringify({
                    grant_type: "refresh_token",
                    client_id: decodedToken.client_id,
                    refresh_token: refreshToken,
                }),
                cache: "no-store",
                credentials: this.getCredentials(),
                headers: headers,
                method: "POST",
            }));
            if (response.status === 200) {
                const responseJson = yield response.json();
                const tokenResponse = new IdentityTokenResponse(responseJson);
                yield this.tokenService.setTokens(tokenResponse.accessToken, tokenResponse.refreshToken, null);
            }
            else {
                const error = yield this.handleError(response, true, true);
                return Promise.reject(error);
            }
        });
    }
    doApiTokenRefresh() {
        return api_service_awaiter(this, void 0, void 0, function* () {
            const clientId = yield this.tokenService.getClientId();
            const clientSecret = yield this.tokenService.getClientSecret();
            const appId = yield this.appIdService.getAppId();
            const deviceRequest = new DeviceRequest(appId, this.platformUtilsService);
            const tokenRequest = new UserApiTokenRequest(clientId, clientSecret, new TokenTwoFactorRequest(), deviceRequest);
            const response = yield this.postIdentityToken(tokenRequest);
            if (!(response instanceof IdentityTokenResponse)) {
                throw new Error("Invalid response received when refreshing api token");
            }
            yield this.tokenService.setToken(response.accessToken);
        });
    }
    send(method, path, body, authed, hasResponse, apiUrl, alterHeaders) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            apiUrl = Utils.isNullOrWhitespace(apiUrl) ? this.environmentService.getApiUrl() : apiUrl;
            // Prevent directory traversal from malicious paths
            const pathParts = path.split("?");
            const requestUrl = apiUrl + Utils.normalizePath(pathParts[0]) + (pathParts.length > 1 ? `?${pathParts[1]}` : "");
            const headers = new Headers({
                "Device-Type": this.deviceType,
            });
            if (this.customUserAgent != null) {
                headers.set("User-Agent", this.customUserAgent);
            }
            const requestInit = {
                cache: "no-store",
                credentials: this.getCredentials(),
                method: method,
            };
            if (authed) {
                const authHeader = yield this.getActiveBearerToken();
                headers.set("Authorization", "Bearer " + authHeader);
            }
            if (body != null) {
                if (typeof body === "string") {
                    requestInit.body = body;
                    headers.set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                }
                else if (typeof body === "object") {
                    if (body instanceof FormData) {
                        requestInit.body = body;
                    }
                    else {
                        headers.set("Content-Type", "application/json; charset=utf-8");
                        requestInit.body = JSON.stringify(body);
                    }
                }
            }
            if (hasResponse) {
                headers.set("Accept", "application/json");
            }
            if (alterHeaders != null) {
                alterHeaders(headers);
            }
            requestInit.headers = headers;
            const response = yield this.fetch(new Request(requestUrl, requestInit));
            const responseType = response.headers.get("content-type");
            const responseIsJson = responseType != null && responseType.indexOf("application/json") !== -1;
            if (hasResponse && response.status === 200 && responseIsJson) {
                const responseJson = yield response.json();
                return responseJson;
            }
            else if (response.status !== 200) {
                const error = yield this.handleError(response, false, authed);
                return Promise.reject(error);
            }
        });
    }
    handleError(response, tokenError, authed) {
        return api_service_awaiter(this, void 0, void 0, function* () {
            let responseJson = null;
            if (this.isJsonResponse(response)) {
                responseJson = yield response.json();
            }
            else if (this.isTextResponse(response)) {
                responseJson = { Message: yield response.text() };
            }
            if (authed) {
                if (response.status === 401 ||
                    response.status === 403 ||
                    (tokenError &&
                        response.status === 400 &&
                        responseJson != null &&
                        responseJson.error === "invalid_grant")) {
                    yield this.logoutCallback(true);
                    return null;
                }
            }
            return new ErrorResponse(responseJson, response.status, tokenError);
        });
    }
    qsStringify(params) {
        return Object.keys(params)
            .map((key) => {
            return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
        })
            .join("&");
    }
    getCredentials() {
        if (!this.isWebClient || this.environmentService.hasBaseUrl()) {
            return "include";
        }
        return undefined;
    }
    addEventParameters(base, start, end, token) {
        if (start != null) {
            base += "?start=" + start;
        }
        if (end != null) {
            base += base.indexOf("?") > -1 ? "&" : "?";
            base += "end=" + end;
        }
        if (token != null) {
            base += base.indexOf("?") > -1 ? "&" : "?";
            base += "continuationToken=" + token;
        }
        return base;
    }
    isJsonResponse(response) {
        const typeHeader = response.headers.get("content-type");
        return typeHeader != null && typeHeader.indexOf("application/json") > -1;
    }
    isTextResponse(response) {
        const typeHeader = response.headers.get("content-type");
        return typeHeader != null && typeHeader.indexOf("text") > -1;
    }
}

;// CONCATENATED MODULE: ./src/services/node-api.service.ts




global.fetch = (external_node_fetch_default());
global.Request = external_node_fetch_namespaceObject.Request;
global.Response = external_node_fetch_namespaceObject.Response;
global.Headers = external_node_fetch_namespaceObject.Headers;
global.FormData = external_form_data_namespaceObject;
class NodeApiService extends ApiService {
    constructor(tokenService, platformUtilsService, environmentService, appIdService, logoutCallback, customUserAgent = null) {
        super(tokenService, platformUtilsService, environmentService, appIdService, logoutCallback, customUserAgent);
    }
    nativeFetch(request) {
        const proxy = process.env.http_proxy || process.env.https_proxy;
        if (proxy) {
            request.agent = new external_https_proxy_agent_namespaceObject.HttpsProxyAgent(proxy);
        }
        return fetch(request);
    }
}

;// CONCATENATED MODULE: ./src/services/node-env-secure-storage.service.ts
var node_env_secure_storage_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



class NodeEnvSecureStorageService {
    constructor(storageService, logService, cryptoService) {
        this.storageService = storageService;
        this.logService = logService;
        this.cryptoService = cryptoService;
    }
    get(key) {
        return node_env_secure_storage_service_awaiter(this, void 0, void 0, function* () {
            const value = yield this.storageService.get(this.makeProtectedStorageKey(key));
            if (value == null) {
                return null;
            }
            const obj = yield this.decrypt(value);
            return obj;
        });
    }
    has(key) {
        return node_env_secure_storage_service_awaiter(this, void 0, void 0, function* () {
            return (yield this.get(key)) != null;
        });
    }
    save(key, obj) {
        return node_env_secure_storage_service_awaiter(this, void 0, void 0, function* () {
            if (obj == null) {
                return this.remove(key);
            }
            if (obj !== null && typeof obj !== "string") {
                throw new Error("Only string storage is allowed.");
            }
            const protectedObj = yield this.encrypt(obj);
            yield this.storageService.save(this.makeProtectedStorageKey(key), protectedObj);
        });
    }
    remove(key) {
        return this.storageService.remove(this.makeProtectedStorageKey(key));
    }
    encrypt(plainValue) {
        return node_env_secure_storage_service_awaiter(this, void 0, void 0, function* () {
            const sessionKey = this.getSessionKey();
            if (sessionKey == null) {
                throw new Error("No session key available.");
            }
            const encValue = yield this.cryptoService().encryptToBytes(Utils.fromB64ToArray(plainValue).buffer, sessionKey);
            if (encValue == null) {
                throw new Error("Value didn't encrypt.");
            }
            return Utils.fromBufferToB64(encValue.buffer);
        });
    }
    decrypt(encValue) {
        return node_env_secure_storage_service_awaiter(this, void 0, void 0, function* () {
            try {
                const sessionKey = this.getSessionKey();
                if (sessionKey == null) {
                    return null;
                }
                const encBuf = EncArrayBuffer.fromB64(encValue);
                const decValue = yield this.cryptoService().decryptFromBytes(encBuf, sessionKey);
                if (decValue == null) {
                    this.logService.info("Failed to decrypt.");
                    return null;
                }
                return Utils.fromBufferToB64(decValue);
            }
            catch (e) {
                this.logService.info("Decrypt error.");
                return null;
            }
        });
    }
    getSessionKey() {
        try {
            if (process.env.BW_SESSION != null) {
                const sessionBuffer = Utils.fromB64ToArray(process.env.BW_SESSION).buffer;
                if (sessionBuffer != null) {
                    const sessionKey = new SymmetricCryptoKey(sessionBuffer);
                    if (sessionBuffer != null) {
                        return sessionKey;
                    }
                }
            }
        }
        catch (e) {
            this.logService.info("Session key is invalid.");
        }
        return null;
    }
    makeProtectedStorageKey(key) {
        return "__PROTECTED__" + key;
    }
}

;// CONCATENATED MODULE: ./src/commands/export.command.ts
var export_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};





class ExportCommand {
    constructor(exportService, policyService) {
        this.exportService = exportService;
        this.policyService = policyService;
    }
    run(options) {
        var _a;
        return export_command_awaiter(this, void 0, void 0, function* () {
            if (options.organizationid == null &&
                (yield this.policyService.policyAppliesToUser(PolicyType.DisablePersonalVaultExport))) {
                return Response.badRequest("One or more organization policies prevents you from exporting your personal vault.");
            }
            const format = (_a = options.format) !== null && _a !== void 0 ? _a : "csv";
            if (options.organizationid != null && !Utils.isGuid(options.organizationid)) {
                return Response.error("`" + options.organizationid + "` is not a GUID.");
            }
            let exportContent = null;
            try {
                exportContent =
                    format === "encrypted_json"
                        ? yield this.getProtectedExport(options.password, options.organizationid)
                        : yield this.getUnprotectedExport(format, options.organizationid);
            }
            catch (e) {
                return Response.error(e);
            }
            return yield this.saveFile(exportContent, options, format);
        });
    }
    getProtectedExport(passwordOption, organizationId) {
        return export_command_awaiter(this, void 0, void 0, function* () {
            const password = yield this.promptPassword(passwordOption);
            return password == null
                ? yield this.exportService.getExport("encrypted_json", organizationId)
                : yield this.exportService.getPasswordProtectedExport(password, organizationId);
        });
    }
    getUnprotectedExport(format, organizationId) {
        return export_command_awaiter(this, void 0, void 0, function* () {
            return this.exportService.getExport(format, organizationId);
        });
    }
    saveFile(exportContent, options, format) {
        return export_command_awaiter(this, void 0, void 0, function* () {
            try {
                const fileName = this.getFileName(format, options.organizationid != null ? "org" : null);
                return yield CliUtils.saveResultToFile(exportContent, options.output, fileName);
            }
            catch (e) {
                return Response.error(e.toString());
            }
        });
    }
    getFileName(format, prefix) {
        if (format === "encrypted_json") {
            if (prefix == null) {
                prefix = "encrypted";
            }
            else {
                prefix = "encrypted_" + prefix;
            }
            format = "json";
        }
        return this.exportService.getFileName(prefix, format);
    }
    promptPassword(password) {
        return export_command_awaiter(this, void 0, void 0, function* () {
            // boolean => flag set with no value, we need to prompt for password
            // string => flag set with value, use this value for password
            // undefined/null/false => account protect, not password, no password needed
            if (typeof password === "string") {
                return password;
            }
            else if (password) {
                const answer = yield external_inquirer_namespaceObject.createPromptModule({
                    output: process.stderr,
                })({
                    type: "password",
                    name: "password",
                    message: "Export file password:",
                });
                return answer.password;
            }
            return null;
        });
    }
}

;// CONCATENATED MODULE: ./src/commands/import.command.ts
var import_command_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




class ImportCommand {
    constructor(importService, organizationService) {
        this.importService = importService;
        this.organizationService = organizationService;
    }
    run(format, filepath, options) {
        return import_command_awaiter(this, void 0, void 0, function* () {
            const organizationId = options.organizationid;
            if (organizationId != null) {
                const organization = yield this.organizationService.getFromState(organizationId);
                if (organization == null) {
                    return Response.badRequest(`You do not belong to an organization with the ID of ${organizationId}. Check the organization ID and sync your vault.`);
                }
                if (!organization.canAccessImportExport) {
                    return Response.badRequest("You are not authorized to import into the provided organization.");
                }
            }
            if (options.formats || false) {
                return yield this.list();
            }
            else {
                return yield this.import(format, filepath, organizationId);
            }
        });
    }
    import(format, filepath, organizationId) {
        return import_command_awaiter(this, void 0, void 0, function* () {
            if (format == null) {
                return Response.badRequest("`format` was not provided.");
            }
            if (filepath == null || filepath === "") {
                return Response.badRequest("`filepath` was not provided.");
            }
            const importer = yield this.importService.getImporter(format, organizationId);
            if (importer === null) {
                return Response.badRequest("Proper importer type required.");
            }
            try {
                let contents;
                if (format === "1password1pux") {
                    contents = yield CliUtils.extract1PuxContent(filepath);
                }
                else {
                    contents = yield CliUtils.readFile(filepath);
                }
                if (contents === null || contents === "") {
                    return Response.badRequest("Import file was empty.");
                }
                const response = yield this.doImport(importer, contents, organizationId);
                if (response.success) {
                    response.data = new MessageResponse("Imported " + filepath, null);
                }
                return response;
            }
            catch (err) {
                return Response.badRequest(err);
            }
        });
    }
    list() {
        return import_command_awaiter(this, void 0, void 0, function* () {
            const options = this.importService
                .getImportOptions()
                .sort((a, b) => {
                return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
            })
                .map((option) => option.id)
                .join("\n");
            const res = new MessageResponse("Supported input formats:", options);
            res.raw = options;
            return Response.success(res);
        });
    }
    doImport(importer, contents, organizationId) {
        return import_command_awaiter(this, void 0, void 0, function* () {
            const err = yield this.importService.import(importer, contents, organizationId);
            if (err != null) {
                if (err.passwordRequired) {
                    importer = this.importService.getImporter("bitwardenpasswordprotected", organizationId, yield this.promptPassword());
                    return this.doImport(importer, contents, organizationId);
                }
                return Response.badRequest(err.message);
            }
            return Response.success();
        });
    }
    promptPassword() {
        return import_command_awaiter(this, void 0, void 0, function* () {
            const answer = yield external_inquirer_namespaceObject.createPromptModule({
                output: process.stderr,
            })({
                type: "password",
                name: "password",
                message: "Import file password:",
            });
            return answer.password;
        });
    }
}

;// CONCATENATED MODULE: ./src/vault.program.ts
var vault_program_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};














const vault_program_writeLn = CliUtils.writeLn;
class VaultProgram extends Program {
    constructor(main) {
        super(main);
        this.main = main;
    }
    register() {
        return vault_program_awaiter(this, void 0, void 0, function* () {
            external_commander_namespaceObject.addCommand(this.listCommand())
                .addCommand(this.getCommand())
                .addCommand(this.createCommand())
                .addCommand(this.editCommand())
                .addCommand(this.deleteCommand())
                .addCommand(this.restoreCommand())
                .addCommand(this.shareCommand("move", false))
                .addCommand(this.confirmCommand())
                .addCommand(this.importCommand())
                .addCommand(this.exportCommand())
                .addCommand(this.shareCommand("share", true));
        });
    }
    validateObject(requestedObject, validObjects) {
        let success = true;
        if (!validObjects.includes(requestedObject)) {
            success = false;
            this.processResponse(Response.badRequest('Unknown object "' +
                requestedObject +
                '". Allowed objects are ' +
                validObjects.join(", ") +
                "."));
        }
        return success;
    }
    listCommand() {
        const listObjects = [
            "items",
            "folders",
            "collections",
            "org-collections",
            "org-members",
            "organizations",
        ];
        return new external_commander_namespaceObject.Command("list")
            .arguments("<object>")
            .description("List an array of objects from the vault.", {
            object: "Valid objects are: " + listObjects.join(", "),
        })
            .option("--search <search>", "Perform a search on the listed objects.")
            .option("--url <url>", "Filter items of type login with a url-match search.")
            .option("--folderid <folderid>", "Filter items by folder id.")
            .option("--collectionid <collectionid>", "Filter items by collection id.")
            .option("--organizationid <organizationid>", "Filter items or collections by organization id.")
            .option("--trash", "Filter items that are deleted and in the trash.")
            .on("--help", () => {
            vault_program_writeLn("\n  Notes:");
            vault_program_writeLn("");
            vault_program_writeLn("    Combining search with a filter performs a logical AND operation.");
            vault_program_writeLn("");
            vault_program_writeLn("    Combining multiple filters performs a logical OR operation.");
            vault_program_writeLn("");
            vault_program_writeLn("  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw list items");
            vault_program_writeLn("    bw list items --folderid 60556c31-e649-4b5d-8daf-fc1c391a1bf2");
            vault_program_writeLn("    bw list items --search google --folderid 60556c31-e649-4b5d-8daf-fc1c391a1bf2");
            vault_program_writeLn("    bw list items --url https://google.com");
            vault_program_writeLn("    bw list items --folderid null");
            vault_program_writeLn("    bw list items --organizationid notnull");
            vault_program_writeLn("    bw list items --folderid 60556c31-e649-4b5d-8daf-fc1c391a1bf2 --organizationid notnull");
            vault_program_writeLn("    bw list items --trash");
            vault_program_writeLn("    bw list folders --search email");
            vault_program_writeLn("    bw list org-members --organizationid 60556c31-e649-4b5d-8daf-fc1c391a1bf2");
            vault_program_writeLn("", true);
        })
            .action((object, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, listObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new ListCommand(this.main.cipherService, this.main.folderService, this.main.collectionService, this.main.organizationService, this.main.searchService, this.main.organizationUserService, this.main.apiService);
            const response = yield command.run(object, cmd);
            this.processResponse(response);
        }));
    }
    getCommand() {
        const getObjects = [
            "item",
            "username",
            "password",
            "uri",
            "totp",
            "notes",
            "exposed",
            "attachment",
            "folder",
            "collection",
            "org-collection",
            "organization",
            "template",
            "fingerprint",
            "send",
        ];
        return new external_commander_namespaceObject.Command("get")
            .arguments("<object> <id>")
            .description("Get an object from the vault.", {
            object: "Valid objects are: " + getObjects.join(", "),
            id: "Search term or object's globally unique `id`.",
        })
            .option("--itemid <itemid>", "Attachment's item id.")
            .option("--output <output>", "Output directory or filename for attachment.")
            .option("--organizationid <organizationid>", "Organization id for an organization object.")
            .on("--help", () => {
            vault_program_writeLn("\n  If raw output is specified and no output filename or directory is given for");
            vault_program_writeLn("  an attachment query, the attachment content is written to stdout.");
            vault_program_writeLn("");
            vault_program_writeLn("  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw get item 99ee88d2-6046-4ea7-92c2-acac464b1412");
            vault_program_writeLn("    bw get password https://google.com");
            vault_program_writeLn("    bw get totp google.com");
            vault_program_writeLn("    bw get notes google.com");
            vault_program_writeLn("    bw get exposed yahoo.com");
            vault_program_writeLn("    bw get attachment b857igwl1dzrs2 --itemid 99ee88d2-6046-4ea7-92c2-acac464b1412 " +
                "--output ./photo.jpg");
            vault_program_writeLn("    bw get attachment photo.jpg --itemid 99ee88d2-6046-4ea7-92c2-acac464b1412 --raw");
            vault_program_writeLn("    bw get folder email");
            vault_program_writeLn("    bw get template folder");
            vault_program_writeLn("", true);
        })
            .action((object, id, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, getObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new GetCommand(this.main.cipherService, this.main.folderService, this.main.collectionService, this.main.totpService, this.main.auditService, this.main.cryptoService, this.main.stateService, this.main.searchService, this.main.apiService, this.main.organizationService);
            const response = yield command.run(object, id, cmd);
            this.processResponse(response);
        }));
    }
    createCommand() {
        const createObjects = ["item", "attachment", "folder", "org-collection"];
        return new external_commander_namespaceObject.Command("create")
            .arguments("<object> [encodedJson]")
            .description("Create an object in the vault.", {
            object: "Valid objects are: " + createObjects.join(", "),
            encodedJson: "Encoded json of the object to create. Can also be piped into stdin.",
        })
            .option("--file <file>", "Path to file for attachment.")
            .option("--itemid <itemid>", "Attachment's item id.")
            .option("--organizationid <organizationid>", "Organization id for an organization object.")
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw create folder eyJuYW1lIjoiTXkgRm9sZGVyIn0K");
            vault_program_writeLn("    echo 'eyJuYW1lIjoiTXkgRm9sZGVyIn0K' | bw create folder");
            vault_program_writeLn("    bw create attachment --file ./myfile.csv " +
                "--itemid 16b15b89-65b3-4639-ad2a-95052a6d8f66");
            vault_program_writeLn("", true);
        })
            .action((object, encodedJson, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, createObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new CreateCommand(this.main.cipherService, this.main.folderService, this.main.stateService, this.main.cryptoService, this.main.apiService, this.main.folderApiService);
            const response = yield command.run(object, encodedJson, cmd);
            this.processResponse(response);
        }));
    }
    editCommand() {
        const editObjects = ["item", "item-collections", "folder", "org-collection"];
        return new external_commander_namespaceObject.Command("edit")
            .arguments("<object> <id> [encodedJson]")
            .description("Edit an object from the vault.", {
            object: "Valid objects are: " + editObjects.join(", "),
            id: "Object's globally unique `id`.",
            encodedJson: "Encoded json of the object to create. Can also be piped into stdin.",
        })
            .option("--organizationid <organizationid>", "Organization id for an organization object.")
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw edit folder 5cdfbd80-d99f-409b-915b-f4c5d0241b02 eyJuYW1lIjoiTXkgRm9sZGVyMiJ9Cg==");
            vault_program_writeLn("    echo 'eyJuYW1lIjoiTXkgRm9sZGVyMiJ9Cg==' | " +
                "bw edit folder 5cdfbd80-d99f-409b-915b-f4c5d0241b02");
            vault_program_writeLn("    bw edit item-collections 78307355-fd25-416b-88b8-b33fd0e88c82 " +
                "WyI5NzQwNTNkMC0zYjMzLTRiOTgtODg2ZS1mZWNmNWM4ZGJhOTYiXQ==");
            vault_program_writeLn("", true);
        })
            .action((object, id, encodedJson, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, editObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new EditCommand(this.main.cipherService, this.main.folderService, this.main.cryptoService, this.main.apiService, this.main.folderApiService);
            const response = yield command.run(object, id, encodedJson, cmd);
            this.processResponse(response);
        }));
    }
    deleteCommand() {
        const deleteObjects = ["item", "attachment", "folder", "org-collection"];
        return new external_commander_namespaceObject.Command("delete")
            .arguments("<object> <id>")
            .description("Delete an object from the vault.", {
            object: "Valid objects are: " + deleteObjects.join(", "),
            id: "Object's globally unique `id`.",
        })
            .option("--itemid <itemid>", "Attachment's item id.")
            .option("--organizationid <organizationid>", "Organization id for an organization object.")
            .option("-p, --permanent", "Permanently deletes the item instead of soft-deleting it (item only).")
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw delete item 7063feab-4b10-472e-b64c-785e2b870b92");
            vault_program_writeLn("    bw delete item 89c21cd2-fab0-4f69-8c6e-ab8a0168f69a --permanent");
            vault_program_writeLn("    bw delete folder 5cdfbd80-d99f-409b-915b-f4c5d0241b02");
            vault_program_writeLn("    bw delete attachment b857igwl1dzrs2 --itemid 310d5ffd-e9a2-4451-af87-ea054dce0f78");
            vault_program_writeLn("", true);
        })
            .action((object, id, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, deleteObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new DeleteCommand(this.main.cipherService, this.main.folderService, this.main.stateService, this.main.apiService, this.main.folderApiService);
            const response = yield command.run(object, id, cmd);
            this.processResponse(response);
        }));
    }
    restoreCommand() {
        const restoreObjects = ["item"];
        return new external_commander_namespaceObject.Command("restore")
            .arguments("<object> <id>")
            .description("Restores an object from the trash.", {
            object: "Valid objects are: " + restoreObjects.join(", "),
            id: "Object's globally unique `id`.",
        })
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw restore item 7063feab-4b10-472e-b64c-785e2b870b92");
            vault_program_writeLn("", true);
        })
            .action((object, id, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, restoreObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new RestoreCommand(this.main.cipherService);
            const response = yield command.run(object, id);
            this.processResponse(response);
        }));
    }
    shareCommand(commandName, deprecated) {
        return new external_commander_namespaceObject.Command(commandName)
            .arguments("<id> <organizationId> [encodedJson]")
            .description((deprecated ? "--DEPRECATED-- " : "") + "Move an item to an organization.", {
            id: "Object's globally unique `id`.",
            organizationId: "Organization's globally unique `id`.",
            encodedJson: "Encoded json of an array of collection ids. Can also be piped into stdin.",
        })
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw " +
                commandName +
                " 4af958ce-96a7-45d9-beed-1e70fabaa27a " +
                "6d82949b-b44d-468a-adae-3f3bacb0ea32 WyI5NzQwNTNkMC0zYjMzLTRiOTgtODg2ZS1mZWNmNWM4ZGJhOTYiXQ==");
            vault_program_writeLn("    echo '[\"974053d0-3b33-4b98-886e-fecf5c8dba96\"]' | bw encode | " +
                "bw " +
                commandName +
                " 4af958ce-96a7-45d9-beed-1e70fabaa27a 6d82949b-b44d-468a-adae-3f3bacb0ea32");
            if (deprecated) {
                vault_program_writeLn("");
                vault_program_writeLn('--DEPRECATED See "bw move" for the current implementation--');
            }
            vault_program_writeLn("", true);
        })
            .action((id, organizationId, encodedJson, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const command = new ShareCommand(this.main.cipherService);
            const response = yield command.run(id, organizationId, encodedJson);
            this.processResponse(response);
        }));
    }
    confirmCommand() {
        const confirmObjects = ["org-member"];
        return new external_commander_namespaceObject.Command("confirm")
            .arguments("<object> <id>")
            .description("Confirm an object to the organization.", {
            object: "Valid objects are: " + confirmObjects.join(", "),
            id: "Object's globally unique `id`.",
        })
            .option("--organizationid <organizationid>", "Organization id for an organization object.")
            .on("--help", () => {
            vault_program_writeLn("\n  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw confirm org-member 7063feab-4b10-472e-b64c-785e2b870b92 " +
                "--organizationid 310d5ffd-e9a2-4451-af87-ea054dce0f78");
            vault_program_writeLn("", true);
        })
            .action((object, id, cmd) => vault_program_awaiter(this, void 0, void 0, function* () {
            if (!this.validateObject(object, confirmObjects)) {
                return;
            }
            yield this.exitIfLocked();
            const command = new ConfirmCommand(this.main.apiService, this.main.cryptoService, this.main.organizationUserService);
            const response = yield command.run(object, id, cmd);
            this.processResponse(response);
        }));
    }
    importCommand() {
        return new external_commander_namespaceObject.Command("import")
            .arguments("[format] [input]")
            .description("Import vault data from a file.", {
            format: "The format of [input]",
            input: "Filepath to data to import",
        })
            .option("--formats", "List formats")
            .option("--organizationid <organizationid>", "ID of the organization to import to.")
            .on("--help", () => {
            vault_program_writeLn("\n Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw import --formats");
            vault_program_writeLn("    bw import bitwardencsv ./from/source.csv");
            vault_program_writeLn("    bw import keepass2xml keepass_backup.xml");
            vault_program_writeLn("    bw import --organizationid cf14adc3-aca5-4573-890a-f6fa231436d9 keepass2xml keepass_backup.xml");
        })
            .action((format, filepath, options) => vault_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const command = new ImportCommand(this.main.importService, this.main.organizationService);
            const response = yield command.run(format, filepath, options);
            this.processResponse(response);
        }));
    }
    exportCommand() {
        return new external_commander_namespaceObject.Command("export")
            .description("Export vault data to a CSV or JSON file.", {})
            .option("--output <output>", "Output directory or filename.")
            .option("--format <format>", "Export file format.")
            .option("--password [password]", "Use password to encrypt instead of your Bitwarden account encryption key. Only applies to the encrypted_json format.")
            .option("--organizationid <organizationid>", "Organization id for an organization.")
            .on("--help", () => {
            vault_program_writeLn("\n  Notes:");
            vault_program_writeLn("");
            vault_program_writeLn("    Valid formats are `csv`, `json`, and `encrypted_json`. Default format is `csv`.");
            vault_program_writeLn("");
            vault_program_writeLn("    If --raw option is specified and no output filename or directory is given, the");
            vault_program_writeLn("    result is written to stdout.");
            vault_program_writeLn("");
            vault_program_writeLn("  Examples:");
            vault_program_writeLn("");
            vault_program_writeLn("    bw export");
            vault_program_writeLn("    bw --raw export");
            vault_program_writeLn("    bw export myPassword321");
            vault_program_writeLn("    bw export myPassword321 --format json");
            vault_program_writeLn("    bw export --output ./exp/bw.csv");
            vault_program_writeLn("    bw export myPassword321 --output bw.json --format json");
            vault_program_writeLn("    bw export myPassword321 --organizationid 7063feab-4b10-472e-b64c-785e2b870b92");
            vault_program_writeLn("", true);
        })
            .action((options) => vault_program_awaiter(this, void 0, void 0, function* () {
            yield this.exitIfLocked();
            const command = new ExportCommand(this.main.exportService, this.main.policyService);
            const response = yield command.run(options);
            this.processResponse(response);
        }));
    }
}

;// CONCATENATED MODULE: ./src/bw.ts
var bw_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



























































// Polyfills
global.DOMParser = new external_jsdom_namespaceObject.JSDOM().window.DOMParser;
// eslint-disable-next-line
const packageJson = __webpack_require__(147);
class Main {
    constructor() {
        let p = null;
        const relativeDataDir = external_path_namespaceObject.join(external_path_namespaceObject.dirname(process.execPath), "bw-data");
        if (external_fs_namespaceObject.existsSync(relativeDataDir)) {
            p = relativeDataDir;
        }
        else if (process.env.BITWARDENCLI_APPDATA_DIR) {
            p = external_path_namespaceObject.resolve(process.env.BITWARDENCLI_APPDATA_DIR);
        }
        else if (process.platform === "darwin") {
            p = external_path_namespaceObject.join(process.env.HOME, "Library/Application Support/Bitwarden CLI");
        }
        else if (process.platform === "win32") {
            p = external_path_namespaceObject.join(process.env.APPDATA, "Bitwarden CLI");
        }
        else if (process.env.XDG_CONFIG_HOME) {
            p = external_path_namespaceObject.join(process.env.XDG_CONFIG_HOME, "Bitwarden CLI");
        }
        else {
            p = external_path_namespaceObject.join(process.env.HOME, ".config/Bitwarden CLI");
        }
        this.i18nService = new I18nService("en", "./locales");
        this.platformUtilsService = new CliPlatformUtilsService(ClientType.Cli, packageJson);
        this.logService = new ConsoleLogService(this.platformUtilsService.isDev(), (level) => process.env.BITWARDENCLI_DEBUG !== "true" && level <= LogLevelType.Info);
        this.cryptoFunctionService = new NodeCryptoFunctionService();
        this.encryptService = new EncryptServiceImplementation(this.cryptoFunctionService, this.logService, true);
        this.storageService = new LowdbStorageService(this.logService, null, p, false, true);
        this.secureStorageService = new NodeEnvSecureStorageService(this.storageService, this.logService, () => this.cryptoService);
        this.memoryStorageService = new MemoryStorageService();
        this.stateMigrationService = new StateMigrationService(this.storageService, this.secureStorageService, new StateFactory(GlobalState, Account));
        this.stateService = new StateService(this.storageService, this.secureStorageService, this.memoryStorageService, this.logService, this.stateMigrationService, new StateFactory(GlobalState, Account));
        this.cryptoService = new CryptoService(this.cryptoFunctionService, this.encryptService, this.platformUtilsService, this.logService, this.stateService);
        this.appIdService = new AppIdService(this.storageService);
        this.tokenService = new TokenService(this.stateService);
        this.messagingService = new NoopMessagingService();
        this.environmentService = new EnvironmentService(this.stateService);
        const customUserAgent = "Bitwarden_CLI/" +
            this.platformUtilsService.getApplicationVersionSync() +
            " (" +
            this.platformUtilsService.getDeviceString().toUpperCase() +
            ")";
        this.apiService = new NodeApiService(this.tokenService, this.platformUtilsService, this.environmentService, this.appIdService, (expired) => bw_awaiter(this, void 0, void 0, function* () { return yield this.logout(); }), customUserAgent);
        this.syncNotifierService = new SyncNotifierService();
        this.organizationApiService = new OrganizationApiService(this.apiService, this.syncService);
        this.containerService = new ContainerService(this.cryptoService, this.encryptService);
        this.settingsService = new SettingsService(this.stateService);
        this.fileUploadService = new FileUploadService(this.logService, this.apiService);
        this.cipherService = new CipherService(this.cryptoService, this.settingsService, this.apiService, this.fileUploadService, this.i18nService, null, this.logService, this.stateService, this.encryptService);
        this.broadcasterService = new BroadcasterService();
        this.folderService = new FolderService(this.cryptoService, this.i18nService, this.cipherService, this.stateService);
        this.folderApiService = new FolderApiService(this.folderService, this.apiService);
        this.collectionService = new CollectionService(this.cryptoService, this.i18nService, this.stateService);
        this.searchService = new SearchService(this.cipherService, this.logService, this.i18nService);
        this.providerService = new ProviderService(this.stateService);
        this.organizationService = new OrganizationService(this.stateService);
        this.organizationUserService = new OrganizationUserServiceImplementation(this.apiService);
        this.policyService = new PolicyService(this.stateService, this.organizationService);
        this.sendService = new SendService(this.cryptoService, this.apiService, this.fileUploadService, this.i18nService, this.cryptoFunctionService, this.stateService);
        this.keyConnectorService = new KeyConnectorService(this.stateService, this.cryptoService, this.apiService, this.tokenService, this.logService, this.organizationService, this.cryptoFunctionService, (expired) => bw_awaiter(this, void 0, void 0, function* () { return yield this.logout(); }));
        this.twoFactorService = new TwoFactorService(this.i18nService, this.platformUtilsService);
        this.authService = new AuthService(this.cryptoService, this.apiService, this.tokenService, this.appIdService, this.platformUtilsService, this.messagingService, this.logService, this.keyConnectorService, this.environmentService, this.stateService, this.twoFactorService, this.i18nService, this.encryptService);
        const lockedCallback = () => bw_awaiter(this, void 0, void 0, function* () { return yield this.cryptoService.clearStoredKey(KeySuffixOptions.Auto); });
        this.vaultTimeoutSettingsService = new VaultTimeoutSettingsService(this.cryptoService, this.tokenService, this.policyService, this.stateService);
        this.vaultTimeoutService = new VaultTimeoutService(this.cipherService, this.folderService, this.collectionService, this.cryptoService, this.platformUtilsService, this.messagingService, this.searchService, this.keyConnectorService, this.stateService, this.authService, this.vaultTimeoutSettingsService, lockedCallback, null);
        this.syncService = new SyncService(this.apiService, this.settingsService, this.folderService, this.cipherService, this.cryptoService, this.collectionService, this.messagingService, this.policyService, this.sendService, this.logService, this.keyConnectorService, this.stateService, this.providerService, this.folderApiService, this.organizationService, (expired) => bw_awaiter(this, void 0, void 0, function* () { return yield this.logout(); }));
        this.passwordGenerationService = new PasswordGenerationService(this.cryptoService, this.policyService, this.stateService);
        this.totpService = new TotpService(this.cryptoFunctionService, this.logService);
        this.importApiService = new ImportApiService(this.apiService);
        this.importService = new ImportService(this.cipherService, this.folderService, this.importApiService, this.i18nService, this.collectionService, this.cryptoService);
        this.exportService = new ExportService(this.folderService, this.cipherService, this.apiService, this.cryptoService, this.cryptoFunctionService);
        this.auditService = new AuditService(this.cryptoFunctionService, this.apiService);
        this.program = new Program(this);
        this.vaultProgram = new VaultProgram(this);
        this.sendProgram = new SendProgram(this);
        this.userVerificationApiService = new UserVerificationApiService(this.apiService);
        this.userVerificationService = new UserVerificationService(this.cryptoService, this.i18nService, this.userVerificationApiService);
    }
    run() {
        return bw_awaiter(this, void 0, void 0, function* () {
            yield this.init();
            yield this.program.register();
            yield this.vaultProgram.register();
            yield this.sendProgram.register();
            external_commander_namespaceObject.parse(process.argv);
            if (process.argv.slice(2).length === 0) {
                external_commander_namespaceObject.outputHelp();
            }
        });
    }
    logout() {
        return bw_awaiter(this, void 0, void 0, function* () {
            this.authService.logOut(() => {
                /* Do nothing */
            });
            const userId = yield this.stateService.getUserId();
            yield Promise.all([
                this.syncService.setLastSync(new Date(0)),
                this.cryptoService.clearKeys(),
                this.settingsService.clear(userId),
                this.cipherService.clear(userId),
                this.folderService.clear(userId),
                this.collectionService.clear(userId),
                this.policyService.clear(userId),
                this.passwordGenerationService.clear(),
            ]);
            yield this.stateService.clean();
            process.env.BW_SESSION = null;
        });
    }
    init() {
        return bw_awaiter(this, void 0, void 0, function* () {
            yield this.storageService.init();
            yield this.stateService.init();
            this.containerService.attachToGlobal(global);
            yield this.environmentService.setUrlsFromStorage();
            const locale = yield this.stateService.getLocale();
            yield this.i18nService.init(locale);
            this.twoFactorService.init();
            const installedVersion = yield this.stateService.getInstalledVersion();
            const currentVersion = yield this.platformUtilsService.getApplicationVersion();
            if (installedVersion == null || installedVersion !== currentVersion) {
                yield this.stateService.setInstalledVersion(currentVersion);
            }
        });
    }
}
const main = new Main();
main.run();

})();

/******/ })()
;
//# sourceMappingURL=bw.js.map