shopar-plugin 0.0.5-alpha.0 → 0.0.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,7 +21,7 @@ Powered and developed by DeepAR.
21
21
 
22
22
  Create an account in the [ShopAR Dashboard](https://dashboard.shopar.ai).
23
23
 
24
- Add some models to your account. Make sure the models' client IDs match the product IDs on your website.
24
+ Add some models to your account. Make sure the models' plugin SKUs match the product IDs on your website.
25
25
 
26
26
  ## Installation
27
27
 
@@ -62,7 +62,7 @@ Paste the following snippet in your HTML.
62
62
  ```
63
63
 
64
64
  - Replace `API_KEY` with your API key. You can find it in the [ShopAR Dashboard](https://dashboard.shopar.ai).
65
- - Replace `PRODUCT_ID` with the ID of the product. Make sure it matches the client ID in the [ShopAR Dashboard](https://dashboard.shopar.ai).
65
+ - Replace `PRODUCT_ID` with the ID of the product. Make sure it matches the plugin SKU of the model in the [ShopAR Dashboard](https://dashboard.shopar.ai).
66
66
  - Replace `TARGET_ELEMENT` with the HTML element you wish to embed the plugin's UI into.
67
67
 
68
68
  To change the look-and-feel of the plugin's UI, modify the following CSS classes:
Binary file
@@ -70,7 +70,7 @@ declare const plugin: {
70
70
  *
71
71
  * @param options Setup options.
72
72
  */
73
- setup: (options: SetupOptions) => Promise<void | {
73
+ setup: (options: SetupOptions) => Promise<{
74
74
  launchAR: () => Promise<void>;
75
75
  launch3D: () => Promise<void>;
76
76
  closeAR: () => Promise<void>;
@@ -1 +1 @@
1
- function e(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=[Uint8Array,Uint32Array],n=t.length-2,o=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],i=[2,12,7,1],r=window[o[i[i[n]]]][o[i[i[i.length-1]]]],s=r.charCodeAt(n),a=s^s,c=new t[1]([a]);function l(){const e=(new TextEncoder).encode(r),t=o.map((e=>e.length));for(let n=0;n<e.length;n++)e[n]^=t[n%t.length];return window[o[t[2]]](String.fromCodePoint(...e))}const d=[1e3,2e3,4e3],u=d.length;function h(t,n=0){return e(this,void 0,void 0,(function*(){try{return yield t()}catch(e){if(n>=u)throw e;return yield new Promise((e=>setTimeout(e,d[n]))),h(t,n+1)}}))}function p(t,n){return e(this,void 0,void 0,(function*(){const o=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:t,sku:n,sid:l()})}`).catch((e=>{throw console.error(e),new Error("API unavailable.")}));if(!e.ok)throw new Error(`API call failed with status ${e.status}.`);return e}))));try{return yield o.json()}catch(e){throw console.error(e),new Error("API returned invalid body.")}}))}const f=["Glasses","Shoes","Watches"];function v(e){return null!=e&&f.includes(e)}let w;const m=()=>w,g=e=>(null==w&&(w=y(e)),w),y=e=>{let t=!1;const n=[];e.then((()=>{t=!0,n.forEach((e=>e()))}));const o=e=>{t?e():n.push(e)},i={organizationId:"Unknown",sku:"Unknown"};let r,s=0;function a(e,t={}){t=Object.assign(Object.assign(Object.assign({},t),i),{vtoTime:(performance.now()-s)/1e3,vtoSessionId:r}),o((()=>{const{trackEventImpl:n}=window.ShopAR__analytics;n(e,t)}))}return{init:function(e,t){i.organizationId=e||"Unknown",i.sku=t||"Unknown",s=performance.now(),o((()=>{const{initializeImpl:e,uuidv4:t}=window.ShopAR__analytics;e(),r=t()}))},initialized:()=>a("initialized"),vtoLaunched:()=>a("vto_launched"),vtoCameraAsked:()=>a("vto_camera_asked"),vtoCameraGranted:()=>a("vto_camera_granted"),vtoCameraDenied:e=>a("vto_camera_denied",{error:e}),vtoInitSuccess:()=>a("vto_init_success"),previewLaunched:()=>a("preview_launched"),previewInteracted:()=>a("preview_interacted")}};const E="0.0.5-alpha.0";let b=`https://cdn.jsdelivr.net/npm/shopar-plugin@${E}/dist`;const C={update:e=>{null!=e&&(b=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>b};function A(e,t,n){const o=null==e?void 0:e.querySelector(`#${t}`);if(null!=o)return o;const i=n();return null==e||e.appendChild(i),i}function S(e,t,n){const o=A(e,t,n),i=o.style;return{element:o,show:()=>{i.display=""},hide:()=>{i.display="none"}}}const P="shopar-deepar-output";function R(){const e=document.createElement("div");e.id=P;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.zIndex="1",t.display="none",e}let $;const L=()=>$,k=e=>(null==$&&($=I(e)),$),I=t=>{const n=m(),o=function(e){return A(e,P,R)}(t),i=o.style;let r,s;let a;let c=!0;return{domElement:o,init:(t,i)=>e(void 0,void 0,void 0,(function*(){const a=function(e){const t={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:t[e]}(i),c=function(e){var t;const n={Glasses:"user",Shoes:"environment",Watches:"environment"};return null==e?"user":null!==(t=n[e])&&void 0!==t?t:"user"}(i);return null==s&&(s=e(void 0,void 0,void 0,(function*(){if(null==(null===(s=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===s?void 0:s.getUserMedia))throw new Error("No camera available!");var s;const l=function(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}(c);n.vtoCameraAsked(),r=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:t||"your_license_key_goes_here",previewElement:o,additionalOptions:{hint:a,cameraConfig:{disableDefaultCamera:!0}}});const d=yield function(t){return e(this,void 0,void 0,(function*(){const e=document.createElement("video");return e.setAttribute("playsinline","playsinline"),e.srcObject=yield t,e}))}(l);n.vtoCameraGranted(),yield function(t,n,o){return e(this,void 0,void 0,(function*(){yield new Promise((i=>{n.onloadedmetadata=()=>{n.play().then((()=>e(this,void 0,void 0,(function*(){t.setVideoElement(n,o),i()}))))}}))}))}(r,d,"user"===c),"Glasses"===i&&function(t,n){e(this,void 0,void 0,(function*(){const{ShopAR__TrueScale:o}=window;yield o.initialize(`${C}/wasm/mediapipe`,t);const i=[],r=setInterval((()=>e(this,void 0,void 0,(function*(){const{error:e,faceWidth:t}=yield o.predict(performance.now());if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(i.length<10)return void i.push(t);clearInterval(r);const s=137/(function(e){let t=0;const n=e.length;for(let o=0;o<n;o++)t+=e[o];return t/n}(i)+5);n.changeParameterVector("GLASSES","","scale",s,s,s,0),n.changeParameterVector("shopar_glasses","","scale",s,s,s,0)}))),200)}))}(d,r),n.vtoInitSuccess()}))),s})),parse:t=>e(void 0,void 0,void 0,(function*(){return null==a&&(a=r.switchEffect(t)),a})),isPaused:()=>c,resume:()=>{c=!1,r.setPaused(c),i.display=""},pause:()=>{c=!0,r.setPaused(c),i.display="none"}}};const U="shopar-three-output";function x(){const e=document.createElement("canvas");e.id=U;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.zIndex="1",e}let D;const _=()=>D,M=(e,t)=>(null==D&&(D=T(e,t)),D),T=(t,n)=>{const o=m(),i=function(e){return A(e,U,x)}(t),r=i.style,s=window.ShopAR__THREE,a=s.THREE,c=new a.WebGLRenderer({powerPreference:"high-performance",canvas:i,antialias:!0,alpha:!0});c.outputEncoding=a.sRGBEncoding,c.toneMapping=a.ACESFilmicToneMapping,c.setPixelRatio(2*window.devicePixelRatio),c.setClearColor(new a.Color(16777215));const l=new a.PerspectiveCamera(25,1,.5),d=function(e){var t;const n={Glasses:[67.5,15,90],Shoes:[-72.8,72.8,54.6],Watches:[0,-10,40],Handbags:[40,0,0],Rings:[0,0,10]};return null==e?n.Glasses:null!==(t=n[e])&&void 0!==t?t:n.Glasses}(n);l.position.set(d[0],d[1],d[2]);const u=new a.Scene,h=new s.OrbitControls(l,c.domElement);h.target.set(0,.03,0),h.dampingFactor=.3;{const e=function(e,t){let n;return()=>{n||e(),clearTimeout(n),n=setTimeout((()=>{n=void 0}),t)}}((()=>o.previewInteracted()),200);h.addEventListener("end",e)}{const e=new a.AmbientLight(new a.Color(16777215),.7),t=new a.RectAreaLight(new a.Color(16772574),10,50,50);t.position.set(-40,60,60);const n=new a.RectAreaLight(new a.Color(16774893),15,50,50);n.position.set(60,60,0),u.add(e,t,n)}const p=()=>{const e=i.clientWidth,t=i.clientHeight;i.width===e&&i.height===t||(c.setSize(e,t,!1),l.aspect=e/t,l.updateProjectionMatrix())};let f;let v=!1;const w=()=>{v||(requestAnimationFrame(w),p(),h.update(),c.render(u,l))};return{domElement:i,updateSize:p,parse:(t,n)=>e(void 0,void 0,void 0,(function*(){return null==f&&(f=e(void 0,void 0,void 0,(function*(){const e=new s.RGBELoader,o=function(e,t){const n=e.THREE,o=new n.DataTexture(t.data,t.width,t.height,void 0,t.type,void 0,n.ClampToEdgeWrapping,n.ClampToEdgeWrapping,n.LinearFilter,n.LinearFilter,1,n.LinearEncoding);return o.flipY=!0,o.generateMipmaps=!1,o.needsUpdate=!0,o}(s,e.parse(n));o.mapping=a.EquirectangularReflectionMapping,o.encoding=a.LinearEncoding,u.environment=o;const i=(new s.GLTFLoader).setDRACOLoader((new s.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${a.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new s.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${a.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(c)).setMeshoptDecoder("function"==typeof s.MeshoptDecoder?s.MeshoptDecoder():s.MeshoptDecoder),r=yield i.parseAsync(t.buffer,"");u.add(r.scene),u.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t.depthWrite=!0,t instanceof a.MeshPhysicalMaterial&&t.transmissionMap&&(t.transmission=1,t.toneMapped=!1,t.fog=!1,t.needsUpdate=!0)}}))}))),f})),isPaused:()=>v,resume:()=>{v=!1,w(),r.display=""},pause:()=>{v=!0,r.display="none"}}};function j(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 N="shopar-error";function z(){const e=document.createElement("div");e.id=N;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="1",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 i=j("4rem",`${C}/img/icons/close.svg`);n.appendChild(i);const r=document.createElement("div");r.className="shopar-error-title",r.textContent="Camera Error",n.appendChild(r);const s=document.createElement("div");return s.className="shopar-error-body",s.textContent="Please refresh the page and allow the use of camera.",n.appendChild(s),e}function G(e,t){return A(e,t.id,(()=>function(e){const{id:t,iconUrl:n,textContent:o,ariaLabel:i}=e,r=document.createElement("button");if(r.id=t,r.type="button",r.className="shopar-btn",null!=n){const e=j("1.75rem",n);r.appendChild(e)}{const e=document.createElement("span");e.textContent=o,r.appendChild(e)}return r.ariaLabel=i,r.style.zIndex="2",r}(t)))}const W="shopar-control";function K(){const e=document.createElement("div");return e.id=W,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e}const O="shopar-loading";function F(){const e=document.createElement("div");e.id=O;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="1",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.justifyContent="center",o.alignItems="center",e.appendChild(n);const i=document.createElement("div");return i.className="shopar-spinner",n.appendChild(i),e}const H="shopar-main";function V(e){return A(e,H,q)}function q(){const e=document.createElement("div");e.id=H;const t=e.style;return t.position="absolute",t.top="0",t.bottom="0",t.left="0",t.right="0",e}function B(t){return e(this,void 0,void 0,(function*(){const n=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(t).catch((e=>{throw console.error(e),new Error("Resource unavailable.")}));if(!e.ok)throw new Error(`Resource download failed with status ${e.status}.`);return e}))));try{return yield(yield n.blob()).arrayBuffer()}catch(e){throw console.error(e),new Error("Resource has invalid body.")}}))}function X(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())}))}function Y(n,o,i){return e(this,void 0,void 0,(function*(){let r="glb".charCodeAt(0),s="3d".charCodeAt(0);r>>=1,r+=s;const l=String.fromCharCode(r+14);s>>=2,r^=s+2;const d=String.fromCharCode(r-3);r^=5;const u=String.fromCharCode(r-7);r^=2;const p=String.fromCharCode(r-7),f=window[`${u}${d+l+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${p}`],v=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield f(`${n}`).catch((()=>{throw new Error("Unknown error.")}));if(!e.ok)throw new Error("Unknown error.");return e})))),w=new t[0](yield(yield v.blob().catch((()=>{throw new Error("Unknown error.")}))).arrayBuffer().catch((()=>{throw new Error("Unknown error.")})));i+=s;const m=w.byteLength;if(c[a]=Math.min(76,o)*((r>>5)-1),152===c[a]&&(c[a]=m),i==a)return w;i=a,i^=a;for(let e=0,t=w.length;e<t;e++)c[a]^=c[i]<<13,c[a]^=c[i]>>17,c[a]^=c[i]<<5,w[e]=w[e]^c[a];return i^=c[0],i^=c[1],i^=c[2],w}))}function J(e,t){if(null==e)throw new Error(`'${t}' not specified.`)}function Q(e,t){if("string"!=typeof e)throw new Error(`'${t}' must be a string.`)}const Z=["AR","3D"];function ee(e){const{apiKey:t,sku:n,targetElement:o,initialState:i,baseUrl:r,defaultUI:s}=e;J(t,"apiKey"),Q(t,"apiKey"),J(n,"sku"),Q(n,"sku"),J(o,"targetElement"),function(e,t){if(!(e instanceof HTMLElement))throw new Error(`'${t}' must be an HTMLElement.`)}(o,"targetElement"),null!=i&&function(e,t,n){if("string"!=typeof e)throw new Error(`'${t}' must be a string.`);if(!n.includes(e))throw new Error(`'${t}' must be ${n.join("' or '")}.`)}(i,"initialState",Z),null!=r&&Q(r,"baseUrl"),null!=s&&function(e,t){if("boolean"!=typeof e)throw new Error(`'${t}' must be a boolean.`)}(s,"defaultUI")}function te(e){const t=getComputedStyle(e);if(!["static","relative"].includes(t.position))throw new Error(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${t.position}'.`)}var ne;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(ne||(ne={}));let oe,ie=ne.None,re=0;const se=[];let ae;function ce(){if(ie===ne.AR){const e=L();null==e||e.isPaused()||e.pause()}else if(ie===ne.Preview){const e=_();null==e||e.isPaused()||e.pause()}}function le(e){if(ie=e,ie===ne.None){const e=se.filter((e=>null!=e));oe.replaceChildren(...e)}else oe.replaceChildren(ae)}function de(t){return e(this,void 0,void 0,(function*(){return ee(t),null==t.defaultUI||t.defaultUI?function(t){var n,o;return e(this,void 0,void 0,(function*(){const{apiKey:i,sku:r,targetElement:s,initialState:a}=t;te(s),C.update(t.baseUrl);const c=p(i,r),l=g(X(`${C}/shopar-analytics.js`));l.init(i,r),s.style.position="relative";const d=V(s);oe=A(d,W,K),ae=G(null,{id:"shopar-btn-close",textContent:"Close",ariaLabel:"Close ShopAR view",iconUrl:`${C}/img/icons/close.svg`}),ae.onclick=()=>{u.hide(),h.hide(),ce(),le(ne.None)};const u=function(e){return S(e,O,F)}(d),h=function(e){return S(e,N,z)}(d),{category:f,arUrl:w,arKey:m,previewUrl:y}=yield c;if(l.initialized(),null!=w&&v(f)){const t=Promise.all([X(`${C}/shopar-deepar.js`),B(w),..."Glasses"===f?[X(`${C}/shopar-true-scale.js`)]:[]]),n={Glasses:`${C}/img/icons/glasses.svg`,Shoes:`${C}/img/icons/shoe.svg`,Watches:`${C}/img/icons/watch.svg`},o=null!=f&&n[f]||n.Glasses;se[ne.AR]=G(oe,{id:"shopar-btn-vto",textContent:"Try-on",ariaLabel:"Launch ShopAR virtual try-on",iconUrl:o}),se[ne.AR].onclick=()=>e(this,void 0,void 0,(function*(){const e=++re,n=ne.AR,o=ie===n?ne.None:n;if(ce(),le(o),ie===ne.None)return;l.vtoLaunched(),h.hide(),u.show();const[,i]=yield t;if(re!==e)return;const r=k(d);try{yield r.init(m,f)}catch(e){return l.vtoCameraDenied(e),u.hide(),void h.show()}re===e&&(yield r.parse(i),re===e&&(r.resume(),u.hide()))}))}if(null!=y){const t=255,n=Promise.all([X(`${C}/shopar-three.js`),Y(y,(new Date).getTime()+t,Math.random()*t),B(`${C}/env/studio5.hdr`)]);se[ne.Preview]=G(oe,{id:"shopar-btn-3d",textContent:"3D",ariaLabel:"Launch ShopAR 3D preview",iconUrl:`${C}/img/icons/cube.svg`}),se[ne.Preview].onclick=()=>e(this,void 0,void 0,(function*(){const e=++re,t=ne.Preview,o=ie===t?ne.None:t;if(ce(),le(o),ie===ne.None)return;l.previewLaunched(),h.hide(),u.show();const[,i,r]=yield n;if(re!==e)return;const s=M(d,f);s.updateSize(),yield s.parse(i,r),re===e&&(s.resume(),u.hide())}))}"AR"===a?null===(n=se[ne.AR])||void 0===n||n.click():"3D"===a&&(null===(o=se[ne.Preview])||void 0===o||o.click())}))}(t):function(t){return e(this,void 0,void 0,(function*(){const{apiKey:n,sku:o,targetElement:i,initialState:r}=t;te(i),C.update(t.baseUrl);const s=p(n,o),a=g(X(`${C}/shopar-analytics.js`));a.init(n,o),i.style.position="relative";const c=V(i),{category:l,arUrl:d,arKey:u,previewUrl:h}=yield s;a.initialized();let f={enabled:!1};if(null!=d&&v(l)){const e=Promise.all([X(`${C}/shopar-deepar.js`),B(d),..."Glasses"===l?[X(`${C}/shopar-true-scale.js`)]:[]]);f={enabled:!0,predownload:e,category:l}}const w=()=>e(this,void 0,void 0,(function*(){if(!f.enabled)throw new Error("Model does not have AR enabled.");if(ie===ne.AR)throw new Error("AR already launched.");const e=++re;if(ie===ne.Preview){const e=_();null==e||e.isPaused()||e.pause()}ie=ne.AR,a.vtoLaunched();const[,t]=yield f.predownload;if(re!==e)return;const n=k(c);try{yield n.init(u,f.category)}catch(e){throw a.vtoCameraDenied(e),e}re===e&&(yield n.parse(t),re===e&&n.resume())}));let m={enabled:!1};if(null!=h){const e=255,t=Promise.all([X(`${C}/shopar-three.js`),Y(h,(new Date).getTime()+e,Math.random()*e),B(`${C}/env/studio5.hdr`)]);m={enabled:!0,predownload:t}}const y=()=>e(this,void 0,void 0,(function*(){if(!m.enabled)throw new Error("Model does not have 3D enabled.");if(ie===ne.Preview)throw new Error("3D already launched.");const e=++re;if(ie===ne.AR){const e=L();null==e||e.isPaused()||e.pause()}ie=ne.Preview,a.previewLaunched();const[,t,n]=yield m.predownload;if(re!==e)return;const o=M(c,l);o.updateSize(),yield o.parse(t,n),re===e&&o.resume()}));return"AR"===r?yield w():"3D"===r&&(yield y()),{launchAR:w,launch3D:y,closeAR:()=>e(this,void 0,void 0,(function*(){if(ie!==ne.AR)throw new Error("AR not launched.");const e=L();null==e||e.isPaused()||e.pause(),ie=ne.None})),close3D:()=>e(this,void 0,void 0,(function*(){if(ie!==ne.Preview)throw new Error("3D not launched.");const e=_();null==e||e.isPaused()||e.pause(),ie=ne.None}))}}))}(t)}))}const ue={setup:function(t){return e(this,void 0,void 0,(function*(){return function(t,n){return e(this,void 0,void 0,(function*(){try{return n()}catch(e){throw e instanceof Error?new ue.PluginError(`${t} failed: ${e.message}`):(console.error(e),new ue.PluginError(`${t} failed.`))}}))}("setup",(()=>de(t)))}))},version:E,PluginError:class extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}};export{ue as plugin};
1
+ function e(e,n,t,o){return new(t||(t=Promise))((function(i,r){function s(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var n;e.done?i(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(s,a)}l((o=o.apply(e,n||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const n=[Uint8Array,Uint32Array],t=n.length-2,o=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],i=[2,12,7,1],r=window[o[i[i[t]]]][o[i[i[i.length-1]]]],s=r.charCodeAt(t),a=s^s,l=new n[1]([a]);function c(){const e=(new TextEncoder).encode(r),n=o.map((e=>e.length));for(let t=0;t<e.length;t++)e[t]^=n[t%n.length];return window[o[n[2]]](String.fromCodePoint(...e))}const d=[1e3,2e3,4e3],u=d.length;function h(n,t=0){return e(this,void 0,void 0,(function*(){try{return yield n()}catch(e){if(t>=u)throw e;return yield new Promise((e=>setTimeout(e,d[t]))),h(n,t+1)}}))}const p=["Glasses","Shoes","Watches"];const f="0.0.5-alpha.1";let v=`https://cdn.jsdelivr.net/npm/shopar-plugin@${f}/dist`;const w={update:e=>{null!=e&&(v=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>v};function m(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())}))}let g,y;const E=()=>y,b=()=>{let e=!1;const n=[];g.then((()=>{e=!0,n.forEach((e=>e()))}));const t=t=>{e?t():n.push(t)},o={organizationId:"Unknown",sku:"Unknown"};let i,r=0;function s(e,n={}){n=Object.assign(Object.assign(Object.assign({},n),o),{vtoTime:(performance.now()-r)/1e3,vtoSessionId:i}),t((()=>{const{trackEventImpl:t}=window.ShopAR__analytics;t(e,n)}))}return{init:function(e,n){o.organizationId=e||"Unknown",o.sku=n||"Unknown",r=performance.now(),t((()=>{const{initializeImpl:e,uuidv4:n}=window.ShopAR__analytics;e(),i=n()}))},initialized:()=>s("initialized"),vtoLaunched:()=>s("vto_launched"),vtoCameraAsked:()=>s("vto_camera_asked"),vtoCameraGranted:()=>s("vto_camera_granted"),vtoCameraDenied:e=>s("vto_camera_denied",{error:e}),vtoInitSuccess:()=>s("vto_init_success"),previewLaunched:()=>s("preview_launched"),previewInteracted:()=>s("preview_interacted")}};let C=!1;function A(e,n,t){const o=null==e?void 0:e.querySelector(`#${n}`);if(null!=o)return o;const i=t();return null==e||e.appendChild(i),i}function S(e,n,t){const o=A(e,n,t),i=o.style;return{element:o,show:()=>{i.display=""},hide:()=>{i.display="none"}}}const P="shopar-deepar-output";function R(e){return A(e,P,$)}function $(){const e=document.createElement("div");e.id=P;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.zIndex="1",n.display="none",e}function I(n){return e(this,void 0,void 0,(function*(){const t=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(n).catch((e=>{throw console.error(e),new Error("Resource unavailable.")}));if(!e.ok)throw new Error(`Resource download failed with status ${e.status}.`);return e}))));try{return yield(yield t.blob()).arrayBuffer()}catch(e){throw console.error(e),new Error("Resource has invalid body.")}}))}let L,k,D,x,U;const _=()=>U,M=(e,n,t)=>{if(null==L&&(L=m(`${w}/shopar-deepar.js`)),null==k&&"Glasses"===t&&(k=m(`${w}/shopar-true-scale.js`)),n!==D&&function(e){D=e,x=I(e)}(n),null==U){const n=R(e);U=T(n)}return U},T=n=>{const t=E();let o,i;let r;let s=!0;return{domElement:n,init:(r,s)=>e(void 0,void 0,void 0,(function*(){return yield L,null==i&&(i=e(void 0,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 Error("No camera available!");var i;const a=function(e){var n;const t={Glasses:"user",Shoes:"environment",Watches:"environment"};return null==e?"user":null!==(n=t[e])&&void 0!==n?n:"user"}(s),l=function(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}(a);t.vtoCameraAsked();const c=function(e){const n={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:n[e]}(s);o=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:r||"your_license_key_goes_here",previewElement:n,additionalOptions:{hint:c,cameraConfig:{disableDefaultCamera:!0}}});const d=yield function(n){return e(this,void 0,void 0,(function*(){const e=document.createElement("video");return e.setAttribute("playsinline","playsinline"),e.srcObject=yield n,e}))}(l);t.vtoCameraGranted(),yield function(n,t,o){return e(this,void 0,void 0,(function*(){yield new Promise((i=>{t.onloadedmetadata=()=>{t.play().then((()=>e(this,void 0,void 0,(function*(){n.setVideoElement(t,o),i()}))))}}))}))}(o,d,"user"===a),"Glasses"===s&&(yield k,function(n,t){e(this,void 0,void 0,(function*(){C=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${w}/wasm/mediapipe`,n);const i=[],r=setInterval((()=>e(this,void 0,void 0,(function*(){if(C)return void clearInterval(r);const{error:e,faceWidth:n}=yield o.predict(performance.now());if(C)return void clearInterval(r);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(i.length<10)return void i.push(n);clearInterval(r);const s=137/(function(e){let n=0;const t=e.length;for(let o=0;o<t;o++)n+=e[o];return n/t}(i)+5);t.changeParameterVector("GLASSES","","scale",s,s,s,0),t.changeParameterVector("shopar_glasses","","scale",s,s,s,0)}))),200)}))}(d,o)),t.vtoInitSuccess()}))),i})),setDomElement:e=>{n=e,null==o||o.shutdown(),o=null,i=null},download:()=>e(void 0,void 0,void 0,(function*(){return x})),parse:n=>e(void 0,void 0,void 0,(function*(){return null==r&&(r=o.switchEffect(n)),r})),clear:()=>{r=null,null==o||o.clearEffect(),C=!0},isPaused:()=>s,resume:()=>{s=!1,null==o||o.setPaused(s),n.style.display=""},pause:()=>{s=!0,null==o||o.setPaused(s),n.style.display="none"}}};const N="shopar-three-output";function j(e){return A(e,N,G)}function G(){const e=document.createElement("canvas");e.id=N;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.zIndex="1",e}let z,W,O,F,K,H;const q=()=>H,V=(t,o,i,r)=>{if(null==z&&(z=m(`${w}/shopar-three.js`)),o!==W&&function(t){const o=255;W=t,O=function(t,o,i){return e(this,void 0,void 0,(function*(){let r="glb".charCodeAt(0),s="3d".charCodeAt(0);r>>=1,r+=s;const c=String.fromCharCode(r+14);s>>=2,r^=s+2;const d=String.fromCharCode(r-3);r^=5;const u=String.fromCharCode(r-7);r^=2;const p=String.fromCharCode(r-7),f=window[`${u}${d+c+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${p}`],v=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield f(`${t}`).catch((()=>{throw new Error("Unknown error.")}));if(!e.ok)throw new Error("Unknown error.");return e})))),w=new n[0](yield(yield v.blob().catch((()=>{throw new Error("Unknown error.")}))).arrayBuffer().catch((()=>{throw new Error("Unknown error.")})));i+=s;const m=w.byteLength;if(l[a]=Math.min(76,o)*((r>>5)-1),152===l[a]&&(l[a]=m),i==a)return w;i=a,i^=a;for(let e=0,n=w.length;e<n;e++)l[a]^=l[i]<<13,l[a]^=l[i]>>17,l[a]^=l[i]<<5,w[e]=w[e]^l[a];return i^=l[0],i^=l[1],i^=l[2],w}))}(t,(new Date).getTime()+o,Math.random()*o)}(o),i!==F&&function(e){F=e,K=I(e)}(i),null==H){const e=j(t);H=B(e,r)}return H},B=(n,t)=>{const o=E();let i,r,s,a,l,c,d=!1;let u;let h=!1;const p=()=>{h||(requestAnimationFrame(p),f(),c.update(),s.render(a,l))},f=()=>{const e=n.clientWidth,t=n.clientHeight;n.width===e&&n.height===t||(s.setSize(e,t,!1),l.aspect=e/t,l.updateProjectionMatrix())};return{domElement:n,init:()=>e(void 0,void 0,void 0,(function*(){if(yield z,!d){i=window.ShopAR__THREE,r=i.THREE,s=new r.WebGLRenderer({powerPreference:"high-performance",canvas:n,antialias:!0,alpha:!0}),s.outputEncoding=r.sRGBEncoding,s.toneMapping=r.ACESFilmicToneMapping,s.setPixelRatio(window.devicePixelRatio||1),s.setClearColor(new r.Color(16777215)),a=new r.Scene,l=new r.PerspectiveCamera(25,1,.5);const e=function(e){var n;const t={Glasses:[67.5,15,90],Shoes:[-72.8,72.8,54.6],Watches:[0,-10,40],Handbags:[40,0,0],Rings:[0,0,10]};return null==e?t.Glasses:null!==(n=t[e])&&void 0!==n?n:t.Glasses}(t);l.position.set(e[0],e[1],e[2]),c=new i.OrbitControls(l,s.domElement),c.target.set(0,.03,0),c.dampingFactor=.3;{const e=function(e,n){let t;return()=>{t||e(),clearTimeout(t),t=setTimeout((()=>{t=void 0}),n)}}((()=>o.previewInteracted()),200);c.addEventListener("end",e)}d=!0}f()})),setDomElement:t=>e(void 0,void 0,void 0,(function*(){n=t,d=!1})),downloadModel:()=>e(void 0,void 0,void 0,(function*(){return O})),downloadEnv:()=>e(void 0,void 0,void 0,(function*(){return K})),parse:(n,t)=>e(void 0,void 0,void 0,(function*(){return null==u&&(u=e(void 0,void 0,void 0,(function*(){const e=new i.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}(i,e.parse(t));o.mapping=r.EquirectangularReflectionMapping,o.encoding=r.LinearEncoding,a.environment=o;const l=(new i.GLTFLoader).setDRACOLoader((new i.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${r.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new i.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${r.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(s)).setMeshoptDecoder("function"==typeof i.MeshoptDecoder?i.MeshoptDecoder():i.MeshoptDecoder),c=yield l.parseAsync(n.buffer,"");a.add(c.scene),a.traverse((e=>{if(e instanceof r.Mesh){const n=e.material;n.depthWrite=!0,n instanceof r.MeshPhysicalMaterial&&n.transmissionMap&&(n.transmission=1,n.toneMapped=!1,n.fog=!1,n.needsUpdate=!0)}}))}))),u})),clear:()=>{u=null,null==a||a.clear()},isPaused:()=>h,resume:()=>{h=!1,p(),n.style.display=""},pause:()=>{h=!0,n.style.display="none"}}};function X(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 Y="shopar-error";function J(){const e=document.createElement("div");e.id=Y;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.zIndex="1",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 i=X("4rem",`${w}/img/icons/close.svg`);t.appendChild(i);const r=document.createElement("div");r.className="shopar-error-title",r.textContent="Camera Error",t.appendChild(r);const s=document.createElement("div");return s.className="shopar-error-body",s.textContent="Please refresh the page and allow the use of camera.",t.appendChild(s),e}function Q(e,n){return A(e,n.id,(()=>function(e){const{id:n,iconUrl:t,textContent:o,ariaLabel:i}=e,r=document.createElement("button");if(r.id=n,r.type="button",r.className="shopar-btn",null!=t){const e=X("1.75rem",t);r.appendChild(e)}{const e=document.createElement("span");e.textContent=o,r.appendChild(e)}return r.ariaLabel=i,r.style.zIndex="2",r}(n)))}const Z="shopar-control";function ee(){const e=document.createElement("div");return e.id=Z,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e}const ne="shopar-loading";function te(){const e=document.createElement("div");e.id=ne;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.zIndex="1",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.justifyContent="center",o.alignItems="center",e.appendChild(t);const i=document.createElement("div");return i.className="shopar-spinner",t.appendChild(i),e}const oe="shopar-main";function ie(){const e=document.createElement("div");e.id=oe;const n=e.style;return n.position="absolute",n.top="0",n.bottom="0",n.left="0",n.right="0",e}function re(e,n){if(null==e)throw new Error(`'${n}' not specified.`)}function se(e,n){if("string"!=typeof e)throw new Error(`'${n}' must be a string.`)}const ae=["AR","3D"];function le(e){const{apiKey:n,sku:t,targetElement:o,initialState:i,baseUrl:r,defaultUI:s}=e;re(n,"apiKey"),se(n,"apiKey"),re(t,"sku"),se(t,"sku"),re(o,"targetElement"),function(e,n){if(!(e instanceof HTMLElement))throw new Error(`'${n}' must be an HTMLElement.`)}(o,"targetElement"),null!=i&&function(e,n,t){if("string"!=typeof e)throw new Error(`'${n}' must be a string.`);if(!t.includes(e))throw new Error(`'${n}' must be ${t.join("' or '")}.`)}(i,"initialState",ae),null!=r&&se(r,"baseUrl"),null!=s&&function(e,n){if("boolean"!=typeof e)throw new Error(`'${n}' must be a boolean.`)}(s,"defaultUI")}var ce;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(ce||(ce={}));let de,ue=ce.None,he=0;const pe=[];let fe,ve,we,me=null;function ge(n){return e(this,void 0,void 0,(function*(){le(n);const{apiKey:t,sku:o,targetElement:i,initialState:r}=n;!function(e){const n=getComputedStyle(e);if(!["static","relative"].includes(n.position))throw new Error(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${n.position}'.`)}(i),w.update(n.baseUrl);const s=function(n,t){return e(this,void 0,void 0,(function*(){const o=yield h((()=>e(this,void 0,void 0,(function*(){const e=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:n,sku:t,sid:c()})}`).catch((e=>{throw console.error(e),new Error("API unavailable.")}));if(!e.ok)throw new Error(`API call failed with status ${e.status}.`);return e}))));try{return yield o.json()}catch(e){throw console.error(e),new Error("API returned invalid body.")}}))}(t,o),a=(null==g&&(g=m(`${w}/shopar-analytics.js`)),null==y&&(y=b()),y);a.init(t,o);const l=i!=me;null!=me&&l&&function(e){const n=e.querySelector(`#${oe}`);null!=n&&n.remove()}(me),me=i,i.style.position="relative";const d=A(i,oe,ie);const u=null==n.defaultUI||n.defaultUI;u&&(de=function(e){return A(e,Z,ee)}(d),fe=Q(null,{id:"shopar-btn-close",textContent:"Close",ariaLabel:"Close ShopAR view",iconUrl:`${w}/img/icons/close.svg`}),ve=function(e){return S(e,ne,te)}(d),we=function(e){return S(e,Y,J)}(d));const{category:f,arUrl:v,arKey:E,previewUrl:C,previewEnvUrl:P}=yield s;a.initialized();{const e=_();null!=e&&(e.clear(),e.isPaused()||e.pause(),l&&e.setDomElement(R(d)));const n=q();if(null!=n&&(n.clear(),n.isPaused()||n.pause(),l&&n.setDomElement(j(d))),++he,ue=ce.None,u){ve.hide(),we.hide();const e=pe.filter((e=>null!=e));de.replaceChildren(...e)}}const $=null!=v&&function(e){return null!=e&&p.includes(e)}(f)?M(d,v,f):null,I=null!=C?V(d,C,null!=P?P:`${w}/env/default.hdr`,f):null,L=()=>e(this,void 0,void 0,(function*(){if(null==$)throw new Error("Model does not have AR enabled.");if(ue===ce.AR)throw new Error("AR already launched.");const e=++he;ue===ce.Preview&&(null==I||I.isPaused()||I.pause()),ue=ce.AR,u&&de.replaceChildren(fe),a.vtoLaunched(),u&&(we.hide(),ve.show());const n=yield $.download();if(he===e){try{yield $.init(E,f)}catch(e){throw a.vtoCameraDenied(e),u&&(ve.hide(),we.show()),e}he===e&&(yield $.parse(n),he===e&&($.resume(),u&&ve.hide()))}})),k=()=>e(this,void 0,void 0,(function*(){if(null==I)throw new Error("Model does not have 3D enabled.");if(ue===ce.Preview)throw new Error("3D already launched.");const e=++he;ue===ce.AR&&(null==$||$.isPaused()||$.pause()),ue=ce.Preview,u&&de.replaceChildren(fe),a.previewLaunched(),u&&(we.hide(),ve.show());const n=yield I.downloadModel();if(he!==e)return;const t=yield I.downloadEnv();he===e&&(yield I.init(),he===e&&(yield I.parse(n,t),he===e&&(I.resume(),u&&ve.hide())))})),D=()=>e(this,void 0,void 0,(function*(){if(ue===ce.None)throw new Error("Neither AR or 3D launched.");if(++he,ue===ce.AR?null==$||$.isPaused()||$.pause():ue===ce.Preview&&(null==I||I.isPaused()||I.pause()),ue=ce.None,u){ve.hide(),we.hide();const e=pe.filter((e=>null!=e));de.replaceChildren(...e)}}));if(u){if(null!=$){const e={Glasses:`${w}/img/icons/glasses.svg`,Shoes:`${w}/img/icons/shoe.svg`,Watches:`${w}/img/icons/watch.svg`},n=null!=f&&e[f]||e.Glasses;pe[ce.AR]=Q(de,{id:"shopar-btn-vto",textContent:"Try-on",ariaLabel:"Launch ShopAR virtual try-on",iconUrl:n}),pe[ce.AR].onclick=L}null!=I&&(pe[ce.Preview]=Q(de,{id:"shopar-btn-3d",textContent:"3D",ariaLabel:"Launch ShopAR 3D preview",iconUrl:`${w}/img/icons/cube.svg`}),pe[ce.Preview].onclick=k),fe.onclick=D}return"AR"===r?yield L():"3D"===r&&(yield k()),{launchAR:L,launch3D:k,closeAR:()=>e(this,void 0,void 0,(function*(){if(ue!==ce.AR)throw new Error("AR not launched.");if(++he,null==$||$.isPaused()||$.pause(),ue=ce.None,u){ve.hide(),we.hide();const e=pe.filter((e=>null!=e));de.replaceChildren(...e)}})),close3D:()=>e(this,void 0,void 0,(function*(){if(ue!==ce.Preview)throw new Error("3D not launched.");if(++he,null==I||I.isPaused()||I.pause(),ue=ce.None,u){ve.hide(),we.hide();const e=pe.filter((e=>null!=e));de.replaceChildren(...e)}}))}}))}const ye={setup:function(n){return e(this,void 0,void 0,(function*(){return function(n,t){return e(this,void 0,void 0,(function*(){try{return t()}catch(e){throw e instanceof Error?new ye.PluginError(`${n} failed: ${e.message}`):(console.error(e),new ye.PluginError(`${n} failed.`))}}))}("setup",(()=>ge(n)))}))},version:f,PluginError:class extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}};export{ye as plugin};
@@ -1 +1 @@
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(i,r){function s(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const n=[Uint8Array,Uint32Array],o=n.length-2,i=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],r=[2,12,7,1],s=window[i[r[r[o]]]][i[r[r[r.length-1]]]],a=s.charCodeAt(o),c=a^a,l=new n[1]([c]);function d(){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 u=[1e3,2e3,4e3],h=u.length;function p(e,n=0){return t(this,void 0,void 0,(function*(){try{return yield e()}catch(t){if(n>=h)throw t;return yield new Promise((e=>setTimeout(e,u[n]))),p(e,n+1)}}))}function f(e,n){return t(this,void 0,void 0,(function*(){const o=yield p((()=>t(this,void 0,void 0,(function*(){const t=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:e,sku:n,sid:d()})}`).catch((e=>{throw console.error(e),new Error("API unavailable.")}));if(!t.ok)throw new Error(`API call failed with status ${t.status}.`);return t}))));try{return yield o.json()}catch(e){throw console.error(e),new Error("API returned invalid body.")}}))}const v=["Glasses","Shoes","Watches"];function w(e){return null!=e&&v.includes(e)}let m;const g=()=>m,y=e=>(null==m&&(m=E(e)),m),E=e=>{let t=!1;const n=[];e.then((()=>{t=!0,n.forEach((e=>e()))}));const o=e=>{t?e():n.push(e)},i={organizationId:"Unknown",sku:"Unknown"};let r,s=0;function a(e,t={}){t=Object.assign(Object.assign(Object.assign({},t),i),{vtoTime:(performance.now()-s)/1e3,vtoSessionId:r}),o((()=>{const{trackEventImpl:n}=window.ShopAR__analytics;n(e,t)}))}return{init:function(e,t){i.organizationId=e||"Unknown",i.sku=t||"Unknown",s=performance.now(),o((()=>{const{initializeImpl:e,uuidv4:t}=window.ShopAR__analytics;e(),r=t()}))},initialized:()=>a("initialized"),vtoLaunched:()=>a("vto_launched"),vtoCameraAsked:()=>a("vto_camera_asked"),vtoCameraGranted:()=>a("vto_camera_granted"),vtoCameraDenied:e=>a("vto_camera_denied",{error:e}),vtoInitSuccess:()=>a("vto_init_success"),previewLaunched:()=>a("preview_launched"),previewInteracted:()=>a("preview_interacted")}};const b="0.0.5-alpha.0";let C=`https://cdn.jsdelivr.net/npm/shopar-plugin@${b}/dist`;const A={update:e=>{null!=e&&(C=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>C};function S(e,t,n){const o=null==e?void 0:e.querySelector(`#${t}`);if(null!=o)return o;const i=n();return null==e||e.appendChild(i),i}function P(e,t,n){const o=S(e,t,n),i=o.style;return{element:o,show:()=>{i.display=""},hide:()=>{i.display="none"}}}const R="shopar-deepar-output";function $(){const e=document.createElement("div");e.id=R;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.zIndex="1",t.display="none",e}let L;const k=()=>L,I=e=>(null==L&&(L=x(e)),L),x=e=>{const n=g(),o=function(e){return S(e,R,$)}(e),i=o.style;let r,s;let a;let c=!0;return{domElement:o,init:(e,i)=>t(void 0,void 0,void 0,(function*(){const a=function(e){const t={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:t[e]}(i),c=function(e){var t;const n={Glasses:"user",Shoes:"environment",Watches:"environment"};return null==e?"user":null!==(t=n[e])&&void 0!==t?t:"user"}(i);return null==s&&(s=t(void 0,void 0,void 0,(function*(){if(null==(null===(s=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===s?void 0:s.getUserMedia))throw new Error("No camera available!");var s;const l=function(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}(c);n.vtoCameraAsked(),r=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:e||"your_license_key_goes_here",previewElement:o,additionalOptions:{hint:a,cameraConfig:{disableDefaultCamera:!0}}});const d=yield function(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.setAttribute("playsinline","playsinline"),t.srcObject=yield e,t}))}(l);n.vtoCameraGranted(),yield function(e,n,o){return t(this,void 0,void 0,(function*(){yield new Promise((i=>{n.onloadedmetadata=()=>{n.play().then((()=>t(this,void 0,void 0,(function*(){e.setVideoElement(n,o),i()}))))}}))}))}(r,d,"user"===c),"Glasses"===i&&function(e,n){t(this,void 0,void 0,(function*(){const{ShopAR__TrueScale:o}=window;yield o.initialize(`${A}/wasm/mediapipe`,e);const i=[],r=setInterval((()=>t(this,void 0,void 0,(function*(){const{error:e,faceWidth:t}=yield o.predict(performance.now());if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(i.length<10)return void i.push(t);clearInterval(r);const s=137/(function(e){let t=0;const n=e.length;for(let o=0;o<n;o++)t+=e[o];return t/n}(i)+5);n.changeParameterVector("GLASSES","","scale",s,s,s,0),n.changeParameterVector("shopar_glasses","","scale",s,s,s,0)}))),200)}))}(d,r),n.vtoInitSuccess()}))),s})),parse:e=>t(void 0,void 0,void 0,(function*(){return null==a&&(a=r.switchEffect(e)),a})),isPaused:()=>c,resume:()=>{c=!1,r.setPaused(c),i.display=""},pause:()=>{c=!0,r.setPaused(c),i.display="none"}}};const U="shopar-three-output";function D(){const e=document.createElement("canvas");e.id=U;const t=e.style;return t.position="absolute",t.top="0",t.left="0",t.width="100%",t.height="100%",t.zIndex="1",e}let T;const _=()=>T,M=(e,t)=>(null==T&&(T=j(e,t)),T),j=(e,n)=>{const o=g(),i=function(e){return S(e,U,D)}(e),r=i.style,s=window.ShopAR__THREE,a=s.THREE,c=new a.WebGLRenderer({powerPreference:"high-performance",canvas:i,antialias:!0,alpha:!0});c.outputEncoding=a.sRGBEncoding,c.toneMapping=a.ACESFilmicToneMapping,c.setPixelRatio(2*window.devicePixelRatio),c.setClearColor(new a.Color(16777215));const l=new a.PerspectiveCamera(25,1,.5),d=function(e){var t;const n={Glasses:[67.5,15,90],Shoes:[-72.8,72.8,54.6],Watches:[0,-10,40],Handbags:[40,0,0],Rings:[0,0,10]};return null==e?n.Glasses:null!==(t=n[e])&&void 0!==t?t:n.Glasses}(n);l.position.set(d[0],d[1],d[2]);const u=new a.Scene,h=new s.OrbitControls(l,c.domElement);h.target.set(0,.03,0),h.dampingFactor=.3;{const e=function(e,t){let n;return()=>{n||e(),clearTimeout(n),n=setTimeout((()=>{n=void 0}),t)}}((()=>o.previewInteracted()),200);h.addEventListener("end",e)}{const e=new a.AmbientLight(new a.Color(16777215),.7),t=new a.RectAreaLight(new a.Color(16772574),10,50,50);t.position.set(-40,60,60);const n=new a.RectAreaLight(new a.Color(16774893),15,50,50);n.position.set(60,60,0),u.add(e,t,n)}const p=()=>{const e=i.clientWidth,t=i.clientHeight;i.width===e&&i.height===t||(c.setSize(e,t,!1),l.aspect=e/t,l.updateProjectionMatrix())};let f;let v=!1;const w=()=>{v||(requestAnimationFrame(w),p(),h.update(),c.render(u,l))};return{domElement:i,updateSize:p,parse:(e,n)=>t(void 0,void 0,void 0,(function*(){return null==f&&(f=t(void 0,void 0,void 0,(function*(){const t=new s.RGBELoader,o=function(e,t){const n=e.THREE,o=new n.DataTexture(t.data,t.width,t.height,void 0,t.type,void 0,n.ClampToEdgeWrapping,n.ClampToEdgeWrapping,n.LinearFilter,n.LinearFilter,1,n.LinearEncoding);return o.flipY=!0,o.generateMipmaps=!1,o.needsUpdate=!0,o}(s,t.parse(n));o.mapping=a.EquirectangularReflectionMapping,o.encoding=a.LinearEncoding,u.environment=o;const i=(new s.GLTFLoader).setDRACOLoader((new s.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${a.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new s.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${a.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(c)).setMeshoptDecoder("function"==typeof s.MeshoptDecoder?s.MeshoptDecoder():s.MeshoptDecoder),r=yield i.parseAsync(e.buffer,"");u.add(r.scene),u.traverse((e=>{if(e instanceof a.Mesh){const t=e.material;t.depthWrite=!0,t instanceof a.MeshPhysicalMaterial&&t.transmissionMap&&(t.transmission=1,t.toneMapped=!1,t.fog=!1,t.needsUpdate=!0)}}))}))),f})),isPaused:()=>v,resume:()=>{v=!1,w(),r.display=""},pause:()=>{v=!0,r.display="none"}}};function N(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 z="shopar-error";function G(){const e=document.createElement("div");e.id=z;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="1",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 i=N("4rem",`${A}/img/icons/close.svg`);n.appendChild(i);const r=document.createElement("div");r.className="shopar-error-title",r.textContent="Camera Error",n.appendChild(r);const s=document.createElement("div");return s.className="shopar-error-body",s.textContent="Please refresh the page and allow the use of camera.",n.appendChild(s),e}function W(e,t){return S(e,t.id,(()=>function(e){const{id:t,iconUrl:n,textContent:o,ariaLabel:i}=e,r=document.createElement("button");if(r.id=t,r.type="button",r.className="shopar-btn",null!=n){const e=N("1.75rem",n);r.appendChild(e)}{const e=document.createElement("span");e.textContent=o,r.appendChild(e)}return r.ariaLabel=i,r.style.zIndex="2",r}(t)))}const K="shopar-control";function O(){const e=document.createElement("div");return e.id=K,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e}const F="shopar-loading";function H(){const e=document.createElement("div");e.id=F;const t=e.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="1",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.justifyContent="center",o.alignItems="center",e.appendChild(n);const i=document.createElement("div");return i.className="shopar-spinner",n.appendChild(i),e}const V="shopar-main";function q(e){return S(e,V,B)}function B(){const e=document.createElement("div");e.id=V;const t=e.style;return t.position="absolute",t.top="0",t.bottom="0",t.left="0",t.right="0",e}function X(e){return t(this,void 0,void 0,(function*(){const n=yield p((()=>t(this,void 0,void 0,(function*(){const t=yield fetch(e).catch((e=>{throw console.error(e),new Error("Resource unavailable.")}));if(!t.ok)throw new Error(`Resource download failed with status ${t.status}.`);return t}))));try{return yield(yield n.blob()).arrayBuffer()}catch(e){throw console.error(e),new Error("Resource has invalid body.")}}))}function Y(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())}))}function J(e,o,i){return t(this,void 0,void 0,(function*(){let r="glb".charCodeAt(0),s="3d".charCodeAt(0);r>>=1,r+=s;const a=String.fromCharCode(r+14);s>>=2,r^=s+2;const d=String.fromCharCode(r-3);r^=5;const u=String.fromCharCode(r-7);r^=2;const h=String.fromCharCode(r-7),f=window[`${u}${d+a+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${h}`],v=yield p((()=>t(this,void 0,void 0,(function*(){const t=yield f(`${e}`).catch((()=>{throw new Error("Unknown error.")}));if(!t.ok)throw new Error("Unknown error.");return t})))),w=new n[0](yield(yield v.blob().catch((()=>{throw new Error("Unknown error.")}))).arrayBuffer().catch((()=>{throw new Error("Unknown error.")})));i+=s;const m=w.byteLength;if(l[c]=Math.min(76,o)*((r>>5)-1),152===l[c]&&(l[c]=m),i==c)return w;i=c,i^=c;for(let e=0,t=w.length;e<t;e++)l[c]^=l[i]<<13,l[c]^=l[i]>>17,l[c]^=l[i]<<5,w[e]=w[e]^l[c];return i^=l[0],i^=l[1],i^=l[2],w}))}function Q(e,t){if(null==e)throw new Error(`'${t}' not specified.`)}function Z(e,t){if("string"!=typeof e)throw new Error(`'${t}' must be a string.`)}const ee=["AR","3D"];function te(e){const{apiKey:t,sku:n,targetElement:o,initialState:i,baseUrl:r,defaultUI:s}=e;Q(t,"apiKey"),Z(t,"apiKey"),Q(n,"sku"),Z(n,"sku"),Q(o,"targetElement"),function(e,t){if(!(e instanceof HTMLElement))throw new Error(`'${t}' must be an HTMLElement.`)}(o,"targetElement"),null!=i&&function(e,t,n){if("string"!=typeof e)throw new Error(`'${t}' must be a string.`);if(!n.includes(e))throw new Error(`'${t}' must be ${n.join("' or '")}.`)}(i,"initialState",ee),null!=r&&Z(r,"baseUrl"),null!=s&&function(e,t){if("boolean"!=typeof e)throw new Error(`'${t}' must be a boolean.`)}(s,"defaultUI")}function ne(e){const t=getComputedStyle(e);if(!["static","relative"].includes(t.position))throw new Error(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${t.position}'.`)}var oe;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(oe||(oe={}));let ie,re=oe.None,se=0;const ae=[];let ce;function le(){if(re===oe.AR){const e=k();null==e||e.isPaused()||e.pause()}else if(re===oe.Preview){const e=_();null==e||e.isPaused()||e.pause()}}function de(e){if(re=e,re===oe.None){const e=ae.filter((e=>null!=e));ie.replaceChildren(...e)}else ie.replaceChildren(ce)}function ue(e){return t(this,void 0,void 0,(function*(){return te(e),null==e.defaultUI||e.defaultUI?function(e){var n,o;return t(this,void 0,void 0,(function*(){const{apiKey:i,sku:r,targetElement:s,initialState:a}=e;ne(s),A.update(e.baseUrl);const c=f(i,r),l=y(Y(`${A}/shopar-analytics.js`));l.init(i,r),s.style.position="relative";const d=q(s);ie=S(d,K,O),ce=W(null,{id:"shopar-btn-close",textContent:"Close",ariaLabel:"Close ShopAR view",iconUrl:`${A}/img/icons/close.svg`}),ce.onclick=()=>{u.hide(),h.hide(),le(),de(oe.None)};const u=function(e){return P(e,F,H)}(d),h=function(e){return P(e,z,G)}(d),{category:p,arUrl:v,arKey:m,previewUrl:g}=yield c;if(l.initialized(),null!=v&&w(p)){const e=Promise.all([Y(`${A}/shopar-deepar.js`),X(v),..."Glasses"===p?[Y(`${A}/shopar-true-scale.js`)]:[]]),n={Glasses:`${A}/img/icons/glasses.svg`,Shoes:`${A}/img/icons/shoe.svg`,Watches:`${A}/img/icons/watch.svg`},o=null!=p&&n[p]||n.Glasses;ae[oe.AR]=W(ie,{id:"shopar-btn-vto",textContent:"Try-on",ariaLabel:"Launch ShopAR virtual try-on",iconUrl:o}),ae[oe.AR].onclick=()=>t(this,void 0,void 0,(function*(){const t=++se,n=oe.AR,o=re===n?oe.None:n;if(le(),de(o),re===oe.None)return;l.vtoLaunched(),h.hide(),u.show();const[,i]=yield e;if(se!==t)return;const r=I(d);try{yield r.init(m,p)}catch(e){return l.vtoCameraDenied(e),u.hide(),void h.show()}se===t&&(yield r.parse(i),se===t&&(r.resume(),u.hide()))}))}if(null!=g){const e=255,n=Promise.all([Y(`${A}/shopar-three.js`),J(g,(new Date).getTime()+e,Math.random()*e),X(`${A}/env/studio5.hdr`)]);ae[oe.Preview]=W(ie,{id:"shopar-btn-3d",textContent:"3D",ariaLabel:"Launch ShopAR 3D preview",iconUrl:`${A}/img/icons/cube.svg`}),ae[oe.Preview].onclick=()=>t(this,void 0,void 0,(function*(){const e=++se,t=oe.Preview,o=re===t?oe.None:t;if(le(),de(o),re===oe.None)return;l.previewLaunched(),h.hide(),u.show();const[,i,r]=yield n;if(se!==e)return;const s=M(d,p);s.updateSize(),yield s.parse(i,r),se===e&&(s.resume(),u.hide())}))}"AR"===a?null===(n=ae[oe.AR])||void 0===n||n.click():"3D"===a&&(null===(o=ae[oe.Preview])||void 0===o||o.click())}))}(e):function(e){return t(this,void 0,void 0,(function*(){const{apiKey:n,sku:o,targetElement:i,initialState:r}=e;ne(i),A.update(e.baseUrl);const s=f(n,o),a=y(Y(`${A}/shopar-analytics.js`));a.init(n,o),i.style.position="relative";const c=q(i),{category:l,arUrl:d,arKey:u,previewUrl:h}=yield s;a.initialized();let p={enabled:!1};if(null!=d&&w(l)){const e=Promise.all([Y(`${A}/shopar-deepar.js`),X(d),..."Glasses"===l?[Y(`${A}/shopar-true-scale.js`)]:[]]);p={enabled:!0,predownload:e,category:l}}const v=()=>t(this,void 0,void 0,(function*(){if(!p.enabled)throw new Error("Model does not have AR enabled.");if(re===oe.AR)throw new Error("AR already launched.");const e=++se;if(re===oe.Preview){const e=_();null==e||e.isPaused()||e.pause()}re=oe.AR,a.vtoLaunched();const[,t]=yield p.predownload;if(se!==e)return;const n=I(c);try{yield n.init(u,p.category)}catch(e){throw a.vtoCameraDenied(e),e}se===e&&(yield n.parse(t),se===e&&n.resume())}));let m={enabled:!1};if(null!=h){const e=255,t=Promise.all([Y(`${A}/shopar-three.js`),J(h,(new Date).getTime()+e,Math.random()*e),X(`${A}/env/studio5.hdr`)]);m={enabled:!0,predownload:t}}const g=()=>t(this,void 0,void 0,(function*(){if(!m.enabled)throw new Error("Model does not have 3D enabled.");if(re===oe.Preview)throw new Error("3D already launched.");const e=++se;if(re===oe.AR){const e=k();null==e||e.isPaused()||e.pause()}re=oe.Preview,a.previewLaunched();const[,t,n]=yield m.predownload;if(se!==e)return;const o=M(c,l);o.updateSize(),yield o.parse(t,n),se===e&&o.resume()}));return"AR"===r?yield v():"3D"===r&&(yield g()),{launchAR:v,launch3D:g,closeAR:()=>t(this,void 0,void 0,(function*(){if(re!==oe.AR)throw new Error("AR not launched.");const e=k();null==e||e.isPaused()||e.pause(),re=oe.None})),close3D:()=>t(this,void 0,void 0,(function*(){if(re!==oe.Preview)throw new Error("3D not launched.");const e=_();null==e||e.isPaused()||e.pause(),re=oe.None}))}}))}(e)}))}const he={setup:function(e){return t(this,void 0,void 0,(function*(){return function(e,n){return t(this,void 0,void 0,(function*(){try{return n()}catch(t){throw t instanceof Error?new he.PluginError(`${e} failed: ${t.message}`):(console.error(t),new he.PluginError(`${e} failed.`))}}))}("setup",(()=>ue(e)))}))},version:b,PluginError:class extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}};e.plugin=he}));
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(i,r){function s(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var n;e.done?i(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(s,a)}l((o=o.apply(e,n||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=[Uint8Array,Uint32Array],o=t.length-2,i=["addEventListener","alert","atob","blur","btoa","cancelAnimationFrame","localStorage","location","locationbar","hash","hasOwnProperty","host","hostname","href","requestAnimationFrame"],r=[2,12,7,1],s=window[i[r[r[o]]]][i[r[r[r.length-1]]]],a=s.charCodeAt(o),l=a^a,c=new t[1]([l]);function d(){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 u=[1e3,2e3,4e3],h=u.length;function p(e,t=0){return n(this,void 0,void 0,(function*(){try{return yield e()}catch(n){if(t>=h)throw n;return yield new Promise((e=>setTimeout(e,u[t]))),p(e,t+1)}}))}const f=["Glasses","Shoes","Watches"];const v="0.0.5-alpha.1";let w=`https://cdn.jsdelivr.net/npm/shopar-plugin@${v}/dist`;const m={update:e=>{null!=e&&(w=e.endsWith("/")?e.substring(0,e.length-1):e)},toString:()=>w};function g(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())}))}let y,E;const b=()=>E,C=()=>{let e=!1;const n=[];y.then((()=>{e=!0,n.forEach((e=>e()))}));const t=t=>{e?t():n.push(t)},o={organizationId:"Unknown",sku:"Unknown"};let i,r=0;function s(e,n={}){n=Object.assign(Object.assign(Object.assign({},n),o),{vtoTime:(performance.now()-r)/1e3,vtoSessionId:i}),t((()=>{const{trackEventImpl:t}=window.ShopAR__analytics;t(e,n)}))}return{init:function(e,n){o.organizationId=e||"Unknown",o.sku=n||"Unknown",r=performance.now(),t((()=>{const{initializeImpl:e,uuidv4:n}=window.ShopAR__analytics;e(),i=n()}))},initialized:()=>s("initialized"),vtoLaunched:()=>s("vto_launched"),vtoCameraAsked:()=>s("vto_camera_asked"),vtoCameraGranted:()=>s("vto_camera_granted"),vtoCameraDenied:e=>s("vto_camera_denied",{error:e}),vtoInitSuccess:()=>s("vto_init_success"),previewLaunched:()=>s("preview_launched"),previewInteracted:()=>s("preview_interacted")}};let A=!1;function S(e,n,t){const o=null==e?void 0:e.querySelector(`#${n}`);if(null!=o)return o;const i=t();return null==e||e.appendChild(i),i}function P(e,n,t){const o=S(e,n,t),i=o.style;return{element:o,show:()=>{i.display=""},hide:()=>{i.display="none"}}}const R="shopar-deepar-output";function $(e){return S(e,R,I)}function I(){const e=document.createElement("div");e.id=R;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.zIndex="1",n.display="none",e}function L(e){return n(this,void 0,void 0,(function*(){const t=yield p((()=>n(this,void 0,void 0,(function*(){const n=yield fetch(e).catch((e=>{throw console.error(e),new Error("Resource unavailable.")}));if(!n.ok)throw new Error(`Resource download failed with status ${n.status}.`);return n}))));try{return yield(yield t.blob()).arrayBuffer()}catch(e){throw console.error(e),new Error("Resource has invalid body.")}}))}let k,x,D,U,_;const M=()=>_,T=(e,n,t)=>{if(null==k&&(k=g(`${m}/shopar-deepar.js`)),null==x&&"Glasses"===t&&(x=g(`${m}/shopar-true-scale.js`)),n!==D&&function(e){D=e,U=L(e)}(n),null==_){const n=$(e);_=N(n)}return _},N=e=>{const t=b();let o,i;let r;let s=!0;return{domElement:e,init:(r,s)=>n(void 0,void 0,void 0,(function*(){return yield k,null==i&&(i=n(void 0,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 Error("No camera available!");var i;const a=function(e){var n;const t={Glasses:"user",Shoes:"environment",Watches:"environment"};return null==e?"user":null!==(n=t[e])&&void 0!==n?n:"user"}(s),l=function(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,frameRate:{ideal:30},width:{ideal:640},height:{ideal:360}}})}(a);t.vtoCameraAsked();const c=function(e){const n={Glasses:"rigidFaceTrackingInit",Shoes:"footInit",Watches:void 0};return null==e?void 0:n[e]}(s);o=yield window.ShopAR__DeepAR.deepar.initialize({licenseKey:r||"your_license_key_goes_here",previewElement:e,additionalOptions:{hint:c,cameraConfig:{disableDefaultCamera:!0}}});const d=yield function(e){return n(this,void 0,void 0,(function*(){const n=document.createElement("video");return n.setAttribute("playsinline","playsinline"),n.srcObject=yield e,n}))}(l);t.vtoCameraGranted(),yield function(e,t,o){return n(this,void 0,void 0,(function*(){yield new Promise((i=>{t.onloadedmetadata=()=>{t.play().then((()=>n(this,void 0,void 0,(function*(){e.setVideoElement(t,o),i()}))))}}))}))}(o,d,"user"===a),"Glasses"===s&&(yield x,function(e,t){n(this,void 0,void 0,(function*(){A=!1;const{ShopAR__TrueScale:o}=window;yield o.initialize(`${m}/wasm/mediapipe`,e);const i=[],r=setInterval((()=>n(this,void 0,void 0,(function*(){if(A)return void clearInterval(r);const{error:e,faceWidth:n}=yield o.predict(performance.now());if(A)return void clearInterval(r);if(null!=e)return void console.error(`TrueScale predict error: ${e}`);if(i.length<10)return void i.push(n);clearInterval(r);const s=137/(function(e){let n=0;const t=e.length;for(let o=0;o<t;o++)n+=e[o];return n/t}(i)+5);t.changeParameterVector("GLASSES","","scale",s,s,s,0),t.changeParameterVector("shopar_glasses","","scale",s,s,s,0)}))),200)}))}(d,o)),t.vtoInitSuccess()}))),i})),setDomElement:n=>{e=n,null==o||o.shutdown(),o=null,i=null},download:()=>n(void 0,void 0,void 0,(function*(){return U})),parse:e=>n(void 0,void 0,void 0,(function*(){return null==r&&(r=o.switchEffect(e)),r})),clear:()=>{r=null,null==o||o.clearEffect(),A=!0},isPaused:()=>s,resume:()=>{s=!1,null==o||o.setPaused(s),e.style.display=""},pause:()=>{s=!0,null==o||o.setPaused(s),e.style.display="none"}}};const j="shopar-three-output";function G(e){return S(e,j,z)}function z(){const e=document.createElement("canvas");e.id=j;const n=e.style;return n.position="absolute",n.top="0",n.left="0",n.width="100%",n.height="100%",n.zIndex="1",e}let W,O,F,K,H,q;const V=()=>q,B=(e,o,i,r)=>{if(null==W&&(W=g(`${m}/shopar-three.js`)),o!==O&&function(e){const o=255;O=e,F=function(e,o,i){return n(this,void 0,void 0,(function*(){let r="glb".charCodeAt(0),s="3d".charCodeAt(0);r>>=1,r+=s;const a=String.fromCharCode(r+14);s>>=2,r^=s+2;const d=String.fromCharCode(r-3);r^=5;const u=String.fromCharCode(r-7);r^=2;const h=String.fromCharCode(r-7),f=window[`${u}${d+a+(typeof[])[(+!+[]+ +!+[])*(+!+[]+ +!+[])]}${h}`],v=yield p((()=>n(this,void 0,void 0,(function*(){const n=yield f(`${e}`).catch((()=>{throw new Error("Unknown error.")}));if(!n.ok)throw new Error("Unknown error.");return n})))),w=new t[0](yield(yield v.blob().catch((()=>{throw new Error("Unknown error.")}))).arrayBuffer().catch((()=>{throw new Error("Unknown error.")})));i+=s;const m=w.byteLength;if(c[l]=Math.min(76,o)*((r>>5)-1),152===c[l]&&(c[l]=m),i==l)return w;i=l,i^=l;for(let e=0,n=w.length;e<n;e++)c[l]^=c[i]<<13,c[l]^=c[i]>>17,c[l]^=c[i]<<5,w[e]=w[e]^c[l];return i^=c[0],i^=c[1],i^=c[2],w}))}(e,(new Date).getTime()+o,Math.random()*o)}(o),i!==K&&function(e){K=e,H=L(e)}(i),null==q){const n=G(e);q=X(n,r)}return q},X=(e,t)=>{const o=b();let i,r,s,a,l,c,d=!1;let u;let h=!1;const p=()=>{h||(requestAnimationFrame(p),f(),c.update(),s.render(a,l))},f=()=>{const n=e.clientWidth,t=e.clientHeight;e.width===n&&e.height===t||(s.setSize(n,t,!1),l.aspect=n/t,l.updateProjectionMatrix())};return{domElement:e,init:()=>n(void 0,void 0,void 0,(function*(){if(yield W,!d){i=window.ShopAR__THREE,r=i.THREE,s=new r.WebGLRenderer({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0}),s.outputEncoding=r.sRGBEncoding,s.toneMapping=r.ACESFilmicToneMapping,s.setPixelRatio(window.devicePixelRatio||1),s.setClearColor(new r.Color(16777215)),a=new r.Scene,l=new r.PerspectiveCamera(25,1,.5);const n=function(e){var n;const t={Glasses:[67.5,15,90],Shoes:[-72.8,72.8,54.6],Watches:[0,-10,40],Handbags:[40,0,0],Rings:[0,0,10]};return null==e?t.Glasses:null!==(n=t[e])&&void 0!==n?n:t.Glasses}(t);l.position.set(n[0],n[1],n[2]),c=new i.OrbitControls(l,s.domElement),c.target.set(0,.03,0),c.dampingFactor=.3;{const e=function(e,n){let t;return()=>{t||e(),clearTimeout(t),t=setTimeout((()=>{t=void 0}),n)}}((()=>o.previewInteracted()),200);c.addEventListener("end",e)}d=!0}f()})),setDomElement:t=>n(void 0,void 0,void 0,(function*(){e=t,d=!1})),downloadModel:()=>n(void 0,void 0,void 0,(function*(){return F})),downloadEnv:()=>n(void 0,void 0,void 0,(function*(){return H})),parse:(e,t)=>n(void 0,void 0,void 0,(function*(){return null==u&&(u=n(void 0,void 0,void 0,(function*(){const n=new i.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}(i,n.parse(t));o.mapping=r.EquirectangularReflectionMapping,o.encoding=r.LinearEncoding,a.environment=o;const l=(new i.GLTFLoader).setDRACOLoader((new i.DRACOLoader).setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${r.REVISION}.0/examples/jsm/libs/draco/gltf/`)).setKTX2Loader((new i.KTX2Loader).setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${r.REVISION}.0/examples/jsm/libs/basis/`).detectSupport(s)).setMeshoptDecoder("function"==typeof i.MeshoptDecoder?i.MeshoptDecoder():i.MeshoptDecoder),c=yield l.parseAsync(e.buffer,"");a.add(c.scene),a.traverse((e=>{if(e instanceof r.Mesh){const n=e.material;n.depthWrite=!0,n instanceof r.MeshPhysicalMaterial&&n.transmissionMap&&(n.transmission=1,n.toneMapped=!1,n.fog=!1,n.needsUpdate=!0)}}))}))),u})),clear:()=>{u=null,null==a||a.clear()},isPaused:()=>h,resume:()=>{h=!1,p(),e.style.display=""},pause:()=>{h=!0,e.style.display="none"}}};function Y(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 J="shopar-error";function Q(){const e=document.createElement("div");e.id=J;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.zIndex="1",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 i=Y("4rem",`${m}/img/icons/close.svg`);t.appendChild(i);const r=document.createElement("div");r.className="shopar-error-title",r.textContent="Camera Error",t.appendChild(r);const s=document.createElement("div");return s.className="shopar-error-body",s.textContent="Please refresh the page and allow the use of camera.",t.appendChild(s),e}function Z(e,n){return S(e,n.id,(()=>function(e){const{id:n,iconUrl:t,textContent:o,ariaLabel:i}=e,r=document.createElement("button");if(r.id=n,r.type="button",r.className="shopar-btn",null!=t){const e=Y("1.75rem",t);r.appendChild(e)}{const e=document.createElement("span");e.textContent=o,r.appendChild(e)}return r.ariaLabel=i,r.style.zIndex="2",r}(n)))}const ee="shopar-control";function ne(){const e=document.createElement("div");return e.id=ee,e.role="group",e.ariaLabel="Preview type chooser",e.className="shopar-btn-container",e}const te="shopar-loading";function oe(){const e=document.createElement("div");e.id=te;const n=e.style;n.position="absolute",n.width="100%",n.height="100%",n.zIndex="1",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.justifyContent="center",o.alignItems="center",e.appendChild(t);const i=document.createElement("div");return i.className="shopar-spinner",t.appendChild(i),e}const ie="shopar-main";function re(){const e=document.createElement("div");e.id=ie;const n=e.style;return n.position="absolute",n.top="0",n.bottom="0",n.left="0",n.right="0",e}function se(e,n){if(null==e)throw new Error(`'${n}' not specified.`)}function ae(e,n){if("string"!=typeof e)throw new Error(`'${n}' must be a string.`)}const le=["AR","3D"];function ce(e){const{apiKey:n,sku:t,targetElement:o,initialState:i,baseUrl:r,defaultUI:s}=e;se(n,"apiKey"),ae(n,"apiKey"),se(t,"sku"),ae(t,"sku"),se(o,"targetElement"),function(e,n){if(!(e instanceof HTMLElement))throw new Error(`'${n}' must be an HTMLElement.`)}(o,"targetElement"),null!=i&&function(e,n,t){if("string"!=typeof e)throw new Error(`'${n}' must be a string.`);if(!t.includes(e))throw new Error(`'${n}' must be ${t.join("' or '")}.`)}(i,"initialState",le),null!=r&&ae(r,"baseUrl"),null!=s&&function(e,n){if("boolean"!=typeof e)throw new Error(`'${n}' must be a boolean.`)}(s,"defaultUI")}var de;!function(e){e[e.None=0]="None",e[e.AR=1]="AR",e[e.Preview=2]="Preview"}(de||(de={}));let ue,he=de.None,pe=0;const fe=[];let ve,we,me,ge=null;function ye(e){return n(this,void 0,void 0,(function*(){ce(e);const{apiKey:t,sku:o,targetElement:i,initialState:r}=e;!function(e){const n=getComputedStyle(e);if(!["static","relative"].includes(n.position))throw new Error(`Invalid targetElement's position. Expected 'static' or 'relative', but found '${n.position}'.`)}(i),m.update(e.baseUrl);const s=function(e,t){return n(this,void 0,void 0,(function*(){const o=yield p((()=>n(this,void 0,void 0,(function*(){const n=yield fetch(`https://dashboard.shopar.ai/plugin?${new URLSearchParams({apiKey:e,sku:t,sid:d()})}`).catch((e=>{throw console.error(e),new Error("API unavailable.")}));if(!n.ok)throw new Error(`API call failed with status ${n.status}.`);return n}))));try{return yield o.json()}catch(e){throw console.error(e),new Error("API returned invalid body.")}}))}(t,o),a=(null==y&&(y=g(`${m}/shopar-analytics.js`)),null==E&&(E=C()),E);a.init(t,o);const l=i!=ge;null!=ge&&l&&function(e){const n=e.querySelector(`#${ie}`);null!=n&&n.remove()}(ge),ge=i,i.style.position="relative";const c=S(i,ie,re);const u=null==e.defaultUI||e.defaultUI;u&&(ue=function(e){return S(e,ee,ne)}(c),ve=Z(null,{id:"shopar-btn-close",textContent:"Close",ariaLabel:"Close ShopAR view",iconUrl:`${m}/img/icons/close.svg`}),we=function(e){return P(e,te,oe)}(c),me=function(e){return P(e,J,Q)}(c));const{category:h,arUrl:v,arKey:w,previewUrl:b,previewEnvUrl:A}=yield s;a.initialized();{const e=M();null!=e&&(e.clear(),e.isPaused()||e.pause(),l&&e.setDomElement($(c)));const n=V();if(null!=n&&(n.clear(),n.isPaused()||n.pause(),l&&n.setDomElement(G(c))),++pe,he=de.None,u){we.hide(),me.hide();const e=fe.filter((e=>null!=e));ue.replaceChildren(...e)}}const R=null!=v&&function(e){return null!=e&&f.includes(e)}(h)?T(c,v,h):null,I=null!=b?B(c,b,null!=A?A:`${m}/env/default.hdr`,h):null,L=()=>n(this,void 0,void 0,(function*(){if(null==R)throw new Error("Model does not have AR enabled.");if(he===de.AR)throw new Error("AR already launched.");const e=++pe;he===de.Preview&&(null==I||I.isPaused()||I.pause()),he=de.AR,u&&ue.replaceChildren(ve),a.vtoLaunched(),u&&(me.hide(),we.show());const n=yield R.download();if(pe===e){try{yield R.init(w,h)}catch(e){throw a.vtoCameraDenied(e),u&&(we.hide(),me.show()),e}pe===e&&(yield R.parse(n),pe===e&&(R.resume(),u&&we.hide()))}})),k=()=>n(this,void 0,void 0,(function*(){if(null==I)throw new Error("Model does not have 3D enabled.");if(he===de.Preview)throw new Error("3D already launched.");const e=++pe;he===de.AR&&(null==R||R.isPaused()||R.pause()),he=de.Preview,u&&ue.replaceChildren(ve),a.previewLaunched(),u&&(me.hide(),we.show());const n=yield I.downloadModel();if(pe!==e)return;const t=yield I.downloadEnv();pe===e&&(yield I.init(),pe===e&&(yield I.parse(n,t),pe===e&&(I.resume(),u&&we.hide())))})),x=()=>n(this,void 0,void 0,(function*(){if(he===de.None)throw new Error("Neither AR or 3D launched.");if(++pe,he===de.AR?null==R||R.isPaused()||R.pause():he===de.Preview&&(null==I||I.isPaused()||I.pause()),he=de.None,u){we.hide(),me.hide();const e=fe.filter((e=>null!=e));ue.replaceChildren(...e)}}));if(u){if(null!=R){const e={Glasses:`${m}/img/icons/glasses.svg`,Shoes:`${m}/img/icons/shoe.svg`,Watches:`${m}/img/icons/watch.svg`},n=null!=h&&e[h]||e.Glasses;fe[de.AR]=Z(ue,{id:"shopar-btn-vto",textContent:"Try-on",ariaLabel:"Launch ShopAR virtual try-on",iconUrl:n}),fe[de.AR].onclick=L}null!=I&&(fe[de.Preview]=Z(ue,{id:"shopar-btn-3d",textContent:"3D",ariaLabel:"Launch ShopAR 3D preview",iconUrl:`${m}/img/icons/cube.svg`}),fe[de.Preview].onclick=k),ve.onclick=x}return"AR"===r?yield L():"3D"===r&&(yield k()),{launchAR:L,launch3D:k,closeAR:()=>n(this,void 0,void 0,(function*(){if(he!==de.AR)throw new Error("AR not launched.");if(++pe,null==R||R.isPaused()||R.pause(),he=de.None,u){we.hide(),me.hide();const e=fe.filter((e=>null!=e));ue.replaceChildren(...e)}})),close3D:()=>n(this,void 0,void 0,(function*(){if(he!==de.Preview)throw new Error("3D not launched.");if(++pe,null==I||I.isPaused()||I.pause(),he=de.None,u){we.hide(),me.hide();const e=fe.filter((e=>null!=e));ue.replaceChildren(...e)}}))}}))}const Ee={setup:function(e){return n(this,void 0,void 0,(function*(){return function(e,t){return n(this,void 0,void 0,(function*(){try{return t()}catch(n){throw n instanceof Error?new Ee.PluginError(`${e} failed: ${n.message}`):(console.error(n),new Ee.PluginError(`${e} failed.`))}}))}("setup",(()=>ye(e)))}))},version:v,PluginError:class extends Error{constructor(e){super(`ShopAR Plugin: ${e}`)}}};e.plugin=Ee}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shopar-plugin",
3
- "version": "0.0.5-alpha.0",
3
+ "version": "0.0.5-alpha.1",
4
4
  "description": "Plugin for the Web that seamlessly integrates into your webpage to create embedded virtual try-on and 3D preview capabilities.",
5
5
  "scripts": {
6
6
  "clean": "rm -rf dist",
Binary file