1 import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, ADDRESS_TYPE } from '../constants';
2 import { addPlusAlias, canonicalizeInternalEmail } from '../helpers/email';
3 import type { Address } from '../interfaces';
6 * Get address from email
7 * Remove + alias and transform to lower case
9 export const getByEmail = (addresses: Address[], email = '') => {
10 const value = canonicalizeInternalEmail(email);
11 return addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === value);
15 * Detect if the email address is a valid plus alias and returns the address model appropriate
17 export const getAddressFromPlusAlias = (addresses: Address[], email = ''): Address | undefined => {
18 const plusIndex = email.indexOf('+');
19 const atIndex = email.indexOf('@');
21 if (plusIndex === -1 || atIndex === -1) {
25 // Remove the plus alias part to find a match with existing addresses
26 const address = getByEmail(addresses, email);
27 const { Status, Receive, Send } = address || {};
29 if (!Status || !Receive || !Send) {
30 // pm.me addresses on free accounts (Send = 0)
34 const plusPart = email.substring(plusIndex + 1, atIndex);
36 // Returns an address where the Email is build to respect the existing capitalization and add the plus part
37 return { ...(address as Address), Email: addPlusAlias(address?.Email, plusPart) };
40 export const getSupportedPlusAlias = ({
44 selfAttendeeEmail: string;
45 selfAddressEmail: string;
47 if (!selfAttendeeEmail) {
48 return selfAddressEmail;
51 const plusIndex = selfAttendeeEmail.indexOf('+');
52 const atIndex = selfAttendeeEmail.indexOf('@');
53 const plusPart = selfAttendeeEmail.substring(plusIndex + 1, atIndex);
55 if (plusIndex === -1) {
56 return selfAddressEmail;
59 return addPlusAlias(selfAddressEmail, plusPart);
62 export const getIsNonDefault = (address: Address) => {
64 address.Status === ADDRESS_STATUS.STATUS_DISABLED ||
65 address.Type === ADDRESS_TYPE.TYPE_EXTERNAL ||
66 address.Receive === ADDRESS_RECEIVE.RECEIVE_NO ||
67 address.Send === ADDRESS_SEND.SEND_NO
71 const addressSort = (a: Address, b: Address) => {
72 if (getIsNonDefault(a)) {
75 if (getIsNonDefault(b)) {
78 return a.Order - b.Order;
81 export const sortAddresses = (addresses?: Address[]) => {
82 if (Array.isArray(addresses)) {
83 return [...addresses].sort(addressSort);