@cleartrip/ct-platform-utils 3.14.1-beta.0 → 3.15.0

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