@tiun/react-native-sdk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,6 +48,45 @@ snippet without reloading:
48
48
  >
49
49
  ```
50
50
 
51
+ ### Events
52
+
53
+ `useTiunEvent('userChange', …)` receives the same payload as the web SDK:
54
+ `{ event, isAuthenticated, user }`. `event` is `'init'`, `'login'`, `'logout'`,
55
+ `'checkout'` (access gained or lost, for any product type — including a
56
+ repeatable product bought with a new reference) or `'update'`. Re-check access
57
+ there:
58
+
59
+ ```tsx
60
+ useTiunEvent('userChange', async ({ isAuthenticated, user }) => {
61
+ setHasPro(isAuthenticated && !!user?.productAccess.includes('prod_pro'));
62
+ const { hasAccess } = await checkProductAccess('prod_ticket', { referenceId: 'order-1042' });
63
+ setHasTicket(hasAccess);
64
+ });
65
+ ```
66
+
67
+ ### Products
68
+
69
+ `useTiun()` exposes the same product methods as the web SDK. Each returns a
70
+ Promise that rejects with `{ code, message }` when the request fails (e.g.
71
+ `http_404` for an unknown product, or `timeout`). Calls made before the snippet
72
+ is ready wait for it; calls still waiting when the provider unmounts reject with
73
+ `destroyed`.
74
+
75
+ ```tsx
76
+ const { listProducts, getProduct, listProductAccess, checkProductAccess } = useTiun();
77
+
78
+ const products = await listProducts(); // Product[]
79
+ const detail = await getProduct('prod_monthly'); // name, pricingLine, …
80
+ const access = await listProductAccess(); // [] when logged out
81
+ const { hasAccess } = await checkProductAccess('prod_monthly');
82
+
83
+ // Repeatable product: check a specific purchase
84
+ await checkProductAccess('prod_ticket', { referenceId: 'order-1042' });
85
+ ```
86
+
87
+ `checkProductAccess` resolves to `{ hasAccess: false, access: null }` when the
88
+ user has no access or isn't logged in.
89
+
51
90
  ## Peer dependencies
52
91
 
53
92
  `react`, `react-native`, `react-native-webview`, `react-native-secure-sign`,
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export declare type Appearance = 'light' | 'dark' | 'auto';
6
6
 
7
7
  export declare interface CheckoutOptions {
8
8
  /**
9
- * Specific product ID to checkout (optional, for future use)
9
+ * The product to check out, from your tiun dashboard.
10
10
  */
11
11
  productId?: string;
12
12
  /**
@@ -35,6 +35,49 @@ declare interface PaywallShowEvent {
35
35
  isConnected: boolean;
36
36
  }
37
37
 
38
+ export declare interface Product {
39
+ productId: string;
40
+ name: string;
41
+ type: ProductType;
42
+ }
43
+
44
+ export declare interface ProductAccess {
45
+ productId: string;
46
+ /** Purchase reference for repeatable products; null for ordinary access. */
47
+ referenceId?: string | null;
48
+ type: ProductType;
49
+ /** ISO 8601 date-time. */
50
+ activatedAt: string;
51
+ /**
52
+ * When the access ends (ISO 8601 date-time). null while a subscription is
53
+ * active and renewing; set to the end of the paid period once it's cancelled.
54
+ */
55
+ expiresAt?: string | null;
56
+ }
57
+
58
+ export declare interface ProductAccessCheck {
59
+ hasAccess: boolean;
60
+ /** Access details when `hasAccess` is true; null otherwise. */
61
+ access?: ProductAccess | null;
62
+ }
63
+
64
+ export declare interface ProductAccessOptions {
65
+ /**
66
+ * Purchase reference for repeatable products (the `referenceId` passed to
67
+ * `checkout()`). Omit for ordinary product access.
68
+ */
69
+ referenceId?: string;
70
+ }
71
+
72
+ export declare interface ProductDetail extends Product {
73
+ /** Localized price summary, e.g. "€9.90 / month". */
74
+ pricingLine: string;
75
+ /** Optional localized explanation shown under the price. */
76
+ explanationLine?: string | null;
77
+ }
78
+
79
+ export declare type ProductType = 'Subscription' | 'OneTime';
80
+
38
81
  export declare type TiunConfig = {
39
82
  /** tiun snippet id (goes in the asset route). */
40
83
  snippetId: string;
@@ -72,17 +115,29 @@ export declare type TiunContextValue = {
72
115
  logout: () => void;
73
116
  checkout: (options?: CheckoutOptions) => void;
74
117
  getUserVerificationToken: () => Promise<string | null>;
118
+ /** List the products available on this snippet. */
119
+ listProducts: () => Promise<Product[]>;
120
+ /** Get a product's details and localized pricing; rejects if it doesn't exist. */
121
+ getProduct: (productId: string) => Promise<ProductDetail>;
122
+ /** List the user's active product access ([] when logged out). */
123
+ listProductAccess: () => Promise<ProductAccess[]>;
124
+ /** Check access to a product ({ hasAccess: false, access: null } when logged out). */
125
+ checkProductAccess: (productId: string, options?: ProductAccessOptions) => Promise<ProductAccessCheck>;
75
126
  };
76
127
 
128
+ export declare interface TiunError {
129
+ code: string;
130
+ message: string;
131
+ details?: unknown;
132
+ }
133
+
77
134
  /** Events surfaced via `useTiunEvent` (names mirror the web SDK). */
78
135
  export declare type TiunEventName = 'ready' | 'userChange' | 'login' | 'logout' | 'paywallShow' | 'paywallHide' | 'error';
79
136
 
80
137
  export declare type TiunEventPayload = {
81
138
  ready: void;
82
- userChange: {
83
- isAuthenticated: boolean;
84
- user: TiunUser | null;
85
- };
139
+ /** Same shape as the web SDK: `event` says what changed ('checkout' = access). */
140
+ userChange: UserChangeEvent;
86
141
  login: {
87
142
  user: TiunUser | null;
88
143
  };
@@ -104,11 +159,31 @@ export declare function TiunProvider({ config, children }: {
104
159
  /** The authenticated user (alias of the web SDK's `UserInfo`). */
105
160
  export declare type TiunUser = UserInfo;
106
161
 
162
+ export declare interface UserChangeEvent {
163
+ /**
164
+ * What changed:
165
+ * - 'init': first state after the snippet loads
166
+ * - 'login' / 'logout': the user signed in or out
167
+ * - 'checkout': the user's access changed — gained or lost, for any product
168
+ * type, including a repeatable product bought with a new reference
169
+ * (which doesn't change `productAccess`). Not only after a checkout.
170
+ * - 'update': profile details changed (email, newsletter opt-in)
171
+ */
172
+ event: 'init' | 'login' | 'checkout' | 'logout' | 'update';
173
+ isAuthenticated: boolean;
174
+ user: UserInfo | null;
175
+ }
176
+
107
177
  declare interface UserInfo {
108
178
  userId: string;
109
179
  email: string;
110
180
  /** Whether the user has opted in to the newsletter. */
111
181
  hasNewsletterOptIn: boolean;
182
+ /**
183
+ * IDs of the products the user has access to. Product IDs only, so it can't
184
+ * tell which references of a repeatable product were bought — use
185
+ * `checkProductAccess(productId, { referenceId })` for those.
186
+ */
112
187
  productAccess: string[];
113
188
  }
114
189
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var we=Object.defineProperty;var ve=(t,r,a)=>r in t?we(t,r,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[r]=a;var fe=(t,r,a)=>(ve(t,typeof r!="symbol"?r+"":r,a),a);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react"),b=require("react-native"),Se=require("react-native-webview"),M=require("react-native-inappbrowser-nitro"),te=require("react-native-secure-sign"),_e=require("react-native-keychain");function me(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const u=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(r,a,u.get?u:{enumerable:!0,get:()=>t[a]})}}return r.default=t,Object.freeze(r)}const ne=me(_e);var se={exports:{}},X={};/**
1
+ "use strict";var Se=Object.defineProperty;var ve=(r,n,i)=>n in r?Se(r,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[n]=i;var fe=(r,n,i)=>(ve(r,typeof n!="symbol"?n+"":n,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react"),w=require("react-native"),we=require("react-native-webview"),Z=require("react-native-inappbrowser-nitro"),oe=require("react-native-secure-sign"),Re=require("react-native-keychain");function me(r){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const i in r)if(i!=="default"){const l=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(n,i,l.get?l:{enumerable:!0,get:()=>r[i]})}}return n.default=r,Object.freeze(n)}const ie=me(Re);var se={exports:{}},ee={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var pe;function Re(){if(pe)return X;pe=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function a(u,o,d){var f=null;if(d!==void 0&&(f=""+d),o.key!==void 0&&(f=""+o.key),"key"in o){d={};for(var E in o)E!=="key"&&(d[E]=o[E])}else d=o;return o=d.ref,{$$typeof:t,type:u,key:f,ref:o!==void 0?o:null,props:d}}return X.Fragment=r,X.jsx=a,X.jsxs=a,X}var Q={};/**
9
+ */var pe;function ke(){if(pe)return ee;pe=1;var r=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function i(l,o,h){var y=null;if(h!==void 0&&(y=""+h),o.key!==void 0&&(y=""+o.key),"key"in o){h={};for(var p in o)p!=="key"&&(h[p]=o[p])}else h=o;return o=h.ref,{$$typeof:r,type:l,key:y,ref:o!==void 0?o:null,props:h}}return ee.Fragment=n,ee.jsx=i,ee.jsxs=i,ee}var te={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,9 +14,9 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var he;function ge(){return he||(he=1,process.env.NODE_ENV!=="production"&&function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===R?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case w:return"Fragment";case q:return"Profiler";case N:return"StrictMode";case G:return"Suspense";case c:return"SuspenseList";case I:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case z:return"Portal";case B:return(e.displayName||"Context")+".Provider";case U:return(e._context.displayName||"Context")+".Consumer";case D:var s=e.render;return e=e.displayName,e||(e=s.displayName||s.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case m:return s=e.displayName||null,s!==null?s:t(e.type)||"Memo";case v:s=e._payload,e=e._init;try{return t(e(s))}catch{}}return null}function r(e){return""+e}function a(e){try{r(e);var s=!1}catch{s=!0}if(s){s=console;var h=s.error,S=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return h.call(s,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",S),r(e)}}function u(e){if(e===w)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===v)return"<...>";try{var s=t(e);return s?"<"+s+">":"<...>"}catch{return"<...>"}}function o(){var e=i.A;return e===null?null:e.getOwner()}function d(){return Error("react-stack-top-frame")}function f(e){if(n.call(e,"key")){var s=Object.getOwnPropertyDescriptor(e,"key").get;if(s&&s.isReactWarning)return!1}return e.key!==void 0}function E(e,s){function h(){p||(p=!0,console.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://react.dev/link/special-props)",s))}h.isReactWarning=!0,Object.defineProperty(e,"key",{get:h,configurable:!0})}function V(){var e=t(this.type);return C[e]||(C[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function A(e,s,h,S,W,x,oe,ie){return h=x.ref,e={$$typeof:j,type:e,key:s,props:x,_owner:W},(h!==void 0?h:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:V}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:oe}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:ie}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function L(e,s,h,S,W,x,oe,ie){var _=s.children;if(_!==void 0)if(S)if(T(_)){for(S=0;S<_.length;S++)P(_[S]);Object.freeze&&Object.freeze(_)}else console.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.");else P(_);if(n.call(s,"key")){_=t(e);var H=Object.keys(s).filter(function(ye){return ye!=="key"});S=0<H.length?"{key: someKey, "+H.join(": ..., ")+": ...}":"{key: someKey}",$[_+S]||(H=0<H.length?"{"+H.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
17
+ */var Te;function ge(){return Te||(Te=1,process.env.NODE_ENV!=="production"&&function(){function r(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===K?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case q:return"Fragment";case V:return"Profiler";case b:return"StrictMode";case F:return"Suspense";case C:return"SuspenseList";case B:return"Activity"}if(typeof t=="object")switch(typeof t.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case D:return"Portal";case Y:return(t.displayName||"Context")+".Provider";case A:return(t._context.displayName||"Context")+".Consumer";case G:var c=t.render;return t=t.displayName,t||(t=c.displayName||c.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case H:return c=t.displayName||null,c!==null?c:r(t.type)||"Memo";case W:c=t._payload,t=t._init;try{return r(t(c))}catch{}}return null}function n(t){return""+t}function i(t){try{n(t);var c=!1}catch{c=!0}if(c){c=console;var T=c.error,_=typeof Symbol=="function"&&Symbol.toStringTag&&t[Symbol.toStringTag]||t.constructor.name||"Object";return T.call(c,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",_),n(t)}}function l(t){if(t===q)return"<>";if(typeof t=="object"&&t!==null&&t.$$typeof===W)return"<...>";try{var c=r(t);return c?"<"+c+">":"<...>"}catch{return"<...>"}}function o(){var t=a.A;return t===null?null:t.getOwner()}function h(){return Error("react-stack-top-frame")}function y(t){if(e.call(t,"key")){var c=Object.getOwnPropertyDescriptor(t,"key").get;if(c&&c.isReactWarning)return!1}return t.key!==void 0}function p(t,c){function T(){d||(d=!0,console.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://react.dev/link/special-props)",c))}T.isReactWarning=!0,Object.defineProperty(t,"key",{get:T,configurable:!0})}function j(){var t=r(this.type);return E[t]||(E[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),t=this.props.ref,t!==void 0?t:null}function $(t,c,T,_,N,P,M,J){return T=P.ref,t={$$typeof:L,type:t,key:c,props:P,_owner:N},(T!==void 0?T:null)!==null?Object.defineProperty(t,"ref",{enumerable:!1,get:j}):Object.defineProperty(t,"ref",{enumerable:!1,value:null}),t._store={},Object.defineProperty(t._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(t,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(t,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(t,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:J}),Object.freeze&&(Object.freeze(t.props),Object.freeze(t)),t}function x(t,c,T,_,N,P,M,J){var S=c.children;if(S!==void 0)if(_)if(u(S)){for(_=0;_<S.length;_++)O(S[_]);Object.freeze&&Object.freeze(S)}else console.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.");else O(S);if(e.call(c,"key")){S=r(t);var R=Object.keys(c).filter(function(_e){return _e!=="key"});_=0<R.length?"{key: someKey, "+R.join(": ..., ")+": ...}":"{key: someKey}",Q[S+_]||(R=0<R.length?"{"+R.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
18
  let props = %s;
19
19
  <%s {...props} />
20
20
  React keys must be passed directly to JSX without using spread:
21
21
  let props = %s;
22
- <%s key={someKey} {...props} />`,S,_,H,_),$[_+S]=!0)}if(_=null,h!==void 0&&(a(h),_=""+h),f(s)&&(a(s.key),_=""+s.key),"key"in s){h={};for(var ae in s)ae!=="key"&&(h[ae]=s[ae])}else h=s;return _&&E(h,typeof e=="function"?e.displayName||e.name||"Unknown":e),A(e,_,x,W,o(),h,oe,ie)}function P(e){typeof e=="object"&&e!==null&&e.$$typeof===j&&e._store&&(e._store.validated=1)}var k=l,j=Symbol.for("react.transitional.element"),z=Symbol.for("react.portal"),w=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),q=Symbol.for("react.profiler"),U=Symbol.for("react.consumer"),B=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),G=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),R=Symbol.for("react.client.reference"),i=k.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,n=Object.prototype.hasOwnProperty,T=Array.isArray,y=console.createTask?console.createTask:function(){return null};k={"react-stack-bottom-frame":function(e){return e()}};var p,C={},O=k["react-stack-bottom-frame"].bind(k,d)(),Y=y(u(d)),$={};Q.Fragment=w,Q.jsx=function(e,s,h,S,W){var x=1e4>i.recentlyCreatedOwnerStacks++;return L(e,s,h,!1,S,W,x?Error("react-stack-top-frame"):O,x?y(u(e)):Y)},Q.jsxs=function(e,s,h,S,W){var x=1e4>i.recentlyCreatedOwnerStacks++;return L(e,s,h,!0,S,W,x?Error("react-stack-top-frame"):O,x?y(u(e)):Y)}}()),Q}process.env.NODE_ENV==="production"?se.exports=Re():se.exports=ge();var g=se.exports;const ke={errorPillText:"Technical Error",errorNotificationTitle:"Technical error",errorNotificationSubtitle:"Please reload the page or contact our support.",errorTitle:"Technical error",errorTextBeforeEmail:"Try reloading the page. If the error persists, please contact ",errorTextAfterEmail:" and we’ll help you right away.",connectionErrorTitle:"No connection",connectionErrorText:"We couldn’t reach tiun. Check your internet connection and try again.",connectionErrorCta:"Try again"},Ne={errorPillText:"Erreur Technique",errorNotificationTitle:"Erreur technique",errorNotificationSubtitle:"Veuillez recharger la page ou contacter notre support.",errorTitle:"Erreur technique",errorTextBeforeEmail:"Veuillez recharger la page. Si l’erreur persiste, contactez ",errorTextAfterEmail:" et nous vous aiderons immédiatement.",connectionErrorTitle:"Pas de connexion",connectionErrorText:"Impossible de joindre tiun. Vérifiez votre connexion Internet et réessayez.",connectionErrorCta:"Réessayer"},Ce={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte lade die Seite neu, oder kontaktiere unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte lade die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktiere ",errorTextAfterEmail:" und wir helfen Dir sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfe deine Internetverbindung und versuche es erneut.",connectionErrorCta:"Erneut versuchen"},Oe={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte laden Sie die Seite neu, oder kontaktieren Sie unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte laden Sie die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktieren Sie ",errorTextAfterEmail:" und wir helfen Ihnen sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",connectionErrorCta:"Erneut versuchen"};function Pe(t,r="informal"){switch((t??"en").trim().toLowerCase()){case"de":return r==="formal"?Oe:Ce;case"fr":return Ne;default:return ke}}const K={start:"TIUN_START",checkout:"TIUN_CHECKOUT",updateContent:"TIUN_UPDATE_CONTENT",login:"TIUN_LOGIN",logout:"TIUN_LOGOUT",getVerificationToken:"TIUN_GET_VERIFICATION_TOKEN",setAppearance:"TIUN_SET_APPEARANCE",overlayChange:"TIUN_OVERLAY_CHANGE",popPubKeyRequest:"TIUN_POP_PUBKEY_REQUEST",popSignRequest:"TIUN_POP_SIGN_REQUEST",tokenGet:"TIUN_TOKEN_GET",tokenPersist:"TIUN_TOKEN_PERSIST",nativeReset:"TIUN_NATIVE_RESET",popPubKey:"TIUN_POP_PUBKEY",restoreToken:"TIUN_RESTORE_TOKEN",popSignResult:"TIUN_POP_SIGN_RESULT",resolveCheckout:"TIUN_RESOLVE_CHECKOUT"},Ie="__TIUN_NATIVE_CRYPTO__",xe="https://api.tiun.live";function ue(t){return(t.host??xe).replace(/\/$/,"")}function re(t){return`app.tiun.pop.${t.snippetId||"default"}`}function Z(t){return`app.tiun.token.${t.snippetId||"default"}`}function Ae(t){return`${`${ue(t)}/live_api/v2/snippets/${encodeURIComponent(t.snippetId)}/webview_return`}?to=${encodeURIComponent(t.returnUrl)}`}function je(t){const r={language:t.language??"en"},a=Object.entries(r).map(([o,d])=>`${encodeURIComponent(o)}=${encodeURIComponent(d)}`).join("&"),u=`${ue(t)}/live_api/v2/snippets/${encodeURIComponent(t.snippetId)}/webview_host`;return a?`${u}?${a}`:u}function Te(t){const r=t.indexOf("?");if(!(r<0))for(const a of t.slice(r+1).split("&")){const u=a.indexOf("=");if((u<0?a:a.slice(0,u))==="status"){const d=u<0?"":a.slice(u+1);return d?decodeURIComponent(d):void 0}}}function Ue(t,r){const a=t.returnUrl.split("?")[0];return r.startsWith(a)}const le="1005";function de(t){return t==null?void 0:t.code}async function $e(t){try{return await te.getPublicKey(t)}catch(r){if(de(r)===le)return te.generate(t,{requireUserAuthentication:!1});throw r}}async function Fe(t){try{return await te.getPublicKey(t)}catch(r){if(de(r)===le)return null;throw r}}function Le(t,r){return te.sign(t,r)}async function We(t){try{await te.removeKey(t)}catch(r){if(de(r)!==le)throw r}}const Ve="tiun_auth_token";async function qe(t){const r=await ne.getGenericPassword({service:t});return r?r.password:null}async function Ye(t,r){await ne.setGenericPassword(Ve,r,{service:t,accessible:ne.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY})}async function ce(t){await ne.resetGenericPassword({service:t})}function Be(t){const r=Pe(t);return{title:r.connectionErrorTitle,text:r.connectionErrorText,cta:r.connectionErrorCta}}function De({language:t,dark:r,onRetry:a}){const u=Be(t),o=r?Ge:null;return g.jsxs(b.View,{style:[F.container,o==null?void 0:o.container],children:[g.jsxs(b.View,{style:F.content,children:[g.jsx(b.Text,{style:[F.title,o==null?void 0:o.title],children:u.title}),g.jsx(b.View,{style:[F.iconBadge,o==null?void 0:o.iconBadge],children:g.jsx(b.Text,{style:[F.iconGlyph,o==null?void 0:o.iconGlyph],children:"!"})}),g.jsx(b.Text,{style:[F.text,o==null?void 0:o.text],children:u.text})]}),g.jsx(b.Pressable,{accessibilityRole:"button",onPress:a,style:({pressed:d})=>[F.button,o==null?void 0:o.button,d&&F.buttonPressed],children:g.jsx(b.Text,{style:[F.buttonText,o==null?void 0:o.buttonText],children:u.cta})})]})}const F=b.StyleSheet.create({container:{...b.StyleSheet.absoluteFillObject,backgroundColor:"#fff",padding:24,justifyContent:"space-between"},content:{flex:1,alignItems:"center",justifyContent:"center",gap:24},title:{fontSize:20,fontWeight:"600",color:"#000",textAlign:"center"},iconBadge:{width:40,height:40,borderRadius:20,backgroundColor:"#FCE7F3",alignItems:"center",justifyContent:"center"},iconGlyph:{color:"#DB2777",fontSize:22,fontWeight:"700",lineHeight:26},text:{fontSize:16,fontWeight:"500",color:"#4B5563",textAlign:"center"},button:{backgroundColor:"#000",borderRadius:999,minHeight:56,alignItems:"center",justifyContent:"center",alignSelf:"stretch"},buttonPressed:{opacity:.9},buttonText:{color:"#fff",fontSize:16,fontWeight:"500"}}),Ge=b.StyleSheet.create({container:{backgroundColor:"#0a0a0a"},title:{color:"#fafafa"},iconBadge:{backgroundColor:"#500724"},iconGlyph:{color:"#F472B6"},text:{color:"#A1A1AA"},button:{backgroundColor:"#fafafa"},buttonText:{color:"#000"}}),He=Se.WebView;function J(t){return`try{window.tiunHost&&${t};}catch(e){}; true;`}const Ke=l.forwardRef(function({config:r,onEvent:a},u){const o=!!r.debug,d=b.useColorScheme(),f=r.appearance==="dark"||r.appearance==="auto"&&d==="dark"?"dark":"light",E=l.useRef(null),[V,A]=l.useState(!1),[L,P]=l.useState(!1),k=l.useRef(!1),j=l.useRef(!1),z=()=>{var i;P(!1),(i=E.current)==null||i.reload()};l.useEffect(()=>{if(!L)return;const i=b.AppState.addEventListener("change",n=>{var T;n==="active"&&(P(!1),(T=E.current)==null||T.reload())});return()=>i.remove()},[L]);const w=`window.${Ie} = true;window.__TIUN_CONFIG__ = Object.assign({}, window.__TIUN_CONFIG__, { returnUrl: ${JSON.stringify(Ae(r))}, appearance: ${JSON.stringify(f)} });true;`,N=(i,...n)=>{var T;return(T=E.current)==null?void 0:T.injectJavaScript(J(`window.tiunHost.${i}(${n.map(y=>JSON.stringify(y)??"null").join(",")})`))},q=l.useRef(f);l.useEffect(()=>{f!==q.current&&(q.current=f,N("setAppearance",f))},[f]);const U=i=>{var n;j.current||(j.current=!0,M.close().catch(()=>{}),M.closeAuth().catch(()=>{}),A(!0),(n=E.current)==null||n.injectJavaScript(J(`window.tiunHost.resolveCheckout(${i?JSON.stringify(i):""})`)))},B=i=>{var n,T,y;switch(i.type){case K.popPubKeyRequest:return $e(re(r)).then(p=>N("popPubKey",p)).catch(p=>{o&&console.warn("[tiun] ensurePopKey failed:",p),N("popPubKey",null)}),!0;case K.tokenGet:return(async()=>{try{const p=await qe(Z(r));if(p&&!await Fe(re(r))){await ce(Z(r)),N("restoreToken",null);return}N("restoreToken",p)}catch{N("restoreToken",null)}})(),!0;case K.popSignRequest:{const p=(n=i.payload)==null?void 0:n.requestId,C=(T=i.payload)==null?void 0:T.information;return Le(re(r),C).then(O=>N("popSignResult",p,O,null)).catch(O=>{const Y=(O==null?void 0:O.code)??"sign_failed";o&&console.warn("[tiun] popSign failed:",O),N("popSignResult",p,null,String(Y))}),!0}case K.tokenPersist:{const p=((y=i.payload)==null?void 0:y.token)??null;return(p?Ye(Z(r),p):ce(Z(r))).catch(C=>o&&console.warn("[tiun] token persist failed:",C)),!0}case K.nativeReset:return Promise.allSettled([We(re(r)),ce(Z(r))]),!0;default:return!1}};l.useImperativeHandle(u,()=>({login:()=>{var i;A(!0),(i=E.current)==null||i.injectJavaScript(J("window.tiunHost.login()"))},checkout:(i,n)=>{var y;A(!0),k.current=!0,j.current=!1;const T=n?[i||null,n]:i?[i]:[];(y=E.current)==null||y.injectJavaScript(J(`window.tiunHost.checkout(${T.map(p=>JSON.stringify(p)).join(",")})`))},logout:()=>{var i;return(i=E.current)==null?void 0:i.injectJavaScript(J("window.tiunHost.logout()"))},getVerificationToken:i=>{var n;return(n=E.current)==null?void 0:n.injectJavaScript(J(`window.tiunHost.getVerificationToken(${i?JSON.stringify(i):""})`))},resolveCheckout:U,reload:()=>{var i;return(i=E.current)==null?void 0:i.reload()}}),[]);const D=i=>{var T,y,p;let n=null;try{n=JSON.parse(i.nativeEvent.data)}catch{o&&console.warn("[tiun] non-JSON bridge message:",i.nativeEvent.data);return}if(!(!n||typeof n.type!="string")){if(n.type==="console"){o&&console.log("[tiun webview]",(T=n.payload)==null?void 0:T.level,(y=n.payload)==null?void 0:y.message);return}if((n.type==="cryptoCheck"||n.type==="hostBridgeReady")&&P(!1),o&&console.log("[tiun] <-",n.type,n.payload),!B(n)){if(n.type===K.overlayChange){const C=!!((p=n.payload)!=null&&p.overlay);A(C),C||(k.current=!1)}a(n)}}},G=i=>{if(k.current=!1,b.Platform.OS==="ios"){M.openAuth(i,r.returnUrl).then(n=>{n.type==="success"&&n.url?U(Te(n.url)):n.type==="cancel"&&U("cancelled")}).catch(n=>o&&console.warn("[tiun] openAuth error:",n));return}M.open(i,{showTitle:!1,enableUrlBarHiding:!1,enableDefaultShare:!1,forceCloseOnRedirection:!1}).then(n=>{n.type==="cancel"&&U("cancelled")}).catch(n=>o&&console.warn("[tiun] in-app browser open error:",n))},c=i=>{M.open(i,{modalPresentationStyle:"fullScreen",modalEnabled:!0,animated:!0,enableBarCollapsing:!0}).catch(n=>o&&console.warn("[tiun] in-app browser open failed:",n))},m=i=>{var T;const n=(T=i.nativeEvent)==null?void 0:T.targetUrl;n&&(k.current?G(n):c(n))},v=i=>{const n=i.url;return n.startsWith(ue(r))||n.startsWith("about:")||n.startsWith("data:")||n==="about:blank"?!0:n.startsWith("http://")||n.startsWith("https://")?(k.current&&i.isTopFrame!==!1?G(n):c(n),!1):!0},{width:I,height:R}=b.useWindowDimensions();return g.jsxs(b.View,{pointerEvents:V?"auto":"none",style:[ee.container,{width:I,height:R},V?ee.visible:ee.hidden],children:[g.jsx(He,{ref:E,source:{uri:je(r)},originWhitelist:["*"],onMessage:D,onShouldStartLoadWithRequest:v,onOpenWindow:m,injectedJavaScriptBeforeContentLoaded:w,javaScriptEnabled:!0,domStorageEnabled:!0,style:ee.webview,containerStyle:ee.webview,onError:i=>{o&&console.warn("[tiun] webview load error:",i.nativeEvent),P(!0)},onHttpError:i=>{o&&console.warn("[tiun] webview http error:",i.nativeEvent),P(!0)}}),L&&V?g.jsx(De,{language:r.language,dark:f==="dark",onRetry:z}):null]})}),ee=b.StyleSheet.create({container:{position:"absolute",top:0,left:0,zIndex:9999,elevation:9999},webview:{flex:1,backgroundColor:"transparent"},visible:{opacity:1},hidden:{opacity:0}});class Je{constructor(){fe(this,"listeners",new Map)}on(r,a){let u=this.listeners.get(r);return u||(u=new Set,this.listeners.set(r,u)),u.add(a),()=>{var o;(o=this.listeners.get(r))==null||o.delete(a)}}emit(r,a){const u=this.listeners.get(r);if(u)for(const o of u)try{o(a)}catch{}}}const Ee=l.createContext(null),be=l.createContext(null);function ze({config:t,children:r}){const a=l.useRef(null),u=l.useRef(!1),o=l.useRef([]),d=l.useRef(new Map),f=l.useRef(new Je).current,[E,V]=l.useState(!1),[A,L]=l.useState(null),[P,k]=l.useState(!1),[j,z]=l.useState(null),w=l.useCallback(c=>{u.current?c():o.current.push(c)},[]),N=l.useCallback(c=>{var m,v,I,R,i,n,T,y,p,C,O,Y;switch(c.type){case"cryptoCheck":z(!!((m=c.payload)!=null&&m.subtle&&((v=c.payload)!=null&&v.secureContext)));break;case"TIUN_SNIPPET_INITIALIZED":{u.current=!0,k(!0),f.emit("ready",void 0);const $=o.current;o.current=[],$.forEach(e=>e());break}case"TIUN_USER_CHANGE":{const $=!!((I=c.payload)!=null&&I.isAuthenticated),e=((R=c.payload)==null?void 0:R.user)??null;V($),L(e),f.emit("userChange",{isAuthenticated:$,user:e}),((i=c.payload)==null?void 0:i.userEvent)==="login"&&f.emit("login",{user:e}),((n=c.payload)==null?void 0:n.userEvent)==="logout"&&f.emit("logout",void 0);break}case"TIUN_VERIFICATION_TOKEN":{const $=((T=c.payload)==null?void 0:T.token)??null,e=(y=c.payload)==null?void 0:y.requestId;e&&d.current.has(e)&&(d.current.get(e)($),d.current.delete(e));break}case"TIUN_SHOW_PAYWALL":f.emit("paywallShow",{isConnected:!!((p=c.payload)!=null&&p.isConnected)});break;case"TIUN_HIDE_PAYWALL":f.emit("paywallHide",{sessionId:((C=c.payload)==null?void 0:C.sessionId)??"",isConnected:((O=c.payload)==null?void 0:O.isConnected)??!0});break;case"TIUN_ERROR":f.emit("error",((Y=c.payload)==null?void 0:Y.error)??c.payload??{});break}},[f]);l.useEffect(()=>{const c=v=>{if(!v||!Ue(t,v))return;const I=Te(v);w(()=>{var R;return(R=a.current)==null?void 0:R.resolveCheckout(I)})},m=b.Linking.addEventListener("url",({url:v})=>c(v));return b.Linking.getInitialURL().then(c).catch(()=>{}),()=>m.remove()},[t,w]);const q=l.useCallback(()=>w(()=>{var c;return(c=a.current)==null?void 0:c.login()}),[w]),U=l.useCallback(()=>w(()=>{var c;return(c=a.current)==null?void 0:c.logout()}),[w]),B=l.useCallback(c=>w(()=>{var m;return(m=a.current)==null?void 0:m.checkout(c==null?void 0:c.productId,c==null?void 0:c.referenceId)}),[w]),D=l.useCallback(()=>new Promise(c=>{const m=`vt_${Math.random().toString(36).slice(2)}_${Date.now()}`;let v=!1;const I=R=>{v||(v=!0,d.current.delete(m),c(R))};d.current.set(m,I),w(()=>{var R;return(R=a.current)==null?void 0:R.getVerificationToken(m)}),setTimeout(()=>I(null),5e3)}),[w]),G=l.useMemo(()=>({isAuthenticated:E,user:A,ready:P,cryptoOk:j,login:q,logout:U,checkout:B,getUserVerificationToken:D}),[E,A,P,j,q,U,B,D]);return g.jsx(Ee.Provider,{value:G,children:g.jsxs(be.Provider,{value:f,children:[r,g.jsx(Ke,{ref:a,config:t,onEvent:N})]})})}function Me(){const t=l.useContext(Ee);if(!t)throw new Error("useTiun must be used within a <TiunProvider>");return t}function Xe(t,r){const a=l.useContext(be),u=l.useRef(r);u.current=r,l.useEffect(()=>{if(!a)throw new Error("useTiunEvent must be used within a <TiunProvider>");return a.on(t,o=>u.current(o))},[a,t])}exports.TiunProvider=ze;exports.useTiun=Me;exports.useTiunEvent=Xe;
22
+ <%s key={someKey} {...props} />`,_,S,R,S),Q[S+_]=!0)}if(S=null,T!==void 0&&(i(T),S=""+T),y(c)&&(i(c.key),S=""+c.key),"key"in c){T={};for(var v in c)v!=="key"&&(T[v]=c[v])}else T=c;return S&&p(T,typeof t=="function"?t.displayName||t.name||"Unknown":t),$(t,S,P,N,o(),T,M,J)}function O(t){typeof t=="object"&&t!==null&&t.$$typeof===L&&t._store&&(t._store.validated=1)}var g=s,L=Symbol.for("react.transitional.element"),D=Symbol.for("react.portal"),q=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),V=Symbol.for("react.profiler"),A=Symbol.for("react.consumer"),Y=Symbol.for("react.context"),G=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),H=Symbol.for("react.memo"),W=Symbol.for("react.lazy"),B=Symbol.for("react.activity"),K=Symbol.for("react.client.reference"),a=g.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,e=Object.prototype.hasOwnProperty,u=Array.isArray,f=console.createTask?console.createTask:function(){return null};g={"react-stack-bottom-frame":function(t){return t()}};var d,E={},m=g["react-stack-bottom-frame"].bind(g,h)(),I=f(l(h)),Q={};te.Fragment=q,te.jsx=function(t,c,T,_,N){var P=1e4>a.recentlyCreatedOwnerStacks++;return x(t,c,T,!1,_,N,P?Error("react-stack-top-frame"):m,P?f(l(t)):I)},te.jsxs=function(t,c,T,_,N){var P=1e4>a.recentlyCreatedOwnerStacks++;return x(t,c,T,!0,_,N,P?Error("react-stack-top-frame"):m,P?f(l(t)):I)}}()),te}process.env.NODE_ENV==="production"?se.exports=ke():se.exports=ge();var k=se.exports;const Ce={errorPillText:"Technical Error",errorNotificationTitle:"Technical error",errorNotificationSubtitle:"Please reload the page or contact our support.",errorTitle:"Technical error",errorTextBeforeEmail:"Try reloading the page. If the error persists, please contact ",errorTextAfterEmail:" and we’ll help you right away.",connectionErrorTitle:"No connection",connectionErrorText:"We couldn’t reach tiun. Check your internet connection and try again.",connectionErrorCta:"Try again"},Pe={errorPillText:"Erreur Technique",errorNotificationTitle:"Erreur technique",errorNotificationSubtitle:"Veuillez recharger la page ou contacter notre support.",errorTitle:"Erreur technique",errorTextBeforeEmail:"Veuillez recharger la page. Si l’erreur persiste, contactez ",errorTextAfterEmail:" et nous vous aiderons immédiatement.",connectionErrorTitle:"Pas de connexion",connectionErrorText:"Impossible de joindre tiun. Vérifiez votre connexion Internet et réessayez.",connectionErrorCta:"Réessayer"},Ne={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte lade die Seite neu, oder kontaktiere unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte lade die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktiere ",errorTextAfterEmail:" und wir helfen Dir sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfe deine Internetverbindung und versuche es erneut.",connectionErrorCta:"Erneut versuchen"},Oe={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte laden Sie die Seite neu, oder kontaktieren Sie unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte laden Sie die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktieren Sie ",errorTextAfterEmail:" und wir helfen Ihnen sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",connectionErrorCta:"Erneut versuchen"};function Ie(r,n="informal"){switch((r??"en").trim().toLowerCase()){case"de":return n==="formal"?Oe:Ne;case"fr":return Pe;default:return Ce}}const z={start:"TIUN_START",checkout:"TIUN_CHECKOUT",updateContent:"TIUN_UPDATE_CONTENT",login:"TIUN_LOGIN",logout:"TIUN_LOGOUT",getVerificationToken:"TIUN_GET_VERIFICATION_TOKEN",setAppearance:"TIUN_SET_APPEARANCE",listProducts:"TIUN_LIST_PRODUCTS",getProduct:"TIUN_GET_PRODUCT",listProductAccess:"TIUN_LIST_PRODUCT_ACCESS",checkProductAccess:"TIUN_CHECK_PRODUCT_ACCESS",productResult:"TIUN_PRODUCT_RESULT",overlayChange:"TIUN_OVERLAY_CHANGE",popPubKeyRequest:"TIUN_POP_PUBKEY_REQUEST",popSignRequest:"TIUN_POP_SIGN_REQUEST",tokenGet:"TIUN_TOKEN_GET",tokenPersist:"TIUN_TOKEN_PERSIST",nativeReset:"TIUN_NATIVE_RESET",popPubKey:"TIUN_POP_PUBKEY",restoreToken:"TIUN_RESTORE_TOKEN",popSignResult:"TIUN_POP_SIGN_RESULT",resolveCheckout:"TIUN_RESOLVE_CHECKOUT"},xe="__TIUN_NATIVE_CRYPTO__",Ae="https://api.tiun.live";function ue(r){return(r.host??Ae).replace(/\/$/,"")}function ae(r){return`app.tiun.pop.${r.snippetId||"default"}`}function re(r){return`app.tiun.token.${r.snippetId||"default"}`}function Ue(r){return`${`${ue(r)}/live_api/v2/snippets/${encodeURIComponent(r.snippetId)}/webview_return`}?to=${encodeURIComponent(r.returnUrl)}`}function je(r){const n={language:r.language??"en"},i=Object.entries(n).map(([o,h])=>`${encodeURIComponent(o)}=${encodeURIComponent(h)}`).join("&"),l=`${ue(r)}/live_api/v2/snippets/${encodeURIComponent(r.snippetId)}/webview_host`;return i?`${l}?${i}`:l}function Ee(r){const n=r.indexOf("?");if(!(n<0))for(const i of r.slice(n+1).split("&")){const l=i.indexOf("=");if((l<0?i:i.slice(0,l))==="status"){const h=l<0?"":i.slice(l+1);return h?decodeURIComponent(h):void 0}}}function $e(r,n){const i=r.returnUrl.split("?")[0];return n.startsWith(i)}const le="1005";function de(r){return r==null?void 0:r.code}async function Le(r){try{return await oe.getPublicKey(r)}catch(n){if(de(n)===le)return oe.generate(r,{requireUserAuthentication:!1});throw n}}async function qe(r){try{return await oe.getPublicKey(r)}catch(n){if(de(n)===le)return null;throw n}}function Fe(r,n){return oe.sign(r,n)}async function We(r){try{await oe.removeKey(r)}catch(n){if(de(n)!==le)throw n}}const De="tiun_auth_token";async function Ve(r){const n=await ie.getGenericPassword({service:r});return n?n.password:null}async function Ye(r,n){await ie.setGenericPassword(De,n,{service:r,accessible:ie.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY})}async function ce(r){await ie.resetGenericPassword({service:r})}function Ge(r){const n=Ie(r);return{title:n.connectionErrorTitle,text:n.connectionErrorText,cta:n.connectionErrorCta}}function He({language:r,dark:n,onRetry:i}){const l=Ge(r),o=n?Be:null;return k.jsxs(w.View,{style:[U.container,o==null?void 0:o.container],children:[k.jsxs(w.View,{style:U.content,children:[k.jsx(w.Text,{style:[U.title,o==null?void 0:o.title],children:l.title}),k.jsx(w.View,{style:[U.iconBadge,o==null?void 0:o.iconBadge],children:k.jsx(w.Text,{style:[U.iconGlyph,o==null?void 0:o.iconGlyph],children:"!"})}),k.jsx(w.Text,{style:[U.text,o==null?void 0:o.text],children:l.text})]}),k.jsx(w.Pressable,{accessibilityRole:"button",onPress:i,style:({pressed:h})=>[U.button,o==null?void 0:o.button,h&&U.buttonPressed],children:k.jsx(w.Text,{style:[U.buttonText,o==null?void 0:o.buttonText],children:l.cta})})]})}const U=w.StyleSheet.create({container:{...w.StyleSheet.absoluteFillObject,backgroundColor:"#fff",padding:24,justifyContent:"space-between"},content:{flex:1,alignItems:"center",justifyContent:"center",gap:24},title:{fontSize:20,fontWeight:"600",color:"#000",textAlign:"center"},iconBadge:{width:40,height:40,borderRadius:20,backgroundColor:"#FCE7F3",alignItems:"center",justifyContent:"center"},iconGlyph:{color:"#DB2777",fontSize:22,fontWeight:"700",lineHeight:26},text:{fontSize:16,fontWeight:"500",color:"#4B5563",textAlign:"center"},button:{backgroundColor:"#000",borderRadius:999,minHeight:56,alignItems:"center",justifyContent:"center",alignSelf:"stretch"},buttonPressed:{opacity:.9},buttonText:{color:"#fff",fontSize:16,fontWeight:"500"}}),Be=w.StyleSheet.create({container:{backgroundColor:"#0a0a0a"},title:{color:"#fafafa"},iconBadge:{backgroundColor:"#500724"},iconGlyph:{color:"#F472B6"},text:{color:"#A1A1AA"},button:{backgroundColor:"#fafafa"},buttonText:{color:"#000"}}),Ke=we.WebView;function X(r){return`try{window.tiunHost&&${r};}catch(e){}; true;`}const Me=s.forwardRef(function({config:n,onEvent:i},l){const o=!!n.debug,h=w.useColorScheme(),y=n.appearance==="dark"||n.appearance==="auto"&&h==="dark"?"dark":"light",p=s.useRef(null),[j,$]=s.useState(!1),[x,O]=s.useState(!1),g=s.useRef(!1),L=s.useRef(!1),D=()=>{var a;O(!1),(a=p.current)==null||a.reload()};s.useEffect(()=>{if(!x)return;const a=w.AppState.addEventListener("change",e=>{var u;e==="active"&&(O(!1),(u=p.current)==null||u.reload())});return()=>a.remove()},[x]);const q=`window.${xe} = true;window.__TIUN_CONFIG__ = Object.assign({}, window.__TIUN_CONFIG__, { returnUrl: ${JSON.stringify(Ue(n))}, appearance: ${JSON.stringify(y)} });true;`,b=(a,...e)=>{var u;return(u=p.current)==null?void 0:u.injectJavaScript(X(`window.tiunHost.${a}(${e.map(f=>JSON.stringify(f)??"null").join(",")})`))},V=s.useRef(y);s.useEffect(()=>{y!==V.current&&(V.current=y,b("setAppearance",y))},[y]);const A=a=>{var e;L.current||(L.current=!0,Z.close().catch(()=>{}),Z.closeAuth().catch(()=>{}),$(!0),(e=p.current)==null||e.injectJavaScript(X(`window.tiunHost.resolveCheckout(${a?JSON.stringify(a):""})`)))},Y=a=>{var e,u,f;switch(a.type){case z.popPubKeyRequest:return Le(ae(n)).then(d=>b("popPubKey",d)).catch(d=>{o&&console.warn("[tiun] ensurePopKey failed:",d),b("popPubKey",null)}),!0;case z.tokenGet:return(async()=>{try{const d=await Ve(re(n));if(d&&!await qe(ae(n))){await ce(re(n)),b("restoreToken",null);return}b("restoreToken",d)}catch{b("restoreToken",null)}})(),!0;case z.popSignRequest:{const d=(e=a.payload)==null?void 0:e.requestId,E=(u=a.payload)==null?void 0:u.information;return Fe(ae(n),E).then(m=>b("popSignResult",d,m,null)).catch(m=>{const I=(m==null?void 0:m.code)??"sign_failed";o&&console.warn("[tiun] popSign failed:",m),b("popSignResult",d,null,String(I))}),!0}case z.tokenPersist:{const d=((f=a.payload)==null?void 0:f.token)??null;return(d?Ye(re(n),d):ce(re(n))).catch(E=>o&&console.warn("[tiun] token persist failed:",E)),!0}case z.nativeReset:return Promise.allSettled([We(ae(n)),ce(re(n))]),!0;default:return!1}};s.useImperativeHandle(l,()=>({login:()=>{var a;$(!0),(a=p.current)==null||a.injectJavaScript(X("window.tiunHost.login()"))},checkout:(a,e)=>{var f;$(!0),g.current=!0,L.current=!1;const u=e?[a||null,e]:a?[a]:[];(f=p.current)==null||f.injectJavaScript(X(`window.tiunHost.checkout(${u.map(d=>JSON.stringify(d)).join(",")})`))},logout:()=>{var a;return(a=p.current)==null?void 0:a.injectJavaScript(X("window.tiunHost.logout()"))},getVerificationToken:a=>{var e;return(e=p.current)==null?void 0:e.injectJavaScript(X(`window.tiunHost.getVerificationToken(${a?JSON.stringify(a):""})`))},productRequest:(a,e,...u)=>b(a,e,...u),resolveCheckout:A,reload:()=>{var a;return(a=p.current)==null?void 0:a.reload()}}),[]);const G=a=>{var u,f,d;let e=null;try{e=JSON.parse(a.nativeEvent.data)}catch{o&&console.warn("[tiun] non-JSON bridge message:",a.nativeEvent.data);return}if(!(!e||typeof e.type!="string")){if(e.type==="console"){o&&console.log("[tiun webview]",(u=e.payload)==null?void 0:u.level,(f=e.payload)==null?void 0:f.message);return}if((e.type==="cryptoCheck"||e.type==="hostBridgeReady")&&O(!1),o&&console.log("[tiun] <-",e.type,e.payload),!Y(e)){if(e.type===z.overlayChange){const E=!!((d=e.payload)!=null&&d.overlay);$(E),E||(g.current=!1)}i(e)}}},F=a=>{if(g.current=!1,w.Platform.OS==="ios"){Z.openAuth(a,n.returnUrl).then(e=>{e.type==="success"&&e.url?A(Ee(e.url)):e.type==="cancel"&&A("cancelled")}).catch(e=>o&&console.warn("[tiun] openAuth error:",e));return}Z.open(a,{showTitle:!1,enableUrlBarHiding:!1,enableDefaultShare:!1,forceCloseOnRedirection:!1}).then(e=>{e.type==="cancel"&&A("cancelled")}).catch(e=>o&&console.warn("[tiun] in-app browser open error:",e))},C=a=>{Z.open(a,{modalPresentationStyle:"fullScreen",modalEnabled:!0,animated:!0,enableBarCollapsing:!0}).catch(e=>o&&console.warn("[tiun] in-app browser open failed:",e))},H=a=>{var u;const e=(u=a.nativeEvent)==null?void 0:u.targetUrl;e&&(g.current?F(e):C(e))},W=a=>{const e=a.url;return e.startsWith(ue(n))||e.startsWith("about:")||e.startsWith("data:")||e==="about:blank"?!0:e.startsWith("http://")||e.startsWith("https://")?(g.current&&a.isTopFrame!==!1?F(e):C(e),!1):!0},{width:B,height:K}=w.useWindowDimensions();return k.jsxs(w.View,{pointerEvents:j?"auto":"none",style:[ne.container,{width:B,height:K},j?ne.visible:ne.hidden],children:[k.jsx(Ke,{ref:p,source:{uri:je(n)},originWhitelist:["*"],onMessage:G,onShouldStartLoadWithRequest:W,onOpenWindow:H,injectedJavaScriptBeforeContentLoaded:q,javaScriptEnabled:!0,domStorageEnabled:!0,style:ne.webview,containerStyle:ne.webview,onError:a=>{o&&console.warn("[tiun] webview load error:",a.nativeEvent),O(!0)},onHttpError:a=>{o&&console.warn("[tiun] webview http error:",a.nativeEvent),O(!0)}}),x&&j?k.jsx(He,{language:n.language,dark:y==="dark",onRetry:D}):null]})}),ne=w.StyleSheet.create({container:{position:"absolute",top:0,left:0,zIndex:9999,elevation:9999},webview:{flex:1,backgroundColor:"transparent"},visible:{opacity:1},hidden:{opacity:0}});class Je{constructor(){fe(this,"listeners",new Map)}on(n,i){let l=this.listeners.get(n);return l||(l=new Set,this.listeners.set(n,l)),l.add(i),()=>{var o;(o=this.listeners.get(n))==null||o.delete(i)}}emit(n,i){const l=this.listeners.get(n);if(l)for(const o of l)try{o(i)}catch{}}}const ze=1e4,he=()=>Promise.reject({code:"invalid_argument",message:"productId is required"}),be=s.createContext(null),ye=s.createContext(null);function Xe({config:r,children:n}){const i=s.useRef(null),l=s.useRef(!1),o=s.useRef([]),h=s.useRef(new Map),y=s.useRef(new Map),p=s.useRef(new Je).current,[j,$]=s.useState(!1),[x,O]=s.useState(null),[g,L]=s.useState(!1),[D,q]=s.useState(null),b=s.useCallback(e=>{l.current?e():o.current.push(e)},[]),V=s.useCallback(e=>{var u,f,d,E,m,I,Q,t,c,T,_,N,P,M,J,S;switch(e.type){case"cryptoCheck":q(!!((u=e.payload)!=null&&u.subtle&&((f=e.payload)!=null&&f.secureContext)));break;case"TIUN_SNIPPET_INITIALIZED":{l.current=!0,L(!0),p.emit("ready",void 0);const R=o.current;o.current=[],R.forEach(v=>v());break}case"TIUN_USER_CHANGE":{const R=!!((d=e.payload)!=null&&d.isAuthenticated),v=((E=e.payload)==null?void 0:E.user)??null;$(R),O(v),p.emit("userChange",{event:((m=e.payload)==null?void 0:m.userEvent)??"update",isAuthenticated:R,user:v}),((I=e.payload)==null?void 0:I.userEvent)==="login"&&p.emit("login",{user:v}),((Q=e.payload)==null?void 0:Q.userEvent)==="logout"&&p.emit("logout",void 0);break}case"TIUN_VERIFICATION_TOKEN":{const R=((t=e.payload)==null?void 0:t.token)??null,v=(c=e.payload)==null?void 0:c.requestId;v&&h.current.has(v)&&(h.current.get(v)(R),h.current.delete(v));break}case"TIUN_PRODUCT_RESULT":{const R=(T=e.payload)==null?void 0:T.requestId,v=R?y.current.get(R):void 0;if(!v)break;clearTimeout(v.timer),y.current.delete(R),(_=e.payload)!=null&&_.error?v.reject(e.payload.error):v.resolve((N=e.payload)==null?void 0:N.result);break}case"TIUN_SHOW_PAYWALL":p.emit("paywallShow",{isConnected:!!((P=e.payload)!=null&&P.isConnected)});break;case"TIUN_HIDE_PAYWALL":p.emit("paywallHide",{sessionId:((M=e.payload)==null?void 0:M.sessionId)??"",isConnected:((J=e.payload)==null?void 0:J.isConnected)??!0});break;case"TIUN_ERROR":p.emit("error",((S=e.payload)==null?void 0:S.error)??e.payload??{});break}},[p]);s.useEffect(()=>{const e=f=>{if(!f||!$e(r,f))return;const d=Ee(f);b(()=>{var E;return(E=i.current)==null?void 0:E.resolveCheckout(d)})},u=w.Linking.addEventListener("url",({url:f})=>e(f));return w.Linking.getInitialURL().then(e).catch(()=>{}),()=>u.remove()},[r,b]);const A=s.useCallback(()=>b(()=>{var e;return(e=i.current)==null?void 0:e.login()}),[b]),Y=s.useCallback(()=>b(()=>{var e;return(e=i.current)==null?void 0:e.logout()}),[b]),G=s.useCallback(e=>b(()=>{var u;return(u=i.current)==null?void 0:u.checkout(e==null?void 0:e.productId,e==null?void 0:e.referenceId)}),[b]),F=s.useCallback(()=>new Promise(e=>{const u=`vt_${Math.random().toString(36).slice(2)}_${Date.now()}`;let f=!1;const d=E=>{f||(f=!0,h.current.delete(u),e(E))};h.current.set(u,d),b(()=>{var E;return(E=i.current)==null?void 0:E.getVerificationToken(u)}),setTimeout(()=>d(null),5e3)}),[b]),C=s.useCallback((e,...u)=>new Promise((f,d)=>{const E=`pr_${Math.random().toString(36).slice(2)}_${Date.now()}`,m={resolve:f,reject:d};y.current.set(E,m),b(()=>{var I;y.current.get(E)===m&&(m.timer=setTimeout(()=>{y.current.delete(E),d({code:"timeout",message:`${e} timed out`})},ze),(I=i.current)==null||I.productRequest(e,E,...u))})}),[b]);s.useEffect(()=>{const e=y.current;return()=>{e.forEach(({reject:u,timer:f})=>{clearTimeout(f),u({code:"destroyed",message:"TiunProvider was unmounted"})}),e.clear()}},[]);const H=s.useCallback(()=>C("listProducts"),[C]),W=s.useCallback(e=>e?C("getProduct",e):he(),[C]),B=s.useCallback(()=>C("listProductAccess"),[C]),K=s.useCallback((e,u)=>e?C("checkProductAccess",e,(u==null?void 0:u.referenceId)||void 0):he(),[C]),a=s.useMemo(()=>({isAuthenticated:j,user:x,ready:g,cryptoOk:D,login:A,logout:Y,checkout:G,getUserVerificationToken:F,listProducts:H,getProduct:W,listProductAccess:B,checkProductAccess:K}),[j,x,g,D,A,Y,G,F,H,W,B,K]);return k.jsx(be.Provider,{value:a,children:k.jsxs(ye.Provider,{value:p,children:[n,k.jsx(Me,{ref:i,config:r,onEvent:V})]})})}function Qe(){const r=s.useContext(be);if(!r)throw new Error("useTiun must be used within a <TiunProvider>");return r}function Ze(r,n){const i=s.useContext(ye),l=s.useRef(n);l.current=n,s.useEffect(()=>{if(!i)throw new Error("useTiunEvent must be used within a <TiunProvider>");return i.on(r,o=>l.current(o))},[i,r])}exports.TiunProvider=Xe;exports.useTiun=Qe;exports.useTiunEvent=Ze;