@cleartrip/ct-platform-utils 3.18.4 → 3.19.0-beta.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,1102 @@
1
- import{__awaiter as n,__generator as t,__assign as o}from"tslib";import{v4 as e}from"uuid";import{Platform as i,AppAgent as r,RequestMethods as a,SOURCE_NAME as u,API_ROUTES as l,MOBILE_CONSTANTS as d,NAVIGATION_ROUTES as s}from"@cleartrip/ct-platform-constants";import c from"ua-parser-js";import{ValidateOTPAction as v}from"@cleartrip/ct-platform-types";var f=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var o=n.map((function(n){return n.trim().replace(/^[/]+/,"")})).join("/");return o=o.replace(/\/\?/g,"?")},w=function(){var n="undefined"!=typeof window?window.location.hostname:"";switch(console.log("API_BASE domain",n),n){case"localhost":case"0.0.0.0":case"qa2new.cleartrip.com":return"https://qa2new.cleartrip.com";case"qa2.cleartrip.com":return"https://qa2.cleartrip.com";case"qa3new.cleartrip.com":return"https://qa3new.cleartrip.com";default:return"https://www.cleartrip.com"}},p=function(n,t){return t.reduce((function(n,t){return n&&n[t]?n[t]:null}),n)},m=function(n,t){return n.reduce((function(n,t){return n&&n[t]?n[t]:null}),t)},g=/\s\s+/g,_=function(n){if(n instanceof Date)return!1;if(null==n)return!0;var t,o=function(n){return"[object Number]"===Object.prototype.toString.call(n)};if(o(n))return o(t=n)&&"NaN"===t.toString();if(n.length>0)return!1;if(0===n.length)return!0;if("object"!=typeof n)return!0;for(var e=Object.keys(n),i=0,r=e[i];i<e.length;i+=1)if(Object.prototype.hasOwnProperty.call(n,r))return!1;return!0},h=function(n){return"object"==typeof n&&null!==n&&"value"in n&&n instanceof HTMLInputElement},y=function(n){return/^[0-9]*$/.test(n)},b="undefined"!=typeof window?window.location.href:"",S=function(n){return D()?"":new URLSearchParams(window.location.search).get(n)},I=function(){return"undefined"!=typeof window?(window.location.pathname+window.location.search).slice(1):""},N=function(n){if(n){var t=n.match(/h_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},O=function(n){if(n){var t=n.match(/w_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},D=function(){return"undefined"==typeof window||!window};function P(n,t){var o=t||p(document,["cookie"]);if(o){for(var e=n+"=",i=o.split(";"),r=0;r<i.length;r++){for(var a=i[r];" "==a.charAt(0);)a=a.substring(1,a.length);if(0==a.indexOf(e))return a.substring(e.length,a.length)}return""}return""}var k=function(n){void 0===n&&(n="");var t=N(n)||0,o=O(n)||0;return{height:"".concat(t,"px"),width:"".concat(o,"px"),heightInNumber:t,widthInNumber:o}},E=function(n){try{if(!n||Number.isNaN(Number(n)))return"";var t=new Date(1e3*n),o=t.getFullYear(),e=String(t.getDate()).padStart(2,"0"),i=String(t.getMonth()+1).padStart(2,"0");return"".concat(o,"-").concat(i,"-").concat(e)}catch(n){return""}},A=function(n,t,o){void 0===t&&(t="dd-mm-yyyy"),void 0===o&&(o="");try{var e=new Date(n),i=e.getFullYear(),r=String(e.getDate()).padStart(2,"0"),a=String(e.getMonth()+1).padStart(2,"0");return"yyyy-mm-dd"===t?"".concat(i,"-").concat(a,"-").concat(r):"".concat(r,"-").concat(a,"-").concat(i)}catch(n){return o}},T=function(n,t){void 0===t&&(t=!0);try{var o={currency:"INR",minimumFractionDigits:0};return t&&(o.style="currency"),"string"!=typeof n&&(n=null==n?void 0:n.toString()),n=n.replace(/,/g,""),parseInt(n,10).toLocaleString("en-IN",o)}catch(n){return""}},M=function(n){var t,o=n.cookieName,e=n.cookieValue,i=n.expiryInDay,r=n.expiryInHours,a=n.expiryInMinutes,u=new Date;i?(u.setTime(u.getTime()+24*i*60*60*1e3),t=u.toUTCString()):r?(u.setTime(u.getTime()+3600*r*1e3),t=u.toUTCString()):a?(u.setTime(u.getTime()+60*a*1e3),t=u.toUTCString()):t="",document.cookie="".concat(o,"=").concat(e,"; expires=").concat(t,"; path=/")};function R(n){try{var t=new URL(n),o=new URLSearchParams(t.search),e={};return o.forEach((function(n,t){e[t]=n})),e}catch(n){return{}}}function C(n){var t=new Date(n),o=new Date;o.setHours(12,0,0,0),t.setHours(12,0,0,0);var e=(t.getTime()-o.getTime())/864e5;return Math.round(e)}var L=function(n){try{var t=new Date;t.setDate(t.getDate()+n);var o=t.getDate(),e=t.toLocaleString("default",{month:"short"}),i=t.getFullYear();return"".concat(o," ").concat(e,", ").concat(i)}catch(n){return""}},j=function(){var n,t=null===(n=p(window,["navigator","userAgent"]))||void 0===n?void 0:n.toLowerCase(),o=/safari/.test(t),e=/iphone|ipod|ipad/.test(t);return p(window,["androidData","app-agent"])&&p(window,["androidData","js-version"])||"function"==typeof p(window,["MobileApp","getAppSpecificData"])?i.ANDROID:p(window,["iosData","app-agent"])&&p(window,["iosData","js-version"])||e&&!o?i.IOS:i.PWA},U=function(){var n,t,o=j();return o===i.IOS?null!==(n=p(window,["iosData","app-agent"]))&&void 0!==n?n:r.IOS:o===i.ANDROID?null!==(t=p(window,["androidData","app-agent"]))&&void 0!==t?t:r.ANDROID:r.PWA},x=function(){if(D())return r.H_UNKNOWN;var n=j();return n===i.IOS?r.H_IOS:(n===i.ANDROID&&r.H_ANDROID,r.H_PWA)},H=function(){var n="";return J()?n=p(window,["iosData","js-version"]):q()&&(n=p(window,["androidData","js-version"])),n&&(n=n.toString().split(".")[0]),n},G=function(){var n,t,o,e;if(!D())return"";var i=new c(null===(n=null===window||void 0===window?void 0:window.navigator)||void 0===n?void 0:n.userAgent);return null!==(e=null===(o=null===(t=null==i?void 0:i.getDevice())||void 0===t?void 0:t.model)||void 0===o?void 0:o.toLowerCase())&&void 0!==e?e:""},B=function(){return j()!==i.ANDROID&&j()!==i.IOS},q=function(){return j()===i.ANDROID},F=function(n){return parseInt(H())>=n},J=function(){return j()===i.IOS},W=w(),Y=function(i,r,d,s,c,v,p){return void 0===r&&(r=a.GET),void 0===s&&(s={}),void 0===c&&(c={}),void 0===v&&(v=!1),void 0===p&&(p={}),n(void 0,void 0,void 0,(function(){var n,a,m,g,_,h,y,b,S,I;return t(this,(function(t){switch(t.label){case 0:return n=function(n,t){var o=l[n];if(o&&o.trim().length){if(o=f(W,o),null==t?void 0:t.pathParams)for(var e=0,i=Object.entries(t.pathParams);e<i.length;e++){var r=i[e],a=r[0],u=r[1];o=o.replace(":".concat(a),u)}return(null==t?void 0:t.queryParams)&&(o+="?".concat(new URLSearchParams(t.queryParams).toString())),o}}(i,c),n&&n.trim().length?(a="",m="",g=w(),D()||(a=j(),m=JSON.stringify(function(n){var t={trackingId:e(),source:u};return D()?o(o({},t),null!=n?n:{}):o(o(o({},t),{platform:U(),deviceModel:G()}),null!=n?n:{})}(p))),_={method:r,headers:o({channel:a,Caller:W,Origin:W,Referer:W,Authority:g,x_ct_sourcetype:"MOBILE","app-agent":U(),"x-unified-header":m,"Content-Type":"application/json"},s)},d&&(_.body=JSON.stringify(d)),[4,fetch(n,_)]):[2,Promise.reject("URL parameter missing")];case 1:return y=t.sent(),b={name:"API_FAILURE",status:y.status,message:"UNKNOWN_ERROR",statusText:y.statusText},(null==y?void 0:y.ok)?[3,3]:v?[2,Promise.reject(b)]:[4,y.json()];case 2:throw S=t.sent().message,b.message=S,b;case 3:return(null==(I=y.headers.get("content-type"))?void 0:I.includes("application/json"))?[4,y.json()]:[3,5];case 4:return h=t.sent(),[3,9];case 5:return(null==I?void 0:I.includes("text"))?[4,y.text()]:[3,7];case 6:return h=t.sent(),[3,9];case 7:return 204===y.status?[3,9]:[4,y.blob()];case 8:h=t.sent(),t.label=9;case 9:return[2,{data:h,status:y.status}]}}))}))},K=function(e,i,r,u,l){return void 0===i&&(i={}),void 0===r&&(r={}),void 0===u&&(u=!1),void 0===l&&(l={}),n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,Y(e,a.GET,null,o({expires:"0",accept:"application/json","cache-control":"no-cache"},i),r,u,l)]}))}))},V=function(e,i,r,u,l,d,s){return void 0===i&&(i=a.POST),void 0===r&&(r={}),void 0===u&&(u={}),void 0===l&&(l={}),void 0===d&&(d=!1),void 0===s&&(s={}),n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,Y(e,i,r,o({expires:"0",accept:"application/json","cache-control":"no-cache"},u),l,d,s)]}))}))},$=function(){var n;if("function"==typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.onRequestMobileNumber)){var t;window.MobileApp.onRequestMobileNumber();var o=new Promise((function(n){t=n}));return window.sendSelectedMobileNumber=function(n){return t(X(n))},o}return Promise.resolve("")},X=function(n){var t="",o=n.match(d.REGEX);return o&&(t=o[0].replace(/\D/g,"")),t},z=function(){return n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,q()?on():tn()]}))}))},Q=function(){var n,t,o;null===(o=null===(t=null===(n=window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===t?void 0:t.PWA_IS_SIGNIN)||void 0===o||o.postMessage({isSignIn:!0})},Z=function(){var n;null===(n=window.MobileApp)||void 0===n||n.onPWALoginStatus(JSON.stringify({isSignIn:!0}))},nn=function(){var n;q()&&(null===(n=window.MobileApp)||void 0===n||n.onPageStart("OTP_SCREEN"))},tn=function(){return n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){return(null===(o=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===o?void 0:o.get)&&"OTPCredential"in window?(n=new AbortController,setTimeout((function(){n.abort()}),6e4),[2,navigator.credentials.get({otp:{transport:["sms"]},signal:n.signal}).then((function(n){return null==n?void 0:n.code}))]):[2,Promise.reject("NOT_SUPPORTED")]}))}))},on=function(){return n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){return o=new Promise((function(t){n=t})),window.sendOtpValue=function(t){n(t)},[2,o]}))}))},en=function(){return n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){return q()&&"function"==typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.isPNPermissionEnabled)?[2,Promise.resolve(!(null===(o=window.MobileApp)||void 0===o?void 0:o.isPNPermissionEnabled()))]:J()?[2,new Promise((function(n,t){var o,e,i,r;window.pushNotifcationPermissionStatus=function(t){var o=JSON.parse(t),e=null==o?void 0:o.status;"boolean"==typeof e&&n(!e)};try{null===(r=null===(i=null===(e=null===(o=null===window||void 0===window?void 0:window.webkit)||void 0===o?void 0:o.messageHandlers)||void 0===e?void 0:e.IS_PN_PERMISSION_ENABLED)||void 0===i?void 0:i.postMessage)||void 0===r||r.call(i,"")}catch(t){n(!1)}}))]:[2,Promise.resolve(!1)]}))}))},rn=function(n){var t,o,e,i,r,a,u,l;q()&&"function"==typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.handlePNPermission)?null===(o=window.MobileApp)||void 0===o||o.handlePNPermission(JSON.stringify({type:n})):J()&&(null===(i=null===(e=null===window||void 0===window?void 0:window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===i?void 0:i.HANDLE_PN_PERMISSION)&&(null===(l=null===(u=null===(a=null===(r=window.webkit)||void 0===r?void 0:r.messageHandlers)||void 0===a?void 0:a.HANDLE_PN_PERMISSION)||void 0===u?void 0:u.postMessage)||void 0===l||l.call(u,JSON.stringify({type:n})))},an=function(o,e){return n(void 0,void 0,void 0,(function(){var n;return t(this,(function(t){switch(t.label){case 0:return[4,V("SEND_OTP",a.POST,{value:o,type:"MOBILE",action:"SIGNIN",countryCode:d.COUNTRY_CODE},{"ab-otp":"b",dvid_data:e})];case 1:return[2,null==(n=t.sent())?void 0:n.data]}}))}))},un=function(e,i){return n(void 0,void 0,void 0,(function(){var n,r;return t(this,(function(t){switch(t.label){case 0:return[4,V("VALIDATE_OTP",a.POST,{otp:i,value:e,type:"MOBILE",action:"SIGNIN",countryCode:"+91"},{"ab-otp":"b"})];case 1:return n=t.sent(),r=null==n?void 0:n.data,[2,o(o({},n),{signup:(null==r?void 0:r.action)===v.SIGNUP,action:null==r?void 0:r.action,status:null==n?void 0:n.status})]}}))}))},ln=function(o,e){return n(void 0,void 0,void 0,(function(){var n,i;return t(this,(function(t){switch(t.label){case 0:return J()?[2,Promise.reject()]:(n=I(),[4,vn(o,e?n:s.PERSONAL_DETAILS+"?onboardingFlow=true",n)]);case 1:return i=t.sent(),q()?[2,wn(i)]:[2,fn(i)]}}))}))},dn=function(n){return(null==n?void 0:n.length)===d.LENGTH&&/^\d{10}$/.test(n)},sn=function(){J()?Q():q()&&Z()},cn=function(){return B()||!J()&&F(5)},vn=function(o,e,i){return n(void 0,void 0,void 0,(function(){var n,r;return t(this,(function(t){switch(t.label){case 0:return n=w(),[4,V("FK_REDIRECTION_INFO",a.POST,{provider:"flipkart",fallbackUri:f(n,o||i),signupPageUri:f(n,e||"personal-details"),currentPageUri:f(n,i)})];case 1:return[2,null==(r=t.sent())?void 0:r.data]}}))}))},fn=function(n){var t,o=null!==(t=null==n?void 0:n.params)&&void 0!==t?t:{},e=null==n?void 0:n.redirectUri;if(e){for(var i in e+="?",o)e+=i+"="+o[i]+"&";return Promise.resolve(e)}return Promise.reject()},wn=function(n){var t,e,i=null==n?void 0:n.params;if(_(i)||"function"!=typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.onNavigationChange))return Promise.reject();var r=f(w(),"dl/oauth2");return null===(e=window.MobileApp)||void 0===e||e.onNavigationChange(JSON.stringify({type:"FkSSO",miscData:o(o({},i),{redirectURI:r})})),Promise.resolve()};function pn(n){try{var t=decodeURIComponent(P("userid",n)||"").split("|");return{email:t[0],profileName:t[1],gender:t[2],photo:t[3],userId:t[4]}}catch(n){return{}}}var mn=function(n){var t=pn(n)||{};return!!(decodeURIComponent(P("usermisc",n)||"").split("|").includes("SIGNED_IN")&&t.userId&&t.userId.length>0)},gn=function(o){return void 0===o&&(o=!0),n(void 0,void 0,void 0,(function(){var e;return t(this,(function(i){switch(i.label){case 0:return[4,n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,K("GET_PROFILE_DETAILS",{caller:w(),"app-agent":U()},{})];case 1:return[2,null==(n=t.sent())?void 0:n.data];case 2:return o=t.sent(),console.error("Failed to fetch user details. Error: ",o),[2,Promise.resolve(null)];case 3:return[2]}}))}))];case 1:return(e=i.sent())&&o&&function(n){var t,o,e,i,r,a;try{if(D()||!(null===window||void 0===window?void 0:window.clevertap)||_(n))return;var u={Identity:null!==(t=null==n?void 0:n.id)&&void 0!==t?t:"",Gender:null!==(o=null==n?void 0:n.gender)&&void 0!==o?o:"",Email:null!==(e=null==n?void 0:n.username)&&void 0!==e?e:"",Phone:"".concat(null==n?void 0:n.countryCode).concat(null==n?void 0:n.mobile),"MSG-sms":!0,"MSG-push":!0,"MSG-email":!1,"MSG-whatsapp":!0};if(null===(i=null==n?void 0:n.travellerDetails)||void 0===i?void 0:i.length)for(var l=0;l<(null===(r=null==n?void 0:n.travellerDetails)||void 0===r?void 0:r.length);l++){var d=null==n?void 0:n.travellerDetails[l];if(d.isRegistered){var s=d.personalDetails.dateOfBirth;u.Name="".concat(d.personalDetails.firstName," ").concat(d.personalDetails.lastName),isNaN(s)||(u.DOB=new Date(s));break}}null===(a=null===window||void 0===window?void 0:window.clevertap)||void 0===a||a.onUserLogin.push({Site:u})}catch(n){console.log("Error pushing clevertap profile information. Error: ",n)}}(e),[2]}}))}))},_n=function(o){return n(void 0,void 0,void 0,(function(){var n;return t(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,K("USER_INSIGHTS",{},{pathParams:{userId:o}})];case 1:return[2,null==(n=t.sent())?void 0:n.data];case 2:return t.sent(),[2,Promise.resolve(null)];case 3:return[2]}}))}))},hn=function(o){return n(void 0,void 0,void 0,(function(){var n,e,i,r,a,u,l,d;return t(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),(n=null!=o?o:pn().userId)?(e=null===(u=null===window||void 0===window?void 0:window.sessionStorage)||void 0===u?void 0:u.getItem("martech_user_attributes"),i=void 0,"string"==typeof e&&(i=JSON.parse(e)),n!==(null==i?void 0:i.accountId)&&(null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.removeItem("martech_user_attributes")),[4,_n(n)]):(null===(a=null===window||void 0===window?void 0:window.sessionStorage)||void 0===a||a.removeItem("martech_user_attributes"),[2,null]);case 1:return r=t.sent(),_(null==r?void 0:r.data)?[2,null]:(null===(d=null===window||void 0===window?void 0:window.sessionStorage)||void 0===d||d.setItem("martech_user_attributes",JSON.stringify(null==r?void 0:r.data)),[2,null==r?void 0:r.data]);case 2:return t.sent(),[2,null];case 3:return[2]}}))}))},yn=function(n){return Object.keys(n).forEach((function(t){n[t]="a_fare_price"===t||"a_ct_discount"===t||"supercoin_balance"===t||"supercoin_earned"===t||"supercoin_burnt"===t||"wallet_balance_used"===t||"convenience_fee"===t?Number(n[t]):""+n[t]})),n},bn=function(){try{if(D())return"";var n=P("ct_statsig_experiments")||"{}",t=n?JSON.parse(decodeURIComponent(n)):{};return Object.keys(t).map((function(n){return n&&t[n]?"".concat(n,":").concat(t[n]):""})).filter((function(n){return!!n})).join("|")}catch(n){return""}},Sn=function(n,t){var e;if(window&&window.ravenWebManager){var i=Nn(),r={page_name:i.pageName,u_utm_source:i.utmSource,domain:window.location.host,u_ab_key:bn(),platform:null===(e=j())||void 0===e?void 0:e.toLowerCase(),login_status:mn()?"yes":"no"},a=yn(t),u=window.ravenWebManager;null==u||u.triggerRaven(n,o(o({},r),a))}},In=function(){if(window&&"undefined"!=typeof window){var n=p(window,["location","pathname"]);if("/"===n||"/flights"===n)return!0}return!1},Nn=function(){var n,t;if(window&&"undefined"!=typeof window){var o=window.location.pathname,e=null!==(n=S("service"))&&void 0!==n?n:"",i=null!==(t=S("utm_source"))&&void 0!==t?t:"organic",r=In()?"skippable_login":"account_login",a="air",u=o.includes("flights/itinerary")||e.includes("flights/itinerary")?"a_itinerary":"a_home";return e.includes("my-account")&&(a="uar",u="account"),e.includes("hotels")&&(a="hotel",u=e.includes("hotels/itinerary")?"h_itinerary":"h_home"),e.includes("bus")&&(a="bus",u=e.includes("bus/itinerary")?"b_itinerary":"b_home"),{loginForm:r,vertical:a,pageName:u,utmSource:i}}return{}},On=function(e,i,r){return n(void 0,void 0,void 0,(function(){var n,a,u,l,d,s,c,v,f,w,p,m,g,h,y,b,S,I,N,O;return t(this,(function(t){switch(t.label){case 0:return[4,hn(r)];case 1:return n=t.sent(),a=o(o({},i),{fk_loyalty_status:"na",fk_loyalty_end_dt:"na",ct_last_booking_dt:"na",ct_lifetime_booking:"na",fk_loyalty_start_dt:"na",ct_first_booking_dt:"na",myntra_loyalty_status:"na",ct_postmerger_booking:"na",ct_last_1year_booking:"na",myntra_loyalty_end_dt:"na",ct_2nd_last_booking_dt:"na",myntra_loyalty_start_dt:"na"}),_(n)||(u=(null!==(d=null==n?void 0:n.loyaltyStatus)&&void 0!==d?d:[]).reduce((function(n,t){return o(o({},n),t)}),{}),l={ct_lifetime_booking:(null!==(c=null===(s=null==n?void 0:n.bookingStatus)||void 0===s?void 0:s.lifetimeBooking)&&void 0!==c?c:"na").toString(),ct_postmerger_booking:(null!==(f=null===(v=null==n?void 0:n.bookingStatus)||void 0===v?void 0:v.postmergerBooking)&&void 0!==f?f:"na").toString(),ct_last_1year_booking:(null!==(p=null===(w=null==n?void 0:n.bookingStatus)||void 0===w?void 0:w.lastOneYearBooking)&&void 0!==p?p:"na").toString(),ct_first_booking_dt:E(null===(m=null==n?void 0:n.bookingStatus)||void 0===m?void 0:m.firstbookingDate)||"na",ct_last_booking_dt:E(null===(g=null==n?void 0:n.bookingStatus)||void 0===g?void 0:g.lastbookingDate)||"na",ct_2nd_last_booking_dt:E(null===(h=null==n?void 0:n.bookingStatus)||void 0===h?void 0:h.secondLastbookingDate)||"na",fk_loyalty_status:(null===(y=null==u?void 0:u.fk)||void 0===y?void 0:y.program)||"na",myntra_loyalty_status:(null===(b=null==u?void 0:u.myntra)||void 0===b?void 0:b.program)||"na",fk_loyalty_end_dt:E(null===(S=null==u?void 0:u.fk)||void 0===S?void 0:S.loyaltyEndDate)||"",fk_loyalty_start_dt:E(null===(I=null==u?void 0:u.fk)||void 0===I?void 0:I.loyaltyStartDate)||"na",myntra_loyalty_start_dt:E(null===(N=null==u?void 0:u.myntra)||void 0===N?void 0:N.loyaltyStartDate)||"na",myntra_loyalty_end_dt:E(null===(O=null==u?void 0:u.myntra)||void 0===O?void 0:O.loyaltyEndDate)||"na"},a=o(o({},a),l),Dn(l)),Sn(e,a),[2]}}))}))},Dn=function(n){var t,o,e,i,r,a,u,l,d;_(n)||(null===(t=null===window||void 0===window?void 0:window.sessionStorage)||void 0===t?void 0:t.getItem("martech_user_props_sent"))||(J()&&(null===(e=null===(o=null===window||void 0===window?void 0:window.webkit)||void 0===o?void 0:o.messageHandlers)||void 0===e?void 0:e.SEND_ATTRIBUTES)?(null===(i=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===i||i.postMessage({type:"GA",params:n}),null===(r=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===r||r.postMessage({type:"Clevertap",params:n}),null===(a=null===window||void 0===window?void 0:window.sessionStorage)||void 0===a||a.setItem("martech_user_props_sent","true")):q()&&(null===(u=null===window||void 0===window?void 0:window.MobileApp)||void 0===u?void 0:u.sendAttributes)?(window.MobileApp.sendAttributes("GA",JSON.stringify(n)),window.MobileApp.sendAttributes("Clevertap",JSON.stringify(n)),null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.setItem("martech_user_props_sent","true")):B()&&window.clevertap&&(window.clevertap.profile.push({Site:n}),null===(d=null===window||void 0===window?void 0:window.sessionStorage)||void 0===d||d.setItem("martech_user_props_sent","true")))},Pn=function(n,t){"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?requestIdleCallback((function(){Sn(n,t)})):setTimeout((function(){Sn(n,t)}),0)},kn=function(e,i,r,a,u,l,d,s){return void 0===r&&(r=450),void 0===a&&(a="Discounts"),void 0===u&&(u="on hotels"),void 0===l&&(l="CTBEST - Exclusive coupon applied for you!"),void 0===d&&(d={}),void 0===s&&(s={}),n(void 0,void 0,void 0,(function(){var n,c,v,f,w,p;return t(this,(function(t){switch(t.label){case 0:n=null!==(p=null===(w=pn())||void 0===w?void 0:w.userId)&&void 0!==p?p:"",c={couponCode:"",couponCallOut:"",couponCallOutPrefix:a,couponCallOutSuffix:u,offerCallOut:l,pageLandingUrl:i},t.label=1;case 1:return t.trys.push([1,3,,4]),v=new Promise((function(n){setTimeout((function(){n(c)}),r)})),f=K("HOTEL_RECOMMENDATIONS",d,{queryParams:o({userId:n,vertical:e},s)},!1,{userBuckets:{"x-cross-sell":"true"},platform:x()}).then((function(n){return n.data})),[4,Promise.race([f,v])];case 2:return[2,t.sent()];case 3:return t.sent(),[2,c];case 4:return[2]}}))}))};export{g as MULTI_SPACE,z as autoReadOtp,Pn as batchRavenEvent,Y as createAPIRequest,K as createGetRequest,V as createPostOrPutRequest,R as extractQueryParamsAsObj,T as formatCurrency,A as formatFullDateString,w as getApiDomain,U as getAppAgent,x as getAppAgentForHotelUnifiedHeader,X as getAutoDetectedMobile,bn as getCTStatsigExpForRaven,P as getCookie,I as getCurrentPathName,b as getCurrentUrl,G as getDeviceModel,j as getDevicePlatform,k as getDimensionFromImageUrl,L as getFutureDateFromDays,N as getHeightFromImgUrl,kn as getHotelCrossSellRecos,H as getJSVersion,p as getNestedValue,C as getNoOfDaysFromToday,S as getQueryParam,Nn as getRavenEventProps,pn as getUserAuthValues,O as getWidthFromImgUrl,ln as handleFKSSO,gn as handleProfileFetch,rn as handlePushPrimerCTA,In as isAirHomePage,q as isAndroidApp,_ as isEmpty,cn as isFKSSOEnabled,h as isHTMLInputElement,J as isIOSApp,F as isJSVersionUpdated,y as isNumeric,B as isPwa,D as isServer,mn as isUserSignedIn,dn as isValidMobileNumber,m as path,Sn as ravenSDKTrigger,E as secondsToDateString,On as sendEventWithUserInsights,an as sendLoginOtp,M as setCookie,Dn as setMartechUserProperties,en as shouldShowPushPrimer,$ as showMobileNumberHint,yn as stringifyPayload,nn as triggerOTPListener,Z as updateNativeAndroidOnSignIn,Q as updateNativeIOSOnSignIn,sn as updateNativeOnLogin,f as urlJoin,un as validateOtp};
1
+ import { __awaiter, __generator, __assign } from 'tslib';
2
+ import { v4 } from 'uuid';
3
+ import { Platform, AppAgent, RequestMethods, SOURCE_NAME, API_ROUTES, MOBILE_CONSTANTS, NAVIGATION_ROUTES } from '@cleartrip/ct-platform-constants';
4
+ import UAParser from 'ua-parser-js';
5
+ import { ValidateOTPAction } from '@cleartrip/ct-platform-types';
6
+
7
+ var urlJoin = function () {
8
+ var parts = [];
9
+ for (var _i = 0; _i < arguments.length; _i++) {
10
+ parts[_i] = arguments[_i];
11
+ }
12
+ var trimmedParts = parts.map(function (part) { return part.trim().replace(/^[/]+/, ''); });
13
+ var joinedParts = trimmedParts.join('/');
14
+ joinedParts = joinedParts.replace(/\/\?/g, '?');
15
+ return joinedParts;
16
+ };
17
+ var getApiDomain = function () {
18
+ var domain = typeof window !== 'undefined' ? window.location.hostname : '';
19
+ console.log('API_BASE domain', domain);
20
+ switch (domain) {
21
+ case 'localhost':
22
+ case '0.0.0.0':
23
+ case 'qa2new.cleartrip.com':
24
+ return 'https://qa2new.cleartrip.com';
25
+ case 'qa2.cleartrip.com':
26
+ return 'https://qa2.cleartrip.com';
27
+ case 'qa3new.cleartrip.com':
28
+ return 'https://qa3new.cleartrip.com';
29
+ case 'www.cleartrip.com':
30
+ default:
31
+ return 'https://www.cleartrip.com';
32
+ }
33
+ };
34
+ var getNestedValue = function (data, path) {
35
+ var reducerFunction = function (prev, current) {
36
+ return prev && prev[current] ? prev[current] : null;
37
+ };
38
+ return path.reduce(reducerFunction, data);
39
+ };
40
+ var path = function (p, o) {
41
+ return p.reduce(function (prev, curr) {
42
+ return prev && prev[curr] ? prev[curr] : null;
43
+ }, o);
44
+ };
45
+ var MULTI_SPACE = /\s\s+/g;
46
+ var isEmpty = function (obj) {
47
+ if (obj instanceof Date) {
48
+ return false;
49
+ }
50
+ if (obj == null) {
51
+ return true;
52
+ }
53
+ var isNumber = function (value) {
54
+ return Object.prototype.toString.call(value) === '[object Number]';
55
+ };
56
+ var isNaN = function (value) { return isNumber(value) && value.toString() === 'NaN'; };
57
+ if (isNumber(obj)) {
58
+ return isNaN(obj);
59
+ }
60
+ if (obj.length > 0) {
61
+ return false;
62
+ }
63
+ if (obj.length === 0) {
64
+ return true;
65
+ }
66
+ if (typeof obj !== 'object') {
67
+ return true;
68
+ }
69
+ var keys = Object.keys(obj);
70
+ for (var i = 0, key = keys[i]; i < keys.length; i += 1) {
71
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
72
+ return false;
73
+ }
74
+ }
75
+ return true;
76
+ };
77
+ var isHTMLInputElement = function (ref) {
78
+ return (typeof ref === 'object' &&
79
+ ref !== null &&
80
+ 'value' in ref &&
81
+ ref instanceof HTMLInputElement);
82
+ };
83
+ var isNumeric = function (value) {
84
+ return /^[0-9]*$/.test(value);
85
+ };
86
+ var getCurrentUrl = typeof window !== 'undefined' ? window.location.href : '';
87
+ var getQueryParam = function (queryParam) {
88
+ if (isServer()) {
89
+ return '';
90
+ }
91
+ var urlParams = new URLSearchParams(window.location.search);
92
+ return urlParams.get(queryParam);
93
+ };
94
+ var getCurrentPathName = function () {
95
+ return typeof window !== 'undefined'
96
+ ? (window.location.pathname + window.location.search).slice(1)
97
+ : '';
98
+ };
99
+ var getHeightFromImgUrl = function (url) {
100
+ if (!url) {
101
+ return;
102
+ }
103
+ var regex = /h_(\d+)[,\/]/;
104
+ var match = url.match(regex);
105
+ if (match && match[1]) {
106
+ return parseInt(match[1], 10);
107
+ }
108
+ return;
109
+ };
110
+ var getWidthFromImgUrl = function (url) {
111
+ if (!url) {
112
+ return;
113
+ }
114
+ var regex = /w_(\d+)[,\/]/;
115
+ var match = url.match(regex);
116
+ if (match && match[1]) {
117
+ return parseInt(match[1], 10);
118
+ }
119
+ return;
120
+ };
121
+ var isServer = function () {
122
+ return typeof window === 'undefined' || !window;
123
+ };
124
+ function getCookie(name, customCookie) {
125
+ var _cookie = customCookie || getNestedValue(document, ['cookie']);
126
+ if (_cookie) {
127
+ var nameEQ = name + '=';
128
+ var ca = _cookie.split(';');
129
+ for (var i = 0; i < ca.length; i++) {
130
+ var c = ca[i];
131
+ while (c.charAt(0) == ' ')
132
+ c = c.substring(1, c.length);
133
+ if (c.indexOf(nameEQ) == 0)
134
+ return c.substring(nameEQ.length, c.length);
135
+ }
136
+ return '';
137
+ }
138
+ else {
139
+ return '';
140
+ }
141
+ }
142
+ var getDimensionFromImageUrl = function (url) {
143
+ if (url === void 0) { url = ''; }
144
+ var height = getHeightFromImgUrl(url) || 0;
145
+ var width = getWidthFromImgUrl(url) || 0;
146
+ return {
147
+ height: "".concat(height, "px"),
148
+ width: "".concat(width, "px"),
149
+ heightInNumber: height,
150
+ widthInNumber: width,
151
+ };
152
+ };
153
+ var secondsToDateString = function (sec) {
154
+ try {
155
+ if (!sec || Number.isNaN(Number(sec))) {
156
+ return '';
157
+ }
158
+ var date = new Date(sec * 1000);
159
+ var year = date.getFullYear();
160
+ var day = String(date.getDate()).padStart(2, '0');
161
+ var month = String(date.getMonth() + 1).padStart(2, '0');
162
+ return "".concat(year, "-").concat(month, "-").concat(day);
163
+ }
164
+ catch (_e) {
165
+ return '';
166
+ }
167
+ };
168
+ var formatFullDateString = function (dateString, format, fallback) {
169
+ if (format === void 0) { format = 'dd-mm-yyyy'; }
170
+ if (fallback === void 0) { fallback = ''; }
171
+ try {
172
+ var date = new Date(dateString);
173
+ var year = date.getFullYear();
174
+ var day = String(date.getDate()).padStart(2, '0');
175
+ var month = String(date.getMonth() + 1).padStart(2, '0');
176
+ switch (format) {
177
+ case 'yyyy-mm-dd':
178
+ return "".concat(year, "-").concat(month, "-").concat(day);
179
+ case 'dd-mm-yyyy':
180
+ default:
181
+ return "".concat(day, "-").concat(month, "-").concat(year);
182
+ }
183
+ }
184
+ catch (_e) {
185
+ return fallback;
186
+ }
187
+ };
188
+ var formatCurrency = function (value, withIcon) {
189
+ if (withIcon === void 0) { withIcon = true; }
190
+ try {
191
+ var config = {
192
+ currency: 'INR',
193
+ minimumFractionDigits: 0,
194
+ };
195
+ if (withIcon) {
196
+ config.style = 'currency';
197
+ }
198
+ if (typeof value !== 'string') {
199
+ value = value === null || value === void 0 ? void 0 : value.toString();
200
+ }
201
+ value = value.replace(/,/g, '');
202
+ return parseInt(value, 10).toLocaleString('en-IN', config);
203
+ }
204
+ catch (_e) {
205
+ return '';
206
+ }
207
+ };
208
+ var setCookie = function (_a) {
209
+ var cookieName = _a.cookieName, cookieValue = _a.cookieValue, expiryInDay = _a.expiryInDay, expiryInHours = _a.expiryInHours, expiryInMinutes = _a.expiryInMinutes;
210
+ var expires;
211
+ var date = new Date();
212
+ if (expiryInDay) {
213
+ date.setTime(date.getTime() + expiryInDay * 24 * 60 * 60 * 1000);
214
+ expires = date.toUTCString();
215
+ }
216
+ else if (expiryInHours) {
217
+ date.setTime(date.getTime() + expiryInHours * 3600 * 1000);
218
+ expires = date.toUTCString();
219
+ }
220
+ else if (expiryInMinutes) {
221
+ date.setTime(date.getTime() + expiryInMinutes * 60 * 1000);
222
+ expires = date.toUTCString();
223
+ }
224
+ else {
225
+ expires = '';
226
+ }
227
+ document.cookie = "".concat(cookieName, "=").concat(cookieValue, "; expires=").concat(expires, "; path=/");
228
+ };
229
+ function extractQueryParamsAsObj(url) {
230
+ try {
231
+ var urlObj = new URL(url);
232
+ var queryParams = new URLSearchParams(urlObj.search);
233
+ var params_1 = {};
234
+ queryParams.forEach(function (value, key) {
235
+ params_1[key] = value;
236
+ });
237
+ return params_1;
238
+ }
239
+ catch (error) {
240
+ return {};
241
+ }
242
+ }
243
+ function getNoOfDaysFromToday(checkInDate) {
244
+ var checkIn = new Date(checkInDate);
245
+ var today = new Date();
246
+ today.setHours(12, 0, 0, 0);
247
+ checkIn.setHours(12, 0, 0, 0);
248
+ var differenceInMs = checkIn.getTime() - today.getTime();
249
+ var differenceInDays = differenceInMs / (1000 * 60 * 60 * 24);
250
+ return Math.round(differenceInDays);
251
+ }
252
+ var getFutureDateFromDays = function (days) {
253
+ try {
254
+ var currentDate = new Date();
255
+ currentDate.setDate(currentDate.getDate() + days);
256
+ var day = currentDate.getDate();
257
+ var month = currentDate.toLocaleString('default', {
258
+ month: 'short',
259
+ });
260
+ var year = currentDate.getFullYear();
261
+ return "".concat(day, " ").concat(month, ", ").concat(year);
262
+ }
263
+ catch (_e) {
264
+ return '';
265
+ }
266
+ };
267
+
268
+ var getDevicePlatform = function () {
269
+ var _a;
270
+ var userAgent = (_a = getNestedValue(window, [
271
+ 'navigator',
272
+ 'userAgent',
273
+ ])) === null || _a === void 0 ? void 0 : _a.toLowerCase();
274
+ var safariBrowser = /safari/.test(userAgent);
275
+ var appleDevice = /iphone|ipod|ipad/.test(userAgent);
276
+ if ((getNestedValue(window, ['androidData', 'app-agent']) &&
277
+ getNestedValue(window, ['androidData', 'js-version'])) ||
278
+ typeof getNestedValue(window, ['MobileApp', 'getAppSpecificData']) ===
279
+ 'function') {
280
+ return Platform.ANDROID;
281
+ }
282
+ else if ((getNestedValue(window, ['iosData', 'app-agent']) &&
283
+ getNestedValue(window, ['iosData', 'js-version'])) ||
284
+ (appleDevice && !safariBrowser)) {
285
+ return Platform.IOS;
286
+ }
287
+ return Platform.PWA;
288
+ };
289
+ var getAppAgent = function () {
290
+ var _a, _b;
291
+ var platform = getDevicePlatform();
292
+ if (platform === Platform.IOS) {
293
+ return (_a = getNestedValue(window, ['iosData', 'app-agent'])) !== null && _a !== void 0 ? _a : AppAgent.IOS;
294
+ }
295
+ else if (platform === Platform.ANDROID) {
296
+ return ((_b = getNestedValue(window, ['androidData', 'app-agent'])) !== null && _b !== void 0 ? _b : AppAgent.ANDROID);
297
+ }
298
+ return AppAgent.PWA;
299
+ };
300
+ var getAppAgentForHotelUnifiedHeader = function () {
301
+ if (isServer()) {
302
+ return AppAgent.H_UNKNOWN;
303
+ }
304
+ var platform = getDevicePlatform();
305
+ if (platform === Platform.IOS) {
306
+ return AppAgent.H_IOS;
307
+ }
308
+ else if (platform === Platform.ANDROID) {
309
+ AppAgent.H_ANDROID;
310
+ }
311
+ return AppAgent.H_PWA;
312
+ };
313
+ var getJSVersion = function () {
314
+ var jsVersion = '';
315
+ if (isIOSApp()) {
316
+ jsVersion = getNestedValue(window, ['iosData', 'js-version']);
317
+ }
318
+ else if (isAndroidApp()) {
319
+ jsVersion = getNestedValue(window, ['androidData', 'js-version']);
320
+ }
321
+ if (jsVersion) {
322
+ jsVersion = jsVersion.toString().split('.')[0];
323
+ }
324
+ return jsVersion;
325
+ };
326
+ var getDeviceModel = function () {
327
+ var _a, _b, _c, _d;
328
+ if (!isServer()) {
329
+ return '';
330
+ }
331
+ var parser = new UAParser((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent);
332
+ return (_d = (_c = (_b = parser === null || parser === void 0 ? void 0 : parser.getDevice()) === null || _b === void 0 ? void 0 : _b.model) === null || _c === void 0 ? void 0 : _c.toLowerCase()) !== null && _d !== void 0 ? _d : '';
333
+ };
334
+ var isPwa = function () {
335
+ return getDevicePlatform() !== Platform.ANDROID &&
336
+ getDevicePlatform() !== Platform.IOS;
337
+ };
338
+ var isAndroidApp = function () {
339
+ return getDevicePlatform() === Platform.ANDROID;
340
+ };
341
+ var isJSVersionUpdated = function (compareVersion) {
342
+ return parseInt(getJSVersion()) >= compareVersion;
343
+ };
344
+ var isIOSApp = function () { return getDevicePlatform() === Platform.IOS; };
345
+
346
+ var API_BASE = getApiDomain();
347
+ var getCustomHeaderClientSide = function (additionalInfo) {
348
+ var unifiedHeader = {
349
+ trackingId: v4(),
350
+ source: SOURCE_NAME,
351
+ };
352
+ if (!isServer()) {
353
+ return __assign(__assign(__assign({}, unifiedHeader), { platform: getAppAgent(), deviceModel: getDeviceModel() }), (additionalInfo !== null && additionalInfo !== void 0 ? additionalInfo : {}));
354
+ }
355
+ return __assign(__assign({}, unifiedHeader), (additionalInfo !== null && additionalInfo !== void 0 ? additionalInfo : {}));
356
+ };
357
+ var getRequestUrl = function (path, params) {
358
+ var url = API_ROUTES[path];
359
+ if (!url || !url.trim().length) {
360
+ return;
361
+ }
362
+ url = urlJoin(API_BASE, url);
363
+ if (params === null || params === void 0 ? void 0 : params.pathParams) {
364
+ for (var _i = 0, _a = Object.entries(params.pathParams); _i < _a.length; _i++) {
365
+ var _b = _a[_i], key = _b[0], value = _b[1];
366
+ url = url.replace(":".concat(key), value);
367
+ }
368
+ }
369
+ if (params === null || params === void 0 ? void 0 : params.queryParams) {
370
+ url += "?".concat(new URLSearchParams(params.queryParams).toString());
371
+ }
372
+ return url;
373
+ };
374
+ var createAPIRequest = function (path, method, payload, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
375
+ if (method === void 0) { method = RequestMethods.GET; }
376
+ if (headers === void 0) { headers = {}; }
377
+ if (params === void 0) { params = {}; }
378
+ if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
379
+ if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
380
+ return __awaiter(void 0, void 0, void 0, function () {
381
+ var url, channel, unifiedHeader, API_AUTHORITY, requestOptions, responseData, response, error, message, contentType;
382
+ return __generator(this, function (_a) {
383
+ switch (_a.label) {
384
+ case 0:
385
+ url = getRequestUrl(path, params);
386
+ if (!url || !url.trim().length) {
387
+ return [2, Promise.reject('URL parameter missing')];
388
+ }
389
+ channel = '';
390
+ unifiedHeader = '';
391
+ API_AUTHORITY = getApiDomain();
392
+ if (!isServer()) {
393
+ channel = getDevicePlatform();
394
+ unifiedHeader = JSON.stringify(getCustomHeaderClientSide(additionalUnifiedHeaders));
395
+ }
396
+ requestOptions = {
397
+ method: method,
398
+ headers: __assign({ channel: channel, Caller: API_BASE, Origin: API_BASE, Referer: API_BASE, Authority: API_AUTHORITY, x_ct_sourcetype: 'MOBILE', 'app-agent': getAppAgent(), 'x-unified-header': unifiedHeader, 'Content-Type': 'application/json' }, headers),
399
+ };
400
+ if (payload) {
401
+ requestOptions.body = JSON.stringify(payload);
402
+ }
403
+ return [4, fetch(url, requestOptions)];
404
+ case 1:
405
+ response = _a.sent();
406
+ error = {
407
+ name: 'API_FAILURE',
408
+ status: response.status,
409
+ message: 'UNKNOWN_ERROR',
410
+ statusText: response.statusText,
411
+ };
412
+ if (!!(response === null || response === void 0 ? void 0 : response.ok)) return [3, 3];
413
+ if (useCustomErrorHandler) {
414
+ return [2, Promise.reject(error)];
415
+ }
416
+ return [4, response.json()];
417
+ case 2:
418
+ message = (_a.sent()).message;
419
+ error.message = message;
420
+ throw error;
421
+ case 3:
422
+ contentType = response.headers.get('content-type');
423
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json'))) return [3, 5];
424
+ return [4, response.json()];
425
+ case 4:
426
+ responseData = _a.sent();
427
+ return [3, 9];
428
+ case 5:
429
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('text'))) return [3, 7];
430
+ return [4, response.text()];
431
+ case 6:
432
+ responseData = _a.sent();
433
+ return [3, 9];
434
+ case 7:
435
+ if (!(response.status !== 204)) return [3, 9];
436
+ return [4, response.blob()];
437
+ case 8:
438
+ responseData = _a.sent();
439
+ _a.label = 9;
440
+ case 9: return [2, {
441
+ data: responseData,
442
+ status: response.status,
443
+ }];
444
+ }
445
+ });
446
+ });
447
+ };
448
+ var createGetRequest = function (path, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
449
+ if (headers === void 0) { headers = {}; }
450
+ if (params === void 0) { params = {}; }
451
+ if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
452
+ if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
453
+ return __awaiter(void 0, void 0, void 0, function () {
454
+ return __generator(this, function (_a) {
455
+ return [2, createAPIRequest(path, RequestMethods.GET, null, __assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler, additionalUnifiedHeaders)];
456
+ });
457
+ });
458
+ };
459
+ var createPostOrPutRequest = function (path, method, payload, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
460
+ if (method === void 0) { method = RequestMethods.POST; }
461
+ if (payload === void 0) { payload = {}; }
462
+ if (headers === void 0) { headers = {}; }
463
+ if (params === void 0) { params = {}; }
464
+ if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
465
+ if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
466
+ return __awaiter(void 0, void 0, void 0, function () {
467
+ return __generator(this, function (_a) {
468
+ return [2, createAPIRequest(path, method, payload, __assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler, additionalUnifiedHeaders)];
469
+ });
470
+ });
471
+ };
472
+
473
+ var showMobileNumberHint = function () {
474
+ var _a;
475
+ if (typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onRequestMobileNumber) === 'function') {
476
+ window.MobileApp.onRequestMobileNumber();
477
+ var promiseResolver_1;
478
+ var mobileNoPromise = new Promise(function (resolve) {
479
+ promiseResolver_1 = resolve;
480
+ });
481
+ window.sendSelectedMobileNumber = function (mobileNum) {
482
+ return promiseResolver_1(getAutoDetectedMobile(mobileNum));
483
+ };
484
+ return mobileNoPromise;
485
+ }
486
+ return Promise.resolve('');
487
+ };
488
+ var getAutoDetectedMobile = function (mobileNumber) {
489
+ var formattedMobileNo = '';
490
+ var matches = mobileNumber.match(MOBILE_CONSTANTS.REGEX);
491
+ if (matches) {
492
+ formattedMobileNo = matches[0].replace(/\D/g, '');
493
+ }
494
+ return formattedMobileNo;
495
+ };
496
+ var autoReadOtp = function () { return __awaiter(void 0, void 0, void 0, function () {
497
+ return __generator(this, function (_a) {
498
+ return [2, isAndroidApp() ? readOtpAndroid() : readOtpPWA()];
499
+ });
500
+ }); };
501
+ var updateNativeIOSOnSignIn = function () {
502
+ var _a, _b, _c;
503
+ (_c = (_b = (_a = window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.PWA_IS_SIGNIN) === null || _c === void 0 ? void 0 : _c.postMessage({
504
+ isSignIn: true,
505
+ });
506
+ };
507
+ var updateNativeAndroidOnSignIn = function () {
508
+ var _a;
509
+ (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPWALoginStatus(JSON.stringify({
510
+ isSignIn: true,
511
+ }));
512
+ };
513
+ var triggerOTPListener = function () {
514
+ var _a;
515
+ if (isAndroidApp()) {
516
+ (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPageStart('OTP_SCREEN');
517
+ }
518
+ };
519
+ var readOtpPWA = function () { return __awaiter(void 0, void 0, void 0, function () {
520
+ var abortController;
521
+ var _a;
522
+ return __generator(this, function (_b) {
523
+ if (!((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.get) || !('OTPCredential' in window)) {
524
+ return [2, Promise.reject('NOT_SUPPORTED')];
525
+ }
526
+ abortController = new AbortController();
527
+ setTimeout(function () {
528
+ abortController.abort();
529
+ }, 60000);
530
+ return [2, navigator.credentials
531
+ .get({
532
+ otp: { transport: ['sms'] },
533
+ signal: abortController.signal,
534
+ })
535
+ .then(function (content) { return content === null || content === void 0 ? void 0 : content.code; })];
536
+ });
537
+ }); };
538
+ var readOtpAndroid = function () { return __awaiter(void 0, void 0, void 0, function () {
539
+ var promiseResolver, otpPromise;
540
+ return __generator(this, function (_a) {
541
+ otpPromise = new Promise(function (resolve) {
542
+ promiseResolver = resolve;
543
+ });
544
+ window.sendOtpValue = function (otp) {
545
+ promiseResolver(otp);
546
+ };
547
+ return [2, otpPromise];
548
+ });
549
+ }); };
550
+ var shouldShowPushPrimer = function () { return __awaiter(void 0, void 0, void 0, function () {
551
+ var _a, _b;
552
+ return __generator(this, function (_c) {
553
+ if (isAndroidApp() &&
554
+ typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.isPNPermissionEnabled) === 'function') {
555
+ return [2, Promise.resolve(!((_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.isPNPermissionEnabled()))];
556
+ }
557
+ else if (isIOSApp()) {
558
+ return [2, new Promise(function (resolve, _reject) {
559
+ var _a, _b, _c, _d;
560
+ window.pushNotifcationPermissionStatus = function (data) {
561
+ var parsedData = JSON.parse(data);
562
+ var status = parsedData === null || parsedData === void 0 ? void 0 : parsedData.status;
563
+ if (typeof status === 'boolean') {
564
+ resolve(!status);
565
+ }
566
+ };
567
+ try {
568
+ (_d = (_c = (_b = (_a = window === null || window === void 0 ? void 0 : window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b['IS_PN_PERMISSION_ENABLED']) === null || _c === void 0 ? void 0 : _c.postMessage) === null || _d === void 0 ? void 0 : _d.call(_c, '');
569
+ }
570
+ catch (error) {
571
+ resolve(false);
572
+ }
573
+ })];
574
+ }
575
+ return [2, Promise.resolve(false)];
576
+ });
577
+ }); };
578
+ var handlePushPrimerCTA = function (type) {
579
+ var _a, _b, _c, _d, _e, _f, _g, _h;
580
+ if (isAndroidApp() &&
581
+ typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.handlePNPermission) === 'function') {
582
+ (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.handlePNPermission(JSON.stringify({ type: type }));
583
+ }
584
+ else if (isIOSApp() &&
585
+ ((_d = (_c = window === null || window === void 0 ? void 0 : window.webkit) === null || _c === void 0 ? void 0 : _c.messageHandlers) === null || _d === void 0 ? void 0 : _d.HANDLE_PN_PERMISSION)) {
586
+ (_h = (_g = (_f = (_e = window.webkit) === null || _e === void 0 ? void 0 : _e.messageHandlers) === null || _f === void 0 ? void 0 : _f.HANDLE_PN_PERMISSION) === null || _g === void 0 ? void 0 : _g.postMessage) === null || _h === void 0 ? void 0 : _h.call(_g, JSON.stringify({ type: type }));
587
+ }
588
+ return;
589
+ };
590
+
591
+ var getProfileDetails = function () { return __awaiter(void 0, void 0, void 0, function () {
592
+ var response, error_1;
593
+ return __generator(this, function (_a) {
594
+ switch (_a.label) {
595
+ case 0:
596
+ _a.trys.push([0, 2, , 3]);
597
+ return [4, createGetRequest('GET_PROFILE_DETAILS', {
598
+ caller: getApiDomain(),
599
+ 'app-agent': getAppAgent(),
600
+ }, {})];
601
+ case 1:
602
+ response = _a.sent();
603
+ return [2, response === null || response === void 0 ? void 0 : response.data];
604
+ case 2:
605
+ error_1 = _a.sent();
606
+ console.error('Failed to fetch user details. Error: ', error_1);
607
+ return [2, Promise.resolve(null)];
608
+ case 3: return [2];
609
+ }
610
+ });
611
+ }); };
612
+ var sendLoginOtp = function (mobile, personalizationHeaders) { return __awaiter(void 0, void 0, void 0, function () {
613
+ var response;
614
+ return __generator(this, function (_a) {
615
+ switch (_a.label) {
616
+ case 0: return [4, createPostOrPutRequest('SEND_OTP', RequestMethods.POST, {
617
+ value: mobile,
618
+ type: 'MOBILE',
619
+ action: 'SIGNIN',
620
+ countryCode: MOBILE_CONSTANTS.COUNTRY_CODE,
621
+ }, {
622
+ 'ab-otp': 'b',
623
+ dvid_data: personalizationHeaders,
624
+ })];
625
+ case 1:
626
+ response = _a.sent();
627
+ return [2, response === null || response === void 0 ? void 0 : response.data];
628
+ }
629
+ });
630
+ }); };
631
+ var validateOtp = function (mobile, otp) { return __awaiter(void 0, void 0, void 0, function () {
632
+ var response, data;
633
+ return __generator(this, function (_a) {
634
+ switch (_a.label) {
635
+ case 0: return [4, createPostOrPutRequest('VALIDATE_OTP', RequestMethods.POST, {
636
+ otp: otp,
637
+ value: mobile,
638
+ type: 'MOBILE',
639
+ action: 'SIGNIN',
640
+ countryCode: '+91',
641
+ }, { 'ab-otp': 'b' })];
642
+ case 1:
643
+ response = _a.sent();
644
+ data = response === null || response === void 0 ? void 0 : response.data;
645
+ return [2, __assign(__assign({}, response), { signup: (data === null || data === void 0 ? void 0 : data.action) === ValidateOTPAction.SIGNUP, action: data === null || data === void 0 ? void 0 : data.action, status: response === null || response === void 0 ? void 0 : response.status })];
646
+ }
647
+ });
648
+ }); };
649
+ var handleFKSSO = function (fallbackUri, skipProfileFlow) { return __awaiter(void 0, void 0, void 0, function () {
650
+ var currentPageUri, redirectionInfo;
651
+ return __generator(this, function (_a) {
652
+ switch (_a.label) {
653
+ case 0:
654
+ if (isIOSApp()) {
655
+ return [2, Promise.reject()];
656
+ }
657
+ currentPageUri = getCurrentPathName();
658
+ return [4, sendFKSSORedirectionInfo(fallbackUri, skipProfileFlow
659
+ ? currentPageUri
660
+ : NAVIGATION_ROUTES.PERSONAL_DETAILS + '?onboardingFlow=true', currentPageUri)];
661
+ case 1:
662
+ redirectionInfo = _a.sent();
663
+ if (isAndroidApp()) {
664
+ return [2, handleFKSSOAndroid(redirectionInfo)];
665
+ }
666
+ else {
667
+ return [2, handleFKSSOWeb(redirectionInfo)];
668
+ }
669
+ }
670
+ });
671
+ }); };
672
+ var isValidMobileNumber = function (text) {
673
+ return (text === null || text === void 0 ? void 0 : text.length) === MOBILE_CONSTANTS.LENGTH && /^\d{10}$/.test(text);
674
+ };
675
+ var updateNativeOnLogin = function () {
676
+ if (isIOSApp()) {
677
+ updateNativeIOSOnSignIn();
678
+ }
679
+ else if (isAndroidApp()) {
680
+ updateNativeAndroidOnSignIn();
681
+ }
682
+ };
683
+ var isFKSSOEnabled = function () {
684
+ return isPwa() || (!isIOSApp() && isJSVersionUpdated(5));
685
+ };
686
+ var sendFKSSORedirectionInfo = function (fallbackUri, signupPageUri, currentPageUri) { return __awaiter(void 0, void 0, void 0, function () {
687
+ var WEBSITE_BASE, response;
688
+ return __generator(this, function (_a) {
689
+ switch (_a.label) {
690
+ case 0:
691
+ WEBSITE_BASE = getApiDomain();
692
+ return [4, createPostOrPutRequest('FK_REDIRECTION_INFO', RequestMethods.POST, {
693
+ provider: 'flipkart',
694
+ fallbackUri: urlJoin(WEBSITE_BASE, fallbackUri || currentPageUri),
695
+ signupPageUri: urlJoin(WEBSITE_BASE, signupPageUri || 'personal-details'),
696
+ currentPageUri: urlJoin(WEBSITE_BASE, currentPageUri),
697
+ })];
698
+ case 1:
699
+ response = _a.sent();
700
+ return [2, response === null || response === void 0 ? void 0 : response.data];
701
+ }
702
+ });
703
+ }); };
704
+ var handleFKSSOWeb = function (redirectionInfo) {
705
+ var _a;
706
+ var params = (_a = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params) !== null && _a !== void 0 ? _a : {};
707
+ var redirectUri = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.redirectUri;
708
+ if (redirectUri) {
709
+ redirectUri += '?';
710
+ for (var key in params) {
711
+ redirectUri += key + '=' + params[key] + '&';
712
+ }
713
+ return Promise.resolve(redirectUri);
714
+ }
715
+ return Promise.reject();
716
+ };
717
+ var handleFKSSOAndroid = function (redirectionInfo) {
718
+ var _a, _b;
719
+ var params = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params;
720
+ if (isEmpty(params) ||
721
+ typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onNavigationChange) !== 'function') {
722
+ return Promise.reject();
723
+ }
724
+ else {
725
+ var FK_REDIRECT_DL = urlJoin(getApiDomain(), 'dl/oauth2');
726
+ (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.onNavigationChange(JSON.stringify({
727
+ type: 'FkSSO',
728
+ miscData: __assign(__assign({}, params), { redirectURI: FK_REDIRECT_DL }),
729
+ }));
730
+ return Promise.resolve();
731
+ }
732
+ };
733
+ function getUserAuthValues(customCookie) {
734
+ try {
735
+ var _a = decodeURIComponent(getCookie('userid', customCookie) || '').split('|'), email = _a[0], profileName = _a[1], gender = _a[2], photo = _a[3], userId = _a[4];
736
+ return {
737
+ email: email,
738
+ profileName: profileName,
739
+ gender: gender,
740
+ photo: photo,
741
+ userId: userId,
742
+ };
743
+ }
744
+ catch (error) {
745
+ return {};
746
+ }
747
+ }
748
+ var isUserSignedIn = function (customCookie) {
749
+ var userObject = getUserAuthValues(customCookie) || {};
750
+ var usermiscVal = decodeURIComponent(getCookie('usermisc', customCookie) || '').split('|');
751
+ var signedIn = usermiscVal.includes('SIGNED_IN') &&
752
+ userObject.userId &&
753
+ userObject.userId.length > 0
754
+ ? true
755
+ : false;
756
+ return signedIn;
757
+ };
758
+ var sendClevertapProfileDetails = function (profileDetails) {
759
+ var _a, _b, _c, _d, _e, _f;
760
+ try {
761
+ if (isServer() || !(window === null || window === void 0 ? void 0 : window.clevertap) || isEmpty(profileDetails)) {
762
+ return;
763
+ }
764
+ var Site = {
765
+ Identity: (_a = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.id) !== null && _a !== void 0 ? _a : '',
766
+ Gender: (_b = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.gender) !== null && _b !== void 0 ? _b : '',
767
+ Email: (_c = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.username) !== null && _c !== void 0 ? _c : '',
768
+ Phone: "".concat(profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.countryCode).concat(profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.mobile),
769
+ 'MSG-sms': true,
770
+ 'MSG-push': true,
771
+ 'MSG-email': false,
772
+ 'MSG-whatsapp': true,
773
+ };
774
+ if ((_d = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails) === null || _d === void 0 ? void 0 : _d.length) {
775
+ for (var i = 0; i < ((_e = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails) === null || _e === void 0 ? void 0 : _e.length); i++) {
776
+ var traveller = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails[i];
777
+ if (traveller.isRegistered) {
778
+ var dateOfBirth = traveller.personalDetails.dateOfBirth;
779
+ Site.Name = "".concat(traveller.personalDetails.firstName, " ").concat(traveller.personalDetails.lastName);
780
+ if (!isNaN(dateOfBirth)) {
781
+ Site.DOB = new Date(dateOfBirth);
782
+ }
783
+ break;
784
+ }
785
+ }
786
+ }
787
+ (_f = window === null || window === void 0 ? void 0 : window.clevertap) === null || _f === void 0 ? void 0 : _f.onUserLogin.push({ Site: Site });
788
+ }
789
+ catch (error) {
790
+ console.log('Error pushing clevertap profile information. Error: ', error);
791
+ }
792
+ };
793
+ var handleProfileFetch = function (updateClevertap) {
794
+ if (updateClevertap === void 0) { updateClevertap = true; }
795
+ return __awaiter(void 0, void 0, void 0, function () {
796
+ var response;
797
+ return __generator(this, function (_a) {
798
+ switch (_a.label) {
799
+ case 0: return [4, getProfileDetails()];
800
+ case 1:
801
+ response = _a.sent();
802
+ if (response) {
803
+ if (updateClevertap) {
804
+ sendClevertapProfileDetails(response);
805
+ }
806
+ }
807
+ return [2];
808
+ }
809
+ });
810
+ });
811
+ };
812
+
813
+ var getUserInsights = function (userId) { return __awaiter(void 0, void 0, void 0, function () {
814
+ var response;
815
+ return __generator(this, function (_a) {
816
+ switch (_a.label) {
817
+ case 0:
818
+ _a.trys.push([0, 2, , 3]);
819
+ return [4, createGetRequest('USER_INSIGHTS', {}, {
820
+ pathParams: {
821
+ userId: userId,
822
+ },
823
+ })];
824
+ case 1:
825
+ response = _a.sent();
826
+ return [2, response === null || response === void 0 ? void 0 : response.data];
827
+ case 2:
828
+ _a.sent();
829
+ return [2, Promise.resolve(null)];
830
+ case 3: return [2];
831
+ }
832
+ });
833
+ }); };
834
+ var getUserInsightsData = function (userId) { return __awaiter(void 0, void 0, void 0, function () {
835
+ var _userId, stringifiedData, sessionData, userInsights;
836
+ var _a, _b, _c, _d;
837
+ return __generator(this, function (_f) {
838
+ switch (_f.label) {
839
+ case 0:
840
+ _f.trys.push([0, 2, , 3]);
841
+ _userId = userId !== null && userId !== void 0 ? userId : getUserAuthValues().userId;
842
+ if (!_userId) {
843
+ (_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.removeItem('martech_user_attributes');
844
+ return [2, null];
845
+ }
846
+ stringifiedData = (_b = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _b === void 0 ? void 0 : _b.getItem('martech_user_attributes');
847
+ sessionData = void 0;
848
+ if (typeof stringifiedData === 'string') {
849
+ sessionData = JSON.parse(stringifiedData);
850
+ }
851
+ if (_userId !== (sessionData === null || sessionData === void 0 ? void 0 : sessionData.accountId)) {
852
+ (_c = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _c === void 0 ? void 0 : _c.removeItem('martech_user_attributes');
853
+ }
854
+ return [4, getUserInsights(_userId)];
855
+ case 1:
856
+ userInsights = _f.sent();
857
+ if (isEmpty(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data)) {
858
+ return [2, null];
859
+ }
860
+ (_d = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _d === void 0 ? void 0 : _d.setItem('martech_user_attributes', JSON.stringify(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data));
861
+ return [2, userInsights === null || userInsights === void 0 ? void 0 : userInsights.data];
862
+ case 2:
863
+ _f.sent();
864
+ return [2, null];
865
+ case 3: return [2];
866
+ }
867
+ });
868
+ }); };
869
+
870
+ var stringifyPayload = function (payload) {
871
+ var keys = Object.keys(payload);
872
+ keys.forEach(function (key) {
873
+ if (key === 'a_fare_price' ||
874
+ key === 'a_ct_discount' ||
875
+ key === 'supercoin_balance' ||
876
+ key === 'supercoin_earned' ||
877
+ key === 'supercoin_burnt' ||
878
+ key === 'wallet_balance_used' ||
879
+ key === 'convenience_fee')
880
+ payload[key] = Number(payload[key]);
881
+ else
882
+ payload[key] = '' + payload[key];
883
+ });
884
+ return payload;
885
+ };
886
+ var getCTStatsigExpForRaven = function () {
887
+ try {
888
+ if (isServer()) {
889
+ return '';
890
+ }
891
+ var cookie = getCookie('ct_statsig_experiments') || '{}';
892
+ var parsedCookie_1 = cookie
893
+ ? JSON.parse(decodeURIComponent(cookie))
894
+ : {};
895
+ return Object.keys(parsedCookie_1)
896
+ .map(function (key) {
897
+ if (key && parsedCookie_1[key]) {
898
+ return "".concat(key, ":").concat(parsedCookie_1[key]);
899
+ }
900
+ return '';
901
+ })
902
+ .filter(function (value) { return !!value; })
903
+ .join('|');
904
+ }
905
+ catch (_e) {
906
+ return '';
907
+ }
908
+ };
909
+ var ravenSDKTrigger = function (eventName, ravenPayload) {
910
+ var _a;
911
+ if (window && window['ravenWebManager']) {
912
+ var _b = getRavenEventProps(), pageName = _b.pageName, utmSource = _b.utmSource;
913
+ var commonPayload = {
914
+ page_name: pageName,
915
+ u_utm_source: utmSource,
916
+ domain: window.location.host,
917
+ u_ab_key: getCTStatsigExpForRaven(),
918
+ platform: (_a = getDevicePlatform()) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
919
+ login_status: isUserSignedIn() ? 'yes' : 'no',
920
+ };
921
+ var newRavenPayload = stringifyPayload(ravenPayload);
922
+ var RavenWebManager = window['ravenWebManager'];
923
+ RavenWebManager === null || RavenWebManager === void 0 ? void 0 : RavenWebManager.triggerRaven(eventName, __assign(__assign({}, commonPayload), newRavenPayload));
924
+ }
925
+ };
926
+ var isAirHomePage = function () {
927
+ if (window && typeof window !== 'undefined') {
928
+ var pathname = getNestedValue(window, ['location', 'pathname']);
929
+ if (pathname === '/' || pathname === '/flights') {
930
+ return true;
931
+ }
932
+ }
933
+ return false;
934
+ };
935
+ var getRavenEventProps = function () {
936
+ var _a, _b;
937
+ if (window && typeof window !== 'undefined') {
938
+ var pathUrl = window.location.pathname;
939
+ var redirectionPath = (_a = getQueryParam('service')) !== null && _a !== void 0 ? _a : '';
940
+ var utmSource = (_b = getQueryParam('utm_source')) !== null && _b !== void 0 ? _b : 'organic';
941
+ var loginForm = isAirHomePage() ? 'skippable_login' : 'account_login';
942
+ var vertical = 'air';
943
+ var pageName = pathUrl.includes('flights/itinerary') ||
944
+ redirectionPath.includes('flights/itinerary')
945
+ ? 'a_itinerary'
946
+ : 'a_home';
947
+ if (redirectionPath.includes('my-account')) {
948
+ vertical = 'uar';
949
+ pageName = 'account';
950
+ }
951
+ if (redirectionPath.includes('hotels')) {
952
+ vertical = 'hotel';
953
+ pageName = redirectionPath.includes('hotels/itinerary')
954
+ ? 'h_itinerary'
955
+ : 'h_home';
956
+ }
957
+ if (redirectionPath.includes('bus')) {
958
+ vertical = 'bus';
959
+ pageName = redirectionPath.includes('bus/itinerary')
960
+ ? 'b_itinerary'
961
+ : 'b_home';
962
+ }
963
+ return { loginForm: loginForm, vertical: vertical, pageName: pageName, utmSource: utmSource };
964
+ }
965
+ return {};
966
+ };
967
+ var sendEventWithUserInsights = function (eventName, ravenPayload, userId) { return __awaiter(void 0, void 0, void 0, function () {
968
+ var userInsights, updatedPayload, loyaltyData, martechAttributes;
969
+ var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
970
+ return __generator(this, function (_t) {
971
+ switch (_t.label) {
972
+ case 0: return [4, getUserInsightsData(userId)];
973
+ case 1:
974
+ userInsights = _t.sent();
975
+ updatedPayload = __assign(__assign({}, ravenPayload), { fk_loyalty_status: 'na', fk_loyalty_end_dt: 'na', ct_last_booking_dt: 'na', ct_lifetime_booking: 'na', fk_loyalty_start_dt: 'na', ct_first_booking_dt: 'na', myntra_loyalty_status: 'na', ct_postmerger_booking: 'na', ct_last_1year_booking: 'na', myntra_loyalty_end_dt: 'na', ct_2nd_last_booking_dt: 'na', myntra_loyalty_start_dt: 'na' });
976
+ if (!isEmpty(userInsights)) {
977
+ loyaltyData = ((_a = userInsights === null || userInsights === void 0 ? void 0 : userInsights.loyaltyStatus) !== null && _a !== void 0 ? _a : []).reduce(function (prev, curr) {
978
+ return __assign(__assign({}, prev), curr);
979
+ }, {});
980
+ martechAttributes = {
981
+ ct_lifetime_booking: ((_c = (_b = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _b === void 0 ? void 0 : _b.lifetimeBooking) !== null && _c !== void 0 ? _c : 'na').toString(),
982
+ ct_postmerger_booking: ((_f = (_d = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _d === void 0 ? void 0 : _d.postmergerBooking) !== null && _f !== void 0 ? _f : 'na').toString(),
983
+ ct_last_1year_booking: ((_h = (_g = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _g === void 0 ? void 0 : _g.lastOneYearBooking) !== null && _h !== void 0 ? _h : 'na').toString(),
984
+ ct_first_booking_dt: secondsToDateString((_j = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _j === void 0 ? void 0 : _j.firstbookingDate) || 'na',
985
+ ct_last_booking_dt: secondsToDateString((_k = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _k === void 0 ? void 0 : _k.lastbookingDate) || 'na',
986
+ ct_2nd_last_booking_dt: secondsToDateString((_l = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _l === void 0 ? void 0 : _l.secondLastbookingDate) || 'na',
987
+ fk_loyalty_status: ((_m = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _m === void 0 ? void 0 : _m.program) || 'na',
988
+ myntra_loyalty_status: ((_o = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _o === void 0 ? void 0 : _o.program) || 'na',
989
+ fk_loyalty_end_dt: secondsToDateString((_p = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _p === void 0 ? void 0 : _p.loyaltyEndDate) || '',
990
+ fk_loyalty_start_dt: secondsToDateString((_q = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _q === void 0 ? void 0 : _q.loyaltyStartDate) || 'na',
991
+ myntra_loyalty_start_dt: secondsToDateString((_r = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _r === void 0 ? void 0 : _r.loyaltyStartDate) ||
992
+ 'na',
993
+ myntra_loyalty_end_dt: secondsToDateString((_s = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _s === void 0 ? void 0 : _s.loyaltyEndDate) ||
994
+ 'na',
995
+ };
996
+ updatedPayload = __assign(__assign({}, updatedPayload), martechAttributes);
997
+ setMartechUserProperties(martechAttributes);
998
+ }
999
+ ravenSDKTrigger(eventName, updatedPayload);
1000
+ return [2];
1001
+ }
1002
+ });
1003
+ }); };
1004
+ var setMartechUserProperties = function (userProperties) {
1005
+ var _a, _b, _c, _d, _f, _g, _h, _j, _k;
1006
+ if (isEmpty(userProperties) ||
1007
+ ((_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem('martech_user_props_sent'))) {
1008
+ return;
1009
+ }
1010
+ if (isIOSApp() && ((_c = (_b = window === null || window === void 0 ? void 0 : window.webkit) === null || _b === void 0 ? void 0 : _b.messageHandlers) === null || _c === void 0 ? void 0 : _c.SEND_ATTRIBUTES)) {
1011
+ (_d = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _d === void 0 ? void 0 : _d.postMessage({
1012
+ type: 'GA',
1013
+ params: userProperties,
1014
+ });
1015
+ (_f = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _f === void 0 ? void 0 : _f.postMessage({
1016
+ type: 'Clevertap',
1017
+ params: userProperties,
1018
+ });
1019
+ (_g = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _g === void 0 ? void 0 : _g.setItem('martech_user_props_sent', 'true');
1020
+ }
1021
+ else if (isAndroidApp() && ((_h = window === null || window === void 0 ? void 0 : window.MobileApp) === null || _h === void 0 ? void 0 : _h.sendAttributes)) {
1022
+ window.MobileApp.sendAttributes('GA', JSON.stringify(userProperties));
1023
+ window.MobileApp.sendAttributes('Clevertap', JSON.stringify(userProperties));
1024
+ (_j = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _j === void 0 ? void 0 : _j.setItem('martech_user_props_sent', 'true');
1025
+ }
1026
+ else if (isPwa() && window.clevertap) {
1027
+ window.clevertap.profile.push({
1028
+ Site: userProperties,
1029
+ });
1030
+ (_k = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _k === void 0 ? void 0 : _k.setItem('martech_user_props_sent', 'true');
1031
+ }
1032
+ };
1033
+ var batchRavenEvent = function (eventName, ravenPayload) {
1034
+ if (typeof window !== 'undefined' &&
1035
+ typeof window.requestIdleCallback === 'function') {
1036
+ requestIdleCallback(function () {
1037
+ ravenSDKTrigger(eventName, ravenPayload);
1038
+ });
1039
+ }
1040
+ else {
1041
+ setTimeout(function () {
1042
+ ravenSDKTrigger(eventName, ravenPayload);
1043
+ }, 0);
1044
+ }
1045
+ };
1046
+
1047
+ var getHotelCrossSellRecos = function (vertical, fallbackPageLandingURL, cutoff, couponCallOutPrefix, couponCallOutSuffix, offerCallOut, additionalHeaders, additionalParams, lpgCTAFlag) {
1048
+ if (cutoff === void 0) { cutoff = 450; }
1049
+ if (couponCallOutPrefix === void 0) { couponCallOutPrefix = 'Discounts'; }
1050
+ if (couponCallOutSuffix === void 0) { couponCallOutSuffix = 'on hotels'; }
1051
+ if (offerCallOut === void 0) { offerCallOut = 'CTBEST - Exclusive coupon applied for you!'; }
1052
+ if (additionalHeaders === void 0) { additionalHeaders = {}; }
1053
+ if (additionalParams === void 0) { additionalParams = {}; }
1054
+ if (lpgCTAFlag === void 0) { lpgCTAFlag = false; }
1055
+ return __awaiter(void 0, void 0, void 0, function () {
1056
+ var userId, fallbackData, timeoutPromise, fetchRecommendationsPromise, result;
1057
+ var _a, _b;
1058
+ return __generator(this, function (_c) {
1059
+ switch (_c.label) {
1060
+ case 0:
1061
+ userId = (_b = (_a = getUserAuthValues()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : '';
1062
+ fallbackData = {
1063
+ couponCode: '',
1064
+ couponCallOut: '',
1065
+ couponCallOutPrefix: couponCallOutPrefix,
1066
+ couponCallOutSuffix: couponCallOutSuffix,
1067
+ offerCallOut: offerCallOut,
1068
+ pageLandingUrl: fallbackPageLandingURL,
1069
+ knowMoreFlag: lpgCTAFlag,
1070
+ };
1071
+ _c.label = 1;
1072
+ case 1:
1073
+ _c.trys.push([1, 3, , 4]);
1074
+ timeoutPromise = new Promise(function (resolve) {
1075
+ setTimeout(function () {
1076
+ resolve(fallbackData);
1077
+ }, cutoff);
1078
+ });
1079
+ fetchRecommendationsPromise = createGetRequest('HOTEL_RECOMMENDATIONS', additionalHeaders, {
1080
+ queryParams: __assign({ userId: userId, vertical: vertical }, additionalParams),
1081
+ }, false, {
1082
+ userBuckets: { 'x-cross-sell': 'true' },
1083
+ platform: getAppAgentForHotelUnifiedHeader(),
1084
+ }).then(function (res) { return res.data; });
1085
+ return [4, Promise.race([
1086
+ fetchRecommendationsPromise,
1087
+ timeoutPromise,
1088
+ ])];
1089
+ case 2:
1090
+ result = _c.sent();
1091
+ return [2, result];
1092
+ case 3:
1093
+ _c.sent();
1094
+ return [2, fallbackData];
1095
+ case 4: return [2];
1096
+ }
1097
+ });
1098
+ });
1099
+ };
1100
+
1101
+ export { MULTI_SPACE, autoReadOtp, batchRavenEvent, createAPIRequest, createGetRequest, createPostOrPutRequest, extractQueryParamsAsObj, formatCurrency, formatFullDateString, getApiDomain, getAppAgent, getAppAgentForHotelUnifiedHeader, getAutoDetectedMobile, getCTStatsigExpForRaven, getCookie, getCurrentPathName, getCurrentUrl, getDeviceModel, getDevicePlatform, getDimensionFromImageUrl, getFutureDateFromDays, getHeightFromImgUrl, getHotelCrossSellRecos, getJSVersion, getNestedValue, getNoOfDaysFromToday, getQueryParam, getRavenEventProps, getUserAuthValues, getWidthFromImgUrl, handleFKSSO, handleProfileFetch, handlePushPrimerCTA, isAirHomePage, isAndroidApp, isEmpty, isFKSSOEnabled, isHTMLInputElement, isIOSApp, isJSVersionUpdated, isNumeric, isPwa, isServer, isUserSignedIn, isValidMobileNumber, path, ravenSDKTrigger, secondsToDateString, sendEventWithUserInsights, sendLoginOtp, setCookie, setMartechUserProperties, shouldShowPushPrimer, showMobileNumberHint, stringifyPayload, triggerOTPListener, updateNativeAndroidOnSignIn, updateNativeIOSOnSignIn, updateNativeOnLogin, urlJoin, validateOtp };
2
1102
  //# sourceMappingURL=ct-platform-utils.esm.js.map