@vitraun/webar 0.1.1 → 0.1.3
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 +60 -91
- package/dist/widget-runtime.min.js +1 -1
- package/dist/widget.min.js +1 -1
- package/package.json +3 -11
package/README.md
CHANGED
|
@@ -1,75 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vitraun/webar
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web Component package for Vitraun Virtual Try-On (`<vitraun-vto>`), distributed as npm + CDN bundle.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Install (npm)
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
```bash
|
|
8
|
+
npm i @vitraun/webar
|
|
9
|
+
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
```ts
|
|
12
|
+
import '@vitraun/webar'
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
// In React / TSX you can write `auto-open={true}` (no spread needed).
|
|
15
|
+
```
|
|
14
16
|
|
|
15
17
|
```html
|
|
16
|
-
<script src="https://cdn.jsdelivr.net/npm/@vitraun/webar-cdn@0.1.0/widget.min.js"></script>
|
|
17
18
|
<vitraun-vto
|
|
18
|
-
merchant-id="
|
|
19
|
-
|
|
20
|
-
lang="en
|
|
21
|
-
|
|
19
|
+
merchant-id="vtrn-mch-key-..."
|
|
20
|
+
widget-id="vtrn-wdg-key-..."
|
|
21
|
+
lang="en"
|
|
22
|
+
auto-open
|
|
22
23
|
></vitraun-vto>
|
|
23
|
-
<script>
|
|
24
|
-
document.querySelector('vitraun-vto')?.open()
|
|
25
|
-
</script>
|
|
26
24
|
```
|
|
27
25
|
|
|
28
|
-
**
|
|
29
|
-
|
|
30
|
-
```html
|
|
31
|
-
<script src="https://cdn.jsdelivr.net/npm/@vitraun/webar-cdn@0.1.0/widget.min.js"></script>
|
|
32
|
-
<vitraun-vto merchant-id="YOUR_MERCHANT_ID" env="prod" lang="pt-BR"></vitraun-vto>
|
|
33
|
-
<script type="module">
|
|
34
|
-
import { subscribeVitraunVTOEvents } from 'https://cdn.jsdelivr.net/npm/@vitraun/webar-cdn@0.1.0/events.min.js'
|
|
26
|
+
**Try-On app origin (`data-base-url`)** is baked into the published bundle from `constants/default-widget-base-url.js` (default dev app origin). Retailers do not need to set it. Use `**data-base-url`** only to override (staging, self-hosted). Rebuild with `VITRAUN_WIDGET_EMBEDDED_BASE_URL=<origin>` when the default dev host is wrong for your setup.
|
|
35
27
|
|
|
36
|
-
|
|
37
|
-
subscribeVitraunVTOEvents(el, (entry) => {
|
|
38
|
-
console.log(entry.type, entry.detail)
|
|
39
|
-
})
|
|
40
|
-
</script>
|
|
41
|
-
```
|
|
28
|
+
The **widget script** itself should be loaded from your **CDN**, from **[jsDelivr](https://www.jsdelivr.com/)** (mirror npm), or via `import '@vitraun/webar'` — not from the Try-On Next.js app.
|
|
42
29
|
|
|
43
|
-
|
|
30
|
+
### jsDelivr (`@vitraun/webar` only)
|
|
44
31
|
|
|
45
|
-
|
|
32
|
+
After **`npm publish`** of `@vitraun/webar`, files under `dist/` are available on jsDelivr (paths match the tarball):
|
|
46
33
|
|
|
47
|
-
```
|
|
48
|
-
npm
|
|
34
|
+
```text
|
|
35
|
+
https://cdn.jsdelivr.net/npm/@vitraun/webar@<version>/dist/widget.min.js
|
|
36
|
+
https://cdn.jsdelivr.net/npm/@vitraun/webar@<version>/dist/events.min.js
|
|
49
37
|
```
|
|
50
38
|
|
|
51
|
-
|
|
52
|
-
import '@vitraun/webar'
|
|
53
|
-
```
|
|
39
|
+
Example (`<version>` = published semver, e.g. `0.1.2`):
|
|
54
40
|
|
|
55
41
|
```html
|
|
56
|
-
<vitraun
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
platform="web"
|
|
61
|
-
isolated-sku="8028997081552"
|
|
62
|
-
apply-skus="SKU001,SKU002"
|
|
63
|
-
></vitraun-vto>
|
|
42
|
+
<script src="https://cdn.jsdelivr.net/npm/@vitraun/webar@0.1.2/dist/widget.min.js"></script>
|
|
43
|
+
<script type="module">
|
|
44
|
+
import { subscribeVitraunVTOEvents } from 'https://cdn.jsdelivr.net/npm/@vitraun/webar@0.1.2/dist/events.min.js'
|
|
45
|
+
</script>
|
|
64
46
|
```
|
|
65
47
|
|
|
66
|
-
|
|
48
|
+
The `package.json` field **`jsdelivr`** points to `dist/widget.min.js` so the default short URL `https://cdn.jsdelivr.net/npm/@vitraun/webar` resolves to the widget bundle when supported by jsDelivr.
|
|
67
49
|
|
|
68
|
-
|
|
50
|
+
Optional attribute `**auto-open`**: when present (or `auto-open="true"`), the element calls `open()` after it connects, so hosts do not need a `useLayoutEffect` or script callback.
|
|
69
51
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
52
|
+
Optional attribute `**console**`: when `true`, the widget shows an Events console button that opens a modal with captured Try-On events.
|
|
53
|
+
|
|
54
|
+
## Events and logs helpers
|
|
55
|
+
|
|
56
|
+
The package exports helpers to capture widget events consistently:
|
|
73
57
|
|
|
74
58
|
```ts
|
|
75
59
|
import {
|
|
@@ -77,62 +61,47 @@ import {
|
|
|
77
61
|
subscribeVitraunVTOEvents,
|
|
78
62
|
} from '@vitraun/webar'
|
|
79
63
|
|
|
80
|
-
const dispose = subscribeVitraunVTOEvents(
|
|
64
|
+
const dispose = subscribeVitraunVTOEvents(containerElement, (entry) => {
|
|
81
65
|
console.log(entry.type, entry.timestamp, entry.detail)
|
|
82
66
|
})
|
|
67
|
+
|
|
68
|
+
// later:
|
|
83
69
|
dispose()
|
|
84
70
|
```
|
|
85
71
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
## Obtaining Vitraun credentials
|
|
89
|
-
|
|
90
|
-
A valid **`merchant-id`** and Vitraun **environment** (`env`) are required for session init and the hosted widget. Obtain production or trial credentials through your **Vitraun account** or sales/onboarding contact.
|
|
91
|
-
|
|
92
|
-
For SDK or integration issues, use [**GitHub Issues**](https://github.com/clagils/tryon-new-version/issues) (see `repository` / `bugs` in `package.json`).
|
|
93
|
-
|
|
94
|
-
## License
|
|
95
|
-
|
|
96
|
-
Proprietary — full text in [**`LICENSE.txt`**](https://github.com/clagils/tryon-new-version/blob/main/vto-npm/webar/LICENSE.txt) (`SEE LICENSE IN LICENSE.txt` in `package.json`).
|
|
97
|
-
|
|
98
|
-
## Resources and links
|
|
72
|
+
By default it listens to: `addToCart`, `removeFromCart`, `redirectToCart`, and `analysisFinished`.
|
|
73
|
+
You can opt in to `statusChange` and `vtoUsage` using options, or pass a custom `eventTypes` list.
|
|
99
74
|
|
|
100
|
-
|
|
101
|
-
- [Widget iframe flow](https://github.com/clagils/tryon-new-version/blob/main/vto-npm/docs/webar-widget-iframe-flow.md) — embed, `postMessage`, heartbeat (pt‑BR)
|
|
102
|
-
- [Publish checklist](https://github.com/clagils/tryon-new-version/blob/main/vto-npm/docs/publish-checklist.md) — releasing `@vitraun/core`, `@vitraun/webar`, `@vitraun/webar-cdn`
|
|
103
|
-
- [`@vitraun/webar` on npm](https://www.npmjs.com/package/@vitraun/webar)
|
|
104
|
-
- [`@vitraun/webar-cdn` on npm](https://www.npmjs.com/package/@vitraun/webar-cdn) (CDN‑friendly flat bundle)
|
|
105
|
-
- [Monorepo layout](https://github.com/clagils/tryon-new-version/blob/main/vto-npm/README.md) — `vto-npm` workspaces
|
|
75
|
+
For React consumers, the package also provides a hook:
|
|
106
76
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
| Import path | Role |
|
|
110
|
-
|-------------|------|
|
|
111
|
-
| `@vitraun/webar` | ESM + types: registers the element when the browser supports custom elements; re‑exports event helpers. |
|
|
112
|
-
| `@vitraun/webar/react` | `useVitraunVTOEventLogs` + types (peer: `react`, `react-dom` ≥ 18). |
|
|
113
|
-
| `@vitraun/webar/widget` / `@vitraun/webar/widget.min.js` | IIFE for `<script src="...">`. |
|
|
114
|
-
| `@vitraun/webar/events` | ESM bundle for `subscribeVitraunVTOEvents` and constants. |
|
|
115
|
-
| `@vitraun/webar/runtime` | Runtime chunk loaded dynamically from the npm entry (not the same as the CDN IIFE pair). |
|
|
77
|
+
```ts
|
|
78
|
+
import { useVitraunVTOEventLogs } from '@vitraun/webar/react'
|
|
116
79
|
|
|
117
|
-
|
|
80
|
+
const { events, clearEvents } = useVitraunVTOEventLogs(containerRef.current)
|
|
81
|
+
```
|
|
118
82
|
|
|
119
|
-
##
|
|
83
|
+
## Use via CDN (HTML puro)
|
|
120
84
|
|
|
121
|
-
|
|
85
|
+
Publish `dist/widget.min.js` and `dist/widget-runtime.min.js` to your CDN after each release (S3 + CloudFront, R2, etc.). This repo ships an **AWS S3** helper that uses the AWS CLI:
|
|
122
86
|
|
|
123
87
|
```bash
|
|
124
|
-
npm ci
|
|
125
88
|
npm run build
|
|
126
|
-
|
|
127
|
-
|
|
89
|
+
export VITRAUN_CDN_UPLOAD=1
|
|
90
|
+
export VITRAUN_CDN_S3_BUCKET=your-bucket-name
|
|
91
|
+
npm run deploy:cdn
|
|
128
92
|
```
|
|
129
93
|
|
|
130
|
-
|
|
94
|
+
See `config/cdn-upload.env.example` for all variables (optional root prefix, dry-run, region).
|
|
131
95
|
|
|
132
|
-
|
|
96
|
+
```html
|
|
97
|
+
<script src="https://cdn.example.com/@vitraun/webar@0.1.0/dist/widget.min.js"></script>
|
|
98
|
+
<vitraun-vto
|
|
99
|
+
merchant-id="vtrn-mch-key-..."
|
|
100
|
+
widget-id="vtrn-wdg-key-..."
|
|
101
|
+
lang="en"
|
|
102
|
+
></vitraun-vto>
|
|
103
|
+
<script>
|
|
104
|
+
document.querySelector('vitraun-vto')?.open()
|
|
105
|
+
</script>
|
|
106
|
+
```
|
|
133
107
|
|
|
134
|
-
[](https://www.npmjs.com/package/@vitraun/webar)
|
|
135
|
-
[](https://github.com/clagils/tryon-new-version/actions/workflows/ci.yml)
|
|
136
|
-
[](https://codecov.io/gh/clagils/tryon-new-version)
|
|
137
|
-
[](https://www.npmjs.com/package/@vitraun/webar)
|
|
138
|
-
[](https://www.typescriptlang.org/)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){"use strict";var v="VITRAUN_CONFIG",f="vtrn-vto-session",I=18e5,d=1e4,c="en-US";function r(n,t,e){var i=n.getAttribute(t);return i!=null&&i!==""?i:e}function h(n,t){if(n==null||n==="")return t;var e=String(n).toLowerCase();return e==="true"||e==="1"||e==="yes"}function m(n){if(n==null||n==="")return null;var t=parseFloat(String(n));return Number.isFinite(t)?t:null}function b(n){return!n||typeof n!="string"?[]:n.split(",").map(function(t){return t.trim()}).filter(Boolean)}function w(n,t){var e=r(n,t,"");if(!e||typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function S(n){try{return JSON.parse(n)}catch{return null}}function p(){return typeof window>"u"||!window.location||!window.location.origin?null:window.location.origin}function _(){return typeof window>"u"||!window.location||!window.location.href?null:window.location.href}function k(n){if(!n||typeof n!="string")return null;try{return new URL(n).origin}catch{return null}}function T(n){var t=String(n||"").trim().toLowerCase();if(!t)throw new Error("The env attribute is required.");if(!/^[a-z0-9-]+$/.test(t))throw new Error("The env attribute contains an invalid value.");return t}function P(n){return n?String(n).trim().toLowerCase():"web"}function C(n){return"https://api."+n+".vitraun.com/v1/tryon/init"}function O(n,t,e){var i=t||c,o="https://app."+n+".vitraun.com/"+encodeURIComponent(i)+"/virtual-tryon";return e&&(o+="?simulation=1"),o}function U(n,t,e,i){return!t||t<=0?n:new Promise(function(o,l){var a=!1,s=setTimeout(function(){if(!a){a=!0;try{i&&typeof i.abort=="function"&&i.abort()}catch{}l(new Error(e||"The operation timed out."))}},t);n.then(function(u){a||(a=!0,clearTimeout(s),o(u))}).catch(function(u){a||(a=!0,clearTimeout(s),l(u))})})}function g(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return"00000000-0000-4000-8000-000000000000";try{var n=sessionStorage.getItem(f);if(n){var t=JSON.parse(n);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch{}var e=window.crypto.randomUUID(),i=Date.now()+I;try{sessionStorage.setItem(f,JSON.stringify({id:e,exp:i}))}catch{}return e}class E extends HTMLElement{static get observedAttributes(){return["merchant-id","env","lang","isolated-sku","apply-skus","flow","basket-opens-in","checkout-opens-in","use-simple-page","show-details","show-product-price","price-from","price-to","currency-symbol","is-simulation-mode","simulation-inline-config","container-min-height","app-id","platform","bundle-id","package-name","app-version","attestation-token","debug","init-timeout-ms"]}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",env:"",lang:c,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:d},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window<"u"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window<"u"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}}attributeChangedCallback(t,e,i){e!==i&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console>"u"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift("[vitraun-vto]"),console.log.apply(console,t)}}_readAttributes(){var t=w(this,"simulation-inline-config"),e=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(e=t.features.showProductPrice);var i=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(i=t.features.useSimplePage);var o="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(o=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var a="";try{a=T(r(this,"env",""))}catch{a=""}var s=parseInt(r(this,"init-timeout-ms",String(d)),10);(!Number.isFinite(s)||s<0)&&(s=d),this._state={merchantId:r(this,"merchant-id",""),env:a,lang:r(this,"lang",c),isolatedSku:r(this,"isolated-sku",null)||null,applySkus:b(r(this,"apply-skus","")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:r(this,"flow",o),basketOpensIn:r(this,"basket-opens-in","event"),checkoutOpensIn:r(this,"checkout-opens-in","event"),useSimplePage:h(r(this,"use-simple-page",""),i),showDetails:h(r(this,"show-details",""),l),showProductPrice:h(r(this,"show-product-price",""),e),priceFrom:m(r(this,"price-from",null)),priceTo:m(r(this,"price-to",null)),currencySymbol:r(this,"currency-symbol",null)||null,isSimulationMode:h(r(this,"is-simulation-mode","false"),!1),simulationInlineConfig:t,appId:r(this,"app-id",null)||null,platform:P(r(this,"platform",null)),bundleId:r(this,"bundle-id",null)||null,packageName:r(this,"package-name",null)||null,appVersion:r(this,"app-version",null)||null,attestationToken:r(this,"attestation-token",null)||null,debug:h(r(this,"debug","false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:s}}_emit(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e??null,bubbles:!0,composed:!0}))}_setStatus(t,e){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:e||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var e=t.data;if(!(!e||typeof e!="object")){var i=this._getIframeElement();if(!(!i||!i.contentWindow)&&t.source===i.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var o=e.type,l=e.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",l);return}var a=["addToCart","removeFromCart","redirectToCart","analysisFinished"];a.indexOf(o)!==-1&&this._emit(o,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,env:this._state.env,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildResolvedUrls(){if(!this._state.env)throw new Error("The env attribute is required.");var t=O(this._state.env,this._state.lang,this._state.isSimulationMode);return{initUrl:C(this._state.env),iframeUrl:t,iframeOrigin:k(t)}}_buildInitPayload(){var t=g();return{merchantId:this._state.merchantId,tryonSessionId:t,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,inlineVirtualTryonConfig:this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"?this._state.simulationInlineConfig:null,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},context:{hostPageOrigin:p(),hostPageUrl:_(),userAgent:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document<"u"&&document.referrer?document.referrer:null,timezone:typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}_normalizeInitResponse(t,e,i){if(!t||typeof t!="object")throw new Error("Invalid init response.");var o=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:i;if(!o)throw new Error("The init API did not return sessionToken.");return{sessionToken:o,tryonSessionId:l,initUrl:e.initUrl,iframeUrl:e.iframeUrl,iframeOrigin:e.iframeOrigin}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error("The merchant-id attribute is required."));if(!this._state.env)return Promise.reject(new Error("The env attribute is required."));var e=this._getInitStateKey();if(this._initPromise&&this._initStateKey===e)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}this._initStateKey=e,this._activeInitRequestId+=1;var i=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildResolvedUrls()}catch(s){return Promise.reject(s)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController<"u"?new AbortController:null;var a=fetch(o.initUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:this._abortController?this._abortController.signal:void 0}).then(function(s){return s.ok?s.json():s.text().then(function(u){var y=S(u),x=y&&y.message||u||"Failed to initialize session ("+s.status+").";throw new Error(x)})}).then(function(s){return t._normalizeInitResponse(s,o,l.tryonSessionId)});return this._initPromise=U(a,this._state.initTimeoutMs,"Timed out while initializing the Vitraun session.",this._abortController).then(function(s){return i!==t._activeInitRequestId||(t._state.sessionToken=s.sessionToken,t._state.tryonSessionId=s.tryonSessionId,t._state.resolvedInitUrl=s.initUrl,t._state.resolvedIframeUrl=s.iframeUrl,t._state.iframeOrigin=s.iframeOrigin,t._setStatus("ready")),s}).catch(function(s){throw i!==t._activeInitRequestId||(t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:s&&s.message?s.message:"Initialization failed."})),s}).finally(function(){i===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var e=this._state.iframeOrigin;if(!e){this._log("Config not sent: iframeOrigin is missing.");return}var i={merchantId:this._state.merchantId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||g(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},hostPageOrigin:p(),hostPageUrl:_()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(i.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:v,payload:i},e)}}_renderLoading(){if(this.shadowRoot){var t=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var e=document.createElement("style");e.textContent=":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-loading {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var i=document.createElement("div");i.className="vitraun-loading",i.textContent="Loading Vitraun...",this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(i)}}_renderError(t){if(this.shadowRoot){var e=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var i=document.createElement("style");i.textContent=":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }.vitraun-error {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var o=document.createElement("div");o.className="vitraun-error",o.textContent=t||"Failed to load Vitraun.",this.shadowRoot.appendChild(i),this.shadowRoot.appendChild(o)}}_renderIframe(t,e){if(this.shadowRoot){var i=this,o=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=":host { display:block; width:100%; min-height:"+o+"; box-sizing:border-box; }";var a=document.createElement("iframe");a.src=t,a.title="Vitraun VTO",a.style.cssText="width:100%;height:100%;border:0;min-height:"+o,a.setAttribute("allow","camera"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.onload=function(){e===i._renderVersion&&[0,50,150,400,1e3].forEach(function(s){setTimeout(function(){e===i._renderVersion&&i._sendConfigToIframe()},s)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(a)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:"The merchant-id attribute is required."}),this._renderError("The merchant-id attribute is required.");return}if(!this._state.env){this._setStatus("error",{message:"The env attribute is required."}),this._renderError("The env attribute is required.");return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(e){t===this._renderVersion&&this._renderIframe(e.iframeUrl,t)}.bind(this)).catch(function(e){t===this._renderVersion&&this._renderError(e&&e.message?e.message:"Failed to load Vitraun.")}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements<"u"&&!customElements.get("vitraun-vto")&&customElements.define("vitraun-vto",E)})();
|
|
1
|
+
(function(){"use strict";var b="VITRAUN_CONFIG",p="vtrn-vto-session",w=18e5,c=1e4,f="en-US",h=80;function s(i,t,e){var n=i.getAttribute(t);return n!=null&&n!==""?n:e}function d(i,t){if(i==null||i==="")return t;var e=String(i).toLowerCase();return e==="true"||e==="1"||e==="yes"}function m(i){if(i==null||i==="")return null;var t=parseFloat(String(i));return Number.isFinite(t)?t:null}function S(i){return!i||typeof i!="string"?[]:i.split(",").map(function(t){return t.trim()}).filter(Boolean)}function k(i,t){var e=s(i,t,"");if(!e||typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function T(i){try{return JSON.parse(i)}catch{return null}}function _(){return typeof window>"u"||!window.location||!window.location.origin?null:window.location.origin}function g(){return typeof window>"u"||!window.location||!window.location.href?null:window.location.href}function P(i){if(!i||typeof i!="string")return null;try{return new URL(i).origin}catch{return null}}function C(i){var t=String(i||"").trim().toLowerCase();if(!t)throw new Error("The env attribute is required.");if(!/^[a-z0-9-]+$/.test(t))throw new Error("The env attribute contains an invalid value.");return t}function O(i){return i?String(i).trim().toLowerCase():"web"}function y(i,t){if(i==null||i==="")return t;var e=parseInt(String(i),10);return!Number.isInteger(e)||e<=0||e>65535?t:e}function U(i,t){return"https://app."+i+".vitraun.com:"+t+"/v1/tryon/init"}function E(i,t,e,n){var o=t||f,l="https://app."+i+".vitraun.com:"+n+"/"+encodeURIComponent(o)+"/virtual-tryon";return e&&(l+="?simulation=1"),l}function x(i,t,e,n){return!t||t<=0?i:new Promise(function(o,l){var a=!1,r=setTimeout(function(){if(!a){a=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch{}l(new Error(e||"The operation timed out."))}},t);i.then(function(u){a||(a=!0,clearTimeout(r),o(u))}).catch(function(u){a||(a=!0,clearTimeout(r),l(u))})})}function I(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return"00000000-0000-4000-8000-000000000000";try{var i=sessionStorage.getItem(p);if(i){var t=JSON.parse(i);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch{}var e=window.crypto.randomUUID(),n=Date.now()+w;try{sessionStorage.setItem(p,JSON.stringify({id:e,exp:n}))}catch{}return e}class R extends HTMLElement{static get observedAttributes(){return["merchant-id","env","api-port","app-port","lang","isolated-sku","apply-skus","flow","basket-opens-in","checkout-opens-in","use-simple-page","show-details","show-product-price","price-from","price-to","currency-symbol","is-simulation-mode","simulation-inline-config","container-min-height","app-id","platform","bundle-id","package-name","app-version","attestation-token","debug","init-timeout-ms"]}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",env:"",apiPort:h,appPort:h,lang:f,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:c},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window<"u"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window<"u"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}}attributeChangedCallback(t,e,n){e!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console>"u"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift("[vitraun-vto]"),console.log.apply(console,t)}}_readAttributes(){var t=k(this,"simulation-inline-config"),e=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(e=t.features.showProductPrice);var n=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(n=t.features.useSimplePage);var o="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(o=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var a="";try{a=C(s(this,"env",""))}catch{a=""}var r=parseInt(s(this,"init-timeout-ms",String(c)),10);(!Number.isFinite(r)||r<0)&&(r=c),this._state={merchantId:s(this,"merchant-id",""),env:a,apiPort:y(s(this,"api-port",String(h)),h),appPort:y(s(this,"app-port",String(h)),h),lang:s(this,"lang",f),isolatedSku:s(this,"isolated-sku",null)||null,applySkus:S(s(this,"apply-skus","")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:s(this,"flow",o),basketOpensIn:s(this,"basket-opens-in","event"),checkoutOpensIn:s(this,"checkout-opens-in","event"),useSimplePage:d(s(this,"use-simple-page",""),n),showDetails:d(s(this,"show-details",""),l),showProductPrice:d(s(this,"show-product-price",""),e),priceFrom:m(s(this,"price-from",null)),priceTo:m(s(this,"price-to",null)),currencySymbol:s(this,"currency-symbol",null)||null,isSimulationMode:d(s(this,"is-simulation-mode","false"),!1),simulationInlineConfig:t,appId:s(this,"app-id",null)||null,platform:O(s(this,"platform",null)),bundleId:s(this,"bundle-id",null)||null,packageName:s(this,"package-name",null)||null,appVersion:s(this,"app-version",null)||null,attestationToken:s(this,"attestation-token",null)||null,debug:d(s(this,"debug","false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:r}}_emit(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e??null,bubbles:!0,composed:!0}))}_setStatus(t,e){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:e||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var e=t.data;if(!(!e||typeof e!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var o=e.type,l=e.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",l);return}var a=["addToCart","removeFromCart","redirectToCart","analysisFinished"];a.indexOf(o)!==-1&&this._emit(o,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildResolvedUrls(){if(!this._state.env)throw new Error("The env attribute is required.");var t=E(this._state.env,this._state.lang,this._state.isSimulationMode,this._state.appPort);return{initUrl:U(this._state.env,this._state.apiPort),iframeUrl:t,iframeOrigin:P(t)}}_buildInitPayload(){var t=I();return{merchantId:this._state.merchantId,tryonSessionId:t,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,inlineVirtualTryonConfig:this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"?this._state.simulationInlineConfig:null,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},context:{hostPageOrigin:_(),hostPageUrl:g(),userAgent:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document<"u"&&document.referrer?document.referrer:null,timezone:typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}_normalizeInitResponse(t,e,n){if(!t||typeof t!="object")throw new Error("Invalid init response.");var o=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!o)throw new Error("The init API did not return sessionToken.");return{sessionToken:o,tryonSessionId:l,initUrl:e.initUrl,iframeUrl:e.iframeUrl,iframeOrigin:e.iframeOrigin}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error("The merchant-id attribute is required."));if(!this._state.env)return Promise.reject(new Error("The env attribute is required."));var e=this._getInitStateKey();if(this._initPromise&&this._initStateKey===e)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}this._initStateKey=e,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildResolvedUrls()}catch(r){return Promise.reject(r)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController<"u"?new AbortController:null;var a=fetch(o.initUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:this._abortController?this._abortController.signal:void 0}).then(function(r){return r.ok?r.json():r.text().then(function(u){var v=T(u),N=v&&v.message||u||"Failed to initialize session ("+r.status+").";throw new Error(N)})}).then(function(r){return t._normalizeInitResponse(r,o,l.tryonSessionId)});return this._initPromise=x(a,this._state.initTimeoutMs,"Timed out while initializing the Vitraun session.",this._abortController).then(function(r){return n!==t._activeInitRequestId||(t._state.sessionToken=r.sessionToken,t._state.tryonSessionId=r.tryonSessionId,t._state.resolvedInitUrl=r.initUrl,t._state.resolvedIframeUrl=r.iframeUrl,t._state.iframeOrigin=r.iframeOrigin,t._setStatus("ready")),r}).catch(function(r){throw n!==t._activeInitRequestId||(t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:r&&r.message?r.message:"Initialization failed."})),r}).finally(function(){n===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var e=this._state.iframeOrigin;if(!e){this._log("Config not sent: iframeOrigin is missing.");return}var n={merchantId:this._state.merchantId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||I(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},hostPageOrigin:_(),hostPageUrl:g()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:b,payload:n},e)}}_renderLoading(){if(this.shadowRoot){var t=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var e=document.createElement("style");e.textContent=":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-loading {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var n=document.createElement("div");n.className="vitraun-loading",n.textContent="Loading Vitraun...",this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var e=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }.vitraun-error {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var o=document.createElement("div");o.className="vitraun-error",o.textContent=t||"Failed to load Vitraun.",this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(o)}}_renderIframe(t,e){if(this.shadowRoot){var n=this,o=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=":host { display:block; width:100%; min-height:"+o+"; box-sizing:border-box; }";var a=document.createElement("iframe");a.src=t,a.title="Vitraun VTO",a.style.cssText="width:100%;height:100%;border:0;min-height:"+o,a.setAttribute("allow","camera"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.onload=function(){e===n._renderVersion&&[0,50,150,400,1e3].forEach(function(r){setTimeout(function(){e===n._renderVersion&&n._sendConfigToIframe()},r)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(a)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:"The merchant-id attribute is required."}),this._renderError("The merchant-id attribute is required.");return}if(!this._state.env){this._setStatus("error",{message:"The env attribute is required."}),this._renderError("The env attribute is required.");return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(e){t===this._renderVersion&&this._renderIframe(e.iframeUrl,t)}.bind(this)).catch(function(e){t===this._renderVersion&&this._renderError(e&&e.message?e.message:"Failed to load Vitraun.")}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements<"u"&&!customElements.get("vitraun-vto")&&customElements.define("vitraun-vto",R)})();
|
package/dist/widget.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var v="VITRAUN_CONFIG",f="vtrn-vto-session",I=18e5,d=1e4,c="en-US";function r(n,t,e){var i=n.getAttribute(t);return i!=null&&i!==""?i:e}function h(n,t){if(n==null||n==="")return t;var e=String(n).toLowerCase();return e==="true"||e==="1"||e==="yes"}function m(n){if(n==null||n==="")return null;var t=parseFloat(String(n));return Number.isFinite(t)?t:null}function b(n){return!n||typeof n!="string"?[]:n.split(",").map(function(t){return t.trim()}).filter(Boolean)}function w(n,t){var e=r(n,t,"");if(!e||typeof e!="string")return null;try{return JSON.parse(e)}catch(i){return null}}function S(n){try{return JSON.parse(n)}catch(t){return null}}function p(){return typeof window=="undefined"||!window.location||!window.location.origin?null:window.location.origin}function _(){return typeof window=="undefined"||!window.location||!window.location.href?null:window.location.href}function k(n){if(!n||typeof n!="string")return null;try{return new URL(n).origin}catch(t){return null}}function T(n){var t=String(n||"").trim().toLowerCase();if(!t)throw new Error("The env attribute is required.");if(!/^[a-z0-9-]+$/.test(t))throw new Error("The env attribute contains an invalid value.");return t}function P(n){return n?String(n).trim().toLowerCase():"web"}function C(n){return"https://api."+n+".vitraun.com/v1/tryon/init"}function O(n,t,e){var i=t||c,o="https://app."+n+".vitraun.com/"+encodeURIComponent(i)+"/virtual-tryon";return e&&(o+="?simulation=1"),o}function U(n,t,e,i){return!t||t<=0?n:new Promise(function(o,l){var a=!1,s=setTimeout(function(){if(!a){a=!0;try{i&&typeof i.abort=="function"&&i.abort()}catch(u){}l(new Error(e||"The operation timed out."))}},t);n.then(function(u){a||(a=!0,clearTimeout(s),o(u))}).catch(function(u){a||(a=!0,clearTimeout(s),l(u))})})}function g(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return"00000000-0000-4000-8000-000000000000";try{var n=sessionStorage.getItem(f);if(n){var t=JSON.parse(n);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch(o){}var e=window.crypto.randomUUID(),i=Date.now()+I;try{sessionStorage.setItem(f,JSON.stringify({id:e,exp:i}))}catch(o){}return e}class E extends HTMLElement{static get observedAttributes(){return["merchant-id","env","lang","isolated-sku","apply-skus","flow","basket-opens-in","checkout-opens-in","use-simple-page","show-details","show-product-price","price-from","price-to","currency-symbol","is-simulation-mode","simulation-inline-config","container-min-height","app-id","platform","bundle-id","package-name","app-version","attestation-token","debug","init-timeout-ms"]}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",env:"",lang:c,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:d},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window!="undefined"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window!="undefined"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(t){}}attributeChangedCallback(t,e,i){e!==i&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console=="undefined"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift("[vitraun-vto]"),console.log.apply(console,t)}}_readAttributes(){var t=w(this,"simulation-inline-config"),e=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(e=t.features.showProductPrice);var i=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(i=t.features.useSimplePage);var o="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(o=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var a="";try{a=T(r(this,"env",""))}catch(u){a=""}var s=parseInt(r(this,"init-timeout-ms",String(d)),10);(!Number.isFinite(s)||s<0)&&(s=d),this._state={merchantId:r(this,"merchant-id",""),env:a,lang:r(this,"lang",c),isolatedSku:r(this,"isolated-sku",null)||null,applySkus:b(r(this,"apply-skus","")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:r(this,"flow",o),basketOpensIn:r(this,"basket-opens-in","event"),checkoutOpensIn:r(this,"checkout-opens-in","event"),useSimplePage:h(r(this,"use-simple-page",""),i),showDetails:h(r(this,"show-details",""),l),showProductPrice:h(r(this,"show-product-price",""),e),priceFrom:m(r(this,"price-from",null)),priceTo:m(r(this,"price-to",null)),currencySymbol:r(this,"currency-symbol",null)||null,isSimulationMode:h(r(this,"is-simulation-mode","false"),!1),simulationInlineConfig:t,appId:r(this,"app-id",null)||null,platform:P(r(this,"platform",null)),bundleId:r(this,"bundle-id",null)||null,packageName:r(this,"package-name",null)||null,appVersion:r(this,"app-version",null)||null,attestationToken:r(this,"attestation-token",null)||null,debug:h(r(this,"debug","false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:s}}_emit(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e!=null?e:null,bubbles:!0,composed:!0}))}_setStatus(t,e){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:e||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var e=t.data;if(!(!e||typeof e!="object")){var i=this._getIframeElement();if(!(!i||!i.contentWindow)&&t.source===i.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var o=e.type,l=e.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",l);return}var a=["addToCart","removeFromCart","redirectToCart","analysisFinished"];a.indexOf(o)!==-1&&this._emit(o,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,env:this._state.env,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildResolvedUrls(){if(!this._state.env)throw new Error("The env attribute is required.");var t=O(this._state.env,this._state.lang,this._state.isSimulationMode);return{initUrl:C(this._state.env),iframeUrl:t,iframeOrigin:k(t)}}_buildInitPayload(){var t=g();return{merchantId:this._state.merchantId,tryonSessionId:t,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,inlineVirtualTryonConfig:this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"?this._state.simulationInlineConfig:null,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},context:{hostPageOrigin:p(),hostPageUrl:_(),userAgent:typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document!="undefined"&&document.referrer?document.referrer:null,timezone:typeof Intl!="undefined"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}_normalizeInitResponse(t,e,i){if(!t||typeof t!="object")throw new Error("Invalid init response.");var o=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:i;if(!o)throw new Error("The init API did not return sessionToken.");return{sessionToken:o,tryonSessionId:l,initUrl:e.initUrl,iframeUrl:e.iframeUrl,iframeOrigin:e.iframeOrigin}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error("The merchant-id attribute is required."));if(!this._state.env)return Promise.reject(new Error("The env attribute is required."));var e=this._getInitStateKey();if(this._initPromise&&this._initStateKey===e)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(s){}this._initStateKey=e,this._activeInitRequestId+=1;var i=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildResolvedUrls()}catch(s){return Promise.reject(s)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController!="undefined"?new AbortController:null;var a=fetch(o.initUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:this._abortController?this._abortController.signal:void 0}).then(function(s){return s.ok?s.json():s.text().then(function(u){var y=S(u),x=y&&y.message||u||"Failed to initialize session ("+s.status+").";throw new Error(x)})}).then(function(s){return t._normalizeInitResponse(s,o,l.tryonSessionId)});return this._initPromise=U(a,this._state.initTimeoutMs,"Timed out while initializing the Vitraun session.",this._abortController).then(function(s){return i!==t._activeInitRequestId||(t._state.sessionToken=s.sessionToken,t._state.tryonSessionId=s.tryonSessionId,t._state.resolvedInitUrl=s.initUrl,t._state.resolvedIframeUrl=s.iframeUrl,t._state.iframeOrigin=s.iframeOrigin,t._setStatus("ready")),s}).catch(function(s){throw i!==t._activeInitRequestId||(t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:s&&s.message?s.message:"Initialization failed."})),s}).finally(function(){i===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var e=this._state.iframeOrigin;if(!e){this._log("Config not sent: iframeOrigin is missing.");return}var i={merchantId:this._state.merchantId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||g(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},hostPageOrigin:p(),hostPageUrl:_()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(i.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:v,payload:i},e)}}_renderLoading(){if(this.shadowRoot){var t=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var e=document.createElement("style");e.textContent=":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-loading {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var i=document.createElement("div");i.className="vitraun-loading",i.textContent="Loading Vitraun...",this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(i)}}_renderError(t){if(this.shadowRoot){var e=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var i=document.createElement("style");i.textContent=":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }.vitraun-error {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var o=document.createElement("div");o.className="vitraun-error",o.textContent=t||"Failed to load Vitraun.",this.shadowRoot.appendChild(i),this.shadowRoot.appendChild(o)}}_renderIframe(t,e){if(this.shadowRoot){var i=this,o=r(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=":host { display:block; width:100%; min-height:"+o+"; box-sizing:border-box; }";var a=document.createElement("iframe");a.src=t,a.title="Vitraun VTO",a.style.cssText="width:100%;height:100%;border:0;min-height:"+o,a.setAttribute("allow","camera"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.onload=function(){e===i._renderVersion&&[0,50,150,400,1e3].forEach(function(s){setTimeout(function(){e===i._renderVersion&&i._sendConfigToIframe()},s)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(a)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:"The merchant-id attribute is required."}),this._renderError("The merchant-id attribute is required.");return}if(!this._state.env){this._setStatus("error",{message:"The env attribute is required."}),this._renderError("The env attribute is required.");return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(e){t===this._renderVersion&&this._renderIframe(e.iframeUrl,t)}.bind(this)).catch(function(e){t===this._renderVersion&&this._renderError(e&&e.message?e.message:"Failed to load Vitraun.")}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements!="undefined"&&!customElements.get("vitraun-vto")&&customElements.define("vitraun-vto",E)})();})();
|
|
1
|
+
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var b="VITRAUN_CONFIG",p="vtrn-vto-session",w=18e5,c=1e4,f="en-US",h=80;function s(i,t,e){var n=i.getAttribute(t);return n!=null&&n!==""?n:e}function d(i,t){if(i==null||i==="")return t;var e=String(i).toLowerCase();return e==="true"||e==="1"||e==="yes"}function m(i){if(i==null||i==="")return null;var t=parseFloat(String(i));return Number.isFinite(t)?t:null}function S(i){return!i||typeof i!="string"?[]:i.split(",").map(function(t){return t.trim()}).filter(Boolean)}function k(i,t){var e=s(i,t,"");if(!e||typeof e!="string")return null;try{return JSON.parse(e)}catch(n){return null}}function T(i){try{return JSON.parse(i)}catch(t){return null}}function _(){return typeof window=="undefined"||!window.location||!window.location.origin?null:window.location.origin}function g(){return typeof window=="undefined"||!window.location||!window.location.href?null:window.location.href}function P(i){if(!i||typeof i!="string")return null;try{return new URL(i).origin}catch(t){return null}}function C(i){var t=String(i||"").trim().toLowerCase();if(!t)throw new Error("The env attribute is required.");if(!/^[a-z0-9-]+$/.test(t))throw new Error("The env attribute contains an invalid value.");return t}function O(i){return i?String(i).trim().toLowerCase():"web"}function y(i,t){if(i==null||i==="")return t;var e=parseInt(String(i),10);return!Number.isInteger(e)||e<=0||e>65535?t:e}function U(i,t){return"https://app."+i+".vitraun.com:"+t+"/v1/tryon/init"}function E(i,t,e,n){var o=t||f,l="https://app."+i+".vitraun.com:"+n+"/"+encodeURIComponent(o)+"/virtual-tryon";return e&&(l+="?simulation=1"),l}function x(i,t,e,n){return!t||t<=0?i:new Promise(function(o,l){var a=!1,r=setTimeout(function(){if(!a){a=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch(u){}l(new Error(e||"The operation timed out."))}},t);i.then(function(u){a||(a=!0,clearTimeout(r),o(u))}).catch(function(u){a||(a=!0,clearTimeout(r),l(u))})})}function I(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return"00000000-0000-4000-8000-000000000000";try{var i=sessionStorage.getItem(p);if(i){var t=JSON.parse(i);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch(o){}var e=window.crypto.randomUUID(),n=Date.now()+w;try{sessionStorage.setItem(p,JSON.stringify({id:e,exp:n}))}catch(o){}return e}class R extends HTMLElement{static get observedAttributes(){return["merchant-id","env","api-port","app-port","lang","isolated-sku","apply-skus","flow","basket-opens-in","checkout-opens-in","use-simple-page","show-details","show-product-price","price-from","price-to","currency-symbol","is-simulation-mode","simulation-inline-config","container-min-height","app-id","platform","bundle-id","package-name","app-version","attestation-token","debug","init-timeout-ms"]}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",env:"",apiPort:h,appPort:h,lang:f,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:c},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window!="undefined"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window!="undefined"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(t){}}attributeChangedCallback(t,e,n){e!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console=="undefined"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift("[vitraun-vto]"),console.log.apply(console,t)}}_readAttributes(){var t=k(this,"simulation-inline-config"),e=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(e=t.features.showProductPrice);var n=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(n=t.features.useSimplePage);var o="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(o=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var a="";try{a=C(s(this,"env",""))}catch(u){a=""}var r=parseInt(s(this,"init-timeout-ms",String(c)),10);(!Number.isFinite(r)||r<0)&&(r=c),this._state={merchantId:s(this,"merchant-id",""),env:a,apiPort:y(s(this,"api-port",String(h)),h),appPort:y(s(this,"app-port",String(h)),h),lang:s(this,"lang",f),isolatedSku:s(this,"isolated-sku",null)||null,applySkus:S(s(this,"apply-skus","")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:s(this,"flow",o),basketOpensIn:s(this,"basket-opens-in","event"),checkoutOpensIn:s(this,"checkout-opens-in","event"),useSimplePage:d(s(this,"use-simple-page",""),n),showDetails:d(s(this,"show-details",""),l),showProductPrice:d(s(this,"show-product-price",""),e),priceFrom:m(s(this,"price-from",null)),priceTo:m(s(this,"price-to",null)),currencySymbol:s(this,"currency-symbol",null)||null,isSimulationMode:d(s(this,"is-simulation-mode","false"),!1),simulationInlineConfig:t,appId:s(this,"app-id",null)||null,platform:O(s(this,"platform",null)),bundleId:s(this,"bundle-id",null)||null,packageName:s(this,"package-name",null)||null,appVersion:s(this,"app-version",null)||null,attestationToken:s(this,"attestation-token",null)||null,debug:d(s(this,"debug","false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:r}}_emit(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e!=null?e:null,bubbles:!0,composed:!0}))}_setStatus(t,e){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:e||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var e=t.data;if(!(!e||typeof e!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var o=e.type,l=e.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",l);return}var a=["addToCart","removeFromCart","redirectToCart","analysisFinished"];a.indexOf(o)!==-1&&this._emit(o,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildResolvedUrls(){if(!this._state.env)throw new Error("The env attribute is required.");var t=E(this._state.env,this._state.lang,this._state.isSimulationMode,this._state.appPort);return{initUrl:U(this._state.env,this._state.apiPort),iframeUrl:t,iframeOrigin:P(t)}}_buildInitPayload(){var t=I();return{merchantId:this._state.merchantId,tryonSessionId:t,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,inlineVirtualTryonConfig:this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"?this._state.simulationInlineConfig:null,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},context:{hostPageOrigin:_(),hostPageUrl:g(),userAgent:typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document!="undefined"&&document.referrer?document.referrer:null,timezone:typeof Intl!="undefined"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}_normalizeInitResponse(t,e,n){if(!t||typeof t!="object")throw new Error("Invalid init response.");var o=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!o)throw new Error("The init API did not return sessionToken.");return{sessionToken:o,tryonSessionId:l,initUrl:e.initUrl,iframeUrl:e.iframeUrl,iframeOrigin:e.iframeOrigin}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error("The merchant-id attribute is required."));if(!this._state.env)return Promise.reject(new Error("The env attribute is required."));var e=this._getInitStateKey();if(this._initPromise&&this._initStateKey===e)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(r){}this._initStateKey=e,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildResolvedUrls()}catch(r){return Promise.reject(r)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController!="undefined"?new AbortController:null;var a=fetch(o.initUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:this._abortController?this._abortController.signal:void 0}).then(function(r){return r.ok?r.json():r.text().then(function(u){var v=T(u),N=v&&v.message||u||"Failed to initialize session ("+r.status+").";throw new Error(N)})}).then(function(r){return t._normalizeInitResponse(r,o,l.tryonSessionId)});return this._initPromise=x(a,this._state.initTimeoutMs,"Timed out while initializing the Vitraun session.",this._abortController).then(function(r){return n!==t._activeInitRequestId||(t._state.sessionToken=r.sessionToken,t._state.tryonSessionId=r.tryonSessionId,t._state.resolvedInitUrl=r.initUrl,t._state.resolvedIframeUrl=r.iframeUrl,t._state.iframeOrigin=r.iframeOrigin,t._setStatus("ready")),r}).catch(function(r){throw n!==t._activeInitRequestId||(t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:r&&r.message?r.message:"Initialization failed."})),r}).finally(function(){n===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var e=this._state.iframeOrigin;if(!e){this._log("Config not sent: iframeOrigin is missing.");return}var n={merchantId:this._state.merchantId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||I(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},hostPageOrigin:_(),hostPageUrl:g()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:b,payload:n},e)}}_renderLoading(){if(this.shadowRoot){var t=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var e=document.createElement("style");e.textContent=":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-loading {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var n=document.createElement("div");n.className="vitraun-loading",n.textContent="Loading Vitraun...",this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var e=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }.vitraun-error {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}";var o=document.createElement("div");o.className="vitraun-error",o.textContent=t||"Failed to load Vitraun.",this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(o)}}_renderIframe(t,e){if(this.shadowRoot){var n=this,o=s(this,"container-min-height","80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=":host { display:block; width:100%; min-height:"+o+"; box-sizing:border-box; }";var a=document.createElement("iframe");a.src=t,a.title="Vitraun VTO",a.style.cssText="width:100%;height:100%;border:0;min-height:"+o,a.setAttribute("allow","camera"),a.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),a.onload=function(){e===n._renderVersion&&[0,50,150,400,1e3].forEach(function(r){setTimeout(function(){e===n._renderVersion&&n._sendConfigToIframe()},r)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(a)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:"The merchant-id attribute is required."}),this._renderError("The merchant-id attribute is required.");return}if(!this._state.env){this._setStatus("error",{message:"The env attribute is required."}),this._renderError("The env attribute is required.");return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(e){t===this._renderVersion&&this._renderIframe(e.iframeUrl,t)}.bind(this)).catch(function(e){t===this._renderVersion&&this._renderError(e&&e.message?e.message:"Failed to load Vitraun.")}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements!="undefined"&&!customElements.get("vitraun-vto")&&customElements.define("vitraun-vto",R)})();})();
|
package/package.json
CHANGED
|
@@ -1,22 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vitraun/webar",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Vitraun WebAR widget as Web Component",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.txt",
|
|
6
|
-
"repository": {
|
|
7
|
-
"type": "git",
|
|
8
|
-
"url": "https://github.com/clagils/tryon-new-version.git",
|
|
9
|
-
"directory": "vto-npm/webar"
|
|
10
|
-
},
|
|
11
|
-
"homepage": "https://github.com/clagils/tryon-new-version/tree/main/vto-npm/webar",
|
|
12
|
-
"bugs": {
|
|
13
|
-
"url": "https://github.com/clagils/tryon-new-version/issues"
|
|
14
|
-
},
|
|
15
6
|
"publishConfig": {
|
|
16
7
|
"access": "public"
|
|
17
8
|
},
|
|
18
9
|
"private": false,
|
|
19
10
|
"type": "module",
|
|
11
|
+
"jsdelivr": "dist/widget.min.js",
|
|
20
12
|
"main": "./dist/index.min.js",
|
|
21
13
|
"module": "./dist/index.min.js",
|
|
22
14
|
"types": "./dist/index.d.ts",
|
|
@@ -63,7 +55,7 @@
|
|
|
63
55
|
"@types/node": "^20",
|
|
64
56
|
"@types/react": "^19.2.14",
|
|
65
57
|
"@vitest/coverage-v8": "^3.2.4",
|
|
66
|
-
"@vitraun/core": "0.1.0",
|
|
58
|
+
"@vitraun/core": "^0.1.0",
|
|
67
59
|
"esbuild": "^0.25.9",
|
|
68
60
|
"eslint": "^9.39.1",
|
|
69
61
|
"jsdom": "^26.1.0",
|