@techstuff-dev/foundation-api-utils 2.3.1 → 2.4.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.
Files changed (39) hide show
  1. package/dist/cjs/chunks/{shared-Dg7JQIWA.js → shared-DVGP3iZ0.js} +2 -2
  2. package/dist/cjs/chunks/{shared-Dg7JQIWA.js.map → shared-DVGP3iZ0.js.map} +1 -1
  3. package/dist/cjs/chunks/{slice-CJ4WSj5p.js → slice-C4MKCa5N.js} +268 -742
  4. package/dist/cjs/chunks/slice-C4MKCa5N.js.map +1 -0
  5. package/dist/cjs/chunks/useAuth-BVyDLl6H.js +25 -0
  6. package/dist/cjs/chunks/useAuth-BVyDLl6H.js.map +1 -0
  7. package/dist/cjs/hooks/index.native.js +1 -1
  8. package/dist/cjs/hooks/index.web.js +1 -1
  9. package/dist/cjs/index.js +644 -31
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/store/index.native.js +2 -4
  12. package/dist/cjs/store/index.native.js.map +1 -1
  13. package/dist/cjs/store/index.web.js +2 -4
  14. package/dist/cjs/store/index.web.js.map +1 -1
  15. package/dist/esm/chunks/{shared-CztMTb2m.js → shared-DvU_DUT_.js} +2 -2
  16. package/dist/esm/chunks/{shared-CztMTb2m.js.map → shared-DvU_DUT_.js.map} +1 -1
  17. package/dist/esm/chunks/{slice-_b4ee7tw.js → slice-B2f63n1v.js} +257 -718
  18. package/dist/esm/chunks/slice-B2f63n1v.js.map +1 -0
  19. package/dist/esm/chunks/useAuth-CTcqsTAS.js +23 -0
  20. package/dist/esm/chunks/useAuth-CTcqsTAS.js.map +1 -0
  21. package/dist/esm/hooks/index.native.js +1 -1
  22. package/dist/esm/hooks/index.web.js +1 -1
  23. package/dist/esm/index.js +609 -4
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/store/index.native.js +2 -4
  26. package/dist/esm/store/index.native.js.map +1 -1
  27. package/dist/esm/store/index.web.js +2 -4
  28. package/dist/esm/store/index.web.js.map +1 -1
  29. package/dist/types/hooks/index.d.ts +1 -1
  30. package/dist/types/{index-CNDW7aai.d.ts → index-UGRVwFLD.d.ts} +108 -38
  31. package/dist/types/index.d.ts +2897 -140
  32. package/dist/types/store/index.d.ts +1 -1
  33. package/package.json +2 -3
  34. package/dist/cjs/chunks/slice-CJ4WSj5p.js.map +0 -1
  35. package/dist/cjs/chunks/useAuth-DKhvUX_r.js +0 -13
  36. package/dist/cjs/chunks/useAuth-DKhvUX_r.js.map +0 -1
  37. package/dist/esm/chunks/slice-_b4ee7tw.js.map +0 -1
  38. package/dist/esm/chunks/useAuth-8d6DlERn.js +0 -11
  39. package/dist/esm/chunks/useAuth-8d6DlERn.js.map +0 -1
@@ -1,11 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var awsAmplify = require('aws-amplify');
4
3
  var slice = require('./slice-CkWobkWw.js');
5
4
  var toolkit = require('@reduxjs/toolkit');
6
5
  var reactRedux = require('react-redux');
7
6
  var React = require('react');
8
- var jwtDecode = require('jwt-decode');
9
7
 
10
8
  // src/utils/env.ts
11
9
  var NOTHING = Symbol.for("immer-nothing");
@@ -5097,641 +5095,17 @@ function createUnwrappingBaseQuery(baseQueryOptions) {
5097
5095
  };
5098
5096
  }
5099
5097
 
5100
- function onlyUnique(value, index, self) {
5101
- return self.indexOf(value) === index;
5102
- }
5103
- function applyCoupon(coupon, netTotal) {
5104
- const discountedAmount = netTotal * (Number(coupon.discount) / 100);
5105
- const discountedTotal = netTotal - discountedAmount;
5106
- const data = {
5107
- ...coupon,
5108
- discountedTotal,
5109
- discountedAmount,
5110
- };
5111
- return data;
5112
- }
5113
- function applyTax(taxRate, netTotal) {
5114
- const taxAmount = netTotal * (taxRate.percentage / 100);
5115
- return taxAmount;
5116
- }
5117
- function toCamelCaseObject(obj) {
5118
- const toCamelCase = (str) => {
5119
- return str.replace(/([-_][a-z])/gi, (match) => {
5120
- return match.toUpperCase().replace(/[-_]/, '');
5121
- });
5122
- };
5123
- const camelCaseObject = {};
5124
- for (const key in obj) {
5125
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
5126
- const camelKey = toCamelCase(key);
5127
- camelCaseObject[camelKey] = obj[key];
5128
- }
5129
- }
5130
- return camelCaseObject;
5131
- }
5132
-
5133
- // TODO: typing.
5134
- const formatUserPayload = (payload) => {
5135
- const { email: userEmail, given_name: firstName, family_name: lastName, birthdate: dateOfBirth, picture: picture, 'cognito:username': uuid, 'custom:termsAccepted': termsAccepted, 'custom:subscriptionId': subscriptionId, 'custom:contactPreferences': contactPreference, 'custom:customerId': customerId, } = payload;
5136
- const parsedTermsAccepted = termsAccepted ? JSON.parse(termsAccepted) : null;
5137
- const parsedContactPreference = contactPreference
5138
- ? JSON.parse(contactPreference)
5139
- : null;
5140
- const data = {
5141
- userEmail,
5142
- lastName,
5143
- firstName,
5144
- dateOfBirth,
5145
- /** Handles the auth micro service/Cognito serving boolean options as a string. */
5146
- termsAccepted: parsedTermsAccepted,
5147
- contactPreference: parsedContactPreference,
5148
- uuid,
5149
- subscription: subscriptionId || null,
5150
- customerId,
5151
- picture,
5152
- };
5153
- return data;
5154
- };
5155
- function formatPromos(data) {
5156
- return data.map((item) => {
5157
- return {
5158
- uuid: item?._source?.uuid?.[0],
5159
- id: item?._source?.uuid?.[0],
5160
- title: item?._source?.title?.[0],
5161
- image: item?._source?.image?.[0],
5162
- imageFormatted: item?._source?.image_formatted?.[0],
5163
- description: item?._source?.description?.[0],
5164
- created: item?._source?.created?.[0],
5165
- updated: item?._source?.updated?.[0],
5166
- weight: item?._source?.weight?.[0],
5167
- buttonText: item?._source?.button_text?.[0],
5168
- link: item?._source?.link?.[0],
5169
- linkMobile: item?._source?.link_mobile?.[0],
5170
- term: item?._source?.term?.[0],
5171
- // video: item?._source?.video?.[0],
5172
- // align: item?._source?.align?.[0],
5173
- // section: item?._source?.section?.[0],
5174
- // backgroundImage: item?._source?.background_image?.[0],
5175
- // backgroundVideo: item?._source?.background_video?.[0],
5176
- // backgroundImageFormatted: item?._source?.background_image_formatted?.[0],
5177
- // langcode: item?._source?.langcode?.[0],
5178
- // authPanel: item?._source?.auth_panel?.[0],
5179
- };
5180
- });
5181
- }
5182
- function formatWorkout(data) {
5183
- return data.map((item) => {
5184
- return {
5185
- changed: item?._source?.changed?.[0],
5186
- created: item?._source?.created?.[0],
5187
- uuid: item?._source?.uuid?.[0],
5188
- description: item?._source?.description?.[0],
5189
- duration: item?._source?.duration_filter?.[0],
5190
- // duration_filter: item?._source?.duration_filter?.[0],
5191
- level: item?._source?.level?.[0],
5192
- published: item?._source?.published?.[0],
5193
- targeted_section: item?._source?.targeted_section?.[0],
5194
- uid: item?._source?.uid?.[0],
5195
- imageStyled: item?._source?.image_16_9?.[0],
5196
- image: item?._source?.image?.[0],
5197
- title: item?._source?.title?.[0],
5198
- video: item?._source?.video_url?.[0],
5199
- videoDownload: item?._source?.video_download?.[0],
5200
- videoPoster: item?._source?.video_poster?.[0],
5201
- workoutCategory: item?._source?.workout_category?.[0],
5202
- workoutType: item?._source?.workout_type?.[0],
5203
- livestreamSection: item?._source?.livestream_section?.[0],
5204
- };
5205
- });
5206
- }
5207
- // export function formatSeries(data: Series[], channel: string) {
5208
- // const formattedSeriesSelection = data.map((series) => {
5209
- // return {
5210
- // uuid: series.uuid,
5211
- // id: series.uuid,
5212
- // title: series.title,
5213
- // subtitle: series.subtitle,
5214
- // thumb: series.imageThumbnailURL,
5215
- // mainImage: series.imageURL,
5216
- // description: series.summary.value,
5217
- // body: series.body.value,
5218
- // nid: series.nid,
5219
- // seasonList: series.season,
5220
- // channel,
5221
- // };
5222
- // });
5223
- // return formattedSeriesSelection;
5224
- // }
5225
- function formatShortform(data) {
5226
- return data.map((item) => {
5227
- const { _source } = item;
5228
- return {
5229
- uuid: _source.uuid && _source.uuid[0],
5230
- id: _source.uuid && _source.uuid[0],
5231
- nid: _source.nid && _source.nid[0],
5232
- title: _source.title && _source.title[0],
5233
- thumb: _source.field_image_thumb && _source.field_image_thumb[0],
5234
- mainImage: _source.field_image_poster && _source.field_image_poster[0],
5235
- description: _source.field_short_synopsis && _source.field_short_synopsis[0],
5236
- body: _source.field_body && _source.field_body[0],
5237
- channel: _source.field_channel && _source.field_channel[0],
5238
- updated: _source.revision_timestamp && _source.revision_timestamp[0],
5239
- langcode: _source.langcode && _source.langcode[0],
5240
- video: _source.field_videomanifest && _source.field_videomanifest[0],
5241
- duration: _source.field_duration && _source.field_duration[0],
5242
- category: _source.field_category && _source.field_category[0],
5243
- };
5244
- });
5245
- }
5246
- // export function formatLongform(data: ESLongForm[]) {
5247
- // return data.map((item) => {
5248
- // const { _source } = item;
5249
- // return {
5250
- // uuid: _source.uuid && _source.uuid[0],
5251
- // id: _source.uuid && _source.uuid[0],
5252
- // nid: _source.nid && _source.nid[0],
5253
- // title: _source.title && _source.title[0],
5254
- // image: _source.image && _source.image[0],
5255
- // image_promo: _source.image_promo && _source.image_promo[0],
5256
- // image_promo_large:
5257
- // _source.image_promo_large && _source.image_promo_large[0],
5258
- // image_poster: _source.image_poster && _source.image_poster[0],
5259
- // summary: _source.summary && _source.summary[0],
5260
- // created: _source.created && _source.created[0],
5261
- // updated: _source.revision_timestamp && _source.revision_timestamp[0],
5262
- // video: _source.video_manifest && _source.video_manifest[0],
5263
- // rating: _source.rating && _source.rating[0],
5264
- // released: _source.released_date && _source.released_date[0],
5265
- // source_id: _source.source_id && _source.source_id[0],
5266
- // director: _source.director && _source.director[0],
5267
- // duration: _source.duration && _source.duration[0],
5268
- // path: _source.path && _source.path[0],
5269
- // genres: _source.genres,
5270
- // actors: _source.actors,
5271
- // writers: _source.writers,
5272
- // };
5273
- // });
5274
- // }
5275
- function formatFaqs(data) {
5276
- return data.map((item) => {
5277
- const { _source } = item;
5278
- return {
5279
- uuid: _source.uuid && _source.uuid[0],
5280
- id: _source.uuid && _source.uuid[0],
5281
- title: _source.title && _source.title[0],
5282
- answer: _source.answer && _source.answer[0],
5283
- created: _source.created && _source.created[0],
5284
- updated: _source.updated && _source.updated[0],
5285
- };
5286
- });
5287
- }
5288
- function formatPages(data) {
5289
- return data.map((item) => {
5290
- return {
5291
- uuid: item?._source?.uuid?.[0],
5292
- id: item?._source?.uuid?.[0],
5293
- title: item?._source?.title?.[0],
5294
- body: item?._source?.body?.[0],
5295
- created: item?._source?.created?.[0],
5296
- updated: item?._source?.updated?.[0],
5297
- langcode: item?._source?.langcode?.[0],
5298
- url: item?._source?.url?.[0],
5299
- };
5300
- });
5301
- }
5302
- function formatSettings(data) {
5303
- return data.map((item) => {
5304
- const { _source } = item;
5305
- const fieldset = _source.fieldset && _source.fieldset[0].toLowerCase();
5306
- return {
5307
- uuid: _source.uuid && _source.uuid[0],
5308
- created: _source.created && _source.created[0],
5309
- updated: _source.updated && _source.updated[0],
5310
- status: _source.status && _source.status[0],
5311
- type: _source.type && _source.type[0],
5312
- video: _source.video && _source.video[0],
5313
- number: _source.number && _source.number[0],
5314
- pass: _source.pass && _source.pass[0],
5315
- fieldset,
5316
- };
5317
- });
5318
- }
5319
- function formatPress(data) {
5320
- return data.map((item) => {
5321
- const { _source } = item;
5322
- return {
5323
- uuid: _source.uuid && _source.uuid[0],
5324
- created: _source.created && _source.created[0],
5325
- updated: _source.updated && _source.updated[0],
5326
- image: _source.image && _source.image[0],
5327
- title: _source.title && _source.title[0],
5328
- };
5329
- });
5330
- }
5331
- function formatGuests(data) {
5332
- return data.map((item) => {
5333
- const { _source } = item;
5334
- return {
5335
- uuid: _source.uuid && _source.uuid[0],
5336
- id: _source.id && _source.id[0],
5337
- title: _source.title && _source.title[0],
5338
- updated: _source.updated && _source.updated[0],
5339
- description: _source.description && _source.description[0],
5340
- image: _source.image_16_9 && _source.image_16_9[0],
5341
- display: _source.display && _source.display[0],
5342
- };
5343
- });
5344
- }
5345
- function formatVideos(data) {
5346
- return data.map((item) => {
5347
- return {
5348
- uuid: item?._source?.uuid?.[0],
5349
- title: item?._source?.title?.[0],
5350
- created: item?._source?.created?.[0],
5351
- updated: item?._source?.updated?.[0],
5352
- description: item?._source?.description?.[0],
5353
- image: item?._source?.image?.[0],
5354
- duration: item?._source?.duration?.[0],
5355
- section: item?._source?.section?.[0],
5356
- videoPoster: item?._source?.video_poster?.[0],
5357
- video: item?._source?.video_url?.[0],
5358
- videoDownload: item?._source?.video_download?.[0],
5359
- sectionId: item?._source?.section_id?.[0],
5360
- };
5361
- });
5362
- }
5363
- function formatSections(data) {
5364
- return data.map((item) => {
5365
- const { _source } = item;
5366
- return {
5367
- uuid: _source.uuid && _source.uuid[0],
5368
- title: _source.title && _source.title[0],
5369
- description: _source.description && _source.description[0],
5370
- image: _source.image && _source.image[0],
5371
- challenge: _source.challenge && _source.challenge[0],
5372
- display: _source.display && _source.display[0],
5373
- id: _source.id && _source.id[0],
5374
- };
5375
- });
5376
- }
5377
- function formatSchedule(data) {
5378
- return data.map((item) => {
5379
- return {
5380
- uuid: item?._source?.uuid?.[0],
5381
- created: item?._source?.created?.[0],
5382
- langcode: item?._source?.langcode?.[0],
5383
- updated: item?._source?.updated?.[0],
5384
- days: [
5385
- {
5386
- monday: item?._source?.monday_title?.map((title, index) => {
5387
- return {
5388
- end: item?._source?.monday_end?.[index],
5389
- start: item?._source?.monday_start?.[index],
5390
- title,
5391
- video: item?._source?.monday_video?.[index],
5392
- live: item?._source?.monday_live?.[index],
5393
- };
5394
- }),
5395
- },
5396
- {
5397
- tuesday: item?._source?.tuesday_title?.map((title, index) => {
5398
- return {
5399
- end: item?._source?.tuesday_end?.[index],
5400
- start: item?._source?.tuesday_start?.[index],
5401
- title,
5402
- video: item?._source?.tuesday_video?.[index],
5403
- live: item?._source?.tuesday_live?.[index],
5404
- };
5405
- }),
5406
- },
5407
- {
5408
- wednesday: item?._source?.wednesday_title?.map((title, index) => {
5409
- return {
5410
- end: item?._source?.wednesday_end?.[index],
5411
- start: item?._source?.wednesday_start?.[index],
5412
- title,
5413
- video: item?._source?.wednesday_video?.[index],
5414
- live: item?._source?.wednesday_live?.[index],
5415
- };
5416
- }),
5417
- },
5418
- {
5419
- thursday: item?._source?.thursday_title?.map((title, index) => {
5420
- return {
5421
- end: item?._source?.thursday_end?.[index],
5422
- start: item?._source?.thursday_start?.[index],
5423
- title,
5424
- video: item?._source?.thursday_video?.[index],
5425
- live: item?._source?.thursday_live?.[index],
5426
- };
5427
- }),
5428
- },
5429
- {
5430
- friday: item?._source?.friday_title?.map((title, index) => {
5431
- return {
5432
- end: item?._source?.friday_end?.[index],
5433
- start: item?._source?.friday_start?.[index],
5434
- title,
5435
- video: item?._source?.friday_video?.[index],
5436
- live: item?._source?.friday_live?.[index],
5437
- };
5438
- }),
5439
- },
5440
- {
5441
- saturday: item?._source?.saturday_title?.map((title, index) => {
5442
- return {
5443
- end: item?._source?.saturday_end?.[index],
5444
- start: item?._source?.saturday_start?.[index],
5445
- title,
5446
- video: item?._source?.saturday_video?.[index],
5447
- live: item?._source?.saturday_live?.[index],
5448
- };
5449
- }),
5450
- },
5451
- {
5452
- sunday: item?._source?.sunday_title?.map((title, index) => {
5453
- return {
5454
- end: item?._source?.sunday_end?.[index],
5455
- start: item?._source?.sunday_start?.[index],
5456
- title,
5457
- video: item?._source?.sunday_video?.[index],
5458
- live: item?._source?.sunday_live?.[index],
5459
- };
5460
- }),
5461
- },
5462
- ],
5463
- };
5464
- });
5465
- }
5466
- function formatChallenges(data) {
5467
- return data.map((item) => {
5468
- const { _source } = item;
5469
- return {
5470
- uuid: _source?.uuid?.[0],
5471
- title: _source.title && _source.title[0],
5472
- body: _source.body && _source.body[0],
5473
- image: _source.image && _source.image[0],
5474
- challengeKey: _source.challenge_key && _source.challenge_key[0],
5475
- created: _source.created && _source.created[0],
5476
- days: _source.days,
5477
- updated: _source.updated && _source.updated[0],
5478
- purchaseButtonLabel: _source.purchase_button_label && _source.purchase_button_label[0],
5479
- price: _source.price && _source.price[0],
5480
- };
5481
- });
5482
- }
5483
- function formatChallengeDays(data) {
5484
- return data.map((item) => {
5485
- return {
5486
- uuid: item?._source?.uuid?.[0],
5487
- title: item?._source?.title?.[0],
5488
- body: item?._source?.body?.[0],
5489
- image: item?._source?.image?.[0],
5490
- created: item?._source?.created?.[0],
5491
- updated: item?._source?.updated?.[0],
5492
- video: item?._source?.video?.[0],
5493
- workout: item?._source?.workout?.[0],
5494
- };
5495
- });
5496
- }
5497
- function formatSecondsToISO8601Duration(seconds) {
5498
- if (!seconds)
5499
- return '';
5500
- // Calculate hours, minutes, and remaining seconds
5501
- const hours = Math.floor(seconds / 3600);
5502
- const minutes = Math.floor((seconds % 3600) / 60);
5503
- const remainingSeconds = seconds % 60;
5504
- // Build the ISO 8601 duration string
5505
- let duration = 'PT';
5506
- if (hours > 0) {
5507
- duration += `${hours}H`;
5508
- }
5509
- if (minutes > 0) {
5510
- duration += `${minutes}M`;
5511
- }
5512
- if (remainingSeconds > 0 || duration === 'PT') {
5513
- duration += `${remainingSeconds}S`;
5514
- }
5515
- return duration;
5516
- }
5517
- function formatAuthSession(session) {
5518
- return {
5519
- accessToken: session?.tokens?.accessToken.toString(),
5520
- idToken: session?.tokens?.idToken?.toString(),
5521
- refreshToken: undefined,
5522
- accessTokenExpiry: session?.tokens?.idToken?.payload?.exp,
5523
- expires: session?.tokens?.idToken?.payload?.exp,
5524
- sub: session?.tokens?.idToken?.payload?.['cognito:username']?.toString(),
5525
- details: {
5526
- userEmail: session?.tokens?.idToken?.payload?.email?.toString(),
5527
- firstName: session?.tokens?.idToken?.payload?.given_name?.toString(),
5528
- lastName: session?.tokens?.idToken?.payload?.family_name?.toString(),
5529
- dateOfBirth: session?.tokens?.idToken?.payload?.birthdate?.toString(),
5530
- 'cognito:username': session?.tokens?.idToken?.payload?.['cognito:username']?.toString(),
5531
- 'custom:termsAccepted': session?.tokens?.idToken?.payload?.['custom:termsAccepted']?.toString(),
5532
- 'custom:subscriptionId': session?.tokens?.idToken?.payload?.['custom:subscriptionId']?.toString(),
5533
- 'custom:contactPreferences': session?.tokens?.idToken?.payload?.['custom:contactPreferences']?.toString(),
5534
- 'custom:customerId': session?.tokens?.idToken?.payload?.['custom:customerId']?.toString(),
5535
- picture: session?.tokens?.idToken?.payload?.picture?.toString(),
5536
- },
5537
- };
5538
- }
5539
- function formatFedaratedSession(session) {
5540
- return {
5541
- accessToken: session?.accessToken?.jwtToken,
5542
- idToken: session?.idToken?.jwtToken,
5543
- refreshToken: session?.refreshToken?.token,
5544
- accessTokenExpiry: session?.accessToken?.payload?.exp,
5545
- expires: session?.accessToken?.payload?.exp,
5546
- sub: session?.idToken?.payload?.sub,
5547
- details: {
5548
- userEmail: session?.idToken?.payload?.email,
5549
- firstName: session?.idToken?.payload?.given_name,
5550
- lastName: session?.idToken?.payload?.family_name,
5551
- dateOfBirth: session?.idToken?.payload?.birthdate,
5552
- 'cognito:username': session?.idToken?.payload?.sub,
5553
- 'custom:termsAccepted': session?.idToken?.payload?.['custom:termsAccepted'],
5554
- 'custom:subscriptionId': session?.idToken?.payload?.['custom:subscriptionId'],
5555
- 'custom:contactPreferences': session?.idToken?.payload?.['custom:contactPreferences'],
5556
- 'custom:customerId': session?.idToken?.payload?.['custom:customerId'],
5557
- picture: session?.idToken?.payload?.picture,
5558
- id: toCamelCaseObject(session?.idToken?.payload),
5559
- },
5560
- };
5561
- }
5562
- function formatSocialAuthSession(tokens) {
5563
- const idToken = jwtDecode.jwtDecode(tokens.idToken);
5564
- return {
5565
- socialSignin: true,
5566
- accessToken: tokens.accessToken,
5567
- idToken: tokens.idToken,
5568
- refreshToken: tokens.refreshToken,
5569
- accessTokenExpiry: idToken?.exp,
5570
- expires: idToken?.exp,
5571
- sub: idToken.sub,
5572
- details: {
5573
- userEmail: idToken.email,
5574
- firstName: idToken.given_name,
5575
- lastName: idToken.family_name,
5576
- dateOfBirth: idToken?.birthdate,
5577
- 'cognito:username': idToken?.['cognito:username'],
5578
- 'custom:termsAccepted': idToken?.['custom:termsAccepted'],
5579
- 'custom:subscriptionId': idToken?.['custom:subscriptionId'],
5580
- 'custom:contactPreferences': idToken?.['custom:contactPreferences'],
5581
- 'custom:customerId': idToken?.['custom:customerId'],
5582
- picture: idToken?.picture,
5583
- },
5584
- };
5585
- }
5586
- function formatConfig(data) {
5587
- return data.map((item) => {
5588
- return {
5589
- uuid: item?._source?.uuid?.[0],
5590
- id: item?._source?.uuid?.[0],
5591
- created: item?._source?.created?.[0],
5592
- updated: item?._source?.updated?.[0],
5593
- type: item?._source?.type?.[0],
5594
- cla: item?._source?.cla?.[0],
5595
- enabled: item?._source?.enabled?.[0],
5596
- name: item?._source?.name?.[0],
5597
- price: item?._source?.price?.[0],
5598
- video: item?._source?.video?.[0],
5599
- imageHomepage: item?._source?.image_homepage?.[0],
5600
- imageSectionBanner: item?._source?.image_section_banner?.[0],
5601
- };
5602
- });
5603
- }
5604
- function formatSectionPanels(data) {
5605
- return data.map((item) => {
5606
- return {
5607
- uuid: item?._source?.uuid?.[0],
5608
- id: item?._source?.uuid?.[0],
5609
- title: item?._source?.title?.[0],
5610
- created: item?._source?.created?.[0],
5611
- updated: item?._source?.updated?.[0],
5612
- weight: item?._source?.weight?.[0],
5613
- items: item?._source?.item_uuid,
5614
- type: item?._source?.type?.[0],
5615
- };
5616
- });
5617
- }
5618
- function formatSectionItems(data) {
5619
- return data.map((item) => {
5620
- return {
5621
- uuid: item?._source?.uuid?.[0],
5622
- id: item?._source?.uuid?.[0],
5623
- title: item?._source?.title?.[0],
5624
- created: item?._source?.created?.[0],
5625
- updated: item?._source?.updated?.[0],
5626
- type: item?._source?.type?.[0],
5627
- term: item?._source?.term?.[0],
5628
- image: item?._source?.custom_image_formatted?.[0],
5629
- bannerImage: item?._source?.banner_image_formatted?.[0],
5630
- };
5631
- });
5098
+ /**
5099
+ * Shared helper to extract auth tokens from the Redux store.
5100
+ * Used by all RTK Query services to attach tokens to request headers
5101
+ * without depending on aws-amplify's Auth.currentSession().
5102
+ */
5103
+ function getAuthHeaders(getState) {
5104
+ const state = getState();
5105
+ const accessToken = state?.auth?.user?.accessToken;
5106
+ const idToken = state?.auth?.user?.idToken;
5107
+ return { accessToken, idToken };
5632
5108
  }
5633
- const formatTaxonomies = (data) => {
5634
- return data.map((item) => {
5635
- return {
5636
- uuid: item?._source?.uuid?.[0],
5637
- id: item?._source?.uuid?.[0],
5638
- updated: item?._source?.updated?.[0],
5639
- vocabulary: item?._source?.vocabulary?.[0],
5640
- name: item?._source?.name?.[0],
5641
- description: item?._source?.description?.[0],
5642
- image: item?._source?.image?.[0],
5643
- imageBanner: item?._source?.image_banner?.[0],
5644
- imageBannerTaxonomy: item?._source?.image_banner_taxonomy?.[0],
5645
- imageLarge: item?._source?.image_large_16_9?.[0],
5646
- weight: item?._source?.weight?.[0],
5647
- parentName: item?._source?.parent_name?.[0],
5648
- color: item?._source?.color?.[0],
5649
- };
5650
- });
5651
- };
5652
- const formatSeries = (data) => {
5653
- return data.map((item) => {
5654
- return {
5655
- uuid: item?._source?.uuid?.[0],
5656
- id: item?._source?.uuid?.[0],
5657
- created: item?._source?.created?.[0],
5658
- updated: item?._source?.updated?.[0],
5659
- title: item?._source?.display_title?.[0],
5660
- synopsis: item?._source?.synopsis?.[0],
5661
- imagePoster: item?._source?.image_style_poster?.[0],
5662
- imageThumb: item?._source?.image_style_thumb?.[0],
5663
- category: item?._source?.category?.[0],
5664
- categoryId: item?._source?.category_id?.[0],
5665
- seasons: item?._source?.seasons || [],
5666
- };
5667
- });
5668
- };
5669
- const formatSeasons = (data) => {
5670
- return data.map((item) => {
5671
- return {
5672
- uuid: item?._source?.uuid?.[0],
5673
- id: item?._source?.uuid?.[0],
5674
- created: item?._source?.created?.[0],
5675
- updated: item?._source?.updated?.[0],
5676
- title: item?._source?.display_title?.[0],
5677
- synopsis: item?._source?.synopsis?.[0],
5678
- imagePoster: item?._source?.image_style_poster?.[0],
5679
- imageThumb: item?._source?.image_style_thumb?.[0],
5680
- episodes: item?._source?.episodes || [],
5681
- seasonNumber: item?._source?.season_number?.[0],
5682
- showId: item?._source?.show?.[0],
5683
- };
5684
- });
5685
- };
5686
- const formatLongform = (data) => {
5687
- return data.map((item) => {
5688
- return {
5689
- uuid: item?._source?.uuid?.[0],
5690
- id: item?._source?.uuid?.[0],
5691
- created: item?._source?.created?.[0],
5692
- updated: item?._source?.updated?.[0],
5693
- title: item?._source?.display_title?.[0],
5694
- synopsis: item?._source?.synopsis?.[0],
5695
- imagePoster: item?._source?.image_style_poster?.[0],
5696
- imageThumb: item?._source?.image_style_thumb?.[0],
5697
- duration: item?._source?.duration?.[0],
5698
- releaseDate: item?._source?.release_date?.[0],
5699
- video: item?._source?.video?.[0],
5700
- imageUrl: item?._source?.image_url?.[0],
5701
- episodeNumber: item?._source?.episode_number?.[0],
5702
- };
5703
- });
5704
- };
5705
- const formatMediaItem = (data) => {
5706
- return data.map((item) => {
5707
- return {
5708
- changed: item?._source?.changed?.[0],
5709
- created: item?._source?.created?.[0],
5710
- image: item?._source?.image?.[0],
5711
- customThumbnail: item?._source?.custom_thumbnail?.[0],
5712
- price: item?._source?.price?.[0],
5713
- priceTwoYear: item?._source?.price_2_year?.[0],
5714
- revisionTimestamp: item?._source?.revision_timestamp?.[0],
5715
- sku: item?._source?.sku?.[0],
5716
- status: item?._source?.status?.[0],
5717
- uuid: item?._source?.uuid?.[0],
5718
- description: item?._source?.description?.[0],
5719
- transcript: item?._source?.transcript?.[0],
5720
- entities: item?._source?.entities,
5721
- phrases: item?._source?.phrases,
5722
- video: item?._source?.video?.[0],
5723
- title: item?._source?.title?.[0],
5724
- generatedTitle: item?._source?.generated_title?.[0],
5725
- projectPricing: item?._source?.project_pricing?.[0],
5726
- related_items: item?._source?.related_uuids,
5727
- franchises: item?._source?.franchise_name,
5728
- franchisesIds: item?._source?.franchise_tid,
5729
- original: item?._source?.original?.[0],
5730
- script: item?._source?.script?.[0],
5731
- hideThumbnailTitle: item?._source?.hide_thumbnail_title?.[0],
5732
- };
5733
- });
5734
- };
5735
5109
 
5736
5110
  /**
5737
5111
  * Platform detection utilities for cross-platform React/React Native applications
@@ -5973,55 +5347,146 @@ const createAuthBaseQuery = () => {
5973
5347
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_AUTH_PREFIX
5974
5348
  ? process.env.NEXT_PUBLIC_API_AUTH_PREFIX
5975
5349
  : (API_AUTH_PREFIX || '');
5976
- console.log('[authApi] Resolved baseUrl:', baseUrl);
5977
5350
  return createUnwrappingBaseQuery({
5978
5351
  baseUrl,
5979
- prepareHeaders: async (headers) => {
5352
+ prepareHeaders: (headers, { getState }) => {
5980
5353
  headers.set('Content-Type', 'application/json');
5981
- try {
5982
- // add accessToken to headers from slice using selectAccessToken selector
5983
- const session = await awsAmplify.Auth.currentSession();
5984
- const idToken = session.getIdToken().getJwtToken(); // ID token
5985
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5986
- if (accessToken && idToken) {
5987
- headers.set('accesstoken', accessToken);
5988
- headers.set('idtoken', idToken);
5989
- // headers.set('refreshtoken', tokens.refreshToken);
5990
- }
5991
- return headers;
5992
- }
5993
- catch (error) {
5994
- // eslint-disable-next-line no-console
5995
- console.error('authDataBaseQuery: ', error);
5996
- return headers;
5354
+ const { accessToken, idToken } = getAuthHeaders(getState);
5355
+ if (accessToken && idToken) {
5356
+ headers.set('accesstoken', accessToken);
5357
+ headers.set('idtoken', idToken);
5997
5358
  }
5359
+ return headers;
5998
5360
  },
5999
5361
  credentials: 'include',
6000
5362
  });
6001
5363
  };
6002
5364
  const authDataBaseQuery = createAuthBaseQuery();
6003
5365
  /**
6004
- * This function is used to retry a request if we get a 401 error.
5366
+ * Mutex to prevent multiple concurrent refresh attempts
5367
+ */
5368
+ let isRefreshing = false;
5369
+ let refreshPromise = null;
5370
+ /**
5371
+ * Attempt to refresh the auth token using the refresh token from Redux state.
5372
+ * Returns true if refresh succeeded and tokens were updated.
5373
+ */
5374
+ async function attemptTokenRefresh(api) {
5375
+ const state = api.getState();
5376
+ const refreshToken = state?.auth?.user?.refreshToken;
5377
+ console.debug('[TokenRefresh] Attempting refresh', {
5378
+ hasRefreshToken: !!refreshToken,
5379
+ refreshTokenPreview: refreshToken ? `${refreshToken.substring(0, 20)}...` : 'none',
5380
+ });
5381
+ if (!refreshToken) {
5382
+ console.warn('[TokenRefresh] No refresh token in Redux store — cannot refresh');
5383
+ return false;
5384
+ }
5385
+ // Use the Next.js API route for refresh (proxies to auth microservice)
5386
+ // Falls back to direct auth API if NEXT_PUBLIC_API_PREFIX is not available
5387
+ const refreshUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PREFIX
5388
+ ? `${process.env.NEXT_PUBLIC_API_PREFIX}/auth/refresh-token`
5389
+ : `${API_AUTH_PREFIX || ''}/user/refreshtoken`;
5390
+ try {
5391
+ const response = await fetch(refreshUrl, {
5392
+ method: 'POST',
5393
+ headers: { 'Content-Type': 'application/json' },
5394
+ credentials: 'include',
5395
+ body: JSON.stringify({ refreshtoken: refreshToken }),
5396
+ });
5397
+ if (!response.ok) {
5398
+ const errorBody = await response.text().catch(() => 'unable to read body');
5399
+ console.error('[TokenRefresh] Refresh request failed', {
5400
+ status: response.status,
5401
+ body: errorBody,
5402
+ url: refreshUrl,
5403
+ });
5404
+ return false;
5405
+ }
5406
+ const data = await response.json();
5407
+ // The response may be wrapped in { success: true, data: {...} } or direct
5408
+ const tokenData = data?.data || data;
5409
+ const accessToken = tokenData?.accessToken || tokenData?.AccessToken;
5410
+ const idToken = tokenData?.idToken || tokenData?.IdToken;
5411
+ console.debug('[TokenRefresh] Refresh response parsed', {
5412
+ hasAccessToken: !!accessToken,
5413
+ hasIdToken: !!idToken,
5414
+ dataKeys: Object.keys(tokenData || {}),
5415
+ });
5416
+ if (accessToken && idToken) {
5417
+ console.debug('[TokenRefresh] SUCCESS — dispatching new credentials + syncing cookies');
5418
+ api.dispatch(slice.setCredentials({
5419
+ accessToken,
5420
+ idToken,
5421
+ refreshToken,
5422
+ }));
5423
+ // Sync refreshed tokens to Cognito-format cookies so Next.js middleware sees valid tokens
5424
+ if (typeof window !== 'undefined') {
5425
+ try {
5426
+ const clientId = process.env?.NEXT_PUBLIC_AWS_COGNITO_CLIENT_ID || '';
5427
+ const lastAuthCookie = `CognitoIdentityServiceProvider.${clientId}.LastAuthUser`;
5428
+ const match = document.cookie.match(new RegExp(`(?:^|; )${lastAuthCookie.replace(/\./g, '\\.')}=([^;]*)`));
5429
+ const username = match ? decodeURIComponent(match[1]) : null;
5430
+ if (username && clientId) {
5431
+ const prefix = `CognitoIdentityServiceProvider.${clientId}.${username}`;
5432
+ const setCookie = (name, value) => {
5433
+ document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${30 * 86400}; SameSite=Lax`;
5434
+ };
5435
+ setCookie(`${prefix}.accessToken`, accessToken);
5436
+ setCookie(`${prefix}.idToken`, idToken);
5437
+ }
5438
+ }
5439
+ catch {
5440
+ // Cookie sync is best-effort
5441
+ }
5442
+ }
5443
+ return true;
5444
+ }
5445
+ console.error('[TokenRefresh] Refresh response missing accessToken or idToken');
5446
+ return false;
5447
+ }
5448
+ catch (err) {
5449
+ console.error('[TokenRefresh] Exception during refresh', err);
5450
+ return false;
5451
+ }
5452
+ }
5453
+ /**
5454
+ * This function retries the request after refreshing the token on 401.
5455
+ * If the refresh fails, it dispatches logout.
6005
5456
  */
6006
5457
  const authDataBaseQueryWithReauth = async (args, api, extraOptions) => {
6007
5458
  let result = await authDataBaseQuery(args, api, extraOptions);
6008
- // If we get a 401 error
5459
+ if (result?.error) {
5460
+ const requestUrl = typeof args === 'string' ? args : args?.url;
5461
+ console.debug('[AuthQuery] Request error', {
5462
+ url: requestUrl,
5463
+ status: result.error.status,
5464
+ data: result.error?.data,
5465
+ });
5466
+ }
6009
5467
  if (result?.error?.status === 401) {
6010
- const authSession = await awsAmplify.Auth.currentAuthenticatedUser({
6011
- bypassCache: true, // Ensures that the user is refreshed from the server
5468
+ const requestUrl = typeof args === 'string' ? args : args?.url;
5469
+ console.warn('[TokenRefresh] 401 received, attempting token refresh', {
5470
+ url: requestUrl,
5471
+ errorStatus: result.error.status,
5472
+ isAlreadyRefreshing: isRefreshing,
6012
5473
  });
6013
- const user = formatAuthSession(authSession);
6014
- api.dispatch(slice.setCredentials(user));
6015
- if (authSession?.tokens) {
6016
- // If we get a new access token, retry the original request.
5474
+ // Use mutex to prevent concurrent refreshes
5475
+ if (!isRefreshing) {
5476
+ isRefreshing = true;
5477
+ refreshPromise = attemptTokenRefresh(api).finally(() => {
5478
+ isRefreshing = false;
5479
+ refreshPromise = null;
5480
+ });
5481
+ }
5482
+ const refreshed = await (refreshPromise || attemptTokenRefresh(api));
5483
+ if (refreshed) {
5484
+ console.debug('[TokenRefresh] Refresh succeeded — retrying original request');
6017
5485
  result = await authDataBaseQuery(args, api, extraOptions);
6018
5486
  }
6019
5487
  else {
6020
- // TODO; require full data reset?
6021
- await awsAmplify.Auth.signOut();
5488
+ console.error('[TokenRefresh] Refresh FAILED dispatching logout');
6022
5489
  api.dispatch(slice.logout());
6023
- // If no access token throw error.
6024
- throw new Error('No access token found');
6025
5490
  }
6026
5491
  }
6027
5492
  return result;
@@ -6029,8 +5494,8 @@ const authDataBaseQueryWithReauth = async (args, api, extraOptions) => {
6029
5494
  const authApi = createApi({
6030
5495
  reducerPath: 'authApi',
6031
5496
  baseQuery: authDataBaseQueryWithReauth,
6032
- tagTypes: ['UserToken', 'UserData'],
6033
- // keepUnusedDataFor: 300,
5497
+ tagTypes: ['UserToken', 'UserData', 'Streak', 'WeeklyProgress', 'WatchProgress', 'Recommendations', 'ActivityStats'],
5498
+ keepUnusedDataFor: 300,
6034
5499
  endpoints: (builder) => ({
6035
5500
  resetPassword: builder.mutation({
6036
5501
  query: (data) => ({
@@ -6168,6 +5633,80 @@ const authApi = createApi({
6168
5633
  }),
6169
5634
  invalidatesTags: ['UserData'],
6170
5635
  }),
5636
+ // Dashboard data endpoints
5637
+ getStreak: builder.query({
5638
+ query: (sub) => ({
5639
+ url: `/user/streak?sub=${sub}`,
5640
+ method: 'GET',
5641
+ }),
5642
+ providesTags: ['Streak'],
5643
+ }),
5644
+ getWeeklyProgress: builder.query({
5645
+ query: (sub) => ({
5646
+ url: `/user/weekly-progress?sub=${sub}`,
5647
+ method: 'GET',
5648
+ }),
5649
+ providesTags: ['WeeklyProgress'],
5650
+ }),
5651
+ getWatchProgress: builder.query({
5652
+ query: ({ sub, limit = 1 }) => ({
5653
+ url: `/user/watch-progress?sub=${sub}&limit=${limit}`,
5654
+ method: 'GET',
5655
+ }),
5656
+ providesTags: ['WatchProgress'],
5657
+ }),
5658
+ getRecommendations: builder.query({
5659
+ query: ({ sub, limit = 8 }) => ({
5660
+ url: `/user/recommendations?sub=${sub}&limit=${limit}`,
5661
+ method: 'GET',
5662
+ }),
5663
+ providesTags: ['Recommendations'],
5664
+ }),
5665
+ getActivityStats: builder.query({
5666
+ query: ({ sub, period = 'this-month' }) => ({
5667
+ url: `/user/activity-stats?sub=${sub}&period=${period}`,
5668
+ method: 'GET',
5669
+ }),
5670
+ providesTags: ['ActivityStats'],
5671
+ }),
5672
+ getActiveChallenges: builder.query({
5673
+ query: (sub) => ({
5674
+ url: `/user/active-challenges?sub=${sub}`,
5675
+ method: 'GET',
5676
+ }),
5677
+ providesTags: ['UserData'],
5678
+ }),
5679
+ getChallengeProgress: builder.query({
5680
+ query: ({ sub, challengeId }) => ({
5681
+ url: `/user/challenge-progress/${challengeId}?sub=${sub}`,
5682
+ method: 'GET',
5683
+ }),
5684
+ providesTags: ['UserData'],
5685
+ }),
5686
+ // Activity logging — invalidates dashboard caches
5687
+ logActivity: builder.mutation({
5688
+ query: (data) => ({
5689
+ url: '/activity',
5690
+ method: 'POST',
5691
+ body: data,
5692
+ }),
5693
+ invalidatesTags: (result, error, arg) => {
5694
+ const tags = [];
5695
+ if (arg.type === 'workout_completed') {
5696
+ tags.push('Streak', 'WeeklyProgress', 'Recommendations', 'ActivityStats', 'UserData');
5697
+ }
5698
+ if (arg.type === 'watch_progress') {
5699
+ tags.push('WatchProgress');
5700
+ }
5701
+ if (arg.type === 'workout_liked' || arg.type === 'workout_unliked') {
5702
+ tags.push('Recommendations', 'UserData');
5703
+ }
5704
+ if (arg.type === 'challenge_joined') {
5705
+ tags.push('UserData');
5706
+ }
5707
+ return tags;
5708
+ },
5709
+ }),
6171
5710
  }),
6172
5711
  });
6173
5712
  // Export hooks for usage in functional components.
@@ -6179,7 +5718,7 @@ const {
6179
5718
  // useLogoutQuery,
6180
5719
  // useLazyLogoutQuery,
6181
5720
  useResetPasswordMutation, // Use this for mobile app.
6182
- useResetPasswordAuthMutation, useRegisterMutation, useVerifyUserQuery, useLazyVerifyUserQuery, useGetUserInfoQuery, useLazyGetUserInfoQuery, useUpdateUserInfoMutation, useForgottenPasswordMutation, useVerifyUserAttributesQuery, useLazyVerifyUserAttributesQuery, useVerifyUserResendQuery, useLazyVerifyUserResendQuery, useUpdateUserMutation, } = authApi;
5721
+ useResetPasswordAuthMutation, useRegisterMutation, useVerifyUserQuery, useLazyVerifyUserQuery, useGetUserInfoQuery, useLazyGetUserInfoQuery, useUpdateUserInfoMutation, useForgottenPasswordMutation, useVerifyUserAttributesQuery, useLazyVerifyUserAttributesQuery, useVerifyUserResendQuery, useLazyVerifyUserResendQuery, useUpdateUserMutation, useGetStreakQuery, useLazyGetStreakQuery, useGetWeeklyProgressQuery, useLazyGetWeeklyProgressQuery, useGetWatchProgressQuery, useLazyGetWatchProgressQuery, useGetRecommendationsQuery, useLazyGetRecommendationsQuery, useGetActivityStatsQuery, useLazyGetActivityStatsQuery, useLogActivityMutation, useGetActiveChallengesQuery, useGetChallengeProgressQuery, } = authApi;
6183
5722
 
6184
5723
  // Create dynamic baseQuery that resolves URL at request time
6185
5724
  const createContentBaseQuery = () => {
@@ -6252,16 +5791,12 @@ const dynamicBaseQuery$1 = async (args, api, extraOptions) => {
6252
5791
  : (API_PAYMENTS_PREFIX || '');
6253
5792
  const baseQuery = createUnwrappingBaseQuery({
6254
5793
  baseUrl,
6255
- prepareHeaders: async (headers) => {
5794
+ prepareHeaders: (headers, { getState }) => {
6256
5795
  headers.set('Content-Type', 'application/json');
6257
- // add accessToken to headers from slice using selectAccessToken selector
6258
- const session = await awsAmplify.Auth.currentSession();
6259
- const idToken = session.getIdToken().getJwtToken(); // ID token
6260
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5796
+ const { accessToken, idToken } = getAuthHeaders(getState);
6261
5797
  if (accessToken && idToken) {
6262
5798
  headers.set('accesstoken', accessToken);
6263
5799
  headers.set('idtoken', idToken);
6264
- // headers.set('refreshtoken', tokens.refreshToken);
6265
5800
  }
6266
5801
  return headers;
6267
5802
  },
@@ -6321,21 +5856,12 @@ const dynamicBaseQuery = async (args, api, extraOptions) => {
6321
5856
  : (API_PAYMENTS_PREFIX || '');
6322
5857
  const baseQuery = createUnwrappingBaseQuery({
6323
5858
  baseUrl,
6324
- prepareHeaders: async (headers) => {
5859
+ prepareHeaders: (headers, { getState }) => {
6325
5860
  headers.set('Content-Type', 'application/json');
6326
- // Try to add accessToken to headers, but don't fail if unavailable
6327
- try {
6328
- const session = await awsAmplify.Auth.currentSession();
6329
- const idToken = session.getIdToken().getJwtToken(); // ID token
6330
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
6331
- if (accessToken && idToken) {
6332
- headers.set('accesstoken', accessToken);
6333
- headers.set('idtoken', idToken);
6334
- }
6335
- }
6336
- catch (error) {
6337
- // Authentication not available - this is OK for public endpoints like getProducts
6338
- console.log('Auth not available for products API request');
5861
+ const { accessToken, idToken } = getAuthHeaders(getState);
5862
+ if (accessToken && idToken) {
5863
+ headers.set('accesstoken', accessToken);
5864
+ headers.set('idtoken', idToken);
6339
5865
  }
6340
5866
  return headers;
6341
5867
  },
@@ -6387,16 +5913,12 @@ const createOrdersBaseQuery = () => {
6387
5913
  : (API_ORDERS_PREFIX || '');
6388
5914
  return fetchBaseQuery({
6389
5915
  baseUrl,
6390
- prepareHeaders: async (headers) => {
5916
+ prepareHeaders: (headers, { getState }) => {
6391
5917
  headers.set('Content-Type', 'application/json');
6392
- // add accessToken to headers from slice using selectAccessToken selector
6393
- const session = await awsAmplify.Auth.currentSession();
6394
- const idToken = session.getIdToken().getJwtToken(); // ID token
6395
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5918
+ const { accessToken, idToken } = getAuthHeaders(getState);
6396
5919
  if (accessToken && idToken) {
6397
5920
  headers.set('accesstoken', accessToken);
6398
5921
  headers.set('idtoken', idToken);
6399
- // headers.set('refreshtoken', tokens.refreshToken);
6400
5922
  }
6401
5923
  return headers;
6402
5924
  },
@@ -6408,25 +5930,9 @@ const dataBaseQuery = createOrdersBaseQuery();
6408
5930
  * This function is used to retry a request if we get a 401 error.
6409
5931
  */
6410
5932
  const dataBaseQueryWithReauth = async (args, api, extraOptions) => {
6411
- let result = await dataBaseQuery(args, api, extraOptions);
6412
- // If we get a 401 error
5933
+ const result = await dataBaseQuery(args, api, extraOptions);
6413
5934
  if (result?.error?.status === 401) {
6414
- const authSession = await awsAmplify.Auth.currentAuthenticatedUser({
6415
- bypassCache: true, // Ensures that the user is refreshed from the server
6416
- });
6417
- const user = formatAuthSession(authSession);
6418
- api.dispatch(slice.setCredentials(user));
6419
- if (authSession?.tokens) {
6420
- // If we get a new access token, retry the original request.
6421
- result = await dataBaseQuery(args, api, extraOptions);
6422
- }
6423
- else {
6424
- // TODO; require full data reset?
6425
- await awsAmplify.Auth.signOut();
6426
- api.dispatch(slice.logout());
6427
- // If no access token throw error.
6428
- throw new Error('No access token found');
6429
- }
5935
+ api.dispatch(slice.logout());
6430
5936
  }
6431
5937
  return result;
6432
5938
  };
@@ -6453,7 +5959,7 @@ const ordersApi = createApi({
6453
5959
  */
6454
5960
  getOrders: builder.query({
6455
5961
  query: ({ customerId }) => ({
6456
- url: `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders`,
5962
+ url: `/payment/orders`,
6457
5963
  params: { customerId },
6458
5964
  }),
6459
5965
  providesTags: ['Orders'],
@@ -6462,7 +5968,7 @@ const ordersApi = createApi({
6462
5968
  * Get a single partnership order by ID from Stripe.
6463
5969
  */
6464
5970
  getOrder: builder.query({
6465
- query: (orderId) => `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders/${orderId}`,
5971
+ query: (orderId) => `/payment/orders/${orderId}`,
6466
5972
  providesTags: (_result, _error, orderId) => [{ type: 'Orders', id: orderId }],
6467
5973
  }),
6468
5974
  }),
@@ -6470,6 +5976,39 @@ const ordersApi = createApi({
6470
5976
  // Export hooks for usage in functional components.
6471
5977
  const { useFetchOrdersQuery, useLazyFetchOrdersQuery, useGetOrdersQuery, useGetOrderQuery, } = ordersApi;
6472
5978
 
5979
+ function onlyUnique(value, index, self) {
5980
+ return self.indexOf(value) === index;
5981
+ }
5982
+ function applyCoupon(coupon, netTotal) {
5983
+ const discountedAmount = netTotal * (Number(coupon.discount) / 100);
5984
+ const discountedTotal = netTotal - discountedAmount;
5985
+ const data = {
5986
+ ...coupon,
5987
+ discountedTotal,
5988
+ discountedAmount,
5989
+ };
5990
+ return data;
5991
+ }
5992
+ function applyTax(taxRate, netTotal) {
5993
+ const taxAmount = netTotal * (taxRate.percentage / 100);
5994
+ return taxAmount;
5995
+ }
5996
+ function toCamelCaseObject(obj) {
5997
+ const toCamelCase = (str) => {
5998
+ return str.replace(/([-_][a-z])/gi, (match) => {
5999
+ return match.toUpperCase().replace(/[-_]/, '');
6000
+ });
6001
+ };
6002
+ const camelCaseObject = {};
6003
+ for (const key in obj) {
6004
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
6005
+ const camelKey = toCamelCase(key);
6006
+ camelCaseObject[camelKey] = obj[key];
6007
+ }
6008
+ }
6009
+ return camelCaseObject;
6010
+ }
6011
+
6473
6012
  const initialState = {
6474
6013
  addedItems: [],
6475
6014
  netTotal: 0,
@@ -6635,32 +6174,6 @@ exports.cartSlice = cartSlice;
6635
6174
  exports.contentApi = contentApi;
6636
6175
  exports.createUnwrappingBaseQuery = createUnwrappingBaseQuery;
6637
6176
  exports.emptyCart = emptyCart;
6638
- exports.formatAuthSession = formatAuthSession;
6639
- exports.formatChallengeDays = formatChallengeDays;
6640
- exports.formatChallenges = formatChallenges;
6641
- exports.formatConfig = formatConfig;
6642
- exports.formatFaqs = formatFaqs;
6643
- exports.formatFedaratedSession = formatFedaratedSession;
6644
- exports.formatGuests = formatGuests;
6645
- exports.formatLongform = formatLongform;
6646
- exports.formatMediaItem = formatMediaItem;
6647
- exports.formatPages = formatPages;
6648
- exports.formatPress = formatPress;
6649
- exports.formatPromos = formatPromos;
6650
- exports.formatSchedule = formatSchedule;
6651
- exports.formatSeasons = formatSeasons;
6652
- exports.formatSecondsToISO8601Duration = formatSecondsToISO8601Duration;
6653
- exports.formatSectionItems = formatSectionItems;
6654
- exports.formatSectionPanels = formatSectionPanels;
6655
- exports.formatSections = formatSections;
6656
- exports.formatSeries = formatSeries;
6657
- exports.formatSettings = formatSettings;
6658
- exports.formatShortform = formatShortform;
6659
- exports.formatSocialAuthSession = formatSocialAuthSession;
6660
- exports.formatTaxonomies = formatTaxonomies;
6661
- exports.formatUserPayload = formatUserPayload;
6662
- exports.formatVideos = formatVideos;
6663
- exports.formatWorkout = formatWorkout;
6664
6177
  exports.getPlatform = getPlatform;
6665
6178
  exports.isReactNative = isReactNative;
6666
6179
  exports.isWeb = isWeb;
@@ -6689,16 +6202,29 @@ exports.toggleCart = toggleCart;
6689
6202
  exports.updateCart = updateCart;
6690
6203
  exports.useFetchOrdersQuery = useFetchOrdersQuery;
6691
6204
  exports.useForgottenPasswordMutation = useForgottenPasswordMutation;
6205
+ exports.useGetActiveChallengesQuery = useGetActiveChallengesQuery;
6206
+ exports.useGetActivityStatsQuery = useGetActivityStatsQuery;
6207
+ exports.useGetChallengeProgressQuery = useGetChallengeProgressQuery;
6692
6208
  exports.useGetOrderQuery = useGetOrderQuery;
6693
6209
  exports.useGetOrdersQuery = useGetOrdersQuery;
6694
6210
  exports.useGetProductsQuery = useGetProductsQuery;
6211
+ exports.useGetRecommendationsQuery = useGetRecommendationsQuery;
6212
+ exports.useGetStreakQuery = useGetStreakQuery;
6695
6213
  exports.useGetUserInfoQuery = useGetUserInfoQuery;
6214
+ exports.useGetWatchProgressQuery = useGetWatchProgressQuery;
6215
+ exports.useGetWeeklyProgressQuery = useGetWeeklyProgressQuery;
6696
6216
  exports.useLazyFetchOrdersQuery = useLazyFetchOrdersQuery;
6217
+ exports.useLazyGetActivityStatsQuery = useLazyGetActivityStatsQuery;
6697
6218
  exports.useLazyGetProductsQuery = useLazyGetProductsQuery;
6219
+ exports.useLazyGetRecommendationsQuery = useLazyGetRecommendationsQuery;
6220
+ exports.useLazyGetStreakQuery = useLazyGetStreakQuery;
6698
6221
  exports.useLazyGetUserInfoQuery = useLazyGetUserInfoQuery;
6222
+ exports.useLazyGetWatchProgressQuery = useLazyGetWatchProgressQuery;
6223
+ exports.useLazyGetWeeklyProgressQuery = useLazyGetWeeklyProgressQuery;
6699
6224
  exports.useLazyVerifyUserAttributesQuery = useLazyVerifyUserAttributesQuery;
6700
6225
  exports.useLazyVerifyUserQuery = useLazyVerifyUserQuery;
6701
6226
  exports.useLazyVerifyUserResendQuery = useLazyVerifyUserResendQuery;
6227
+ exports.useLogActivityMutation = useLogActivityMutation;
6702
6228
  exports.usePurchaseProductMutation = usePurchaseProductMutation;
6703
6229
  exports.useRegisterMutation = useRegisterMutation;
6704
6230
  exports.useResetPasswordAuthMutation = useResetPasswordAuthMutation;
@@ -6708,4 +6234,4 @@ exports.useUpdateUserMutation = useUpdateUserMutation;
6708
6234
  exports.useVerifyUserAttributesQuery = useVerifyUserAttributesQuery;
6709
6235
  exports.useVerifyUserQuery = useVerifyUserQuery;
6710
6236
  exports.useVerifyUserResendQuery = useVerifyUserResendQuery;
6711
- //# sourceMappingURL=slice-CJ4WSj5p.js.map
6237
+ //# sourceMappingURL=slice-C4MKCa5N.js.map