@cleartrip/ct-platform-utils 3.11.1-beta.5 → 3.11.2

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,980 +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
- var shouldShowPushPrimer = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
471
- var platform, getValue_1, value_1, interval_1;
472
- var _a, _b, _c;
473
- return tslib.__generator(this, function (_d) {
474
- switch (_d.label) {
475
- case 0:
476
- platform = getDevicePlatform();
477
- if (!(platform === ctPlatformConstants.PLATFORM_CONSTANTS.IOS &&
478
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.IS_PN_PERMISSION_ENABLED) === 'function')) return [3, 2];
479
- getValue_1 = function () {
480
- var _a;
481
- return (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.IS_PN_PERMISSION_ENABLED();
482
- };
483
- return [4, getValue_1()];
484
- case 1:
485
- value_1 = _d.sent();
486
- interval_1 = setInterval(function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
487
- return tslib.__generator(this, function (_a) {
488
- switch (_a.label) {
489
- case 0: return [4, getValue_1()];
490
- case 1:
491
- value_1 = _a.sent();
492
- if (value_1 !== null) {
493
- clearInterval(interval_1);
494
- }
495
- return [2];
496
- }
497
- });
498
- }); }, 1000);
499
- return [2, value_1];
500
- case 2:
501
- if (platform === ctPlatformConstants.PLATFORM_CONSTANTS.ANDROID &&
502
- typeof ((_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.isPNPermissionEnabled) === 'function') {
503
- return [2, (_c = window.MobileApp) === null || _c === void 0 ? void 0 : _c.isPNPermissionEnabled()];
504
- }
505
- _d.label = 3;
506
- case 3: return [2, false];
507
- }
508
- });
509
- }); };
510
- var handlePushPrimerCTA = function (type) {
511
- var _a, _b, _c, _d;
512
- if (isAndroidApp() &&
513
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.handlePNPermission) === 'function') {
514
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.handlePNPermission(JSON.stringify({
515
- type: type,
516
- }));
517
- }
518
- else if (isIOSApp() &&
519
- typeof ((_c = window.MobileApp) === null || _c === void 0 ? void 0 : _c.HANDLE_PN_PERMISSION) === 'function') {
520
- (_d = window.MobileApp) === null || _d === void 0 ? void 0 : _d.HANDLE_PN_PERMISSION(JSON.stringify({
521
- type: type,
522
- }));
523
- }
524
- return '';
525
- };
526
-
527
- var sendLoginOtp = function (mobile, personalizationHeaders) { return tslib.__awaiter(void 0, void 0, void 0, function () {
528
- var response;
529
- return tslib.__generator(this, function (_a) {
530
- switch (_a.label) {
531
- case 0: return [4, createPostOrPutRequest('SEND_OTP', ctPlatformConstants.RequestMethods.POST, {
532
- value: mobile,
533
- type: 'MOBILE',
534
- action: 'SIGNIN',
535
- countryCode: ctPlatformConstants.MOBILE_CONSTANTS.COUNTRY_CODE,
536
- }, {
537
- 'ab-otp': 'b',
538
- dvid_data: personalizationHeaders,
539
- })];
540
- case 1:
541
- response = _a.sent();
542
- return [2, response === null || response === void 0 ? void 0 : response.data];
543
- }
544
- });
545
- }); };
546
- var validateOtp = function (mobile, otp) { return tslib.__awaiter(void 0, void 0, void 0, function () {
547
- var response, data;
548
- return tslib.__generator(this, function (_a) {
549
- switch (_a.label) {
550
- case 0: return [4, createPostOrPutRequest('VALIDATE_OTP', ctPlatformConstants.RequestMethods.POST, {
551
- otp: otp,
552
- value: mobile,
553
- type: 'MOBILE',
554
- action: 'SIGNIN',
555
- countryCode: '+91',
556
- }, { 'ab-otp': 'b' })];
557
- case 1:
558
- response = _a.sent();
559
- data = response === null || response === void 0 ? void 0 : response.data;
560
- 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 })];
561
- }
562
- });
563
- }); };
564
- var handleFKSSO = function (fallbackUri, signupPageUri, currentPageUri) { return tslib.__awaiter(void 0, void 0, void 0, function () {
565
- var redirectionInfo;
566
- return tslib.__generator(this, function (_a) {
567
- switch (_a.label) {
568
- case 0:
569
- if (isIOSApp()) {
570
- return [2, Promise.reject()];
571
- }
572
- return [4, sendFKSSORedirectionInfo(fallbackUri, signupPageUri, currentPageUri)];
573
- case 1:
574
- redirectionInfo = _a.sent();
575
- if (isAndroidApp()) {
576
- return [2, handleFKSSOAndroid(redirectionInfo)];
577
- }
578
- else {
579
- return [2, handleFKSSOWeb(redirectionInfo)];
580
- }
581
- }
582
- });
583
- }); };
584
- var isValidMobileNumber = function (text) {
585
- return (text === null || text === void 0 ? void 0 : text.length) === ctPlatformConstants.MOBILE_CONSTANTS.LENGTH && /^\d{10}$/.test(text);
586
- };
587
- var updateNativeOnLogin = function () {
588
- if (isIOSApp()) {
589
- updateNativeIOSOnSignIn();
590
- }
591
- else if (isAndroidApp()) {
592
- updateNativeAndroidOnSignIn();
593
- }
594
- };
595
- var isFKSSOEnabled = function () {
596
- return isPwa() || (!isIOSApp() && isJSVersionUpdated(5));
597
- };
598
- var sendFKSSORedirectionInfo = function (fallbackUri, signupPageUri, currentPageUri) { return tslib.__awaiter(void 0, void 0, void 0, function () {
599
- var WEBSITE_BASE, response;
600
- return tslib.__generator(this, function (_a) {
601
- switch (_a.label) {
602
- case 0:
603
- WEBSITE_BASE = getApiDomain();
604
- return [4, createPostOrPutRequest('FK_REDIRECTION_INFO', ctPlatformConstants.RequestMethods.POST, {
605
- provider: 'flipkart',
606
- fallbackUri: urlJoin(WEBSITE_BASE, fallbackUri || getCurrentPathName()),
607
- signupPageUri: urlJoin(WEBSITE_BASE, signupPageUri || 'personal-details'),
608
- currentPageUri: urlJoin(WEBSITE_BASE, currentPageUri),
609
- })];
610
- case 1:
611
- response = _a.sent();
612
- return [2, response === null || response === void 0 ? void 0 : response.data];
613
- }
614
- });
615
- }); };
616
- var handleFKSSOWeb = function (redirectionInfo) {
617
- var _a;
618
- var params = (_a = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params) !== null && _a !== void 0 ? _a : {};
619
- var redirectUri = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.redirectUri;
620
- if (redirectUri) {
621
- redirectUri += '?';
622
- for (var key in params) {
623
- redirectUri += key + '=' + params[key] + '&';
624
- }
625
- return Promise.resolve(redirectUri);
626
- }
627
- return Promise.reject();
628
- };
629
- var handleFKSSOAndroid = function (redirectionInfo) {
630
- var _a, _b;
631
- var params = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params;
632
- if (isEmpty(params) ||
633
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onNavigationChange) !== 'function') {
634
- return Promise.reject();
635
- }
636
- else {
637
- var FK_REDIRECT_DL = urlJoin(getApiDomain(), 'dl/oauth2');
638
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.onNavigationChange(JSON.stringify({
639
- type: 'FkSSO',
640
- miscData: tslib.__assign(tslib.__assign({}, params), { redirectURI: FK_REDIRECT_DL }),
641
- }));
642
- return Promise.resolve();
643
- }
644
- };
645
- function getUserAuthValues(customCookie) {
646
- try {
647
- var _a = decodeURIComponent(getCookie('userid', customCookie) || '').split('|'), email = _a[0], profileName = _a[1], gender = _a[2], photo = _a[3], userId = _a[4];
648
- return {
649
- email: email,
650
- profileName: profileName,
651
- gender: gender,
652
- photo: photo,
653
- userId: userId,
654
- };
655
- }
656
- catch (error) {
657
- return {};
658
- }
659
- }
660
- var isUserSignedIn = function (customCookie) {
661
- var userObject = getUserAuthValues(customCookie) || {};
662
- var usermiscVal = decodeURIComponent(getCookie('usermisc', customCookie) || '').split('|');
663
- var signedIn = usermiscVal.includes('SIGNED_IN') &&
664
- userObject.userId &&
665
- userObject.userId.length > 0
666
- ? true
667
- : false;
668
- return signedIn;
669
- };
670
-
671
- var getUserInsights = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
672
- var response;
673
- return tslib.__generator(this, function (_a) {
674
- switch (_a.label) {
675
- case 0:
676
- _a.trys.push([0, 2, , 3]);
677
- return [4, createGetRequest('USER_INSIGHTS', {}, {
678
- pathParams: {
679
- userId: userId,
680
- },
681
- })];
682
- case 1:
683
- response = _a.sent();
684
- return [2, response === null || response === void 0 ? void 0 : response.data];
685
- case 2:
686
- _a.sent();
687
- return [2, Promise.resolve(null)];
688
- case 3: return [2];
689
- }
690
- });
691
- }); };
692
- var getUserInsightsData = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
693
- var _userId, stringifiedData, sessionData, userInsights;
694
- var _a, _b, _c, _d;
695
- return tslib.__generator(this, function (_f) {
696
- switch (_f.label) {
697
- case 0:
698
- _f.trys.push([0, 2, , 3]);
699
- _userId = userId !== null && userId !== void 0 ? userId : getUserAuthValues().userId;
700
- if (!_userId) {
701
- (_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.removeItem('martech_user_attributes');
702
- return [2, null];
703
- }
704
- stringifiedData = (_b = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _b === void 0 ? void 0 : _b.getItem('martech_user_attributes');
705
- sessionData = void 0;
706
- if (typeof stringifiedData === 'string') {
707
- sessionData = JSON.parse(stringifiedData);
708
- }
709
- if (_userId !== (sessionData === null || sessionData === void 0 ? void 0 : sessionData.accountId)) {
710
- (_c = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _c === void 0 ? void 0 : _c.removeItem('martech_user_attributes');
711
- }
712
- return [4, getUserInsights(_userId)];
713
- case 1:
714
- userInsights = _f.sent();
715
- if (isEmpty(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data)) {
716
- return [2, null];
717
- }
718
- (_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));
719
- return [2, userInsights === null || userInsights === void 0 ? void 0 : userInsights.data];
720
- case 2:
721
- _f.sent();
722
- return [2, null];
723
- case 3: return [2];
724
- }
725
- });
726
- }); };
727
-
728
- var stringifyPayload = function (payload) {
729
- var keys = Object.keys(payload);
730
- keys.forEach(function (key) {
731
- if (key === 'a_fare_price' ||
732
- key === 'a_ct_discount' ||
733
- key === 'supercoin_balance' ||
734
- key === 'supercoin_earned' ||
735
- key === 'supercoin_burnt' ||
736
- key === 'wallet_balance_used' ||
737
- key === 'convenience_fee')
738
- payload[key] = Number(payload[key]);
739
- else
740
- payload[key] = '' + payload[key];
741
- });
742
- return payload;
743
- };
744
- var ravenSDKTrigger = function (eventName, ravenPayload) {
745
- var _a;
746
- if (window && window['ravenWebManager']) {
747
- var _b = getRavenEventProps(), pageName = _b.pageName, utmSource = _b.utmSource;
748
- var commonPayload = {
749
- page_name: pageName,
750
- u_utm_source: utmSource,
751
- domain: window.location.host,
752
- platform: (_a = getDevicePlatform()) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
753
- login_status: isUserSignedIn() ? 'yes' : 'no',
754
- };
755
- var newRavenPayload = stringifyPayload(ravenPayload);
756
- var RavenWebManager = window['ravenWebManager'];
757
- RavenWebManager === null || RavenWebManager === void 0 ? void 0 : RavenWebManager.triggerRaven(eventName, tslib.__assign(tslib.__assign({}, commonPayload), newRavenPayload));
758
- }
759
- };
760
- var isAirHomePage = function () {
761
- if (window && typeof window !== 'undefined') {
762
- var pathname = getNestedValue(window, ['location', 'pathname']);
763
- if (pathname === '/' || pathname === '/flights') {
764
- return true;
765
- }
766
- }
767
- return false;
768
- };
769
- var getRavenEventProps = function () {
770
- var _a, _b;
771
- if (window && typeof window !== 'undefined') {
772
- var pathUrl = window.location.pathname;
773
- var redirectionPath = (_a = getQueryParam('service')) !== null && _a !== void 0 ? _a : '';
774
- var utmSource = (_b = getQueryParam('utm_source')) !== null && _b !== void 0 ? _b : 'organic';
775
- var loginForm = isAirHomePage() ? 'skippable_login' : 'account_login';
776
- var vertical = 'air';
777
- var pageName = pathUrl.includes('flights/itinerary') ||
778
- redirectionPath.includes('flights/itinerary')
779
- ? 'a_itinerary'
780
- : 'a_home';
781
- if (redirectionPath.includes('my-account')) {
782
- vertical = 'uar';
783
- pageName = 'account';
784
- }
785
- if (redirectionPath.includes('hotels')) {
786
- vertical = 'hotel';
787
- pageName = redirectionPath.includes('hotels/itinerary')
788
- ? 'h_itinerary'
789
- : 'h_home';
790
- }
791
- if (redirectionPath.includes('bus')) {
792
- vertical = 'bus';
793
- pageName = redirectionPath.includes('bus/itinerary')
794
- ? 'b_itinerary'
795
- : 'b_home';
796
- }
797
- return { loginForm: loginForm, vertical: vertical, pageName: pageName, utmSource: utmSource };
798
- }
799
- return {};
800
- };
801
- var sendEventWithUserInsights = function (eventName, ravenPayload, userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
802
- var userInsights, updatedPayload, loyaltyData, martechAttributes;
803
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
804
- return tslib.__generator(this, function (_s) {
805
- switch (_s.label) {
806
- case 0: return [4, getUserInsightsData(userId)];
807
- case 1:
808
- userInsights = _s.sent();
809
- 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' });
810
- if (!isEmpty(userInsights)) {
811
- loyaltyData = ((_a = userInsights === null || userInsights === void 0 ? void 0 : userInsights.loyaltyStatus) !== null && _a !== void 0 ? _a : []).reduce(function (prev, curr) {
812
- return tslib.__assign(tslib.__assign({}, prev), curr);
813
- }, {});
814
- martechAttributes = {
815
- 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(),
816
- 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(),
817
- 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(),
818
- ct_first_booking_dt: secondsToDateString((_h = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _h === void 0 ? void 0 : _h.firstbookingDate) || 'na',
819
- ct_last_booking_dt: secondsToDateString((_j = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _j === void 0 ? void 0 : _j.lastbookingDate) || 'na',
820
- 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',
821
- fk_loyalty_status: ((_l = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _l === void 0 ? void 0 : _l.program) || 'na',
822
- myntra_loyalty_status: ((_m = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _m === void 0 ? void 0 : _m.program) || 'na',
823
- fk_loyalty_end_dt: secondsToDateString((_o = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _o === void 0 ? void 0 : _o.loyaltyEndDate) || '',
824
- fk_loyalty_start_dt: secondsToDateString((_p = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _p === void 0 ? void 0 : _p.loyaltyStartDate) || 'na',
825
- myntra_loyalty_start_dt: secondsToDateString((_q = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _q === void 0 ? void 0 : _q.loyaltyStartDate) ||
826
- 'na',
827
- myntra_loyalty_end_dt: secondsToDateString((_r = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _r === void 0 ? void 0 : _r.loyaltyEndDate) ||
828
- 'na',
829
- };
830
- updatedPayload = tslib.__assign(tslib.__assign({}, updatedPayload), martechAttributes);
831
- setMartechUserProperties(martechAttributes);
832
- }
833
- ravenSDKTrigger(eventName, updatedPayload);
834
- return [2];
835
- }
836
- });
837
- }); };
838
- var setMartechUserProperties = function (userProperties) {
839
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
840
- if (isEmpty(userProperties) ||
841
- ((_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem('martech_user_props_sent'))) {
842
- return;
843
- }
844
- 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)) {
845
- (_d = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _d === void 0 ? void 0 : _d.postMessage({
846
- type: 'GA',
847
- params: userProperties,
848
- });
849
- (_e = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _e === void 0 ? void 0 : _e.postMessage({
850
- type: 'Clevertap',
851
- params: userProperties,
852
- });
853
- (_f = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _f === void 0 ? void 0 : _f.setItem('martech_user_props_sent', 'true');
854
- }
855
- else if (isAndroidApp() && ((_g = window === null || window === void 0 ? void 0 : window.MobileApp) === null || _g === void 0 ? void 0 : _g.sendAttributes)) {
856
- window.MobileApp.sendAttributes('GA', JSON.stringify(userProperties));
857
- window.MobileApp.sendAttributes('Clevertap', JSON.stringify(userProperties));
858
- (_h = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _h === void 0 ? void 0 : _h.setItem('martech_user_props_sent', 'true');
859
- }
860
- else if (isPwa() && window.clevertap) {
861
- window.clevertap.profile.push({
862
- Site: userProperties,
863
- });
864
- (_j = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _j === void 0 ? void 0 : _j.setItem('martech_user_props_sent', 'true');
865
- }
866
- };
867
- var batchRavenEvent = function (eventName, ravenPayload) {
868
- if (typeof window !== 'undefined' &&
869
- typeof window.requestIdleCallback === 'function') {
870
- requestIdleCallback(function () {
871
- ravenSDKTrigger(eventName, ravenPayload);
872
- });
873
- }
874
- else {
875
- setTimeout(function () {
876
- ravenSDKTrigger(eventName, ravenPayload);
877
- }, 0);
878
- }
879
- };
880
-
881
- var getHotelCrossSellRecos = function (vertical, fallbackPageLandingURL, cutoff) {
882
- if (cutoff === void 0) { cutoff = 450; }
883
- return tslib.__awaiter(void 0, void 0, void 0, function () {
884
- var userId, fallbackData, timeoutPromise, fetchRecommendationsPromise, result;
885
- var _a, _b;
886
- return tslib.__generator(this, function (_c) {
887
- switch (_c.label) {
888
- case 0:
889
- userId = (_b = (_a = getUserAuthValues()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : '';
890
- fallbackData = {
891
- couponCode: '',
892
- offerCallOut: 'FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU',
893
- couponCallOut: 'Offer applied on hotels',
894
- pageLandingUrl: fallbackPageLandingURL,
895
- };
896
- _c.label = 1;
897
- case 1:
898
- _c.trys.push([1, 3, , 4]);
899
- timeoutPromise = new Promise(function (resolve) {
900
- setTimeout(function () {
901
- resolve(fallbackData);
902
- }, cutoff);
903
- });
904
- fetchRecommendationsPromise = createGetRequest('HOTEL_RECOMMENDATIONS', {}, {
905
- queryParams: {
906
- userId: userId,
907
- vertical: vertical,
908
- },
909
- }).then(function (res) { return res.data; });
910
- return [4, Promise.race([
911
- fetchRecommendationsPromise,
912
- timeoutPromise,
913
- ])];
914
- case 2:
915
- result = _c.sent();
916
- return [2, result];
917
- case 3:
918
- _c.sent();
919
- return [2, fallbackData];
920
- case 4: return [2];
921
- }
922
- });
923
- });
924
- };
925
-
926
- exports.MULTI_SPACE = MULTI_SPACE;
927
- exports.autoReadOtp = autoReadOtp;
928
- exports.batchRavenEvent = batchRavenEvent;
929
- exports.createAPIRequest = createAPIRequest;
930
- exports.createGetRequest = createGetRequest;
931
- exports.createPostOrPutRequest = createPostOrPutRequest;
932
- exports.formatCurrency = formatCurrency;
933
- exports.formatFullDateString = formatFullDateString;
934
- exports.getApiDomain = getApiDomain;
935
- exports.getAppAgent = getAppAgent;
936
- exports.getAutoDetectedMobile = getAutoDetectedMobile;
937
- exports.getCookie = getCookie;
938
- exports.getCurrentPathName = getCurrentPathName;
939
- exports.getCurrentUrl = getCurrentUrl;
940
- exports.getDevicePlatform = getDevicePlatform;
941
- exports.getDimensionFromImageUrl = getDimensionFromImageUrl;
942
- exports.getHeightFromImgUrl = getHeightFromImgUrl;
943
- exports.getHotelCrossSellRecos = getHotelCrossSellRecos;
944
- exports.getJSVersion = getJSVersion;
945
- exports.getNestedValue = getNestedValue;
946
- exports.getQueryParam = getQueryParam;
947
- exports.getRavenEventProps = getRavenEventProps;
948
- exports.getUserAuthValues = getUserAuthValues;
949
- exports.getWidthFromImgUrl = getWidthFromImgUrl;
950
- exports.handleFKSSO = handleFKSSO;
951
- exports.handlePushPrimerCTA = handlePushPrimerCTA;
952
- exports.isAirHomePage = isAirHomePage;
953
- exports.isAndroidApp = isAndroidApp;
954
- exports.isEmpty = isEmpty;
955
- exports.isFKSSOEnabled = isFKSSOEnabled;
956
- exports.isHTMLInputElement = isHTMLInputElement;
957
- exports.isIOSApp = isIOSApp;
958
- exports.isJSVersionUpdated = isJSVersionUpdated;
959
- exports.isNumeric = isNumeric;
960
- exports.isPwa = isPwa;
961
- exports.isServer = isServer;
962
- exports.isUserSignedIn = isUserSignedIn;
963
- exports.isValidMobileNumber = isValidMobileNumber;
964
- exports.path = path;
965
- exports.ravenSDKTrigger = ravenSDKTrigger;
966
- exports.replacePlaceHolder = replacePlaceHolder;
967
- exports.secondsToDateString = secondsToDateString;
968
- exports.sendEventWithUserInsights = sendEventWithUserInsights;
969
- exports.sendLoginOtp = sendLoginOtp;
970
- exports.setMartechUserProperties = setMartechUserProperties;
971
- exports.shouldShowPushPrimer = shouldShowPushPrimer;
972
- exports.showMobileNumberHint = showMobileNumberHint;
973
- exports.stringifyPayload = stringifyPayload;
974
- exports.triggerOTPListener = triggerOTPListener;
975
- exports.updateNativeAndroidOnSignIn = updateNativeAndroidOnSignIn;
976
- exports.updateNativeIOSOnSignIn = updateNativeIOSOnSignIn;
977
- exports.updateNativeOnLogin = updateNativeOnLogin;
978
- exports.urlJoin = urlJoin;
979
- exports.validateOtp = validateOtp;
1
+ "use strict";var t=require("tslib"),n=require("@cleartrip/ct-platform-constants"),e=require("@cleartrip/ct-platform-types"),o=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var e=t.map((function(t){return t.trim().replace(/^[/]+/,"")})).join("/");return e=e.replace(/\/\?/g,"?")},i=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"}},r=function(t,n){return n.reduce((function(t,n){return t&&t[n]?t[n]:null}),t)},a=function(t){if(t instanceof Date)return!1;if(null==t)return!0;var n,e=function(t){return"[object Number]"===Object.prototype.toString.call(t)};if(e(t))return e(n=t)&&"NaN"===n.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),i=0,r=o[i];i<o.length;i+=1)if(Object.prototype.hasOwnProperty.call(t,r))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 n=t.match(/h_(\d+)[,\/]/);return n&&n[1]?parseInt(n[1],10):void 0}},c=function(t){if(t){var n=t.match(/w_(\d+)[,\/]/);return n&&n[1]?parseInt(n[1],10):void 0}},v=function(){return"undefined"==typeof window||!window};function p(t,n){var e=n||r(document,["cookie"]);if(e){for(var o=t+"=",i=e.split(";"),a=0;a<i.length;a++){for(var s=i[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 n=new Date(1e3*t),e=n.getFullYear(),o=String(n.getDate()).padStart(2,"0"),i=String(n.getMonth()+1).padStart(2,"0");return"".concat(e,"-").concat(i,"-").concat(o)}catch(t){return""}},f=function(){var t,e=null===(t=r(window,["navigator","userAgent"]))||void 0===t?void 0:t.toLowerCase(),o=/safari/.test(e),i=/iphone|ipod|ipad/.test(e);return r(window,["androidData","app-agent"])&&r(window,["androidData","js-version"])||"function"==typeof r(window,["MobileApp","getAppSpecificData"])?n.Platform.ANDROID:r(window,["iosData","app-agent"])&&r(window,["iosData","js-version"])||i&&!o?n.Platform.IOS:n.Platform.PWA},w=function(){var t,e,o=f();return o===n.Platform.IOS?null!==(t=r(window,["iosData","app-agent"]))&&void 0!==t?t:n.AppAgent.IOS:o===n.Platform.ANDROID?null!==(e=r(window,["androidData","app-agent"]))&&void 0!==e?e:n.AppAgent.ANDROID:n.AppAgent.PWA},g=function(){var t="";return S()?t=r(window,["iosData","js-version"]):h()&&(t=r(window,["androidData","js-version"])),t&&(t=t.toString().split(".")[0]),t},m=function(){return f()!==n.Platform.ANDROID&&f()!==n.Platform.IOS},h=function(){return f()===n.Platform.ANDROID},y=function(t){return parseInt(g())>=t},S=function(){return f()===n.Platform.IOS},b=i(),I=function(e,r,a,s,u,l){return void 0===r&&(r=n.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,_,f,g,m;return t.__generator(this,(function(h){switch(h.label){case 0:return d=function(t,e){var i=n.API_ROUTES[t];if(i&&i.trim().length){if(i=o(b,i),null==e?void 0:e.pathParams)for(var r=0,a=Object.entries(e.pathParams);r<a.length;r++){var s=a[r],u=s[0],l=s[1];i=i.replace(":".concat(u),l)}return(null==e?void 0:e.queryParams)&&(i+="?".concat(new URLSearchParams(e.queryParams).toString())),i}}(e,u),d&&d.trim().length?(c=i(),v={method:r,headers:t.__assign({Caller:b,Origin:b,Referer:b,Authority:c,x_ct_sourcetype:"MOBILE","app-agent":w(),"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(),f={name:"API_FAILURE",status:_.status,message:"UNKNOWN_ERROR",statusText:_.statusText},(null==_?void 0:_.ok)?[3,3]:l?[2,Promise.reject(f)]:[4,_.json()];case 2:throw g=h.sent().message,f.message=g,f;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}]}}))}))},N=function(e,o,i,r){return void 0===o&&(o={}),void 0===i&&(i={}),void 0===r&&(r=!1),t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(a){return[2,I(e,n.RequestMethods.GET,null,t.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},o),i,r)]}))}))},O=function(e,o,i,r,a,s){return void 0===o&&(o=n.RequestMethods.POST),void 0===i&&(i={}),void 0===r&&(r={}),void 0===a&&(a={}),void 0===s&&(s=!1),t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(n){return[2,I(e,o,i,t.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},r),a,s)]}))}))},P=function(t){var e="",o=t.match(n.MOBILE_CONSTANTS.REGEX);return o&&(e=o[0].replace(/\D/g,"")),e},A=function(){var t,n,e;null===(e=null===(n=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===n?void 0:n.PWA_IS_SIGNIN)||void 0===e||e.postMessage({isSignIn:!0})},x=function(){var t;null===(t=window.MobileApp)||void 0===t||t.onPWALoginStatus(JSON.stringify({isSignIn:!0}))},E=function(){return t.__awaiter(void 0,void 0,void 0,(function(){var n,e;return t.__generator(this,(function(t){return(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.get)&&"OTPCredential"in window?(n=new AbortController,setTimeout((function(){n.abort()}),6e4),[2,navigator.credentials.get({otp:{transport:["sms"]},signal:n.signal}).then((function(t){return null==t?void 0:t.code}))]):[2,Promise.reject("NOT_SUPPORTED")]}))}))},D=function(){return t.__awaiter(void 0,void 0,void 0,(function(){var n,e;return t.__generator(this,(function(t){return e=new Promise((function(t){n=t})),window.sendOtpValue=function(t){n(t)},[2,e]}))}))},M=function(e,r,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=i(),[4,O("FK_REDIRECTION_INFO",n.RequestMethods.POST,{provider:"flipkart",fallbackUri:o(s,e||l()),signupPageUri:o(s,r||"personal-details"),currentPageUri:o(s,a)})];case 1:return[2,null==(u=t.sent())?void 0:u.data]}}))}))},T=function(t){var n,e=null!==(n=null==t?void 0:t.params)&&void 0!==n?n:{},o=null==t?void 0:t.redirectUri;if(o){for(var i in o+="?",e)o+=i+"="+e[i]+"&";return Promise.resolve(o)}return Promise.reject()},R=function(n){var e,r,s=null==n?void 0:n.params;if(a(s)||"function"!=typeof(null===(e=window.MobileApp)||void 0===e?void 0:e.onNavigationChange))return Promise.reject();var u=o(i(),"dl/oauth2");return null===(r=window.MobileApp)||void 0===r||r.onNavigationChange(JSON.stringify({type:"FkSSO",miscData:t.__assign(t.__assign({},s),{redirectURI:u})})),Promise.resolve()};function k(t){try{var n=decodeURIComponent(p("userid",t)||"").split("|");return{email:n[0],profileName:n[1],gender:n[2],photo:n[3],userId:n[4]}}catch(t){return{}}}var C=function(t){var n=k(t)||{};return!!(decodeURIComponent(p("usermisc",t)||"").split("|").includes("SIGNED_IN")&&n.userId&&n.userId.length>0)},U=function(n){return t.__awaiter(void 0,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,N("USER_INSIGHTS",{},{pathParams:{userId:n}})];case 1:return[2,null==(e=t.sent())?void 0:e.data];case 2:return t.sent(),[2,Promise.resolve(null)];case 3:return[2]}}))}))},L=function(n){return t.__awaiter(void 0,void 0,void 0,(function(){var e,o,i,r,s,u,l,d;return t.__generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),(e=null!=n?n:k().userId)?(o=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 o&&(i=JSON.parse(o)),e!==(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,U(e)]):(null===(s=null===window||void 0===window?void 0:window.sessionStorage)||void 0===s||s.removeItem("martech_user_attributes"),[2,null]);case 1:return r=t.sent(),a(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]}}))}))},j=function(t){return Object.keys(t).forEach((function(n){t[n]="a_fare_price"===n||"a_ct_discount"===n||"supercoin_balance"===n||"supercoin_earned"===n||"supercoin_burnt"===n||"wallet_balance_used"===n||"convenience_fee"===n?Number(t[n]):""+t[n]})),t},q=function(n,e){var o;if(window&&window.ravenWebManager){var i=B(),r={page_name:i.pageName,u_utm_source:i.utmSource,domain:window.location.host,platform:null===(o=f())||void 0===o?void 0:o.toLowerCase(),login_status:C()?"yes":"no"},a=j(e),s=window.ravenWebManager;null==s||s.triggerRaven(n,t.__assign(t.__assign({},r),a))}},F=function(){if(window&&"undefined"!=typeof window){var t=r(window,["location","pathname"]);if("/"===t||"/flights"===t)return!0}return!1},B=function(){var t,n;if(window&&"undefined"!=typeof window){var e=window.location.pathname,o=null!==(t=u("service"))&&void 0!==t?t:"",i=null!==(n=u("utm_source"))&&void 0!==n?n:"organic",r=F()?"skippable_login":"account_login",a="air",s=e.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:r,vertical:a,pageName:s,utmSource:i}}return{}},H=function(t){var n,e,o,i,r,s,u,l,d;a(t)||(null===(n=null===window||void 0===window?void 0:window.sessionStorage)||void 0===n?void 0:n.getItem("martech_user_props_sent"))||(S()&&(null===(o=null===(e=null===window||void 0===window?void 0:window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===o?void 0:o.SEND_ATTRIBUTES)?(null===(i=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===i||i.postMessage({type:"GA",params:t}),null===(r=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===r||r.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()?D():E()]}))}))},exports.batchRavenEvent=function(t,n){"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?requestIdleCallback((function(){q(t,n)})):setTimeout((function(){q(t,n)}),0)},exports.createAPIRequest=I,exports.createGetRequest=N,exports.createPostOrPutRequest=O,exports.formatCurrency=function(t,n){void 0===n&&(n=!0);try{var e={currency:"INR",minimumFractionDigits:0};return n&&(e.style="currency"),"string"!=typeof t&&(t=null==t?void 0:t.toString()),t=t.replace(/,/g,""),parseInt(t,10).toLocaleString("en-IN",e)}catch(t){return""}},exports.formatFullDateString=function(t,n,e){void 0===n&&(n="dd-mm-yyyy"),void 0===e&&(e="");try{var o=new Date(t),i=o.getFullYear(),r=String(o.getDate()).padStart(2,"0"),a=String(o.getMonth()+1).padStart(2,"0");return"yyyy-mm-dd"===n?"".concat(i,"-").concat(a,"-").concat(r):"".concat(r,"-").concat(a,"-").concat(i)}catch(t){return e}},exports.getApiDomain=i,exports.getAppAgent=w,exports.getAutoDetectedMobile=P,exports.getCookie=p,exports.getCurrentPathName=l,exports.getCurrentUrl=s,exports.getDevicePlatform=f,exports.getDimensionFromImageUrl=function(t){void 0===t&&(t="");var n=d(t)||0,e=c(t)||0;return{height:"".concat(n,"px"),width:"".concat(e,"px"),heightInNumber:n,widthInNumber:e}},exports.getHeightFromImgUrl=d,exports.getHotelCrossSellRecos=function(n,e,o){return void 0===o&&(o=450),t.__awaiter(void 0,void 0,void 0,(function(){var i,r,a,s,u,l;return t.__generator(this,(function(t){switch(t.label){case 0:i=null!==(l=null===(u=k())||void 0===u?void 0:u.userId)&&void 0!==l?l:"",r={couponCode:"",offerCallOut:"FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU",couponCallOut:"Offer applied on hotels",pageLandingUrl:e},t.label=1;case 1:return t.trys.push([1,3,,4]),a=new Promise((function(t){setTimeout((function(){t(r)}),o)})),s=N("HOTEL_RECOMMENDATIONS",{},{queryParams:{userId:i,vertical:n}}).then((function(t){return t.data})),[4,Promise.race([s,a])];case 2:return[2,t.sent()];case 3:return t.sent(),[2,r];case 4:return[2]}}))}))},exports.getJSVersion=g,exports.getNestedValue=r,exports.getQueryParam=u,exports.getRavenEventProps=B,exports.getUserAuthValues=k,exports.getWidthFromImgUrl=c,exports.handleFKSSO=function(n,e,o){return t.__awaiter(void 0,void 0,void 0,(function(){var i;return t.__generator(this,(function(t){switch(t.label){case 0:return S()?[2,Promise.reject()]:[4,M(n,e,o)];case 1:return i=t.sent(),h()?[2,R(i)]:[2,T(i)]}}))}))},exports.handlePushPrimerCTA=function(t){var n,e,o,i;return h()&&"function"==typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.handlePNPermission)?null===(e=window.MobileApp)||void 0===e||e.handlePNPermission(JSON.stringify({type:t})):S()&&"function"==typeof(null===(o=window.MobileApp)||void 0===o?void 0:o.HANDLE_PN_PERMISSION)&&(null===(i=window.MobileApp)||void 0===i||i.HANDLE_PN_PERMISSION(JSON.stringify({type:t}))),""},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)===n.MOBILE_CONSTANTS.LENGTH&&/^\d{10}$/.test(t)},exports.path=function(t,n){return t.reduce((function(t,n){return t&&t[n]?t[n]:null}),n)},exports.ravenSDKTrigger=q,exports.secondsToDateString=_,exports.sendEventWithUserInsights=function(n,e,o){return t.__awaiter(void 0,void 0,void 0,(function(){var i,r,s,u,l,d,c,v,p,f,w,g,m,h,y,S,b,I,N,O;return t.__generator(this,(function(P){switch(P.label){case 0:return[4,L(o)];case 1:return i=P.sent(),r=t.__assign(t.__assign({},e),{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(i)||(s=(null!==(l=null==i?void 0:i.loyaltyStatus)&&void 0!==l?l:[]).reduce((function(n,e){return t.__assign(t.__assign({},n),e)}),{}),u={ct_lifetime_booking:(null!==(c=null===(d=null==i?void 0:i.bookingStatus)||void 0===d?void 0:d.lifetimeBooking)&&void 0!==c?c:"na").toString(),ct_postmerger_booking:(null!==(p=null===(v=null==i?void 0:i.bookingStatus)||void 0===v?void 0:v.postmergerBooking)&&void 0!==p?p:"na").toString(),ct_last_1year_booking:(null!==(w=null===(f=null==i?void 0:i.bookingStatus)||void 0===f?void 0:f.lastOneYearBooking)&&void 0!==w?w:"na").toString(),ct_first_booking_dt:_(null===(g=null==i?void 0:i.bookingStatus)||void 0===g?void 0:g.firstbookingDate)||"na",ct_last_booking_dt:_(null===(m=null==i?void 0:i.bookingStatus)||void 0===m?void 0:m.lastbookingDate)||"na",ct_2nd_last_booking_dt:_(null===(h=null==i?void 0:i.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===(N=null==s?void 0:s.myntra)||void 0===N?void 0:N.loyaltyStartDate)||"na",myntra_loyalty_end_dt:_(null===(O=null==s?void 0:s.myntra)||void 0===O?void 0:O.loyaltyEndDate)||"na"},r=t.__assign(t.__assign({},r),u),H(u)),q(n,r),[2]}}))}))},exports.sendLoginOtp=function(e,o){return t.__awaiter(void 0,void 0,void 0,(function(){var i;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,O("SEND_OTP",n.RequestMethods.POST,{value:e,type:"MOBILE",action:"SIGNIN",countryCode:n.MOBILE_CONSTANTS.COUNTRY_CODE},{"ab-otp":"b",dvid_data:o})];case 1:return[2,null==(i=t.sent())?void 0:i.data]}}))}))},exports.setMartechUserProperties=H,exports.shouldShowPushPrimer=function(){return t.__awaiter(void 0,void 0,void 0,(function(){var e,o,i,r,a,s,u;return t.__generator(this,(function(l){switch(l.label){case 0:return(e=f())!==n.PLATFORM_CONSTANTS.IOS||"function"!=typeof(null===(a=window.MobileApp)||void 0===a?void 0:a.IS_PN_PERMISSION_ENABLED)?[3,2]:(o=function(){var t;return null===(t=window.MobileApp)||void 0===t?void 0:t.IS_PN_PERMISSION_ENABLED()},[4,o()]);case 1:return i=l.sent(),r=setInterval((function(){return t.__awaiter(void 0,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return[4,o()];case 1:return null!==(i=t.sent())&&clearInterval(r),[2]}}))}))}),1e3),[2,i];case 2:if(e===n.PLATFORM_CONSTANTS.ANDROID&&"function"==typeof(null===(s=window.MobileApp)||void 0===s?void 0:s.isPNPermissionEnabled))return[2,null===(u=window.MobileApp)||void 0===u?void 0:u.isPNPermissionEnabled()];l.label=3;case 3:return[2,!1]}}))}))},exports.showMobileNumberHint=function(){var t;if("function"==typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.onRequestMobileNumber)){var n;window.MobileApp.onRequestMobileNumber();var e=new Promise((function(t){n=t}));return window.sendSelectedMobileNumber=function(t){return n(P(t))},e}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,i){return t.__awaiter(void 0,void 0,void 0,(function(){var r,a;return t.__generator(this,(function(s){switch(s.label){case 0:return[4,O("VALIDATE_OTP",n.RequestMethods.POST,{otp:i,value:o,type:"MOBILE",action:"SIGNIN",countryCode:"+91"},{"ab-otp":"b"})];case 1:return r=s.sent(),a=null==r?void 0:r.data,[2,t.__assign(t.__assign({},r),{signup:(null==a?void 0:a.action)===e.ValidateOTPAction.SIGNUP,action:null==a?void 0:a.action,status:null==r?void 0:r.status})]}}))}))};
980
2
  //# sourceMappingURL=ct-platform-utils.cjs.js.map