shopar-plugin 0.0.7 → 0.0.8-alpha.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 +2 -2
- package/dist/shopar-analytics.js +1 -1
- package/dist/shopar-plugin.esm.js +1 -1
- package/dist/shopar-plugin.js +1 -1
- package/dist/shopar-three.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ There are two distinct ways of integrating the plugin: via Script tag and via NP
|
|
|
32
32
|
Add the following script to your HTML.
|
|
33
33
|
|
|
34
34
|
```html
|
|
35
|
-
<script src="https://cdn.jsdelivr.net/npm/shopar-plugin@
|
|
35
|
+
<script src="https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist/shopar-plugin.js"></script>
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
It is possible to use a different CDN instead of [jsDelivr](https://www.jsdelivr.com/) (e.g. [cdnjs](https://cdnjs.com/), [unpkg](https://www.unpkg.com/)), or even a relative path if the plugin is distributed as a static asset to your app. Just make sure to set the `baseUrl` parameter accordingly (see [setup options](#shoparpluginsetupoptions) for more details).
|
|
@@ -143,7 +143,7 @@ Options used for the plugin setup:
|
|
|
143
143
|
- `baseUrl` (optional)
|
|
144
144
|
- Type: `string`
|
|
145
145
|
- If provided, defines where the additional ShopAR plugin files are fetched from.
|
|
146
|
-
- Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@
|
|
146
|
+
- Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist`
|
|
147
147
|
- `strings` (optional)
|
|
148
148
|
- Type: `object`
|
|
149
149
|
- If provided, overrides strings in the UI.
|
package/dist/shopar-analytics.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,(function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){return Number.isInteger(t)&&t>=0}function n(t){this.name="ArgumentError",this.message=t}var s=e((function(t,e){if(e=e||{},"function"!=typeof t)throw new n("fetch must be a function");if("object"!=typeof e)throw new n("defaults must be an object");if(void 0!==e.retries&&!i(e.retries))throw new n("retries must be a positive integer");if(void 0!==e.retryDelay&&!i(e.retryDelay)&&"function"!=typeof e.retryDelay)throw new n("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==e.retryOn&&!Array.isArray(e.retryOn)&&"function"!=typeof e.retryOn)throw new n("retryOn property expects an array or function");return e=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},e),function(s,r){var a=e.retries,o=e.retryDelay,c=e.retryOn;if(r&&void 0!==r.retries){if(!i(r.retries))throw new n("retries must be a positive integer");a=r.retries}if(r&&void 0!==r.retryDelay){if(!i(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new n("retryDelay must be a positive integer or a function returning a positive integer");o=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new n("retryOn property expects an array or function");c=r.retryOn}return new Promise((function(e,i){var n=function(n){var o="undefined"!=typeof Request&&s instanceof Request?s.clone():s;t(o,r).then((function(t){if(Array.isArray(c)&&-1===c.indexOf(t.status))e(t);else if("function"==typeof c)try{return Promise.resolve(c(n,null,t)).then((function(i){i?u(n,null,t):e(t)})).catch(i)}catch(t){i(t)}else n<a?u(n,null,t):e(t)})).catch((function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then((function(e){e?u(n,t,null):i(t)})).catch((function(t){i(t)}))}catch(t){i(t)}else n<a?u(n,t,null):i(t)}))};function u(t,e,i){var s="function"==typeof o?o(t,e,i):o;setTimeout((function(){n(++t)}),s)}n(0)}))}}));var r,a;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(a||(a={}));class o{scope;type;value;remaining;reset;constructor(t=r.unknown,e=a.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){let a=new o;const c=t.headers.get(e.toLowerCase())||r.unknown;a.scope=r[c];const u=t.headers.get(i.toLowerCase())||"",h=parseInt(u,10);isNaN(h)||(a.value=h);const l=t.headers.get(n.toLowerCase())||"",f=parseInt(l,10);isNaN(f)||(a.remaining=f);const m=t.headers.get(s.toLowerCase())||"",y=parseInt(m,10);return isNaN(y)||(a.reset=new Date(1e3*y)),a}class u{config;constructor(t){this.config=t}async doReq(t,e,i={},n={}){let r=`${this.config.baseUrl}${t}`;const o=this._prepareSearchParams(n);o&&(r+=`?${o.toString()}`);const u={...this.config.headers,...i.headers},l=await s(fetch)(r,{retries:3,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:u,method:e,body:i.body?i.body:void 0});if(204===l.status)return l;if(429==l.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=a.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=a.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=a.api),e}(l);return Promise.reject(new h(t))}if(401===l.status)return Promise.reject(new Error("Forbidden"));if(l.status>=400){const t=await l.json();return Promise.reject(new Error(t.message))}return await l.json()}post(t,e={},i={}){return this.doReq(t,"POST",e,i)}get(t,e={},i={}){return this.doReq(t,"GET",e,i)}put(t,e={},i={}){return this.doReq(t,"PUT",e,i)}delete(t,e={},i={}){return this.doReq(t,"DELETE",e,i)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach((n=>{t[n]&&(e.append(n,t[n]),i=!0)})),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==a.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}class l{client;constructor({orgId:t="",token:e,url:i}){e||console.warn("Missing Axiom token");const n=i??"https://api.axiom.co",s={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(s["User-Agent"]="axiom-js/1.0.0-rc.1"),t&&(s["X-Axiom-Org-Id"]=t),this.client=new u({baseUrl:n,headers:s,timeout:3e3})}}var f,m,y,p,d,g;!function(t){t.TimestampField="_time";t.Service=class extends l{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(f||(f={})),function(t){t.Service=class extends l{current=()=>this.client.get("/v1/user")}}(m||(m={}));class w{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout((()=>{}),0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout((()=>{this.activeFlush=this.flush()}),1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);const e=await this.ingestFn(this.id,t,this.options);return this.lastFlush=new Date,e}}class v extends l{datasets;users;localPath="/v1";constructor(t){super(t),this.datasets=new f.Service(t),this.users=new m.Service(t)}ingestRaw=(t,e,i=y.JSON,n=p.Identity,s)=>this.client.post(this.localPath+"/datasets/"+t+"/ingest",{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter});queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache});query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:"legacy"})};aplQuery=(t,e)=>this.query(t,e)}class
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,(function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){return Number.isInteger(t)&&t>=0}function n(t){this.name="ArgumentError",this.message=t}var s=e((function(t,e){if(e=e||{},"function"!=typeof t)throw new n("fetch must be a function");if("object"!=typeof e)throw new n("defaults must be an object");if(void 0!==e.retries&&!i(e.retries))throw new n("retries must be a positive integer");if(void 0!==e.retryDelay&&!i(e.retryDelay)&&"function"!=typeof e.retryDelay)throw new n("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==e.retryOn&&!Array.isArray(e.retryOn)&&"function"!=typeof e.retryOn)throw new n("retryOn property expects an array or function");return e=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},e),function(s,r){var a=e.retries,o=e.retryDelay,c=e.retryOn;if(r&&void 0!==r.retries){if(!i(r.retries))throw new n("retries must be a positive integer");a=r.retries}if(r&&void 0!==r.retryDelay){if(!i(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new n("retryDelay must be a positive integer or a function returning a positive integer");o=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new n("retryOn property expects an array or function");c=r.retryOn}return new Promise((function(e,i){var n=function(n){var o="undefined"!=typeof Request&&s instanceof Request?s.clone():s;t(o,r).then((function(t){if(Array.isArray(c)&&-1===c.indexOf(t.status))e(t);else if("function"==typeof c)try{return Promise.resolve(c(n,null,t)).then((function(i){i?u(n,null,t):e(t)})).catch(i)}catch(t){i(t)}else n<a?u(n,null,t):e(t)})).catch((function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then((function(e){e?u(n,t,null):i(t)})).catch((function(t){i(t)}))}catch(t){i(t)}else n<a?u(n,t,null):i(t)}))};function u(t,e,i){var s="function"==typeof o?o(t,e,i):o;setTimeout((function(){n(++t)}),s)}n(0)}))}}));var r,a;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(a||(a={}));class o{scope;type;value;remaining;reset;constructor(t=r.unknown,e=a.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){let a=new o;const c=t.headers.get(e.toLowerCase())||r.unknown;a.scope=r[c];const u=t.headers.get(i.toLowerCase())||"",h=parseInt(u,10);isNaN(h)||(a.value=h);const l=t.headers.get(n.toLowerCase())||"",f=parseInt(l,10);isNaN(f)||(a.remaining=f);const m=t.headers.get(s.toLowerCase())||"",y=parseInt(m,10);return isNaN(y)||(a.reset=new Date(1e3*y)),a}class u{config;constructor(t){this.config=t}async doReq(t,e,i={},n={}){let r=`${this.config.baseUrl}${t}`;const o=this._prepareSearchParams(n);o&&(r+=`?${o.toString()}`);const u={...this.config.headers,...i.headers},l=await s(fetch)(r,{retries:3,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:u,method:e,body:i.body?i.body:void 0});if(204===l.status)return l;if(429==l.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=a.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=a.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=a.api),e}(l);return Promise.reject(new h(t))}if(401===l.status)return Promise.reject(new Error("Forbidden"));if(l.status>=400){const t=await l.json();return Promise.reject(new Error(t.message))}return await l.json()}post(t,e={},i={}){return this.doReq(t,"POST",e,i)}get(t,e={},i={}){return this.doReq(t,"GET",e,i)}put(t,e={},i={}){return this.doReq(t,"PUT",e,i)}delete(t,e={},i={}){return this.doReq(t,"DELETE",e,i)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach((n=>{t[n]&&(e.append(n,t[n]),i=!0)})),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==a.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}class l{client;constructor({orgId:t="",token:e,url:i}){e||console.warn("Missing Axiom token");const n=i??"https://api.axiom.co",s={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(s["User-Agent"]="axiom-js/1.0.0-rc.1"),t&&(s["X-Axiom-Org-Id"]=t),this.client=new u({baseUrl:n,headers:s,timeout:3e3})}}var f,m,y,p,d,g;!function(t){t.TimestampField="_time";t.Service=class extends l{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(f||(f={})),function(t){t.Service=class extends l{current=()=>this.client.get("/v1/user")}}(m||(m={}));class w{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout((()=>{}),0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout((()=>{this.activeFlush=this.flush()}),1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);const e=await this.ingestFn(this.id,t,this.options);return this.lastFlush=new Date,e}}class v extends l{datasets;users;localPath="/v1";constructor(t){super(t),this.datasets=new f.Service(t),this.users=new m.Service(t)}ingestRaw=(t,e,i=y.JSON,n=p.Identity,s)=>this.client.post(this.localPath+"/datasets/"+t+"/ingest",{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter});queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache});query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:"legacy"})};aplQuery=(t,e)=>this.query(t,e)}class b extends v{batch={};ingest=(t,e,i)=>{const n=function(t,e){return`${t}:${e?.timestampField||"-"}:${e?.timestampFormat||"-"}:${e?.csvDelimiter||"-"}`}(t,i);return this.batch[n]||(this.batch[n]=new w(((t,e,i)=>{const n=(Array.isArray(e)?e:[e]).map((t=>JSON.stringify(t))).join("\n");return this.ingestRaw(t,n,y.NDJSON,p.Identity,i)}),t,i)),this.batch[n].ingest(e)};flush=async()=>{let t=[];for(const e in this.batch)t.push(this.batch[e].flush());await Promise.all(t)}}let x;!function(t){t.JSON="application/json",t.NDJSON="application/x-ndjson",t.CSV="text/csv"}(y||(y={})),function(t){t.Identity="",t.GZIP="gzip"}(p||(p={})),function(t){t.Count="count",t.Distinct="distinct",t.Sum="sum",t.Avg="avg",t.Min="min",t.Max="max",t.Topk="topk",t.Percentiles="percentiles",t.Histogram="histogram",t.Variance="variance",t.Stdev="stdev",t.ArgMin="argmin",t.ArgMax="argmax",t.MakeSet="makeset",t.MakeSetIf="makesetif",t.CountIf="countif",t.CountDistinctIf="distinctif"}(d||(d={})),function(t){t.And="and",t.Or="or",t.Not="not",t.Equal="==",t.NotEqual="!=",t.Exists="exists",t.NotExists="not-exists",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.LessThan="<",t.LessThanOrEqualTo="<=",t.Gt="gt",t.Gte="gte",t.Lt="lt",t.Lte="lte",t.StartsWith="starts-with",t.NotStartsWith="not-starts-with",t.EndsWith="ends-with",t.NotEndsWith="not-ends-with",t.Contains="contains",t.NotContains="not-contains",t.Regexp="regexp",t.NotRegexp="not-regexp"}(g||(g={})),t.initializeImpl=function(){x=new b({token:"xaat-16d05fdd-4ab9-4990-acba-7cee24974bfb"})},t.trackEventImpl=function(t,e){x.ingest("shopar-plugin-alpha",Object.assign({name:t},e))}}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,n,t,o){return new(t||(t=Promise))((function(r,i){function a(e){try{l(o.next(e))}catch(e){i(e)}}function s(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var n;e.done?r(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,s)}l((o=o.apply(e,n||[])).next())}))}!function(){const e={css:".shopar-btn-container{position:absolute;width:100%;bottom:0;padding-bottom:2rem;display:flex;justify-content:center;gap:.5rem;pointer-events:none}.shopar-btn{padding:.5rem .75rem;display:flex;justify-content:center;align-items:center;gap:.25rem;background-color:#fff;border:1px solid #ddd;border-radius:9999px;cursor:pointer;pointer-events:auto}.shopar-btn:hover{background-color:#f5f5f5}.shopar-loading-container{display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1rem;background-color:#fff}.shopar-loading-text{text-align:center}.shopar-loading-bar-bg{width:80%;height:.5rem;background-color:#e5e7eb;border-radius:9999px}.shopar-loading-bar-fg{background-color:#1434f7;border-radius:9999px;transition:none;transform:translateX(-100%);will-change:transform}.shopar-loading-bar-fg.active{transition:transform 5s cubic-bezier(0,0,.2,1);transform:none}.shopar-qr{display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:#fff}"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}(),"function"==typeof SuppressedError&&SuppressedError;class n extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}const t=[Uint8Array,Uint32Array],o=t.length-2,r=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],i=[2,12,7,1],a=window[r[i[i[o]]]][r[i[i[i.length-1]]]],s=a.charCodeAt(o),l=s^s,c=new t[1]([l]);function d(){const e=(new TextEncoder).encode(a),n=r.map((e=>e.length));for(let t=0;t<e.length;t++)e[t]^=n[t%n.length];return window[r[n[2]]](String.fromCodePoint(...e))}const u=[1e3,2e3,4e3],h=u.length;function p(n,t=0){return e(this,void 0,void 0,(function*(){try{return yield n()}catch(e){if(t>=h)throw e;return yield new Promise((e=>setTimeout(e,u[t]))),p(n,t+1)}}))}const f=["Glasses","Shoes","Watches"],m=["Shoes"];let v;const g=new Uint8Array(16);function w(){if(!v&&(v="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!v))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return v(g)}const y=[];for(let e=0;e<256;++e)y.push((e+256).toString(16).slice(1));var b={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function E(e,n,t){if(b.randomUUID&&!n&&!e)return b.randomUUID();const o=(e=e||{}).random||(e.rng||w)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,n){t=t||0;for(let e=0;e<16;++e)n[t+e]=o[e];return n}return function(e,n=0){return y[e[n+0]]+y[e[n+1]]+y[e[n+2]]+y[e[n+3]]+"-"+y[e[n+4]]+y[e[n+5]]+"-"+y[e[n+6]]+y[e[n+7]]+"-"+y[e[n+8]]+y[e[n+9]]+"-"+y[e[n+10]]+y[e[n+11]]+y[e[n+12]]+y[e[n+13]]+y[e[n+14]]+y[e[n+15]]}(o)}const C="0.0.7";let S=`https://cdn.jsdelivr.net/npm/shopar-plugin@${C}/dist`;const R={update:e=>{null!=e&&(S=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>S};function A(n){return e(this,void 0,void 0,(function*(){if("function"!=typeof importScripts){const e=document.createElement("script");return e.setAttribute("src",n),e.setAttribute("crossorigin","anonymous"),new Promise((n=>{e.addEventListener("load",(()=>n()),!1),e.addEventListener("error",(()=>n()),!1),document.body.appendChild(e)}))}importScripts(n.toString())}))}const k="qrLaunch",x="arLaunch",M="previewLaunch",L="heartbeat";let $,D,U=!1;const P=[];function T(e,n){const t=performance.now(),o=E();let r=0,i=0,a=0,s=0,l=0,c=!1;window.setInterval((()=>{c&&(r=i+a,c=!1,d(L,{engagementTotal:r,engagementAR:i,engagement3D:a}))}),1e3);const d=(r,i={})=>{var a;i=Object.assign(Object.assign({},i),{pluginVersion:C,sessionId:D,setupId:o,timeSinceSetup:performance.now()-t,sku:e,apiKey:n}),a=()=>{window.ShopAR__analytics.trackEventImpl(r,i)},U?a():P.push(a)};return{trackEvent:d,arInteracted:()=>{const e=performance.now(),n=e-s;s=e,n<200&&(i+=n,c=!0)},previewInteracted:()=>{const e=performance.now(),n=e-l;l=e,n<200&&(a+=n,c=!0)}}}function I(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}function j(n){return e(this,void 0,void 0,(function*(){const e=document.createElement("video");return e.setAttribute("playsinline","playsinline"),e.srcObject=yield n,e}))}const N=200,O=10;let _,G,F,W,V=!1;function q(t){return e(this,void 0,void 0,(function*(){const o=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(t).catch((e=>{throw console.error(e),new n("Resource unavailable.")}));if(!e.ok)throw new n(`Resource download failed with status ${e.status}.`);return e}))));try{return yield(yield o.blob()).arrayBuffer()}catch(e){throw console.error(e),new n("Resource has invalid body.")}}))}let z,B,H,K,X,Q,Z,Y=!0;function J(e){e!==W&&(W=e,F=q(e),Q=null,null==z||z.clearEffect(),V=!0)}function ee(t,o,r){return e(this,void 0,void 0,(function*(){return H=r,K=t,null==X&&(X=(()=>e(this,void 0,void 0,(function*(){if(null==(null===(i=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new n("No camera available!");var i;const a=re(r),s=I(a),l=function(e){const n={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:n[e]}(r);z=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:o||"your_license_key_goes_here",previewElement:t,additionalOptions:{hint:l,cameraConfig:{disableDefaultCamera:!0}}}),B=yield j(s),yield ie(z,B,"user"===a),"Glasses"===r&&(yield G,function(n,t){e(this,void 0,void 0,(function*(){V=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${R}/wasm/mediapipe`,n);const r=[],i=setInterval((()=>e(this,void 0,void 0,(function*(){if(V)return void clearInterval(i);const{error:e,faceWidth:n}=yield o.predict(performance.now());if(V)return void clearInterval(i);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(r.length<O)return void r.push(n);clearInterval(i);const a=137/(function(e){let n=0;const t=e.length;for(let o=0;o<t;o++)n+=e[o];return n/t}(r)+5);t.changeParameterVector("GLASSES","","scale",a,a,a,0),t.changeParameterVector("shopar_glasses","","scale",a,a,a,0)}))),N)}))}(B,z))})))()),X}))}function ne(e){z.callbacks.onFaceTracked=n=>{n.some((e=>e.detected))&&e()},z.callbacks.onFeetTracked=(n,t)=>{(n.detected||t.detected)&&e()},z.callbacks.onWristTracked=n=>{n.detected&&e()}}function te(n){return e(this,void 0,void 0,(function*(){return null==Q&&(Q=z.switchEffect(n)),Q}))}function oe(){null!=z&&(Y=!0,z.setPaused(Y),null!=B&&null!=B.srcObject&&B.srcObject instanceof MediaStream&&(B.srcObject.getTracks().forEach((e=>e.stop())),B=null),z.stopCamera(),K.style.display="none")}function re(e){var n;return null==e?"user":null!==(n={Glasses:"user",Shoes:"environment",Watches:"environment"}[e])&&void 0!==n?n:"user"}function ie(n,t,o){return e(this,void 0,void 0,(function*(){yield new Promise((r=>{t.onloadedmetadata=()=>{t.play().then((()=>e(this,void 0,void 0,(function*(){n.setVideoElement(t,o),r()}))))}}))}))}const ae={"loading.ar":"Loading Try On...","loading.3d":"Loading 3D..."},se=Object.keys(ae);function le(e){return ae[e]}function ce(e,n){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width",e),t.setAttribute("height",e);{const o=document.createElementNS("http://www.w3.org/2000/svg","image");o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n),o.setAttribute("width",e),o.setAttribute("height",e),t.appendChild(o)}return t}const de="shopar-error";function ue(e,n,t,o){const r=document.createElement("button");r.id=e,r.type="button",r.className="shopar-btn";{const e=ce("1.75rem",o);r.appendChild(e)}{const e=document.createElement("span");e.textContent=n,r.appendChild(e)}r.ariaLabel=t;return r.style.display="none",r}const he="shopar-control";const pe="shopar-deepar-output";function fe(e){const n=document.createElement("div");n.className=e,n.classList.add("shopar-loading-container",e);const t=n.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",n}function me(e,n){const t=document.createElement("div");return t.classList.add("shopar-loading-text",e),t.textContent=n,t.style.textAlign="center",t}function ve(e){const n=document.createElement("div");n.classList.add("shopar-loading-bar-bg",e);const t=n.style;return t.position="relative",t.overflow="hidden",n}function ge(e){const n=document.createElement("div");n.classList.add("shopar-loading-bar-fg",e);const t=n.style;return t.width="100%",t.height="100%",n}const we="shopar-main";const ye="shopar-qr-output";const be="shopar-three-output";var Ee;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(Ee||(Ee={}));let Ce,Se,Re,Ae,ke,xe,Me,Le,$e,De,Ue,Pe,Te,Ie,je=Ee.None;function Ne(e){je=e}let Oe,_e=!1,Ge=null;function Fe(){if(_e)return;!function(){try{const e=document.createElement("style"),n=process.env.css;null!=n&&(e.innerHTML=n);const t=document.head;t.insertBefore(e,t.children[0])}catch(e){console.warn("Failed to write default ShopAR Plugin CSS.")}}(),Ce=function(){const e=document.createElement("div");e.id=we;const n=e.style;return n.position="absolute",n.top="0",n.bottom="0",n.left="0",n.right="0",e}(),Re=function(){const e=new Image,n=e.style;return n.maxWidth="100%",n.maxHeight="100%",e}(),Se=function(e){const n=document.createElement("div");n.id=ye;const t=n.style;t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.display="none";const o=document.createElement("div");o.className="shopar-qr";const r=o.style;r.position="relative",r.top="0",r.left="0",r.width="100%",r.height="100%",n.appendChild(o);const i=document.createElement("div");i.innerText="Scan on mobile or tablet to try on",i.style.textAlign="center",o.appendChild(i);const a=document.createElement("div");return a.appendChild(e),o.appendChild(a),n}(Re),Ce.appendChild(Se),Ae=function(){const e=document.createElement("div");e.id=pe;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none",e}(),Ce.appendChild(Ae),ke=function(){const e=document.createElement("canvas");e.id=be;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none",e}(),Ce.appendChild(ke),De=fe("shopar-ar-loading-container");const e=me("shopar-ar-loading-text",le("loading.ar"));De.appendChild(e);const n=ve("shopar-ar-loading-bar-bg");Ue=ge("shopar-ar-loading-bar-fg"),n.appendChild(Ue),De.appendChild(n),Ce.appendChild(De),Pe=fe("shopar-3d-loading-container");const t=me("shopar-3d-loading-text",le("loading.3d"));Pe.appendChild(t);const o=ve("shopar-3d-loading-bar-bg");Te=ge("shopar-3d-loading-bar-fg"),o.appendChild(Te),Pe.appendChild(o),Ce.appendChild(Pe),Ie=function(){const e=document.createElement("div");e.id=de;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.display="none";const t=document.createElement("div"),o=t.style;o.position="absolute",o.width="100%",o.height="100%",o.backgroundColor="#ffffff",o.display="flex",o.flexDirection="column",o.justifyContent="center",o.alignItems="center",e.appendChild(t);const r=ce("4rem",`${R}/img/icons/close.svg`);t.appendChild(r);const i=document.createElement("div");i.className="shopar-error-title",i.textContent="Camera Error",t.appendChild(i);const a=document.createElement("div");return a.className="shopar-error-body",a.textContent="Please refresh the page and allow the use of camera.",t.appendChild(a),e}(),Ce.appendChild(Ie),xe=function(){const e=document.createElement("div");return e.id=he,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e.style.display="none",e}(),Ce.appendChild(xe),Me=ue("shopar-btn-vto","Try-on","Launch ShopAR virtual try-on","data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22/%3E"),xe.appendChild(Me),Le=ue("shopar-btn-3d","3D","Launch ShopAR 3D preview",`${R}/img/icons/cube.svg`),xe.appendChild(Le),$e=ue("shopar-btn-close","Close","Close ShopAR view",`${R}/img/icons/close.svg`),xe.append($e),_e=!0}function We(e,n,t,o){var r;Ve(xe,e),Ve(Me,e&&(t||n)&&je===Ee.None),Ve(Le,e&&o&&je===Ee.None),Ve($e,e&&je!==Ee.None),qe(),Be(),e||""===(r=Ie).style.display&&Ve(r,!1)}function Ve(e,n){e.style.display=n?"":"none"}function qe(){Ue.classList.remove("active"),De.style.visibility="hidden"}function ze(){Te.classList.add("active"),Pe.style.visibility="visible"}function Be(){Te.classList.remove("active"),Pe.style.visibility="hidden"}let He,Ke,Xe,Qe,Ze,Ye=!0;function Je(n,t){return e(this,void 0,void 0,(function*(){yield Oe;const e=`https://apps.deepar.ai/${C.includes("alpha")?"shopar-qr-alpha":"shopar-qr"}/?${new URLSearchParams({a:n,s:t,h:location.href})}`,o=yield window.ShopAR__QR.toDataURL(e),r=Re,i=new Promise(((e,n)=>{r.onload=e,r.onerror=n}));r.src=o,yield i,Ye=!1,Se.style.display=""}))}function en(){Ye=!0,Se.style.display="none"}let nn,tn,on,rn,an,sn,ln,cn,dn,un,hn,pn,fn,mn,vn,gn,wn,yn=!1,bn=!1;const En=25,Cn=5,Sn=40,Rn=45,An=45,kn=3,xn=0,Mn=1.5,Ln=1,$n=.5;let Dn,Un;function Pn(o){if(o!==Xe){const r=255;Xe=o,Ke=function(o,r,i){return e(this,void 0,void 0,(function*(){let a="glb".charCodeAt(0),s="3d".charCodeAt(0);a>>=1,a+=s;const d=String.fromCharCode(a+14);s>>=2,a^=s+2;const u=String.fromCharCode(a-3);a^=5;const h=String.fromCharCode(a-7);a^=2;const f=String.fromCharCode(a-7),m=window[`${h}${u+d+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${f}`],v=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield m(`${o}`).catch((()=>{throw new n("Unknown error.")}));if(!e.ok)throw new n("Unknown error.");return e})))),g=new t[0](yield(yield v.blob().catch((()=>{throw new n("Unknown error.")}))).arrayBuffer().catch((()=>{throw new n("Unknown error.")})));i+=s;const w=g.byteLength;if(c[l]=Math.min(76,r)*((a>>5)-1),152===c[l]&&(c[l]=w),i==l)return g;i=l,i^=l;for(let e=0,n=g.length;e<n;e++)c[l]^=c[i]<<13,c[l]^=c[i]>>17,c[l]^=c[i]<<5,g[e]=g[e]^c[l];return i^=c[0],i^=c[1],i^=c[2],g}))}(o,(new Date).getTime()+r,Math.random()*r),Dn=null,null==fn||fn.clear()}}function Tn(e){gn.removeEventListener("change",Un),Un=e,gn.addEventListener("change",e)}function In(n,t){return e(this,void 0,void 0,(function*(){return null==Dn&&(Dn=(()=>e(this,void 0,void 0,(function*(){const e=new tn.RGBELoader,o=function(e,n){const t=e.THREE,o=new t.DataTexture(n.data,n.width,n.height,void 0,n.type,void 0,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearFilter,1,t.LinearEncoding);return o.flipY=!0,o.generateMipmaps=!1,o.needsUpdate=!0,o}(tn,e.parse(t));o.mapping=on.EquirectangularReflectionMapping,o.encoding=on.LinearEncoding,fn.environment=o;const r=(new tn.GLTFLoader).setDRACOLoader((new tn.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${on.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new tn.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${on.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(rn)).setMeshoptDecoder("function"==typeof tn.MeshoptDecoder?tn.MeshoptDecoder():tn.MeshoptDecoder);return yield r.parseAsync(n.buffer,"")})))()),Dn}))}function jn(e,n){fn.add(e.scene);const t=(new on.Box3).setFromObject(e.scene);an.position.y=t.min.y-xn,fn.add(an),fn.traverse((e=>{if(e instanceof on.Mesh){const n=e.material;n.depthWrite=!0,n instanceof on.MeshPhysicalMaterial&&n.transmissionMap&&(n.transmission=1,n.toneMapped=!1,n.fog=!1,n.needsUpdate=!0)}})),gn.fov=En;const o=tn.reduceVertices,r=t.min.clone().add(t.max).divideScalar(2);gn.target.set(r.x,r.y,r.z),gn.panSphereCenter.set(r.x,r.y,r.z);const i=Math.sqrt(o(e.scene,((e,n)=>Math.max(e,r.distanceToSquared(n))),0));wn=i/Math.sin(En/2*on.MathUtils.DEG2RAD),gn.panSphereRadius=Math.min(i,wn-i);const a=r.clone().addScaledVector(function(e){var n;const t={Glasses:new on.Vector3(67.5,15,90),Shoes:new on.Vector3(-55,30,30),Watches:new on.Vector3(0,-10,40),Handbags:new on.Vector3(40,0,0),Rings:new on.Vector3(0,0,10)},o=null==e?t.Glasses:null!==(n=t[e])&&void 0!==n?n:t.Glasses;return o.normalize()}(n),wn);mn.position.set(a.x,a.y,a.z)}function Nn(){yn=!0,null!=nn&&(nn.style.display="none")}function On(){if(yn)return;requestAnimationFrame(On),gn.update(),_n(),mn.fov=mn.aspect<1?2*Math.atan(Math.tan(gn.fov/2*on.MathUtils.DEG2RAD)/mn.aspect)*on.MathUtils.RAD2DEG:gn.fov,mn.updateProjectionMatrix();const e=fn.background;fn.background=null,fn.overrideMaterial=un;const n=rn.getClearAlpha();rn.setClearAlpha(0),rn.setRenderTarget(sn),rn.render(fn,vn),fn.overrideMaterial=null,Gn(Mn),Gn(.4*Mn),rn.setRenderTarget(null),rn.setClearAlpha(n),fn.background=e,rn.render(fn,mn)}function _n(){const e=nn.clientWidth,n=nn.clientHeight;nn.width===e&&nn.height===n||(rn.setSize(e,n,!1),mn.aspect=e/n)}function Gn(e){dn.visible=!0,hn.uniforms.tDiffuse.value=sn.texture,hn.uniforms.h.value=1*e/256,dn.material=hn,rn.setRenderTarget(ln),rn.render(dn,vn),pn.uniforms.tDiffuse.value=ln.texture,pn.uniforms.v.value=1*e/256,dn.material=pn,rn.setRenderTarget(sn),rn.render(dn,vn),dn.visible=!1}function Fn(e,t){if(null==e)throw new n(`'${t}' not specified.`)}function Wn(e,t){if("string"!=typeof e)throw new n(`'${t}' must be a string.`)}const Vn=["AR","3D"];function qn(e){const{apiKey:t,sku:o,targetElement:r,initialState:i,baseUrl:a,defaultUI:s,strings:l}=e;Fn(t,"apiKey"),Wn(t,"apiKey"),Fn(o,"sku"),Wn(o,"sku"),Fn(r,"targetElement"),function(e,t){if(!(e instanceof HTMLElement))throw new n(`'${t}' must be an HTMLElement.`)}(r,"targetElement"),null!=i&&function(e,t,o){if("string"!=typeof e)throw new n(`'${t}' must be a string.`);if(!o.includes(e))throw new n(`'${t}' must be ${o.join("' or '")}.`)}(i,"initialState",Vn),null!=a&&Wn(a,"baseUrl"),null!=s&&function(e,t){if("boolean"!=typeof e)throw new n(`'${t}' must be a boolean.`)}(s,"defaultUI"),null!=l&&function(e,t,o){for(const r of o){const o=e[r];if(null!=o&&"string"!=typeof o)throw new n(`Value for key '${r}' in '${t}' must be a string.`)}}(l,"strings",se)}let zn=0,Bn=0;function Hn(t){var o,r;return e(this,void 0,void 0,(function*(){qn(t);const{apiKey:i,sku:a,targetElement:s,initialState:l}=t;!function(e){const t=getComputedStyle(e);if(!["static","relative"].includes(t.position))throw new n(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${t.position}'.`)}(s),R.update(t.baseUrl),function(e){if(null!=e)for(const n of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(ae,n)){console.warn(`String for key '${n}' will be ignored.`);continue}const t=e[n];null!=t&&(ae[n]=t)}}(t.strings);const c=function(t,o){return e(this,void 0,void 0,(function*(){const r=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:t,sku:o,sid:d()})}`).catch((e=>{throw console.error(e),new n("API unavailable.")}));if(!e.ok)throw new n(`API call failed with status ${e.status}.`);return e}))));try{return yield r.json()}catch(e){throw console.error(e),new n("API returned invalid body.")}}))}(i,a);null==$&&(D=E(),$=A(`${R}/shopar-analytics.js`),$.then((()=>{U=!0,window.ShopAR__analytics.initializeImpl(),P.forEach((e=>e()))})));const{trackEvent:u,arInteracted:h,previewInteracted:v}=T(a,i);u("setup",{hostname:window.location.hostname}),Fe();const g=++Bn,w=yield c;u("apiResponse",w);const{category:y,arUrl:b,arKey:C,previewUrl:S,previewEnvUrl:L}=w;Kn(g);const N=null!=b&&function(e){return null!=e&&f.includes(e)}(y),O=null==(null===(o=t._internalOptions)||void 0===o?void 0:o.qrEnabled)||(null===(r=t._internalOptions)||void 0===r?void 0:r.qrEnabled),W=N&&function(e){return null!=e&&m.includes(e)}(y),V=O&&W&&!(yield function(){var n;return e(this,void 0,void 0,(function*(){return null==Z&&(Z=A(`${R}/shopar-platform.js`)),yield Z,["Android","iOS","Windows Phone",void 0].includes(null===(n=window.ShopAR__platform.platform.os)||void 0===n?void 0:n.family)}))}());Kn(g),V&&function(){e(this,void 0,void 0,(function*(){null==Oe&&(Oe=A(`${R}/shopar-qr.js`))}))}();const X=N&&!V;X&&(null==_&&(_=A(`${R}/shopar-deepar.js`)),J(b),"Glasses"===y&&null==G&&(G=A(`${R}/shopar-true-scale.js`)));const Q=null!=S;var se;Q&&(null==He&&(He=A(`${R}/shopar-three.js`)),Pn(S),(se=null!=L?L:`${R}/env/default.hdr`)!==Ze&&(Ze=se,Qe=q(se))),function(e){e.style.position="relative",null==Ge?e.appendChild(Ce):e!==Ge&&(Ge.removeChild(Ce),e.appendChild(Ce)),Ge=e}(s);const le=null==t.defaultUI||t.defaultUI;if(We(le,V,X,Q),je===Ee.AR){if(!Y)if(ne(h),X){u(x);const e=yield F;Kn(g),yield te(e),Kn(g)}else oe(),Ne(Ee.None),le&&(Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0));if(!Ye)if(V){u(k);try{yield Je(i,a)}catch(e){throw new n(`QR failed: ${e instanceof Error?e.message:"Unknown error."}`)}}else en(),Ne(Ee.None),le&&(Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0))}else if(je===Ee.Preview&&!yn)if(Tn(v),Q){u(M),ze(),Ve(ke,!1);const e=yield Ke;Kn(g);const n=yield Qe;Kn(g);const t=yield In(e,n);Kn(g),jn(t,y),Ve(ke,!0),Be()}else Nn(),Ne(Ee.None),le&&(Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0));const ce=()=>e(this,void 0,void 0,(function*(){if(V){if(je===Ee.AR)throw new n("AR already launched.");try{u(k);++zn;return je===Ee.Preview&&Q&&!yn&&Nn(),Ne(Ee.AR),le&&(Ve(Me,!1),Ve(Le,!1),Ve($e,!0)),le&&Ve(Ie,!1),void(yield Je(i,a))}catch(e){const t=e instanceof Error;throw u("qrLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),new n(`QR failed: ${t?e.message:"Unknown error."}`)}}if(!X)throw new n("Model does not have AR enabled.");if(je===Ee.AR)throw new n("AR already launched.");try{u(x);const n=++zn;je===Ee.Preview&&Q&&!yn&&Nn(),Ne(Ee.AR),le&&(Ve(Me,!1),Ve(Le,!1),Ve($e,!0)),le&&Ve(Ie,!1),Ue.classList.add("active"),De.style.visibility="visible";const t=yield F;if(zn!==n||Bn!==g)return;if(yield _,zn!==n||Bn!==g)return;if(yield ee(Ae,C,y),zn!==n||Bn!==g)return;if(ne(h),yield te(t),zn!==n||Bn!==g)return;if(yield function(){return e(this,void 0,void 0,(function*(){if(null!=z){if(Y=!1,null==B){const e=re(H),n=I(e);B=yield j(n),yield ie(z,B,"user"===e)}z.setPaused(Y),K.style.display=""}}))}(),zn!==n||Bn!==g)return}catch(e){const t=e instanceof Error;throw u("arLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),le&&Ve(Ie,!0),oe(),new n(`AR failed: ${t?e.message:"Unknown error."}`)}finally{qe()}})),de=()=>e(this,void 0,void 0,(function*(){if(!Q)throw new n("Model does not have 3D enabled.");if(je===Ee.Preview)throw new n("3D already launched.");try{u(M);const n=++zn;je===Ee.AR&&(X&&!Y&&oe(),en()),Ne(Ee.Preview),le&&(Ve(Me,!1),Ve(Le,!1),Ve($e,!0)),le&&Ve(Ie,!1),ze();const t=yield Ke;if(zn!==n||Bn!==g)return;const o=yield Qe;if(zn!==n||Bn!==g)return;if(yield He,zn!==n||Bn!==g)return;if(yield function(n){return e(this,void 0,void 0,(function*(){if(nn=n,!bn){tn=window.ShopAR__THREE,on=tn.THREE,rn=new on.WebGLRenderer({powerPreference:"high-performance",canvas:n,antialias:!0,alpha:!0}),rn.outputEncoding=on.sRGBEncoding,rn.toneMapping=on.ACESFilmicToneMapping,rn.setPixelRatio(window.devicePixelRatio||1),rn.setClearColor(new on.Color(16777215)),fn=new on.Scene,an=new on.Group,an.position.y=-.7,sn=new on.WebGLRenderTarget(512,512),sn.texture.generateMipmaps=!1,ln=new on.WebGLRenderTarget(512,512),ln.texture.generateMipmaps=!1;const e=new on.PlaneGeometry(Rn,An).rotateX(Math.PI/2),t=new on.MeshBasicMaterial({map:sn.texture,opacity:$n,transparent:!0,depthWrite:!1});cn=new on.Mesh(e,t),cn.renderOrder=1,an.add(cn),cn.scale.y=-1,dn=new on.Mesh(e),dn.visible=!1,an.add(dn),vn=new on.OrthographicCamera(-Rn/2,Rn/2,An/2,-An/2,0,kn),vn.rotation.x=Math.PI/2,an.add(vn),un=new on.MeshDepthMaterial,un.userData.darkness={value:Ln},un.onBeforeCompile=function(e){e.uniforms.darkness=un.userData.darkness,e.fragmentShader=`\n uniform float darkness;\n ${e.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );")}\n `},un.depthTest=!1,un.depthWrite=!1,hn=new on.ShaderMaterial(tn.HorizontalBlurShader),hn.depthTest=!1,pn=new on.ShaderMaterial(tn.VerticalBlurShader),pn.depthTest=!1,mn=new on.PerspectiveCamera(25,1,.5),gn=new tn.OrbitControls(mn,rn.domElement),gn.minFov=Cn,gn.maxFov=Sn,gn.enableDamping=!0,gn.dampingFactor=.3,gn.zoomSpeed=3,gn.panSpeed=.5,gn.rotateSpeed=.5,bn=!0}_n()}))}(ke),zn!==n||Bn!==g)return;Tn(v);const r=yield In(t,o);if(zn!==n||Bn!==g)return;jn(r,y),yn=!1,On(),null!=nn&&(nn.style.display="")}catch(e){const t=e instanceof Error;throw u("previewLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),new n(`3D failed: ${t?e.message:"Unknown error."}`)}finally{Be()}})),ue=()=>e(this,void 0,void 0,(function*(){if(je===Ee.None)throw new n("Neither AR or 3D launched.");++zn,je===Ee.AR?(X&&!Y&&oe(),en()):je===Ee.Preview&&Q&&!yn&&Nn(),Ne(Ee.None),qe(),Be(),le&&(Ve(Ie,!1),Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0))}));return le&&((V||X)&&(!function(e){const n={Glasses:"glasses.svg",Shoes:"shoe.svg",Watches:"watch.svg"},t=`${R}/img/icons/${null!=e&&n[e]||n.Glasses}`;Me.firstChild.firstChild.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t)}(y),Me.onclick=ce),Q&&(Le.onclick=de),$e.onclick=ue),"AR"===l?(yield ce(),Kn(g)):"3D"===l&&(yield de(),Kn(g)),{launchAR:ce,launch3D:de,closeAR:()=>e(this,void 0,void 0,(function*(){if(je!==Ee.AR)throw new n("AR not launched.");++zn,X&&!Y&&oe(),en(),Ne(Ee.None),qe(),le&&(Ve(Ie,!1),Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0))})),close3D:()=>e(this,void 0,void 0,(function*(){if(je!==Ee.Preview)throw new n("3D not launched.");++zn,Q&&!yn&&Nn(),Ne(Ee.None),Be(),le&&(Ve(Ie,!1),Ve($e,!1),(V||X)&&Ve(Me,!0),Q&&Ve(Le,!0))})),close:ue}}))}function Kn(e){if(Bn!==e)throw new n("Setup cancelled. Please ensure that setup is only called once.")}const Xn={setup:function(t){return e(this,void 0,void 0,(function*(){return function(t,o){return e(this,void 0,void 0,(function*(){try{return o()}catch(e){throw e instanceof Error?new n(`${t} failed: ${e.message}`):(console.error(e),new n(`${t} failed.`))}}))}("setup",(()=>Hn(t)))}))},version:C};export{Xn as plugin};
|
|
1
|
+
function e(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((o=o.apply(e,t||[])).next())}))}!function(){const e={css:".shopar-btn-container{position:absolute;width:100%;bottom:0;padding-bottom:2rem;display:flex;justify-content:center;gap:.5rem;pointer-events:none}.shopar-btn{padding:.5rem .75rem;display:flex;justify-content:center;align-items:center;gap:.25rem;background-color:#fff;border:1px solid #ddd;border-radius:9999px;cursor:pointer;pointer-events:auto}.shopar-btn:hover{background-color:#f5f5f5}.shopar-loading-container{display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1rem;background-color:#fff}.shopar-loading-text{text-align:center}.shopar-loading-bar-bg{width:80%;height:.5rem;background-color:#e5e7eb;border-radius:9999px}.shopar-loading-bar-fg{background-color:#1434f7;border-radius:9999px;transition:none;transform:translateX(-100%);will-change:transform}.shopar-loading-bar-fg.active{transition:transform 5s cubic-bezier(0,0,.2,1);transform:none}.shopar-qr{display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:#fff}"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}(),"function"==typeof SuppressedError&&SuppressedError;class t extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}const n=[Uint8Array,Uint32Array],o=n.length-2,r=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],i=[2,12,7,1],a=window[r[i[i[o]]]][r[i[i[i.length-1]]]],s=a.charCodeAt(o),c=s^s,l=new n[1]([c]);function d(){const e=(new TextEncoder).encode(a),t=r.map((e=>e.length));for(let n=0;n<e.length;n++)e[n]^=t[n%t.length];return window[r[t[2]]](String.fromCodePoint(...e))}const u=[1e3,2e3,4e3],h=u.length;function p(t,n=0){return e(this,void 0,void 0,(function*(){try{return yield t()}catch(e){if(n>=h)throw e;return yield new Promise((e=>setTimeout(e,u[n]))),p(t,n+1)}}))}const f=["Glasses","Shoes","Watches"],g=["Shoes"];const m="0.0.8-alpha.0";let v=`https://cdn.jsdelivr.net/npm/shopar-plugin@${m}/dist`;const w={update:e=>{null!=e&&(v=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>v};function y(t){return e(this,void 0,void 0,(function*(){if("function"!=typeof importScripts){const e=document.createElement("script");return e.setAttribute("src",t),e.setAttribute("crossorigin","anonymous"),new Promise((t=>{e.addEventListener("load",(()=>t()),!1),e.addEventListener("error",(()=>t()),!1),document.body.appendChild(e)}))}importScripts(t.toString())}))}let b;const R=(()=>{const e=(()=>{var e;if(null===(e=document.documentElement.getAttribute("itemtype"))||void 0===e?void 0:e.includes("schema.org/SearchResultsPage"))return!0;const t=null!=document.head?Array.from(document.head.querySelectorAll("meta")):[];for(const e of t)if("viewport"===e.name)return!0;return!1})();return e||console.warn('No <meta name="viewport"> detected; ShopAR will cap pixel density at 1.'),()=>e?window.devicePixelRatio:1})();let S,E,A;function C(e){const t=function(e){const t=new E.DataTexture(e.data,e.width,e.height,void 0,e.type,void 0,E.ClampToEdgeWrapping,E.ClampToEdgeWrapping,E.LinearFilter,E.LinearFilter,1,E.LinearEncoding);return t.flipY=!0,t.generateMipmaps=!1,t.needsUpdate=!0,t}(A.parse(e));return t.mapping=E.EquirectangularReflectionMapping,t.encoding=E.LinearEncoding,t}const I=45,L=45,k=3,P=1.5,T=1,x=.5;let M,U,D,$,_,N,j=!1;const O=0;let q,G,W,Q=!1,F=1,V=1,H=1;const B=1;let K;const z=new Map;function X(t){const n=t.getContext("2d");null==n&&console.warn("2D context missing.");let o,r,i,a,s,c,l,d=!1,u=!0,h=!1,p=1,f=1,g=1;const m={threeInit:()=>{d||(Z(),o=new G.Scene,r=new G.PerspectiveCamera(25,1,.5),i=new q.OrbitControls(r,t),i.enableInteraction(),({renderShadow:s,shadowGroup:a}=function(e){const t=new M.WebGLRenderTarget(512,512);t.texture.generateMipmaps=!1;const n=new M.WebGLRenderTarget(512,512);n.texture.generateMipmaps=!1;const o=new M.Group;o.position.y=-.7;const r=new M.PlaneGeometry(I,L).rotateX(Math.PI/2),i=new M.MeshBasicMaterial({map:t.texture,opacity:x,transparent:!0,depthWrite:!1}),a=new M.Mesh(r,i);a.renderOrder=1,a.scale.y=-1,o.add(a);const s=new M.Mesh(r);s.visible=!1,o.add(s);const c=new M.OrthographicCamera(-I/2,I/2,L/2,-L/2,0,k);function l(e){s.visible=!0,$.uniforms.tDiffuse.value=t.texture,$.uniforms.h.value=1*e/256,s.material=$,U.setRenderTarget(n),U.render(s,c),_.uniforms.tDiffuse.value=n.texture,_.uniforms.v.value=1*e/256,s.material=_,U.setRenderTarget(t),U.render(s,c),s.visible=!1}return c.rotation.x=Math.PI/2,o.add(c),{shadowGroup:o,renderShadow:()=>{const n=e.background;e.background=null,e.overrideMaterial=D;const o=U.getClearAlpha();U.setClearAlpha(0),U.setRenderTarget(t),U.render(e,c),e.overrideMaterial=null,l(P),l(.4*P),U.setRenderTarget(null),U.setClearAlpha(o),e.background=n}}}(o)),d=!0)},threeParse:(t,n)=>(null==c&&(c=(()=>e(this,void 0,void 0,(function*(){var e,r;return E=(e=q).THREE,A=new e.RGBELoader,o.environment=C(n),function(e,t){const{THREE:n}=t;S=(new t.GLTFLoader).setDRACOLoader((new t.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${n.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new t.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${n.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(e)).setMeshoptDecoder("function"==typeof t.MeshoptDecoder?t.MeshoptDecoder():t.MeshoptDecoder)}(K,q),r=t,S.parseAsync(r.buffer,"")})))()),c),threeLoad:(e,t)=>{o.clear(),o.add(e.scene);const n=(new G.Box3).setFromObject(e.scene);a.position.y=n.min.y-O,o.add(a),s(),o.traverse((e=>{if(e instanceof G.Mesh){const t=e.material;t.depthWrite=!0,t instanceof G.MeshPhysicalMaterial&&t.transmissionMap&&(t.transmission=1,t.toneMapped=!1,t.fog=!1,t.needsUpdate=!0)}}));const r=n.min.clone().add(n.max).divideScalar(2),c=Math.sqrt(q.reduceVertices(e.scene,((e,t)=>Math.max(e,r.distanceToSquared(t))),0));i.reset(r,c,function(e,t){var n;const o={Glasses:new t(67.5,15,90),Shoes:new t(-55,30,30),Watches:new t(0,-10,40),Handbags:new t(40,0,0),Rings:new t(0,0,10)};return(null==e?o.Glasses:null!==(n=o[e])&&void 0!==n?n:o.Glasses).normalize()}(t,G.Vector3))},threePaused:()=>u,threeResume:()=>{u=!1,K.setAnimationLoop(Y),t.style.visibility="visible"},threePause:()=>{u=!0,function(){for(const{threePaused:e}of z.values())if(!e())return!1;return!0}()&&K.setAnimationLoop(null),t.style.visibility="hidden"},threeSetOnInteracted:e=>{i.removeEventListener("change",l),l=e,i.addEventListener("change",e)},preRender_:()=>{d&&!u&&i.update()&&(h=!0)},shouldRender_:()=>!(!d||u)&&h,render_:()=>{K.setViewport(0,0,t.width,t.height),K.render(o,r),h=!1,null!=n&&(n.clearRect(0,0,t.width,t.height),n.drawImage(W,0,V-t.height,t.width,t.height,0,0,t.width,t.height))},updateSize_:()=>{const{clientWidth:e,clientHeight:n}=t;e===p&&n===f&&H===g||(t.width=Math.ceil(e*H*B),t.height=Math.ceil(n*H*B),p=e,f=n,g=H,h=!0)},target_:t};return z.set(t,m),m}function Z(){if(Q)return;q=window.ShopAR__THREE,G=q.THREE,W=document.createElement("canvas");var e,t;W.style.position="block",K=new G.WebGLRenderer({powerPreference:"high-performance",canvas:W,antialias:!0,alpha:!0}),K.outputEncoding=G.sRGBEncoding,K.toneMapping=G.ACESFilmicToneMapping,K.setClearColor(new G.Color(16777215)),e=K,t=q,j||(M=t.THREE,U=e,D=new M.MeshDepthMaterial,D.userData.darkness={value:T},D.onBeforeCompile=e=>{e.uniforms.darkness=D.userData.darkness;const t=e.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );");e.fragmentShader=`uniform float darkness;\n${t}`},D.depthTest=!1,D.depthWrite=!1,$=new M.ShaderMaterial(t.HorizontalBlurShader),$.depthTest=!1,_=new M.ShaderMaterial(t.VerticalBlurShader),_.depthTest=!1,j=!0),J(),Q=!0}function Y(){J(),K.clear();for(const{preRender_:e,shouldRender_:t,render_:n}of z.values())e(),t()&&n()}function J(){let e=0,t=0;for(const{target_:n}of z.values()){const{clientWidth:o,clientHeight:r}=n;e=Math.max(e,o),t=Math.max(t,r)}const n=R();e=Math.ceil(e*n*B),t=Math.ceil(t*n*B),e===F&&t===V&&n===H||(F=e,V=t,H=n,K.setSize(F,V,!1));for(const{updateSize_:e}of z.values())e()}const ee={"loading.ar":"Loading Try On...","loading.3d":"Loading 3D..."},te=Object.keys(ee);function ne(e){return ee[e]}function oe(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("width",e),n.setAttribute("height",e);{const o=document.createElementNS("http://www.w3.org/2000/svg","image");o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),o.setAttribute("width",e),o.setAttribute("height",e),n.appendChild(o)}return n}const re="shopar-error";function ie(e,t,n,o){const r=document.createElement("button");r.id=e,r.type="button",r.className="shopar-btn";{const e=oe("1.75rem",o);r.appendChild(e)}{const e=document.createElement("span");e.textContent=t,r.appendChild(e)}r.ariaLabel=n;return r.style.display="none",r}const ae="shopar-control";const se="shopar-deepar-output";function ce(e){const t=document.createElement("div");t.className=e,t.classList.add("shopar-loading-container",e);const n=t.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",t}function le(e,t){const n=document.createElement("div");return n.classList.add("shopar-loading-text",e),n.textContent=t,n.style.textAlign="center",n}function de(e){const t=document.createElement("div");t.classList.add("shopar-loading-bar-bg",e);const n=t.style;return n.position="relative",n.overflow="hidden",t}function ue(e){const t=document.createElement("div");t.classList.add("shopar-loading-bar-fg",e);const n=t.style;return n.width="100%",n.height="100%",t}const he="shopar-main";const pe="shopar-qr-output";const fe="shopar-three-output";var ge;!function(e){e[e.None=0]="None",e[e.QR=1]="QR",e[e.AR=2]="AR",e[e.Preview=3]="Preview"}(ge||(ge={}));let me=!1;function ve(){me||(!function(){try{const e=document.createElement("style"),t=process.env.css;null!=t&&(e.innerHTML=t);const n=document.head;n.insertBefore(e,n.children[0])}catch(e){console.warn("Failed to write default ShopAR Plugin CSS.")}}(),me=!0)}function we(){ve();const e=function(){const e=document.createElement("div");e.id=he;const t=e.style;return t.position="absolute",t.top="0",t.bottom="0",t.left="0",t.right="0",e}(),t=function(){const e=new Image,t=e.style;return t.maxWidth="100%",t.maxHeight="100%",e}(),n=function(e){const t=document.createElement("div");t.id=pe;const n=t.style;n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none";const o=document.createElement("div");o.className="shopar-qr";const r=o.style;r.position="relative",r.top="0",r.left="0",r.width="100%",r.height="100%",t.appendChild(o);const i=document.createElement("div");i.innerText="Scan on mobile or tablet to try on",i.style.textAlign="center",o.appendChild(i);const a=document.createElement("div");return a.appendChild(e),o.appendChild(a),t}(t);e.appendChild(n);const o=function(){const e=document.createElement("div");e.id=se;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.display="none",e}();e.appendChild(o);const r=function(){const e=document.createElement("canvas");e.id=fe;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.visibility="hidden",e}();e.appendChild(r);const i=ce("shopar-ar-loading-container"),a=le("shopar-ar-loading-text",ne("loading.ar"));i.appendChild(a);const s=de("shopar-ar-loading-bar-bg"),c=ue("shopar-ar-loading-bar-fg");s.appendChild(c),i.appendChild(s),e.appendChild(i);const l=ce("shopar-3d-loading-container"),d=le("shopar-3d-loading-text",ne("loading.3d"));l.appendChild(d);const u=de("shopar-3d-loading-bar-bg"),h=ue("shopar-3d-loading-bar-fg");u.appendChild(h),l.appendChild(u),e.appendChild(l);const p=function(){const e=document.createElement("div");e.id=re;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.display="none";const n=document.createElement("div"),o=n.style;o.position="absolute",o.width="100%",o.height="100%",o.backgroundColor="#ffffff",o.display="flex",o.flexDirection="column",o.justifyContent="center",o.alignItems="center",e.appendChild(n);const r=oe("4rem",`${w}/img/icons/close.svg`);n.appendChild(r);const i=document.createElement("div");i.className="shopar-error-title",i.textContent="Camera Error",n.appendChild(i);const a=document.createElement("div");return a.className="shopar-error-body",a.textContent="Please refresh the page and allow the use of camera.",n.appendChild(a),e}();e.appendChild(p);const f=function(){const e=document.createElement("div");return e.id=ae,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e.style.display="none",e}();e.appendChild(f);const g=ie("shopar-btn-vto","Try-on","Launch ShopAR virtual try-on","data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22/%3E");f.appendChild(g);const m=ie("shopar-btn-3d","3D","Launch ShopAR 3D preview",`${w}/img/icons/cube.svg`);f.appendChild(m);const v=ie("shopar-btn-close","Close","Close ShopAR view",`${w}/img/icons/close.svg`);f.append(v);let y,b=ge.None,R=!1,S=!1,E=!1,A=!1;function C(){c.classList.remove("active"),i.style.visibility="hidden"}function I(){h.classList.remove("active"),l.style.visibility="hidden"}return{setTargetElement:function(t){t.style.position="relative",t.appendChild(e)},getQRTarget:function(){return n},getQRImage:function(){return t},getDeepARTarget:function(){return o},getThreeTarget:function(){return r},setVisibilityParameters:function(e,t,n,o,r){var i;R=e,S=t,E=n,A=o,y=r,ye(f,R),ye(g,R&&(E||S)&&b===ge.None),ye(m,R&&A&&b===ge.None),ye(v,R&&b!==ge.None),C(),I(),R||""===(i=p).style.display&&ye(i,!1)},getUIState:function(){return b},setUIState:function(e){b=e,b===ge.None?(C(),I(),R&&(ye(p,!1),ye(v,!1),(S||E)&&ye(g,!0),A&&ye(m,!0))):b!==ge.QR&&b!==ge.AR&&b!==ge.Preview||R&&(ye(p,!1),ye(g,!1),ye(m,!1),ye(v,!0))},setDefaultUIActions:function(e,t,n){R&&((S||E)&&(!function(e){const t={Glasses:"glasses.svg",Shoes:"shoe.svg",Watches:"watch.svg"},n=null!=e&&t[e]||t.Glasses,o=`${w}/img/icons/${n}`;g.firstChild.firstChild.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o)}(y),g.onclick=e),A&&(m.onclick=t),v.onclick=n)},startDeepARLoading:function(){c.classList.add("active"),i.style.visibility="visible"},stopDeepARLoading:C,startThreeLoading:function(){h.classList.add("active"),l.style.visibility="visible"},stopThreeLoading:I,showCameraError:function(){R&&ye(p,!0)}}}function ye(e,t){e.style.display=t?"":"none"}const be=new Map;function Re(t){let n=be.get(t);return null==n?(n=function(){let t=0,n=null,o=null,r=null;const i=()=>(null==n&&(n=we()),n);return{getSetupId:()=>t,incrementSetupId_:()=>t++,getUI_:()=>n,findUI:i,findQR:()=>{if(null==o){const{getQRTarget:t,getQRImage:n}=i();o=function(t,n){let o=!0;return{qrPaused:()=>o,qrDraw:(r,i)=>e(this,void 0,void 0,(function*(){yield b;const e=`https://apps.deepar.ai/${m.includes("alpha")?"shopar-qr-alpha":"shopar-qr"}/?${new URLSearchParams({a:r,s:i,h:location.href})}`,a=yield window.ShopAR__QR.toDataURL(e),s=new Promise(((e,t)=>{n.onload=e,n.onerror=t}));n.src=a,yield s,o=!1,t.style.display=""})),qrPause:()=>e(this,void 0,void 0,(function*(){o=!0,t.style.display="none"}))}}(t(),n())}return o},findThree:()=>{if(null==r){const{getThreeTarget:e}=i();r=X(e())}return r}}}(),be.set(t,n)):n.incrementSetupId_(),n}function Se(e){for(const t of be.values()){if(t===e)continue;const n=t.getUI_();if(null==n)continue;const{getUIState:o,setUIState:r}=n;o()===ge.AR&&r(ge.None)}}let Ee;const Ae=new Uint8Array(16);function Ce(){if(!Ee&&(Ee="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ee))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ee(Ae)}const Ie=[];for(let e=0;e<256;++e)Ie.push((e+256).toString(16).slice(1));var Le={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ke(e,t,n){if(Le.randomUUID&&!t&&!e)return Le.randomUUID();const o=(e=e||{}).random||(e.rng||Ce)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=o[e];return t}return function(e,t=0){return Ie[e[t+0]]+Ie[e[t+1]]+Ie[e[t+2]]+Ie[e[t+3]]+"-"+Ie[e[t+4]]+Ie[e[t+5]]+"-"+Ie[e[t+6]]+Ie[e[t+7]]+"-"+Ie[e[t+8]]+Ie[e[t+9]]+"-"+Ie[e[t+10]]+Ie[e[t+11]]+Ie[e[t+12]]+Ie[e[t+13]]+Ie[e[t+14]]+Ie[e[t+15]]}(o)}const Pe="qrLaunch",Te="arLaunch",xe="previewLaunch",Me="heartbeat";let Ue,De,$e=!1;const _e=[];function Ne(e,t){const n=performance.now(),o=ke();let r=0,i=0,a=0,s=0,c=0,l=!1;window.setInterval((()=>{l&&(r=i+a,l=!1,d(Me,{engagementTotal:r,engagementAR:i,engagement3D:a}))}),1e3);const d=(r,i={})=>{var a;i=Object.assign(Object.assign({},i),{pluginVersion:m,sessionId:De,setupId:o,timeSinceSetup:performance.now()-n,sku:e,apiKey:t}),a=()=>{window.ShopAR__analytics.trackEventImpl(r,i)},$e?a():_e.push(a)};return{trackEvent:d,arInteracted:()=>{const e=performance.now(),t=e-s;s=e,t<200&&(i+=t,l=!0)},previewInteracted:()=>{const e=performance.now(),t=e-c;c=e,t<200&&(a+=t,l=!0)}}}function je(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}function Oe(t){return e(this,void 0,void 0,(function*(){const e=document.createElement("video");return e.setAttribute("playsinline","playsinline"),e.srcObject=yield t,e}))}const qe=200,Ge=10;let We,Qe,Fe,Ve=!1;function He(n){return e(this,void 0,void 0,(function*(){const o=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(n).catch((e=>{throw console.error(e),new t("Resource unavailable.")}));if(!e.ok)throw new t(`Resource download failed with status ${e.status}.`);return e}))));try{return yield(yield o.blob()).arrayBuffer()}catch(e){throw console.error(e),new t("Resource has invalid body.")}}))}let Be,Ke,ze,Xe,Ze,Ye,Je,et,tt=!0;function nt(e){e!==Fe&&(Fe=e,He(e),Ye=null,Ve=!0)}function ot(n,o){return e(this,void 0,void 0,(function*(){return ze=o,null==Ze&&(Ze=(()=>e(this,void 0,void 0,(function*(){if(null==(null===(r=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia))throw new t("No camera available!");var r;const i=ct(o),a=je(i),s=function(e){const t={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:t[e]}(o);Be=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:n||"your_license_key_goes_here",previewElement:Xe,additionalOptions:{hint:s,cameraConfig:{disableDefaultCamera:!0}}}),Ke=yield Oe(a),yield lt(Be,Ke,"user"===i),"Glasses"===o&&(yield Qe,function(t,n){e(this,void 0,void 0,(function*(){Ve=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${w}/wasm/mediapipe`,t);const r=[],i=setInterval((()=>e(this,void 0,void 0,(function*(){if(Ve)return void clearInterval(i);const{error:e,faceWidth:t}=yield o.predict(performance.now());if(Ve)return void clearInterval(i);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(r.length<Ge)return void r.push(t);clearInterval(i);const a=137/(function(e){let t=0;const n=e.length;for(let o=0;o<n;o++)t+=e[o];return t/n}(r)+5);n.changeParameterVector("GLASSES","","scale",a,a,a,0),n.changeParameterVector("shopar_glasses","","scale",a,a,a,0)}))),qe)}))}(Ke,Be))})))()),Ze}))}function rt(t){return e(this,void 0,void 0,(function*(){t!==Xe&&(Xe=t,null!=Be&&Be.changePreviewElement(Xe))}))}function it(e){Be.callbacks.onFaceTracked=t=>{t.some((e=>e.detected))&&e()},Be.callbacks.onFeetTracked=(t,n)=>{(t.detected||n.detected)&&e()},Be.callbacks.onWristTracked=t=>{t.detected&&e()}}function at(t,n){return e(this,void 0,void 0,(function*(){return null!=Ye&&Je===n||(Ye=Be.switchEffect(t),Je=n),Ye}))}function st(){null!=Be&&(tt=!0,Be.setPaused(tt),null!=Ke&&null!=Ke.srcObject&&Ke.srcObject instanceof MediaStream&&(Ke.srcObject.getTracks().forEach((e=>e.stop())),Ke=null),Be.stopCamera(),Xe.style.display="none")}function ct(e){var t;return null==e?"user":null!==(t={Glasses:"user",Shoes:"environment",Watches:"environment"}[e])&&void 0!==t?t:"user"}function lt(t,n,o){return e(this,void 0,void 0,(function*(){yield new Promise((r=>{n.onloadedmetadata=()=>{n.play().then((()=>e(this,void 0,void 0,(function*(){t.setVideoElement(n,o),r()}))))}}))}))}function dt(o,r,i){return e(this,void 0,void 0,(function*(){let a="glb".charCodeAt(0),s="3d".charCodeAt(0);a>>=1,a+=s;const d=String.fromCharCode(a+14);s>>=2,a^=s+2;const u=String.fromCharCode(a-3);a^=5;const h=String.fromCharCode(a-7);a^=2;const f=String.fromCharCode(a-7),g=window[`${h}${u+d+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${f}`],m=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield g(`${o}`).catch((()=>{throw new t("Unknown error.")}));if(!e.ok)throw new t("Unknown error.");return e})))),v=new n[0](yield(yield m.blob().catch((()=>{throw new t("Unknown error.")}))).arrayBuffer().catch((()=>{throw new t("Unknown error.")})));i+=s;const w=v.byteLength;if(l[c]=Math.min(76,r)*((a>>5)-1),152===l[c]&&(l[c]=w),i==c)return v;i=c,i^=c;for(let e=0,t=v.length;e<t;e++)l[c]^=l[i]<<13,l[c]^=l[i]>>17,l[c]^=l[i]<<5,v[e]=v[e]^l[c];return i^=l[0],i^=l[1],i^=l[2],v}))}function ut(e,n){if(null==e)throw new t(`'${n}' not specified.`)}function ht(e,n){if("string"!=typeof e)throw new t(`'${n}' must be a string.`)}const pt=["AR","3D"];function ft(e){const{apiKey:n,sku:o,targetElement:r,initialState:i,baseUrl:a,defaultUI:s,strings:c}=e;ut(n,"apiKey"),ht(n,"apiKey"),ut(o,"sku"),ht(o,"sku"),ut(r,"targetElement"),function(e,n){if(!(e instanceof HTMLElement))throw new t(`'${n}' must be an HTMLElement.`)}(r,"targetElement"),null!=i&&function(e,n,o){if("string"!=typeof e)throw new t(`'${n}' must be a string.`);if(!o.includes(e))throw new t(`'${n}' must be ${o.join("' or '")}.`)}(i,"initialState",pt),null!=a&&ht(a,"baseUrl"),null!=s&&function(e,n){if("boolean"!=typeof e)throw new t(`'${n}' must be a boolean.`)}(s,"defaultUI"),null!=c&&function(e,n,o){for(const r of o){const o=e[r];if(null!=o&&"string"!=typeof o)throw new t(`Value for key '${r}' in '${n}' must be a string.`)}}(c,"strings",te)}function gt(n){var o,r;return e(this,void 0,void 0,(function*(){ft(n);const{apiKey:i,sku:a,targetElement:s,initialState:c}=n;!function(e){const n=getComputedStyle(e);if(!["static","relative"].includes(n.position))throw new t(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${n.position}'.`)}(s),w.update(n.baseUrl),function(e){if(null!=e)for(const t of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(ee,t)){console.warn(`String for key '${t}' will be ignored.`);continue}const n=e[t];null!=n&&(ee[t]=n)}}(n.strings);const l=function(n,o){return e(this,void 0,void 0,(function*(){const r=yield p((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:n,sku:o,sid:d()})}`).catch((e=>{throw console.error(e),new t("API unavailable.")}));if(!e.ok)throw new t(`API call failed with status ${e.status}.`);return e}))));try{return yield r.json()}catch(e){throw console.error(e),new t("API returned invalid body.")}}))}(i,a),u=Re(s),{getSetupId:h,findUI:m,findQR:v,findThree:R}=u,S=h();null==Ue&&(De=ke(),Ue=y(`${w}/shopar-analytics.js`),Ue.then((()=>{$e=!0,window.ShopAR__analytics.initializeImpl(),_e.forEach((e=>e()))})));const{trackEvent:E,arInteracted:A,previewInteracted:C}=Ne(a,i);E("setup",{hostname:window.location.hostname});const I=yield l;E("apiResponse",I);const{category:L,arUrl:k,arKey:P,previewUrl:T,previewEnvUrl:x}=I;mt(h(),S);const M=null!=k&&function(e){return null!=e&&f.includes(e)}(L),U=null==(null===(o=n._internalOptions)||void 0===o?void 0:o.qrEnabled)||(null===(r=n._internalOptions)||void 0===r?void 0:r.qrEnabled),D=M&&function(e){return null!=e&&g.includes(e)}(L),$=U&&D&&!(yield function(){var t;return e(this,void 0,void 0,(function*(){return null==et&&(et=y(`${w}/shopar-platform.js`)),yield et,["Android","iOS","Windows Phone",void 0].includes(null===(t=window.ShopAR__platform.platform.os)||void 0===t?void 0:t.family)}))}()),_=M&&!$,j=null!=T;if(mt(h(),S),$&&function(){e(this,void 0,void 0,(function*(){null==b&&(b=y(`${w}/shopar-qr.js`))}))}(),_&&(null==We&&(We=y(`${w}/shopar-deepar.js`)),nt(k),"Glasses"===L&&null==Qe&&(Qe=y(`${w}/shopar-true-scale.js`))),j){null==N&&(N=y(`${w}/shopar-three.js`));const e=255;dt(T,(new Date).getTime()+e,Math.random()*e),He(null!=x?x:`${w}/env/default.hdr`)}const{setTargetElement:O,getDeepARTarget:q,setVisibilityParameters:G,getUIState:W,setUIState:Q,setDefaultUIActions:F,startDeepARLoading:V,stopDeepARLoading:H,startThreeLoading:B,stopThreeLoading:K,showCameraError:z}=m();O(s);G(null==n.defaultUI||n.defaultUI,$,_,j,L),function(e,n){const o=e.parentNode;if(null==o)throw new t("Parent node missing.");new MutationObserver((t=>{for(const o of t)for(const t of o.removedNodes)if(t===e)return void n()})).observe(o,{childList:!0})}(s,(()=>{W()!==ge.QR||X()||Y(),W()!==ge.AR||tt||st(),W()!==ge.Preview||oe()||ie(),Q(ge.None)}));const{qrPaused:X,qrDraw:Z,qrPause:Y}=v(),{threeInit:J,threeParse:te,threeLoad:ne,threePaused:oe,threeResume:re,threePause:ie,threeSetOnInteracted:ae}=R();let se=0;if(W()===ge.QR){if(!X())if($){E(Pe);try{yield Z(i,a)}catch(e){throw new t(`QR failed: ${e instanceof Error?e.message:"Unknown error."}`)}}else Y(),Q(ge.None)}else if(W()===ge.AR){if(!tt)if(_){E(Te);const e=yield He(k);mt(h(),S),Se(u),rt(q()),yield at(e,k),it(A),mt(h(),S)}else st(),Q(ge.None)}else if(W()===ge.Preview&&!oe())if(j){E(xe),B();const e=255,t=yield dt(T,(new Date).getTime()+e,Math.random()*e);mt(h(),S);const n=yield He(null!=x?x:`${w}/env/default.hdr`);mt(h(),S);const o=yield te(t,n);mt(h(),S),ne(o,L),ae(C),K()}else ie(),Q(ge.None);const ce=()=>e(this,void 0,void 0,(function*(){if($){if(W()===ge.QR||W()===ge.AR)throw new t("AR already launched.");try{E(Pe);const e=++se;if(W()===ge.Preview&&j&&!oe()&&ie(),Q(ge.QR),yield Z(i,a),se!==e)return;return void mt(h(),S)}catch(e){const n=e instanceof Error;throw E("qrLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),new t(`QR failed: ${n?e.message:"Unknown error."}`)}}if(!_)throw new t("Model does not have AR enabled.");if(W()===ge.AR)throw new t("AR already launched.");try{E(Te);const t=++se;W()===ge.Preview&&j&&!oe()&&ie(),Se(u),Q(ge.AR),V();const n=yield He(k);if(se!==t)return;if(mt(h(),S),yield We,se!==t)return;if(mt(h(),S),st(),rt(q()),yield ot(P,L),se!==t)return;if(mt(h(),S),yield at(n,k),it(A),se!==t)return;if(mt(h(),S),yield function(){return e(this,void 0,void 0,(function*(){if(null!=Be){if(tt=!1,null==Ke){const e=ct(ze),t=je(e);Ke=yield Oe(t),yield lt(Be,Ke,"user"===e)}Be.setPaused(tt),Xe.style.display=""}}))}(),se!==t)return;mt(h(),S)}catch(e){const n=e instanceof Error;throw E("arLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),z(),st(),new t(`AR failed: ${n?e.message:"Unknown error."}`)}finally{H()}})),le=()=>e(this,void 0,void 0,(function*(){if(!j)throw new t("Model does not have 3D enabled.");if(W()===ge.Preview)throw new t("3D already launched.");try{E(xe);const e=++se;W()===ge.AR&&(_&&!tt&&st(),Y()),Q(ge.Preview),B();const t=255,n=yield dt(T,(new Date).getTime()+t,Math.random()*t);if(se!==e)return;mt(h(),S);const o=yield He(null!=x?x:`${w}/env/default.hdr`);if(se!==e)return;if(mt(h(),S),yield N,se!==e)return;if(mt(h(),S),J(),se!==e)return;mt(h(),S);const r=yield te(n,o);if(se!==e)return;mt(h(),S),ne(r,L),ae(C),re()}catch(e){const n=e instanceof Error;throw E("previewLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),new t(`3D failed: ${n?e.message:"Unknown error."}`)}finally{K()}})),de=()=>e(this,void 0,void 0,(function*(){if(W()===ge.None)throw new t("Neither AR or 3D launched.");++se,W()===ge.QR||W()===ge.AR?(_&&!tt&&st(),Y()):W()===ge.Preview&&j&&!oe()&&ie(),Q(ge.None)}));return F(ce,le,de),"AR"===c?(yield ce(),mt(h(),S)):"3D"===c&&(yield le(),mt(h(),S)),{launchAR:ce,launch3D:le,closeAR:()=>e(this,void 0,void 0,(function*(){if(W()!==ge.AR||W()!==ge.QR)throw new t("AR not launched.");++se,_&&!tt&&st(),Y(),Q(ge.None)})),close3D:()=>e(this,void 0,void 0,(function*(){if(W()!==ge.Preview)throw new t("3D not launched.");++se,j&&!oe()&&ie(),Q(ge.None)})),close:de}}))}function mt(e,n){if(e!==n)throw new t("Setup cancelled. Please ensure that setup is only called once.")}const vt={setup:function(n){return e(this,void 0,void 0,(function*(){return function(n,o){return e(this,void 0,void 0,(function*(){try{return o()}catch(e){throw e instanceof Error?new t(`${n} failed: ${e.message}`):(console.error(e),new t(`${n} failed.`))}}))}("setup",(()=>gt(n)))}))},version:m};export{vt as plugin};
|
package/dist/shopar-plugin.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).ShopAR={})}(this,(function(e){"use strict";function n(e,n,t,o){return new(t||(t=Promise))((function(r,i){function a(e){try{l(o.next(e))}catch(e){i(e)}}function s(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var n;e.done?r(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,s)}l((o=o.apply(e,n||[])).next())}))}!function(){const e={css:".shopar-btn-container{position:absolute;width:100%;bottom:0;padding-bottom:2rem;display:flex;justify-content:center;gap:.5rem;pointer-events:none}.shopar-btn{padding:.5rem .75rem;display:flex;justify-content:center;align-items:center;gap:.25rem;background-color:#fff;border:1px solid #ddd;border-radius:9999px;cursor:pointer;pointer-events:auto}.shopar-btn:hover{background-color:#f5f5f5}.shopar-loading-container{display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1rem;background-color:#fff}.shopar-loading-text{text-align:center}.shopar-loading-bar-bg{width:80%;height:.5rem;background-color:#e5e7eb;border-radius:9999px}.shopar-loading-bar-fg{background-color:#1434f7;border-radius:9999px;transition:none;transform:translateX(-100%);will-change:transform}.shopar-loading-bar-fg.active{transition:transform 5s cubic-bezier(0,0,.2,1);transform:none}.shopar-qr{display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:#fff}"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}(),"function"==typeof SuppressedError&&SuppressedError;class t extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}const o=[Uint8Array,Uint32Array],r=o.length-2,i=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],a=[2,12,7,1],s=window[i[a[a[r]]]][i[a[a[a.length-1]]]],l=s.charCodeAt(r),c=l^l,d=new o[1]([c]);function u(){const e=(new TextEncoder).encode(s),n=i.map((e=>e.length));for(let t=0;t<e.length;t++)e[t]^=n[t%n.length];return window[i[n[2]]](String.fromCodePoint(...e))}const h=[1e3,2e3,4e3],p=h.length;function f(e,t=0){return n(this,void 0,void 0,(function*(){try{return yield e()}catch(n){if(t>=p)throw n;return yield new Promise((e=>setTimeout(e,h[t]))),f(e,t+1)}}))}const m=["Glasses","Shoes","Watches"],v=["Shoes"];let g;const w=new Uint8Array(16);function y(){if(!g&&(g="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(w)}const b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));var E={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function C(e,n,t){if(E.randomUUID&&!n&&!e)return E.randomUUID();const o=(e=e||{}).random||(e.rng||y)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,n){t=t||0;for(let e=0;e<16;++e)n[t+e]=o[e];return n}return function(e,n=0){return b[e[n+0]]+b[e[n+1]]+b[e[n+2]]+b[e[n+3]]+"-"+b[e[n+4]]+b[e[n+5]]+"-"+b[e[n+6]]+b[e[n+7]]+"-"+b[e[n+8]]+b[e[n+9]]+"-"+b[e[n+10]]+b[e[n+11]]+b[e[n+12]]+b[e[n+13]]+b[e[n+14]]+b[e[n+15]]}(o)}const S="0.0.7";let R=`https://cdn.jsdelivr.net/npm/shopar-plugin@${S}/dist`;const A={update:e=>{null!=e&&(R=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>R};function x(e){return n(this,void 0,void 0,(function*(){if("function"!=typeof importScripts){const n=document.createElement("script");return n.setAttribute("src",e),n.setAttribute("crossorigin","anonymous"),new Promise((e=>{n.addEventListener("load",(()=>e()),!1),n.addEventListener("error",(()=>e()),!1),document.body.appendChild(n)}))}importScripts(e.toString())}))}const k="qrLaunch",M="arLaunch",L="previewLaunch",$="heartbeat";let D,U,P=!1;const T=[];function I(e,n){const t=performance.now(),o=C();let r=0,i=0,a=0,s=0,l=0,c=!1;window.setInterval((()=>{c&&(r=i+a,c=!1,d($,{engagementTotal:r,engagementAR:i,engagement3D:a}))}),1e3);const d=(r,i={})=>{var a;i=Object.assign(Object.assign({},i),{pluginVersion:S,sessionId:U,setupId:o,timeSinceSetup:performance.now()-t,sku:e,apiKey:n}),a=()=>{window.ShopAR__analytics.trackEventImpl(r,i)},P?a():T.push(a)};return{trackEvent:d,arInteracted:()=>{const e=performance.now(),n=e-s;s=e,n<200&&(i+=n,c=!0)},previewInteracted:()=>{const e=performance.now(),n=e-l;l=e,n<200&&(a+=n,c=!0)}}}function j(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}function N(e){return n(this,void 0,void 0,(function*(){const n=document.createElement("video");return n.setAttribute("playsinline","playsinline"),n.srcObject=yield e,n}))}const O=200,_=10;let G,F,W,V,q=!1;function z(e){return n(this,void 0,void 0,(function*(){const o=yield f((()=>n(this,void 0,void 0,(function*(){const n=yield fetch(e).catch((e=>{throw console.error(e),new t("Resource unavailable.")}));if(!n.ok)throw new t(`Resource download failed with status ${n.status}.`);return n}))));try{return yield(yield o.blob()).arrayBuffer()}catch(e){throw console.error(e),new t("Resource has invalid body.")}}))}let B,H,K,X,Q,Z,Y,J=!0;function ee(e){e!==V&&(V=e,W=z(e),Z=null,null==B||B.clearEffect(),q=!0)}function ne(e,o,r){return n(this,void 0,void 0,(function*(){return K=r,X=e,null==Q&&(Q=(()=>n(this,void 0,void 0,(function*(){if(null==(null===(i=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new t("No camera available!");var i;const a=ie(r),s=j(a),l=function(e){const n={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:n[e]}(r);B=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:o||"your_license_key_goes_here",previewElement:e,additionalOptions:{hint:l,cameraConfig:{disableDefaultCamera:!0}}}),H=yield N(s),yield ae(B,H,"user"===a),"Glasses"===r&&(yield F,function(e,t){n(this,void 0,void 0,(function*(){q=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${A}/wasm/mediapipe`,e);const r=[],i=setInterval((()=>n(this,void 0,void 0,(function*(){if(q)return void clearInterval(i);const{error:e,faceWidth:n}=yield o.predict(performance.now());if(q)return void clearInterval(i);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(r.length<_)return void r.push(n);clearInterval(i);const a=137/(function(e){let n=0;const t=e.length;for(let o=0;o<t;o++)n+=e[o];return n/t}(r)+5);t.changeParameterVector("GLASSES","","scale",a,a,a,0),t.changeParameterVector("shopar_glasses","","scale",a,a,a,0)}))),O)}))}(H,B))})))()),Q}))}function te(e){B.callbacks.onFaceTracked=n=>{n.some((e=>e.detected))&&e()},B.callbacks.onFeetTracked=(n,t)=>{(n.detected||t.detected)&&e()},B.callbacks.onWristTracked=n=>{n.detected&&e()}}function oe(e){return n(this,void 0,void 0,(function*(){return null==Z&&(Z=B.switchEffect(e)),Z}))}function re(){null!=B&&(J=!0,B.setPaused(J),null!=H&&null!=H.srcObject&&H.srcObject instanceof MediaStream&&(H.srcObject.getTracks().forEach((e=>e.stop())),H=null),B.stopCamera(),X.style.display="none")}function ie(e){var n;return null==e?"user":null!==(n={Glasses:"user",Shoes:"environment",Watches:"environment"}[e])&&void 0!==n?n:"user"}function ae(e,t,o){return n(this,void 0,void 0,(function*(){yield new Promise((r=>{t.onloadedmetadata=()=>{t.play().then((()=>n(this,void 0,void 0,(function*(){e.setVideoElement(t,o),r()}))))}}))}))}const se={"loading.ar":"Loading Try On...","loading.3d":"Loading 3D..."},le=Object.keys(se);function ce(e){return se[e]}function de(e,n){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width",e),t.setAttribute("height",e);{const o=document.createElementNS("http://www.w3.org/2000/svg","image");o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n),o.setAttribute("width",e),o.setAttribute("height",e),t.appendChild(o)}return t}const ue="shopar-error";function he(e,n,t,o){const r=document.createElement("button");r.id=e,r.type="button",r.className="shopar-btn";{const e=de("1.75rem",o);r.appendChild(e)}{const e=document.createElement("span");e.textContent=n,r.appendChild(e)}r.ariaLabel=t;return r.style.display="none",r}const pe="shopar-control";const fe="shopar-deepar-output";function me(e){const n=document.createElement("div");n.className=e,n.classList.add("shopar-loading-container",e);const t=n.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",n}function ve(e,n){const t=document.createElement("div");return t.classList.add("shopar-loading-text",e),t.textContent=n,t.style.textAlign="center",t}function ge(e){const n=document.createElement("div");n.classList.add("shopar-loading-bar-bg",e);const t=n.style;return t.position="relative",t.overflow="hidden",n}function we(e){const n=document.createElement("div");n.classList.add("shopar-loading-bar-fg",e);const t=n.style;return t.width="100%",t.height="100%",n}const ye="shopar-main";const be="shopar-qr-output";const Ee="shopar-three-output";var Ce;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(Ce||(Ce={}));let Se,Re,Ae,xe,ke,Me,Le,$e,De,Ue,Pe,Te,Ie,je,Ne=Ce.None;function Oe(e){Ne=e}let _e,Ge=!1,Fe=null;function We(){if(Ge)return;!function(){try{const e=document.createElement("style"),n=process.env.css;null!=n&&(e.innerHTML=n);const t=document.head;t.insertBefore(e,t.children[0])}catch(e){console.warn("Failed to write default ShopAR Plugin CSS.")}}(),Se=function(){const e=document.createElement("div");e.id=ye;const n=e.style;return n.position="absolute",n.top="0",n.bottom="0",n.left="0",n.right="0",e}(),Ae=function(){const e=new Image,n=e.style;return n.maxWidth="100%",n.maxHeight="100%",e}(),Re=function(e){const n=document.createElement("div");n.id=be;const t=n.style;t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.display="none";const o=document.createElement("div");o.className="shopar-qr";const r=o.style;r.position="relative",r.top="0",r.left="0",r.width="100%",r.height="100%",n.appendChild(o);const i=document.createElement("div");i.innerText="Scan on mobile or tablet to try on",i.style.textAlign="center",o.appendChild(i);const a=document.createElement("div");return a.appendChild(e),o.appendChild(a),n}(Ae),Se.appendChild(Re),xe=function(){const e=document.createElement("div");e.id=fe;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none",e}(),Se.appendChild(xe),ke=function(){const e=document.createElement("canvas");e.id=Ee;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none",e}(),Se.appendChild(ke),Ue=me("shopar-ar-loading-container");const e=ve("shopar-ar-loading-text",ce("loading.ar"));Ue.appendChild(e);const n=ge("shopar-ar-loading-bar-bg");Pe=we("shopar-ar-loading-bar-fg"),n.appendChild(Pe),Ue.appendChild(n),Se.appendChild(Ue),Te=me("shopar-3d-loading-container");const t=ve("shopar-3d-loading-text",ce("loading.3d"));Te.appendChild(t);const o=ge("shopar-3d-loading-bar-bg");Ie=we("shopar-3d-loading-bar-fg"),o.appendChild(Ie),Te.appendChild(o),Se.appendChild(Te),je=function(){const e=document.createElement("div");e.id=ue;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.display="none";const t=document.createElement("div"),o=t.style;o.position="absolute",o.width="100%",o.height="100%",o.backgroundColor="#ffffff",o.display="flex",o.flexDirection="column",o.justifyContent="center",o.alignItems="center",e.appendChild(t);const r=de("4rem",`${A}/img/icons/close.svg`);t.appendChild(r);const i=document.createElement("div");i.className="shopar-error-title",i.textContent="Camera Error",t.appendChild(i);const a=document.createElement("div");return a.className="shopar-error-body",a.textContent="Please refresh the page and allow the use of camera.",t.appendChild(a),e}(),Se.appendChild(je),Me=function(){const e=document.createElement("div");return e.id=pe,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e.style.display="none",e}(),Se.appendChild(Me),Le=he("shopar-btn-vto","Try-on","Launch ShopAR virtual try-on","data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22/%3E"),Me.appendChild(Le),$e=he("shopar-btn-3d","3D","Launch ShopAR 3D preview",`${A}/img/icons/cube.svg`),Me.appendChild($e),De=he("shopar-btn-close","Close","Close ShopAR view",`${A}/img/icons/close.svg`),Me.append(De),Ge=!0}function Ve(e,n,t,o){var r;qe(Me,e),qe(Le,e&&(t||n)&&Ne===Ce.None),qe($e,e&&o&&Ne===Ce.None),qe(De,e&&Ne!==Ce.None),ze(),He(),e||""===(r=je).style.display&&qe(r,!1)}function qe(e,n){e.style.display=n?"":"none"}function ze(){Pe.classList.remove("active"),Ue.style.visibility="hidden"}function Be(){Ie.classList.add("active"),Te.style.visibility="visible"}function He(){Ie.classList.remove("active"),Te.style.visibility="hidden"}let Ke,Xe,Qe,Ze,Ye,Je=!0;function en(e,t){return n(this,void 0,void 0,(function*(){yield _e;const n=`https://apps.deepar.ai/${S.includes("alpha")?"shopar-qr-alpha":"shopar-qr"}/?${new URLSearchParams({a:e,s:t,h:location.href})}`,o=yield window.ShopAR__QR.toDataURL(n),r=Ae,i=new Promise(((e,n)=>{r.onload=e,r.onerror=n}));r.src=o,yield i,Je=!1,Re.style.display=""}))}function nn(){Je=!0,Re.style.display="none"}let tn,on,rn,an,sn,ln,cn,dn,un,hn,pn,fn,mn,vn,gn,wn,yn,bn=!1,En=!1;const Cn=25,Sn=5,Rn=40,An=45,xn=45,kn=3,Mn=0,Ln=1.5,$n=1,Dn=.5;let Un,Pn;function Tn(e){if(e!==Qe){const r=255;Qe=e,Xe=function(e,r,i){return n(this,void 0,void 0,(function*(){let a="glb".charCodeAt(0),s="3d".charCodeAt(0);a>>=1,a+=s;const l=String.fromCharCode(a+14);s>>=2,a^=s+2;const u=String.fromCharCode(a-3);a^=5;const h=String.fromCharCode(a-7);a^=2;const p=String.fromCharCode(a-7),m=window[`${h}${u+l+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${p}`],v=yield f((()=>n(this,void 0,void 0,(function*(){const n=yield m(`${e}`).catch((()=>{throw new t("Unknown error.")}));if(!n.ok)throw new t("Unknown error.");return n})))),g=new o[0](yield(yield v.blob().catch((()=>{throw new t("Unknown error.")}))).arrayBuffer().catch((()=>{throw new t("Unknown error.")})));i+=s;const w=g.byteLength;if(d[c]=Math.min(76,r)*((a>>5)-1),152===d[c]&&(d[c]=w),i==c)return g;i=c,i^=c;for(let e=0,n=g.length;e<n;e++)d[c]^=d[i]<<13,d[c]^=d[i]>>17,d[c]^=d[i]<<5,g[e]=g[e]^d[c];return i^=d[0],i^=d[1],i^=d[2],g}))}(e,(new Date).getTime()+r,Math.random()*r),Un=null,null==mn||mn.clear()}}function In(e){wn.removeEventListener("change",Pn),Pn=e,wn.addEventListener("change",e)}function jn(e,t){return n(this,void 0,void 0,(function*(){return null==Un&&(Un=(()=>n(this,void 0,void 0,(function*(){const n=new on.RGBELoader,o=function(e,n){const t=e.THREE,o=new t.DataTexture(n.data,n.width,n.height,void 0,n.type,void 0,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearFilter,1,t.LinearEncoding);return o.flipY=!0,o.generateMipmaps=!1,o.needsUpdate=!0,o}(on,n.parse(t));o.mapping=rn.EquirectangularReflectionMapping,o.encoding=rn.LinearEncoding,mn.environment=o;const r=(new on.GLTFLoader).setDRACOLoader((new on.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${rn.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new on.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${rn.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(an)).setMeshoptDecoder("function"==typeof on.MeshoptDecoder?on.MeshoptDecoder():on.MeshoptDecoder);return yield r.parseAsync(e.buffer,"")})))()),Un}))}function Nn(e,n){mn.add(e.scene);const t=(new rn.Box3).setFromObject(e.scene);sn.position.y=t.min.y-Mn,mn.add(sn),mn.traverse((e=>{if(e instanceof rn.Mesh){const n=e.material;n.depthWrite=!0,n instanceof rn.MeshPhysicalMaterial&&n.transmissionMap&&(n.transmission=1,n.toneMapped=!1,n.fog=!1,n.needsUpdate=!0)}})),wn.fov=Cn;const o=on.reduceVertices,r=t.min.clone().add(t.max).divideScalar(2);wn.target.set(r.x,r.y,r.z),wn.panSphereCenter.set(r.x,r.y,r.z);const i=Math.sqrt(o(e.scene,((e,n)=>Math.max(e,r.distanceToSquared(n))),0));yn=i/Math.sin(Cn/2*rn.MathUtils.DEG2RAD),wn.panSphereRadius=Math.min(i,yn-i);const a=r.clone().addScaledVector(function(e){var n;const t={Glasses:new rn.Vector3(67.5,15,90),Shoes:new rn.Vector3(-55,30,30),Watches:new rn.Vector3(0,-10,40),Handbags:new rn.Vector3(40,0,0),Rings:new rn.Vector3(0,0,10)},o=null==e?t.Glasses:null!==(n=t[e])&&void 0!==n?n:t.Glasses;return o.normalize()}(n),yn);vn.position.set(a.x,a.y,a.z)}function On(){bn=!0,null!=tn&&(tn.style.display="none")}function _n(){if(bn)return;requestAnimationFrame(_n),wn.update(),Gn(),vn.fov=vn.aspect<1?2*Math.atan(Math.tan(wn.fov/2*rn.MathUtils.DEG2RAD)/vn.aspect)*rn.MathUtils.RAD2DEG:wn.fov,vn.updateProjectionMatrix();const e=mn.background;mn.background=null,mn.overrideMaterial=hn;const n=an.getClearAlpha();an.setClearAlpha(0),an.setRenderTarget(ln),an.render(mn,gn),mn.overrideMaterial=null,Fn(Ln),Fn(.4*Ln),an.setRenderTarget(null),an.setClearAlpha(n),mn.background=e,an.render(mn,vn)}function Gn(){const e=tn.clientWidth,n=tn.clientHeight;tn.width===e&&tn.height===n||(an.setSize(e,n,!1),vn.aspect=e/n)}function Fn(e){un.visible=!0,pn.uniforms.tDiffuse.value=ln.texture,pn.uniforms.h.value=1*e/256,un.material=pn,an.setRenderTarget(cn),an.render(un,gn),fn.uniforms.tDiffuse.value=cn.texture,fn.uniforms.v.value=1*e/256,un.material=fn,an.setRenderTarget(ln),an.render(un,gn),un.visible=!1}function Wn(e,n){if(null==e)throw new t(`'${n}' not specified.`)}function Vn(e,n){if("string"!=typeof e)throw new t(`'${n}' must be a string.`)}const qn=["AR","3D"];function zn(e){const{apiKey:n,sku:o,targetElement:r,initialState:i,baseUrl:a,defaultUI:s,strings:l}=e;Wn(n,"apiKey"),Vn(n,"apiKey"),Wn(o,"sku"),Vn(o,"sku"),Wn(r,"targetElement"),function(e,n){if(!(e instanceof HTMLElement))throw new t(`'${n}' must be an HTMLElement.`)}(r,"targetElement"),null!=i&&function(e,n,o){if("string"!=typeof e)throw new t(`'${n}' must be a string.`);if(!o.includes(e))throw new t(`'${n}' must be ${o.join("' or '")}.`)}(i,"initialState",qn),null!=a&&Vn(a,"baseUrl"),null!=s&&function(e,n){if("boolean"!=typeof e)throw new t(`'${n}' must be a boolean.`)}(s,"defaultUI"),null!=l&&function(e,n,o){for(const r of o){const o=e[r];if(null!=o&&"string"!=typeof o)throw new t(`Value for key '${r}' in '${n}' must be a string.`)}}(l,"strings",le)}let Bn=0,Hn=0;function Kn(e){var o,r;return n(this,void 0,void 0,(function*(){zn(e);const{apiKey:i,sku:a,targetElement:s,initialState:l}=e;!function(e){const n=getComputedStyle(e);if(!["static","relative"].includes(n.position))throw new t(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${n.position}'.`)}(s),A.update(e.baseUrl),function(e){if(null!=e)for(const n of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(se,n)){console.warn(`String for key '${n}' will be ignored.`);continue}const t=e[n];null!=t&&(se[n]=t)}}(e.strings);const c=function(e,o){return n(this,void 0,void 0,(function*(){const r=yield f((()=>n(this,void 0,void 0,(function*(){const n=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:e,sku:o,sid:u()})}`).catch((e=>{throw console.error(e),new t("API unavailable.")}));if(!n.ok)throw new t(`API call failed with status ${n.status}.`);return n}))));try{return yield r.json()}catch(e){throw console.error(e),new t("API returned invalid body.")}}))}(i,a);null==D&&(U=C(),D=x(`${A}/shopar-analytics.js`),D.then((()=>{P=!0,window.ShopAR__analytics.initializeImpl(),T.forEach((e=>e()))})));const{trackEvent:d,arInteracted:h,previewInteracted:p}=I(a,i);d("setup",{hostname:window.location.hostname}),We();const g=++Hn,w=yield c;d("apiResponse",w);const{category:y,arUrl:b,arKey:E,previewUrl:S,previewEnvUrl:R}=w;Xn(g);const $=null!=b&&function(e){return null!=e&&m.includes(e)}(y),O=null==(null===(o=e._internalOptions)||void 0===o?void 0:o.qrEnabled)||(null===(r=e._internalOptions)||void 0===r?void 0:r.qrEnabled),_=$&&function(e){return null!=e&&v.includes(e)}(y),V=O&&_&&!(yield function(){var e;return n(this,void 0,void 0,(function*(){return null==Y&&(Y=x(`${A}/shopar-platform.js`)),yield Y,["Android","iOS","Windows Phone",void 0].includes(null===(e=window.ShopAR__platform.platform.os)||void 0===e?void 0:e.family)}))}());Xn(g),V&&function(){n(this,void 0,void 0,(function*(){null==_e&&(_e=x(`${A}/shopar-qr.js`))}))}();const q=$&&!V;q&&(null==G&&(G=x(`${A}/shopar-deepar.js`)),ee(b),"Glasses"===y&&null==F&&(F=x(`${A}/shopar-true-scale.js`)));const Q=null!=S;var Z;Q&&(null==Ke&&(Ke=x(`${A}/shopar-three.js`)),Tn(S),(Z=null!=R?R:`${A}/env/default.hdr`)!==Ye&&(Ye=Z,Ze=z(Z))),function(e){e.style.position="relative",null==Fe?e.appendChild(Se):e!==Fe&&(Fe.removeChild(Se),e.appendChild(Se)),Fe=e}(s);const le=null==e.defaultUI||e.defaultUI;if(Ve(le,V,q,Q),Ne===Ce.AR){if(!J)if(te(h),q){d(M);const e=yield W;Xn(g),yield oe(e),Xn(g)}else re(),Oe(Ce.None),le&&(qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0));if(!Je)if(V){d(k);try{yield en(i,a)}catch(e){throw new t(`QR failed: ${e instanceof Error?e.message:"Unknown error."}`)}}else nn(),Oe(Ce.None),le&&(qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0))}else if(Ne===Ce.Preview&&!bn)if(In(p),Q){d(L),Be(),qe(ke,!1);const e=yield Xe;Xn(g);const n=yield Ze;Xn(g);const t=yield jn(e,n);Xn(g),Nn(t,y),qe(ke,!0),He()}else On(),Oe(Ce.None),le&&(qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0));const ce=()=>n(this,void 0,void 0,(function*(){if(V){if(Ne===Ce.AR)throw new t("AR already launched.");try{d(k);++Bn;return Ne===Ce.Preview&&Q&&!bn&&On(),Oe(Ce.AR),le&&(qe(Le,!1),qe($e,!1),qe(De,!0)),le&&qe(je,!1),void(yield en(i,a))}catch(e){const n=e instanceof Error;throw d("qrLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),new t(`QR failed: ${n?e.message:"Unknown error."}`)}}if(!q)throw new t("Model does not have AR enabled.");if(Ne===Ce.AR)throw new t("AR already launched.");try{d(M);const e=++Bn;Ne===Ce.Preview&&Q&&!bn&&On(),Oe(Ce.AR),le&&(qe(Le,!1),qe($e,!1),qe(De,!0)),le&&qe(je,!1),Pe.classList.add("active"),Ue.style.visibility="visible";const t=yield W;if(Bn!==e||Hn!==g)return;if(yield G,Bn!==e||Hn!==g)return;if(yield ne(xe,E,y),Bn!==e||Hn!==g)return;if(te(h),yield oe(t),Bn!==e||Hn!==g)return;if(yield function(){return n(this,void 0,void 0,(function*(){if(null!=B){if(J=!1,null==H){const e=ie(K),n=j(e);H=yield N(n),yield ae(B,H,"user"===e)}B.setPaused(J),X.style.display=""}}))}(),Bn!==e||Hn!==g)return}catch(e){const n=e instanceof Error;throw d("arLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),le&&qe(je,!0),re(),new t(`AR failed: ${n?e.message:"Unknown error."}`)}finally{ze()}})),de=()=>n(this,void 0,void 0,(function*(){if(!Q)throw new t("Model does not have 3D enabled.");if(Ne===Ce.Preview)throw new t("3D already launched.");try{d(L);const e=++Bn;Ne===Ce.AR&&(q&&!J&&re(),nn()),Oe(Ce.Preview),le&&(qe(Le,!1),qe($e,!1),qe(De,!0)),le&&qe(je,!1),Be();const t=yield Xe;if(Bn!==e||Hn!==g)return;const o=yield Ze;if(Bn!==e||Hn!==g)return;if(yield Ke,Bn!==e||Hn!==g)return;if(yield function(e){return n(this,void 0,void 0,(function*(){if(tn=e,!En){on=window.ShopAR__THREE,rn=on.THREE,an=new rn.WebGLRenderer({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0}),an.outputEncoding=rn.sRGBEncoding,an.toneMapping=rn.ACESFilmicToneMapping,an.setPixelRatio(window.devicePixelRatio||1),an.setClearColor(new rn.Color(16777215)),mn=new rn.Scene,sn=new rn.Group,sn.position.y=-.7,ln=new rn.WebGLRenderTarget(512,512),ln.texture.generateMipmaps=!1,cn=new rn.WebGLRenderTarget(512,512),cn.texture.generateMipmaps=!1;const n=new rn.PlaneGeometry(An,xn).rotateX(Math.PI/2),t=new rn.MeshBasicMaterial({map:ln.texture,opacity:Dn,transparent:!0,depthWrite:!1});dn=new rn.Mesh(n,t),dn.renderOrder=1,sn.add(dn),dn.scale.y=-1,un=new rn.Mesh(n),un.visible=!1,sn.add(un),gn=new rn.OrthographicCamera(-An/2,An/2,xn/2,-xn/2,0,kn),gn.rotation.x=Math.PI/2,sn.add(gn),hn=new rn.MeshDepthMaterial,hn.userData.darkness={value:$n},hn.onBeforeCompile=function(e){e.uniforms.darkness=hn.userData.darkness,e.fragmentShader=`\n uniform float darkness;\n ${e.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );")}\n `},hn.depthTest=!1,hn.depthWrite=!1,pn=new rn.ShaderMaterial(on.HorizontalBlurShader),pn.depthTest=!1,fn=new rn.ShaderMaterial(on.VerticalBlurShader),fn.depthTest=!1,vn=new rn.PerspectiveCamera(25,1,.5),wn=new on.OrbitControls(vn,an.domElement),wn.minFov=Sn,wn.maxFov=Rn,wn.enableDamping=!0,wn.dampingFactor=.3,wn.zoomSpeed=3,wn.panSpeed=.5,wn.rotateSpeed=.5,En=!0}Gn()}))}(ke),Bn!==e||Hn!==g)return;In(p);const r=yield jn(t,o);if(Bn!==e||Hn!==g)return;Nn(r,y),bn=!1,_n(),null!=tn&&(tn.style.display="")}catch(e){const n=e instanceof Error;throw d("previewLaunchFailure",{errorName:n?e.name:"Unknown",errorMessage:n?e.message:""}),new t(`3D failed: ${n?e.message:"Unknown error."}`)}finally{He()}})),ue=()=>n(this,void 0,void 0,(function*(){if(Ne===Ce.None)throw new t("Neither AR or 3D launched.");++Bn,Ne===Ce.AR?(q&&!J&&re(),nn()):Ne===Ce.Preview&&Q&&!bn&&On(),Oe(Ce.None),ze(),He(),le&&(qe(je,!1),qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0))}));return le&&((V||q)&&(!function(e){const n={Glasses:"glasses.svg",Shoes:"shoe.svg",Watches:"watch.svg"},t=`${A}/img/icons/${null!=e&&n[e]||n.Glasses}`;Le.firstChild.firstChild.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t)}(y),Le.onclick=ce),Q&&($e.onclick=de),De.onclick=ue),"AR"===l?(yield ce(),Xn(g)):"3D"===l&&(yield de(),Xn(g)),{launchAR:ce,launch3D:de,closeAR:()=>n(this,void 0,void 0,(function*(){if(Ne!==Ce.AR)throw new t("AR not launched.");++Bn,q&&!J&&re(),nn(),Oe(Ce.None),ze(),le&&(qe(je,!1),qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0))})),close3D:()=>n(this,void 0,void 0,(function*(){if(Ne!==Ce.Preview)throw new t("3D not launched.");++Bn,Q&&!bn&&On(),Oe(Ce.None),He(),le&&(qe(je,!1),qe(De,!1),(V||q)&&qe(Le,!0),Q&&qe($e,!0))})),close:ue}}))}function Xn(e){if(Hn!==e)throw new t("Setup cancelled. Please ensure that setup is only called once.")}const Qn={setup:function(e){return n(this,void 0,void 0,(function*(){return function(e,o){return n(this,void 0,void 0,(function*(){try{return o()}catch(n){throw n instanceof Error?new t(`${e} failed: ${n.message}`):(console.error(n),new t(`${e} failed.`))}}))}("setup",(()=>Kn(e)))}))},version:S};e.plugin=Qn}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ShopAR={})}(this,(function(e){"use strict";function t(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((o=o.apply(e,t||[])).next())}))}!function(){const e={css:".shopar-btn-container{position:absolute;width:100%;bottom:0;padding-bottom:2rem;display:flex;justify-content:center;gap:.5rem;pointer-events:none}.shopar-btn{padding:.5rem .75rem;display:flex;justify-content:center;align-items:center;gap:.25rem;background-color:#fff;border:1px solid #ddd;border-radius:9999px;cursor:pointer;pointer-events:auto}.shopar-btn:hover{background-color:#f5f5f5}.shopar-loading-container{display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1rem;background-color:#fff}.shopar-loading-text{text-align:center}.shopar-loading-bar-bg{width:80%;height:.5rem;background-color:#e5e7eb;border-radius:9999px}.shopar-loading-bar-fg{background-color:#1434f7;border-radius:9999px;transition:none;transform:translateX(-100%);will-change:transform}.shopar-loading-bar-fg.active{transition:transform 5s cubic-bezier(0,0,.2,1);transform:none}.shopar-qr{display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:#fff}"};try{if(process)return process.env=Object.assign({},process.env),void Object.assign(process.env,e)}catch(e){}globalThis.process={env:e}}(),"function"==typeof SuppressedError&&SuppressedError;class n extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}const o=[Uint8Array,Uint32Array],r=o.length-2,i=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],a=[2,12,7,1],s=window[i[a[a[r]]]][i[a[a[a.length-1]]]],c=s.charCodeAt(r),l=c^c,d=new o[1]([l]);function u(){const e=(new TextEncoder).encode(s),t=i.map((e=>e.length));for(let n=0;n<e.length;n++)e[n]^=t[n%t.length];return window[i[t[2]]](String.fromCodePoint(...e))}const h=[1e3,2e3,4e3],p=h.length;function f(e,n=0){return t(this,void 0,void 0,(function*(){try{return yield e()}catch(t){if(n>=p)throw t;return yield new Promise((e=>setTimeout(e,h[n]))),f(e,n+1)}}))}const g=["Glasses","Shoes","Watches"],m=["Shoes"];const v="0.0.8-alpha.0";let w=`https://cdn.jsdelivr.net/npm/shopar-plugin@${v}/dist`;const y={update:e=>{null!=e&&(w=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>w};function b(e){return t(this,void 0,void 0,(function*(){if("function"!=typeof importScripts){const t=document.createElement("script");return t.setAttribute("src",e),t.setAttribute("crossorigin","anonymous"),new Promise((e=>{t.addEventListener("load",(()=>e()),!1),t.addEventListener("error",(()=>e()),!1),document.body.appendChild(t)}))}importScripts(e.toString())}))}let R;const S=(()=>{const e=(()=>{var e;if(null===(e=document.documentElement.getAttribute("itemtype"))||void 0===e?void 0:e.includes("schema.org/SearchResultsPage"))return!0;const t=null!=document.head?Array.from(document.head.querySelectorAll("meta")):[];for(const e of t)if("viewport"===e.name)return!0;return!1})();return e||console.warn('No <meta name="viewport"> detected; ShopAR will cap pixel density at 1.'),()=>e?window.devicePixelRatio:1})();let E,A,C;function T(e){const t=function(e){const t=new A.DataTexture(e.data,e.width,e.height,void 0,e.type,void 0,A.ClampToEdgeWrapping,A.ClampToEdgeWrapping,A.LinearFilter,A.LinearFilter,1,A.LinearEncoding);return t.flipY=!0,t.generateMipmaps=!1,t.needsUpdate=!0,t}(C.parse(e));return t.mapping=A.EquirectangularReflectionMapping,t.encoding=A.LinearEncoding,t}const I=45,L=45,k=3,P=1.5,x=1,M=.5;let U,D,$,_,N,j,O=!1;const q=0;let G,W,Q,F=!1,V=1,H=1,B=1;const K=1;let z;const X=new Map;function Z(e){const n=e.getContext("2d");null==n&&console.warn("2D context missing.");let o,r,i,a,s,c,l,d=!1,u=!0,h=!1,p=1,f=1,g=1;const m={threeInit:()=>{d||(Y(),o=new W.Scene,r=new W.PerspectiveCamera(25,1,.5),i=new G.OrbitControls(r,e),i.enableInteraction(),({renderShadow:s,shadowGroup:a}=function(e){const t=new U.WebGLRenderTarget(512,512);t.texture.generateMipmaps=!1;const n=new U.WebGLRenderTarget(512,512);n.texture.generateMipmaps=!1;const o=new U.Group;o.position.y=-.7;const r=new U.PlaneGeometry(I,L).rotateX(Math.PI/2),i=new U.MeshBasicMaterial({map:t.texture,opacity:M,transparent:!0,depthWrite:!1}),a=new U.Mesh(r,i);a.renderOrder=1,a.scale.y=-1,o.add(a);const s=new U.Mesh(r);s.visible=!1,o.add(s);const c=new U.OrthographicCamera(-I/2,I/2,L/2,-L/2,0,k);function l(e){s.visible=!0,_.uniforms.tDiffuse.value=t.texture,_.uniforms.h.value=1*e/256,s.material=_,D.setRenderTarget(n),D.render(s,c),N.uniforms.tDiffuse.value=n.texture,N.uniforms.v.value=1*e/256,s.material=N,D.setRenderTarget(t),D.render(s,c),s.visible=!1}return c.rotation.x=Math.PI/2,o.add(c),{shadowGroup:o,renderShadow:()=>{const n=e.background;e.background=null,e.overrideMaterial=$;const o=D.getClearAlpha();D.setClearAlpha(0),D.setRenderTarget(t),D.render(e,c),e.overrideMaterial=null,l(P),l(.4*P),D.setRenderTarget(null),D.setClearAlpha(o),e.background=n}}}(o)),d=!0)},threeParse:(e,n)=>(null==c&&(c=(()=>t(this,void 0,void 0,(function*(){var t,r;return A=(t=G).THREE,C=new t.RGBELoader,o.environment=T(n),function(e,t){const{THREE:n}=t;E=(new t.GLTFLoader).setDRACOLoader((new t.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${n.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new t.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${n.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(e)).setMeshoptDecoder("function"==typeof t.MeshoptDecoder?t.MeshoptDecoder():t.MeshoptDecoder)}(z,G),r=e,E.parseAsync(r.buffer,"")})))()),c),threeLoad:(e,t)=>{o.clear(),o.add(e.scene);const n=(new W.Box3).setFromObject(e.scene);a.position.y=n.min.y-q,o.add(a),s(),o.traverse((e=>{if(e instanceof W.Mesh){const t=e.material;t.depthWrite=!0,t instanceof W.MeshPhysicalMaterial&&t.transmissionMap&&(t.transmission=1,t.toneMapped=!1,t.fog=!1,t.needsUpdate=!0)}}));const r=n.min.clone().add(n.max).divideScalar(2),c=Math.sqrt(G.reduceVertices(e.scene,((e,t)=>Math.max(e,r.distanceToSquared(t))),0));i.reset(r,c,function(e,t){var n;const o={Glasses:new t(67.5,15,90),Shoes:new t(-55,30,30),Watches:new t(0,-10,40),Handbags:new t(40,0,0),Rings:new t(0,0,10)};return(null==e?o.Glasses:null!==(n=o[e])&&void 0!==n?n:o.Glasses).normalize()}(t,W.Vector3))},threePaused:()=>u,threeResume:()=>{u=!1,z.setAnimationLoop(J),e.style.visibility="visible"},threePause:()=>{u=!0,function(){for(const{threePaused:e}of X.values())if(!e())return!1;return!0}()&&z.setAnimationLoop(null),e.style.visibility="hidden"},threeSetOnInteracted:e=>{i.removeEventListener("change",l),l=e,i.addEventListener("change",e)},preRender_:()=>{d&&!u&&i.update()&&(h=!0)},shouldRender_:()=>!(!d||u)&&h,render_:()=>{z.setViewport(0,0,e.width,e.height),z.render(o,r),h=!1,null!=n&&(n.clearRect(0,0,e.width,e.height),n.drawImage(Q,0,H-e.height,e.width,e.height,0,0,e.width,e.height))},updateSize_:()=>{const{clientWidth:t,clientHeight:n}=e;t===p&&n===f&&B===g||(e.width=Math.ceil(t*B*K),e.height=Math.ceil(n*B*K),p=t,f=n,g=B,h=!0)},target_:e};return X.set(e,m),m}function Y(){if(F)return;G=window.ShopAR__THREE,W=G.THREE,Q=document.createElement("canvas");var e,t;Q.style.position="block",z=new W.WebGLRenderer({powerPreference:"high-performance",canvas:Q,antialias:!0,alpha:!0}),z.outputEncoding=W.sRGBEncoding,z.toneMapping=W.ACESFilmicToneMapping,z.setClearColor(new W.Color(16777215)),e=z,t=G,O||(U=t.THREE,D=e,$=new U.MeshDepthMaterial,$.userData.darkness={value:x},$.onBeforeCompile=e=>{e.uniforms.darkness=$.userData.darkness;const t=e.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );");e.fragmentShader=`uniform float darkness;\n${t}`},$.depthTest=!1,$.depthWrite=!1,_=new U.ShaderMaterial(t.HorizontalBlurShader),_.depthTest=!1,N=new U.ShaderMaterial(t.VerticalBlurShader),N.depthTest=!1,O=!0),ee(),F=!0}function J(){ee(),z.clear();for(const{preRender_:e,shouldRender_:t,render_:n}of X.values())e(),t()&&n()}function ee(){let e=0,t=0;for(const{target_:n}of X.values()){const{clientWidth:o,clientHeight:r}=n;e=Math.max(e,o),t=Math.max(t,r)}const n=S();e=Math.ceil(e*n*K),t=Math.ceil(t*n*K),e===V&&t===H&&n===B||(V=e,H=t,B=n,z.setSize(V,H,!1));for(const{updateSize_:e}of X.values())e()}const te={"loading.ar":"Loading Try On...","loading.3d":"Loading 3D..."},ne=Object.keys(te);function oe(e){return te[e]}function re(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("width",e),n.setAttribute("height",e);{const o=document.createElementNS("http://www.w3.org/2000/svg","image");o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),o.setAttribute("width",e),o.setAttribute("height",e),n.appendChild(o)}return n}const ie="shopar-error";function ae(e,t,n,o){const r=document.createElement("button");r.id=e,r.type="button",r.className="shopar-btn";{const e=re("1.75rem",o);r.appendChild(e)}{const e=document.createElement("span");e.textContent=t,r.appendChild(e)}r.ariaLabel=n;return r.style.display="none",r}const se="shopar-control";const ce="shopar-deepar-output";function le(e){const t=document.createElement("div");t.className=e,t.classList.add("shopar-loading-container",e);const n=t.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",t}function de(e,t){const n=document.createElement("div");return n.classList.add("shopar-loading-text",e),n.textContent=t,n.style.textAlign="center",n}function ue(e){const t=document.createElement("div");t.classList.add("shopar-loading-bar-bg",e);const n=t.style;return n.position="relative",n.overflow="hidden",t}function he(e){const t=document.createElement("div");t.classList.add("shopar-loading-bar-fg",e);const n=t.style;return n.width="100%",n.height="100%",t}const pe="shopar-main";const fe="shopar-qr-output";const ge="shopar-three-output";var me;!function(e){e[e.None=0]="None",e[e.QR=1]="QR",e[e.AR=2]="AR",e[e.Preview=3]="Preview"}(me||(me={}));let ve=!1;function we(){ve||(!function(){try{const e=document.createElement("style"),t=process.env.css;null!=t&&(e.innerHTML=t);const n=document.head;n.insertBefore(e,n.children[0])}catch(e){console.warn("Failed to write default ShopAR Plugin CSS.")}}(),ve=!0)}function ye(){we();const e=function(){const e=document.createElement("div");e.id=pe;const t=e.style;return t.position="absolute",t.top="0",t.bottom="0",t.left="0",t.right="0",e}(),t=function(){const e=new Image,t=e.style;return t.maxWidth="100%",t.maxHeight="100%",e}(),n=function(e){const t=document.createElement("div");t.id=fe;const n=t.style;n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.display="none";const o=document.createElement("div");o.className="shopar-qr";const r=o.style;r.position="relative",r.top="0",r.left="0",r.width="100%",r.height="100%",t.appendChild(o);const i=document.createElement("div");i.innerText="Scan on mobile or tablet to try on",i.style.textAlign="center",o.appendChild(i);const a=document.createElement("div");return a.appendChild(e),o.appendChild(a),t}(t);e.appendChild(n);const o=function(){const e=document.createElement("div");e.id=ce;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.display="none",e}();e.appendChild(o);const r=function(){const e=document.createElement("canvas");e.id=ge;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.visibility="hidden",e}();e.appendChild(r);const i=le("shopar-ar-loading-container"),a=de("shopar-ar-loading-text",oe("loading.ar"));i.appendChild(a);const s=ue("shopar-ar-loading-bar-bg"),c=he("shopar-ar-loading-bar-fg");s.appendChild(c),i.appendChild(s),e.appendChild(i);const l=le("shopar-3d-loading-container"),d=de("shopar-3d-loading-text",oe("loading.3d"));l.appendChild(d);const u=ue("shopar-3d-loading-bar-bg"),h=he("shopar-3d-loading-bar-fg");u.appendChild(h),l.appendChild(u),e.appendChild(l);const p=function(){const e=document.createElement("div");e.id=ie;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.display="none";const n=document.createElement("div"),o=n.style;o.position="absolute",o.width="100%",o.height="100%",o.backgroundColor="#ffffff",o.display="flex",o.flexDirection="column",o.justifyContent="center",o.alignItems="center",e.appendChild(n);const r=re("4rem",`${y}/img/icons/close.svg`);n.appendChild(r);const i=document.createElement("div");i.className="shopar-error-title",i.textContent="Camera Error",n.appendChild(i);const a=document.createElement("div");return a.className="shopar-error-body",a.textContent="Please refresh the page and allow the use of camera.",n.appendChild(a),e}();e.appendChild(p);const f=function(){const e=document.createElement("div");return e.id=se,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e.style.display="none",e}();e.appendChild(f);const g=ae("shopar-btn-vto","Try-on","Launch ShopAR virtual try-on","data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22/%3E");f.appendChild(g);const m=ae("shopar-btn-3d","3D","Launch ShopAR 3D preview",`${y}/img/icons/cube.svg`);f.appendChild(m);const v=ae("shopar-btn-close","Close","Close ShopAR view",`${y}/img/icons/close.svg`);f.append(v);let w,b=me.None,R=!1,S=!1,E=!1,A=!1;function C(){c.classList.remove("active"),i.style.visibility="hidden"}function T(){h.classList.remove("active"),l.style.visibility="hidden"}return{setTargetElement:function(t){t.style.position="relative",t.appendChild(e)},getQRTarget:function(){return n},getQRImage:function(){return t},getDeepARTarget:function(){return o},getThreeTarget:function(){return r},setVisibilityParameters:function(e,t,n,o,r){var i;R=e,S=t,E=n,A=o,w=r,be(f,R),be(g,R&&(E||S)&&b===me.None),be(m,R&&A&&b===me.None),be(v,R&&b!==me.None),C(),T(),R||""===(i=p).style.display&&be(i,!1)},getUIState:function(){return b},setUIState:function(e){b=e,b===me.None?(C(),T(),R&&(be(p,!1),be(v,!1),(S||E)&&be(g,!0),A&&be(m,!0))):b!==me.QR&&b!==me.AR&&b!==me.Preview||R&&(be(p,!1),be(g,!1),be(m,!1),be(v,!0))},setDefaultUIActions:function(e,t,n){R&&((S||E)&&(!function(e){const t={Glasses:"glasses.svg",Shoes:"shoe.svg",Watches:"watch.svg"},n=null!=e&&t[e]||t.Glasses,o=`${y}/img/icons/${n}`;g.firstChild.firstChild.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o)}(w),g.onclick=e),A&&(m.onclick=t),v.onclick=n)},startDeepARLoading:function(){c.classList.add("active"),i.style.visibility="visible"},stopDeepARLoading:C,startThreeLoading:function(){h.classList.add("active"),l.style.visibility="visible"},stopThreeLoading:T,showCameraError:function(){R&&be(p,!0)}}}function be(e,t){e.style.display=t?"":"none"}const Re=new Map;function Se(e){let n=Re.get(e);return null==n?(n=function(){let e=0,n=null,o=null,r=null;const i=()=>(null==n&&(n=ye()),n);return{getSetupId:()=>e,incrementSetupId_:()=>e++,getUI_:()=>n,findUI:i,findQR:()=>{if(null==o){const{getQRTarget:e,getQRImage:n}=i();o=function(e,n){let o=!0;return{qrPaused:()=>o,qrDraw:(r,i)=>t(this,void 0,void 0,(function*(){yield R;const t=`https://apps.deepar.ai/${v.includes("alpha")?"shopar-qr-alpha":"shopar-qr"}/?${new URLSearchParams({a:r,s:i,h:location.href})}`,a=yield window.ShopAR__QR.toDataURL(t),s=new Promise(((e,t)=>{n.onload=e,n.onerror=t}));n.src=a,yield s,o=!1,e.style.display=""})),qrPause:()=>t(this,void 0,void 0,(function*(){o=!0,e.style.display="none"}))}}(e(),n())}return o},findThree:()=>{if(null==r){const{getThreeTarget:e}=i();r=Z(e())}return r}}}(),Re.set(e,n)):n.incrementSetupId_(),n}function Ee(e){for(const t of Re.values()){if(t===e)continue;const n=t.getUI_();if(null==n)continue;const{getUIState:o,setUIState:r}=n;o()===me.AR&&r(me.None)}}let Ae;const Ce=new Uint8Array(16);function Te(){if(!Ae&&(Ae="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ae))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ae(Ce)}const Ie=[];for(let e=0;e<256;++e)Ie.push((e+256).toString(16).slice(1));var Le={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ke(e,t,n){if(Le.randomUUID&&!t&&!e)return Le.randomUUID();const o=(e=e||{}).random||(e.rng||Te)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=o[e];return t}return function(e,t=0){return Ie[e[t+0]]+Ie[e[t+1]]+Ie[e[t+2]]+Ie[e[t+3]]+"-"+Ie[e[t+4]]+Ie[e[t+5]]+"-"+Ie[e[t+6]]+Ie[e[t+7]]+"-"+Ie[e[t+8]]+Ie[e[t+9]]+"-"+Ie[e[t+10]]+Ie[e[t+11]]+Ie[e[t+12]]+Ie[e[t+13]]+Ie[e[t+14]]+Ie[e[t+15]]}(o)}const Pe="qrLaunch",xe="arLaunch",Me="previewLaunch",Ue="heartbeat";let De,$e,_e=!1;const Ne=[];function je(e,t){const n=performance.now(),o=ke();let r=0,i=0,a=0,s=0,c=0,l=!1;window.setInterval((()=>{l&&(r=i+a,l=!1,d(Ue,{engagementTotal:r,engagementAR:i,engagement3D:a}))}),1e3);const d=(r,i={})=>{var a;i=Object.assign(Object.assign({},i),{pluginVersion:v,sessionId:$e,setupId:o,timeSinceSetup:performance.now()-n,sku:e,apiKey:t}),a=()=>{window.ShopAR__analytics.trackEventImpl(r,i)},_e?a():Ne.push(a)};return{trackEvent:d,arInteracted:()=>{const e=performance.now(),t=e-s;s=e,t<200&&(i+=t,l=!0)},previewInteracted:()=>{const e=performance.now(),t=e-c;c=e,t<200&&(a+=t,l=!0)}}}function Oe(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}function qe(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.setAttribute("playsinline","playsinline"),t.srcObject=yield e,t}))}const Ge=200,We=10;let Qe,Fe,Ve,He=!1;function Be(e){return t(this,void 0,void 0,(function*(){const o=yield f((()=>t(this,void 0,void 0,(function*(){const t=yield fetch(e).catch((e=>{throw console.error(e),new n("Resource unavailable.")}));if(!t.ok)throw new n(`Resource download failed with status ${t.status}.`);return t}))));try{return yield(yield o.blob()).arrayBuffer()}catch(e){throw console.error(e),new n("Resource has invalid body.")}}))}let Ke,ze,Xe,Ze,Ye,Je,et,tt,nt=!0;function ot(e){e!==Ve&&(Ve=e,Be(e),Je=null,He=!0)}function rt(e,o){return t(this,void 0,void 0,(function*(){return Xe=o,null==Ye&&(Ye=(()=>t(this,void 0,void 0,(function*(){if(null==(null===(r=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia))throw new n("No camera available!");var r;const i=lt(o),a=Oe(i),s=function(e){const t={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:t[e]}(o);Ke=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:e||"your_license_key_goes_here",previewElement:Ze,additionalOptions:{hint:s,cameraConfig:{disableDefaultCamera:!0}}}),ze=yield qe(a),yield dt(Ke,ze,"user"===i),"Glasses"===o&&(yield Fe,function(e,n){t(this,void 0,void 0,(function*(){He=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${y}/wasm/mediapipe`,e);const r=[],i=setInterval((()=>t(this,void 0,void 0,(function*(){if(He)return void clearInterval(i);const{error:e,faceWidth:t}=yield o.predict(performance.now());if(He)return void clearInterval(i);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(r.length<We)return void r.push(t);clearInterval(i);const a=137/(function(e){let t=0;const n=e.length;for(let o=0;o<n;o++)t+=e[o];return t/n}(r)+5);n.changeParameterVector("GLASSES","","scale",a,a,a,0),n.changeParameterVector("shopar_glasses","","scale",a,a,a,0)}))),Ge)}))}(ze,Ke))})))()),Ye}))}function it(e){return t(this,void 0,void 0,(function*(){e!==Ze&&(Ze=e,null!=Ke&&Ke.changePreviewElement(Ze))}))}function at(e){Ke.callbacks.onFaceTracked=t=>{t.some((e=>e.detected))&&e()},Ke.callbacks.onFeetTracked=(t,n)=>{(t.detected||n.detected)&&e()},Ke.callbacks.onWristTracked=t=>{t.detected&&e()}}function st(e,n){return t(this,void 0,void 0,(function*(){return null!=Je&&et===n||(Je=Ke.switchEffect(e),et=n),Je}))}function ct(){null!=Ke&&(nt=!0,Ke.setPaused(nt),null!=ze&&null!=ze.srcObject&&ze.srcObject instanceof MediaStream&&(ze.srcObject.getTracks().forEach((e=>e.stop())),ze=null),Ke.stopCamera(),Ze.style.display="none")}function lt(e){var t;return null==e?"user":null!==(t={Glasses:"user",Shoes:"environment",Watches:"environment"}[e])&&void 0!==t?t:"user"}function dt(e,n,o){return t(this,void 0,void 0,(function*(){yield new Promise((r=>{n.onloadedmetadata=()=>{n.play().then((()=>t(this,void 0,void 0,(function*(){e.setVideoElement(n,o),r()}))))}}))}))}function ut(e,r,i){return t(this,void 0,void 0,(function*(){let a="glb".charCodeAt(0),s="3d".charCodeAt(0);a>>=1,a+=s;const c=String.fromCharCode(a+14);s>>=2,a^=s+2;const u=String.fromCharCode(a-3);a^=5;const h=String.fromCharCode(a-7);a^=2;const p=String.fromCharCode(a-7),g=window[`${h}${u+c+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${p}`],m=yield f((()=>t(this,void 0,void 0,(function*(){const t=yield g(`${e}`).catch((()=>{throw new n("Unknown error.")}));if(!t.ok)throw new n("Unknown error.");return t})))),v=new o[0](yield(yield m.blob().catch((()=>{throw new n("Unknown error.")}))).arrayBuffer().catch((()=>{throw new n("Unknown error.")})));i+=s;const w=v.byteLength;if(d[l]=Math.min(76,r)*((a>>5)-1),152===d[l]&&(d[l]=w),i==l)return v;i=l,i^=l;for(let e=0,t=v.length;e<t;e++)d[l]^=d[i]<<13,d[l]^=d[i]>>17,d[l]^=d[i]<<5,v[e]=v[e]^d[l];return i^=d[0],i^=d[1],i^=d[2],v}))}function ht(e,t){if(null==e)throw new n(`'${t}' not specified.`)}function pt(e,t){if("string"!=typeof e)throw new n(`'${t}' must be a string.`)}const ft=["AR","3D"];function gt(e){const{apiKey:t,sku:o,targetElement:r,initialState:i,baseUrl:a,defaultUI:s,strings:c}=e;ht(t,"apiKey"),pt(t,"apiKey"),ht(o,"sku"),pt(o,"sku"),ht(r,"targetElement"),function(e,t){if(!(e instanceof HTMLElement))throw new n(`'${t}' must be an HTMLElement.`)}(r,"targetElement"),null!=i&&function(e,t,o){if("string"!=typeof e)throw new n(`'${t}' must be a string.`);if(!o.includes(e))throw new n(`'${t}' must be ${o.join("' or '")}.`)}(i,"initialState",ft),null!=a&&pt(a,"baseUrl"),null!=s&&function(e,t){if("boolean"!=typeof e)throw new n(`'${t}' must be a boolean.`)}(s,"defaultUI"),null!=c&&function(e,t,o){for(const r of o){const o=e[r];if(null!=o&&"string"!=typeof o)throw new n(`Value for key '${r}' in '${t}' must be a string.`)}}(c,"strings",ne)}function mt(e){var o,r;return t(this,void 0,void 0,(function*(){gt(e);const{apiKey:i,sku:a,targetElement:s,initialState:c}=e;!function(e){const t=getComputedStyle(e);if(!["static","relative"].includes(t.position))throw new n(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${t.position}'.`)}(s),y.update(e.baseUrl),function(e){if(null!=e)for(const t of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(te,t)){console.warn(`String for key '${t}' will be ignored.`);continue}const n=e[t];null!=n&&(te[t]=n)}}(e.strings);const l=function(e,o){return t(this,void 0,void 0,(function*(){const r=yield f((()=>t(this,void 0,void 0,(function*(){const t=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:e,sku:o,sid:u()})}`).catch((e=>{throw console.error(e),new n("API unavailable.")}));if(!t.ok)throw new n(`API call failed with status ${t.status}.`);return t}))));try{return yield r.json()}catch(e){throw console.error(e),new n("API returned invalid body.")}}))}(i,a),d=Se(s),{getSetupId:h,findUI:p,findQR:v,findThree:w}=d,S=h();null==De&&($e=ke(),De=b(`${y}/shopar-analytics.js`),De.then((()=>{_e=!0,window.ShopAR__analytics.initializeImpl(),Ne.forEach((e=>e()))})));const{trackEvent:E,arInteracted:A,previewInteracted:C}=je(a,i);E("setup",{hostname:window.location.hostname});const T=yield l;E("apiResponse",T);const{category:I,arUrl:L,arKey:k,previewUrl:P,previewEnvUrl:x}=T;vt(h(),S);const M=null!=L&&function(e){return null!=e&&g.includes(e)}(I),U=null==(null===(o=e._internalOptions)||void 0===o?void 0:o.qrEnabled)||(null===(r=e._internalOptions)||void 0===r?void 0:r.qrEnabled),D=M&&function(e){return null!=e&&m.includes(e)}(I),$=U&&D&&!(yield function(){var e;return t(this,void 0,void 0,(function*(){return null==tt&&(tt=b(`${y}/shopar-platform.js`)),yield tt,["Android","iOS","Windows Phone",void 0].includes(null===(e=window.ShopAR__platform.platform.os)||void 0===e?void 0:e.family)}))}()),_=M&&!$,N=null!=P;if(vt(h(),S),$&&function(){t(this,void 0,void 0,(function*(){null==R&&(R=b(`${y}/shopar-qr.js`))}))}(),_&&(null==Qe&&(Qe=b(`${y}/shopar-deepar.js`)),ot(L),"Glasses"===I&&null==Fe&&(Fe=b(`${y}/shopar-true-scale.js`))),N){null==j&&(j=b(`${y}/shopar-three.js`));const e=255;ut(P,(new Date).getTime()+e,Math.random()*e),Be(null!=x?x:`${y}/env/default.hdr`)}const{setTargetElement:O,getDeepARTarget:q,setVisibilityParameters:G,getUIState:W,setUIState:Q,setDefaultUIActions:F,startDeepARLoading:V,stopDeepARLoading:H,startThreeLoading:B,stopThreeLoading:K,showCameraError:z}=p();O(s);G(null==e.defaultUI||e.defaultUI,$,_,N,I),function(e,t){const o=e.parentNode;if(null==o)throw new n("Parent node missing.");new MutationObserver((n=>{for(const o of n)for(const n of o.removedNodes)if(n===e)return void t()})).observe(o,{childList:!0})}(s,(()=>{W()!==me.QR||X()||Y(),W()!==me.AR||nt||ct(),W()!==me.Preview||oe()||ie(),Q(me.None)}));const{qrPaused:X,qrDraw:Z,qrPause:Y}=v(),{threeInit:J,threeParse:ee,threeLoad:ne,threePaused:oe,threeResume:re,threePause:ie,threeSetOnInteracted:ae}=w();let se=0;if(W()===me.QR){if(!X())if($){E(Pe);try{yield Z(i,a)}catch(e){throw new n(`QR failed: ${e instanceof Error?e.message:"Unknown error."}`)}}else Y(),Q(me.None)}else if(W()===me.AR){if(!nt)if(_){E(xe);const e=yield Be(L);vt(h(),S),Ee(d),it(q()),yield st(e,L),at(A),vt(h(),S)}else ct(),Q(me.None)}else if(W()===me.Preview&&!oe())if(N){E(Me),B();const e=255,t=yield ut(P,(new Date).getTime()+e,Math.random()*e);vt(h(),S);const n=yield Be(null!=x?x:`${y}/env/default.hdr`);vt(h(),S);const o=yield ee(t,n);vt(h(),S),ne(o,I),ae(C),K()}else ie(),Q(me.None);const ce=()=>t(this,void 0,void 0,(function*(){if($){if(W()===me.QR||W()===me.AR)throw new n("AR already launched.");try{E(Pe);const e=++se;if(W()===me.Preview&&N&&!oe()&&ie(),Q(me.QR),yield Z(i,a),se!==e)return;return void vt(h(),S)}catch(e){const t=e instanceof Error;throw E("qrLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),new n(`QR failed: ${t?e.message:"Unknown error."}`)}}if(!_)throw new n("Model does not have AR enabled.");if(W()===me.AR)throw new n("AR already launched.");try{E(xe);const e=++se;W()===me.Preview&&N&&!oe()&&ie(),Ee(d),Q(me.AR),V();const n=yield Be(L);if(se!==e)return;if(vt(h(),S),yield Qe,se!==e)return;if(vt(h(),S),ct(),it(q()),yield rt(k,I),se!==e)return;if(vt(h(),S),yield st(n,L),at(A),se!==e)return;if(vt(h(),S),yield function(){return t(this,void 0,void 0,(function*(){if(null!=Ke){if(nt=!1,null==ze){const e=lt(Xe),t=Oe(e);ze=yield qe(t),yield dt(Ke,ze,"user"===e)}Ke.setPaused(nt),Ze.style.display=""}}))}(),se!==e)return;vt(h(),S)}catch(e){const t=e instanceof Error;throw E("arLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),z(),ct(),new n(`AR failed: ${t?e.message:"Unknown error."}`)}finally{H()}})),le=()=>t(this,void 0,void 0,(function*(){if(!N)throw new n("Model does not have 3D enabled.");if(W()===me.Preview)throw new n("3D already launched.");try{E(Me);const e=++se;W()===me.AR&&(_&&!nt&&ct(),Y()),Q(me.Preview),B();const t=255,n=yield ut(P,(new Date).getTime()+t,Math.random()*t);if(se!==e)return;vt(h(),S);const o=yield Be(null!=x?x:`${y}/env/default.hdr`);if(se!==e)return;if(vt(h(),S),yield j,se!==e)return;if(vt(h(),S),J(),se!==e)return;vt(h(),S);const r=yield ee(n,o);if(se!==e)return;vt(h(),S),ne(r,I),ae(C),re()}catch(e){const t=e instanceof Error;throw E("previewLaunchFailure",{errorName:t?e.name:"Unknown",errorMessage:t?e.message:""}),new n(`3D failed: ${t?e.message:"Unknown error."}`)}finally{K()}})),de=()=>t(this,void 0,void 0,(function*(){if(W()===me.None)throw new n("Neither AR or 3D launched.");++se,W()===me.QR||W()===me.AR?(_&&!nt&&ct(),Y()):W()===me.Preview&&N&&!oe()&&ie(),Q(me.None)}));return F(ce,le,de),"AR"===c?(yield ce(),vt(h(),S)):"3D"===c&&(yield le(),vt(h(),S)),{launchAR:ce,launch3D:le,closeAR:()=>t(this,void 0,void 0,(function*(){if(W()!==me.AR||W()!==me.QR)throw new n("AR not launched.");++se,_&&!nt&&ct(),Y(),Q(me.None)})),close3D:()=>t(this,void 0,void 0,(function*(){if(W()!==me.Preview)throw new n("3D not launched.");++se,N&&!oe()&&ie(),Q(me.None)})),close:de}}))}function vt(e,t){if(e!==t)throw new n("Setup cancelled. Please ensure that setup is only called once.")}const wt={setup:function(e){return t(this,void 0,void 0,(function*(){return function(e,o){return t(this,void 0,void 0,(function*(){try{return o()}catch(t){throw t instanceof Error?new n(`${e} failed: ${t.message}`):(console.error(t),new n(`${e} failed.`))}}))}("setup",(()=>mt(e)))}))},version:v};e.plugin=wt}));
|