@namiml/expo-sdk 3.4.0-dev.202605060437

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 (60) hide show
  1. package/dist/index.cjs +4000 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.ts +151 -0
  4. package/dist/index.mjs +3966 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/nami-expo-nami-iap.tgz +0 -0
  7. package/package.json +92 -0
  8. package/src/adapters/expo-device.adapter.ts +106 -0
  9. package/src/adapters/expo-purchase.adapter.ts +79 -0
  10. package/src/adapters/expo-storage.adapter.ts +92 -0
  11. package/src/adapters/expo-ui.adapter.ts +57 -0
  12. package/src/adapters/index.ts +33 -0
  13. package/src/amazon-kepler.d.ts +7 -0
  14. package/src/components/NamiView.tsx +1006 -0
  15. package/src/components/PaywallScreen.tsx +245 -0
  16. package/src/components/TemplateRenderer.tsx +243 -0
  17. package/src/components/containers/NamiBackgroundContainer.tsx +103 -0
  18. package/src/components/containers/NamiCarousel.tsx +217 -0
  19. package/src/components/containers/NamiCollapseContainer.tsx +116 -0
  20. package/src/components/containers/NamiContainer.tsx +315 -0
  21. package/src/components/containers/NamiContentContainer.tsx +140 -0
  22. package/src/components/containers/NamiFooter.tsx +35 -0
  23. package/src/components/containers/NamiHeader.tsx +45 -0
  24. package/src/components/containers/NamiProductContainer.tsx +248 -0
  25. package/src/components/containers/NamiRepeatingGrid.tsx +81 -0
  26. package/src/components/containers/NamiResponsiveGrid.tsx +75 -0
  27. package/src/components/containers/NamiStack.tsx +69 -0
  28. package/src/components/elements/NamiButton.tsx +285 -0
  29. package/src/components/elements/NamiCountdownTimer.tsx +123 -0
  30. package/src/components/elements/NamiImage.tsx +177 -0
  31. package/src/components/elements/NamiPlayPauseButton.tsx +93 -0
  32. package/src/components/elements/NamiProgressBar.tsx +90 -0
  33. package/src/components/elements/NamiProgressIndicator.tsx +41 -0
  34. package/src/components/elements/NamiQRCode.tsx +51 -0
  35. package/src/components/elements/NamiRadioButton.tsx +62 -0
  36. package/src/components/elements/NamiSegmentPicker.tsx +67 -0
  37. package/src/components/elements/NamiSegmentPickerItem.tsx +184 -0
  38. package/src/components/elements/NamiSpacer.tsx +23 -0
  39. package/src/components/elements/NamiSymbol.tsx +104 -0
  40. package/src/components/elements/NamiText.tsx +311 -0
  41. package/src/components/elements/NamiToggleButton.tsx +102 -0
  42. package/src/components/elements/NamiToggleSwitch.tsx +64 -0
  43. package/src/components/elements/NamiVideo.kepler.tsx +638 -0
  44. package/src/components/elements/NamiVideo.tsx +133 -0
  45. package/src/components/elements/NamiVolumeButton.tsx +93 -0
  46. package/src/context/FocusContext.tsx +169 -0
  47. package/src/context/PaywallContext.tsx +343 -0
  48. package/src/global.d.ts +5 -0
  49. package/src/index.ts +62 -0
  50. package/src/nami.ts +24 -0
  51. package/src/react-native-qrcode-svg.d.ts +4 -0
  52. package/src/utils/actionHandler.ts +281 -0
  53. package/src/utils/fonts.ts +359 -0
  54. package/src/utils/iconMap.ts +67 -0
  55. package/src/utils/impression.ts +39 -0
  56. package/src/utils/rendering.ts +197 -0
  57. package/src/utils/smartText.ts +148 -0
  58. package/src/utils/styles.ts +668 -0
  59. package/src/utils/tvFocus.ts +31 -0
  60. package/src/utils/videoControls.ts +49 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,3966 @@
1
+ import { NAMI_SDK_PACKAGE_VERSION, registerPlatformAdapters, registerPurchaseAdapter, logger, Nami as Nami$1, PaywallState, initialState, getUrlParams, SMART_TEXT_PATTERN, VAR_REGEX, LIQUID_VARIABLE_REGEX, isAnonymousMode, NamiAPI, storageService, getDeviceScaleFactor, NamiEventEmitter, PAYWALL_ACTION_EVENT, NamiPaywallAction, NamiReservedActions, isNamiFlowCampaign, NamiFlowManager, hasAllPaywalls, getPaywallDataFromLabel, getPaywall } from '@namiml/sdk-core';
2
+ export { NamiCampaignManager, NamiCustomerManager, NamiEntitlementManager, NamiFlowManager, NamiPaywallManager, NamiProfileManager } from '@namiml/sdk-core';
3
+ import { Platform, Dimensions, StyleSheet, View, ScrollView, ImageBackground, BackHandler, ActivityIndicator, SafeAreaView, StatusBar, Animated } from 'react-native';
4
+ import require$$0, { createContext, useRef, useState, useEffect, useMemo, useContext, useCallback, useLayoutEffect } from 'react';
5
+
6
+ class ExpoStorageAdapter {
7
+ constructor() {
8
+ this.db = null;
9
+ this.memoryFallback = null;
10
+ try {
11
+ const { openDatabaseSync } = require('expo-sqlite');
12
+ const database = openDatabaseSync('nami-sdk-storage');
13
+ database.runSync('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)');
14
+ this.db = database;
15
+ }
16
+ catch {
17
+ this.memoryFallback = new Map();
18
+ }
19
+ }
20
+ getItem(key) {
21
+ if (this.memoryFallback)
22
+ return this.memoryFallback.get(key) ?? null;
23
+ const database = this.db;
24
+ if (!database)
25
+ return null;
26
+ try {
27
+ const row = database.getFirstSync('SELECT value FROM kv WHERE key = ?', [key]);
28
+ return row?.value ?? null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ setItem(key, value) {
35
+ if (this.memoryFallback) {
36
+ this.memoryFallback.set(key, value);
37
+ return;
38
+ }
39
+ const database = this.db;
40
+ if (!database)
41
+ return;
42
+ try {
43
+ database.runSync('INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)', [key, value]);
44
+ }
45
+ catch {
46
+ /* silent */
47
+ }
48
+ }
49
+ removeItem(key) {
50
+ if (this.memoryFallback) {
51
+ this.memoryFallback.delete(key);
52
+ return;
53
+ }
54
+ const database = this.db;
55
+ if (!database)
56
+ return;
57
+ try {
58
+ database.runSync('DELETE FROM kv WHERE key = ?', [key]);
59
+ }
60
+ catch {
61
+ /* silent */
62
+ }
63
+ }
64
+ clear() {
65
+ if (this.memoryFallback) {
66
+ this.memoryFallback.clear();
67
+ return;
68
+ }
69
+ const database = this.db;
70
+ if (!database)
71
+ return;
72
+ try {
73
+ database.runSync('DELETE FROM kv');
74
+ }
75
+ catch {
76
+ /* silent */
77
+ }
78
+ }
79
+ getAllKeys() {
80
+ if (this.memoryFallback)
81
+ return [...this.memoryFallback.keys()];
82
+ const database = this.db;
83
+ if (!database)
84
+ return [];
85
+ try {
86
+ const rows = database.getAllSync('SELECT key FROM kv');
87
+ return rows.map((row) => row.key).filter((key) => typeof key === 'string');
88
+ }
89
+ catch {
90
+ return [];
91
+ }
92
+ }
93
+ }
94
+
95
+ function getExpoDevice() { return require('expo-device'); }
96
+ function getExpoConstants() { return require('expo-constants').default; }
97
+ function getExpoLocalization() { return require('expo-localization'); }
98
+ const SDK_CLIENT = 'expo';
99
+ const TV_SCALE_FACTORS = {
100
+ 720: 0.67,
101
+ 1080: 1,
102
+ 1440: 1.5,
103
+ 2160: 2,
104
+ };
105
+ class ExpoDeviceAdapter {
106
+ getDeviceData() {
107
+ let osName = Platform.OS;
108
+ let osVersion = String(Platform.Version);
109
+ let deviceModel;
110
+ try {
111
+ const device = getExpoDevice();
112
+ if (device) {
113
+ osName = device.osName ?? osName;
114
+ osVersion = device.osVersion ?? osVersion;
115
+ deviceModel = device.modelName ?? device.modelId;
116
+ }
117
+ }
118
+ catch { /* expo-device unavailable */ }
119
+ return {
120
+ os_name: osName,
121
+ os_version: osVersion,
122
+ browser_name: '',
123
+ browser_version: '',
124
+ sdk_client: SDK_CLIENT,
125
+ sdk_version: NAMI_SDK_PACKAGE_VERSION,
126
+ language: this.getLanguage(),
127
+ ...(deviceModel ? { device_model: deviceModel } : {}),
128
+ extended_platform: 'expo',
129
+ extended_platform_version: this.getExpoVersion(),
130
+ };
131
+ }
132
+ getExpoVersion() {
133
+ try {
134
+ const constants = getExpoConstants();
135
+ return constants?.expoConfig?.sdkVersion ?? '';
136
+ }
137
+ catch {
138
+ return '';
139
+ }
140
+ }
141
+ getDeviceFormFactor() {
142
+ try {
143
+ const device = getExpoDevice();
144
+ const deviceType = device?.deviceType;
145
+ const DeviceType = device?.DeviceType;
146
+ if (DeviceType && deviceType === DeviceType.TV)
147
+ return 'television';
148
+ if (DeviceType && deviceType === DeviceType.TABLET)
149
+ return 'tablet';
150
+ }
151
+ catch {
152
+ // expo-device may not be available (e.g., Expo Go without native modules)
153
+ }
154
+ return 'phone';
155
+ }
156
+ getDeviceScaleFactor(formFactor) {
157
+ const ff = formFactor ?? this.getDeviceFormFactor();
158
+ if (ff !== 'television')
159
+ return 1;
160
+ const { height } = Dimensions.get('window');
161
+ const closest = Object.keys(TV_SCALE_FACTORS)
162
+ .map(Number)
163
+ .reduce((prev, curr) => Math.abs(curr - height) < Math.abs(prev - height) ? curr : prev);
164
+ return TV_SCALE_FACTORS[closest] ?? 1;
165
+ }
166
+ generateUUID() {
167
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
168
+ const r = (Math.random() * 16) | 0;
169
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
170
+ return v.toString(16);
171
+ });
172
+ }
173
+ getScreenInfo() {
174
+ const { width, height, scale } = Dimensions.get('window');
175
+ return { width, height, scale };
176
+ }
177
+ getLanguage() {
178
+ try {
179
+ const { getLocales } = getExpoLocalization();
180
+ const locales = getLocales();
181
+ return locales?.[0]?.languageCode ?? 'en';
182
+ }
183
+ catch {
184
+ return 'en';
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Expo UI adapter.
191
+ * Uses a listener pattern so the Expo PaywallView component can register
192
+ * itself to receive create/reRender/flowNav events from the core SDK.
193
+ */
194
+ class ExpoUIAdapter {
195
+ constructor() {
196
+ this.paywallListener = null;
197
+ this.reRenderListener = null;
198
+ this.flowNavListener = null;
199
+ }
200
+ onPaywallRequested(listener) {
201
+ this.paywallListener = listener;
202
+ return () => { this.paywallListener = null; };
203
+ }
204
+ onReRenderRequested(listener) {
205
+ this.reRenderListener = listener;
206
+ return () => { this.reRenderListener = null; };
207
+ }
208
+ onFlowNavigationRequested(listener) {
209
+ this.flowNavListener = listener;
210
+ return () => { this.flowNavListener = null; };
211
+ }
212
+ createPaywall(type, value, context) {
213
+ // In Expo, we don't create a DOM element. Instead, we notify the
214
+ // registered PaywallView component to present the paywall.
215
+ // The PaywallView resolves the paywall data using the same core logic.
216
+ if (this.paywallListener) {
217
+ // Build minimal paywall info for navigation
218
+ const paywallInfo = { type, value, context };
219
+ this.paywallListener(paywallInfo, context);
220
+ }
221
+ return { type, value, context };
222
+ }
223
+ reRenderPaywall() {
224
+ this.reRenderListener?.();
225
+ }
226
+ flowNavigateToScreen(paywall, options) {
227
+ this.flowNavListener?.(paywall, options);
228
+ }
229
+ }
230
+
231
+ function getExpoNamiIap() {
232
+ return require('@namiml/expo-nami-iap');
233
+ }
234
+ function getPurchaseErrorMessage(error) {
235
+ if (error instanceof Error && error.message) {
236
+ return error.message;
237
+ }
238
+ if (typeof error === 'object' && error && 'message' in error) {
239
+ const message = error.message;
240
+ if (typeof message === 'string' && message.length > 0) {
241
+ return message;
242
+ }
243
+ }
244
+ return 'Purchase failed';
245
+ }
246
+ class ExpoPurchaseAdapter {
247
+ async getProducts(skuIds) {
248
+ const { initConnection, getProducts } = getExpoNamiIap();
249
+ await initConnection();
250
+ return getProducts(skuIds);
251
+ }
252
+ async purchase(skuId, context) {
253
+ const { initConnection, purchase } = getExpoNamiIap();
254
+ await initConnection();
255
+ try {
256
+ const tx = await purchase({
257
+ skuId,
258
+ offerId: context?.offerId,
259
+ appAccountToken: context?.appAccountToken,
260
+ });
261
+ return {
262
+ success: true,
263
+ transactionId: tx.transactionId,
264
+ receipt: tx.receipt,
265
+ skuId: tx.skuId,
266
+ };
267
+ }
268
+ catch (error) {
269
+ return { success: false, skuId, message: getPurchaseErrorMessage(error) };
270
+ }
271
+ }
272
+ async restorePurchases() {
273
+ const { initConnection, restorePurchases } = getExpoNamiIap();
274
+ await initConnection();
275
+ const txs = await restorePurchases();
276
+ return txs.map((t) => ({ success: true, transactionId: t.transactionId, receipt: t.receipt, skuId: t.skuId }));
277
+ }
278
+ }
279
+
280
+ const expoUIAdapter = new ExpoUIAdapter();
281
+ let adaptersRegistered = false;
282
+ function registerExpoAdapters() {
283
+ if (adaptersRegistered) {
284
+ return;
285
+ }
286
+ try {
287
+ registerPlatformAdapters({
288
+ storage: new ExpoStorageAdapter(),
289
+ device: new ExpoDeviceAdapter(),
290
+ ui: expoUIAdapter,
291
+ });
292
+ registerPurchaseAdapter(new ExpoPurchaseAdapter());
293
+ adaptersRegistered = true;
294
+ }
295
+ catch (error) {
296
+ logger.warn('[NamiExpo] Failed to register Expo adapters.', error);
297
+ }
298
+ }
299
+ registerExpoAdapters();
300
+
301
+ class Nami {
302
+ static get sdkVersion() {
303
+ return Nami$1.sdkVersion();
304
+ }
305
+ static sdkPackageVersion() {
306
+ return Nami$1.sdkPackageVersion();
307
+ }
308
+ static async configure(config) {
309
+ return Nami$1.configure(config);
310
+ }
311
+ static async reset() {
312
+ await Nami$1.reset?.();
313
+ }
314
+ }
315
+
316
+ var jsxRuntime = {exports: {}};
317
+
318
+ var reactJsxRuntime_production_min = {};
319
+
320
+ /**
321
+ * @license React
322
+ * react-jsx-runtime.production.min.js
323
+ *
324
+ * Copyright (c) Facebook, Inc. and its affiliates.
325
+ *
326
+ * This source code is licensed under the MIT license found in the
327
+ * LICENSE file in the root directory of this source tree.
328
+ */
329
+
330
+ var hasRequiredReactJsxRuntime_production_min;
331
+
332
+ function requireReactJsxRuntime_production_min () {
333
+ if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
334
+ hasRequiredReactJsxRuntime_production_min = 1;
335
+ var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:true,ref:true,__self:true,__source:true};
336
+ function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a) void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
337
+ return reactJsxRuntime_production_min;
338
+ }
339
+
340
+ var reactJsxRuntime_development = {};
341
+
342
+ /**
343
+ * @license React
344
+ * react-jsx-runtime.development.js
345
+ *
346
+ * Copyright (c) Facebook, Inc. and its affiliates.
347
+ *
348
+ * This source code is licensed under the MIT license found in the
349
+ * LICENSE file in the root directory of this source tree.
350
+ */
351
+
352
+ var hasRequiredReactJsxRuntime_development;
353
+
354
+ function requireReactJsxRuntime_development () {
355
+ if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
356
+ hasRequiredReactJsxRuntime_development = 1;
357
+
358
+ if (process.env.NODE_ENV !== "production") {
359
+ (function() {
360
+
361
+ var React = require$$0;
362
+
363
+ // ATTENTION
364
+ // When adding new symbols to this file,
365
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
366
+ // The Symbol used to tag the ReactElement-like types.
367
+ var REACT_ELEMENT_TYPE = Symbol.for('react.element');
368
+ var REACT_PORTAL_TYPE = Symbol.for('react.portal');
369
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
370
+ var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
371
+ var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
372
+ var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
373
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
374
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
375
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
376
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
377
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
378
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
379
+ var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
380
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
381
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
382
+ function getIteratorFn(maybeIterable) {
383
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
384
+ return null;
385
+ }
386
+
387
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
388
+
389
+ if (typeof maybeIterator === 'function') {
390
+ return maybeIterator;
391
+ }
392
+
393
+ return null;
394
+ }
395
+
396
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
397
+
398
+ function error(format) {
399
+ {
400
+ {
401
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
402
+ args[_key2 - 1] = arguments[_key2];
403
+ }
404
+
405
+ printWarning('error', format, args);
406
+ }
407
+ }
408
+ }
409
+
410
+ function printWarning(level, format, args) {
411
+ // When changing this logic, you might want to also
412
+ // update consoleWithStackDev.www.js as well.
413
+ {
414
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
415
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
416
+
417
+ if (stack !== '') {
418
+ format += '%s';
419
+ args = args.concat([stack]);
420
+ } // eslint-disable-next-line react-internal/safe-string-coercion
421
+
422
+
423
+ var argsWithFormat = args.map(function (item) {
424
+ return String(item);
425
+ }); // Careful: RN currently depends on this prefix
426
+
427
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
428
+ // breaks IE9: https://github.com/facebook/react/issues/13610
429
+ // eslint-disable-next-line react-internal/no-production-logging
430
+
431
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
432
+ }
433
+ }
434
+
435
+ // -----------------------------------------------------------------------------
436
+
437
+ var enableScopeAPI = false; // Experimental Create Event Handle API.
438
+ var enableCacheElement = false;
439
+ var enableTransitionTracing = false; // No known bugs, but needs performance testing
440
+
441
+ var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
442
+ // stuff. Intended to enable React core members to more easily debug scheduling
443
+ // issues in DEV builds.
444
+
445
+ var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
446
+
447
+ var REACT_MODULE_REFERENCE;
448
+
449
+ {
450
+ REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
451
+ }
452
+
453
+ function isValidElementType(type) {
454
+ if (typeof type === 'string' || typeof type === 'function') {
455
+ return true;
456
+ } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
457
+
458
+
459
+ if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
460
+ return true;
461
+ }
462
+
463
+ if (typeof type === 'object' && type !== null) {
464
+ if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
465
+ // types supported by any Flight configuration anywhere since
466
+ // we don't know which Flight build this will end up being used
467
+ // with.
468
+ type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
469
+ return true;
470
+ }
471
+ }
472
+
473
+ return false;
474
+ }
475
+
476
+ function getWrappedName(outerType, innerType, wrapperName) {
477
+ var displayName = outerType.displayName;
478
+
479
+ if (displayName) {
480
+ return displayName;
481
+ }
482
+
483
+ var functionName = innerType.displayName || innerType.name || '';
484
+ return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
485
+ } // Keep in sync with react-reconciler/getComponentNameFromFiber
486
+
487
+
488
+ function getContextName(type) {
489
+ return type.displayName || 'Context';
490
+ } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
491
+
492
+
493
+ function getComponentNameFromType(type) {
494
+ if (type == null) {
495
+ // Host root, text node or just invalid type.
496
+ return null;
497
+ }
498
+
499
+ {
500
+ if (typeof type.tag === 'number') {
501
+ error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
502
+ }
503
+ }
504
+
505
+ if (typeof type === 'function') {
506
+ return type.displayName || type.name || null;
507
+ }
508
+
509
+ if (typeof type === 'string') {
510
+ return type;
511
+ }
512
+
513
+ switch (type) {
514
+ case REACT_FRAGMENT_TYPE:
515
+ return 'Fragment';
516
+
517
+ case REACT_PORTAL_TYPE:
518
+ return 'Portal';
519
+
520
+ case REACT_PROFILER_TYPE:
521
+ return 'Profiler';
522
+
523
+ case REACT_STRICT_MODE_TYPE:
524
+ return 'StrictMode';
525
+
526
+ case REACT_SUSPENSE_TYPE:
527
+ return 'Suspense';
528
+
529
+ case REACT_SUSPENSE_LIST_TYPE:
530
+ return 'SuspenseList';
531
+
532
+ }
533
+
534
+ if (typeof type === 'object') {
535
+ switch (type.$$typeof) {
536
+ case REACT_CONTEXT_TYPE:
537
+ var context = type;
538
+ return getContextName(context) + '.Consumer';
539
+
540
+ case REACT_PROVIDER_TYPE:
541
+ var provider = type;
542
+ return getContextName(provider._context) + '.Provider';
543
+
544
+ case REACT_FORWARD_REF_TYPE:
545
+ return getWrappedName(type, type.render, 'ForwardRef');
546
+
547
+ case REACT_MEMO_TYPE:
548
+ var outerName = type.displayName || null;
549
+
550
+ if (outerName !== null) {
551
+ return outerName;
552
+ }
553
+
554
+ return getComponentNameFromType(type.type) || 'Memo';
555
+
556
+ case REACT_LAZY_TYPE:
557
+ {
558
+ var lazyComponent = type;
559
+ var payload = lazyComponent._payload;
560
+ var init = lazyComponent._init;
561
+
562
+ try {
563
+ return getComponentNameFromType(init(payload));
564
+ } catch (x) {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ // eslint-disable-next-line no-fallthrough
570
+ }
571
+ }
572
+
573
+ return null;
574
+ }
575
+
576
+ var assign = Object.assign;
577
+
578
+ // Helpers to patch console.logs to avoid logging during side-effect free
579
+ // replaying on render function. This currently only patches the object
580
+ // lazily which won't cover if the log function was extracted eagerly.
581
+ // We could also eagerly patch the method.
582
+ var disabledDepth = 0;
583
+ var prevLog;
584
+ var prevInfo;
585
+ var prevWarn;
586
+ var prevError;
587
+ var prevGroup;
588
+ var prevGroupCollapsed;
589
+ var prevGroupEnd;
590
+
591
+ function disabledLog() {}
592
+
593
+ disabledLog.__reactDisabledLog = true;
594
+ function disableLogs() {
595
+ {
596
+ if (disabledDepth === 0) {
597
+ /* eslint-disable react-internal/no-production-logging */
598
+ prevLog = console.log;
599
+ prevInfo = console.info;
600
+ prevWarn = console.warn;
601
+ prevError = console.error;
602
+ prevGroup = console.group;
603
+ prevGroupCollapsed = console.groupCollapsed;
604
+ prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
605
+
606
+ var props = {
607
+ configurable: true,
608
+ enumerable: true,
609
+ value: disabledLog,
610
+ writable: true
611
+ }; // $FlowFixMe Flow thinks console is immutable.
612
+
613
+ Object.defineProperties(console, {
614
+ info: props,
615
+ log: props,
616
+ warn: props,
617
+ error: props,
618
+ group: props,
619
+ groupCollapsed: props,
620
+ groupEnd: props
621
+ });
622
+ /* eslint-enable react-internal/no-production-logging */
623
+ }
624
+
625
+ disabledDepth++;
626
+ }
627
+ }
628
+ function reenableLogs() {
629
+ {
630
+ disabledDepth--;
631
+
632
+ if (disabledDepth === 0) {
633
+ /* eslint-disable react-internal/no-production-logging */
634
+ var props = {
635
+ configurable: true,
636
+ enumerable: true,
637
+ writable: true
638
+ }; // $FlowFixMe Flow thinks console is immutable.
639
+
640
+ Object.defineProperties(console, {
641
+ log: assign({}, props, {
642
+ value: prevLog
643
+ }),
644
+ info: assign({}, props, {
645
+ value: prevInfo
646
+ }),
647
+ warn: assign({}, props, {
648
+ value: prevWarn
649
+ }),
650
+ error: assign({}, props, {
651
+ value: prevError
652
+ }),
653
+ group: assign({}, props, {
654
+ value: prevGroup
655
+ }),
656
+ groupCollapsed: assign({}, props, {
657
+ value: prevGroupCollapsed
658
+ }),
659
+ groupEnd: assign({}, props, {
660
+ value: prevGroupEnd
661
+ })
662
+ });
663
+ /* eslint-enable react-internal/no-production-logging */
664
+ }
665
+
666
+ if (disabledDepth < 0) {
667
+ error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
668
+ }
669
+ }
670
+ }
671
+
672
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
673
+ var prefix;
674
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
675
+ {
676
+ if (prefix === undefined) {
677
+ // Extract the VM specific prefix used by each line.
678
+ try {
679
+ throw Error();
680
+ } catch (x) {
681
+ var match = x.stack.trim().match(/\n( *(at )?)/);
682
+ prefix = match && match[1] || '';
683
+ }
684
+ } // We use the prefix to ensure our stacks line up with native stack frames.
685
+
686
+
687
+ return '\n' + prefix + name;
688
+ }
689
+ }
690
+ var reentry = false;
691
+ var componentFrameCache;
692
+
693
+ {
694
+ var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
695
+ componentFrameCache = new PossiblyWeakMap();
696
+ }
697
+
698
+ function describeNativeComponentFrame(fn, construct) {
699
+ // If something asked for a stack inside a fake render, it should get ignored.
700
+ if ( !fn || reentry) {
701
+ return '';
702
+ }
703
+
704
+ {
705
+ var frame = componentFrameCache.get(fn);
706
+
707
+ if (frame !== undefined) {
708
+ return frame;
709
+ }
710
+ }
711
+
712
+ var control;
713
+ reentry = true;
714
+ var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
715
+
716
+ Error.prepareStackTrace = undefined;
717
+ var previousDispatcher;
718
+
719
+ {
720
+ previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
721
+ // for warnings.
722
+
723
+ ReactCurrentDispatcher.current = null;
724
+ disableLogs();
725
+ }
726
+
727
+ try {
728
+ // This should throw.
729
+ if (construct) {
730
+ // Something should be setting the props in the constructor.
731
+ var Fake = function () {
732
+ throw Error();
733
+ }; // $FlowFixMe
734
+
735
+
736
+ Object.defineProperty(Fake.prototype, 'props', {
737
+ set: function () {
738
+ // We use a throwing setter instead of frozen or non-writable props
739
+ // because that won't throw in a non-strict mode function.
740
+ throw Error();
741
+ }
742
+ });
743
+
744
+ if (typeof Reflect === 'object' && Reflect.construct) {
745
+ // We construct a different control for this case to include any extra
746
+ // frames added by the construct call.
747
+ try {
748
+ Reflect.construct(Fake, []);
749
+ } catch (x) {
750
+ control = x;
751
+ }
752
+
753
+ Reflect.construct(fn, [], Fake);
754
+ } else {
755
+ try {
756
+ Fake.call();
757
+ } catch (x) {
758
+ control = x;
759
+ }
760
+
761
+ fn.call(Fake.prototype);
762
+ }
763
+ } else {
764
+ try {
765
+ throw Error();
766
+ } catch (x) {
767
+ control = x;
768
+ }
769
+
770
+ fn();
771
+ }
772
+ } catch (sample) {
773
+ // This is inlined manually because closure doesn't do it for us.
774
+ if (sample && control && typeof sample.stack === 'string') {
775
+ // This extracts the first frame from the sample that isn't also in the control.
776
+ // Skipping one frame that we assume is the frame that calls the two.
777
+ var sampleLines = sample.stack.split('\n');
778
+ var controlLines = control.stack.split('\n');
779
+ var s = sampleLines.length - 1;
780
+ var c = controlLines.length - 1;
781
+
782
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
783
+ // We expect at least one stack frame to be shared.
784
+ // Typically this will be the root most one. However, stack frames may be
785
+ // cut off due to maximum stack limits. In this case, one maybe cut off
786
+ // earlier than the other. We assume that the sample is longer or the same
787
+ // and there for cut off earlier. So we should find the root most frame in
788
+ // the sample somewhere in the control.
789
+ c--;
790
+ }
791
+
792
+ for (; s >= 1 && c >= 0; s--, c--) {
793
+ // Next we find the first one that isn't the same which should be the
794
+ // frame that called our sample function and the control.
795
+ if (sampleLines[s] !== controlLines[c]) {
796
+ // In V8, the first line is describing the message but other VMs don't.
797
+ // If we're about to return the first line, and the control is also on the same
798
+ // line, that's a pretty good indicator that our sample threw at same line as
799
+ // the control. I.e. before we entered the sample frame. So we ignore this result.
800
+ // This can happen if you passed a class to function component, or non-function.
801
+ if (s !== 1 || c !== 1) {
802
+ do {
803
+ s--;
804
+ c--; // We may still have similar intermediate frames from the construct call.
805
+ // The next one that isn't the same should be our match though.
806
+
807
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
808
+ // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
809
+ var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
810
+ // but we have a user-provided "displayName"
811
+ // splice it in to make the stack more readable.
812
+
813
+
814
+ if (fn.displayName && _frame.includes('<anonymous>')) {
815
+ _frame = _frame.replace('<anonymous>', fn.displayName);
816
+ }
817
+
818
+ {
819
+ if (typeof fn === 'function') {
820
+ componentFrameCache.set(fn, _frame);
821
+ }
822
+ } // Return the line we found.
823
+
824
+
825
+ return _frame;
826
+ }
827
+ } while (s >= 1 && c >= 0);
828
+ }
829
+
830
+ break;
831
+ }
832
+ }
833
+ }
834
+ } finally {
835
+ reentry = false;
836
+
837
+ {
838
+ ReactCurrentDispatcher.current = previousDispatcher;
839
+ reenableLogs();
840
+ }
841
+
842
+ Error.prepareStackTrace = previousPrepareStackTrace;
843
+ } // Fallback to just using the name if we couldn't make it throw.
844
+
845
+
846
+ var name = fn ? fn.displayName || fn.name : '';
847
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
848
+
849
+ {
850
+ if (typeof fn === 'function') {
851
+ componentFrameCache.set(fn, syntheticFrame);
852
+ }
853
+ }
854
+
855
+ return syntheticFrame;
856
+ }
857
+ function describeFunctionComponentFrame(fn, source, ownerFn) {
858
+ {
859
+ return describeNativeComponentFrame(fn, false);
860
+ }
861
+ }
862
+
863
+ function shouldConstruct(Component) {
864
+ var prototype = Component.prototype;
865
+ return !!(prototype && prototype.isReactComponent);
866
+ }
867
+
868
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
869
+
870
+ if (type == null) {
871
+ return '';
872
+ }
873
+
874
+ if (typeof type === 'function') {
875
+ {
876
+ return describeNativeComponentFrame(type, shouldConstruct(type));
877
+ }
878
+ }
879
+
880
+ if (typeof type === 'string') {
881
+ return describeBuiltInComponentFrame(type);
882
+ }
883
+
884
+ switch (type) {
885
+ case REACT_SUSPENSE_TYPE:
886
+ return describeBuiltInComponentFrame('Suspense');
887
+
888
+ case REACT_SUSPENSE_LIST_TYPE:
889
+ return describeBuiltInComponentFrame('SuspenseList');
890
+ }
891
+
892
+ if (typeof type === 'object') {
893
+ switch (type.$$typeof) {
894
+ case REACT_FORWARD_REF_TYPE:
895
+ return describeFunctionComponentFrame(type.render);
896
+
897
+ case REACT_MEMO_TYPE:
898
+ // Memo may contain any component type so we recursively resolve it.
899
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
900
+
901
+ case REACT_LAZY_TYPE:
902
+ {
903
+ var lazyComponent = type;
904
+ var payload = lazyComponent._payload;
905
+ var init = lazyComponent._init;
906
+
907
+ try {
908
+ // Lazy may contain any component type so we recursively resolve it.
909
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
910
+ } catch (x) {}
911
+ }
912
+ }
913
+ }
914
+
915
+ return '';
916
+ }
917
+
918
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
919
+
920
+ var loggedTypeFailures = {};
921
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
922
+
923
+ function setCurrentlyValidatingElement(element) {
924
+ {
925
+ if (element) {
926
+ var owner = element._owner;
927
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
928
+ ReactDebugCurrentFrame.setExtraStackFrame(stack);
929
+ } else {
930
+ ReactDebugCurrentFrame.setExtraStackFrame(null);
931
+ }
932
+ }
933
+ }
934
+
935
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
936
+ {
937
+ // $FlowFixMe This is okay but Flow doesn't know it.
938
+ var has = Function.call.bind(hasOwnProperty);
939
+
940
+ for (var typeSpecName in typeSpecs) {
941
+ if (has(typeSpecs, typeSpecName)) {
942
+ var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
943
+ // fail the render phase where it didn't fail before. So we log it.
944
+ // After these have been cleaned up, we'll let them throw.
945
+
946
+ try {
947
+ // This is intentionally an invariant that gets caught. It's the same
948
+ // behavior as without this statement except with a better message.
949
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
950
+ // eslint-disable-next-line react-internal/prod-error-codes
951
+ var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
952
+ err.name = 'Invariant Violation';
953
+ throw err;
954
+ }
955
+
956
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
957
+ } catch (ex) {
958
+ error$1 = ex;
959
+ }
960
+
961
+ if (error$1 && !(error$1 instanceof Error)) {
962
+ setCurrentlyValidatingElement(element);
963
+
964
+ error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
965
+
966
+ setCurrentlyValidatingElement(null);
967
+ }
968
+
969
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
970
+ // Only monitor this failure once because there tends to be a lot of the
971
+ // same error.
972
+ loggedTypeFailures[error$1.message] = true;
973
+ setCurrentlyValidatingElement(element);
974
+
975
+ error('Failed %s type: %s', location, error$1.message);
976
+
977
+ setCurrentlyValidatingElement(null);
978
+ }
979
+ }
980
+ }
981
+ }
982
+ }
983
+
984
+ var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
985
+
986
+ function isArray(a) {
987
+ return isArrayImpl(a);
988
+ }
989
+
990
+ /*
991
+ * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
992
+ * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
993
+ *
994
+ * The functions in this module will throw an easier-to-understand,
995
+ * easier-to-debug exception with a clear errors message message explaining the
996
+ * problem. (Instead of a confusing exception thrown inside the implementation
997
+ * of the `value` object).
998
+ */
999
+ // $FlowFixMe only called in DEV, so void return is not possible.
1000
+ function typeName(value) {
1001
+ {
1002
+ // toStringTag is needed for namespaced types like Temporal.Instant
1003
+ var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
1004
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
1005
+ return type;
1006
+ }
1007
+ } // $FlowFixMe only called in DEV, so void return is not possible.
1008
+
1009
+
1010
+ function willCoercionThrow(value) {
1011
+ {
1012
+ try {
1013
+ testStringCoercion(value);
1014
+ return false;
1015
+ } catch (e) {
1016
+ return true;
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ function testStringCoercion(value) {
1022
+ // If you ended up here by following an exception call stack, here's what's
1023
+ // happened: you supplied an object or symbol value to React (as a prop, key,
1024
+ // DOM attribute, CSS property, string ref, etc.) and when React tried to
1025
+ // coerce it to a string using `'' + value`, an exception was thrown.
1026
+ //
1027
+ // The most common types that will cause this exception are `Symbol` instances
1028
+ // and Temporal objects like `Temporal.Instant`. But any object that has a
1029
+ // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
1030
+ // exception. (Library authors do this to prevent users from using built-in
1031
+ // numeric operators like `+` or comparison operators like `>=` because custom
1032
+ // methods are needed to perform accurate arithmetic or comparison.)
1033
+ //
1034
+ // To fix the problem, coerce this object or symbol value to a string before
1035
+ // passing it to React. The most reliable way is usually `String(value)`.
1036
+ //
1037
+ // To find which value is throwing, check the browser or debugger console.
1038
+ // Before this exception was thrown, there should be `console.error` output
1039
+ // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
1040
+ // problem and how that type was used: key, atrribute, input value prop, etc.
1041
+ // In most cases, this console output also shows the component and its
1042
+ // ancestor components where the exception happened.
1043
+ //
1044
+ // eslint-disable-next-line react-internal/safe-string-coercion
1045
+ return '' + value;
1046
+ }
1047
+ function checkKeyStringCoercion(value) {
1048
+ {
1049
+ if (willCoercionThrow(value)) {
1050
+ error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
1051
+
1052
+ return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
1053
+ }
1054
+ }
1055
+ }
1056
+
1057
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
1058
+ var RESERVED_PROPS = {
1059
+ key: true,
1060
+ ref: true,
1061
+ __self: true,
1062
+ __source: true
1063
+ };
1064
+ var specialPropKeyWarningShown;
1065
+ var specialPropRefWarningShown;
1066
+
1067
+ function hasValidRef(config) {
1068
+ {
1069
+ if (hasOwnProperty.call(config, 'ref')) {
1070
+ var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
1071
+
1072
+ if (getter && getter.isReactWarning) {
1073
+ return false;
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ return config.ref !== undefined;
1079
+ }
1080
+
1081
+ function hasValidKey(config) {
1082
+ {
1083
+ if (hasOwnProperty.call(config, 'key')) {
1084
+ var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
1085
+
1086
+ if (getter && getter.isReactWarning) {
1087
+ return false;
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ return config.key !== undefined;
1093
+ }
1094
+
1095
+ function warnIfStringRefCannotBeAutoConverted(config, self) {
1096
+ {
1097
+ if (typeof config.ref === 'string' && ReactCurrentOwner.current && self) ;
1098
+ }
1099
+ }
1100
+
1101
+ function defineKeyPropWarningGetter(props, displayName) {
1102
+ {
1103
+ var warnAboutAccessingKey = function () {
1104
+ if (!specialPropKeyWarningShown) {
1105
+ specialPropKeyWarningShown = true;
1106
+
1107
+ error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1108
+ }
1109
+ };
1110
+
1111
+ warnAboutAccessingKey.isReactWarning = true;
1112
+ Object.defineProperty(props, 'key', {
1113
+ get: warnAboutAccessingKey,
1114
+ configurable: true
1115
+ });
1116
+ }
1117
+ }
1118
+
1119
+ function defineRefPropWarningGetter(props, displayName) {
1120
+ {
1121
+ var warnAboutAccessingRef = function () {
1122
+ if (!specialPropRefWarningShown) {
1123
+ specialPropRefWarningShown = true;
1124
+
1125
+ error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1126
+ }
1127
+ };
1128
+
1129
+ warnAboutAccessingRef.isReactWarning = true;
1130
+ Object.defineProperty(props, 'ref', {
1131
+ get: warnAboutAccessingRef,
1132
+ configurable: true
1133
+ });
1134
+ }
1135
+ }
1136
+ /**
1137
+ * Factory method to create a new React element. This no longer adheres to
1138
+ * the class pattern, so do not use new to call it. Also, instanceof check
1139
+ * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
1140
+ * if something is a React Element.
1141
+ *
1142
+ * @param {*} type
1143
+ * @param {*} props
1144
+ * @param {*} key
1145
+ * @param {string|object} ref
1146
+ * @param {*} owner
1147
+ * @param {*} self A *temporary* helper to detect places where `this` is
1148
+ * different from the `owner` when React.createElement is called, so that we
1149
+ * can warn. We want to get rid of owner and replace string `ref`s with arrow
1150
+ * functions, and as long as `this` and owner are the same, there will be no
1151
+ * change in behavior.
1152
+ * @param {*} source An annotation object (added by a transpiler or otherwise)
1153
+ * indicating filename, line number, and/or other information.
1154
+ * @internal
1155
+ */
1156
+
1157
+
1158
+ var ReactElement = function (type, key, ref, self, source, owner, props) {
1159
+ var element = {
1160
+ // This tag allows us to uniquely identify this as a React Element
1161
+ $$typeof: REACT_ELEMENT_TYPE,
1162
+ // Built-in properties that belong on the element
1163
+ type: type,
1164
+ key: key,
1165
+ ref: ref,
1166
+ props: props,
1167
+ // Record the component responsible for creating this element.
1168
+ _owner: owner
1169
+ };
1170
+
1171
+ {
1172
+ // The validation flag is currently mutative. We put it on
1173
+ // an external backing store so that we can freeze the whole object.
1174
+ // This can be replaced with a WeakMap once they are implemented in
1175
+ // commonly used development environments.
1176
+ element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1177
+ // the validation flag non-enumerable (where possible, which should
1178
+ // include every environment we run tests in), so the test framework
1179
+ // ignores it.
1180
+
1181
+ Object.defineProperty(element._store, 'validated', {
1182
+ configurable: false,
1183
+ enumerable: false,
1184
+ writable: true,
1185
+ value: false
1186
+ }); // self and source are DEV only properties.
1187
+
1188
+ Object.defineProperty(element, '_self', {
1189
+ configurable: false,
1190
+ enumerable: false,
1191
+ writable: false,
1192
+ value: self
1193
+ }); // Two elements created in two different places should be considered
1194
+ // equal for testing purposes and therefore we hide it from enumeration.
1195
+
1196
+ Object.defineProperty(element, '_source', {
1197
+ configurable: false,
1198
+ enumerable: false,
1199
+ writable: false,
1200
+ value: source
1201
+ });
1202
+
1203
+ if (Object.freeze) {
1204
+ Object.freeze(element.props);
1205
+ Object.freeze(element);
1206
+ }
1207
+ }
1208
+
1209
+ return element;
1210
+ };
1211
+ /**
1212
+ * https://github.com/reactjs/rfcs/pull/107
1213
+ * @param {*} type
1214
+ * @param {object} props
1215
+ * @param {string} key
1216
+ */
1217
+
1218
+ function jsxDEV(type, config, maybeKey, source, self) {
1219
+ {
1220
+ var propName; // Reserved names are extracted
1221
+
1222
+ var props = {};
1223
+ var key = null;
1224
+ var ref = null; // Currently, key can be spread in as a prop. This causes a potential
1225
+ // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
1226
+ // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
1227
+ // but as an intermediary step, we will use jsxDEV for everything except
1228
+ // <div {...props} key="Hi" />, because we aren't currently able to tell if
1229
+ // key is explicitly declared to be undefined or not.
1230
+
1231
+ if (maybeKey !== undefined) {
1232
+ {
1233
+ checkKeyStringCoercion(maybeKey);
1234
+ }
1235
+
1236
+ key = '' + maybeKey;
1237
+ }
1238
+
1239
+ if (hasValidKey(config)) {
1240
+ {
1241
+ checkKeyStringCoercion(config.key);
1242
+ }
1243
+
1244
+ key = '' + config.key;
1245
+ }
1246
+
1247
+ if (hasValidRef(config)) {
1248
+ ref = config.ref;
1249
+ warnIfStringRefCannotBeAutoConverted(config, self);
1250
+ } // Remaining properties are added to a new props object
1251
+
1252
+
1253
+ for (propName in config) {
1254
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1255
+ props[propName] = config[propName];
1256
+ }
1257
+ } // Resolve default props
1258
+
1259
+
1260
+ if (type && type.defaultProps) {
1261
+ var defaultProps = type.defaultProps;
1262
+
1263
+ for (propName in defaultProps) {
1264
+ if (props[propName] === undefined) {
1265
+ props[propName] = defaultProps[propName];
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ if (key || ref) {
1271
+ var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
1272
+
1273
+ if (key) {
1274
+ defineKeyPropWarningGetter(props, displayName);
1275
+ }
1276
+
1277
+ if (ref) {
1278
+ defineRefPropWarningGetter(props, displayName);
1279
+ }
1280
+ }
1281
+
1282
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1283
+ }
1284
+ }
1285
+
1286
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
1287
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1288
+
1289
+ function setCurrentlyValidatingElement$1(element) {
1290
+ {
1291
+ if (element) {
1292
+ var owner = element._owner;
1293
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1294
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1295
+ } else {
1296
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ var propTypesMisspellWarningShown;
1302
+
1303
+ {
1304
+ propTypesMisspellWarningShown = false;
1305
+ }
1306
+ /**
1307
+ * Verifies the object is a ReactElement.
1308
+ * See https://reactjs.org/docs/react-api.html#isvalidelement
1309
+ * @param {?object} object
1310
+ * @return {boolean} True if `object` is a ReactElement.
1311
+ * @final
1312
+ */
1313
+
1314
+
1315
+ function isValidElement(object) {
1316
+ {
1317
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1318
+ }
1319
+ }
1320
+
1321
+ function getDeclarationErrorAddendum() {
1322
+ {
1323
+ if (ReactCurrentOwner$1.current) {
1324
+ var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1325
+
1326
+ if (name) {
1327
+ return '\n\nCheck the render method of `' + name + '`.';
1328
+ }
1329
+ }
1330
+
1331
+ return '';
1332
+ }
1333
+ }
1334
+
1335
+ function getSourceInfoErrorAddendum(source) {
1336
+ {
1337
+
1338
+ return '';
1339
+ }
1340
+ }
1341
+ /**
1342
+ * Warn if there's no key explicitly set on dynamic arrays of children or
1343
+ * object keys are not valid. This allows us to keep track of children between
1344
+ * updates.
1345
+ */
1346
+
1347
+
1348
+ var ownerHasKeyUseWarning = {};
1349
+
1350
+ function getCurrentComponentErrorInfo(parentType) {
1351
+ {
1352
+ var info = getDeclarationErrorAddendum();
1353
+
1354
+ if (!info) {
1355
+ var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1356
+
1357
+ if (parentName) {
1358
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1359
+ }
1360
+ }
1361
+
1362
+ return info;
1363
+ }
1364
+ }
1365
+ /**
1366
+ * Warn if the element doesn't have an explicit key assigned to it.
1367
+ * This element is in an array. The array could grow and shrink or be
1368
+ * reordered. All children that haven't already been validated are required to
1369
+ * have a "key" property assigned to it. Error statuses are cached so a warning
1370
+ * will only be shown once.
1371
+ *
1372
+ * @internal
1373
+ * @param {ReactElement} element Element that requires a key.
1374
+ * @param {*} parentType element's parent's type.
1375
+ */
1376
+
1377
+
1378
+ function validateExplicitKey(element, parentType) {
1379
+ {
1380
+ if (!element._store || element._store.validated || element.key != null) {
1381
+ return;
1382
+ }
1383
+
1384
+ element._store.validated = true;
1385
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1386
+
1387
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1388
+ return;
1389
+ }
1390
+
1391
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1392
+ // property, it may be the creator of the child that's responsible for
1393
+ // assigning it a key.
1394
+
1395
+ var childOwner = '';
1396
+
1397
+ if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1398
+ // Give the component that originally created this child.
1399
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1400
+ }
1401
+
1402
+ setCurrentlyValidatingElement$1(element);
1403
+
1404
+ error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
1405
+
1406
+ setCurrentlyValidatingElement$1(null);
1407
+ }
1408
+ }
1409
+ /**
1410
+ * Ensure that every element either is passed in a static location, in an
1411
+ * array with an explicit keys property defined, or in an object literal
1412
+ * with valid key property.
1413
+ *
1414
+ * @internal
1415
+ * @param {ReactNode} node Statically passed child of any type.
1416
+ * @param {*} parentType node's parent's type.
1417
+ */
1418
+
1419
+
1420
+ function validateChildKeys(node, parentType) {
1421
+ {
1422
+ if (typeof node !== 'object') {
1423
+ return;
1424
+ }
1425
+
1426
+ if (isArray(node)) {
1427
+ for (var i = 0; i < node.length; i++) {
1428
+ var child = node[i];
1429
+
1430
+ if (isValidElement(child)) {
1431
+ validateExplicitKey(child, parentType);
1432
+ }
1433
+ }
1434
+ } else if (isValidElement(node)) {
1435
+ // This element was passed in a valid location.
1436
+ if (node._store) {
1437
+ node._store.validated = true;
1438
+ }
1439
+ } else if (node) {
1440
+ var iteratorFn = getIteratorFn(node);
1441
+
1442
+ if (typeof iteratorFn === 'function') {
1443
+ // Entry iterators used to provide implicit keys,
1444
+ // but now we print a separate warning for them later.
1445
+ if (iteratorFn !== node.entries) {
1446
+ var iterator = iteratorFn.call(node);
1447
+ var step;
1448
+
1449
+ while (!(step = iterator.next()).done) {
1450
+ if (isValidElement(step.value)) {
1451
+ validateExplicitKey(step.value, parentType);
1452
+ }
1453
+ }
1454
+ }
1455
+ }
1456
+ }
1457
+ }
1458
+ }
1459
+ /**
1460
+ * Given an element, validate that its props follow the propTypes definition,
1461
+ * provided by the type.
1462
+ *
1463
+ * @param {ReactElement} element
1464
+ */
1465
+
1466
+
1467
+ function validatePropTypes(element) {
1468
+ {
1469
+ var type = element.type;
1470
+
1471
+ if (type === null || type === undefined || typeof type === 'string') {
1472
+ return;
1473
+ }
1474
+
1475
+ var propTypes;
1476
+
1477
+ if (typeof type === 'function') {
1478
+ propTypes = type.propTypes;
1479
+ } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1480
+ // Inner props are checked in the reconciler.
1481
+ type.$$typeof === REACT_MEMO_TYPE)) {
1482
+ propTypes = type.propTypes;
1483
+ } else {
1484
+ return;
1485
+ }
1486
+
1487
+ if (propTypes) {
1488
+ // Intentionally inside to avoid triggering lazy initializers:
1489
+ var name = getComponentNameFromType(type);
1490
+ checkPropTypes(propTypes, element.props, 'prop', name, element);
1491
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1492
+ propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1493
+
1494
+ var _name = getComponentNameFromType(type);
1495
+
1496
+ error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1497
+ }
1498
+
1499
+ if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1500
+ error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1501
+ }
1502
+ }
1503
+ }
1504
+ /**
1505
+ * Given a fragment, validate that it can only be provided with fragment props
1506
+ * @param {ReactElement} fragment
1507
+ */
1508
+
1509
+
1510
+ function validateFragmentProps(fragment) {
1511
+ {
1512
+ var keys = Object.keys(fragment.props);
1513
+
1514
+ for (var i = 0; i < keys.length; i++) {
1515
+ var key = keys[i];
1516
+
1517
+ if (key !== 'children' && key !== 'key') {
1518
+ setCurrentlyValidatingElement$1(fragment);
1519
+
1520
+ error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1521
+
1522
+ setCurrentlyValidatingElement$1(null);
1523
+ break;
1524
+ }
1525
+ }
1526
+
1527
+ if (fragment.ref !== null) {
1528
+ setCurrentlyValidatingElement$1(fragment);
1529
+
1530
+ error('Invalid attribute `ref` supplied to `React.Fragment`.');
1531
+
1532
+ setCurrentlyValidatingElement$1(null);
1533
+ }
1534
+ }
1535
+ }
1536
+
1537
+ var didWarnAboutKeySpread = {};
1538
+ function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1539
+ {
1540
+ var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1541
+ // succeed and there will likely be errors in render.
1542
+
1543
+ if (!validType) {
1544
+ var info = '';
1545
+
1546
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1547
+ info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
1548
+ }
1549
+
1550
+ var sourceInfo = getSourceInfoErrorAddendum();
1551
+
1552
+ if (sourceInfo) {
1553
+ info += sourceInfo;
1554
+ } else {
1555
+ info += getDeclarationErrorAddendum();
1556
+ }
1557
+
1558
+ var typeString;
1559
+
1560
+ if (type === null) {
1561
+ typeString = 'null';
1562
+ } else if (isArray(type)) {
1563
+ typeString = 'array';
1564
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1565
+ typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1566
+ info = ' Did you accidentally export a JSX literal instead of a component?';
1567
+ } else {
1568
+ typeString = typeof type;
1569
+ }
1570
+
1571
+ error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
1572
+ }
1573
+
1574
+ var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1575
+ // TODO: Drop this when these are no longer allowed as the type argument.
1576
+
1577
+ if (element == null) {
1578
+ return element;
1579
+ } // Skip key warning if the type isn't valid since our key validation logic
1580
+ // doesn't expect a non-string/function type and can throw confusing errors.
1581
+ // We don't want exception behavior to differ between dev and prod.
1582
+ // (Rendering will throw with a helpful message and as soon as the type is
1583
+ // fixed, the key warnings will appear.)
1584
+
1585
+
1586
+ if (validType) {
1587
+ var children = props.children;
1588
+
1589
+ if (children !== undefined) {
1590
+ if (isStaticChildren) {
1591
+ if (isArray(children)) {
1592
+ for (var i = 0; i < children.length; i++) {
1593
+ validateChildKeys(children[i], type);
1594
+ }
1595
+
1596
+ if (Object.freeze) {
1597
+ Object.freeze(children);
1598
+ }
1599
+ } else {
1600
+ error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
1601
+ }
1602
+ } else {
1603
+ validateChildKeys(children, type);
1604
+ }
1605
+ }
1606
+ }
1607
+
1608
+ {
1609
+ if (hasOwnProperty.call(props, 'key')) {
1610
+ var componentName = getComponentNameFromType(type);
1611
+ var keys = Object.keys(props).filter(function (k) {
1612
+ return k !== 'key';
1613
+ });
1614
+ var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1615
+
1616
+ if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1617
+ var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1618
+
1619
+ error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
1620
+
1621
+ didWarnAboutKeySpread[componentName + beforeExample] = true;
1622
+ }
1623
+ }
1624
+ }
1625
+
1626
+ if (type === REACT_FRAGMENT_TYPE) {
1627
+ validateFragmentProps(element);
1628
+ } else {
1629
+ validatePropTypes(element);
1630
+ }
1631
+
1632
+ return element;
1633
+ }
1634
+ } // These two functions exist to still get child warnings in dev
1635
+ // even with the prod transform. This means that jsxDEV is purely
1636
+ // opt-in behavior for better messages but that we won't stop
1637
+ // giving you warnings if you use production apis.
1638
+
1639
+ function jsxWithValidationStatic(type, props, key) {
1640
+ {
1641
+ return jsxWithValidation(type, props, key, true);
1642
+ }
1643
+ }
1644
+ function jsxWithValidationDynamic(type, props, key) {
1645
+ {
1646
+ return jsxWithValidation(type, props, key, false);
1647
+ }
1648
+ }
1649
+
1650
+ var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1651
+ // for now we can ship identical prod functions
1652
+
1653
+ var jsxs = jsxWithValidationStatic ;
1654
+
1655
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1656
+ reactJsxRuntime_development.jsx = jsx;
1657
+ reactJsxRuntime_development.jsxs = jsxs;
1658
+ })();
1659
+ }
1660
+ return reactJsxRuntime_development;
1661
+ }
1662
+
1663
+ var hasRequiredJsxRuntime;
1664
+
1665
+ function requireJsxRuntime () {
1666
+ if (hasRequiredJsxRuntime) return jsxRuntime.exports;
1667
+ hasRequiredJsxRuntime = 1;
1668
+
1669
+ if (process.env.NODE_ENV === 'production') {
1670
+ jsxRuntime.exports = requireReactJsxRuntime_production_min();
1671
+ } else {
1672
+ jsxRuntime.exports = requireReactJsxRuntime_development();
1673
+ }
1674
+ return jsxRuntime.exports;
1675
+ }
1676
+
1677
+ var jsxRuntimeExports = requireJsxRuntime();
1678
+
1679
+ function asMethod(candidate) {
1680
+ return typeof candidate === 'function'
1681
+ ? candidate
1682
+ : undefined;
1683
+ }
1684
+ const PaywallCtx = createContext(null);
1685
+ const FirstFocusReadyCtx = createContext(null);
1686
+ function usePaywallContext() {
1687
+ const ctx = useContext(PaywallCtx);
1688
+ if (!ctx)
1689
+ throw new Error('usePaywallContext must be used within a PaywallProvider');
1690
+ return ctx;
1691
+ }
1692
+ function useFirstFocusReadyContext() {
1693
+ const ctx = useContext(FirstFocusReadyCtx);
1694
+ if (!ctx)
1695
+ throw new Error('useFirstFocusReadyContext must be used within a PaywallProvider');
1696
+ return ctx;
1697
+ }
1698
+ const PaywallProvider = ({ paywall, context, campaign, flow, onFirstFocusReady, children, }) => {
1699
+ const providerRef = useRef(null);
1700
+ const pageHistoryRef = useRef([]);
1701
+ const [firstFocusReadyKey, setFirstFocusReadyKey] = useState(null);
1702
+ const [state, setState] = useState(() => {
1703
+ const provider = PaywallState.create(paywall, context, campaign);
1704
+ if (flow)
1705
+ provider.setFlow(flow);
1706
+ providerRef.current = provider;
1707
+ pageHistoryRef.current = [provider.state.currentPage ?? paywall.template?.initialState?.currentPage ?? 'page1'];
1708
+ return cloneStateWithDynamicProps(provider.state, provider);
1709
+ });
1710
+ useEffect(() => {
1711
+ const provider = providerRef.current;
1712
+ if (!provider)
1713
+ return;
1714
+ const unsubscribe = provider.subscribe(() => {
1715
+ setState(cloneStateWithDynamicProps(provider.state, provider));
1716
+ });
1717
+ return () => {
1718
+ unsubscribe();
1719
+ PaywallState.remove(provider);
1720
+ };
1721
+ }, []);
1722
+ useEffect(() => {
1723
+ const provider = providerRef.current;
1724
+ if (!provider)
1725
+ return;
1726
+ setFirstFocusReadyKey(null);
1727
+ provider.setPaywall(paywall, context, campaign);
1728
+ if (flow)
1729
+ provider.setFlow(flow);
1730
+ pageHistoryRef.current = [provider.state.currentPage ?? paywall.template?.initialState?.currentPage ?? 'page1'];
1731
+ setState(cloneStateWithDynamicProps(provider.state, provider));
1732
+ }, [paywall, context, campaign, flow]);
1733
+ const methods = useMemo(() => ({
1734
+ setPaywall: (nextPaywall, nextContext, nextCampaign) => {
1735
+ providerRef.current?.setPaywall(nextPaywall, nextContext, nextCampaign);
1736
+ const provider = providerRef.current;
1737
+ pageHistoryRef.current = [provider?.state.currentPage ?? nextPaywall.template?.initialState?.currentPage ?? 'page1'];
1738
+ },
1739
+ setCurrentPage: (page) => {
1740
+ const provider = providerRef.current;
1741
+ const currentPage = provider?.state.currentPage ?? pageHistoryRef.current[pageHistoryRef.current.length - 1] ?? 'page1';
1742
+ if (!page || page === currentPage) {
1743
+ return;
1744
+ }
1745
+ const currentHistory = pageHistoryRef.current.length ? pageHistoryRef.current : [currentPage];
1746
+ pageHistoryRef.current = [...currentHistory, page];
1747
+ provider?.setCurrentPage(page);
1748
+ },
1749
+ canGoBackPage: () => {
1750
+ if (pageHistoryRef.current.length > 1) {
1751
+ return true;
1752
+ }
1753
+ return asMethod(providerRef.current?.canGoBackPage)?.call(providerRef.current) ?? false;
1754
+ },
1755
+ goBackPage: () => {
1756
+ const provider = providerRef.current;
1757
+ if (pageHistoryRef.current.length > 1) {
1758
+ const nextHistory = [...pageHistoryRef.current];
1759
+ nextHistory.pop();
1760
+ const previousPage = nextHistory[nextHistory.length - 1];
1761
+ if (!previousPage) {
1762
+ return false;
1763
+ }
1764
+ pageHistoryRef.current = nextHistory;
1765
+ const providerHandled = asMethod(provider?.goBackPage)?.call(provider) ?? false;
1766
+ if (!providerHandled) {
1767
+ provider?.setCurrentPage(previousPage);
1768
+ }
1769
+ return true;
1770
+ }
1771
+ return asMethod(provider?.goBackPage)?.call(provider) ?? false;
1772
+ },
1773
+ setCurrentGroupData: (groupId, groupName) => {
1774
+ providerRef.current?.setCurrentGroupData(groupId, groupName);
1775
+ },
1776
+ setSelectedProducts: (products) => {
1777
+ providerRef.current?.setSelectedProducts(products);
1778
+ },
1779
+ setCurrentFormId: (formId, value) => {
1780
+ providerRef.current?.setCurrentFormId(formId, value);
1781
+ },
1782
+ setFormState: (formId, value) => {
1783
+ providerRef.current?.setFormState(formId, value);
1784
+ },
1785
+ setTimerState: (timerId, remainingSeconds, savedAt, hasEmittedCompletion) => {
1786
+ providerRef.current?.setTimerState(timerId, remainingSeconds, savedAt, hasEmittedCompletion);
1787
+ },
1788
+ getTimerState: (timerId) => {
1789
+ return providerRef.current?.getTimerState(timerId);
1790
+ },
1791
+ setProductDetails: (details) => {
1792
+ providerRef.current?.setProductDetails(details);
1793
+ },
1794
+ setPurchaseInProgress: (inProgress) => {
1795
+ providerRef.current?.setPurchaseInProgress(inProgress);
1796
+ },
1797
+ setPurchase: (inProgress, product) => {
1798
+ providerRef.current?.setPurchase(inProgress, product);
1799
+ },
1800
+ setCustomerAttribute: (attributes) => {
1801
+ providerRef.current?.setCustomerAttribute(attributes);
1802
+ },
1803
+ removeCustomerAttribute: (key) => {
1804
+ providerRef.current?.removeCustomerAttribute(key);
1805
+ },
1806
+ setIsLoggedIn: (isLoggedIn) => {
1807
+ providerRef.current?.setIsLoggedIn(isLoggedIn);
1808
+ },
1809
+ setAppSuppliedVideoDetails: (details) => {
1810
+ providerRef.current?.setAppSuppliedVideoDetails(details);
1811
+ },
1812
+ resetAppSuppliedVideoDetails: () => {
1813
+ providerRef.current?.resetAppSuppliedVideoDetails();
1814
+ },
1815
+ setMediaList: (media) => {
1816
+ providerRef.current?.setMediaList(media);
1817
+ },
1818
+ setSafeAreaTop: (top) => {
1819
+ providerRef.current?.setSafeAreaTop(top);
1820
+ },
1821
+ setFullScreenPresentation: (full) => {
1822
+ providerRef.current?.setFullScreenPresentation(full);
1823
+ },
1824
+ setFormFactor: (factor) => {
1825
+ providerRef.current?.setFormFactor(factor);
1826
+ },
1827
+ setUserInteractionEnabled: (enabled) => {
1828
+ providerRef.current?.setUserInteractionEnabled(enabled);
1829
+ },
1830
+ setUserTags: (tags) => {
1831
+ providerRef.current?.setUserTags(tags);
1832
+ },
1833
+ setLaunchDetails: (value, type) => {
1834
+ providerRef.current?.setLaunchDetails(value, type);
1835
+ },
1836
+ setOpenHeaderIds: (id, sku) => {
1837
+ providerRef.current?.setOpenHeaderIds(id, sku);
1838
+ },
1839
+ setFlow: (nextFlow) => {
1840
+ providerRef.current?.setFlow(nextFlow);
1841
+ },
1842
+ notifyFirstFocusReady: (paywallId, page, formFactor) => {
1843
+ setFirstFocusReadyKey(`${paywallId}:${page}:${formFactor ?? ''}`);
1844
+ onFirstFocusReady?.(paywallId, page, formFactor);
1845
+ },
1846
+ setCurrentSlideIndex: (index) => {
1847
+ providerRef.current?.setCurrentSlideIndex(index);
1848
+ },
1849
+ getPaywallActionEventData: () => {
1850
+ return providerRef.current?.getPaywallActionEventData() ?? {};
1851
+ },
1852
+ getSelectedPaywall: () => {
1853
+ return providerRef.current?.getSelectedPaywall();
1854
+ },
1855
+ getSelectedCampaign: () => {
1856
+ return providerRef.current?.getSelectedCampaign();
1857
+ },
1858
+ }), [onFirstFocusReady]);
1859
+ const focusReadyValue = useMemo(() => ({
1860
+ firstFocusReadyKey,
1861
+ notifyFirstFocusReady: methods.notifyFirstFocusReady,
1862
+ }), [firstFocusReadyKey, methods]);
1863
+ const value = useMemo(() => {
1864
+ const provider = providerRef.current;
1865
+ return {
1866
+ state,
1867
+ productDetails: provider?.getProductDetails() ?? provider?.productDetails ?? [],
1868
+ flow: provider?.flow,
1869
+ filteredSkuMenus: provider?.filteredSkuMenus ?? [],
1870
+ ...methods,
1871
+ };
1872
+ }, [methods, state]);
1873
+ return (jsxRuntimeExports.jsx(PaywallCtx.Provider, { value: value, children: jsxRuntimeExports.jsx(FirstFocusReadyCtx.Provider, { value: focusReadyValue, children: children }) }));
1874
+ };
1875
+ function cloneStateWithDynamicProps(state, provider) {
1876
+ const nextState = { ...(state ?? initialState) };
1877
+ defineDynamicStateProps(nextState, provider);
1878
+ return nextState;
1879
+ }
1880
+ function defineDynamicStateProps(state, provider) {
1881
+ Object.defineProperty(state, 'tvQuality', {
1882
+ get: () => getTVQuality(provider),
1883
+ enumerable: false,
1884
+ configurable: true,
1885
+ });
1886
+ Object.defineProperty(state, 'viewportWidth', {
1887
+ get: getViewportWidth,
1888
+ enumerable: false,
1889
+ configurable: true,
1890
+ });
1891
+ Object.defineProperty(state, 'viewportHeight', {
1892
+ get: getViewportHeight,
1893
+ enumerable: false,
1894
+ configurable: true,
1895
+ });
1896
+ }
1897
+ function getTVQuality(provider) {
1898
+ if (provider.getFormFactor() !== 'television') {
1899
+ return '';
1900
+ }
1901
+ const { width, height, scale } = Dimensions.get('window');
1902
+ const maxDimension = Math.max(width, height) * (scale || 1);
1903
+ const minDimension = Math.min(width, height) * (scale || 1);
1904
+ if (!maxDimension || !minDimension) {
1905
+ return '720p';
1906
+ }
1907
+ if (maxDimension >= 3840 || minDimension >= 2160) {
1908
+ return '4K';
1909
+ }
1910
+ if (maxDimension >= 1920 || minDimension >= 1080) {
1911
+ return '1080p';
1912
+ }
1913
+ return '720p';
1914
+ }
1915
+ function getViewportWidth() {
1916
+ return Dimensions.get('window').width;
1917
+ }
1918
+ function getViewportHeight() {
1919
+ return Dimensions.get('window').height;
1920
+ }
1921
+
1922
+ let fontModule = null;
1923
+ try {
1924
+ fontModule = require('expo-font');
1925
+ }
1926
+ catch {
1927
+ try {
1928
+ fontModule = require('@amazon-devices/expo-font');
1929
+ }
1930
+ catch {
1931
+ fontModule = null;
1932
+ }
1933
+ }
1934
+ const knownFontFaces = new Set();
1935
+ const loadedFonts = new Set();
1936
+ const loadingFonts = new Map();
1937
+ let warnedMissingFontModule = false;
1938
+ const warnedFailedFontLoads = new Set();
1939
+ const fontFamilyVariants = new Map();
1940
+ const aliasToFamilyKey = new Map();
1941
+ const KEPLER_VARIANT_COLLISION_FAMILY_KEYS = new Set(['All-ProDisplayC']);
1942
+ async function prepareAndLoadFonts(fontsObject) {
1943
+ if (!fontsObject)
1944
+ return false;
1945
+ if (!fontModule) {
1946
+ if (!warnedMissingFontModule && Object.keys(fontsObject).length > 0) {
1947
+ warnedMissingFontModule = true;
1948
+ logger.warn('[NamiExpo][fonts] Paywall requested hosted fonts, but expo-font is unavailable in the current app runtime.');
1949
+ }
1950
+ return false;
1951
+ }
1952
+ const fonts = collectHostedFonts(fontsObject);
1953
+ for (const font of fonts) {
1954
+ registerFontMetadata(font);
1955
+ }
1956
+ const results = await Promise.all(fonts.map((font) => loadFont(font)));
1957
+ return results.some(Boolean);
1958
+ }
1959
+ function prewarmPaywallFonts(paywalls) {
1960
+ const uniqueCollections = new Set();
1961
+ for (const paywall of paywalls) {
1962
+ if (!paywall?.fonts) {
1963
+ continue;
1964
+ }
1965
+ uniqueCollections.add(paywall.fonts);
1966
+ }
1967
+ for (const fonts of uniqueCollections) {
1968
+ void prepareAndLoadFonts(fonts);
1969
+ }
1970
+ }
1971
+ async function prepareAndLoadFontsWithTimeout(fontsObject, timeoutMs = 1200) {
1972
+ if (!fontsObject || Object.keys(fontsObject).length === 0) {
1973
+ return 'none';
1974
+ }
1975
+ let timer;
1976
+ const result = await Promise.race([
1977
+ ensureFontsReady(fontsObject).then((value) => (value === 'none' ? 'failed' : value)),
1978
+ new Promise((resolve) => {
1979
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
1980
+ }),
1981
+ ]);
1982
+ if (timer) {
1983
+ clearTimeout(timer);
1984
+ }
1985
+ return result;
1986
+ }
1987
+ async function ensureFontsReady(fontsObject) {
1988
+ if (!fontsObject || Object.keys(fontsObject).length === 0) {
1989
+ return 'none';
1990
+ }
1991
+ await prepareAndLoadFonts(fontsObject);
1992
+ const fonts = collectHostedFonts(fontsObject);
1993
+ const allReady = fonts.every((font) => loadedFonts.has(font.alias || buildFontFaceFamily(font)));
1994
+ return allReady ? 'ready' : 'failed';
1995
+ }
1996
+ function collectHostedFonts(fontsObject) {
1997
+ if (!fontsObject) {
1998
+ return [];
1999
+ }
2000
+ return Object.entries(fontsObject)
2001
+ .flatMap(([fontName, value]) => {
2002
+ if (!value?.file) {
2003
+ return [];
2004
+ }
2005
+ return [{
2006
+ ...value,
2007
+ alias: sanitizeFontName(fontName),
2008
+ }];
2009
+ });
2010
+ }
2011
+ async function loadFont(font) {
2012
+ if (!fontModule)
2013
+ return false;
2014
+ if (shouldSkipHostedFontLoad(font)) {
2015
+ return false;
2016
+ }
2017
+ const family = font.alias || buildFontFaceFamily(font);
2018
+ knownFontFaces.add(family);
2019
+ if (loadedFonts.has(family))
2020
+ return false;
2021
+ const existing = loadingFonts.get(family);
2022
+ if (existing) {
2023
+ await existing;
2024
+ return false;
2025
+ }
2026
+ let loaded = false;
2027
+ const promise = fontModule
2028
+ .loadAsync({ [family]: { uri: font.file } })
2029
+ .then(() => {
2030
+ loadedFonts.add(family);
2031
+ loaded = true;
2032
+ })
2033
+ .catch((error) => {
2034
+ if (!warnedFailedFontLoads.has(family)) {
2035
+ warnedFailedFontLoads.add(family);
2036
+ logger.warn(`[NamiExpo][fonts] Failed to load hosted font "${family}" from "${font.file}".`, error);
2037
+ }
2038
+ // Keep the renderer resilient if a hosted font is unavailable.
2039
+ })
2040
+ .finally(() => {
2041
+ loadingFonts.delete(family);
2042
+ });
2043
+ loadingFonts.set(family, promise);
2044
+ await promise;
2045
+ return loaded;
2046
+ }
2047
+ function buildFontFaceFamily(font) {
2048
+ return sanitizeFontName(`${font.family}-${font.style}`);
2049
+ }
2050
+ function sanitizeFontName(value) {
2051
+ return value.replace(/ /g, '');
2052
+ }
2053
+ function registerFontMetadata(font) {
2054
+ const familyKey = sanitizeFontName(font.family);
2055
+ aliasToFamilyKey.set(font.alias, familyKey);
2056
+ const variant = normalizeFontVariant(font.style);
2057
+ const variants = fontFamilyVariants.get(familyKey) ?? new Map();
2058
+ variants.set(variant, font.alias);
2059
+ fontFamilyVariants.set(familyKey, variants);
2060
+ }
2061
+ function normalizeFontVariant(style) {
2062
+ const normalized = sanitizeFontName(style ?? '').toLowerCase();
2063
+ const hasBold = normalized.includes('bold');
2064
+ const hasItalic = normalized.includes('italic');
2065
+ if (hasBold && hasItalic)
2066
+ return 'boldItalic';
2067
+ if (hasBold)
2068
+ return 'bold';
2069
+ if (hasItalic)
2070
+ return 'italic';
2071
+ return 'regular';
2072
+ }
2073
+ function shouldSkipHostedFontLoad(font) {
2074
+ const isTelevisionRuntime = Platform.isTV === true;
2075
+ if (!isTelevisionRuntime) {
2076
+ return false;
2077
+ }
2078
+ const familyKey = sanitizeFontName(font.family);
2079
+ if (!KEPLER_VARIANT_COLLISION_FAMILY_KEYS.has(familyKey)) {
2080
+ return false;
2081
+ }
2082
+ const variant = normalizeFontVariant(font.style);
2083
+ return variant === 'italic' || variant === 'boldItalic';
2084
+ }
2085
+
2086
+ const HEX_ALPHA_REGEX = /^#([0-9a-f]{8})$/i;
2087
+ const HEX_SHORT_ALPHA_REGEX = /^#([0-9a-f]{4})$/i;
2088
+ const HSLA_REGEX = /^hsla?\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%(?:\s*,\s*([\d.]+))?\s*\)$/i;
2089
+ function parseColor(color) {
2090
+ if (!color)
2091
+ return undefined;
2092
+ if (typeof color === 'string') {
2093
+ const trimmed = color.trim();
2094
+ if (!trimmed)
2095
+ return undefined;
2096
+ if (trimmed.toLowerCase().includes('gradient('))
2097
+ return undefined;
2098
+ return normalizeColorString(trimmed);
2099
+ }
2100
+ if (color.rgba) {
2101
+ const { r, g, b, a } = color.rgba;
2102
+ return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a ?? 1})`;
2103
+ }
2104
+ if (color.hex)
2105
+ return normalizeColorString(color.hex);
2106
+ return undefined;
2107
+ }
2108
+ function normalizeColorString(input) {
2109
+ const value = input.trim();
2110
+ if (!value)
2111
+ return value;
2112
+ const match = value.match(/^rgba?\((.+)\)$/i);
2113
+ if (match) {
2114
+ const inside = match[1];
2115
+ const [base, alphaRaw] = inside.split('/').map((v) => v.trim());
2116
+ const parts = base.split(/[\s,]+/).filter(Boolean);
2117
+ const nums = parts.map((p) => p.trim());
2118
+ const r = nums[0];
2119
+ const g = nums[1];
2120
+ const b = nums[2];
2121
+ const a = alphaRaw ?? nums[3];
2122
+ if (r != null && g != null && b != null) {
2123
+ if (a != null) {
2124
+ return `rgba(${r},${g},${b},${a})`;
2125
+ }
2126
+ return `rgb(${r},${g},${b})`;
2127
+ }
2128
+ }
2129
+ const hexAlphaMatch = value.match(HEX_ALPHA_REGEX);
2130
+ if (hexAlphaMatch) {
2131
+ const hex = hexAlphaMatch[1];
2132
+ const r = parseInt(hex.slice(0, 2), 16);
2133
+ const g = parseInt(hex.slice(2, 4), 16);
2134
+ const b = parseInt(hex.slice(4, 6), 16);
2135
+ const a = parseInt(hex.slice(6, 8), 16) / 255;
2136
+ return `rgba(${r},${g},${b},${Number(a.toFixed(3))})`;
2137
+ }
2138
+ const hexShortAlphaMatch = value.match(HEX_SHORT_ALPHA_REGEX);
2139
+ if (hexShortAlphaMatch) {
2140
+ const hex = hexShortAlphaMatch[1];
2141
+ const r = parseInt(hex[0] + hex[0], 16);
2142
+ const g = parseInt(hex[1] + hex[1], 16);
2143
+ const b = parseInt(hex[2] + hex[2], 16);
2144
+ const a = parseInt(hex[3] + hex[3], 16) / 255;
2145
+ return `rgba(${r},${g},${b},${Number(a.toFixed(3))})`;
2146
+ }
2147
+ const hslaMatch = value.match(HSLA_REGEX);
2148
+ if (hslaMatch) {
2149
+ const h = parseFloat(hslaMatch[1]);
2150
+ const s = parseFloat(hslaMatch[2]);
2151
+ const l = parseFloat(hslaMatch[3]);
2152
+ const a = hslaMatch[4] != null ? parseFloat(hslaMatch[4]) : undefined;
2153
+ const [r, g, b] = hslToRgb(h, s, l);
2154
+ if (a != null && !Number.isNaN(a)) {
2155
+ return `rgba(${r},${g},${b},${Number(a.toFixed(3))})`;
2156
+ }
2157
+ return `rgb(${r},${g},${b})`;
2158
+ }
2159
+ return value;
2160
+ }
2161
+ function hslToRgb(h, s, l) {
2162
+ const hh = ((h % 360) + 360) % 360;
2163
+ const ss = Math.max(0, Math.min(100, s)) / 100;
2164
+ const ll = Math.max(0, Math.min(100, l)) / 100;
2165
+ const c = (1 - Math.abs(2 * ll - 1)) * ss;
2166
+ const x = c * (1 - Math.abs(((hh / 60) % 2) - 1));
2167
+ const m = ll - c / 2;
2168
+ let r1 = 0;
2169
+ let g1 = 0;
2170
+ let b1 = 0;
2171
+ if (hh < 60) {
2172
+ r1 = c;
2173
+ g1 = x;
2174
+ b1 = 0;
2175
+ }
2176
+ else if (hh < 120) {
2177
+ r1 = x;
2178
+ g1 = c;
2179
+ b1 = 0;
2180
+ }
2181
+ else if (hh < 180) {
2182
+ r1 = 0;
2183
+ g1 = c;
2184
+ b1 = x;
2185
+ }
2186
+ else if (hh < 240) {
2187
+ r1 = 0;
2188
+ g1 = x;
2189
+ b1 = c;
2190
+ }
2191
+ else if (hh < 300) {
2192
+ r1 = x;
2193
+ g1 = 0;
2194
+ b1 = c;
2195
+ }
2196
+ else {
2197
+ r1 = c;
2198
+ g1 = 0;
2199
+ b1 = x;
2200
+ }
2201
+ const r = Math.round((r1 + m) * 255);
2202
+ const g = Math.round((g1 + m) * 255);
2203
+ const b = Math.round((b1 + m) * 255);
2204
+ return [r, g, b];
2205
+ }
2206
+ function isLinearGradient(value) {
2207
+ if (!value || typeof value !== 'string')
2208
+ return false;
2209
+ return value.trim().toLowerCase().startsWith('linear-gradient(');
2210
+ }
2211
+ function parseSize(value, scaleFactor = 1) {
2212
+ if (value === undefined || value === null)
2213
+ return undefined;
2214
+ if (typeof value === 'number')
2215
+ return value * scaleFactor;
2216
+ if (typeof value === 'string') {
2217
+ const num = parseFloat(value);
2218
+ if (!isNaN(num))
2219
+ return num * scaleFactor;
2220
+ }
2221
+ return undefined;
2222
+ }
2223
+ function parseSizeOrPercent(value, scaleFactor = 1) {
2224
+ if (value === undefined || value === null)
2225
+ return undefined;
2226
+ if (typeof value === 'string' && value.endsWith('%'))
2227
+ return value;
2228
+ return parseSize(value, scaleFactor);
2229
+ }
2230
+ function flexDirectionFromConfig(dir) {
2231
+ switch (dir) {
2232
+ case 'horizontal': return 'row';
2233
+ case 'vertical': return 'column';
2234
+ case 'horizontal-reverse': return 'row-reverse';
2235
+ case 'vertical-reverse': return 'column-reverse';
2236
+ default: return 'column';
2237
+ }
2238
+ }
2239
+ const ALIGNMENT_VALUE_MAP = {
2240
+ top: 'flex-start',
2241
+ left: 'flex-start',
2242
+ right: 'flex-end',
2243
+ bottom: 'flex-end',
2244
+ start: 'flex-start',
2245
+ end: 'flex-end',
2246
+ leading: 'flex-start',
2247
+ trailing: 'flex-end',
2248
+ center: 'center',
2249
+ stretch: 'stretch',
2250
+ };
2251
+ const JUSTIFY_VALUE_MAP = {
2252
+ spaceBetween: 'space-between',
2253
+ 'space-between': 'space-between',
2254
+ spaceAround: 'space-around',
2255
+ 'space-around': 'space-around',
2256
+ spaceEvenly: 'space-evenly',
2257
+ 'space-evenly': 'space-evenly',
2258
+ top: 'flex-start',
2259
+ bottom: 'flex-end',
2260
+ left: 'flex-start',
2261
+ right: 'flex-end',
2262
+ start: 'flex-start',
2263
+ end: 'flex-end',
2264
+ leading: 'flex-start',
2265
+ trailing: 'flex-end',
2266
+ center: 'center',
2267
+ };
2268
+ function mapAlignmentValue(align) {
2269
+ if (!align)
2270
+ return undefined;
2271
+ return ALIGNMENT_VALUE_MAP[align] ?? undefined;
2272
+ }
2273
+ function mapJustifyValue(align) {
2274
+ if (!align)
2275
+ return undefined;
2276
+ return JUSTIFY_VALUE_MAP[align] ?? ALIGNMENT_VALUE_MAP[align];
2277
+ }
2278
+ function mapPositionAlignment(align) {
2279
+ return mapAlignmentValue(align);
2280
+ }
2281
+ function paddingAndMarginStyles(component, scaleFactor) {
2282
+ const s = {};
2283
+ if (component.leftPadding != null)
2284
+ s.paddingLeft = parseSize(component.leftPadding, scaleFactor);
2285
+ if (component.rightPadding != null)
2286
+ s.paddingRight = parseSize(component.rightPadding, scaleFactor);
2287
+ if (component.topPadding != null)
2288
+ s.paddingTop = parseSize(component.topPadding, scaleFactor);
2289
+ if (component.bottomPadding != null)
2290
+ s.paddingBottom = parseSize(component.bottomPadding, scaleFactor);
2291
+ if (component.leftMargin != null)
2292
+ s.marginLeft = parseSize(component.leftMargin, scaleFactor);
2293
+ if (component.rightMargin != null)
2294
+ s.marginRight = parseSize(component.rightMargin, scaleFactor);
2295
+ if (component.topMargin != null)
2296
+ s.marginTop = parseSize(component.topMargin, scaleFactor);
2297
+ if (component.bottomMargin != null)
2298
+ s.marginBottom = parseSize(component.bottomMargin, scaleFactor);
2299
+ return s;
2300
+ }
2301
+ function borderStyles(component, scaleFactor, inFocusedState = false) {
2302
+ const s = {};
2303
+ const bw = parseSize(inFocusedState ? (component.focusedBorderWidth ?? component.borderWidth) : component.borderWidth, scaleFactor);
2304
+ const bc = parseColor(inFocusedState ? (component.focusedBorderColor ?? component.borderColor) : component.borderColor);
2305
+ const br = parseSize(inFocusedState ? (component.focusedBorderRadius ?? component.borderRadius) : component.borderRadius, scaleFactor);
2306
+ const roundBorders = inFocusedState
2307
+ ? (component.focusedRoundBorders ?? component.roundBorders)
2308
+ : component.roundBorders;
2309
+ if (roundBorders?.length) {
2310
+ const mapping = {
2311
+ upperLeft: 'borderTopLeftRadius',
2312
+ upperRight: 'borderTopRightRadius',
2313
+ lowerLeft: 'borderBottomLeftRadius',
2314
+ lowerRight: 'borderBottomRightRadius',
2315
+ };
2316
+ for (const corner of roundBorders) {
2317
+ const key = mapping[corner];
2318
+ if (key && br != null)
2319
+ s[key] = br;
2320
+ }
2321
+ }
2322
+ else if (br != null) {
2323
+ s.borderRadius = br;
2324
+ }
2325
+ const sides = inFocusedState
2326
+ ? (component.focusedBorders ?? component.borders ?? [])
2327
+ : (component.borders ?? []);
2328
+ if (sides.length > 0 && bw != null) {
2329
+ const sideMap = {
2330
+ top: ['borderTopWidth', 'borderTopColor'],
2331
+ bottom: ['borderBottomWidth', 'borderBottomColor'],
2332
+ left: ['borderLeftWidth', 'borderLeftColor'],
2333
+ right: ['borderRightWidth', 'borderRightColor'],
2334
+ };
2335
+ for (const side of sides) {
2336
+ const [wKey, cKey] = sideMap[side];
2337
+ s[wKey] = bw;
2338
+ if (bc)
2339
+ s[cKey] = bc;
2340
+ }
2341
+ }
2342
+ else if (bw != null) {
2343
+ s.borderWidth = bw;
2344
+ if (bc)
2345
+ s.borderColor = bc;
2346
+ }
2347
+ else if (bc) {
2348
+ s.borderColor = bc;
2349
+ }
2350
+ return s;
2351
+ }
2352
+ function parseDropShadow(value) {
2353
+ if (!value || typeof value !== 'string')
2354
+ return null;
2355
+ const match = value.trim().match(/(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s+(.+)/);
2356
+ if (!match)
2357
+ return null;
2358
+ const x = parseFloat(match[1]);
2359
+ const y = parseFloat(match[2]);
2360
+ const blur = parseFloat(match[3]);
2361
+ const color = parseColor(match[4].trim());
2362
+ return { x, y, blur, color: color ?? undefined };
2363
+ }
2364
+ function shadowStyles(component) {
2365
+ const parsed = parseDropShadow(component.dropShadow);
2366
+ if (!parsed)
2367
+ return {};
2368
+ const { x, y, blur, color } = parsed;
2369
+ return {
2370
+ ...Platform.select({
2371
+ ios: {
2372
+ shadowColor: color ?? 'rgba(0,0,0,0.5)',
2373
+ shadowOffset: { width: x, height: y },
2374
+ shadowOpacity: 1,
2375
+ shadowRadius: blur,
2376
+ },
2377
+ android: {
2378
+ elevation: blur ? Math.ceil(blur / 2) : 4,
2379
+ },
2380
+ }),
2381
+ };
2382
+ }
2383
+ function sizeStyles(component, scaleFactor, parentDirection) {
2384
+ const s = {};
2385
+ const rawW = component.width ?? component.fixedWidth;
2386
+ const rawH = component.height ?? component.fixedHeight;
2387
+ const w = parseSizeOrPercent(rawW, scaleFactor);
2388
+ const h = parseSizeOrPercent(rawH, scaleFactor);
2389
+ if (w != null)
2390
+ s.width = w;
2391
+ if (h != null)
2392
+ s.height = h;
2393
+ s.maxWidth = '100%';
2394
+ if (rawW === 'fitContent') {
2395
+ s.flexShrink = 0;
2396
+ s.flexGrow = 0;
2397
+ }
2398
+ if (rawH === 'fitContent') {
2399
+ s.flexGrow = 0;
2400
+ }
2401
+ if (typeof rawW === 'string' && rawW.trim().endsWith('%')) {
2402
+ s.flexShrink = 1;
2403
+ s.minWidth = 0;
2404
+ }
2405
+ if (typeof rawH === 'string' && rawH.trim().endsWith('%')) {
2406
+ s.flexShrink = 1;
2407
+ }
2408
+ String(component.id ?? '');
2409
+ String(component.namiComponentType ?? '');
2410
+ if (rawW == null && rawH == null) {
2411
+ s.alignSelf = 'stretch';
2412
+ }
2413
+ return s;
2414
+ }
2415
+ function layoutStyles(component, scaleFactor) {
2416
+ const s = {};
2417
+ s.flexDirection = flexDirectionFromConfig(component.direction);
2418
+ const alignment = component.alignment;
2419
+ const horizontal = component.horizontalAlignment;
2420
+ const vertical = component.verticalAlignment;
2421
+ const verticalAlign = vertical ? mapAlignmentValue(vertical) : undefined;
2422
+ const horizontalAlign = horizontal ? mapAlignmentValue(horizontal) : undefined;
2423
+ const fallbackAlign = alignment ? (mapAlignmentValue(alignment) ?? 'center') : 'center';
2424
+ const fallbackJustify = alignment ? (mapJustifyValue(alignment) ?? 'center') : 'center';
2425
+ const isRow = s.flexDirection === 'row' || s.flexDirection === 'row-reverse';
2426
+ if (verticalAlign && horizontalAlign) {
2427
+ if (isRow) {
2428
+ s.alignItems = verticalAlign;
2429
+ s.justifyContent = mapJustifyValue(horizontal) ?? fallbackJustify;
2430
+ }
2431
+ else {
2432
+ s.alignItems = horizontalAlign;
2433
+ s.justifyContent = mapJustifyValue(vertical) ?? 'center';
2434
+ }
2435
+ }
2436
+ else if (!isRow) {
2437
+ s.alignItems = horizontalAlign ?? fallbackAlign;
2438
+ s.justifyContent = mapJustifyValue(vertical) ?? 'center';
2439
+ }
2440
+ else {
2441
+ s.alignItems = verticalAlign ?? 'center';
2442
+ s.justifyContent = mapJustifyValue(horizontal) ?? fallbackJustify;
2443
+ }
2444
+ if (component.grow)
2445
+ s.flexGrow = 1;
2446
+ return s;
2447
+ }
2448
+ function positionStyles(component) {
2449
+ const pos = component.position;
2450
+ if (!pos)
2451
+ return { position: 'relative' };
2452
+ const [alignment, spot] = pos.split('-');
2453
+ const s = { position: 'absolute' };
2454
+ const alignSelf = mapPositionAlignment(alignment);
2455
+ if (alignSelf)
2456
+ s.alignSelf = alignSelf;
2457
+ if (spot === 'top' || spot === 'bottom' || spot === 'left' || spot === 'right') {
2458
+ s[spot] = 0;
2459
+ }
2460
+ return s;
2461
+ }
2462
+ function backgroundColorStyle(component, inFocusedState = false) {
2463
+ const fill = typeof component.fillColor === 'string' ? component.fillColor : undefined;
2464
+ const focusedFill = typeof component.focusedFillColor === 'string' ? component.focusedFillColor : undefined;
2465
+ const useFocused = inFocusedState && focusedFill;
2466
+ const primary = useFocused ? focusedFill : fill;
2467
+ const fallback = useFocused ? component.focusedFillColorFallback : component.fillColorFallback;
2468
+ const gradientSource = primary ?? fill;
2469
+ if (isLinearGradient(gradientSource)) {
2470
+ const fallbackColor = parseColor(fallback);
2471
+ return fallbackColor ? { backgroundColor: fallbackColor } : { backgroundColor: 'transparent' };
2472
+ }
2473
+ const bg = parseColor(primary) ?? parseColor(fallback);
2474
+ if (bg)
2475
+ return { backgroundColor: bg };
2476
+ return {};
2477
+ }
2478
+ function transformStyles(component, scaleFactor) {
2479
+ const transforms = [];
2480
+ const mx = parseSize(component.moveX, scaleFactor);
2481
+ const my = parseSize(component.moveY, scaleFactor);
2482
+ if (mx)
2483
+ transforms.push({ translateX: mx });
2484
+ if (my)
2485
+ transforms.push({ translateY: my });
2486
+ if (transforms.length)
2487
+ return { transform: transforms };
2488
+ return {};
2489
+ }
2490
+ function applyStyles(component, scaleFactor = 1, inFocusedState = false, parentDirection) {
2491
+ return {
2492
+ ...positionStyles(component),
2493
+ ...paddingAndMarginStyles(component, scaleFactor),
2494
+ ...borderStyles(component, scaleFactor, inFocusedState),
2495
+ ...shadowStyles(component),
2496
+ ...sizeStyles(component, scaleFactor),
2497
+ ...layoutStyles(component),
2498
+ ...backgroundColorStyle(component, inFocusedState),
2499
+ ...transformStyles(component, scaleFactor),
2500
+ ...(component.zIndex != null ? { zIndex: component.zIndex } : {}),
2501
+ };
2502
+ }
2503
+ function resolveFillImageUrl(fillImage) {
2504
+ if (!fillImage)
2505
+ return undefined;
2506
+ if (typeof fillImage === 'string')
2507
+ return fillImage;
2508
+ if (typeof fillImage === 'object' && typeof fillImage.url === 'string')
2509
+ return fillImage.url;
2510
+ return undefined;
2511
+ }
2512
+ function childSpacingStyle(index, component, scaleFactor) {
2513
+ if (!component?.spacing || index === 0)
2514
+ return {};
2515
+ const spacing = parseSize(component.spacing, scaleFactor);
2516
+ if (spacing == null)
2517
+ return {};
2518
+ const isVertical = component.direction === 'vertical';
2519
+ return isVertical ? { marginTop: spacing } : { marginLeft: spacing };
2520
+ }
2521
+
2522
+ function getAttr(object, ...attrs) {
2523
+ let current = object;
2524
+ for (const attr of attrs) {
2525
+ if (current === undefined || current === null)
2526
+ return undefined;
2527
+ current = Array.isArray(current) ? current[+attr] : current[attr];
2528
+ }
2529
+ return current;
2530
+ }
2531
+ function interpolateString(value, replacements) {
2532
+ let output = value;
2533
+ if (typeof value !== 'string') {
2534
+ return output;
2535
+ }
2536
+ if (!value.includes('$')) {
2537
+ return value;
2538
+ }
2539
+ const regex = new RegExp(VAR_REGEX.source, VAR_REGEX.flags);
2540
+ const matches = [];
2541
+ let matchResult;
2542
+ while ((matchResult = regex.exec(value)) !== null) {
2543
+ matches.push(matchResult);
2544
+ if (!regex.global)
2545
+ break;
2546
+ if (matchResult.index === regex.lastIndex)
2547
+ regex.lastIndex++;
2548
+ }
2549
+ for (const [match, rawPath] of matches) {
2550
+ const path = interpolateString(rawPath, replacements);
2551
+ if (match === value)
2552
+ return replacer(match, path);
2553
+ if (path !== rawPath) {
2554
+ output = output.replace(rawPath, path);
2555
+ }
2556
+ output = output.replace(VAR_REGEX, replacer);
2557
+ }
2558
+ return output;
2559
+ function replacer(matchValue, pathValue) {
2560
+ const pathParts = String(pathValue).split('.');
2561
+ const firstKey = pathParts[0];
2562
+ if (!firstKey)
2563
+ return matchValue;
2564
+ const firstSegment = getAttr(replacements, firstKey);
2565
+ if (firstSegment === undefined)
2566
+ return matchValue;
2567
+ const isEmptyObject = typeof firstSegment === 'object'
2568
+ && firstSegment !== null
2569
+ && Object.keys(firstSegment).length === 0;
2570
+ if (isEmptyObject)
2571
+ return '';
2572
+ const newValue = getAttr(replacements, ...pathParts);
2573
+ if (newValue === undefined)
2574
+ return '';
2575
+ if (typeof newValue !== 'string')
2576
+ return newValue;
2577
+ return interpolateString(newValue, replacements);
2578
+ }
2579
+ }
2580
+ function interpolate(value, replacements) {
2581
+ if (Array.isArray(value)) {
2582
+ const output = [];
2583
+ for (const item of value) {
2584
+ const newValue = interpolate(item, replacements);
2585
+ if (Array.isArray(newValue)) {
2586
+ output.push(...newValue);
2587
+ }
2588
+ else {
2589
+ output.push(newValue);
2590
+ }
2591
+ }
2592
+ return output;
2593
+ }
2594
+ if (value === null || value === undefined)
2595
+ return value;
2596
+ if (typeof value === 'object') {
2597
+ const output = {};
2598
+ for (const [key, current] of Object.entries(value)) {
2599
+ output[key] = key === 'newRow' ? current : interpolate(current, replacements);
2600
+ }
2601
+ return output;
2602
+ }
2603
+ if (typeof value === 'string')
2604
+ return interpolateString(value, replacements);
2605
+ return value;
2606
+ }
2607
+ function buildSmartTextReplacements(state, flow, sku, block) {
2608
+ return {
2609
+ state,
2610
+ urlParams: getUrlParams(),
2611
+ flow: {
2612
+ isLaunched: !!flow?.manager?.flowOpen,
2613
+ previousStepAvailable: !!flow?.previousStepAvailable,
2614
+ nextStepAvailable: !!flow?.nextStepAvailable,
2615
+ },
2616
+ launch: state.launch,
2617
+ sku: sku ?? state.sku,
2618
+ customer: state.customer,
2619
+ block,
2620
+ };
2621
+ }
2622
+ function interpolateSmartText(value, replacements) {
2623
+ if (value == null)
2624
+ return value;
2625
+ if (typeof value !== 'string')
2626
+ return value;
2627
+ if (!value.includes(SMART_TEXT_PATTERN))
2628
+ return value;
2629
+ return interpolateString(value, replacements);
2630
+ }
2631
+
2632
+ const DEEP_SMART_TEXT_PRESERVE_KEYS = new Set([
2633
+ 'components',
2634
+ 'productBaseComponents',
2635
+ 'productFeaturedComponents',
2636
+ 'collapseHeader',
2637
+ ]);
2638
+ function componentSmartTextSku(component) {
2639
+ return component?.smartTextSku ?? component?.sku;
2640
+ }
2641
+ function conditionComponentMatches(ctx, condition, sku = componentSmartTextSku(condition)) {
2642
+ if (condition.assertions) {
2643
+ return condition.assertions.every((test) => testObjectMatches(ctx, test, undefined, sku));
2644
+ }
2645
+ if (condition.orAssertions) {
2646
+ return !condition.orAssertions.length || condition.orAssertions.some((test) => testObjectMatches(ctx, test, undefined, sku));
2647
+ }
2648
+ return false;
2649
+ }
2650
+ function withOverrides(ctx, { conditionAttributes, ...component }, sku = componentSmartTextSku(component)) {
2651
+ if (!conditionAttributes)
2652
+ return component;
2653
+ return conditionAttributes.reduce((nextComponent, condition) => {
2654
+ if (!conditionComponentMatches(ctx, condition, sku))
2655
+ return nextComponent;
2656
+ const resolvedAttributes = Object.fromEntries(Object.entries(condition.attributes ?? {}).map(([key, value]) => [
2657
+ key,
2658
+ valueFromSmartText(ctx, value, sku),
2659
+ ]));
2660
+ return { ...nextComponent, ...resolvedAttributes };
2661
+ }, component);
2662
+ }
2663
+ function valueFromSmartText(ctx, value, sku, block = null) {
2664
+ const replacements = buildSmartTextReplacements(ctx.state, ctx.flow, sku ?? ctx.state?.sku, block);
2665
+ if (typeof value === 'string' && value.includes(SMART_TEXT_PATTERN)) {
2666
+ return interpolateSmartText(value, replacements);
2667
+ }
2668
+ return value;
2669
+ }
2670
+ function resolveComponentSmartText(component, ctx) {
2671
+ const smartTextSku = componentSmartTextSku(component);
2672
+ const replacements = buildSmartTextReplacements(ctx.state, ctx.flow, smartTextSku);
2673
+ const preservedEntries = [];
2674
+ const shallowComponent = Object.entries(component ?? {}).reduce((output, [key, value]) => {
2675
+ if (DEEP_SMART_TEXT_PRESERVE_KEYS.has(key)) {
2676
+ // Child component trees need to keep their original template strings so they can
2677
+ // be resolved later with their own component/SKU context.
2678
+ preservedEntries.push([key, value]);
2679
+ return output;
2680
+ }
2681
+ output[key] = valueFromSmartText(ctx, value, smartTextSku);
2682
+ return output;
2683
+ }, {});
2684
+ const resolvedComponent = interpolate(shallowComponent, replacements);
2685
+ preservedEntries.forEach(([key, value]) => {
2686
+ resolvedComponent[key] = value;
2687
+ });
2688
+ return resolvedComponent;
2689
+ }
2690
+ function testObjectMatches(ctx, { value: rawValue, expected, operator }, block, sku) {
2691
+ let value = valueFromSmartText(ctx, rawValue, sku, block);
2692
+ expected = valueFromSmartText(ctx, expected, sku, block);
2693
+ if (operator === 'equals')
2694
+ return value === expected;
2695
+ if (operator === 'notEquals')
2696
+ return value !== expected;
2697
+ if (operator === 'contains') {
2698
+ if (typeof rawValue === 'string' && rawValue.includes('launch.productGroups')) {
2699
+ const launchGroups = ctx?.state?.launch?.productGroups;
2700
+ const fallbackGroups = Array.isArray(ctx?.state?.groups)
2701
+ ? ctx.state.groups.map((group) => group?.ref).filter(Boolean)
2702
+ : [];
2703
+ const unresolvedValue = value == null
2704
+ || value === ''
2705
+ || value === rawValue
2706
+ || (Array.isArray(value) && value.length === 0);
2707
+ if (unresolvedValue) {
2708
+ value = Array.isArray(launchGroups) && launchGroups.length ? launchGroups : fallbackGroups;
2709
+ }
2710
+ }
2711
+ if (!Array.isArray(value) && typeof value !== 'string' && !(value instanceof String)) {
2712
+ value = value?.toString?.();
2713
+ }
2714
+ if (expected === 'collapse') {
2715
+ expected += `_${ctx.getCurrentCollapsibleSku?.()?.skuId ?? ''}`;
2716
+ }
2717
+ return value?.includes?.(expected);
2718
+ }
2719
+ if (operator === 'notContains') {
2720
+ if (!Array.isArray(value) && typeof value !== 'string' && !(value instanceof String)) {
2721
+ value = value?.toString?.();
2722
+ }
2723
+ return !value?.includes?.(expected);
2724
+ }
2725
+ if (operator === 'set') {
2726
+ if (typeof expected === 'boolean') {
2727
+ return !!value && (!(value.toString().match(LIQUID_VARIABLE_REGEX)) === expected);
2728
+ }
2729
+ return !!value && !value.toString().match(LIQUID_VARIABLE_REGEX);
2730
+ }
2731
+ if (operator === 'notSet') {
2732
+ return !value || !!value.toString().match(LIQUID_VARIABLE_REGEX);
2733
+ }
2734
+ if (operator === 'gt')
2735
+ return value > expected;
2736
+ if (operator === 'gte')
2737
+ return value >= expected;
2738
+ if (operator === 'lt')
2739
+ return value < expected;
2740
+ if (operator === 'lte')
2741
+ return value <= expected;
2742
+ return false;
2743
+ }
2744
+
2745
+ const componentRendererCache = new Map();
2746
+ function resolveRenderer(rendererKey) {
2747
+ if (componentRendererCache.has(rendererKey)) {
2748
+ return componentRendererCache.get(rendererKey) ?? null;
2749
+ }
2750
+ let renderer = null;
2751
+ switch (rendererKey) {
2752
+ case 'NamiButton':
2753
+ renderer = require('./elements/NamiButton').NamiButton;
2754
+ break;
2755
+ case 'NamiText':
2756
+ renderer = require('./elements/NamiText').NamiText;
2757
+ break;
2758
+ case 'NamiSymbol':
2759
+ renderer = require('./elements/NamiSymbol').NamiSymbol;
2760
+ break;
2761
+ case 'NamiImage':
2762
+ renderer = require('./elements/NamiImage').NamiImage;
2763
+ break;
2764
+ case 'NamiSpacer':
2765
+ renderer = require('./elements/NamiSpacer').NamiSpacer;
2766
+ break;
2767
+ case 'NamiVideo':
2768
+ renderer = require('./elements/NamiVideo').NamiVideo;
2769
+ break;
2770
+ case 'NamiContainer':
2771
+ renderer = require('./containers/NamiContainer').NamiContainer;
2772
+ break;
2773
+ case 'NamiProductContainer':
2774
+ renderer = require('./containers/NamiProductContainer').NamiProductContainer;
2775
+ break;
2776
+ case 'NamiStack':
2777
+ renderer = require('./containers/NamiStack').NamiStack;
2778
+ break;
2779
+ case 'NamiCarousel':
2780
+ renderer = require('./containers/NamiCarousel').NamiCarousel;
2781
+ break;
2782
+ case 'NamiCollapseContainer':
2783
+ renderer = require('./containers/NamiCollapseContainer').NamiCollapseContainer;
2784
+ break;
2785
+ case 'NamiResponsiveGrid':
2786
+ renderer = require('./containers/NamiResponsiveGrid').NamiResponsiveGrid;
2787
+ break;
2788
+ case 'NamiRepeatingGrid':
2789
+ renderer = require('./containers/NamiRepeatingGrid').NamiRepeatingGrid;
2790
+ break;
2791
+ case 'NamiSegmentPicker':
2792
+ renderer = require('./elements/NamiSegmentPicker').NamiSegmentPicker;
2793
+ break;
2794
+ case 'NamiSegmentPickerItem':
2795
+ renderer = require('./elements/NamiSegmentPickerItem').NamiSegmentPickerItem;
2796
+ break;
2797
+ case 'NamiToggleSwitch':
2798
+ renderer = require('./elements/NamiToggleSwitch').NamiToggleSwitch;
2799
+ break;
2800
+ case 'NamiRadioButton':
2801
+ renderer = require('./elements/NamiRadioButton').NamiRadioButton;
2802
+ break;
2803
+ case 'NamiProgressIndicator':
2804
+ renderer = require('./elements/NamiProgressIndicator').NamiProgressIndicator;
2805
+ break;
2806
+ case 'NamiProgressBar':
2807
+ renderer = require('./elements/NamiProgressBar').NamiProgressBar;
2808
+ break;
2809
+ case 'NamiCountdownTimer':
2810
+ renderer = require('./elements/NamiCountdownTimer').NamiCountdownTimer;
2811
+ break;
2812
+ case 'NamiToggleButton':
2813
+ renderer = require('./elements/NamiToggleButton').NamiToggleButton;
2814
+ break;
2815
+ case 'NamiPlayPauseButton':
2816
+ renderer = require('./elements/NamiPlayPauseButton').NamiPlayPauseButton;
2817
+ break;
2818
+ case 'NamiVolumeButton':
2819
+ renderer = require('./elements/NamiVolumeButton').NamiVolumeButton;
2820
+ break;
2821
+ case 'NamiQRCode':
2822
+ renderer = require('./elements/NamiQRCode').NamiQRCode;
2823
+ break;
2824
+ default:
2825
+ renderer = null;
2826
+ }
2827
+ componentRendererCache.set(rendererKey, renderer);
2828
+ return renderer;
2829
+ }
2830
+ function renderWithKey(rendererKey, props) {
2831
+ const Renderer = resolveRenderer(rendererKey);
2832
+ return Renderer ? jsxRuntimeExports.jsx(Renderer, { ...props }) : null;
2833
+ }
2834
+ const TemplateRenderer = ({ component, scaleFactor = 1, onClose, parentDirection, parentCrossAxisFitContent }) => {
2835
+ const ctx = usePaywallContext();
2836
+ const smartTextSku = component?.smartTextSku ?? component?.sku;
2837
+ // Skip hidden components
2838
+ if (component.hidden)
2839
+ return null;
2840
+ // Handle condition components - evaluate condition, render children if matched
2841
+ if (component.component === 'condition') {
2842
+ const cond = component;
2843
+ if (!conditionComponentMatches(ctx, cond, smartTextSku))
2844
+ return null;
2845
+ // Render children of condition
2846
+ return (jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: cond.components?.map((child, i) => (jsxRuntimeExports.jsx(TemplateRenderer, { component: child, scaleFactor: scaleFactor, onClose: onClose, parentDirection: parentDirection, parentCrossAxisFitContent: parentCrossAxisFitContent }, child.id ?? i))) }));
2847
+ }
2848
+ // Apply conditionAttributes overrides if any match
2849
+ let resolvedComponent = component;
2850
+ if (component.conditionAttributes?.length) {
2851
+ resolvedComponent = withOverrides(ctx, resolvedComponent, smartTextSku);
2852
+ }
2853
+ // Resolve smart-text values on component fields (shallow)
2854
+ if (!resolvedComponent.__namiSmartTextResolved) {
2855
+ resolvedComponent = resolveComponentSmartText(resolvedComponent, ctx);
2856
+ }
2857
+ const componentType = resolvedComponent.component;
2858
+ return renderResolvedComponent(componentType, resolvedComponent, scaleFactor, onClose, parentDirection, parentCrossAxisFitContent);
2859
+ };
2860
+ function renderResolvedComponent(componentType, resolvedComponent, scaleFactor, onClose, parentDirection, parentCrossAxisFitContent) {
2861
+ const sharedProps = {
2862
+ component: resolvedComponent,
2863
+ scaleFactor,
2864
+ onClose,
2865
+ parentDirection,
2866
+ parentCrossAxisFitContent,
2867
+ };
2868
+ switch (componentType) {
2869
+ case 'button':
2870
+ return renderWithKey('NamiButton', sharedProps);
2871
+ case 'text':
2872
+ case 'title':
2873
+ case 'body':
2874
+ case 'legal':
2875
+ case 'text-list':
2876
+ return renderWithKey('NamiText', sharedProps);
2877
+ case 'symbol':
2878
+ return renderWithKey('NamiSymbol', sharedProps);
2879
+ case 'image':
2880
+ return renderWithKey('NamiImage', sharedProps);
2881
+ case 'spacer':
2882
+ return renderWithKey('NamiSpacer', sharedProps);
2883
+ case 'videoUrl':
2884
+ return renderWithKey('NamiVideo', sharedProps);
2885
+ case 'container':
2886
+ case 'formContainer':
2887
+ return renderWithKey('NamiContainer', sharedProps);
2888
+ case 'productContainer':
2889
+ return renderWithKey('NamiProductContainer', sharedProps);
2890
+ case 'stack':
2891
+ return renderWithKey('NamiStack', sharedProps);
2892
+ case 'carouselContainer':
2893
+ return renderWithKey('NamiCarousel', sharedProps);
2894
+ case 'collapseContainer':
2895
+ return renderWithKey('NamiCollapseContainer', sharedProps);
2896
+ case 'responsiveGrid':
2897
+ return renderWithKey('NamiResponsiveGrid', sharedProps);
2898
+ case 'repeatingGrid':
2899
+ return renderWithKey('NamiRepeatingGrid', sharedProps);
2900
+ case 'segmentPicker':
2901
+ case 'formSegmentPicker':
2902
+ return renderWithKey('NamiSegmentPicker', sharedProps);
2903
+ case 'segmentPickerItem':
2904
+ return renderWithKey('NamiSegmentPickerItem', sharedProps);
2905
+ case 'toggleSwitch':
2906
+ return renderWithKey('NamiToggleSwitch', sharedProps);
2907
+ case 'radio':
2908
+ return renderWithKey('NamiRadioButton', sharedProps);
2909
+ case 'progressIndicator':
2910
+ return renderWithKey('NamiProgressIndicator', sharedProps);
2911
+ case 'progressBar':
2912
+ return renderWithKey('NamiProgressBar', sharedProps);
2913
+ case 'countdownTimerText':
2914
+ return renderWithKey('NamiCountdownTimer', sharedProps);
2915
+ case 'toggleButton':
2916
+ return renderWithKey('NamiToggleButton', sharedProps);
2917
+ case 'playPauseButton':
2918
+ return renderWithKey('NamiPlayPauseButton', sharedProps);
2919
+ case 'volumeButton':
2920
+ return renderWithKey('NamiVolumeButton', sharedProps);
2921
+ case 'qrCode':
2922
+ return renderWithKey('NamiQRCode', sharedProps);
2923
+ default:
2924
+ return null;
2925
+ }
2926
+ }
2927
+
2928
+ function splitContainerStyles(style) {
2929
+ const { paddingLeft, paddingRight, paddingTop, paddingBottom, flexDirection, alignItems, justifyContent, ...rest } = style;
2930
+ const outer = { ...rest };
2931
+ const inner = {
2932
+ ...(paddingLeft != null ? { paddingLeft } : {}),
2933
+ ...(paddingRight != null ? { paddingRight } : {}),
2934
+ ...(paddingTop != null ? { paddingTop } : {}),
2935
+ ...(paddingBottom != null ? { paddingBottom } : {}),
2936
+ ...(flexDirection ? { flexDirection } : {}),
2937
+ ...(alignItems ? { alignItems } : {}),
2938
+ ...(justifyContent ? { justifyContent } : {}),
2939
+ };
2940
+ return { outer, inner };
2941
+ }
2942
+ const NamiContentContainer = ({ component, scaleFactor, onClose, }) => {
2943
+ const ctx = usePaywallContext();
2944
+ if (!component || component.hidden)
2945
+ return null;
2946
+ const baseStyle = useMemo(() => applyStyles(component, scaleFactor), [component, scaleFactor]);
2947
+ const { outer, inner } = splitContainerStyles(baseStyle);
2948
+ const formFactor = ctx.state.formFactor;
2949
+ const scrollEnabled = formFactor !== 'television';
2950
+ const direction = component.direction ?? 'vertical';
2951
+ const flexDir = flexDirectionFromConfig(direction);
2952
+ const contentAlignment = useMemo(() => {
2953
+ const vertical = component.verticalAlignment;
2954
+ const horizontal = component.horizontalAlignment;
2955
+ const isRow = flexDir === 'row' || flexDir === 'row-reverse';
2956
+ return {
2957
+ alignItems: isRow
2958
+ ? (vertical === 'top' ? 'flex-start' : vertical === 'bottom' ? 'flex-end' : vertical === 'center' ? 'center' : 'center')
2959
+ : (horizontal === 'left' ? 'flex-start' : horizontal === 'right' ? 'flex-end' : horizontal === 'center' ? 'center' : 'center'),
2960
+ justifyContent: isRow
2961
+ ? (horizontal === 'left' ? 'flex-start' : horizontal === 'right' ? 'flex-end' : horizontal === 'center' ? 'center' : 'flex-start')
2962
+ : (vertical === 'top' ? 'flex-start' : vertical === 'bottom' ? 'flex-end' : vertical === 'center' ? 'center' : 'flex-start'),
2963
+ };
2964
+ }, [component.verticalAlignment, component.horizontalAlignment, flexDir]);
2965
+ const renderedChildren = useMemo(() => {
2966
+ return component.components?.map((comp, i) => (jsxRuntimeExports.jsx(View, { style: [
2967
+ styles$5.fullWidth,
2968
+ i === 0
2969
+ ? null
2970
+ : childSpacingStyle(i, { spacing: component.spacing, direction }, scaleFactor),
2971
+ ], children: jsxRuntimeExports.jsx(TemplateRenderer, { component: comp, scaleFactor: scaleFactor, onClose: onClose, parentDirection: direction }) }, comp.id ?? i)));
2972
+ }, [component.components, component.spacing, direction, scaleFactor, onClose]);
2973
+ const innerContentStyle = useMemo(() => [
2974
+ styles$5.inner,
2975
+ {
2976
+ flexDirection: flexDir,
2977
+ },
2978
+ inner,
2979
+ contentAlignment,
2980
+ ], [flexDir, inner, contentAlignment]);
2981
+ if (!scrollEnabled) {
2982
+ return (jsxRuntimeExports.jsx(View, { style: [styles$5.outer, outer], children: jsxRuntimeExports.jsx(View, { style: [styles$5.scroll, innerContentStyle], children: renderedChildren }) }));
2983
+ }
2984
+ return (jsxRuntimeExports.jsx(View, { style: [styles$5.outer, outer], children: jsxRuntimeExports.jsx(ScrollView, { style: styles$5.scroll, contentContainerStyle: innerContentStyle, showsVerticalScrollIndicator: false, scrollEnabled: true, children: renderedChildren }) }));
2985
+ };
2986
+ const styles$5 = StyleSheet.create({
2987
+ outer: {
2988
+ flex: 1,
2989
+ minHeight: 0,
2990
+ zIndex: 2,
2991
+ },
2992
+ scroll: {
2993
+ flex: 1,
2994
+ },
2995
+ inner: {
2996
+ width: '100%',
2997
+ flexGrow: 1,
2998
+ },
2999
+ fullWidth: {
3000
+ width: '100%',
3001
+ },
3002
+ });
3003
+
3004
+ const NamiBackgroundContainer = ({ component, scaleFactor, onClose }) => {
3005
+ if (!component || component.hidden)
3006
+ return null;
3007
+ const containerStyle = useMemo(() => applyStyles(component, scaleFactor), [component, scaleFactor]);
3008
+ const fillImageUrl = resolveFillImageUrl(component.fillImage);
3009
+ const bgColor = parseColor(component.fillColor) ?? parseColor(component.fillColorFallback);
3010
+ const direction = component.direction ?? 'vertical';
3011
+ const content = (jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: component.components?.map((comp, i) => {
3012
+ const marginKey = direction === 'vertical' ? 'topMargin' : 'leftMargin';
3013
+ const spacedComponent = i === 0 || !component.spacing
3014
+ ? comp
3015
+ : {
3016
+ ...comp,
3017
+ [marginKey]: mergeRawMarginValue(comp[marginKey], component.spacing),
3018
+ };
3019
+ return (jsxRuntimeExports.jsx(TemplateRenderer, { component: spacedComponent, scaleFactor: scaleFactor, onClose: onClose, parentDirection: direction }, comp.id ?? i));
3020
+ }) }));
3021
+ if (fillImageUrl) {
3022
+ return (jsxRuntimeExports.jsx(ImageBackground, { source: { uri: fillImageUrl }, resizeMode: 'cover', style: [containerStyle, styles$4.background], children: content }));
3023
+ }
3024
+ return (jsxRuntimeExports.jsx(View, { style: [containerStyle, bgColor ? { backgroundColor: bgColor } : null, styles$4.background], children: content }));
3025
+ };
3026
+ function mergeRawMarginValue(existing, spacing) {
3027
+ if (existing == null)
3028
+ return spacing;
3029
+ const existingNumeric = toNumericMargin(existing);
3030
+ const spacingNumeric = toNumericMargin(spacing);
3031
+ if (existingNumeric == null || spacingNumeric == null) {
3032
+ return existing;
3033
+ }
3034
+ return existingNumeric + spacingNumeric;
3035
+ }
3036
+ function toNumericMargin(value) {
3037
+ if (typeof value === 'number' && Number.isFinite(value)) {
3038
+ return value;
3039
+ }
3040
+ if (typeof value !== 'string') {
3041
+ return null;
3042
+ }
3043
+ const trimmed = value.trim();
3044
+ if (!trimmed || !/^-?\d+(\.\d+)?$/.test(trimmed)) {
3045
+ return null;
3046
+ }
3047
+ const parsed = Number(trimmed);
3048
+ return Number.isFinite(parsed) ? parsed : null;
3049
+ }
3050
+ const styles$4 = StyleSheet.create({
3051
+ background: {
3052
+ ...StyleSheet.absoluteFillObject,
3053
+ },
3054
+ });
3055
+
3056
+ const NamiHeader = ({ components, scaleFactor, onClose }) => {
3057
+ const ctx = usePaywallContext();
3058
+ const formFactor = ctx.state.formFactor;
3059
+ const inFullScreen = ctx.state.fullScreenPresentation ?? false;
3060
+ const marginTop = formFactor === 'phone' && !inFullScreen ? 40 : 0;
3061
+ const list = Array.isArray(components)
3062
+ ? components
3063
+ : components?.components ?? [components];
3064
+ const renderedList = require$$0.useMemo(() => list.map((comp, i) => (jsxRuntimeExports.jsx(TemplateRenderer, { component: comp, scaleFactor: scaleFactor, onClose: onClose }, comp.id ?? i))), [list, scaleFactor, onClose]);
3065
+ return (jsxRuntimeExports.jsx(View, { style: [styles$3.header, { marginTop }], children: renderedList }));
3066
+ };
3067
+ const styles$3 = StyleSheet.create({
3068
+ header: {
3069
+ display: 'flex',
3070
+ position: 'relative',
3071
+ width: '100%',
3072
+ alignItems: 'center',
3073
+ justifyContent: 'center',
3074
+ zIndex: 2,
3075
+ },
3076
+ });
3077
+
3078
+ const NamiFooter = ({ components, scaleFactor, onClose }) => {
3079
+ const list = Array.isArray(components)
3080
+ ? components
3081
+ : components?.components ?? [components];
3082
+ return (jsxRuntimeExports.jsx(View, { style: styles$2.footer, children: list.map((comp, i) => (jsxRuntimeExports.jsx(TemplateRenderer, { component: comp, scaleFactor: scaleFactor, onClose: onClose }, comp.id ?? i))) }));
3083
+ };
3084
+ const styles$2 = StyleSheet.create({
3085
+ footer: {
3086
+ position: 'absolute',
3087
+ bottom: 0,
3088
+ width: '100%',
3089
+ alignItems: 'center',
3090
+ justifyContent: 'center',
3091
+ zIndex: 3,
3092
+ },
3093
+ });
3094
+
3095
+ function buildImpressionPayload(impression) {
3096
+ const payload = { ...impression };
3097
+ const sessionId = storageService.getSessionId();
3098
+ if (sessionId) {
3099
+ payload.session = sessionId;
3100
+ }
3101
+ const launchId = storageService.getLaunchId();
3102
+ if (launchId) {
3103
+ payload.launch_id = launchId;
3104
+ }
3105
+ payload.app_env = "production";
3106
+ payload.url_params = getUrlParams();
3107
+ return payload;
3108
+ }
3109
+ const postImpression = async (impression) => {
3110
+ if (isAnonymousMode()) {
3111
+ return;
3112
+ }
3113
+ const payload = buildImpressionPayload(impression);
3114
+ try {
3115
+ await NamiAPI.instance.postImpression(payload);
3116
+ }
3117
+ catch (error) {
3118
+ logger.error('Error posting impression', error);
3119
+ }
3120
+ };
3121
+
3122
+ let KeplerTVFocusGuideView = null;
3123
+ try {
3124
+ KeplerTVFocusGuideView = require('@amazon-devices/react-native-kepler').TVFocusGuideView;
3125
+ }
3126
+ catch {
3127
+ KeplerTVFocusGuideView = null;
3128
+ }
3129
+ const fontGateCache = new Map();
3130
+ const PaywallScreen = ({ paywall, onClose, onCommitted, holdInteractionUntilFocus = false, isActive = true, }) => {
3131
+ const ctx = usePaywallContext();
3132
+ const focusReadyCtx = useFirstFocusReadyContext();
3133
+ const scaleFactor = getDeviceScaleFactor(ctx.state.formFactor);
3134
+ const userInteractionEnabled = ctx.state.userInteractionEnabled !== false;
3135
+ const currentPageName = ctx.state.selectedPaywall === paywall
3136
+ ? ctx.state.currentPage
3137
+ : paywall.template?.initialState?.currentPage ?? 'page1';
3138
+ const page = useMemo(() => {
3139
+ let currentPage;
3140
+ if (ctx.state.selectedPaywall === paywall) {
3141
+ currentPage = ctx.state.currentPage;
3142
+ }
3143
+ else {
3144
+ currentPage = paywall.template?.initialState?.currentPage ?? 'page1';
3145
+ }
3146
+ return paywall.template?.pages?.find((p) => p.name === currentPage) ?? null;
3147
+ }, [paywall, ctx.state.selectedPaywall, ctx.state.currentPage]);
3148
+ const firstFocusReadyKey = `${paywall.id ?? 'unknown'}:${page?.name ?? currentPageName}:${ctx.state.formFactor ?? ''}`;
3149
+ const shouldHoldForFocus = holdInteractionUntilFocus && ctx.state.formFactor === 'television';
3150
+ const focusReady = !shouldHoldForFocus || focusReadyCtx.firstFocusReadyKey === firstFocusReadyKey;
3151
+ const interactionEnabled = userInteractionEnabled && focusReady;
3152
+ const fontNames = useMemo(() => Object.keys(paywall.fonts ?? {}).sort(), [paywall.fonts]);
3153
+ const fontGateCacheKey = `${paywall.id ?? 'unknown'}:${page?.name ?? currentPageName}:${fontNames.join(',')}`;
3154
+ const hasFonts = fontNames.length > 0;
3155
+ const [fontGateState, setFontGateState] = useState(() => {
3156
+ if (!hasFonts) {
3157
+ return 'ready';
3158
+ }
3159
+ return fontGateCache.get(fontGateCacheKey) ?? 'pending';
3160
+ });
3161
+ useEffect(() => {
3162
+ void postImpression({
3163
+ segment: ctx.state.selectedCampaign?.segment,
3164
+ call_to_action: paywall.id,
3165
+ });
3166
+ NamiEventEmitter.getInstance().emit(PAYWALL_ACTION_EVENT, {
3167
+ ...ctx.getPaywallActionEventData(),
3168
+ action: NamiPaywallAction.SHOW_PAYWALL,
3169
+ });
3170
+ }, [paywall.id, ctx.state.selectedCampaign?.segment]);
3171
+ useEffect(() => {
3172
+ let cancelled = false;
3173
+ if (!hasFonts) {
3174
+ setFontGateState('ready');
3175
+ return;
3176
+ }
3177
+ const cachedGateState = fontGateCache.get(fontGateCacheKey);
3178
+ if (cachedGateState) {
3179
+ setFontGateState(cachedGateState);
3180
+ return;
3181
+ }
3182
+ setFontGateState('pending');
3183
+ void prepareAndLoadFontsWithTimeout(paywall.fonts, 1500).then((result) => {
3184
+ if (!cancelled) {
3185
+ const resolvedState = result === 'ready' ? 'ready' : 'fallback';
3186
+ fontGateCache.set(fontGateCacheKey, resolvedState);
3187
+ setFontGateState(resolvedState);
3188
+ }
3189
+ });
3190
+ return () => {
3191
+ cancelled = true;
3192
+ };
3193
+ }, [currentPageName, fontGateCacheKey, fontNames.length, hasFonts, page?.name, paywall.fonts, paywall.id]);
3194
+ useEffect(() => {
3195
+ if (fontGateState === 'pending') {
3196
+ return;
3197
+ }
3198
+ paywall.id ?? 'unknown';
3199
+ const pageName = page?.name ?? currentPageName;
3200
+ onCommitted?.(paywall, pageName, ctx.state.formFactor);
3201
+ }, [fontGateState, paywall, paywall.id, page?.name, currentPageName, interactionEnabled, onCommitted, ctx.state.formFactor]);
3202
+ useEffect(() => {
3203
+ if (!isActive) {
3204
+ return;
3205
+ }
3206
+ const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
3207
+ const hasRemoteBackActions = !!ctx.flow?.currentFlowStep?.actions?.[NamiReservedActions.REMOTE_BACK]?.length;
3208
+ if (hasRemoteBackActions) {
3209
+ return false;
3210
+ }
3211
+ const canGoBackPage = ctx.canGoBackPage();
3212
+ if (!canGoBackPage) {
3213
+ return false;
3214
+ }
3215
+ return ctx.goBackPage();
3216
+ });
3217
+ return () => subscription.remove();
3218
+ }, [ctx, isActive]);
3219
+ const { backgroundContainer, header = [], contentContainer, footer = [], } = (page ?? {});
3220
+ const hasHeader = Array.isArray(header)
3221
+ ? header.length > 0
3222
+ : Array.isArray(header?.components)
3223
+ ? header.components.length > 0
3224
+ : Boolean(header);
3225
+ const hasFooter = Array.isArray(footer)
3226
+ ? footer.length > 0
3227
+ : Array.isArray(footer?.components)
3228
+ ? footer.components.length > 0
3229
+ : Boolean(footer);
3230
+ const bgColor = parseColor(backgroundContainer?.fillColor)
3231
+ ?? parseColor(backgroundContainer?.fillColorFallback)
3232
+ ?? 'transparent';
3233
+ const waitingOverlayColor = bgColor === 'transparent' ? '#111118' : bgColor;
3234
+ const PageFocusWrapper = ctx.state.formFactor === 'television' && KeplerTVFocusGuideView
3235
+ ? KeplerTVFocusGuideView
3236
+ : View;
3237
+ const pageFocusWrapperProps = ctx.state.formFactor === 'television' && KeplerTVFocusGuideView
3238
+ ? {
3239
+ autoFocus: true,
3240
+ style: styles$1.pageRoot,
3241
+ }
3242
+ : { style: styles$1.pageRoot };
3243
+ if (!page) {
3244
+ throw new Error(`Page with name ${ctx.state.currentPage} not found in paywall template.`);
3245
+ }
3246
+ if (fontGateState === 'pending') {
3247
+ return (jsxRuntimeExports.jsx(View, { style: [styles$1.screen, styles$1.pendingScreen, { backgroundColor: waitingOverlayColor }], children: jsxRuntimeExports.jsx(ActivityIndicator, { size: "large", color: "#FFFFFF" }) }));
3248
+ }
3249
+ return (jsxRuntimeExports.jsx(View, { style: [styles$1.screen, { backgroundColor: bgColor }], pointerEvents: interactionEnabled ? 'auto' : 'none', children: jsxRuntimeExports.jsxs(PageFocusWrapper, { ...pageFocusWrapperProps, children: [backgroundContainer && (jsxRuntimeExports.jsx(NamiBackgroundContainer, { component: backgroundContainer, scaleFactor: scaleFactor, onClose: onClose })), hasHeader && (jsxRuntimeExports.jsx(NamiHeader, { components: header, scaleFactor: scaleFactor, onClose: onClose })), contentContainer && (jsxRuntimeExports.jsx(NamiContentContainer, { component: contentContainer, scaleFactor: scaleFactor, onClose: onClose })), hasFooter && (jsxRuntimeExports.jsx(NamiFooter, { components: footer, scaleFactor: scaleFactor, onClose: onClose })), shouldHoldForFocus && !focusReady && (jsxRuntimeExports.jsx(View, { pointerEvents: "none", style: [styles$1.waitingOverlay, { backgroundColor: waitingOverlayColor }] }))] }, `${paywall.id}:${page.name ?? currentPageName}`) }));
3250
+ };
3251
+ const styles$1 = StyleSheet.create({
3252
+ screen: { flex: 1 },
3253
+ pendingScreen: {
3254
+ alignItems: 'center',
3255
+ justifyContent: 'center',
3256
+ },
3257
+ pageRoot: { flex: 1 },
3258
+ waitingOverlay: {
3259
+ ...StyleSheet.absoluteFillObject,
3260
+ alignItems: 'center',
3261
+ justifyContent: 'center',
3262
+ zIndex: 20,
3263
+ },
3264
+ });
3265
+
3266
+ createContext(null);
3267
+ createContext(false);
3268
+ const FocusContext = createContext(true);
3269
+ createContext(null);
3270
+ const FocusProvider = ({ children, enabled }) => (jsxRuntimeExports.jsx(FocusContext.Provider, { value: enabled, children: children }));
3271
+
3272
+ const DEFAULT_CONTEXT = {
3273
+ productGroups: [],
3274
+ customAttributes: {},
3275
+ customObject: {},
3276
+ currentGroup: '',
3277
+ };
3278
+ const REMOTE_BACK_FALLBACK_DELAY_MS = 600;
3279
+ const NamiView = ({ placement, url, onClose, onSignIn, onDeepLink, onPurchase, onRestore, onPaywallEvent, onHandoff, onFlowEvent, }) => {
3280
+ const [launchRequest, setLaunchRequest] = useState(null);
3281
+ const [reloadKey, setReloadKey] = useState(0);
3282
+ const [isClosing, setIsClosing] = useState(false);
3283
+ const [paywallData, setPaywallData] = useState(null);
3284
+ const [campaignData, setCampaignData] = useState(null);
3285
+ const [launchPreviewPaywall, setLaunchPreviewPaywall] = useState(null);
3286
+ const [pendingTransitionPaywall, setPendingTransitionPaywall] = useState(null);
3287
+ const [initialScreenCommitted, setInitialScreenCommitted] = useState(false);
3288
+ const [loading, setLoading] = useState(true);
3289
+ const [flowState, setFlowState] = useState({ paywalls: [], index: 0, animation: null });
3290
+ const flowRef = useRef();
3291
+ const lastLaunchKeyRef = useRef('');
3292
+ const lastAppearStepIdRef = useRef('');
3293
+ const launchCacheRef = useRef(new Map());
3294
+ const remoteBackFallbackTimeoutRef = useRef(null);
3295
+ const remoteBackFallbackAttemptRef = useRef(null);
3296
+ const pendingNavigationFrameRef = useRef(null);
3297
+ // Stable refs for callbacks so event listeners always see latest values
3298
+ const onCloseRef = useRef(onClose);
3299
+ const onSignInRef = useRef(onSignIn);
3300
+ const onDeepLinkRef = useRef(onDeepLink);
3301
+ const onPurchaseRef = useRef(onPurchase);
3302
+ const onRestoreRef = useRef(onRestore);
3303
+ const onPaywallEventRef = useRef(onPaywallEvent);
3304
+ const onHandoffRef = useRef(onHandoff);
3305
+ const onFlowEventRef = useRef(onFlowEvent);
3306
+ useEffect(() => { onCloseRef.current = onClose; }, [onClose]);
3307
+ useEffect(() => { onSignInRef.current = onSignIn; }, [onSignIn]);
3308
+ useEffect(() => { onDeepLinkRef.current = onDeepLink; }, [onDeepLink]);
3309
+ useEffect(() => { onPurchaseRef.current = onPurchase; }, [onPurchase]);
3310
+ useEffect(() => { onRestoreRef.current = onRestore; }, [onRestore]);
3311
+ useEffect(() => { onPaywallEventRef.current = onPaywallEvent; }, [onPaywallEvent]);
3312
+ useEffect(() => { onHandoffRef.current = onHandoff; }, [onHandoff]);
3313
+ useEffect(() => { onFlowEventRef.current = onFlowEvent; }, [onFlowEvent]);
3314
+ const resolvedLaunch = useMemo(() => {
3315
+ if (launchRequest?.value)
3316
+ return launchRequest;
3317
+ if (url)
3318
+ return { type: 'url', value: url };
3319
+ if (placement)
3320
+ return { type: 'label', value: placement };
3321
+ return { type: undefined, value: '' };
3322
+ }, [launchRequest, url, placement]);
3323
+ const ctx = useMemo(() => ({
3324
+ ...DEFAULT_CONTEXT,
3325
+ ...(resolvedLaunch.context ?? launchRequest?.context ?? {}),
3326
+ customAttributes: {
3327
+ ...DEFAULT_CONTEXT.customAttributes,
3328
+ ...(resolvedLaunch.context?.customAttributes ??
3329
+ launchRequest?.context?.customAttributes ??
3330
+ {}),
3331
+ },
3332
+ customObject: {
3333
+ ...DEFAULT_CONTEXT.customObject,
3334
+ ...(resolvedLaunch.context?.customObject ??
3335
+ launchRequest?.context?.customObject ??
3336
+ {}),
3337
+ },
3338
+ productGroups: resolvedLaunch.context?.productGroups ??
3339
+ launchRequest?.context?.productGroups ??
3340
+ DEFAULT_CONTEXT.productGroups,
3341
+ }), [launchRequest?.context, resolvedLaunch.context]);
3342
+ const isFlowCampaign = isNamiFlowCampaign(campaignData);
3343
+ const clearRemoteBackFallback = useCallback(() => {
3344
+ if (remoteBackFallbackTimeoutRef.current) {
3345
+ clearTimeout(remoteBackFallbackTimeoutRef.current);
3346
+ remoteBackFallbackTimeoutRef.current = null;
3347
+ }
3348
+ remoteBackFallbackAttemptRef.current = null;
3349
+ }, []);
3350
+ const finishActiveFlow = useCallback(() => {
3351
+ clearRemoteBackFallback();
3352
+ const activeFlow = flowRef.current;
3353
+ if (!activeFlow)
3354
+ return;
3355
+ if (NamiFlowManager.instance.currentFlow === activeFlow || NamiFlowManager.instance.flowOpen) {
3356
+ NamiFlowManager.finish();
3357
+ }
3358
+ flowRef.current = undefined;
3359
+ lastAppearStepIdRef.current = '';
3360
+ }, [clearRemoteBackFallback]);
3361
+ const requestClose = useCallback(() => {
3362
+ clearRemoteBackFallback();
3363
+ if (onCloseRef.current) {
3364
+ setIsClosing(true);
3365
+ onCloseRef.current();
3366
+ return;
3367
+ }
3368
+ }, [clearRemoteBackFallback]);
3369
+ const scheduleRemoteBackFallbackClose = useCallback((flow, stepId, paywallId) => {
3370
+ clearRemoteBackFallback();
3371
+ remoteBackFallbackAttemptRef.current = {
3372
+ flow,
3373
+ stepId,
3374
+ paywallId,
3375
+ };
3376
+ remoteBackFallbackTimeoutRef.current = setTimeout(() => {
3377
+ remoteBackFallbackTimeoutRef.current = null;
3378
+ const attempt = remoteBackFallbackAttemptRef.current;
3379
+ const activeFlow = flowRef.current;
3380
+ activeFlow?.currentFlowStep?.id;
3381
+ activeFlow?.currentFlowStep?.type;
3382
+ const activePaywallId = paywallData?.id;
3383
+ const transitionedToTerminalExit = !!attempt
3384
+ && attempt.flow === activeFlow
3385
+ && activePaywallId === attempt.paywallId
3386
+ && (activeFlow?.currentFlowStep?.type === 'exit'
3387
+ || NamiFlowManager.instance.flowOpen === false);
3388
+ const shouldFallbackClose = !isClosing
3389
+ && !!attempt
3390
+ && ((attempt.flow === activeFlow
3391
+ && activeFlow?.currentFlowStep?.id === attempt.stepId
3392
+ && activePaywallId === attempt.paywallId
3393
+ && activeFlow?.previousStepAvailable === false)
3394
+ || transitionedToTerminalExit);
3395
+ if (!shouldFallbackClose) {
3396
+ remoteBackFallbackAttemptRef.current = null;
3397
+ return;
3398
+ }
3399
+ remoteBackFallbackAttemptRef.current = null;
3400
+ finishActiveFlow();
3401
+ requestClose();
3402
+ }, REMOTE_BACK_FALLBACK_DELAY_MS);
3403
+ }, [clearRemoteBackFallback, finishActiveFlow, isClosing, paywallData?.id, requestClose]);
3404
+ const handleFlowNavigation = useCallback((paywall, options) => {
3405
+ const flow = flowRef.current;
3406
+ const currentPaywall = flowState.paywalls[flowState.index] ??
3407
+ flowState.paywalls[flowState.paywalls.length - 1] ??
3408
+ paywallData;
3409
+ const shouldUseAnimatedTransition = options.transition !== 'none'
3410
+ && !!currentPaywall
3411
+ && currentPaywall.id !== paywall.id;
3412
+ const applyNavigation = () => {
3413
+ if (flow?.previousFlowStep) {
3414
+ flow.executeLifecycle(flow.previousFlowStep, NamiReservedActions.DISAPPEAR);
3415
+ }
3416
+ setFlowState(() => {
3417
+ if (!shouldUseAnimatedTransition || !currentPaywall) {
3418
+ return { paywalls: [paywall], index: 0, animation: options };
3419
+ }
3420
+ return {
3421
+ paywalls: [currentPaywall, paywall],
3422
+ index: 1,
3423
+ animation: options,
3424
+ };
3425
+ });
3426
+ setPaywallData(paywall);
3427
+ if (flow?.currentFlowStep) {
3428
+ flow.executeLifecycle(flow.currentFlowStep, NamiReservedActions.APPEAR);
3429
+ lastAppearStepIdRef.current = flow.currentFlowStep.id;
3430
+ }
3431
+ };
3432
+ if (!shouldUseAnimatedTransition) {
3433
+ setPendingTransitionPaywall(null);
3434
+ applyNavigation();
3435
+ return;
3436
+ }
3437
+ setPendingTransitionPaywall(paywall);
3438
+ if (pendingNavigationFrameRef.current != null) {
3439
+ cancelAnimationFrame(pendingNavigationFrameRef.current);
3440
+ }
3441
+ pendingNavigationFrameRef.current = requestAnimationFrame(() => {
3442
+ pendingNavigationFrameRef.current = null;
3443
+ applyNavigation();
3444
+ });
3445
+ }, [flowState.index, flowState.paywalls, paywallData]);
3446
+ const handleFlowAnimationSettled = useCallback((paywall) => {
3447
+ setPendingTransitionPaywall(null);
3448
+ setFlowState((prev) => {
3449
+ const current = prev.paywalls[prev.index] ?? prev.paywalls[prev.paywalls.length - 1];
3450
+ if (!prev.animation && current?.id === paywall.id) {
3451
+ return prev;
3452
+ }
3453
+ if (prev.paywalls.length > 1 && prev.index > 0) {
3454
+ return {
3455
+ paywalls: prev.paywalls,
3456
+ index: prev.index,
3457
+ animation: null,
3458
+ };
3459
+ }
3460
+ return { paywalls: [paywall], index: 0, animation: null };
3461
+ });
3462
+ }, []);
3463
+ useEffect(() => {
3464
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
3465
+ const flow = flowRef.current;
3466
+ if (flow?.currentFlowStep) {
3467
+ const stepcrumbs = Array.isArray(flow.stepcrumbs) ? flow.stepcrumbs : [];
3468
+ const previousScreenStep = [...stepcrumbs]
3469
+ .slice(0, -1)
3470
+ .reverse()
3471
+ .find((step) => step?.type === 'screen');
3472
+ const hasRemoteBackActions = !!flow.currentFlowStep?.actions?.[NamiReservedActions.REMOTE_BACK]?.length;
3473
+ const canNavigateBackInFlow = flow.previousStepAvailable
3474
+ || (Boolean(previousScreenStep)
3475
+ && previousScreenStep?.allow_back_to !== false);
3476
+ if (hasRemoteBackActions) {
3477
+ if (!canNavigateBackInFlow) {
3478
+ scheduleRemoteBackFallbackClose(flow, flow.currentFlowStep.id, paywallData?.id);
3479
+ }
3480
+ else {
3481
+ clearRemoteBackFallback();
3482
+ }
3483
+ flow.triggerActions(NamiReservedActions.REMOTE_BACK);
3484
+ return true;
3485
+ }
3486
+ clearRemoteBackFallback();
3487
+ if (!canNavigateBackInFlow) {
3488
+ finishActiveFlow();
3489
+ requestClose();
3490
+ return true;
3491
+ }
3492
+ flow.back();
3493
+ return true;
3494
+ }
3495
+ if (paywallData) {
3496
+ requestClose();
3497
+ return true;
3498
+ }
3499
+ return false;
3500
+ });
3501
+ return () => subscription.remove();
3502
+ }, [clearRemoteBackFallback, finishActiveFlow, paywallData, requestClose, scheduleRemoteBackFallbackClose]);
3503
+ // ─── Paywall action event listener ───────────────────────────────────
3504
+ useEffect(() => {
3505
+ const emitter = NamiEventEmitter.getInstance();
3506
+ const handler = (event) => {
3507
+ // Forward to catch-all
3508
+ onPaywallEventRef.current?.(event);
3509
+ // Route to specific callbacks
3510
+ switch (event.action) {
3511
+ case NamiPaywallAction.CLOSE_PAYWALL:
3512
+ onCloseRef.current?.();
3513
+ break;
3514
+ case NamiPaywallAction.SIGN_IN:
3515
+ onSignInRef.current?.();
3516
+ break;
3517
+ case NamiPaywallAction.DEEPLINK:
3518
+ if (event.deeplinkUrl) {
3519
+ onDeepLinkRef.current?.(event.deeplinkUrl);
3520
+ }
3521
+ break;
3522
+ case NamiPaywallAction.BUY_SKU:
3523
+ onPurchaseRef.current?.(event.sku);
3524
+ break;
3525
+ case NamiPaywallAction.RESTORE_PURCHASES:
3526
+ onRestoreRef.current?.();
3527
+ break;
3528
+ }
3529
+ };
3530
+ emitter.addListener(PAYWALL_ACTION_EVENT, handler);
3531
+ return () => {
3532
+ emitter.removeListener(PAYWALL_ACTION_EVENT, handler);
3533
+ };
3534
+ }, [finishActiveFlow]);
3535
+ // ─── Flow handlers ───────────────────────────────────────────────────
3536
+ useEffect(() => {
3537
+ NamiFlowManager.registerStepHandoff((handoffTag, handoffData) => {
3538
+ onHandoffRef.current?.(handoffTag, handoffData);
3539
+ });
3540
+ NamiFlowManager.registerEventHandler((eventData) => {
3541
+ onFlowEventRef.current?.(eventData);
3542
+ });
3543
+ return () => {
3544
+ NamiFlowManager.registerStepHandoff(undefined);
3545
+ NamiFlowManager.registerEventHandler(() => { });
3546
+ };
3547
+ }, []);
3548
+ // ─── ExpoUIAdapter listener subscriptions ────────────────────────────
3549
+ useEffect(() => {
3550
+ const unsubPaywall = expoUIAdapter.onPaywallRequested((info, context) => {
3551
+ setLaunchRequest({ type: info?.type, value: info?.value ?? '', context });
3552
+ });
3553
+ const unsubReRender = expoUIAdapter.onReRenderRequested(() => {
3554
+ setReloadKey(k => k + 1);
3555
+ });
3556
+ const unsubFlow = expoUIAdapter.onFlowNavigationRequested((paywall, options) => {
3557
+ handleFlowNavigation(paywall, options);
3558
+ });
3559
+ return () => {
3560
+ unsubPaywall();
3561
+ unsubReRender();
3562
+ unsubFlow();
3563
+ };
3564
+ }, [handleFlowNavigation]);
3565
+ useEffect(() => {
3566
+ return () => {
3567
+ if (pendingNavigationFrameRef.current != null) {
3568
+ cancelAnimationFrame(pendingNavigationFrameRef.current);
3569
+ pendingNavigationFrameRef.current = null;
3570
+ }
3571
+ clearRemoteBackFallback();
3572
+ finishActiveFlow();
3573
+ };
3574
+ }, [clearRemoteBackFallback, finishActiveFlow]);
3575
+ // ─── Reset state when launch key changes ─────────────────────────────
3576
+ useEffect(() => {
3577
+ const launchKey = `${resolvedLaunch.type ?? ''}:${resolvedLaunch.value ?? ''}`;
3578
+ if (launchKey !== lastLaunchKeyRef.current) {
3579
+ lastLaunchKeyRef.current = launchKey;
3580
+ setIsClosing(false);
3581
+ setFlowState({ paywalls: [], index: 0, animation: null });
3582
+ finishActiveFlow();
3583
+ setPaywallData(null);
3584
+ setCampaignData(null);
3585
+ setLaunchPreviewPaywall(null);
3586
+ setPendingTransitionPaywall(null);
3587
+ setInitialScreenCommitted(false);
3588
+ lastAppearStepIdRef.current = '';
3589
+ }
3590
+ }, [finishActiveFlow, resolvedLaunch.type, resolvedLaunch.value]);
3591
+ // ─── Campaign / paywall resolution ───────────────────────────────────
3592
+ useEffect(() => {
3593
+ let cancelled = false;
3594
+ const resolveLaunch = async () => {
3595
+ const value = resolvedLaunch.value;
3596
+ const type = resolvedLaunch.type ?? (url ? 'url' : 'label');
3597
+ const cacheKey = `${type}:${value}`;
3598
+ if (!value) {
3599
+ setLoading(false);
3600
+ setPaywallData(null);
3601
+ setCampaignData(null);
3602
+ setLaunchPreviewPaywall(null);
3603
+ return;
3604
+ }
3605
+ const cachedLaunch = launchCacheRef.current.get(cacheKey);
3606
+ if (cachedLaunch) {
3607
+ setLaunchPreviewPaywall(cachedLaunch.launchPreviewPaywall);
3608
+ setPaywallData(cachedLaunch.paywallData);
3609
+ setCampaignData(cachedLaunch.campaignData);
3610
+ setLoading(false);
3611
+ }
3612
+ else {
3613
+ setLoading(true);
3614
+ }
3615
+ try {
3616
+ const data = getPaywallDataFromLabel(value, type);
3617
+ const paywall = data?.paywall;
3618
+ const flowPaywalls = isNamiFlowCampaign(data?.campaign)
3619
+ ? (data?.campaign?.flow?.object?.screens ?? [])
3620
+ .map((screenId) => getPaywall(screenId))
3621
+ .filter((item) => item != null)
3622
+ : [];
3623
+ const initialPaywall = paywall ?? flowPaywalls[0];
3624
+ const nextCampaign = data?.campaign ? data.campaign : { value, type };
3625
+ const nextLaunch = {
3626
+ launchPreviewPaywall: initialPaywall ?? null,
3627
+ paywallData: data?.paywall ?? null,
3628
+ campaignData: nextCampaign,
3629
+ };
3630
+ if (!cancelled) {
3631
+ setLaunchPreviewPaywall(nextLaunch.launchPreviewPaywall);
3632
+ setInitialScreenCommitted(false);
3633
+ setPaywallData(nextLaunch.paywallData);
3634
+ setCampaignData(nextLaunch.campaignData);
3635
+ setLoading(false);
3636
+ launchCacheRef.current.set(cacheKey, nextLaunch);
3637
+ }
3638
+ prewarmPaywallFonts([paywall, ...flowPaywalls]);
3639
+ if (initialPaywall?.fonts) {
3640
+ void prepareAndLoadFontsWithTimeout(initialPaywall.fonts);
3641
+ }
3642
+ }
3643
+ catch (e) {
3644
+ if (!cancelled) {
3645
+ setLoading(false);
3646
+ }
3647
+ logger.warn('[NamiExpo] Failed to resolve paywall launch.', e);
3648
+ }
3649
+ };
3650
+ void resolveLaunch();
3651
+ return () => {
3652
+ cancelled = true;
3653
+ };
3654
+ }, [resolvedLaunch.value, resolvedLaunch.type, url, reloadKey]);
3655
+ // ─── Flow presentation ───────────────────────────────────────────────
3656
+ useEffect(() => {
3657
+ if (!campaignData)
3658
+ return;
3659
+ if (!isNamiFlowCampaign(campaignData))
3660
+ return;
3661
+ const screens = campaignData.flow?.object?.screens ?? [];
3662
+ if (screens.length && !hasAllPaywalls(screens))
3663
+ return;
3664
+ if (flowRef.current)
3665
+ return;
3666
+ const flow = NamiFlowManager.instance.presentFlow(campaignData, {
3667
+ type: resolvedLaunch.type,
3668
+ value: resolvedLaunch.value,
3669
+ context: ctx,
3670
+ }, ctx);
3671
+ flowRef.current = flow;
3672
+ }, [campaignData, resolvedLaunch.type, resolvedLaunch.value, ctx, reloadKey]);
3673
+ useEffect(() => {
3674
+ const flow = flowRef.current;
3675
+ const activePaywall = flowState.paywalls[flowState.index] ??
3676
+ flowState.paywalls[flowState.paywalls.length - 1];
3677
+ if (!flow || !activePaywall || !flow.currentFlowStep) {
3678
+ return;
3679
+ }
3680
+ const currentStep = flow.currentFlowStep;
3681
+ if (lastAppearStepIdRef.current === currentStep.id) {
3682
+ return;
3683
+ }
3684
+ flow.executeLifecycle(currentStep, NamiReservedActions.APPEAR);
3685
+ lastAppearStepIdRef.current = currentStep.id;
3686
+ }, [flowState.paywalls, flowState.index]);
3687
+ useEffect(() => {
3688
+ const attempt = remoteBackFallbackAttemptRef.current;
3689
+ if (!attempt) {
3690
+ return;
3691
+ }
3692
+ if (isClosing) {
3693
+ clearRemoteBackFallback();
3694
+ return;
3695
+ }
3696
+ const activeFlow = flowRef.current;
3697
+ const activeStepId = activeFlow?.currentFlowStep?.id;
3698
+ const activePaywallId = paywallData?.id;
3699
+ const didNavigateAway = attempt.flow !== activeFlow
3700
+ || attempt.stepId !== activeStepId
3701
+ || attempt.paywallId !== activePaywallId;
3702
+ if (didNavigateAway) {
3703
+ clearRemoteBackFallback();
3704
+ }
3705
+ }, [clearRemoteBackFallback, flowState.index, flowState.paywalls, isClosing, paywallData?.id]);
3706
+ const hasFlowScreen = flowState.paywalls.length > 0;
3707
+ const launchPlaceholderPaywall = launchPreviewPaywall
3708
+ ?? paywallData
3709
+ ?? flowState.paywalls[flowState.index]
3710
+ ?? flowState.paywalls[0]
3711
+ ?? null;
3712
+ const showLaunchPlaceholder = Boolean(launchPlaceholderPaywall)
3713
+ && (loading || !initialScreenCommitted);
3714
+ const showTransitionPlaceholder = Boolean(pendingTransitionPaywall)
3715
+ && !loading
3716
+ && !isClosing;
3717
+ const handleInitialCommitted = useCallback((_paywall, _pageName, _formFactor) => {
3718
+ setInitialScreenCommitted(true);
3719
+ }, []);
3720
+ if (isClosing) {
3721
+ return jsxRuntimeExports.jsx(SafeAreaView, { style: styles.root });
3722
+ }
3723
+ if (loading || !campaignData || (!isFlowCampaign && !paywallData) || (isFlowCampaign && !hasFlowScreen)) {
3724
+ return jsxRuntimeExports.jsx(LaunchPlaceholder, { paywall: launchPlaceholderPaywall });
3725
+ }
3726
+ return (jsxRuntimeExports.jsxs(SafeAreaView, { style: styles.root, children: [jsxRuntimeExports.jsx(StatusBar, { barStyle: "light-content" }), isFlowCampaign ? (jsxRuntimeExports.jsx(FlowRenderer, { paywalls: flowState.paywalls, currentIndex: flowState.index, animation: flowState.animation ?? undefined, onSettled: handleFlowAnimationSettled, onTransitionVisible: () => setPendingTransitionPaywall(null), onInitialCommitted: handleInitialCommitted, onClose: onClose, campaign: campaignData, context: ctx, flow: flowRef.current })) : (jsxRuntimeExports.jsx(PaywallProvider, { paywall: paywallData, context: ctx, campaign: campaignData, children: jsxRuntimeExports.jsx(PaywallScreen, { paywall: paywallData, onClose: requestClose, onCommitted: handleInitialCommitted, isActive: true }) })), !isClosing && showLaunchPlaceholder && jsxRuntimeExports.jsx(LaunchPlaceholder, { paywall: launchPlaceholderPaywall, overlay: true }), showTransitionPlaceholder && jsxRuntimeExports.jsx(LaunchPlaceholder, { paywall: pendingTransitionPaywall, overlay: true })] }));
3727
+ };
3728
+ const LaunchPlaceholder = ({ paywall, overlay = false }) => {
3729
+ const initialPageName = paywall?.template?.initialState?.currentPage ?? 'page1';
3730
+ const page = paywall?.template?.pages?.find((item) => item?.name === initialPageName) ?? null;
3731
+ const backgroundContainer = page?.backgroundContainer;
3732
+ const backgroundColor = parseColor(backgroundContainer?.fillColor)
3733
+ ?? parseColor(backgroundContainer?.fillColorFallback)
3734
+ ?? '#111118';
3735
+ return (jsxRuntimeExports.jsx(View, { pointerEvents: "none", style: [
3736
+ styles.loading,
3737
+ overlay ? styles.loadingOverlay : null,
3738
+ { backgroundColor },
3739
+ ], children: jsxRuntimeExports.jsx(ActivityIndicator, { size: "large", color: "#FFFFFF" }) }));
3740
+ };
3741
+ const getPaywallBackgroundColor = (paywall) => {
3742
+ const initialPageName = paywall?.template?.initialState?.currentPage ?? 'page1';
3743
+ const page = paywall?.template?.pages?.find((item) => item?.name === initialPageName) ?? null;
3744
+ const backgroundContainer = page?.backgroundContainer;
3745
+ return (parseColor(backgroundContainer?.fillColor)
3746
+ ?? parseColor(backgroundContainer?.fillColorFallback)
3747
+ ?? '#111118');
3748
+ };
3749
+ /** Renders multi-step flow paywalls with transition animations */
3750
+ const FlowRenderer = ({ paywalls, currentIndex, animation, onSettled, onTransitionVisible, onInitialCommitted, onClose, campaign, context, flow }) => {
3751
+ const { width, height } = Dimensions.get('window');
3752
+ const progress = useRef(new Animated.Value(0)).current;
3753
+ const transitionSequenceRef = useRef(0);
3754
+ const lastTransitionSignatureRef = useRef('');
3755
+ const startedTransitionKeyRef = useRef(null);
3756
+ const [completedTransitionKey, setCompletedTransitionKey] = useState(null);
3757
+ const transition = animation?.transition ?? 'slide';
3758
+ const direction = animation?.direction === 'backward' ? -1 : 1;
3759
+ const isVertical = transition === 'verticalSlide';
3760
+ const shouldAnimatePair = paywalls.length === 2
3761
+ && currentIndex === 1
3762
+ && animation != null;
3763
+ const shouldRenderPair = shouldAnimatePair;
3764
+ const sourcePaywall = shouldRenderPair ? paywalls[0] : undefined;
3765
+ const targetPaywall = shouldRenderPair
3766
+ ? paywalls[1]
3767
+ : (paywalls[currentIndex] ?? paywalls[0]);
3768
+ const targetBackgroundColor = useMemo(() => getPaywallBackgroundColor(targetPaywall), [targetPaywall]);
3769
+ const transitionSignature = shouldAnimatePair
3770
+ ? `${sourcePaywall?.id ?? 'source'}->${targetPaywall?.id ?? 'target'}:${transition}:${direction}`
3771
+ : '';
3772
+ if (shouldAnimatePair && lastTransitionSignatureRef.current !== transitionSignature) {
3773
+ lastTransitionSignatureRef.current = transitionSignature;
3774
+ transitionSequenceRef.current += 1;
3775
+ }
3776
+ else if (!shouldAnimatePair) {
3777
+ lastTransitionSignatureRef.current = '';
3778
+ }
3779
+ const activeTransitionKey = shouldAnimatePair
3780
+ ? `${transitionSignature}:${transitionSequenceRef.current}`
3781
+ : '';
3782
+ const [committedTarget, setCommittedTarget] = useState({
3783
+ transitionKey: null,
3784
+ paywallId: null,
3785
+ });
3786
+ const interactionReady = !shouldAnimatePair
3787
+ || (committedTarget.transitionKey === activeTransitionKey
3788
+ && committedTarget.paywallId === (targetPaywall?.id ?? null));
3789
+ const transitionReady = shouldAnimatePair && interactionReady;
3790
+ const handleTargetCommitted = useCallback((paywall, _pageName, formFactor) => {
3791
+ if (paywall.id !== targetPaywall?.id) {
3792
+ return;
3793
+ }
3794
+ setCommittedTarget({
3795
+ transitionKey: activeTransitionKey || null,
3796
+ paywallId: paywall.id ?? null,
3797
+ });
3798
+ }, [activeTransitionKey, targetPaywall?.id]);
3799
+ const handleVisibleCommitted = useCallback((paywall, pageName, formFactor) => {
3800
+ if (currentIndex === 0) {
3801
+ onInitialCommitted?.(paywall, pageName, formFactor);
3802
+ }
3803
+ handleTargetCommitted(paywall, pageName, formFactor);
3804
+ }, [currentIndex, handleTargetCommitted, onInitialCommitted]);
3805
+ useLayoutEffect(() => {
3806
+ const activePaywall = paywalls[currentIndex] ?? paywalls[paywalls.length - 1];
3807
+ if (!shouldAnimatePair) {
3808
+ startedTransitionKeyRef.current = null;
3809
+ setCompletedTransitionKey(null);
3810
+ progress.stopAnimation();
3811
+ progress.setValue(0);
3812
+ return;
3813
+ }
3814
+ if (transition === 'fade' || transition === 'none') {
3815
+ if (startedTransitionKeyRef.current === activeTransitionKey) {
3816
+ return;
3817
+ }
3818
+ startedTransitionKeyRef.current = activeTransitionKey;
3819
+ setCompletedTransitionKey(null);
3820
+ progress.stopAnimation();
3821
+ progress.setValue(0);
3822
+ if (activePaywall) {
3823
+ requestAnimationFrame(() => {
3824
+ onSettled?.(activePaywall);
3825
+ });
3826
+ }
3827
+ return;
3828
+ }
3829
+ if (!transitionReady) {
3830
+ if (startedTransitionKeyRef.current !== activeTransitionKey) {
3831
+ progress.stopAnimation();
3832
+ progress.setValue(0);
3833
+ }
3834
+ return;
3835
+ }
3836
+ if (startedTransitionKeyRef.current === activeTransitionKey) {
3837
+ return;
3838
+ }
3839
+ startedTransitionKeyRef.current = activeTransitionKey;
3840
+ setCompletedTransitionKey(null);
3841
+ progress.stopAnimation();
3842
+ progress.setValue(0);
3843
+ Animated.timing(progress, {
3844
+ toValue: 1,
3845
+ duration: 250,
3846
+ useNativeDriver: true,
3847
+ }).start(({ finished }) => {
3848
+ if (finished) {
3849
+ setCompletedTransitionKey(activeTransitionKey);
3850
+ }
3851
+ });
3852
+ }, [
3853
+ activeTransitionKey,
3854
+ animation?.direction,
3855
+ currentIndex,
3856
+ onSettled,
3857
+ paywalls,
3858
+ progress,
3859
+ sourcePaywall?.id,
3860
+ transitionReady,
3861
+ transition,
3862
+ ]);
3863
+ useEffect(() => {
3864
+ if (!shouldAnimatePair
3865
+ || !targetPaywall
3866
+ || !interactionReady
3867
+ || completedTransitionKey !== activeTransitionKey) {
3868
+ return;
3869
+ }
3870
+ onSettled?.(targetPaywall);
3871
+ }, [
3872
+ activeTransitionKey,
3873
+ completedTransitionKey,
3874
+ interactionReady,
3875
+ onSettled,
3876
+ shouldAnimatePair,
3877
+ targetPaywall,
3878
+ ]);
3879
+ useEffect(() => {
3880
+ if (!shouldAnimatePair || !interactionReady) {
3881
+ return;
3882
+ }
3883
+ onTransitionVisible?.();
3884
+ }, [interactionReady, onTransitionVisible, shouldAnimatePair]);
3885
+ if (transition === 'fade') {
3886
+ const current = paywalls[currentIndex] ?? paywalls[0];
3887
+ if (!current)
3888
+ return null;
3889
+ return (jsxRuntimeExports.jsx(View, { style: styles.flowContainer, children: jsxRuntimeExports.jsx(View, { style: { width, height }, children: jsxRuntimeExports.jsx(FocusProvider, { enabled: true, children: jsxRuntimeExports.jsx(PaywallProvider, { paywall: current, context: context, campaign: campaign, flow: flow, children: jsxRuntimeExports.jsx(PaywallScreen, { paywall: current, onClose: onClose, onCommitted: handleVisibleCommitted, isActive: true }) }) }) }) }));
3890
+ }
3891
+ const renderedPaywalls = shouldRenderPair
3892
+ ? [
3893
+ { paywall: sourcePaywall, role: 'source', key: 0 },
3894
+ { paywall: targetPaywall, role: 'target', key: 1 },
3895
+ ]
3896
+ : [{ paywall: paywalls[currentIndex] ?? paywalls[0], role: 'target', key: currentIndex }];
3897
+ return (jsxRuntimeExports.jsxs(View, { style: styles.flowContainer, children: [renderedPaywalls.map(({ paywall: pw, role, key }) => {
3898
+ if (!pw) {
3899
+ return null;
3900
+ }
3901
+ const animatedStyle = role === 'target' && shouldAnimatePair
3902
+ ? { opacity: 0 }
3903
+ : null;
3904
+ return (jsxRuntimeExports.jsx(Animated.View, { pointerEvents: role === 'target' && !shouldAnimatePair && interactionReady ? 'auto' : 'none', style: [
3905
+ styles.flowScreen,
3906
+ {
3907
+ width,
3908
+ height,
3909
+ zIndex: role === 'target' ? 2 : 1,
3910
+ elevation: role === 'target' ? 2 : 1,
3911
+ },
3912
+ animatedStyle ?? null,
3913
+ ], children: jsxRuntimeExports.jsx(FocusProvider, { enabled: role === 'target' && !shouldAnimatePair && interactionReady, children: jsxRuntimeExports.jsx(PaywallProvider, { paywall: pw, context: context, campaign: campaign, flow: flow, children: jsxRuntimeExports.jsx(PaywallScreen, { paywall: pw, onClose: onClose, onCommitted: role === 'target' ? handleVisibleCommitted : undefined, isActive: role === 'target' && !shouldAnimatePair && interactionReady }) }) }) }, pw.id ?? key));
3914
+ }), shouldAnimatePair && !interactionReady && (jsxRuntimeExports.jsx(LaunchPlaceholder, { paywall: targetPaywall ?? null, overlay: true })), transitionReady && targetPaywall && (jsxRuntimeExports.jsx(Animated.View, { pointerEvents: "none", style: [
3915
+ styles.flowScreen,
3916
+ {
3917
+ width,
3918
+ height,
3919
+ zIndex: 3,
3920
+ elevation: 3,
3921
+ backgroundColor: targetBackgroundColor,
3922
+ },
3923
+ isVertical
3924
+ ? {
3925
+ transform: [{
3926
+ translateY: progress.interpolate({
3927
+ inputRange: [0, 1],
3928
+ outputRange: [height * direction, 0],
3929
+ }),
3930
+ }],
3931
+ }
3932
+ : {
3933
+ transform: [{
3934
+ translateX: progress.interpolate({
3935
+ inputRange: [0, 1],
3936
+ outputRange: [width * direction, 0],
3937
+ }),
3938
+ }],
3939
+ },
3940
+ ] }))] }));
3941
+ };
3942
+ const styles = StyleSheet.create({
3943
+ root: { flex: 1, backgroundColor: '#000' },
3944
+ loading: {
3945
+ flex: 1,
3946
+ backgroundColor: '#111118',
3947
+ alignItems: 'center',
3948
+ justifyContent: 'center',
3949
+ },
3950
+ loadingOverlay: {
3951
+ ...StyleSheet.absoluteFillObject,
3952
+ zIndex: 50,
3953
+ },
3954
+ flowContainer: { flex: 1, overflow: 'hidden' },
3955
+ flowScreen: { position: 'absolute', top: 0, left: 0 },
3956
+ });
3957
+
3958
+ const runtimeGlobals = globalThis;
3959
+ const sdkEnvKey = 'NAMI_SDK' + '_ENV';
3960
+ if (typeof runtimeGlobals[sdkEnvKey] !== 'string' || runtimeGlobals[sdkEnvKey] === '') {
3961
+ const devFlag = typeof __DEV__ === 'boolean' ? __DEV__ : false;
3962
+ runtimeGlobals[sdkEnvKey] = devFlag ? 'development' : 'production';
3963
+ }
3964
+
3965
+ export { ExpoDeviceAdapter, ExpoPurchaseAdapter, ExpoStorageAdapter, ExpoUIAdapter, Nami, NamiView, PaywallProvider, PaywallScreen, TemplateRenderer, usePaywallContext };
3966
+ //# sourceMappingURL=index.mjs.map