@cleartrip/ct-platform-utils 3.11.1-beta.1 → 3.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,922 +1,2 @@
1
- 'use strict';
2
-
3
- var tslib = require('tslib');
4
- var ctPlatformConstants = require('@cleartrip/ct-platform-constants');
5
- var ctPlatformTypes = require('@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 replacePlaceHolder = function (text, data, replaceWithTag, replaceClass) {
154
- if (replaceWithTag === void 0) { replaceWithTag = false; }
155
- if (replaceClass === void 0) { replaceClass = ''; }
156
- if (!isEmpty(text) && !isEmpty(data)) {
157
- var placeholders_1 = text.match(/[^{\}]+(?=})/g);
158
- text = text.replace(/[{}]/g, '');
159
- if (!isEmpty(placeholders_1)) {
160
- placeholders_1.forEach(function (item, index) {
161
- if (replaceWithTag) {
162
- text = text.replace(placeholders_1[index], "<span class=".concat(replaceClass, ">").concat(data[placeholders_1[index]], "</span>"));
163
- }
164
- else {
165
- text = text.replace(placeholders_1[index], data[placeholders_1[index]]);
166
- }
167
- });
168
- }
169
- }
170
- return text;
171
- };
172
- var secondsToDateString = function (sec) {
173
- try {
174
- if (!sec || Number.isNaN(Number(sec))) {
175
- return '';
176
- }
177
- var date = new Date(sec * 1000);
178
- var year = date.getFullYear();
179
- var day = String(date.getDate()).padStart(2, '0');
180
- var month = String(date.getMonth() + 1).padStart(2, '0');
181
- return "".concat(year, "-").concat(month, "-").concat(day);
182
- }
183
- catch (_e) {
184
- return '';
185
- }
186
- };
187
- var formatFullDateString = function (dateString, format, fallback) {
188
- if (format === void 0) { format = 'dd-mm-yyyy'; }
189
- if (fallback === void 0) { fallback = ''; }
190
- try {
191
- var date = new Date(dateString);
192
- var year = date.getFullYear();
193
- var day = String(date.getDate()).padStart(2, '0');
194
- var month = String(date.getMonth() + 1).padStart(2, '0');
195
- switch (format) {
196
- case 'yyyy-mm-dd':
197
- return "".concat(year, "-").concat(month, "-").concat(day);
198
- case 'dd-mm-yyyy':
199
- default:
200
- return "".concat(day, "-").concat(month, "-").concat(year);
201
- }
202
- }
203
- catch (_e) {
204
- return fallback;
205
- }
206
- };
207
- var formatCurrency = function (value, withIcon) {
208
- if (withIcon === void 0) { withIcon = true; }
209
- try {
210
- var config = {
211
- currency: 'INR',
212
- minimumFractionDigits: 0,
213
- };
214
- if (withIcon) {
215
- config.style = 'currency';
216
- }
217
- if (typeof value !== 'string') {
218
- value = value === null || value === void 0 ? void 0 : value.toString();
219
- }
220
- value = value.replace(/,/g, '');
221
- return parseInt(value, 10).toLocaleString('en-IN', config);
222
- }
223
- catch (_e) {
224
- return '';
225
- }
226
- };
227
-
228
- var getDevicePlatform = function () {
229
- var _a;
230
- var userAgent = (_a = getNestedValue(window, [
231
- 'navigator',
232
- 'userAgent',
233
- ])) === null || _a === void 0 ? void 0 : _a.toLowerCase();
234
- var safariBrowser = /safari/.test(userAgent);
235
- var appleDevice = /iphone|ipod|ipad/.test(userAgent);
236
- if ((getNestedValue(window, ['androidData', 'app-agent']) &&
237
- getNestedValue(window, ['androidData', 'js-version'])) ||
238
- typeof getNestedValue(window, ['MobileApp', 'getAppSpecificData']) ===
239
- 'function') {
240
- return ctPlatformConstants.Platform.ANDROID;
241
- }
242
- else if ((getNestedValue(window, ['iosData', 'app-agent']) &&
243
- getNestedValue(window, ['iosData', 'js-version'])) ||
244
- (appleDevice && !safariBrowser)) {
245
- return ctPlatformConstants.Platform.IOS;
246
- }
247
- return ctPlatformConstants.Platform.PWA;
248
- };
249
- var getAppAgent = function () {
250
- var _a, _b;
251
- var platform = getDevicePlatform();
252
- if (platform === ctPlatformConstants.Platform.IOS) {
253
- return (_a = getNestedValue(window, ['iosData', 'app-agent'])) !== null && _a !== void 0 ? _a : ctPlatformConstants.AppAgent.IOS;
254
- }
255
- else if (platform === ctPlatformConstants.Platform.ANDROID) {
256
- return ((_b = getNestedValue(window, ['androidData', 'app-agent'])) !== null && _b !== void 0 ? _b : ctPlatformConstants.AppAgent.ANDROID);
257
- }
258
- return ctPlatformConstants.AppAgent.PWA;
259
- };
260
- var getJSVersion = function () {
261
- var jsVersion = '';
262
- if (isIOSApp()) {
263
- jsVersion = getNestedValue(window, ['iosData', 'js-version']);
264
- }
265
- else if (isAndroidApp()) {
266
- jsVersion = getNestedValue(window, ['androidData', 'js-version']);
267
- }
268
- if (jsVersion) {
269
- jsVersion = jsVersion.toString().split('.')[0];
270
- }
271
- return jsVersion;
272
- };
273
- var isPwa = function () {
274
- return getDevicePlatform() !== ctPlatformConstants.Platform.ANDROID &&
275
- getDevicePlatform() !== ctPlatformConstants.Platform.IOS;
276
- };
277
- var isAndroidApp = function () {
278
- return getDevicePlatform() === ctPlatformConstants.Platform.ANDROID;
279
- };
280
- var isJSVersionUpdated = function (compareVersion) {
281
- return parseInt(getJSVersion()) >= compareVersion;
282
- };
283
- var isIOSApp = function () { return getDevicePlatform() === ctPlatformConstants.Platform.IOS; };
284
-
285
- var API_BASE = getApiDomain();
286
- var getRequestUrl = function (path, params) {
287
- var url = ctPlatformConstants.API_ROUTES[path];
288
- if (!url || !url.trim().length) {
289
- return;
290
- }
291
- url = urlJoin(API_BASE, url);
292
- if (params === null || params === void 0 ? void 0 : params.pathParams) {
293
- for (var _i = 0, _a = Object.entries(params.pathParams); _i < _a.length; _i++) {
294
- var _b = _a[_i], key = _b[0], value = _b[1];
295
- url = url.replace(":".concat(key), value);
296
- }
297
- }
298
- if (params === null || params === void 0 ? void 0 : params.queryParams) {
299
- url += "?".concat(new URLSearchParams(params.queryParams).toString());
300
- }
301
- return url;
302
- };
303
- var createAPIRequest = function (path, method, payload, headers, params, useCustomErrorHandler) {
304
- if (method === void 0) { method = ctPlatformConstants.RequestMethods.GET; }
305
- if (headers === void 0) { headers = {}; }
306
- if (params === void 0) { params = {}; }
307
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
308
- return tslib.__awaiter(void 0, void 0, void 0, function () {
309
- var url, API_AUTHORITY, requestOptions, responseData, response, error, message, contentType;
310
- return tslib.__generator(this, function (_a) {
311
- switch (_a.label) {
312
- case 0:
313
- url = getRequestUrl(path, params);
314
- if (!url || !url.trim().length) {
315
- return [2, Promise.reject('URL parameter missing')];
316
- }
317
- API_AUTHORITY = getApiDomain();
318
- requestOptions = {
319
- method: method,
320
- headers: tslib.__assign({ Caller: API_BASE, Origin: API_BASE, Referer: API_BASE, Authority: API_AUTHORITY, x_ct_sourcetype: 'MOBILE', 'app-agent': getAppAgent(), 'Content-Type': 'application/json' }, headers),
321
- };
322
- if (payload) {
323
- requestOptions.body = JSON.stringify(payload);
324
- }
325
- return [4, fetch(url, requestOptions)];
326
- case 1:
327
- response = _a.sent();
328
- error = {
329
- name: 'API_FAILURE',
330
- status: response.status,
331
- message: 'UNKNOWN_ERROR',
332
- statusText: response.statusText,
333
- };
334
- if (!!(response === null || response === void 0 ? void 0 : response.ok)) return [3, 3];
335
- if (useCustomErrorHandler) {
336
- return [2, Promise.reject(error)];
337
- }
338
- return [4, response.json()];
339
- case 2:
340
- message = (_a.sent()).message;
341
- error.message = message;
342
- throw error;
343
- case 3:
344
- contentType = response.headers.get('content-type');
345
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json'))) return [3, 5];
346
- return [4, response.json()];
347
- case 4:
348
- responseData = _a.sent();
349
- return [3, 9];
350
- case 5:
351
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('text'))) return [3, 7];
352
- return [4, response.text()];
353
- case 6:
354
- responseData = _a.sent();
355
- return [3, 9];
356
- case 7:
357
- if (!(response.status !== 204)) return [3, 9];
358
- return [4, response.blob()];
359
- case 8:
360
- responseData = _a.sent();
361
- _a.label = 9;
362
- case 9: return [2, {
363
- data: responseData,
364
- status: response.status,
365
- }];
366
- }
367
- });
368
- });
369
- };
370
- var createGetRequest = function (path, headers, params, useCustomErrorHandler) {
371
- if (headers === void 0) { headers = {}; }
372
- if (params === void 0) { params = {}; }
373
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
374
- return tslib.__awaiter(void 0, void 0, void 0, function () {
375
- return tslib.__generator(this, function (_a) {
376
- return [2, createAPIRequest(path, ctPlatformConstants.RequestMethods.GET, null, tslib.__assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler)];
377
- });
378
- });
379
- };
380
- var createPostOrPutRequest = function (path, method, payload, headers, params, useCustomErrorHandler) {
381
- if (method === void 0) { method = ctPlatformConstants.RequestMethods.POST; }
382
- if (payload === void 0) { payload = {}; }
383
- if (headers === void 0) { headers = {}; }
384
- if (params === void 0) { params = {}; }
385
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
386
- return tslib.__awaiter(void 0, void 0, void 0, function () {
387
- return tslib.__generator(this, function (_a) {
388
- return [2, createAPIRequest(path, method, payload, tslib.__assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler)];
389
- });
390
- });
391
- };
392
-
393
- var showMobileNumberHint = function () {
394
- var _a;
395
- if (typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onRequestMobileNumber) === 'function') {
396
- window.MobileApp.onRequestMobileNumber();
397
- var promiseResolver_1;
398
- var mobileNoPromise = new Promise(function (resolve) {
399
- promiseResolver_1 = resolve;
400
- });
401
- window.sendSelectedMobileNumber = function (mobileNum) {
402
- return promiseResolver_1(getAutoDetectedMobile(mobileNum));
403
- };
404
- return mobileNoPromise;
405
- }
406
- return Promise.resolve('');
407
- };
408
- var getAutoDetectedMobile = function (mobileNumber) {
409
- var formattedMobileNo = '';
410
- var matches = mobileNumber.match(ctPlatformConstants.MOBILE_CONSTANTS.REGEX);
411
- if (matches) {
412
- formattedMobileNo = matches[0].replace(/\D/g, '');
413
- }
414
- return formattedMobileNo;
415
- };
416
- var autoReadOtp = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
417
- return tslib.__generator(this, function (_a) {
418
- return [2, isAndroidApp() ? readOtpAndroid() : readOtpPWA()];
419
- });
420
- }); };
421
- var updateNativeIOSOnSignIn = function () {
422
- var _a, _b, _c;
423
- (_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({
424
- isSignIn: true,
425
- });
426
- };
427
- var updateNativeAndroidOnSignIn = function () {
428
- var _a;
429
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPWALoginStatus(JSON.stringify({
430
- isSignIn: true,
431
- }));
432
- };
433
- var triggerOTPListener = function () {
434
- var _a;
435
- if (isAndroidApp()) {
436
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPageStart('OTP_SCREEN');
437
- }
438
- };
439
- var readOtpPWA = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
440
- var abortController;
441
- var _a;
442
- return tslib.__generator(this, function (_b) {
443
- if (!((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.get) || !('OTPCredential' in window)) {
444
- return [2, Promise.reject('NOT_SUPPORTED')];
445
- }
446
- abortController = new AbortController();
447
- setTimeout(function () {
448
- abortController.abort();
449
- }, 60000);
450
- return [2, navigator.credentials
451
- .get({
452
- otp: { transport: ['sms'] },
453
- signal: abortController.signal,
454
- })
455
- .then(function (content) { return content === null || content === void 0 ? void 0 : content.code; })];
456
- });
457
- }); };
458
- var readOtpAndroid = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
459
- var promiseResolver, otpPromise;
460
- return tslib.__generator(this, function (_a) {
461
- otpPromise = new Promise(function (resolve) {
462
- promiseResolver = resolve;
463
- });
464
- window.sendOtpValue = function (otp) {
465
- promiseResolver(otp);
466
- };
467
- return [2, otpPromise];
468
- });
469
- }); };
470
-
471
- var sendLoginOtp = function (mobile, personalizationHeaders) { return tslib.__awaiter(void 0, void 0, void 0, function () {
472
- var response;
473
- return tslib.__generator(this, function (_a) {
474
- switch (_a.label) {
475
- case 0: return [4, createPostOrPutRequest('SEND_OTP', ctPlatformConstants.RequestMethods.POST, {
476
- value: mobile,
477
- type: 'MOBILE',
478
- action: 'SIGNIN',
479
- countryCode: ctPlatformConstants.MOBILE_CONSTANTS.COUNTRY_CODE,
480
- }, {
481
- 'ab-otp': 'b',
482
- dvid_data: personalizationHeaders,
483
- })];
484
- case 1:
485
- response = _a.sent();
486
- return [2, response === null || response === void 0 ? void 0 : response.data];
487
- }
488
- });
489
- }); };
490
- var validateOtp = function (mobile, otp) { return tslib.__awaiter(void 0, void 0, void 0, function () {
491
- var response, data;
492
- return tslib.__generator(this, function (_a) {
493
- switch (_a.label) {
494
- case 0: return [4, createPostOrPutRequest('VALIDATE_OTP', ctPlatformConstants.RequestMethods.POST, {
495
- otp: otp,
496
- value: mobile,
497
- type: 'MOBILE',
498
- action: 'SIGNIN',
499
- countryCode: '+91',
500
- }, { 'ab-otp': 'b' })];
501
- case 1:
502
- response = _a.sent();
503
- data = response === null || response === void 0 ? void 0 : response.data;
504
- return [2, tslib.__assign(tslib.__assign({}, response), { signup: (data === null || data === void 0 ? void 0 : data.action) === ctPlatformTypes.ValidateOTPAction.SIGNUP, action: data === null || data === void 0 ? void 0 : data.action, status: response === null || response === void 0 ? void 0 : response.status })];
505
- }
506
- });
507
- }); };
508
- var handleFKSSO = function (fallbackUri, signupPageUri, currentPageUri) { return tslib.__awaiter(void 0, void 0, void 0, function () {
509
- var redirectionInfo;
510
- return tslib.__generator(this, function (_a) {
511
- switch (_a.label) {
512
- case 0:
513
- if (isIOSApp()) {
514
- return [2, Promise.reject()];
515
- }
516
- return [4, sendFKSSORedirectionInfo(fallbackUri, signupPageUri, currentPageUri)];
517
- case 1:
518
- redirectionInfo = _a.sent();
519
- if (isAndroidApp()) {
520
- return [2, handleFKSSOAndroid(redirectionInfo)];
521
- }
522
- else {
523
- return [2, handleFKSSOWeb(redirectionInfo)];
524
- }
525
- }
526
- });
527
- }); };
528
- var isValidMobileNumber = function (text) {
529
- return (text === null || text === void 0 ? void 0 : text.length) === ctPlatformConstants.MOBILE_CONSTANTS.LENGTH && /^\d{10}$/.test(text);
530
- };
531
- var updateNativeOnLogin = function () {
532
- if (isIOSApp()) {
533
- updateNativeIOSOnSignIn();
534
- }
535
- else if (isAndroidApp()) {
536
- updateNativeAndroidOnSignIn();
537
- }
538
- };
539
- var isFKSSOEnabled = function () {
540
- return isPwa() || (!isIOSApp() && isJSVersionUpdated(5));
541
- };
542
- var sendFKSSORedirectionInfo = function (fallbackUri, signupPageUri, currentPageUri) { return tslib.__awaiter(void 0, void 0, void 0, function () {
543
- var WEBSITE_BASE, response;
544
- return tslib.__generator(this, function (_a) {
545
- switch (_a.label) {
546
- case 0:
547
- WEBSITE_BASE = getApiDomain();
548
- return [4, createPostOrPutRequest('FK_REDIRECTION_INFO', ctPlatformConstants.RequestMethods.POST, {
549
- provider: 'flipkart',
550
- fallbackUri: urlJoin(WEBSITE_BASE, fallbackUri || getCurrentPathName()),
551
- signupPageUri: urlJoin(WEBSITE_BASE, signupPageUri || 'personal-details'),
552
- currentPageUri: urlJoin(WEBSITE_BASE, currentPageUri),
553
- })];
554
- case 1:
555
- response = _a.sent();
556
- return [2, response === null || response === void 0 ? void 0 : response.data];
557
- }
558
- });
559
- }); };
560
- var handleFKSSOWeb = function (redirectionInfo) {
561
- var _a;
562
- var params = (_a = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params) !== null && _a !== void 0 ? _a : {};
563
- var redirectUri = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.redirectUri;
564
- if (redirectUri) {
565
- redirectUri += '?';
566
- for (var key in params) {
567
- redirectUri += key + '=' + params[key] + '&';
568
- }
569
- return Promise.resolve(redirectUri);
570
- }
571
- return Promise.reject();
572
- };
573
- var handleFKSSOAndroid = function (redirectionInfo) {
574
- var _a, _b;
575
- var params = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params;
576
- if (isEmpty(params) ||
577
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onNavigationChange) !== 'function') {
578
- return Promise.reject();
579
- }
580
- else {
581
- var FK_REDIRECT_DL = urlJoin(getApiDomain(), 'dl/oauth2');
582
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.onNavigationChange(JSON.stringify({
583
- type: 'FkSSO',
584
- miscData: tslib.__assign(tslib.__assign({}, params), { redirectURI: FK_REDIRECT_DL }),
585
- }));
586
- return Promise.resolve();
587
- }
588
- };
589
- function getUserAuthValues(customCookie) {
590
- try {
591
- var _a = decodeURIComponent(getCookie('userid', customCookie) || '').split('|'), email = _a[0], profileName = _a[1], gender = _a[2], photo = _a[3], userId = _a[4];
592
- return {
593
- email: email,
594
- profileName: profileName,
595
- gender: gender,
596
- photo: photo,
597
- userId: userId,
598
- };
599
- }
600
- catch (error) {
601
- return {};
602
- }
603
- }
604
- var isUserSignedIn = function (customCookie) {
605
- var userObject = getUserAuthValues(customCookie) || {};
606
- var usermiscVal = decodeURIComponent(getCookie('usermisc', customCookie) || '').split('|');
607
- var signedIn = usermiscVal.includes('SIGNED_IN') &&
608
- userObject.userId &&
609
- userObject.userId.length > 0
610
- ? true
611
- : false;
612
- return signedIn;
613
- };
614
-
615
- var getUserInsights = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
616
- var response;
617
- return tslib.__generator(this, function (_a) {
618
- switch (_a.label) {
619
- case 0:
620
- _a.trys.push([0, 2, , 3]);
621
- return [4, createGetRequest('USER_INSIGHTS', {}, {
622
- pathParams: {
623
- userId: userId,
624
- },
625
- })];
626
- case 1:
627
- response = _a.sent();
628
- return [2, response === null || response === void 0 ? void 0 : response.data];
629
- case 2:
630
- _a.sent();
631
- return [2, Promise.resolve(null)];
632
- case 3: return [2];
633
- }
634
- });
635
- }); };
636
- var getUserInsightsData = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
637
- var _userId, stringifiedData, sessionData, userInsights;
638
- var _a, _b, _c, _d;
639
- return tslib.__generator(this, function (_f) {
640
- switch (_f.label) {
641
- case 0:
642
- _f.trys.push([0, 2, , 3]);
643
- _userId = userId !== null && userId !== void 0 ? userId : getUserAuthValues().userId;
644
- if (!_userId) {
645
- (_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.removeItem('martech_user_attributes');
646
- return [2, null];
647
- }
648
- stringifiedData = (_b = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _b === void 0 ? void 0 : _b.getItem('martech_user_attributes');
649
- sessionData = void 0;
650
- if (typeof stringifiedData === 'string') {
651
- sessionData = JSON.parse(stringifiedData);
652
- }
653
- if (_userId !== (sessionData === null || sessionData === void 0 ? void 0 : sessionData.accountId)) {
654
- (_c = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _c === void 0 ? void 0 : _c.removeItem('martech_user_attributes');
655
- }
656
- return [4, getUserInsights(_userId)];
657
- case 1:
658
- userInsights = _f.sent();
659
- if (isEmpty(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data)) {
660
- return [2, null];
661
- }
662
- (_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));
663
- return [2, userInsights === null || userInsights === void 0 ? void 0 : userInsights.data];
664
- case 2:
665
- _f.sent();
666
- return [2, null];
667
- case 3: return [2];
668
- }
669
- });
670
- }); };
671
-
672
- var stringifyPayload = function (payload) {
673
- var keys = Object.keys(payload);
674
- keys.forEach(function (key) {
675
- if (key === 'a_fare_price' ||
676
- key === 'a_ct_discount' ||
677
- key === 'supercoin_balance' ||
678
- key === 'supercoin_earned' ||
679
- key === 'supercoin_burnt' ||
680
- key === 'wallet_balance_used' ||
681
- key === 'convenience_fee')
682
- payload[key] = Number(payload[key]);
683
- else
684
- payload[key] = '' + payload[key];
685
- });
686
- return payload;
687
- };
688
- var ravenSDKTrigger = function (eventName, ravenPayload) {
689
- var _a;
690
- if (window && window['ravenWebManager']) {
691
- var _b = getRavenEventProps(), pageName = _b.pageName, utmSource = _b.utmSource;
692
- var commonPayload = {
693
- page_name: pageName,
694
- u_utm_source: utmSource,
695
- domain: window.location.host,
696
- platform: (_a = getDevicePlatform()) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
697
- login_status: isUserSignedIn() ? 'yes' : 'no',
698
- };
699
- var newRavenPayload = stringifyPayload(ravenPayload);
700
- var RavenWebManager = window['ravenWebManager'];
701
- RavenWebManager === null || RavenWebManager === void 0 ? void 0 : RavenWebManager.triggerRaven(eventName, tslib.__assign(tslib.__assign({}, commonPayload), newRavenPayload));
702
- }
703
- };
704
- var isAirHomePage = function () {
705
- if (window && typeof window !== 'undefined') {
706
- var pathname = getNestedValue(window, ['location', 'pathname']);
707
- if (pathname === '/' || pathname === '/flights') {
708
- return true;
709
- }
710
- }
711
- return false;
712
- };
713
- var getRavenEventProps = function () {
714
- var _a, _b;
715
- if (window && typeof window !== 'undefined') {
716
- var pathUrl = window.location.pathname;
717
- var redirectionPath = (_a = getQueryParam('service')) !== null && _a !== void 0 ? _a : '';
718
- var utmSource = (_b = getQueryParam('utm_source')) !== null && _b !== void 0 ? _b : 'organic';
719
- var loginForm = isAirHomePage() ? 'skippable_login' : 'account_login';
720
- var vertical = 'air';
721
- var pageName = pathUrl.includes('flights/itinerary') ||
722
- redirectionPath.includes('flights/itinerary')
723
- ? 'a_itinerary'
724
- : 'a_home';
725
- if (redirectionPath.includes('my-account')) {
726
- vertical = 'uar';
727
- pageName = 'account';
728
- }
729
- if (redirectionPath.includes('hotels')) {
730
- vertical = 'hotel';
731
- pageName = redirectionPath.includes('hotels/itinerary')
732
- ? 'h_itinerary'
733
- : 'h_home';
734
- }
735
- if (redirectionPath.includes('bus')) {
736
- vertical = 'bus';
737
- pageName = redirectionPath.includes('bus/itinerary')
738
- ? 'b_itinerary'
739
- : 'b_home';
740
- }
741
- return { loginForm: loginForm, vertical: vertical, pageName: pageName, utmSource: utmSource };
742
- }
743
- return {};
744
- };
745
- var sendEventWithUserInsights = function (eventName, ravenPayload, userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
746
- var userInsights, updatedPayload, loyaltyData, martechAttributes;
747
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
748
- return tslib.__generator(this, function (_s) {
749
- switch (_s.label) {
750
- case 0: return [4, getUserInsightsData(userId)];
751
- case 1:
752
- userInsights = _s.sent();
753
- updatedPayload = tslib.__assign(tslib.__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' });
754
- if (!isEmpty(userInsights)) {
755
- loyaltyData = ((_a = userInsights === null || userInsights === void 0 ? void 0 : userInsights.loyaltyStatus) !== null && _a !== void 0 ? _a : []).reduce(function (prev, curr) {
756
- return tslib.__assign(tslib.__assign({}, prev), curr);
757
- }, {});
758
- martechAttributes = {
759
- 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(),
760
- ct_postmerger_booking: ((_e = (_d = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _d === void 0 ? void 0 : _d.postmergerBooking) !== null && _e !== void 0 ? _e : 'na').toString(),
761
- ct_last_1year_booking: ((_g = (_f = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _f === void 0 ? void 0 : _f.lastOneYearBooking) !== null && _g !== void 0 ? _g : 'na').toString(),
762
- ct_first_booking_dt: secondsToDateString((_h = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _h === void 0 ? void 0 : _h.firstbookingDate) || 'na',
763
- ct_last_booking_dt: secondsToDateString((_j = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _j === void 0 ? void 0 : _j.lastbookingDate) || 'na',
764
- ct_2nd_last_booking_dt: secondsToDateString((_k = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _k === void 0 ? void 0 : _k.secondLastbookingDate) || 'na',
765
- fk_loyalty_status: ((_l = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _l === void 0 ? void 0 : _l.program) || 'na',
766
- myntra_loyalty_status: ((_m = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _m === void 0 ? void 0 : _m.program) || 'na',
767
- fk_loyalty_end_dt: secondsToDateString((_o = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _o === void 0 ? void 0 : _o.loyaltyEndDate) || '',
768
- fk_loyalty_start_dt: secondsToDateString((_p = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _p === void 0 ? void 0 : _p.loyaltyStartDate) || 'na',
769
- myntra_loyalty_start_dt: secondsToDateString((_q = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _q === void 0 ? void 0 : _q.loyaltyStartDate) ||
770
- 'na',
771
- myntra_loyalty_end_dt: secondsToDateString((_r = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _r === void 0 ? void 0 : _r.loyaltyEndDate) ||
772
- 'na',
773
- };
774
- updatedPayload = tslib.__assign(tslib.__assign({}, updatedPayload), martechAttributes);
775
- setMartechUserProperties(martechAttributes);
776
- }
777
- ravenSDKTrigger(eventName, updatedPayload);
778
- return [2];
779
- }
780
- });
781
- }); };
782
- var setMartechUserProperties = function (userProperties) {
783
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
784
- if (isEmpty(userProperties) ||
785
- ((_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem('martech_user_props_sent'))) {
786
- return;
787
- }
788
- 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)) {
789
- (_d = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _d === void 0 ? void 0 : _d.postMessage({
790
- type: 'GA',
791
- params: userProperties,
792
- });
793
- (_e = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _e === void 0 ? void 0 : _e.postMessage({
794
- type: 'Clevertap',
795
- params: userProperties,
796
- });
797
- (_f = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _f === void 0 ? void 0 : _f.setItem('martech_user_props_sent', 'true');
798
- }
799
- else if (isAndroidApp() && ((_g = window === null || window === void 0 ? void 0 : window.MobileApp) === null || _g === void 0 ? void 0 : _g.sendAttributes)) {
800
- window.MobileApp.sendAttributes('GA', JSON.stringify(userProperties));
801
- window.MobileApp.sendAttributes('Clevertap', JSON.stringify(userProperties));
802
- (_h = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _h === void 0 ? void 0 : _h.setItem('martech_user_props_sent', 'true');
803
- }
804
- else if (isPwa() && window.clevertap) {
805
- window.clevertap.profile.push({
806
- Site: userProperties,
807
- });
808
- (_j = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _j === void 0 ? void 0 : _j.setItem('martech_user_props_sent', 'true');
809
- }
810
- };
811
- var batchRavenEvent = function (eventName, ravenPayload) {
812
- if (typeof window !== 'undefined' &&
813
- typeof window.requestIdleCallback === 'function') {
814
- requestIdleCallback(function () {
815
- ravenSDKTrigger(eventName, ravenPayload);
816
- });
817
- }
818
- else {
819
- setTimeout(function () {
820
- ravenSDKTrigger(eventName, ravenPayload);
821
- }, 0);
822
- }
823
- };
824
-
825
- var getHotelCrossSellRecos = function (vertical, fallbackPageLandingURL, cutoff) {
826
- if (cutoff === void 0) { cutoff = 450; }
827
- return tslib.__awaiter(void 0, void 0, void 0, function () {
828
- var userId, fallbackData, timeoutPromise, fetchRecommendationsPromise, result;
829
- var _a, _b;
830
- return tslib.__generator(this, function (_c) {
831
- switch (_c.label) {
832
- case 0:
833
- userId = (_b = (_a = getUserAuthValues()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : '';
834
- fallbackData = {
835
- couponCode: '',
836
- offerCallOut: 'FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU',
837
- couponCallOut: 'Offer applied on hotels',
838
- pageLandingUrl: fallbackPageLandingURL,
839
- };
840
- _c.label = 1;
841
- case 1:
842
- _c.trys.push([1, 3, , 4]);
843
- timeoutPromise = new Promise(function (resolve) {
844
- setTimeout(function () {
845
- resolve(fallbackData);
846
- }, cutoff);
847
- });
848
- fetchRecommendationsPromise = createGetRequest('HOTEL_RECOMMENDATIONS', {}, {
849
- queryParams: {
850
- userId: userId,
851
- vertical: vertical,
852
- },
853
- }).then(function (res) { return res.data; });
854
- return [4, Promise.race([
855
- fetchRecommendationsPromise,
856
- timeoutPromise,
857
- ])];
858
- case 2:
859
- result = _c.sent();
860
- return [2, result];
861
- case 3:
862
- _c.sent();
863
- return [2, fallbackData];
864
- case 4: return [2];
865
- }
866
- });
867
- });
868
- };
869
-
870
- exports.MULTI_SPACE = MULTI_SPACE;
871
- exports.autoReadOtp = autoReadOtp;
872
- exports.batchRavenEvent = batchRavenEvent;
873
- exports.createAPIRequest = createAPIRequest;
874
- exports.createGetRequest = createGetRequest;
875
- exports.createPostOrPutRequest = createPostOrPutRequest;
876
- exports.formatCurrency = formatCurrency;
877
- exports.formatFullDateString = formatFullDateString;
878
- exports.getApiDomain = getApiDomain;
879
- exports.getAppAgent = getAppAgent;
880
- exports.getAutoDetectedMobile = getAutoDetectedMobile;
881
- exports.getCookie = getCookie;
882
- exports.getCurrentPathName = getCurrentPathName;
883
- exports.getCurrentUrl = getCurrentUrl;
884
- exports.getDevicePlatform = getDevicePlatform;
885
- exports.getDimensionFromImageUrl = getDimensionFromImageUrl;
886
- exports.getHeightFromImgUrl = getHeightFromImgUrl;
887
- exports.getHotelCrossSellRecos = getHotelCrossSellRecos;
888
- exports.getJSVersion = getJSVersion;
889
- exports.getNestedValue = getNestedValue;
890
- exports.getQueryParam = getQueryParam;
891
- exports.getRavenEventProps = getRavenEventProps;
892
- exports.getUserAuthValues = getUserAuthValues;
893
- exports.getWidthFromImgUrl = getWidthFromImgUrl;
894
- exports.handleFKSSO = handleFKSSO;
895
- exports.isAirHomePage = isAirHomePage;
896
- exports.isAndroidApp = isAndroidApp;
897
- exports.isEmpty = isEmpty;
898
- exports.isFKSSOEnabled = isFKSSOEnabled;
899
- exports.isHTMLInputElement = isHTMLInputElement;
900
- exports.isIOSApp = isIOSApp;
901
- exports.isJSVersionUpdated = isJSVersionUpdated;
902
- exports.isNumeric = isNumeric;
903
- exports.isPwa = isPwa;
904
- exports.isServer = isServer;
905
- exports.isUserSignedIn = isUserSignedIn;
906
- exports.isValidMobileNumber = isValidMobileNumber;
907
- exports.path = path;
908
- exports.ravenSDKTrigger = ravenSDKTrigger;
909
- exports.replacePlaceHolder = replacePlaceHolder;
910
- exports.secondsToDateString = secondsToDateString;
911
- exports.sendEventWithUserInsights = sendEventWithUserInsights;
912
- exports.sendLoginOtp = sendLoginOtp;
913
- exports.setMartechUserProperties = setMartechUserProperties;
914
- exports.showMobileNumberHint = showMobileNumberHint;
915
- exports.stringifyPayload = stringifyPayload;
916
- exports.triggerOTPListener = triggerOTPListener;
917
- exports.updateNativeAndroidOnSignIn = updateNativeAndroidOnSignIn;
918
- exports.updateNativeIOSOnSignIn = updateNativeIOSOnSignIn;
919
- exports.updateNativeOnLogin = updateNativeOnLogin;
920
- exports.urlJoin = urlJoin;
921
- exports.validateOtp = validateOtp;
1
+ "use strict";var t=require("tslib"),e=require("@cleartrip/ct-platform-constants"),n=require("@cleartrip/ct-platform-types"),o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t.map((function(t){return t.trim().replace(/^[/]+/,"")})).join("/");return n=n.replace(/\/\?/g,"?")},r=function(){var t="undefined"!=typeof window?window.location.hostname:"";switch(console.log("API_BASE domain",t),t){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"}},i=function(t,e){return e.reduce((function(t,e){return t&&t[e]?t[e]:null}),t)},a=function(t){if(t instanceof Date)return!1;if(null==t)return!0;var e,n=function(t){return"[object Number]"===Object.prototype.toString.call(t)};if(n(t))return n(e=t)&&"NaN"===e.toString();if(t.length>0)return!1;if(0===t.length)return!0;if("object"!=typeof t)return!0;for(var o=Object.keys(t),r=0,i=o[r];r<o.length;r+=1)if(Object.prototype.hasOwnProperty.call(t,i))return!1;return!0},s="undefined"!=typeof window?window.location.href:"",u=function(t){return v()?"":new URLSearchParams(window.location.search).get(t)},l=function(){return"undefined"!=typeof window?(window.location.pathname+window.location.search).slice(1):""},d=function(t){if(t){var e=t.match(/h_(\d+)[,\/]/);return e&&e[1]?parseInt(e[1],10):void 0}},c=function(t){if(t){var e=t.match(/w_(\d+)[,\/]/);return e&&e[1]?parseInt(e[1],10):void 0}},v=function(){return"undefined"==typeof window||!window};function p(t,e){var n=e||i(document,["cookie"]);if(n){for(var o=t+"=",r=n.split(";"),a=0;a<r.length;a++){for(var s=r[a];" "==s.charAt(0);)s=s.substring(1,s.length);if(0==s.indexOf(o))return s.substring(o.length,s.length)}return""}return""}var _=function(t){try{if(!t||Number.isNaN(Number(t)))return"";var e=new Date(1e3*t),n=e.getFullYear(),o=String(e.getDate()).padStart(2,"0"),r=String(e.getMonth()+1).padStart(2,"0");return"".concat(n,"-").concat(r,"-").concat(o)}catch(t){return""}},g=function(){var t,n=null===(t=i(window,["navigator","userAgent"]))||void 0===t?void 0:t.toLowerCase(),o=/safari/.test(n),r=/iphone|ipod|ipad/.test(n);return i(window,["androidData","app-agent"])&&i(window,["androidData","js-version"])||"function"==typeof i(window,["MobileApp","getAppSpecificData"])?e.Platform.ANDROID:i(window,["iosData","app-agent"])&&i(window,["iosData","js-version"])||r&&!o?e.Platform.IOS:e.Platform.PWA},f=function(){var t,n,o=g();return o===e.Platform.IOS?null!==(t=i(window,["iosData","app-agent"]))&&void 0!==t?t:e.AppAgent.IOS:o===e.Platform.ANDROID?null!==(n=i(window,["androidData","app-agent"]))&&void 0!==n?n:e.AppAgent.ANDROID:e.AppAgent.PWA},w=function(){var t="";return S()?t=i(window,["iosData","js-version"]):h()&&(t=i(window,["androidData","js-version"])),t&&(t=t.toString().split(".")[0]),t},m=function(){return g()!==e.Platform.ANDROID&&g()!==e.Platform.IOS},h=function(){return g()===e.Platform.ANDROID},y=function(t){return parseInt(w())>=t},S=function(){return g()===e.Platform.IOS},b=r(),I=function(n,i,a,s,u,l){return void 0===i&&(i=e.RequestMethods.GET),void 0===s&&(s={}),void 0===u&&(u={}),void 0===l&&(l=!1),t.__awaiter(void 0,void 0,void 0,(function(){var d,c,v,p,_,g,w,m;return t.__generator(this,(function(h){switch(h.label){case 0:return d=function(t,n){var r=e.API_ROUTES[t];if(r&&r.trim().length){if(r=o(b,r),null==n?void 0:n.pathParams)for(var i=0,a=Object.entries(n.pathParams);i<a.length;i++){var s=a[i],u=s[0],l=s[1];r=r.replace(":".concat(u),l)}return(null==n?void 0:n.queryParams)&&(r+="?".concat(new URLSearchParams(n.queryParams).toString())),r}}(n,u),d&&d.trim().length?(c=r(),v={method:i,headers:t.__assign({Caller:b,Origin:b,Referer:b,Authority:c,x_ct_sourcetype:"MOBILE","app-agent":f(),"Content-Type":"application/json"},s)},a&&(v.body=JSON.stringify(a)),[4,fetch(d,v)]):[2,Promise.reject("URL parameter missing")];case 1:return _=h.sent(),g={name:"API_FAILURE",status:_.status,message:"UNKNOWN_ERROR",statusText:_.statusText},(null==_?void 0:_.ok)?[3,3]:l?[2,Promise.reject(g)]:[4,_.json()];case 2:throw w=h.sent().message,g.message=w,g;case 3:return(null==(m=_.headers.get("content-type"))?void 0:m.includes("application/json"))?[4,_.json()]:[3,5];case 4:return p=h.sent(),[3,9];case 5:return(null==m?void 0:m.includes("text"))?[4,_.text()]:[3,7];case 6:return p=h.sent(),[3,9];case 7:return 204===_.status?[3,9]:[4,_.blob()];case 8:p=h.sent(),h.label=9;case 9:return[2,{data:p,status:_.status}]}}))}))},O=function(n,o,r,i){return void 0===o&&(o={}),void 0===r&&(r={}),void 0===i&&(i=!1),t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(a){return[2,I(n,e.RequestMethods.GET,null,t.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},o),r,i)]}))}))},N=function(n,o,r,i,a,s){return void 0===o&&(o=e.RequestMethods.POST),void 0===r&&(r={}),void 0===i&&(i={}),void 0===a&&(a={}),void 0===s&&(s=!1),t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(e){return[2,I(n,o,r,t.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},i),a,s)]}))}))},P=function(t){var n="",o=t.match(e.MOBILE_CONSTANTS.REGEX);return o&&(n=o[0].replace(/\D/g,"")),n},A=function(){var t,e,n;null===(n=null===(e=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===e?void 0:e.PWA_IS_SIGNIN)||void 0===n||n.postMessage({isSignIn:!0})},x=function(){var t;null===(t=window.MobileApp)||void 0===t||t.onPWALoginStatus(JSON.stringify({isSignIn:!0}))},D=function(){return t.__awaiter(void 0,void 0,void 0,(function(){var e,n;return t.__generator(this,(function(t){return(null===(n=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===n?void 0:n.get)&&"OTPCredential"in window?(e=new AbortController,setTimeout((function(){e.abort()}),6e4),[2,navigator.credentials.get({otp:{transport:["sms"]},signal:e.signal}).then((function(t){return null==t?void 0:t.code}))]):[2,Promise.reject("NOT_SUPPORTED")]}))}))},E=function(){return t.__awaiter(void 0,void 0,void 0,(function(){var e,n;return t.__generator(this,(function(t){return n=new Promise((function(t){e=t})),window.sendOtpValue=function(t){e(t)},[2,n]}))}))},k=function(n,i,a){return t.__awaiter(void 0,void 0,void 0,(function(){var s,u;return t.__generator(this,(function(t){switch(t.label){case 0:return s=r(),[4,N("FK_REDIRECTION_INFO",e.RequestMethods.POST,{provider:"flipkart",fallbackUri:o(s,n||l()),signupPageUri:o(s,i||"personal-details"),currentPageUri:o(s,a)})];case 1:return[2,null==(u=t.sent())?void 0:u.data]}}))}))},T=function(t){var e,n=null!==(e=null==t?void 0:t.params)&&void 0!==e?e:{},o=null==t?void 0:t.redirectUri;if(o){for(var r in o+="?",n)o+=r+"="+n[r]+"&";return Promise.resolve(o)}return Promise.reject()},R=function(e){var n,i,s=null==e?void 0:e.params;if(a(s)||"function"!=typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.onNavigationChange))return Promise.reject();var u=o(r(),"dl/oauth2");return null===(i=window.MobileApp)||void 0===i||i.onNavigationChange(JSON.stringify({type:"FkSSO",miscData:t.__assign(t.__assign({},s),{redirectURI:u})})),Promise.resolve()};function M(t){try{var e=decodeURIComponent(p("userid",t)||"").split("|");return{email:e[0],profileName:e[1],gender:e[2],photo:e[3],userId:e[4]}}catch(t){return{}}}var C=function(t){var e=M(t)||{};return!!(decodeURIComponent(p("usermisc",t)||"").split("|").includes("SIGNED_IN")&&e.userId&&e.userId.length>0)},U=function(e){return t.__awaiter(void 0,void 0,void 0,(function(){var n;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,O("USER_INSIGHTS",{},{pathParams:{userId:e}})];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]}}))}))},L=function(e){return t.__awaiter(void 0,void 0,void 0,(function(){var n,o,r,i,s,u,l,d;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),(n=null!=e?e:M().userId)?(o=null===(u=null===window||void 0===window?void 0:window.sessionStorage)||void 0===u?void 0:u.getItem("martech_user_attributes"),r=void 0,"string"==typeof o&&(r=JSON.parse(o)),n!==(null==r?void 0:r.accountId)&&(null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.removeItem("martech_user_attributes")),[4,U(n)]):(null===(s=null===window||void 0===window?void 0:window.sessionStorage)||void 0===s||s.removeItem("martech_user_attributes"),[2,null]);case 1:return i=t.sent(),a(null==i?void 0:i.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==i?void 0:i.data)),[2,null==i?void 0:i.data]);case 2:return t.sent(),[2,null];case 3:return[2]}}))}))},j=function(t){return Object.keys(t).forEach((function(e){t[e]="a_fare_price"===e||"a_ct_discount"===e||"supercoin_balance"===e||"supercoin_earned"===e||"supercoin_burnt"===e||"wallet_balance_used"===e||"convenience_fee"===e?Number(t[e]):""+t[e]})),t},q=function(e,n){var o;if(window&&window.ravenWebManager){var r=B(),i={page_name:r.pageName,u_utm_source:r.utmSource,domain:window.location.host,platform:null===(o=g())||void 0===o?void 0:o.toLowerCase(),login_status:C()?"yes":"no"},a=j(n),s=window.ravenWebManager;null==s||s.triggerRaven(e,t.__assign(t.__assign({},i),a))}},F=function(){if(window&&"undefined"!=typeof window){var t=i(window,["location","pathname"]);if("/"===t||"/flights"===t)return!0}return!1},B=function(){var t,e;if(window&&"undefined"!=typeof window){var n=window.location.pathname,o=null!==(t=u("service"))&&void 0!==t?t:"",r=null!==(e=u("utm_source"))&&void 0!==e?e:"organic",i=F()?"skippable_login":"account_login",a="air",s=n.includes("flights/itinerary")||o.includes("flights/itinerary")?"a_itinerary":"a_home";return o.includes("my-account")&&(a="uar",s="account"),o.includes("hotels")&&(a="hotel",s=o.includes("hotels/itinerary")?"h_itinerary":"h_home"),o.includes("bus")&&(a="bus",s=o.includes("bus/itinerary")?"b_itinerary":"b_home"),{loginForm:i,vertical:a,pageName:s,utmSource:r}}return{}},G=function(t){var e,n,o,r,i,s,u,l,d;a(t)||(null===(e=null===window||void 0===window?void 0:window.sessionStorage)||void 0===e?void 0:e.getItem("martech_user_props_sent"))||(S()&&(null===(o=null===(n=null===window||void 0===window?void 0:window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===o?void 0:o.SEND_ATTRIBUTES)?(null===(r=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===r||r.postMessage({type:"GA",params:t}),null===(i=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===i||i.postMessage({type:"Clevertap",params:t}),null===(s=null===window||void 0===window?void 0:window.sessionStorage)||void 0===s||s.setItem("martech_user_props_sent","true")):h()&&(null===(u=null===window||void 0===window?void 0:window.MobileApp)||void 0===u?void 0:u.sendAttributes)?(window.MobileApp.sendAttributes("GA",JSON.stringify(t)),window.MobileApp.sendAttributes("Clevertap",JSON.stringify(t)),null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.setItem("martech_user_props_sent","true")):m()&&window.clevertap&&(window.clevertap.profile.push({Site:t}),null===(d=null===window||void 0===window?void 0:window.sessionStorage)||void 0===d||d.setItem("martech_user_props_sent","true")))};exports.MULTI_SPACE=/\s\s+/g,exports.autoReadOtp=function(){return t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,h()?E():D()]}))}))},exports.batchRavenEvent=function(t,e){"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?requestIdleCallback((function(){q(t,e)})):setTimeout((function(){q(t,e)}),0)},exports.createAPIRequest=I,exports.createGetRequest=O,exports.createPostOrPutRequest=N,exports.formatCurrency=function(t,e){void 0===e&&(e=!0);try{var n={currency:"INR",minimumFractionDigits:0};return e&&(n.style="currency"),"string"!=typeof t&&(t=null==t?void 0:t.toString()),t=t.replace(/,/g,""),parseInt(t,10).toLocaleString("en-IN",n)}catch(t){return""}},exports.formatFullDateString=function(t,e,n){void 0===e&&(e="dd-mm-yyyy"),void 0===n&&(n="");try{var o=new Date(t),r=o.getFullYear(),i=String(o.getDate()).padStart(2,"0"),a=String(o.getMonth()+1).padStart(2,"0");return"yyyy-mm-dd"===e?"".concat(r,"-").concat(a,"-").concat(i):"".concat(i,"-").concat(a,"-").concat(r)}catch(t){return n}},exports.getApiDomain=r,exports.getAppAgent=f,exports.getAutoDetectedMobile=P,exports.getCookie=p,exports.getCurrentPathName=l,exports.getCurrentUrl=s,exports.getDevicePlatform=g,exports.getDimensionFromImageUrl=function(t){void 0===t&&(t="");var e=d(t)||0,n=c(t)||0;return{height:"".concat(e,"px"),width:"".concat(n,"px"),heightInNumber:e,widthInNumber:n}},exports.getHeightFromImgUrl=d,exports.getHotelCrossSellRecos=function(e,n,o){return void 0===o&&(o=450),t.__awaiter(void 0,void 0,void 0,(function(){var r,i,a,s,u,l;return t.__generator(this,(function(t){switch(t.label){case 0:r=null!==(l=null===(u=M())||void 0===u?void 0:u.userId)&&void 0!==l?l:"",i={couponCode:"",offerCallOut:"FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU",couponCallOut:"Offer applied on hotels",pageLandingUrl:n},t.label=1;case 1:return t.trys.push([1,3,,4]),a=new Promise((function(t){setTimeout((function(){t(i)}),o)})),s=O("HOTEL_RECOMMENDATIONS",{},{queryParams:{userId:r,vertical:e}}).then((function(t){return t.data})),[4,Promise.race([s,a])];case 2:return[2,t.sent()];case 3:return t.sent(),[2,i];case 4:return[2]}}))}))},exports.getJSVersion=w,exports.getNestedValue=i,exports.getQueryParam=u,exports.getRavenEventProps=B,exports.getUserAuthValues=M,exports.getWidthFromImgUrl=c,exports.handleFKSSO=function(e,n,o){return t.__awaiter(void 0,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return S()?[2,Promise.reject()]:[4,k(e,n,o)];case 1:return r=t.sent(),h()?[2,R(r)]:[2,T(r)]}}))}))},exports.isAirHomePage=F,exports.isAndroidApp=h,exports.isEmpty=a,exports.isFKSSOEnabled=function(){return m()||!S()&&y(5)},exports.isHTMLInputElement=function(t){return"object"==typeof t&&null!==t&&"value"in t&&t instanceof HTMLInputElement},exports.isIOSApp=S,exports.isJSVersionUpdated=y,exports.isNumeric=function(t){return/^[0-9]*$/.test(t)},exports.isPwa=m,exports.isServer=v,exports.isUserSignedIn=C,exports.isValidMobileNumber=function(t){return(null==t?void 0:t.length)===e.MOBILE_CONSTANTS.LENGTH&&/^\d{10}$/.test(t)},exports.path=function(t,e){return t.reduce((function(t,e){return t&&t[e]?t[e]:null}),e)},exports.ravenSDKTrigger=q,exports.secondsToDateString=_,exports.sendEventWithUserInsights=function(e,n,o){return t.__awaiter(void 0,void 0,void 0,(function(){var r,i,s,u,l,d,c,v,p,g,f,w,m,h,y,S,b,I,O,N;return t.__generator(this,(function(P){switch(P.label){case 0:return[4,L(o)];case 1:return r=P.sent(),i=t.__assign(t.__assign({},n),{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"}),a(r)||(s=(null!==(l=null==r?void 0:r.loyaltyStatus)&&void 0!==l?l:[]).reduce((function(e,n){return t.__assign(t.__assign({},e),n)}),{}),u={ct_lifetime_booking:(null!==(c=null===(d=null==r?void 0:r.bookingStatus)||void 0===d?void 0:d.lifetimeBooking)&&void 0!==c?c:"na").toString(),ct_postmerger_booking:(null!==(p=null===(v=null==r?void 0:r.bookingStatus)||void 0===v?void 0:v.postmergerBooking)&&void 0!==p?p:"na").toString(),ct_last_1year_booking:(null!==(f=null===(g=null==r?void 0:r.bookingStatus)||void 0===g?void 0:g.lastOneYearBooking)&&void 0!==f?f:"na").toString(),ct_first_booking_dt:_(null===(w=null==r?void 0:r.bookingStatus)||void 0===w?void 0:w.firstbookingDate)||"na",ct_last_booking_dt:_(null===(m=null==r?void 0:r.bookingStatus)||void 0===m?void 0:m.lastbookingDate)||"na",ct_2nd_last_booking_dt:_(null===(h=null==r?void 0:r.bookingStatus)||void 0===h?void 0:h.secondLastbookingDate)||"na",fk_loyalty_status:(null===(y=null==s?void 0:s.fk)||void 0===y?void 0:y.program)||"na",myntra_loyalty_status:(null===(S=null==s?void 0:s.myntra)||void 0===S?void 0:S.program)||"na",fk_loyalty_end_dt:_(null===(b=null==s?void 0:s.fk)||void 0===b?void 0:b.loyaltyEndDate)||"",fk_loyalty_start_dt:_(null===(I=null==s?void 0:s.fk)||void 0===I?void 0:I.loyaltyStartDate)||"na",myntra_loyalty_start_dt:_(null===(O=null==s?void 0:s.myntra)||void 0===O?void 0:O.loyaltyStartDate)||"na",myntra_loyalty_end_dt:_(null===(N=null==s?void 0:s.myntra)||void 0===N?void 0:N.loyaltyEndDate)||"na"},i=t.__assign(t.__assign({},i),u),G(u)),q(e,i),[2]}}))}))},exports.sendLoginOtp=function(n,o){return t.__awaiter(void 0,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,N("SEND_OTP",e.RequestMethods.POST,{value:n,type:"MOBILE",action:"SIGNIN",countryCode:e.MOBILE_CONSTANTS.COUNTRY_CODE},{"ab-otp":"b",dvid_data:o})];case 1:return[2,null==(r=t.sent())?void 0:r.data]}}))}))},exports.setMartechUserProperties=G,exports.showMobileNumberHint=function(){var t;if("function"==typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.onRequestMobileNumber)){var e;window.MobileApp.onRequestMobileNumber();var n=new Promise((function(t){e=t}));return window.sendSelectedMobileNumber=function(t){return e(P(t))},n}return Promise.resolve("")},exports.stringifyPayload=j,exports.triggerOTPListener=function(){var t;h()&&(null===(t=window.MobileApp)||void 0===t||t.onPageStart("OTP_SCREEN"))},exports.updateNativeAndroidOnSignIn=x,exports.updateNativeIOSOnSignIn=A,exports.updateNativeOnLogin=function(){S()?A():h()&&x()},exports.urlJoin=o,exports.validateOtp=function(o,r){return t.__awaiter(void 0,void 0,void 0,(function(){var i,a;return t.__generator(this,(function(s){switch(s.label){case 0:return[4,N("VALIDATE_OTP",e.RequestMethods.POST,{otp:r,value:o,type:"MOBILE",action:"SIGNIN",countryCode:"+91"},{"ab-otp":"b"})];case 1:return i=s.sent(),a=null==i?void 0:i.data,[2,t.__assign(t.__assign({},i),{signup:(null==a?void 0:a.action)===n.ValidateOTPAction.SIGNUP,action:null==a?void 0:a.action,status:null==i?void 0:i.status})]}}))}))};
922
2
  //# sourceMappingURL=ct-platform-utils.cjs.js.map