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