@limrun/ui 0.20.8 → 0.21.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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./duo-frame-gXvPDImv.js");function Q(d){const t=new Map,e=new Map,n=d.clone();return q(d,n,function(s,r){t.set(r,s),e.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=t.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(i){return e.get(i)}),r.bind(r.skeleton,r.bindMatrix)}),n}function q(d,t,e){e(d,t);for(let n=0;n<d.children.length;n++)q(d.children[n],t.children[n],e)}class J extends h.Loader{constructor(t){super(t),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new ne(e)}),this.register(function(e){return new se(e)}),this.register(function(e){return new fe(e)}),this.register(function(e){return new de(e)}),this.register(function(e){return new pe(e)}),this.register(function(e){return new ie(e)}),this.register(function(e){return new oe(e)}),this.register(function(e){return new ae(e)}),this.register(function(e){return new ce(e)}),this.register(function(e){return new te(e)}),this.register(function(e){return new le(e)}),this.register(function(e){return new re(e)}),this.register(function(e){return new he(e)}),this.register(function(e){return new ue(e)}),this.register(function(e){return new $(e)}),this.register(function(e){return new K(e,T.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new K(e,T.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new me(e)})}load(t,e,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const c=h.LoaderUtils.extractUrlBase(t);o=h.LoaderUtils.resolveURL(c,this.path)}else o=h.LoaderUtils.extractUrlBase(t);this.manager.itemStart(t);const a=function(c){s?s(c):console.error(c),r.manager.itemError(t),r.manager.itemEnd(t)},i=new h.FileLoader(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(t,function(c){try{r.parse(c,o,function(u){e(u),r.manager.itemEnd(t)},a)}catch(u){a(u)}},n,a)}setDRACOLoader(t){return this.dracoLoader=t,this}setKTX2Loader(t){return this.ktx2Loader=t,this}setMeshoptDecoder(t){return this.meshoptDecoder=t,this}register(t){return this.pluginCallbacks.indexOf(t)===-1&&this.pluginCallbacks.push(t),this}unregister(t){return this.pluginCallbacks.indexOf(t)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(t),1),this}parse(t,e,n,s){let r;const o={},a={},i=new TextDecoder;if(typeof t=="string")r=JSON.parse(t);else if(t instanceof ArrayBuffer)if(i.decode(new Uint8Array(t,0,4))===W){try{o[T.KHR_BINARY_GLTF]=new ge(t)}catch(l){s&&s(l);return}r=JSON.parse(o[T.KHR_BINARY_GLTF].content)}else r=JSON.parse(i.decode(t));else r=t;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new Ne(r,{path:e||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const l=this.pluginCallbacks[u](c);l.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[l.name]=l,o[l.name]=!0}if(r.extensionsUsed)for(let u=0;u<r.extensionsUsed.length;++u){const l=r.extensionsUsed[u],f=r.extensionsRequired||[];switch(l){case T.KHR_MATERIALS_UNLIT:o[l]=new ee;break;case T.KHR_DRACO_MESH_COMPRESSION:o[l]=new Te(r,this.dracoLoader);break;case T.KHR_TEXTURE_TRANSFORM:o[l]=new Re;break;case T.KHR_MESH_QUANTIZATION:o[l]=new Me;break;default:f.indexOf(l)>=0&&a[l]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+l+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(n,s)}parseAsync(t,e){const n=this;return new Promise(function(s,r){n.parse(t,e,s,r)})}}function Z(){let d={};return{get:function(t){return d[t]},add:function(t,e){d[t]=e},remove:function(t){delete d[t]},removeAll:function(){d={}}}}function _(d,t,e){const n=d.json.materials[t];return n.extensions&&n.extensions[e]?n.extensions[e]:null}const T={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ${constructor(t){this.parser=t,this.name=T.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const t=this.parser,e=this.parser.json.nodes||[];for(let n=0,s=e.length;n<s;n++){const r=e[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&t._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(t){const e=this.parser,n="light:"+t;let s=e.cache.get(n);if(s)return s;const r=e.json,i=((r.extensions&&r.extensions[this.name]||{}).lights||[])[t];let c;const u=new h.Color(16777215);i.color!==void 0&&u.setRGB(i.color[0],i.color[1],i.color[2],h.LinearSRGBColorSpace);const l=i.range!==void 0?i.range:0;switch(i.type){case"directional":c=new h.DirectionalLight(u),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new h.PointLight(u),c.distance=l;break;case"spot":c=new h.SpotLight(u),c.distance=l,i.spot=i.spot||{},i.spot.innerConeAngle=i.spot.innerConeAngle!==void 0?i.spot.innerConeAngle:0,i.spot.outerConeAngle=i.spot.outerConeAngle!==void 0?i.spot.outerConeAngle:Math.PI/4,c.angle=i.spot.outerConeAngle,c.penumbra=1-i.spot.innerConeAngle/i.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+i.type)}return c.position.set(0,0,0),w(c,i),i.intensity!==void 0&&(c.intensity=i.intensity),c.name=e.createUniqueName(i.name||"light_"+t),s=Promise.resolve(c),e.cache.add(n,s),s}getDependency(t,e){if(t==="light")return this._loadLight(e)}createNodeAttachment(t){const e=this,n=this.parser,r=n.json.nodes[t],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(i){return n._getNodeRef(e.cache,a,i)})}}class ee{constructor(){this.name=T.KHR_MATERIALS_UNLIT}getMaterialType(){return h.MeshBasicMaterial}extendParams(t,e,n){const s=[];t.color=new h.Color(1,1,1),t.opacity=1;const r=e.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;t.color.setRGB(o[0],o[1],o[2],h.LinearSRGBColorSpace),t.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(t,"map",r.baseColorTexture,h.SRGBColorSpace))}return Promise.all(s)}}class te{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||n.emissiveStrength!==void 0&&(e.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class ne{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_CLEARCOAT}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(e.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(e,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(e.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(e,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(e,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;e.clearcoatNormalScale=new h.Vector2(r,r)}return Promise.all(s)}}class se{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_DISPERSION}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||(e.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class re{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_IRIDESCENCE}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(e.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(e,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(e.iridescenceIOR=n.iridescenceIor),e.iridescenceThicknessRange===void 0&&(e.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(e.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(e.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(e,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class ie{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_SHEEN}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];if(e.sheenColor=new h.Color(0,0,0),e.sheenRoughness=0,e.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;e.sheenColor.setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(e.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(e,"sheenColorMap",n.sheenColorTexture,h.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(e,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class oe{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_TRANSMISSION}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(e.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(e,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class ae{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_VOLUME}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];e.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(e,"thicknessMap",n.thicknessTexture)),e.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return e.attenuationColor=new h.Color().setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace),Promise.all(s)}}class ce{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_IOR}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||(e.ior=n.ior!==void 0?n.ior:1.5),Promise.resolve()}}class le{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_SPECULAR}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];e.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(e,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return e.specularColor=new h.Color().setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(e,"specularColorMap",n.specularColorTexture,h.SRGBColorSpace)),Promise.all(s)}}class ue{constructor(t){this.parser=t,this.name=T.EXT_MATERIALS_BUMP}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return e.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(e,"bumpMap",n.bumpTexture)),Promise.all(s)}}class he{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_ANISOTROPY}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(e.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(e.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(e,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class fe{constructor(t){this.parser=t,this.name=T.KHR_TEXTURE_BASISU}loadTexture(t){const e=this.parser,n=e.json,s=n.textures[t];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=e.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return e.loadTextureImage(t,r.source,o)}}class de{constructor(t){this.parser=t,this.name=T.EXT_TEXTURE_WEBP}loadTexture(t){const e=this.name,n=this.parser,s=n.json,r=s.textures[t];if(!r.extensions||!r.extensions[e])return null;const o=r.extensions[e],a=s.images[o.source];let i=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(i=c)}return n.loadTextureImage(t,o.source,i)}}class pe{constructor(t){this.parser=t,this.name=T.EXT_TEXTURE_AVIF}loadTexture(t){const e=this.name,n=this.parser,s=n.json,r=s.textures[t];if(!r.extensions||!r.extensions[e])return null;const o=r.extensions[e],a=s.images[o.source];let i=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(i=c)}return n.loadTextureImage(t,o.source,i)}}class K{constructor(t,e){this.name=e,this.parser=t}loadBufferView(t){const e=this.parser.json,n=e.bufferViews[t];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const i=s.byteOffset||0,c=s.byteLength||0,u=s.count,l=s.byteStride,f=new Uint8Array(a,i,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(u,l,f,s.mode,s.filter).then(function(p){return p.buffer}):o.ready.then(function(){const p=new ArrayBuffer(u*l);return o.decodeGltfBuffer(new Uint8Array(p),u,l,f,s.mode,s.filter),p})})}else return null}}class me{constructor(t){this.name=T.EXT_MESH_GPU_INSTANCING,this.parser=t}createNodeMesh(t){const e=this.parser.json,n=e.nodes[t];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=e.meshes[n.mesh];for(const c of s.primitives)if(c.mode!==S.TRIANGLES&&c.mode!==S.TRIANGLE_STRIP&&c.mode!==S.TRIANGLE_FAN&&c.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],i={};for(const c in o)a.push(this.parser.getDependency("accessor",o[c]).then(u=>(i[c]=u,i[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(t)),Promise.all(a).then(c=>{const u=c.pop(),l=u.isGroup?u.children:[u],f=c[0].count,p=[];for(const m of l){const M=new h.Matrix4,g=new h.Vector3,R=new h.Quaternion,A=new h.Vector3(1,1,1),x=new h.InstancedMesh(m.geometry,m.material,f);for(let E=0;E<f;E++)i.TRANSLATION&&g.fromBufferAttribute(i.TRANSLATION,E),i.ROTATION&&R.fromBufferAttribute(i.ROTATION,E),i.SCALE&&A.fromBufferAttribute(i.SCALE,E),x.setMatrixAt(E,M.compose(g,R,A));for(const E in i)if(E==="_COLOR_0"){const L=i[E];x.instanceColor=new h.InstancedBufferAttribute(L.array,L.itemSize,L.normalized)}else E!=="TRANSLATION"&&E!=="ROTATION"&&E!=="SCALE"&&m.geometry.setAttribute(E,i[E]);h.Object3D.prototype.copy.call(x,m),this.parser.assignFinalMaterial(x),p.push(x)}return u.isGroup?(u.clear(),u.add(...p),u):p[0]}))}}const W="glTF",F=12,j={JSON:1313821514,BIN:5130562};class ge{constructor(t){this.name=T.KHR_BINARY_GLTF,this.content=null,this.body=null;const e=new DataView(t,0,F),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(t.slice(0,4))),version:e.getUint32(4,!0),length:e.getUint32(8,!0)},this.header.magic!==W)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-F,r=new DataView(t,F);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const i=r.getUint32(o,!0);if(o+=4,i===j.JSON){const c=new Uint8Array(t,F+o,a);this.content=n.decode(c)}else if(i===j.BIN){const c=F+o;this.body=t.slice(c,c+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Te{constructor(t,e){if(!e)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=T.KHR_DRACO_MESH_COMPRESSION,this.json=t,this.dracoLoader=e,this.dracoLoader.preload()}decodePrimitive(t,e){const n=this.json,s=this.dracoLoader,r=t.extensions[this.name].bufferView,o=t.extensions[this.name].attributes,a={},i={},c={};for(const u in o){const l=B[u]||u.toLowerCase();a[l]=o[u]}for(const u in t.attributes){const l=B[u]||u.toLowerCase();if(o[u]!==void 0){const f=n.accessors[t.attributes[u]],p=O[f.componentType];c[l]=p.name,i[l]=f.normalized===!0}}return e.getDependency("bufferView",r).then(function(u){return new Promise(function(l,f){s.decodeDracoFile(u,function(p){for(const m in p.attributes){const M=p.attributes[m],g=i[m];g!==void 0&&(M.normalized=g)}l(p)},a,c,h.LinearSRGBColorSpace,f)})})}}class Re{constructor(){this.name=T.KHR_TEXTURE_TRANSFORM}extendTexture(t,e){return(e.texCoord===void 0||e.texCoord===t.channel)&&e.offset===void 0&&e.rotation===void 0&&e.scale===void 0||(t=t.clone(),e.texCoord!==void 0&&(t.channel=e.texCoord),e.offset!==void 0&&t.offset.fromArray(e.offset),e.rotation!==void 0&&(t.rotation=e.rotation),e.scale!==void 0&&t.repeat.fromArray(e.scale),t.needsUpdate=!0),t}}class Me{constructor(){this.name=T.KHR_MESH_QUANTIZATION}}class Y extends h.Interpolant{constructor(t,e,n,s){super(t,e,n,s)}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=t*s*3+s;for(let o=0;o!==s;o++)e[o]=n[r+o];return e}interpolate_(t,e,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,i=a*2,c=a*3,u=s-e,l=(n-e)/u,f=l*l,p=f*l,m=t*c,M=m-c,g=-2*p+3*f,R=p-f,A=1-g,x=R-f+l;for(let E=0;E!==a;E++){const L=o[M+E+a],b=o[M+E+i]*u,y=o[m+E+a],P=o[m+E]*u;r[E]=A*L+x*b+g*y+R*P}return r}}const Ee=new h.Quaternion;class xe extends Y{interpolate_(t,e,n,s){const r=super.interpolate_(t,e,n,s);return Ee.fromArray(r).normalize().toArray(r),r}}const S={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},O={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},V={9728:h.NearestFilter,9729:h.LinearFilter,9984:h.NearestMipmapNearestFilter,9985:h.LinearMipmapNearestFilter,9986:h.NearestMipmapLinearFilter,9987:h.LinearMipmapLinearFilter},z={33071:h.ClampToEdgeWrapping,33648:h.MirroredRepeatWrapping,10497:h.RepeatWrapping},D={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},B={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},N={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Ae={CUBICSPLINE:void 0,LINEAR:h.InterpolateLinear,STEP:h.InterpolateDiscrete},G={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function _e(d){return d.DefaultMaterial===void 0&&(d.DefaultMaterial=new h.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:h.FrontSide})),d.DefaultMaterial}function I(d,t,e){for(const n in e.extensions)d[n]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[n]=e.extensions[n])}function w(d,t){t.extras!==void 0&&(typeof t.extras=="object"?Object.assign(d.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function Le(d,t,e){let n=!1,s=!1,r=!1;for(let c=0,u=t.length;c<u;c++){const l=t[c];if(l.POSITION!==void 0&&(n=!0),l.NORMAL!==void 0&&(s=!0),l.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(d);const o=[],a=[],i=[];for(let c=0,u=t.length;c<u;c++){const l=t[c];if(n){const f=l.POSITION!==void 0?e.getDependency("accessor",l.POSITION):d.attributes.position;o.push(f)}if(s){const f=l.NORMAL!==void 0?e.getDependency("accessor",l.NORMAL):d.attributes.normal;a.push(f)}if(r){const f=l.COLOR_0!==void 0?e.getDependency("accessor",l.COLOR_0):d.attributes.color;i.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(i)]).then(function(c){const u=c[0],l=c[1],f=c[2];return n&&(d.morphAttributes.position=u),s&&(d.morphAttributes.normal=l),r&&(d.morphAttributes.color=f),d.morphTargetsRelative=!0,d})}function Se(d,t){if(d.updateMorphTargets(),t.weights!==void 0)for(let e=0,n=t.weights.length;e<n;e++)d.morphTargetInfluences[e]=t.weights[e];if(t.extras&&Array.isArray(t.extras.targetNames)){const e=t.extras.targetNames;if(d.morphTargetInfluences.length===e.length){d.morphTargetDictionary={};for(let n=0,s=e.length;n<s;n++)d.morphTargetDictionary[e[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function ye(d){let t;const e=d.extensions&&d.extensions[T.KHR_DRACO_MESH_COMPRESSION];if(e?t="draco:"+e.bufferView+":"+e.indices+":"+v(e.attributes):t=d.indices+":"+v(d.attributes)+":"+d.mode,d.targets!==void 0)for(let n=0,s=d.targets.length;n<s;n++)t+=":"+v(d.targets[n]);return t}function v(d){let t="";const e=Object.keys(d).sort();for(let n=0,s=e.length;n<s;n++)t+=e[n]+":"+d[e[n]]+";";return t}function U(d){switch(d){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function we(d){return d.search(/\.jpe?g($|\?)/i)>0||d.search(/^data\:image\/jpeg/)===0?"image/jpeg":d.search(/\.webp($|\?)/i)>0||d.search(/^data\:image\/webp/)===0?"image/webp":d.search(/\.ktx2($|\?)/i)>0||d.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const be=new h.Matrix4;class Ne{constructor(t={},e={}){this.json=t,this.extensions={},this.plugins={},this.options=e,this.cache=new Z,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const i=a.match(/Version\/(\d+)/);s=n&&i?parseInt(i[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new h.TextureLoader(this.options.manager):this.textureLoader=new h.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new h.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(t){this.extensions=t}setPlugins(t){this.plugins=t}parse(t,e){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return I(r,a,s),w(a,s),Promise.all(n._invokeAll(function(i){return i.afterRoot&&i.afterRoot(a)})).then(function(){for(const i of a.scenes)i.updateMatrixWorld();t(a)})}).catch(e)}_markDefs(){const t=this.json.nodes||[],e=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=e.length;s<r;s++){const o=e[s].joints;for(let a=0,i=o.length;a<i;a++)t[o[a]].isBone=!0}for(let s=0,r=t.length;s<r;s++){const o=t[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(t,e){e!==void 0&&(t.refs[e]===void 0&&(t.refs[e]=t.uses[e]=0),t.refs[e]++)}_getNodeRef(t,e,n){if(t.refs[e]<=1)return n;const s=n.clone(),r=(o,a)=>{const i=this.associations.get(o);i!=null&&this.associations.set(a,i);for(const[c,u]of o.children.entries())r(u,a.children[c])};return r(n,s),s.name+="_instance_"+t.uses[e]++,s}_invokeOne(t){const e=Object.values(this.plugins);e.push(this);for(let n=0;n<e.length;n++){const s=t(e[n]);if(s)return s}return null}_invokeAll(t){const e=Object.values(this.plugins);e.unshift(this);const n=[];for(let s=0;s<e.length;s++){const r=t(e[s]);r&&n.push(r)}return n}getDependency(t,e){const n=t+":"+e;let s=this.cache.get(n);if(!s){switch(t){case"scene":s=this.loadScene(e);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(e)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(e)});break;case"accessor":s=this.loadAccessor(e);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(e)});break;case"buffer":s=this.loadBuffer(e);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(e)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(e)});break;case"skin":s=this.loadSkin(e);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(e)});break;case"camera":s=this.loadCamera(e);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(t,e)}),!s)throw new Error("Unknown type: "+t);break}this.cache.add(n,s)}return s}getDependencies(t){let e=this.cache.get(t);if(!e){const n=this,s=this.json[t+(t==="mesh"?"es":"s")]||[];e=Promise.all(s.map(function(r,o){return n.getDependency(t,o)})),this.cache.add(t,e)}return e}loadBuffer(t){const e=this.json.buffers[t],n=this.fileLoader;if(e.type&&e.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+e.type+" buffer type is not supported.");if(e.uri===void 0&&t===0)return Promise.resolve(this.extensions[T.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(h.LoaderUtils.resolveURL(e.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+e.uri+'".'))})})}loadBufferView(t){const e=this.json.bufferViews[t];return this.getDependency("buffer",e.buffer).then(function(n){const s=e.byteLength||0,r=e.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(t){const e=this,n=this.json,s=this.json.accessors[t];if(s.bufferView===void 0&&s.sparse===void 0){const o=D[s.type],a=O[s.componentType],i=s.normalized===!0,c=new a(s.count*o);return Promise.resolve(new h.BufferAttribute(c,o,i))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],i=D[s.type],c=O[s.componentType],u=c.BYTES_PER_ELEMENT,l=u*i,f=s.byteOffset||0,p=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,m=s.normalized===!0;let M,g;if(p&&p!==l){const R=Math.floor(f/p),A="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+R+":"+s.count;let x=e.cache.get(A);x||(M=new c(a,R*p,s.count*p/u),x=new h.InterleavedBuffer(M,p/u),e.cache.add(A,x)),g=new h.InterleavedBufferAttribute(x,i,f%p/u,m)}else a===null?M=new c(s.count*i):M=new c(a,f,s.count*i),g=new h.BufferAttribute(M,i,m);if(s.sparse!==void 0){const R=D.SCALAR,A=O[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,E=s.sparse.values.byteOffset||0,L=new A(o[1],x,s.sparse.count*R),b=new c(o[2],E,s.sparse.count*i);a!==null&&(g=new h.BufferAttribute(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let y=0,P=L.length;y<P;y++){const C=L[y];if(g.setX(C,b[y*i]),i>=2&&g.setY(C,b[y*i+1]),i>=3&&g.setZ(C,b[y*i+2]),i>=4&&g.setW(C,b[y*i+3]),i>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=m}return g})}loadTexture(t){const e=this.json,n=this.options,r=e.textures[t].source,o=e.images[r];let a=this.textureLoader;if(o.uri){const i=n.manager.getHandler(o.uri);i!==null&&(a=i)}return this.loadTextureImage(t,r,a)}loadTextureImage(t,e,n){const s=this,r=this.json,o=r.textures[t],a=r.images[e],i=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[i])return this.textureCache[i];const c=this.loadImageSource(e,n).then(function(u){u.flipY=!1,u.name=o.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return u.magFilter=V[f.magFilter]||h.LinearFilter,u.minFilter=V[f.minFilter]||h.LinearMipmapLinearFilter,u.wrapS=z[f.wrapS]||h.RepeatWrapping,u.wrapT=z[f.wrapT]||h.RepeatWrapping,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==h.NearestFilter&&u.minFilter!==h.LinearFilter,s.associations.set(u,{textures:t}),u}).catch(function(){return null});return this.textureCache[i]=c,c}loadImageSource(t,e){const n=this,s=this.json,r=this.options;if(this.sourceCache[t]!==void 0)return this.sourceCache[t].then(l=>l.clone());const o=s.images[t],a=self.URL||self.webkitURL;let i=o.uri||"",c=!1;if(o.bufferView!==void 0)i=n.getDependency("bufferView",o.bufferView).then(function(l){c=!0;const f=new Blob([l],{type:o.mimeType});return i=a.createObjectURL(f),i});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+t+" is missing URI and bufferView");const u=Promise.resolve(i).then(function(l){return new Promise(function(f,p){let m=f;e.isImageBitmapLoader===!0&&(m=function(M){const g=new h.Texture(M);g.needsUpdate=!0,f(g)}),e.load(h.LoaderUtils.resolveURL(l,r.path),m,void 0,p)})}).then(function(l){return c===!0&&a.revokeObjectURL(i),w(l,o),l.userData.mimeType=o.mimeType||we(o.uri),l}).catch(function(l){throw console.error("THREE.GLTFLoader: Couldn't load texture",i),l});return this.sourceCache[t]=u,u}assignTexture(t,e,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[T.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[T.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const i=r.associations.get(o);o=r.extensions[T.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,i)}}return s!==void 0&&(o.colorSpace=s),t[e]=o,o})}assignFinalMaterial(t){const e=t.geometry;let n=t.material;const s=e.attributes.tangent===void 0,r=e.attributes.color!==void 0,o=e.attributes.normal===void 0;if(t.isPoints){const a="PointsMaterial:"+n.uuid;let i=this.cache.get(a);i||(i=new h.PointsMaterial,h.Material.prototype.copy.call(i,n),i.color.copy(n.color),i.map=n.map,i.sizeAttenuation=!1,this.cache.add(a,i)),n=i}else if(t.isLine){const a="LineBasicMaterial:"+n.uuid;let i=this.cache.get(a);i||(i=new h.LineBasicMaterial,h.Material.prototype.copy.call(i,n),i.color.copy(n.color),i.map=n.map,this.cache.add(a,i)),n=i}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let i=this.cache.get(a);i||(i=n.clone(),r&&(i.vertexColors=!0),o&&(i.flatShading=!0),s&&(i.normalScale&&(i.normalScale.y*=-1),i.clearcoatNormalScale&&(i.clearcoatNormalScale.y*=-1)),this.cache.add(a,i),this.associations.set(i,this.associations.get(n))),n=i}t.material=n}getMaterialType(){return h.MeshStandardMaterial}loadMaterial(t){const e=this,n=this.json,s=this.extensions,r=n.materials[t];let o;const a={},i=r.extensions||{},c=[];if(i[T.KHR_MATERIALS_UNLIT]){const l=s[T.KHR_MATERIALS_UNLIT];o=l.getMaterialType(),c.push(l.extendParams(a,r,e))}else{const l=r.pbrMetallicRoughness||{};if(a.color=new h.Color(1,1,1),a.opacity=1,Array.isArray(l.baseColorFactor)){const f=l.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],h.LinearSRGBColorSpace),a.opacity=f[3]}l.baseColorTexture!==void 0&&c.push(e.assignTexture(a,"map",l.baseColorTexture,h.SRGBColorSpace)),a.metalness=l.metallicFactor!==void 0?l.metallicFactor:1,a.roughness=l.roughnessFactor!==void 0?l.roughnessFactor:1,l.metallicRoughnessTexture!==void 0&&(c.push(e.assignTexture(a,"metalnessMap",l.metallicRoughnessTexture)),c.push(e.assignTexture(a,"roughnessMap",l.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(t)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(t,a)})))}r.doubleSided===!0&&(a.side=h.DoubleSide);const u=r.alphaMode||G.OPAQUE;if(u===G.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===G.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==h.MeshBasicMaterial&&(c.push(e.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new h.Vector2(1,1),r.normalTexture.scale!==void 0)){const l=r.normalTexture.scale;a.normalScale.set(l,l)}if(r.occlusionTexture!==void 0&&o!==h.MeshBasicMaterial&&(c.push(e.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==h.MeshBasicMaterial){const l=r.emissiveFactor;a.emissive=new h.Color().setRGB(l[0],l[1],l[2],h.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==h.MeshBasicMaterial&&c.push(e.assignTexture(a,"emissiveMap",r.emissiveTexture,h.SRGBColorSpace)),Promise.all(c).then(function(){const l=new o(a);return r.name&&(l.name=r.name),w(l,r),e.associations.set(l,{materials:t}),r.extensions&&I(s,l,r),l})}createUniqueName(t){const e=h.PropertyBinding.sanitizeNodeName(t||"");return e in this.nodeNamesUsed?e+"_"+ ++this.nodeNamesUsed[e]:(this.nodeNamesUsed[e]=0,e)}loadGeometries(t){const e=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[T.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,e).then(function(i){return X(i,a,e)})}const o=[];for(let a=0,i=t.length;a<i;a++){const c=t[a],u=ye(c),l=s[u];if(l)o.push(l.promise);else{let f;c.extensions&&c.extensions[T.KHR_DRACO_MESH_COMPRESSION]?f=r(c):f=X(new h.BufferGeometry,c,e),s[u]={primitive:c,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(t){const e=this,n=this.json,s=this.extensions,r=n.meshes[t],o=r.primitives,a=[];for(let i=0,c=o.length;i<c;i++){const u=o[i].material===void 0?_e(this.cache):this.getDependency("material",o[i].material);a.push(u)}return a.push(e.loadGeometries(o)),Promise.all(a).then(function(i){const c=i.slice(0,i.length-1),u=i[i.length-1],l=[];for(let p=0,m=u.length;p<m;p++){const M=u[p],g=o[p];let R;const A=c[p];if(g.mode===S.TRIANGLES||g.mode===S.TRIANGLE_STRIP||g.mode===S.TRIANGLE_FAN||g.mode===void 0)R=r.isSkinnedMesh===!0?new h.SkinnedMesh(M,A):new h.Mesh(M,A),R.isSkinnedMesh===!0&&R.normalizeSkinWeights(),g.mode===S.TRIANGLE_STRIP?R.geometry=h.toTrianglesDrawMode(R.geometry,h.TriangleStripDrawMode):g.mode===S.TRIANGLE_FAN&&(R.geometry=h.toTrianglesDrawMode(R.geometry,h.TriangleFanDrawMode));else if(g.mode===S.LINES)R=new h.LineSegments(M,A);else if(g.mode===S.LINE_STRIP)R=new h.Line(M,A);else if(g.mode===S.LINE_LOOP)R=new h.LineLoop(M,A);else if(g.mode===S.POINTS)R=new h.Points(M,A);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(R.geometry.morphAttributes).length>0&&Se(R,r),R.name=e.createUniqueName(r.name||"mesh_"+t),w(R,r),g.extensions&&I(s,R,g),e.assignFinalMaterial(R),l.push(R)}for(let p=0,m=l.length;p<m;p++)e.associations.set(l[p],{meshes:t,primitives:p});if(l.length===1)return r.extensions&&I(s,l[0],r),l[0];const f=new h.Group;r.extensions&&I(s,f,r),e.associations.set(f,{meshes:t});for(let p=0,m=l.length;p<m;p++)f.add(l[p]);return f})}loadCamera(t){let e;const n=this.json.cameras[t],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?e=new h.PerspectiveCamera(h.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(e=new h.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(e.name=this.createUniqueName(n.name)),w(e,n),Promise.resolve(e)}loadSkin(t){const e=this.json.skins[t],n=[];for(let s=0,r=e.joints.length;s<r;s++)n.push(this._loadNodeShallow(e.joints[s]));return e.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",e.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],i=[];for(let c=0,u=o.length;c<u;c++){const l=o[c];if(l){a.push(l);const f=new h.Matrix4;r!==null&&f.fromArray(r.array,c*16),i.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',e.joints[c])}return new h.Skeleton(a,i)})}loadAnimation(t){const e=this.json,n=this,s=e.animations[t],r=s.name?s.name:"animation_"+t,o=[],a=[],i=[],c=[],u=[];for(let l=0,f=s.channels.length;l<f;l++){const p=s.channels[l],m=s.samplers[p.sampler],M=p.target,g=M.node,R=s.parameters!==void 0?s.parameters[m.input]:m.input,A=s.parameters!==void 0?s.parameters[m.output]:m.output;M.node!==void 0&&(o.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",R)),i.push(this.getDependency("accessor",A)),c.push(m),u.push(M))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(i),Promise.all(c),Promise.all(u)]).then(function(l){const f=l[0],p=l[1],m=l[2],M=l[3],g=l[4],R=[];for(let x=0,E=f.length;x<E;x++){const L=f[x],b=p[x],y=m[x],P=M[x],C=g[x];if(L===void 0)continue;L.updateMatrix&&L.updateMatrix();const k=n._createAnimationTracks(L,b,y,P,C);if(k)for(let H=0;H<k.length;H++)R.push(k[H])}const A=new h.AnimationClip(r,void 0,R);return w(A,s),A})}createNodeMesh(t){const e=this.json,n=this,s=e.nodes[t];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let i=0,c=s.weights.length;i<c;i++)a.morphTargetInfluences[i]=s.weights[i]}),o})}loadNode(t){const e=this.json,n=this,s=e.nodes[t],r=n._loadNodeShallow(t),o=[],a=s.children||[];for(let c=0,u=a.length;c<u;c++)o.push(n.getDependency("node",a[c]));const i=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),i]).then(function(c){const u=c[0],l=c[1],f=c[2];f!==null&&u.traverse(function(p){p.isSkinnedMesh&&p.bind(f,be)});for(let p=0,m=l.length;p<m;p++)u.add(l[p]);if(u.userData.pivot!==void 0&&l.length>0){const p=u.userData.pivot,m=l[0];u.pivot=new h.Vector3().fromArray(p),u.position.x-=p[0],u.position.y-=p[1],u.position.z-=p[2],m.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(t){const e=this.json,n=this.extensions,s=this;if(this.nodeCache[t]!==void 0)return this.nodeCache[t];const r=e.nodes[t],o=r.name?s.createUniqueName(r.name):"",a=[],i=s._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(t)});return i&&a.push(i),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(c){return s._getNodeRef(s.cameraCache,r.camera,c)})),s._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(t)}).forEach(function(c){a.push(c)}),this.nodeCache[t]=Promise.all(a).then(function(c){let u;if(r.isBone===!0?u=new h.Bone:c.length>1?u=new h.Group:c.length===1?u=c[0]:u=new h.Object3D,u!==c[0])for(let l=0,f=c.length;l<f;l++)u.add(c[l]);if(r.name&&(u.userData.name=r.name,u.name=o),w(u,r),r.extensions&&I(n,u,r),r.matrix!==void 0){const l=new h.Matrix4;l.fromArray(r.matrix),u.applyMatrix4(l)}else r.translation!==void 0&&u.position.fromArray(r.translation),r.rotation!==void 0&&u.quaternion.fromArray(r.rotation),r.scale!==void 0&&u.scale.fromArray(r.scale);if(!s.associations.has(u))s.associations.set(u,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const l=s.associations.get(u);s.associations.set(u,{...l})}return s.associations.get(u).nodes=t,u}),this.nodeCache[t]}loadScene(t){const e=this.extensions,n=this.json.scenes[t],s=this,r=new h.Group;n.name&&(r.name=s.createUniqueName(n.name)),w(r,n),n.extensions&&I(e,r,n);const o=n.nodes||[],a=[];for(let i=0,c=o.length;i<c;i++)a.push(s.getDependency("node",o[i]));return Promise.all(a).then(function(i){for(let u=0,l=i.length;u<l;u++){const f=i[u];f.parent!==null?r.add(Q(f)):r.add(f)}const c=u=>{const l=new Map;for(const[f,p]of s.associations)(f instanceof h.Material||f instanceof h.Texture)&&l.set(f,p);return u.traverse(f=>{const p=s.associations.get(f);p!=null&&l.set(f,p)}),l};return s.associations=c(r),r})}_createAnimationTracks(t,e,n,s,r){const o=[],a=t.name?t.name:t.uuid,i=[];N[r.path]===N.weights?t.traverse(function(f){f.morphTargetInfluences&&i.push(f.name?f.name:f.uuid)}):i.push(a);let c;switch(N[r.path]){case N.weights:c=h.NumberKeyframeTrack;break;case N.rotation:c=h.QuaternionKeyframeTrack;break;case N.translation:case N.scale:c=h.VectorKeyframeTrack;break;default:n.itemSize===1?c=h.NumberKeyframeTrack:c=h.VectorKeyframeTrack;break}const u=s.interpolation!==void 0?Ae[s.interpolation]:h.InterpolateLinear,l=this._getArrayFromAccessor(n);for(let f=0,p=i.length;f<p;f++){const m=new c(i[f]+"."+N[r.path],e.array,l,u);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),o.push(m)}return o}_getArrayFromAccessor(t){let e=t.array;if(t.normalized){const n=U(e.constructor),s=new Float32Array(e.length);for(let r=0,o=e.length;r<o;r++)s[r]=e[r]*n;e=s}return e}_createCubicSplineTrackInterpolant(t){t.createInterpolant=function(n){const s=this instanceof h.QuaternionKeyframeTrack?xe:Y;return new s(this.times,this.values,this.getValueSize()/3,n)},t.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ie(d,t,e){const n=t.attributes,s=new h.Box3;if(n.POSITION!==void 0){const a=e.json.accessors[n.POSITION],i=a.min,c=a.max;if(i!==void 0&&c!==void 0){if(s.set(new h.Vector3(i[0],i[1],i[2]),new h.Vector3(c[0],c[1],c[2])),a.normalized){const u=U(O[a.componentType]);s.min.multiplyScalar(u),s.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=t.targets;if(r!==void 0){const a=new h.Vector3,i=new h.Vector3;for(let c=0,u=r.length;c<u;c++){const l=r[c];if(l.POSITION!==void 0){const f=e.json.accessors[l.POSITION],p=f.min,m=f.max;if(p!==void 0&&m!==void 0){if(i.setX(Math.max(Math.abs(p[0]),Math.abs(m[0]))),i.setY(Math.max(Math.abs(p[1]),Math.abs(m[1]))),i.setZ(Math.max(Math.abs(p[2]),Math.abs(m[2]))),f.normalized){const M=U(O[f.componentType]);i.multiplyScalar(M)}a.max(i)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}d.boundingBox=s;const o=new h.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,d.boundingSphere=o}function X(d,t,e){const n=t.attributes,s=[];function r(o,a){return e.getDependency("accessor",o).then(function(i){d.setAttribute(a,i)})}for(const o in n){const a=B[o]||o.toLowerCase();a in d.attributes||s.push(r(n[o],a))}if(t.indices!==void 0&&!d.index){const o=e.getDependency("accessor",t.indices).then(function(a){d.setIndex(a)});s.push(o)}return h.ColorManagement.workingColorSpace!==h.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${h.ColorManagement.workingColorSpace}" not supported.`),w(d,t),Ie(d,t,e),Promise.all(s).then(function(){return t.targets!==void 0?Le(d,t.targets,e):d})}exports.GLTFLoader=J;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./duo-frame-B1NXSk6a.js");function Q(d){const t=new Map,e=new Map,n=d.clone();return q(d,n,function(s,r){t.set(r,s),e.set(s,r)}),n.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=t.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(i){return e.get(i)}),r.bind(r.skeleton,r.bindMatrix)}),n}function q(d,t,e){e(d,t);for(let n=0;n<d.children.length;n++)q(d.children[n],t.children[n],e)}class J extends h.Loader{constructor(t){super(t),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new ne(e)}),this.register(function(e){return new se(e)}),this.register(function(e){return new fe(e)}),this.register(function(e){return new de(e)}),this.register(function(e){return new pe(e)}),this.register(function(e){return new ie(e)}),this.register(function(e){return new oe(e)}),this.register(function(e){return new ae(e)}),this.register(function(e){return new ce(e)}),this.register(function(e){return new te(e)}),this.register(function(e){return new le(e)}),this.register(function(e){return new re(e)}),this.register(function(e){return new he(e)}),this.register(function(e){return new ue(e)}),this.register(function(e){return new $(e)}),this.register(function(e){return new K(e,T.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new K(e,T.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new me(e)})}load(t,e,n,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const c=h.LoaderUtils.extractUrlBase(t);o=h.LoaderUtils.resolveURL(c,this.path)}else o=h.LoaderUtils.extractUrlBase(t);this.manager.itemStart(t);const a=function(c){s?s(c):console.error(c),r.manager.itemError(t),r.manager.itemEnd(t)},i=new h.FileLoader(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(t,function(c){try{r.parse(c,o,function(u){e(u),r.manager.itemEnd(t)},a)}catch(u){a(u)}},n,a)}setDRACOLoader(t){return this.dracoLoader=t,this}setKTX2Loader(t){return this.ktx2Loader=t,this}setMeshoptDecoder(t){return this.meshoptDecoder=t,this}register(t){return this.pluginCallbacks.indexOf(t)===-1&&this.pluginCallbacks.push(t),this}unregister(t){return this.pluginCallbacks.indexOf(t)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(t),1),this}parse(t,e,n,s){let r;const o={},a={},i=new TextDecoder;if(typeof t=="string")r=JSON.parse(t);else if(t instanceof ArrayBuffer)if(i.decode(new Uint8Array(t,0,4))===W){try{o[T.KHR_BINARY_GLTF]=new ge(t)}catch(l){s&&s(l);return}r=JSON.parse(o[T.KHR_BINARY_GLTF].content)}else r=JSON.parse(i.decode(t));else r=t;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new Ne(r,{path:e||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const l=this.pluginCallbacks[u](c);l.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[l.name]=l,o[l.name]=!0}if(r.extensionsUsed)for(let u=0;u<r.extensionsUsed.length;++u){const l=r.extensionsUsed[u],f=r.extensionsRequired||[];switch(l){case T.KHR_MATERIALS_UNLIT:o[l]=new ee;break;case T.KHR_DRACO_MESH_COMPRESSION:o[l]=new Te(r,this.dracoLoader);break;case T.KHR_TEXTURE_TRANSFORM:o[l]=new Re;break;case T.KHR_MESH_QUANTIZATION:o[l]=new Me;break;default:f.indexOf(l)>=0&&a[l]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+l+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(n,s)}parseAsync(t,e){const n=this;return new Promise(function(s,r){n.parse(t,e,s,r)})}}function Z(){let d={};return{get:function(t){return d[t]},add:function(t,e){d[t]=e},remove:function(t){delete d[t]},removeAll:function(){d={}}}}function _(d,t,e){const n=d.json.materials[t];return n.extensions&&n.extensions[e]?n.extensions[e]:null}const T={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ${constructor(t){this.parser=t,this.name=T.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const t=this.parser,e=this.parser.json.nodes||[];for(let n=0,s=e.length;n<s;n++){const r=e[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&t._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(t){const e=this.parser,n="light:"+t;let s=e.cache.get(n);if(s)return s;const r=e.json,i=((r.extensions&&r.extensions[this.name]||{}).lights||[])[t];let c;const u=new h.Color(16777215);i.color!==void 0&&u.setRGB(i.color[0],i.color[1],i.color[2],h.LinearSRGBColorSpace);const l=i.range!==void 0?i.range:0;switch(i.type){case"directional":c=new h.DirectionalLight(u),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new h.PointLight(u),c.distance=l;break;case"spot":c=new h.SpotLight(u),c.distance=l,i.spot=i.spot||{},i.spot.innerConeAngle=i.spot.innerConeAngle!==void 0?i.spot.innerConeAngle:0,i.spot.outerConeAngle=i.spot.outerConeAngle!==void 0?i.spot.outerConeAngle:Math.PI/4,c.angle=i.spot.outerConeAngle,c.penumbra=1-i.spot.innerConeAngle/i.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+i.type)}return c.position.set(0,0,0),w(c,i),i.intensity!==void 0&&(c.intensity=i.intensity),c.name=e.createUniqueName(i.name||"light_"+t),s=Promise.resolve(c),e.cache.add(n,s),s}getDependency(t,e){if(t==="light")return this._loadLight(e)}createNodeAttachment(t){const e=this,n=this.parser,r=n.json.nodes[t],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(i){return n._getNodeRef(e.cache,a,i)})}}class ee{constructor(){this.name=T.KHR_MATERIALS_UNLIT}getMaterialType(){return h.MeshBasicMaterial}extendParams(t,e,n){const s=[];t.color=new h.Color(1,1,1),t.opacity=1;const r=e.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;t.color.setRGB(o[0],o[1],o[2],h.LinearSRGBColorSpace),t.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(t,"map",r.baseColorTexture,h.SRGBColorSpace))}return Promise.all(s)}}class te{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||n.emissiveStrength!==void 0&&(e.emissiveIntensity=n.emissiveStrength),Promise.resolve()}}class ne{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_CLEARCOAT}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];if(n.clearcoatFactor!==void 0&&(e.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(e,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(e.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(e,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(e,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){const r=n.clearcoatNormalTexture.scale;e.clearcoatNormalScale=new h.Vector2(r,r)}return Promise.all(s)}}class se{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_DISPERSION}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||(e.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}}class re{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_IRIDESCENCE}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.iridescenceFactor!==void 0&&(e.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(e,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(e.iridescenceIOR=n.iridescenceIor),e.iridescenceThicknessRange===void 0&&(e.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(e.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(e.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(e,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(s)}}class ie{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_SHEEN}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];if(e.sheenColor=new h.Color(0,0,0),e.sheenRoughness=0,e.sheen=1,n.sheenColorFactor!==void 0){const r=n.sheenColorFactor;e.sheenColor.setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace)}return n.sheenRoughnessFactor!==void 0&&(e.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(e,"sheenColorMap",n.sheenColorTexture,h.SRGBColorSpace)),n.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(e,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(s)}}class oe{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_TRANSMISSION}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.transmissionFactor!==void 0&&(e.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(e,"transmissionMap",n.transmissionTexture)),Promise.all(s)}}class ae{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_VOLUME}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];e.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(e,"thicknessMap",n.thicknessTexture)),e.attenuationDistance=n.attenuationDistance||1/0;const r=n.attenuationColor||[1,1,1];return e.attenuationColor=new h.Color().setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace),Promise.all(s)}}class ce{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_IOR}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);return n===null||(e.ior=n.ior!==void 0?n.ior:1.5),Promise.resolve()}}class le{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_SPECULAR}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];e.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&s.push(this.parser.assignTexture(e,"specularIntensityMap",n.specularTexture));const r=n.specularColorFactor||[1,1,1];return e.specularColor=new h.Color().setRGB(r[0],r[1],r[2],h.LinearSRGBColorSpace),n.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(e,"specularColorMap",n.specularColorTexture,h.SRGBColorSpace)),Promise.all(s)}}class ue{constructor(t){this.parser=t,this.name=T.EXT_MATERIALS_BUMP}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return e.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&s.push(this.parser.assignTexture(e,"bumpMap",n.bumpTexture)),Promise.all(s)}}class he{constructor(t){this.parser=t,this.name=T.KHR_MATERIALS_ANISOTROPY}getMaterialType(t){return _(this.parser,t,this.name)!==null?h.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const n=_(this.parser,t,this.name);if(n===null)return Promise.resolve();const s=[];return n.anisotropyStrength!==void 0&&(e.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(e.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(e,"anisotropyMap",n.anisotropyTexture)),Promise.all(s)}}class fe{constructor(t){this.parser=t,this.name=T.KHR_TEXTURE_BASISU}loadTexture(t){const e=this.parser,n=e.json,s=n.textures[t];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=e.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return e.loadTextureImage(t,r.source,o)}}class de{constructor(t){this.parser=t,this.name=T.EXT_TEXTURE_WEBP}loadTexture(t){const e=this.name,n=this.parser,s=n.json,r=s.textures[t];if(!r.extensions||!r.extensions[e])return null;const o=r.extensions[e],a=s.images[o.source];let i=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(i=c)}return n.loadTextureImage(t,o.source,i)}}class pe{constructor(t){this.parser=t,this.name=T.EXT_TEXTURE_AVIF}loadTexture(t){const e=this.name,n=this.parser,s=n.json,r=s.textures[t];if(!r.extensions||!r.extensions[e])return null;const o=r.extensions[e],a=s.images[o.source];let i=n.textureLoader;if(a.uri){const c=n.options.manager.getHandler(a.uri);c!==null&&(i=c)}return n.loadTextureImage(t,o.source,i)}}class K{constructor(t,e){this.name=e,this.parser=t}loadBufferView(t){const e=this.parser.json,n=e.bufferViews[t];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const i=s.byteOffset||0,c=s.byteLength||0,u=s.count,l=s.byteStride,f=new Uint8Array(a,i,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(u,l,f,s.mode,s.filter).then(function(p){return p.buffer}):o.ready.then(function(){const p=new ArrayBuffer(u*l);return o.decodeGltfBuffer(new Uint8Array(p),u,l,f,s.mode,s.filter),p})})}else return null}}class me{constructor(t){this.name=T.EXT_MESH_GPU_INSTANCING,this.parser=t}createNodeMesh(t){const e=this.parser.json,n=e.nodes[t];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=e.meshes[n.mesh];for(const c of s.primitives)if(c.mode!==S.TRIANGLES&&c.mode!==S.TRIANGLE_STRIP&&c.mode!==S.TRIANGLE_FAN&&c.mode!==void 0)return null;const o=n.extensions[this.name].attributes,a=[],i={};for(const c in o)a.push(this.parser.getDependency("accessor",o[c]).then(u=>(i[c]=u,i[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(t)),Promise.all(a).then(c=>{const u=c.pop(),l=u.isGroup?u.children:[u],f=c[0].count,p=[];for(const m of l){const M=new h.Matrix4,g=new h.Vector3,R=new h.Quaternion,A=new h.Vector3(1,1,1),x=new h.InstancedMesh(m.geometry,m.material,f);for(let E=0;E<f;E++)i.TRANSLATION&&g.fromBufferAttribute(i.TRANSLATION,E),i.ROTATION&&R.fromBufferAttribute(i.ROTATION,E),i.SCALE&&A.fromBufferAttribute(i.SCALE,E),x.setMatrixAt(E,M.compose(g,R,A));for(const E in i)if(E==="_COLOR_0"){const L=i[E];x.instanceColor=new h.InstancedBufferAttribute(L.array,L.itemSize,L.normalized)}else E!=="TRANSLATION"&&E!=="ROTATION"&&E!=="SCALE"&&m.geometry.setAttribute(E,i[E]);h.Object3D.prototype.copy.call(x,m),this.parser.assignFinalMaterial(x),p.push(x)}return u.isGroup?(u.clear(),u.add(...p),u):p[0]}))}}const W="glTF",F=12,j={JSON:1313821514,BIN:5130562};class ge{constructor(t){this.name=T.KHR_BINARY_GLTF,this.content=null,this.body=null;const e=new DataView(t,0,F),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(t.slice(0,4))),version:e.getUint32(4,!0),length:e.getUint32(8,!0)},this.header.magic!==W)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-F,r=new DataView(t,F);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const i=r.getUint32(o,!0);if(o+=4,i===j.JSON){const c=new Uint8Array(t,F+o,a);this.content=n.decode(c)}else if(i===j.BIN){const c=F+o;this.body=t.slice(c,c+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Te{constructor(t,e){if(!e)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=T.KHR_DRACO_MESH_COMPRESSION,this.json=t,this.dracoLoader=e,this.dracoLoader.preload()}decodePrimitive(t,e){const n=this.json,s=this.dracoLoader,r=t.extensions[this.name].bufferView,o=t.extensions[this.name].attributes,a={},i={},c={};for(const u in o){const l=B[u]||u.toLowerCase();a[l]=o[u]}for(const u in t.attributes){const l=B[u]||u.toLowerCase();if(o[u]!==void 0){const f=n.accessors[t.attributes[u]],p=O[f.componentType];c[l]=p.name,i[l]=f.normalized===!0}}return e.getDependency("bufferView",r).then(function(u){return new Promise(function(l,f){s.decodeDracoFile(u,function(p){for(const m in p.attributes){const M=p.attributes[m],g=i[m];g!==void 0&&(M.normalized=g)}l(p)},a,c,h.LinearSRGBColorSpace,f)})})}}class Re{constructor(){this.name=T.KHR_TEXTURE_TRANSFORM}extendTexture(t,e){return(e.texCoord===void 0||e.texCoord===t.channel)&&e.offset===void 0&&e.rotation===void 0&&e.scale===void 0||(t=t.clone(),e.texCoord!==void 0&&(t.channel=e.texCoord),e.offset!==void 0&&t.offset.fromArray(e.offset),e.rotation!==void 0&&(t.rotation=e.rotation),e.scale!==void 0&&t.repeat.fromArray(e.scale),t.needsUpdate=!0),t}}class Me{constructor(){this.name=T.KHR_MESH_QUANTIZATION}}class Y extends h.Interpolant{constructor(t,e,n,s){super(t,e,n,s)}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=t*s*3+s;for(let o=0;o!==s;o++)e[o]=n[r+o];return e}interpolate_(t,e,n,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,i=a*2,c=a*3,u=s-e,l=(n-e)/u,f=l*l,p=f*l,m=t*c,M=m-c,g=-2*p+3*f,R=p-f,A=1-g,x=R-f+l;for(let E=0;E!==a;E++){const L=o[M+E+a],b=o[M+E+i]*u,y=o[m+E+a],P=o[m+E]*u;r[E]=A*L+x*b+g*y+R*P}return r}}const Ee=new h.Quaternion;class xe extends Y{interpolate_(t,e,n,s){const r=super.interpolate_(t,e,n,s);return Ee.fromArray(r).normalize().toArray(r),r}}const S={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},O={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},V={9728:h.NearestFilter,9729:h.LinearFilter,9984:h.NearestMipmapNearestFilter,9985:h.LinearMipmapNearestFilter,9986:h.NearestMipmapLinearFilter,9987:h.LinearMipmapLinearFilter},z={33071:h.ClampToEdgeWrapping,33648:h.MirroredRepeatWrapping,10497:h.RepeatWrapping},D={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},B={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},N={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Ae={CUBICSPLINE:void 0,LINEAR:h.InterpolateLinear,STEP:h.InterpolateDiscrete},G={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function _e(d){return d.DefaultMaterial===void 0&&(d.DefaultMaterial=new h.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:h.FrontSide})),d.DefaultMaterial}function I(d,t,e){for(const n in e.extensions)d[n]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[n]=e.extensions[n])}function w(d,t){t.extras!==void 0&&(typeof t.extras=="object"?Object.assign(d.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function Le(d,t,e){let n=!1,s=!1,r=!1;for(let c=0,u=t.length;c<u;c++){const l=t[c];if(l.POSITION!==void 0&&(n=!0),l.NORMAL!==void 0&&(s=!0),l.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(d);const o=[],a=[],i=[];for(let c=0,u=t.length;c<u;c++){const l=t[c];if(n){const f=l.POSITION!==void 0?e.getDependency("accessor",l.POSITION):d.attributes.position;o.push(f)}if(s){const f=l.NORMAL!==void 0?e.getDependency("accessor",l.NORMAL):d.attributes.normal;a.push(f)}if(r){const f=l.COLOR_0!==void 0?e.getDependency("accessor",l.COLOR_0):d.attributes.color;i.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(i)]).then(function(c){const u=c[0],l=c[1],f=c[2];return n&&(d.morphAttributes.position=u),s&&(d.morphAttributes.normal=l),r&&(d.morphAttributes.color=f),d.morphTargetsRelative=!0,d})}function Se(d,t){if(d.updateMorphTargets(),t.weights!==void 0)for(let e=0,n=t.weights.length;e<n;e++)d.morphTargetInfluences[e]=t.weights[e];if(t.extras&&Array.isArray(t.extras.targetNames)){const e=t.extras.targetNames;if(d.morphTargetInfluences.length===e.length){d.morphTargetDictionary={};for(let n=0,s=e.length;n<s;n++)d.morphTargetDictionary[e[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function ye(d){let t;const e=d.extensions&&d.extensions[T.KHR_DRACO_MESH_COMPRESSION];if(e?t="draco:"+e.bufferView+":"+e.indices+":"+v(e.attributes):t=d.indices+":"+v(d.attributes)+":"+d.mode,d.targets!==void 0)for(let n=0,s=d.targets.length;n<s;n++)t+=":"+v(d.targets[n]);return t}function v(d){let t="";const e=Object.keys(d).sort();for(let n=0,s=e.length;n<s;n++)t+=e[n]+":"+d[e[n]]+";";return t}function U(d){switch(d){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function we(d){return d.search(/\.jpe?g($|\?)/i)>0||d.search(/^data\:image\/jpeg/)===0?"image/jpeg":d.search(/\.webp($|\?)/i)>0||d.search(/^data\:image\/webp/)===0?"image/webp":d.search(/\.ktx2($|\?)/i)>0||d.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const be=new h.Matrix4;class Ne{constructor(t={},e={}){this.json=t,this.extensions={},this.plugins={},this.options=e,this.cache=new Z,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const i=a.match(/Version\/(\d+)/);s=n&&i?parseInt(i[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&o<98?this.textureLoader=new h.TextureLoader(this.options.manager):this.textureLoader=new h.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new h.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(t){this.extensions=t}setPlugins(t){this.plugins=t}parse(t,e){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:n,userData:{}};return I(r,a,s),w(a,s),Promise.all(n._invokeAll(function(i){return i.afterRoot&&i.afterRoot(a)})).then(function(){for(const i of a.scenes)i.updateMatrixWorld();t(a)})}).catch(e)}_markDefs(){const t=this.json.nodes||[],e=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=e.length;s<r;s++){const o=e[s].joints;for(let a=0,i=o.length;a<i;a++)t[o[a]].isBone=!0}for(let s=0,r=t.length;s<r;s++){const o=t[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(t,e){e!==void 0&&(t.refs[e]===void 0&&(t.refs[e]=t.uses[e]=0),t.refs[e]++)}_getNodeRef(t,e,n){if(t.refs[e]<=1)return n;const s=n.clone(),r=(o,a)=>{const i=this.associations.get(o);i!=null&&this.associations.set(a,i);for(const[c,u]of o.children.entries())r(u,a.children[c])};return r(n,s),s.name+="_instance_"+t.uses[e]++,s}_invokeOne(t){const e=Object.values(this.plugins);e.push(this);for(let n=0;n<e.length;n++){const s=t(e[n]);if(s)return s}return null}_invokeAll(t){const e=Object.values(this.plugins);e.unshift(this);const n=[];for(let s=0;s<e.length;s++){const r=t(e[s]);r&&n.push(r)}return n}getDependency(t,e){const n=t+":"+e;let s=this.cache.get(n);if(!s){switch(t){case"scene":s=this.loadScene(e);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(e)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(e)});break;case"accessor":s=this.loadAccessor(e);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(e)});break;case"buffer":s=this.loadBuffer(e);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(e)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(e)});break;case"skin":s=this.loadSkin(e);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(e)});break;case"camera":s=this.loadCamera(e);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(t,e)}),!s)throw new Error("Unknown type: "+t);break}this.cache.add(n,s)}return s}getDependencies(t){let e=this.cache.get(t);if(!e){const n=this,s=this.json[t+(t==="mesh"?"es":"s")]||[];e=Promise.all(s.map(function(r,o){return n.getDependency(t,o)})),this.cache.add(t,e)}return e}loadBuffer(t){const e=this.json.buffers[t],n=this.fileLoader;if(e.type&&e.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+e.type+" buffer type is not supported.");if(e.uri===void 0&&t===0)return Promise.resolve(this.extensions[T.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){n.load(h.LoaderUtils.resolveURL(e.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+e.uri+'".'))})})}loadBufferView(t){const e=this.json.bufferViews[t];return this.getDependency("buffer",e.buffer).then(function(n){const s=e.byteLength||0,r=e.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(t){const e=this,n=this.json,s=this.json.accessors[t];if(s.bufferView===void 0&&s.sparse===void 0){const o=D[s.type],a=O[s.componentType],i=s.normalized===!0,c=new a(s.count*o);return Promise.resolve(new h.BufferAttribute(c,o,i))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],i=D[s.type],c=O[s.componentType],u=c.BYTES_PER_ELEMENT,l=u*i,f=s.byteOffset||0,p=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,m=s.normalized===!0;let M,g;if(p&&p!==l){const R=Math.floor(f/p),A="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+R+":"+s.count;let x=e.cache.get(A);x||(M=new c(a,R*p,s.count*p/u),x=new h.InterleavedBuffer(M,p/u),e.cache.add(A,x)),g=new h.InterleavedBufferAttribute(x,i,f%p/u,m)}else a===null?M=new c(s.count*i):M=new c(a,f,s.count*i),g=new h.BufferAttribute(M,i,m);if(s.sparse!==void 0){const R=D.SCALAR,A=O[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,E=s.sparse.values.byteOffset||0,L=new A(o[1],x,s.sparse.count*R),b=new c(o[2],E,s.sparse.count*i);a!==null&&(g=new h.BufferAttribute(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let y=0,P=L.length;y<P;y++){const C=L[y];if(g.setX(C,b[y*i]),i>=2&&g.setY(C,b[y*i+1]),i>=3&&g.setZ(C,b[y*i+2]),i>=4&&g.setW(C,b[y*i+3]),i>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=m}return g})}loadTexture(t){const e=this.json,n=this.options,r=e.textures[t].source,o=e.images[r];let a=this.textureLoader;if(o.uri){const i=n.manager.getHandler(o.uri);i!==null&&(a=i)}return this.loadTextureImage(t,r,a)}loadTextureImage(t,e,n){const s=this,r=this.json,o=r.textures[t],a=r.images[e],i=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[i])return this.textureCache[i];const c=this.loadImageSource(e,n).then(function(u){u.flipY=!1,u.name=o.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return u.magFilter=V[f.magFilter]||h.LinearFilter,u.minFilter=V[f.minFilter]||h.LinearMipmapLinearFilter,u.wrapS=z[f.wrapS]||h.RepeatWrapping,u.wrapT=z[f.wrapT]||h.RepeatWrapping,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==h.NearestFilter&&u.minFilter!==h.LinearFilter,s.associations.set(u,{textures:t}),u}).catch(function(){return null});return this.textureCache[i]=c,c}loadImageSource(t,e){const n=this,s=this.json,r=this.options;if(this.sourceCache[t]!==void 0)return this.sourceCache[t].then(l=>l.clone());const o=s.images[t],a=self.URL||self.webkitURL;let i=o.uri||"",c=!1;if(o.bufferView!==void 0)i=n.getDependency("bufferView",o.bufferView).then(function(l){c=!0;const f=new Blob([l],{type:o.mimeType});return i=a.createObjectURL(f),i});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+t+" is missing URI and bufferView");const u=Promise.resolve(i).then(function(l){return new Promise(function(f,p){let m=f;e.isImageBitmapLoader===!0&&(m=function(M){const g=new h.Texture(M);g.needsUpdate=!0,f(g)}),e.load(h.LoaderUtils.resolveURL(l,r.path),m,void 0,p)})}).then(function(l){return c===!0&&a.revokeObjectURL(i),w(l,o),l.userData.mimeType=o.mimeType||we(o.uri),l}).catch(function(l){throw console.error("THREE.GLTFLoader: Couldn't load texture",i),l});return this.sourceCache[t]=u,u}assignTexture(t,e,n,s){const r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[T.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[T.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const i=r.associations.get(o);o=r.extensions[T.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,i)}}return s!==void 0&&(o.colorSpace=s),t[e]=o,o})}assignFinalMaterial(t){const e=t.geometry;let n=t.material;const s=e.attributes.tangent===void 0,r=e.attributes.color!==void 0,o=e.attributes.normal===void 0;if(t.isPoints){const a="PointsMaterial:"+n.uuid;let i=this.cache.get(a);i||(i=new h.PointsMaterial,h.Material.prototype.copy.call(i,n),i.color.copy(n.color),i.map=n.map,i.sizeAttenuation=!1,this.cache.add(a,i)),n=i}else if(t.isLine){const a="LineBasicMaterial:"+n.uuid;let i=this.cache.get(a);i||(i=new h.LineBasicMaterial,h.Material.prototype.copy.call(i,n),i.color.copy(n.color),i.map=n.map,this.cache.add(a,i)),n=i}if(s||r||o){let a="ClonedMaterial:"+n.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let i=this.cache.get(a);i||(i=n.clone(),r&&(i.vertexColors=!0),o&&(i.flatShading=!0),s&&(i.normalScale&&(i.normalScale.y*=-1),i.clearcoatNormalScale&&(i.clearcoatNormalScale.y*=-1)),this.cache.add(a,i),this.associations.set(i,this.associations.get(n))),n=i}t.material=n}getMaterialType(){return h.MeshStandardMaterial}loadMaterial(t){const e=this,n=this.json,s=this.extensions,r=n.materials[t];let o;const a={},i=r.extensions||{},c=[];if(i[T.KHR_MATERIALS_UNLIT]){const l=s[T.KHR_MATERIALS_UNLIT];o=l.getMaterialType(),c.push(l.extendParams(a,r,e))}else{const l=r.pbrMetallicRoughness||{};if(a.color=new h.Color(1,1,1),a.opacity=1,Array.isArray(l.baseColorFactor)){const f=l.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],h.LinearSRGBColorSpace),a.opacity=f[3]}l.baseColorTexture!==void 0&&c.push(e.assignTexture(a,"map",l.baseColorTexture,h.SRGBColorSpace)),a.metalness=l.metallicFactor!==void 0?l.metallicFactor:1,a.roughness=l.roughnessFactor!==void 0?l.roughnessFactor:1,l.metallicRoughnessTexture!==void 0&&(c.push(e.assignTexture(a,"metalnessMap",l.metallicRoughnessTexture)),c.push(e.assignTexture(a,"roughnessMap",l.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(t)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(t,a)})))}r.doubleSided===!0&&(a.side=h.DoubleSide);const u=r.alphaMode||G.OPAQUE;if(u===G.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===G.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==h.MeshBasicMaterial&&(c.push(e.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new h.Vector2(1,1),r.normalTexture.scale!==void 0)){const l=r.normalTexture.scale;a.normalScale.set(l,l)}if(r.occlusionTexture!==void 0&&o!==h.MeshBasicMaterial&&(c.push(e.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==h.MeshBasicMaterial){const l=r.emissiveFactor;a.emissive=new h.Color().setRGB(l[0],l[1],l[2],h.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==h.MeshBasicMaterial&&c.push(e.assignTexture(a,"emissiveMap",r.emissiveTexture,h.SRGBColorSpace)),Promise.all(c).then(function(){const l=new o(a);return r.name&&(l.name=r.name),w(l,r),e.associations.set(l,{materials:t}),r.extensions&&I(s,l,r),l})}createUniqueName(t){const e=h.PropertyBinding.sanitizeNodeName(t||"");return e in this.nodeNamesUsed?e+"_"+ ++this.nodeNamesUsed[e]:(this.nodeNamesUsed[e]=0,e)}loadGeometries(t){const e=this,n=this.extensions,s=this.primitiveCache;function r(a){return n[T.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,e).then(function(i){return X(i,a,e)})}const o=[];for(let a=0,i=t.length;a<i;a++){const c=t[a],u=ye(c),l=s[u];if(l)o.push(l.promise);else{let f;c.extensions&&c.extensions[T.KHR_DRACO_MESH_COMPRESSION]?f=r(c):f=X(new h.BufferGeometry,c,e),s[u]={primitive:c,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(t){const e=this,n=this.json,s=this.extensions,r=n.meshes[t],o=r.primitives,a=[];for(let i=0,c=o.length;i<c;i++){const u=o[i].material===void 0?_e(this.cache):this.getDependency("material",o[i].material);a.push(u)}return a.push(e.loadGeometries(o)),Promise.all(a).then(function(i){const c=i.slice(0,i.length-1),u=i[i.length-1],l=[];for(let p=0,m=u.length;p<m;p++){const M=u[p],g=o[p];let R;const A=c[p];if(g.mode===S.TRIANGLES||g.mode===S.TRIANGLE_STRIP||g.mode===S.TRIANGLE_FAN||g.mode===void 0)R=r.isSkinnedMesh===!0?new h.SkinnedMesh(M,A):new h.Mesh(M,A),R.isSkinnedMesh===!0&&R.normalizeSkinWeights(),g.mode===S.TRIANGLE_STRIP?R.geometry=h.toTrianglesDrawMode(R.geometry,h.TriangleStripDrawMode):g.mode===S.TRIANGLE_FAN&&(R.geometry=h.toTrianglesDrawMode(R.geometry,h.TriangleFanDrawMode));else if(g.mode===S.LINES)R=new h.LineSegments(M,A);else if(g.mode===S.LINE_STRIP)R=new h.Line(M,A);else if(g.mode===S.LINE_LOOP)R=new h.LineLoop(M,A);else if(g.mode===S.POINTS)R=new h.Points(M,A);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(R.geometry.morphAttributes).length>0&&Se(R,r),R.name=e.createUniqueName(r.name||"mesh_"+t),w(R,r),g.extensions&&I(s,R,g),e.assignFinalMaterial(R),l.push(R)}for(let p=0,m=l.length;p<m;p++)e.associations.set(l[p],{meshes:t,primitives:p});if(l.length===1)return r.extensions&&I(s,l[0],r),l[0];const f=new h.Group;r.extensions&&I(s,f,r),e.associations.set(f,{meshes:t});for(let p=0,m=l.length;p<m;p++)f.add(l[p]);return f})}loadCamera(t){let e;const n=this.json.cameras[t],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?e=new h.PerspectiveCamera(h.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(e=new h.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(e.name=this.createUniqueName(n.name)),w(e,n),Promise.resolve(e)}loadSkin(t){const e=this.json.skins[t],n=[];for(let s=0,r=e.joints.length;s<r;s++)n.push(this._loadNodeShallow(e.joints[s]));return e.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",e.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),o=s,a=[],i=[];for(let c=0,u=o.length;c<u;c++){const l=o[c];if(l){a.push(l);const f=new h.Matrix4;r!==null&&f.fromArray(r.array,c*16),i.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',e.joints[c])}return new h.Skeleton(a,i)})}loadAnimation(t){const e=this.json,n=this,s=e.animations[t],r=s.name?s.name:"animation_"+t,o=[],a=[],i=[],c=[],u=[];for(let l=0,f=s.channels.length;l<f;l++){const p=s.channels[l],m=s.samplers[p.sampler],M=p.target,g=M.node,R=s.parameters!==void 0?s.parameters[m.input]:m.input,A=s.parameters!==void 0?s.parameters[m.output]:m.output;M.node!==void 0&&(o.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",R)),i.push(this.getDependency("accessor",A)),c.push(m),u.push(M))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(i),Promise.all(c),Promise.all(u)]).then(function(l){const f=l[0],p=l[1],m=l[2],M=l[3],g=l[4],R=[];for(let x=0,E=f.length;x<E;x++){const L=f[x],b=p[x],y=m[x],P=M[x],C=g[x];if(L===void 0)continue;L.updateMatrix&&L.updateMatrix();const k=n._createAnimationTracks(L,b,y,P,C);if(k)for(let H=0;H<k.length;H++)R.push(k[H])}const A=new h.AnimationClip(r,void 0,R);return w(A,s),A})}createNodeMesh(t){const e=this.json,n=this,s=e.nodes[t];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const o=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let i=0,c=s.weights.length;i<c;i++)a.morphTargetInfluences[i]=s.weights[i]}),o})}loadNode(t){const e=this.json,n=this,s=e.nodes[t],r=n._loadNodeShallow(t),o=[],a=s.children||[];for(let c=0,u=a.length;c<u;c++)o.push(n.getDependency("node",a[c]));const i=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),i]).then(function(c){const u=c[0],l=c[1],f=c[2];f!==null&&u.traverse(function(p){p.isSkinnedMesh&&p.bind(f,be)});for(let p=0,m=l.length;p<m;p++)u.add(l[p]);if(u.userData.pivot!==void 0&&l.length>0){const p=u.userData.pivot,m=l[0];u.pivot=new h.Vector3().fromArray(p),u.position.x-=p[0],u.position.y-=p[1],u.position.z-=p[2],m.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(t){const e=this.json,n=this.extensions,s=this;if(this.nodeCache[t]!==void 0)return this.nodeCache[t];const r=e.nodes[t],o=r.name?s.createUniqueName(r.name):"",a=[],i=s._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(t)});return i&&a.push(i),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(c){return s._getNodeRef(s.cameraCache,r.camera,c)})),s._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(t)}).forEach(function(c){a.push(c)}),this.nodeCache[t]=Promise.all(a).then(function(c){let u;if(r.isBone===!0?u=new h.Bone:c.length>1?u=new h.Group:c.length===1?u=c[0]:u=new h.Object3D,u!==c[0])for(let l=0,f=c.length;l<f;l++)u.add(c[l]);if(r.name&&(u.userData.name=r.name,u.name=o),w(u,r),r.extensions&&I(n,u,r),r.matrix!==void 0){const l=new h.Matrix4;l.fromArray(r.matrix),u.applyMatrix4(l)}else r.translation!==void 0&&u.position.fromArray(r.translation),r.rotation!==void 0&&u.quaternion.fromArray(r.rotation),r.scale!==void 0&&u.scale.fromArray(r.scale);if(!s.associations.has(u))s.associations.set(u,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const l=s.associations.get(u);s.associations.set(u,{...l})}return s.associations.get(u).nodes=t,u}),this.nodeCache[t]}loadScene(t){const e=this.extensions,n=this.json.scenes[t],s=this,r=new h.Group;n.name&&(r.name=s.createUniqueName(n.name)),w(r,n),n.extensions&&I(e,r,n);const o=n.nodes||[],a=[];for(let i=0,c=o.length;i<c;i++)a.push(s.getDependency("node",o[i]));return Promise.all(a).then(function(i){for(let u=0,l=i.length;u<l;u++){const f=i[u];f.parent!==null?r.add(Q(f)):r.add(f)}const c=u=>{const l=new Map;for(const[f,p]of s.associations)(f instanceof h.Material||f instanceof h.Texture)&&l.set(f,p);return u.traverse(f=>{const p=s.associations.get(f);p!=null&&l.set(f,p)}),l};return s.associations=c(r),r})}_createAnimationTracks(t,e,n,s,r){const o=[],a=t.name?t.name:t.uuid,i=[];N[r.path]===N.weights?t.traverse(function(f){f.morphTargetInfluences&&i.push(f.name?f.name:f.uuid)}):i.push(a);let c;switch(N[r.path]){case N.weights:c=h.NumberKeyframeTrack;break;case N.rotation:c=h.QuaternionKeyframeTrack;break;case N.translation:case N.scale:c=h.VectorKeyframeTrack;break;default:n.itemSize===1?c=h.NumberKeyframeTrack:c=h.VectorKeyframeTrack;break}const u=s.interpolation!==void 0?Ae[s.interpolation]:h.InterpolateLinear,l=this._getArrayFromAccessor(n);for(let f=0,p=i.length;f<p;f++){const m=new c(i[f]+"."+N[r.path],e.array,l,u);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),o.push(m)}return o}_getArrayFromAccessor(t){let e=t.array;if(t.normalized){const n=U(e.constructor),s=new Float32Array(e.length);for(let r=0,o=e.length;r<o;r++)s[r]=e[r]*n;e=s}return e}_createCubicSplineTrackInterpolant(t){t.createInterpolant=function(n){const s=this instanceof h.QuaternionKeyframeTrack?xe:Y;return new s(this.times,this.values,this.getValueSize()/3,n)},t.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ie(d,t,e){const n=t.attributes,s=new h.Box3;if(n.POSITION!==void 0){const a=e.json.accessors[n.POSITION],i=a.min,c=a.max;if(i!==void 0&&c!==void 0){if(s.set(new h.Vector3(i[0],i[1],i[2]),new h.Vector3(c[0],c[1],c[2])),a.normalized){const u=U(O[a.componentType]);s.min.multiplyScalar(u),s.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=t.targets;if(r!==void 0){const a=new h.Vector3,i=new h.Vector3;for(let c=0,u=r.length;c<u;c++){const l=r[c];if(l.POSITION!==void 0){const f=e.json.accessors[l.POSITION],p=f.min,m=f.max;if(p!==void 0&&m!==void 0){if(i.setX(Math.max(Math.abs(p[0]),Math.abs(m[0]))),i.setY(Math.max(Math.abs(p[1]),Math.abs(m[1]))),i.setZ(Math.max(Math.abs(p[2]),Math.abs(m[2]))),f.normalized){const M=U(O[f.componentType]);i.multiplyScalar(M)}a.max(i)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}d.boundingBox=s;const o=new h.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,d.boundingSphere=o}function X(d,t,e){const n=t.attributes,s=[];function r(o,a){return e.getDependency("accessor",o).then(function(i){d.setAttribute(a,i)})}for(const o in n){const a=B[o]||o.toLowerCase();a in d.attributes||s.push(r(n[o],a))}if(t.indices!==void 0&&!d.index){const o=e.getDependency("accessor",t.indices).then(function(a){d.setIndex(a)});s.push(o)}return h.ColorManagement.workingColorSpace!==h.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${h.ColorManagement.workingColorSpace}" not supported.`),w(d,t),Ie(d,t,e),Promise.all(s).then(function(){return t.targets!==void 0?Le(d,t.targets,e):d})}exports.GLTFLoader=J;
@@ -1,4 +1,4 @@
1
- import { L as Ae, a as G, F as he, M as w, V as fe, C as F, b, S as U, c as Le, P as Me, D as Se, d as K, e as C, I as ye, Q as de, f as we, O as pe, T as be, g as Ne, B as V, h as Ie, i as me, N as Oe, j as Ce, k as Fe, l as Q, m as ge, R as J, n as Pe, o as ke, p as He, q as z, r as De, s as Te, t as ve, u as v, v as Ge, w as Ue, x as Ke, y as Be, z as ee, A as je, E as Ve, G as ze, H as Xe, J as X, K as qe, U as We, W as Ye, X as Qe, Y as Je, Z as Ze, _ as $e, $ as Re, a0 as en, a1 as ne, a2 as te, a3 as se, a4 as ie, a5 as re, a6 as nn, a7 as tn, a8 as sn, a9 as rn, aa as on, ab as an } from "./duo-frame-Sz0TWot-.mjs";
1
+ import { L as Ae, a as G, F as he, M as w, V as fe, C as F, b, S as U, c as Le, P as Me, D as Se, d as K, e as C, I as ye, Q as de, f as we, O as pe, T as be, g as Ne, B as V, h as Ie, i as me, N as Oe, j as Ce, k as Fe, l as Q, m as ge, R as J, n as Pe, o as ke, p as He, q as z, r as De, s as Te, t as ve, u as v, v as Ge, w as Ue, x as Ke, y as Be, z as ee, A as je, E as Ve, G as ze, H as Xe, J as X, K as qe, U as We, W as Ye, X as Qe, Y as Je, Z as Ze, _ as $e, $ as Re, a0 as en, a1 as ne, a2 as te, a3 as se, a4 as ie, a5 as re, a6 as nn, a7 as tn, a8 as sn, a9 as rn, aa as on, ab as an } from "./duo-frame-D1JK_cRk.mjs";
2
2
  function cn(f) {
3
3
  const n = /* @__PURE__ */ new Map(), e = /* @__PURE__ */ new Map(), t = f.clone();
4
4
  return Ee(f, t, function(s, i) {
@@ -12,6 +12,14 @@ export declare const CONTROL_MSG_TYPE: {
12
12
  readonly SET_CLIPBOARD: 9;
13
13
  readonly SET_DISPLAY_POWER: 10;
14
14
  readonly ROTATE_DEVICE: 11;
15
+ readonly INJECT_MOUSE_EVENT: 40;
16
+ readonly INJECT_MAC_KEY: 41;
17
+ readonly INJECT_MAC_SCROLL: 42;
18
+ };
19
+ export declare const MAC_INPUT_ACTION: {
20
+ readonly DOWN: 0;
21
+ readonly UP: 1;
22
+ readonly MOVE: 2;
15
23
  };
16
24
  export declare const AMOTION_EVENT: {
17
25
  readonly ACTION_DOWN: 0;
@@ -0,0 +1 @@
1
+ export declare function macKeyCodeFor(code: string): number | undefined;
@@ -51,7 +51,7 @@ export type DeviceStreamOptions = DeviceStreamLiveOptions & {
51
51
  watchOnly?: boolean;
52
52
  sessionId?: string;
53
53
  /** Required with proxy transports; direct instance URLs can supply the platform implicitly. */
54
- platform?: 'ios' | 'android';
54
+ platform?: 'ios' | 'android' | 'macos';
55
55
  deviceModel?: 'iphone-duo';
56
56
  } & ({
57
57
  url: string;
@@ -59,7 +59,7 @@ export type DeviceStreamOptions = DeviceStreamLiveOptions & {
59
59
  transport?: never;
60
60
  } | {
61
61
  transport: DeviceStreamTransport;
62
- platform: 'ios' | 'android';
62
+ platform: 'ios' | 'android' | 'macos';
63
63
  url?: never;
64
64
  token?: never;
65
65
  });
@@ -1,6 +1,6 @@
1
1
  export declare const debugLog: (...args: any[]) => void;
2
2
  export declare const debugWarn: (...args: any[]) => void;
3
3
  export declare const safeInvoke: <Args extends unknown[]>(label: string, fn: ((...args: Args) => unknown) | undefined, ...args: Args) => void;
4
- export type DevicePlatform = 'ios' | 'android';
4
+ export type DevicePlatform = 'ios' | 'android' | 'macos';
5
5
  export declare const detectPlatform: (url: string) => DevicePlatform;
6
6
  export declare const withAuthenticationToken: (url: string, token: string) => string;
@@ -2,3 +2,6 @@ export declare function createTouchControlMessage(action: number, pointerId: num
2
2
  export declare function createTwoFingerTouchControlMessage(action: number, videoWidth: number, videoHeight: number, x0: number, y0: number, x1: number, y1: number): ArrayBuffer;
3
3
  export declare function createSetClipboardMessage(text: string, paste?: boolean): ArrayBuffer;
4
4
  export declare function createInjectKeycodeMessage(action: number, keycode: number, repeat?: number, metaState?: number): ArrayBuffer;
5
+ export declare function createMouseControlMessage(action: number, videoWidth: number, videoHeight: number, x: number, y: number, buttons: number): ArrayBuffer;
6
+ export declare function createMacKeyMessage(action: number, keyCode: number): ArrayBuffer;
7
+ export declare function createMacScrollMessage(videoWidth: number, videoHeight: number, x: number, y: number, deltaX: number, deltaY: number): ArrayBuffer;
@@ -0,0 +1,2 @@
1
+ "use strict";const Z={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11,INJECT_MOUSE_EVENT:40,INJECT_MAC_KEY:41,INJECT_MAC_SCROLL:42},Re={DOWN:0,UP:1,MOVE:2},Ue={ACTION_DOWN:0,ACTION_UP:1,ACTION_MOVE:2,ACTION_CANCEL:3,ACTION_POINTER_DOWN:5,ACTION_POINTER_UP:6,BUTTON_PRIMARY:1,BUTTON_SECONDARY:2,BUTTON_TERTIARY:4},o={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},wt={KeyA:o.KEYCODE_A,KeyB:o.KEYCODE_B,KeyC:o.KEYCODE_C,KeyD:o.KEYCODE_D,KeyE:o.KEYCODE_E,KeyF:o.KEYCODE_F,KeyG:o.KEYCODE_G,KeyH:o.KEYCODE_H,KeyI:o.KEYCODE_I,KeyJ:o.KEYCODE_J,KeyK:o.KEYCODE_K,KeyL:o.KEYCODE_L,KeyM:o.KEYCODE_M,KeyN:o.KEYCODE_N,KeyO:o.KEYCODE_O,KeyP:o.KEYCODE_P,KeyQ:o.KEYCODE_Q,KeyR:o.KEYCODE_R,KeyS:o.KEYCODE_S,KeyT:o.KEYCODE_T,KeyU:o.KEYCODE_U,KeyV:o.KEYCODE_V,KeyW:o.KEYCODE_W,KeyX:o.KEYCODE_X,KeyY:o.KEYCODE_Y,KeyZ:o.KEYCODE_Z,Digit0:o.KEYCODE_0,Digit1:o.KEYCODE_1,Digit2:o.KEYCODE_2,Digit3:o.KEYCODE_3,Digit4:o.KEYCODE_4,Digit5:o.KEYCODE_5,Digit6:o.KEYCODE_6,Digit7:o.KEYCODE_7,Digit8:o.KEYCODE_8,Digit9:o.KEYCODE_9,Backquote:o.KEYCODE_GRAVE,Minus:o.KEYCODE_MINUS,Equal:o.KEYCODE_EQUALS,BracketLeft:o.KEYCODE_LEFT_BRACKET,BracketRight:o.KEYCODE_RIGHT_BRACKET,Backslash:o.KEYCODE_BACKSLASH,Semicolon:o.KEYCODE_SEMICOLON,Quote:o.KEYCODE_APOSTROPHE,Comma:o.KEYCODE_COMMA,Period:o.KEYCODE_PERIOD,Slash:o.KEYCODE_SLASH,Space:o.KEYCODE_SPACE,Tab:o.KEYCODE_TAB,Escape:o.KEYCODE_ESCAPE,ArrowUp:o.DPAD_UP,ArrowDown:o.DPAD_DOWN,ArrowLeft:o.DPAD_LEFT,ArrowRight:o.DPAD_RIGHT,Enter:o.ENTER,Backspace:o.DEL,Delete:o.FORWARD_DEL,Home:o.KEYCODE_MOVE_HOME,End:o.KEYCODE_MOVE_END,PageUp:o.KEYCODE_PAGE_UP,PageDown:o.KEYCODE_PAGE_DOWN,Insert:o.KEYCODE_INSERT,F1:o.KEYCODE_F1,F2:o.KEYCODE_F2,F3:o.KEYCODE_F3,F4:o.KEYCODE_F4,F5:o.KEYCODE_F5,F6:o.KEYCODE_F6,F7:o.KEYCODE_F7,F8:o.KEYCODE_F8,F9:o.KEYCODE_F9,F10:o.KEYCODE_F10,F11:o.KEYCODE_F11,F12:o.KEYCODE_F12,ShiftLeft:o.KEYCODE_SHIFT_LEFT,ShiftRight:o.KEYCODE_SHIFT_RIGHT,ControlLeft:o.KEYCODE_CTRL_LEFT,ControlRight:o.KEYCODE_CTRL_RIGHT,AltLeft:o.KEYCODE_ALT_LEFT,AltRight:o.KEYCODE_ALT_RIGHT,MetaLeft:o.KEYCODE_META_LEFT,MetaRight:o.KEYCODE_META_RIGHT,ContextMenu:o.MENU,Numpad0:o.KEYCODE_NUMPAD_0,Numpad1:o.KEYCODE_NUMPAD_1,Numpad2:o.KEYCODE_NUMPAD_2,Numpad3:o.KEYCODE_NUMPAD_3,Numpad4:o.KEYCODE_NUMPAD_4,Numpad5:o.KEYCODE_NUMPAD_5,Numpad6:o.KEYCODE_NUMPAD_6,Numpad7:o.KEYCODE_NUMPAD_7,Numpad8:o.KEYCODE_NUMPAD_8,Numpad9:o.KEYCODE_NUMPAD_9,NumpadDivide:o.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:o.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:o.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:o.KEYCODE_NUMPAD_ADD,NumpadDecimal:o.KEYCODE_NUMPAD_DOT,NumpadComma:o.KEYCODE_NUMPAD_COMMA,NumpadEnter:o.KEYCODE_NUMPAD_ENTER,NumpadEqual:o.KEYCODE_NUMPAD_EQUALS},or={KeyA:0,KeyS:1,KeyD:2,KeyF:3,KeyH:4,KeyG:5,KeyZ:6,KeyX:7,KeyC:8,KeyV:9,IntlBackslash:10,KeyB:11,KeyQ:12,KeyW:13,KeyE:14,KeyR:15,KeyY:16,KeyT:17,Digit1:18,Digit2:19,Digit3:20,Digit4:21,Digit6:22,Digit5:23,Equal:24,Digit9:25,Digit7:26,Minus:27,Digit8:28,Digit0:29,BracketRight:30,KeyO:31,KeyU:32,BracketLeft:33,KeyI:34,KeyP:35,Enter:36,KeyL:37,KeyJ:38,Quote:39,KeyK:40,Semicolon:41,Backslash:42,Comma:43,Slash:44,KeyN:45,KeyM:46,Period:47,Tab:48,Space:49,Backquote:50,Backspace:51,Escape:53,MetaRight:54,MetaLeft:55,ShiftLeft:56,CapsLock:57,AltLeft:58,ControlLeft:59,ShiftRight:60,AltRight:61,ControlRight:62,Fn:63,F17:64,NumpadDecimal:65,NumpadMultiply:67,NumpadAdd:69,NumLock:71,NumpadDivide:75,NumpadEnter:76,NumpadSubtract:78,F18:79,F19:80,NumpadEqual:81,Numpad0:82,Numpad1:83,Numpad2:84,Numpad3:85,Numpad4:86,Numpad5:87,Numpad6:88,Numpad7:89,F20:90,Numpad8:91,Numpad9:92,F5:96,F6:97,F7:98,F3:99,F8:100,F9:101,F11:103,F13:105,F16:106,F14:107,F10:109,ContextMenu:110,F12:111,F15:113,Help:114,Insert:114,Home:115,PageUp:116,Delete:117,F4:118,End:119,F2:120,PageDown:121,F1:122,ArrowLeft:123,ArrowRight:124,ArrowDown:125,ArrowUp:126};function ct(t){return or[t]}function Nt(t,e,r,a,u,l,i=1,E=0,O=0){const m=new ArrayBuffer(32),S=new DataView(m);let w=0;S.setUint8(w,Z.INJECT_TOUCH_EVENT),w+=1;const N=t===Ue.ACTION_POINTER_DOWN?Ue.ACTION_DOWN:t===Ue.ACTION_POINTER_UP?Ue.ACTION_UP:t;return S.setUint8(w,N),w+=1,S.setBigInt64(w,BigInt(e),!0),w+=8,S.setInt32(w,Math.round(u),!0),w+=4,S.setInt32(w,Math.round(l),!0),w+=4,S.setUint16(w,r,!0),w+=2,S.setUint16(w,a,!0),w+=2,S.setInt16(w,Math.round(i*65535),!0),w+=2,S.setInt32(w,E,!0),w+=4,S.setInt32(w,O,!0),m}function ar(t,e,r,a,u,l,i){const E=new ArrayBuffer(24),O=new DataView(E);let m=0;return O.setUint8(m,Z.INJECT_TWO_FINGER_TOUCH_EVENT),m+=1,O.setUint8(m,t),m+=1,O.setInt32(m,Math.round(a),!0),m+=4,O.setInt32(m,Math.round(u),!0),m+=4,O.setInt32(m,Math.round(l),!0),m+=4,O.setInt32(m,Math.round(i),!0),m+=4,O.setUint16(m,e,!0),m+=2,O.setUint16(m,r,!0),m+=2,O.setUint16(m,0,!0),E}function bt(t,e=!0){const a=new TextEncoder().encode(t),u=new ArrayBuffer(14+a.length),l=new DataView(u);let i=0;return l.setUint8(i,Z.SET_CLIPBOARD),i+=1,l.setBigInt64(i,BigInt(0),!1),i+=8,l.setUint8(i,e?1:0),i+=1,l.setUint32(i,a.length,!1),i+=4,new Uint8Array(u,i).set(a),u}function Xe(t,e,r=0,a=0){const u=new ArrayBuffer(14),l=new DataView(u);let i=0;return l.setUint8(i,Z.INJECT_KEYCODE),i+=1,l.setUint8(i,t),i+=1,l.setInt32(i,e,!0),i+=4,l.setInt32(i,r,!0),i+=4,l.setInt32(i,a,!0),u}function sr(t,e,r,a,u,l){const i=new ArrayBuffer(18),E=new DataView(i);return E.setUint8(0,Z.INJECT_MOUSE_EVENT),E.setUint8(1,t),E.setInt32(2,Math.round(a),!0),E.setInt32(6,Math.round(u),!0),E.setUint16(10,e,!0),E.setUint16(12,r,!0),E.setInt32(14,l,!0),i}function Yt(t,e){const r=new ArrayBuffer(4),a=new DataView(r);return a.setUint8(0,Z.INJECT_MAC_KEY),a.setUint8(1,t),a.setUint16(2,e,!0),r}function cr(t,e,r,a,u,l){const i=new ArrayBuffer(21),E=new DataView(i);return E.setUint8(0,Z.INJECT_MAC_SCROLL),E.setInt32(1,Math.round(r),!0),E.setInt32(5,Math.round(a),!0),E.setUint16(9,t,!0),E.setUint16(11,e,!0),E.setFloat32(13,u,!0),E.setFloat32(17,l,!0),i}function lr(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function It(t){return t===2?2:t===3?1:t===4?3:0}class dr{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,r=It(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==r)&&this.release(),this.screenId=e?.screenId,this.turns=r}touch(e,r,a,u=!1){if(this.screenId===void 0)return;const l=Rt(r,a,u?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...l}),this.held&&(Object.assign(this.held,l),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,l.x,l.y))}release(){if(!this.held)return;const{screenId:e,x:r,y:a}=this.held;this.held=void 0,this.send(1,e,r,a)}}const ur={width:164.6,height:117.8,depth:5.2};function Rt(t,e,r){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),r===1?{x:e,y:1-t}:r===2?{x:1-t,y:1-e}:r===3?{x:1-e,y:t}:{x:t,y:e}}function fr(t){return Number.isFinite(t)&&t>=0&&t<=180}function Er(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function hr(t,e,r){return e&&(t||!r)?"touch":t?"ignore":"orbit"}function Ut(t,e,r,a){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(r)||!Number.isFinite(a)||r<0||r>1||a<0||a>1)throw new RangeError("Invalid display touch coordinates");const u=new ArrayBuffer(12),l=new DataView(u);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,r,!0),l.setFloat32(8,a,!0),u}class mr{constructor(e,r){this.send=e,this.failed=r}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!fr(e)||(this.latest=e,this.flush())}stop(){this.stopped=!0,this.latest=void 0}async flush(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.latest!==void 0&&!this.stopped;){const e=this.latest;this.latest=void 0,await this.send(e)}}catch(e){this.latest=void 0,this.stopped||this.failed(e)}finally{this.running=!1}}}}const pr={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class Cr{constructor(e,r){this.send=e,this.failed=r}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,r){this.tail=this.tail.then(()=>this.send(e,r)).catch(this.failed)}}const Qe="Accessibility unavailable on this device.",ze=500,kt=(t,e)=>Math.abs(t.x-e.x)<.5&&Math.abs(t.y-e.y)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5,Or=t=>Math.max(0,t.width)*Math.max(0,t.height),Dr=t=>{const e=t.find(r=>r.frame&&r.frame.width>0&&r.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},_r=t=>{const e={};return typeof t.AXUniqueId=="string"&&t.AXUniqueId.length>0&&(e.AXUniqueId=t.AXUniqueId),typeof t.AXLabel=="string"&&t.AXLabel.length>0&&(e.AXLabel=t.AXLabel),typeof t.type=="string"&&t.type.length>0&&(e.className=t.type),e},gr=t=>{const e={};for(const[r,a]of Object.entries(t))r!=="children"&&(e[r]=a);return e};function Pt(t){const e=Array.isArray(t)?t:[t],r=Dr(e),a=[],u=(l,i)=>{if(a.length>=ze)return;const E=l.frame;if(E&&E.width>0&&E.height>0&&!kt(E,r)){const m=l.role_description||l.role||"",S=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";a.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:i,path:i,label:S,value:typeof l.AXValue=="string"?l.AXValue:"",role:m,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:E.x,y:E.y,width:E.width,height:E.height},selectors:_r(l),raw:gr(l)})}const O=Array.isArray(l.children)?l.children:[];for(let m=0;m<O.length&&a.length<ze;m++)u(O[m],`${i}.${m}`)};for(let l=0;l<e.length&&a.length<ze;l++)u(e[l],String(l));return{platform:"ios",screen:{width:r.width,height:r.height},elements:a,capturedAt:Date.now()}}const Tr=t=>{let e={x:0,y:0,width:1,height:1},r=0;for(const a of t){const u=a.parsedBounds;if(!u)continue;const l=u.right-u.left,i=u.bottom-u.top,E=Math.max(0,l)*Math.max(0,i);E>r&&(r=E,e={x:0,y:0,width:l,height:i})}return e},yr=t=>{const e={};return typeof t.resourceId=="string"&&t.resourceId.length>0&&(e.resourceId=t.resourceId),typeof t.contentDesc=="string"&&t.contentDesc.length>0&&(e.contentDesc=t.contentDesc),typeof t.text=="string"&&t.text.length>0&&(e.text=t.text),typeof t.className=="string"&&t.className.length>0&&(e.className=t.className),e};function Lt(t){const e=Tr(t),r=[];for(let a=0;a<t.length&&r.length<ze;a++){const u=t[a],l=u.parsedBounds;if(!l)continue;const i=Math.max(0,l.right-l.left),E=Math.max(0,l.bottom-l.top);if(i<=0||E<=0)continue;const O={x:l.left,y:l.top,width:i,height:E};if(kt(O,{x:0,y:0,width:e.width,height:e.height}))continue;const m=u.contentDesc||u.text||"",S=u.className||"";r.push({id:u.resourceId&&u.resourceId.length>0?u.resourceId:u.contentDesc&&u.contentDesc.length>0?`cd:${u.contentDesc}`:String(a),path:String(a),label:m,value:typeof u.text=="string"?u.text:"",role:S,type:S,enabled:u.enabled!==!1,focused:u.focused===!0,frame:O,selectors:yr(u),raw:{...u}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:r,capturedAt:Date.now()}}function Sr(t,e){const r=Math.max(0,t.x),a=Math.max(0,t.y),u=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),i=Math.max(0,u-r),E=Math.max(0,l-a);return i>0&&E>0?{x:r,y:a,width:i,height:E}:null}function Ft(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const r=t.frame,a=e.frame;return r.x===a.x&&r.y===a.y&&r.width===a.width&&r.height===a.height}function Bt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let r=0;r<t.elements.length;r++)if(!Ft(t.elements[r],e.elements[r]))return!1;return!0}function Kr(t,e,r){let a=null,u=1/0;for(const l of t.elements){const i=l.frame;if(e<i.x||r<i.y||e>i.x+i.width||r>i.y+i.height)continue;const E=Or(i);E<u&&(u=E,a=l)}return a}function Ar(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const r=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${r} })`}return null}return t.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })`:t.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })`:t.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })`:null}function xt(t){const e=t.role||t.type||"";if(!e)return"element";let r=e.replace(/^AX/,"");return r.includes(".")&&(r=r.split(".").pop()),r==="GenericElement"?"Element":(r=r.replace(/([a-z])([A-Z])/g,"$1 $2"),r)}const yt=80;function Mr(t){const e=xt(t),r=t.label||t.value||"";if(!r)return e;const a=r.length>yt?r.slice(0,yt).trimEnd()+"…":r;return`${e} · ${a}`}const vr=500,wr=2e3,St=5e3,Nr=8e3,br=1200,Yr=250,Ir=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class Rr{platform;send;onSnapshot;onStatusChange;baseIntervalMs;maxBackoffMs;androidElementTreeOptions;pending=new Map;running=!1;timer;currentInterval;lastSnapshot=null;inflight=!1;lastBumpAtMs=0;boostUntilMs=0;status="idle";constructor(e){this.platform=e.platform,this.send=e.send,this.onSnapshot=e.onSnapshot,this.onStatusChange=e.onStatusChange,this.baseIntervalMs=e.baseIntervalMs??vr,this.maxBackoffMs=e.maxBackoffMs??wr,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.failAllPending("Inspector stopped"),this.lastSnapshot=null,this.setStatus("idle"),this.onSnapshot(null))}getStatus(){return this.status}setStatus(e,r){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,r)}catch(a){console.error("[AxFetcher] onStatusChange threw:",a)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+br;const r=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<r){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const r=e.id;if(!this.pending.get(r))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const E=typeof e.error=="string"?e.error:null;if(E)return this.settleReject(r,new Error(E)),!0;const O=typeof e.json=="string"?e.json:"";try{const m=JSON.parse(O),S=Pt(m);this.settleResolve(r,S)}catch(m){this.settleReject(r,m instanceof Error?m:new Error(String(m)))}return!0}if(e.type!=="getElementTreeResult")return!1;const u=e.error;if(u&&typeof u=="object"){const E=typeof u.message=="string"?u.message:"getElementTree failed";return this.settleReject(r,new Error(E)),!0}const l=e.payload,i=Array.isArray(l?.nodes)?l.nodes:[];try{const E=Lt(i);this.settleResolve(r,E)}catch(E){this.settleReject(r,E instanceof Error?E:new Error(String(E)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=Ir();return new Promise((r,a)=>{const u=window.setTimeout(()=>{this.pending.delete(e),a(new Error("elementTree request timed out"))},Nr+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:r,reject:a,timer:u}),this.send(this.buildRequest(e))||(window.clearTimeout(u),this.pending.delete(e),a(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const r=e instanceof Error?e.message:String(e),a=/unavailable|not (yet )?running|failed|timeout/i.test(r);this.currentInterval=a?St:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(a?"unavailable":"error",r)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const r=this.lastSnapshot;if(Bt(r,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(Qe)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(Qe)?(this.currentInterval=St,this.setStatus("unavailable",Qe)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(Yr,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,r){const a=this.pending.get(e);a&&(window.clearTimeout(a.timer),this.pending.delete(e),a.resolve(r))}settleReject(e,r){const a=this.pending.get(e);a&&(window.clearTimeout(a.timer),this.pending.delete(e),a.reject(r))}failAllPending(e){for(const[r,a]of this.pending.entries())window.clearTimeout(a.timer),a.reject(new Error(e)),this.pending.delete(r)}}function Kt(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const r=e??null;try{t.jitterBufferTarget!==r&&(t.jitterBufferTarget=r)}catch(a){console.warn("RemoteControl: could not set the jitter buffer target.",a)}}const Wt=`(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
2
+ `,At=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Wt],{type:"text/javascript;charset=utf-8"});function Ur(t){let e;try{if(e=At&&(self.URL||self.webkitURL).createObjectURL(At),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Wt),{name:t?.name})}}function kr(t,e,r){const{MediaStreamTrackProcessor:a,MediaStreamTrackGenerator:u}=globalThis,l=e.getVideoTracks()[0];let i,E,O,m,S=!1;const w=()=>{S||(S=!0,i?.stop(),E?.stop(),O&&(O.postMessage({type:"stop"}),m=setTimeout(()=>O?.terminate(),1e3)))},N=D=>{t.srcObject=D,t.play().catch(()=>{})},q=D=>{S||(w(),r(D),N(e))};try{if(l&&a&&u){i=l.clone();const D=new a({track:i,maxBufferSize:1}),H=new u({kind:"video"});E=H,O=new Ur,O.onmessage=({data:L})=>{L.type==="error"?q(new Error(L.message)):L.type==="stopped"&&(clearTimeout(m),O?.terminate())},O.onerror=L=>q(new Error(L.message)),O.postMessage({type:"start",readable:D.readable,writable:H.writable},[D.readable,H.writable]),N(new MediaStream(e.getTracks().map(L=>L===l?H:L)))}else N(e)}catch(D){q(D)}return w}function ke(t){return typeof t=="number"&&Number.isFinite(t)}function Te(t,e){if(!(!ke(t)||!ke(e)||t<e||e<0))return t-e}class Pr{previous=new Map;reset(){this.previous.clear()}read(e,r,a){const u={timestamp:0,video:[],audio:[]};a==null?u.requestedTargetMs=null:ke(a)&&a>=0&&a<=4e3&&(u.requestedTargetMs=a);const l=new Map;return e.forEach(i=>{if(i.type!=="inbound-rtp"||!ke(i.timestamp))return;const E=i.kind??i.mediaType;if(E!=="video"&&E!=="audio")return;const O=r.filter(P=>P.kind===E),m=i.trackIdentifier?O.find(P=>P.trackId===i.trackIdentifier):i.mid!=null?O.find(P=>P.mid===i.mid):O.length===1?O[0]:void 0;if(!m)return;const S=this.previous.get(i.id),N=S?.trackId===m.trackId&&S.stats.ssrc===i.ssrc?S.stats:void 0,q=N?i.timestamp-N.timestamp:void 0,D={id:i.id,trackId:m.trackId,timestamp:i.timestamp};if(q!==void 0&&q>0){D.intervalMs=q;const P=Te(i.jitterBufferEmittedCount,N?.jitterBufferEmittedCount),B=Te(i.jitterBufferDelay,N?.jitterBufferDelay);P!==void 0&&P>0&&B!==void 0&&(D.bufferDelayMs=B/P*1e3);const V=Te(i.bytesReceived,N?.bytesReceived);V!==void 0&&(D.bitrateBps=V*8e3/q)}if(E==="video"){const P={...D,display:m.display??"primary"};if(D.intervalMs!==void 0){const B=Te(i.framesDecoded,N?.framesDecoded);B!==void 0&&(P.fps=B*1e3/D.intervalMs),P.droppedFrames=Te(i.framesDropped,N?.framesDropped),P.freezes=Te(i.freezeCount,N?.freezeCount)}u.video.push(P)}else u.audio.push(D);u.timestamp=Math.max(u.timestamp,i.timestamp),l.set(i.id,N&&i.timestamp<=N.timestamp?S:{stats:i,trackId:m.trackId});const H=i.transportId?e.get(i.transportId):void 0,L=H?.selectedCandidatePairId?e.get(H.selectedCandidatePairId):void 0;L?.state==="succeeded"&&ke(L.currentRoundTripTime)&&L.currentRoundTripTime>=0&&(u.rttMs=L.currentRoundTripTime*1e3)}),this.previous=l,u.video.length||u.audio.length?u:null}}const at=new WeakSet;function Lr(t,e,r){const{peer:a,displays:u}=t,l=new Pr;let i,E=!1,O=!1,m=!1,S=0,w=!1,N=!1;const q=()=>!E&&!document.hidden&&a.connectionState==="connected",D=B=>{if(!(!B&&!w)){w=B!==null;try{e()?.(B)}catch(V){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',V)}}},H=()=>{O=!1,S++,clearTimeout(i),l.reset(),D(null)},L=async()=>{if(m||!q())return;if(at.has(a)){i=setTimeout(()=>{L()},2e3);return}m=!0,at.add(a);const B=S;try{const V=await a.getStats();if(B!==S||!q())return;const ce=a.getTransceivers().filter(Y=>(Y.currentDirection==="recvonly"||Y.currentDirection==="sendrecv")&&Y.receiver.track.readyState!=="ended").map(Y=>({trackId:Y.receiver.track.id,kind:Y.receiver.track.kind,mid:Y.mid,display:u.get(Y.receiver)}));D(l.read(V,ce,r())),N=!1}catch(V){if(B!==S||!q())return;N||console.warn("[RemoteControl] could not read playback stats:",V),N=!0,l.reset(),D(null)}finally{m=!1,at.delete(a),O&&q()&&(i=setTimeout(()=>{L()},B===S?2e3:0))}},P=()=>{if(!q()){H();return}O||(O=!0,L())};return document.addEventListener("visibilitychange",P),a.addEventListener("connectionstatechange",P),P(),()=>{E=!0,document.removeEventListener("visibilitychange",P),a.removeEventListener("connectionstatechange",P),H()}}function Fr(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let a=!1,u=!1,l=0;return r.onmessage=i=>{if(u)return;let E;try{E=JSON.parse(i.data)}catch(O){console.warn("Invalid latency trace message",O);return}E&&typeof E=="object"&&!Array.isArray(E)&&e(E)},r.onclose=()=>{u=!0,a=!1},{accept(i){a=!u&&i===1},wrap(i){if(!a||i.byteLength===0)return i;const E=new DataView(i),O=E.getUint8(0),m=O===Z.INJECT_MOUSE_EVENT||O===Z.INJECT_MAC_KEY||O===Z.INJECT_MAC_SCROLL,S=i.byteLength===32&&O===Z.INJECT_TOUCH_EVENT&&E.getUint8(1)<=2;if(!m&&!S)return i;const w=new ArrayBuffer(6+i.byteLength),N=new DataView(w);return N.setUint8(0,240),N.setUint8(1,1),N.setUint32(2,++l,!0),new Uint8Array(w,6).set(new Uint8Array(i)),w},close(){u=!0,a=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Br{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const a={generation:e,isCurrent:()=>e===this.generation},u=this.tail.then(()=>r(a));return this.tail=u.catch(()=>{}),u}invalidate(){++this.generation}}function xr(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function Wr(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function qr(t,e){return!t||t.facingMode!==e.facingMode}function Vr(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function $r(t){return{type:"cameraResult",granted:!0,camera:Vr(t)}}const se=(...t)=>{window.debugRemoteControl&&console.log(...t)},y=(...t)=>{window.debugRemoteControl&&console.warn(...t)},F=(t,e,...r)=>{if(e)try{e(...r)}catch(a){console.error(`[RemoteControl] customer callback "${t}" threw:`,a)}},qt=t=>t.includes("/android_")?"android":t.includes("/macos_")?"macos":"ios",Mt=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},st=3,Hr=1e3,Jr=15e3,Gr=3e3,jr=4e3;function vt(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Xr(t){let e={...t};const{url:r,deviceModel:a}=e;let u=e.token;const l=e.watchOnly??!1,i=e.sessionId??vt(),E=e.platform??qt(r??"");let O={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const m=n=>{O={...O,...n},F("onStateChange",e.onStateChange,O)},S=n=>m({videoReady:n}),w=n=>m({duoState:n}),N=n=>m({duoError:n}),q=n=>m({duo:n}),D=n=>se(n);let H=null,L;const P=()=>{L?.(),L=H&&e.onPlaybackStats?Lr(H,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},B=new Map,V=new Set,ce=new Set,Y=new Map;let ye=!1;const Pe=new Map,lt=(n,f,c)=>{f.stop?.(),f.stop=kr(n,c,d=>y("Video playback fallback:",d))},Vt=()=>{Pe.clear();for(const[n,f]of B)f.clear?.(),f.stop?.(),f.stop=void 0,n.srcObject=null};let Ee=!1,Se=!1,Le=0,g=null,I=null,x=null,Fe=null,he,Ke,Ae,Be,me,de=0,xe=0,re=!1,ue=null,Q=null,fe;const Ze=new Br;let Me=null,We=null,et=!l&&(e.microphoneEnabled??!1),tt=!1,ve=null,te=null,qe=0,dt=Promise.resolve(),pe=null,we=!1,ne=new Map,ee=new Map,le=new Map,ie=new Map,$=null,Ne=null,ut=0;const Ve=n=>{if(n===null&&Ne===null)return;Ne=n;const f=++ut;queueMicrotask(()=>{f===ut&&F("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let Ce=null,Oe=new Map;const $t=(n,f)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const K=g;if(!K||K.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const p=vt(),C=setTimeout(()=>{Oe.delete(p),d(new Error("Device control timed out"))},5e3);Oe.set(p,{resolve:c,reject:d,timer:C}),K.send(JSON.stringify({type:n,id:p,...f}))}),De=n=>{Ce!==n&&(Ce=n,m({connection:n}),F("onConnectionStateChange",e.onConnectionStateChange,n))},oe=n=>{l||!x||x.readyState!=="open"||(x.send(Fe?.wrap(n)??n),$?.bumpActivity())},Ht=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:i}))},ft=()=>{he&&window.clearInterval(he),he=window.setInterval(Ht,1e4)},be=()=>{he&&(window.clearInterval(he),he=void 0)},$e=()=>{Ke&&(window.clearTimeout(Ke),Ke=void 0)},He=()=>{Ae&&(window.clearTimeout(Ae),Ae=void 0)},Ye=()=>{Be&&(window.clearInterval(Be),Be=void 0)},Ie=()=>{me!==void 0&&(window.clearTimeout(me),me=void 0)},Jt=()=>{we||(we=!0,Ye(),S(!0),De("connected"))},J=n=>{for(const f of n.getTracks())try{f.stop()}catch(c){y("track.stop() failed:",c)}},Gt=()=>{const n=Q;n&&(Q=null,J(n))},Et=n=>{const f=dt.then(n).catch(c=>{y("microphone operation failed:",c)});return dt=f,f},rt=()=>et||tt,ht=n=>{const f=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;pe=f,n.send(JSON.stringify({type:"microphoneStart",id:f}))},nt=()=>Et(()=>jt()),jt=async()=>{const n=qe,f=()=>n===qe&&rt(),c=h=>{F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:h})};if(!f())return;const d=g,K=ve;if(!d||d.readyState!==WebSocket.OPEN||!K||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),c("Microphone capture requires a secure context (https)");return}let p=null;try{p=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(h){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",h)}if(!f()){p&&J(p);return}if(!p){c("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){J(p),c("Captured stream has no audio track");return}try{await K.replaceTrack(C)}catch(h){y("replaceTrack(audioTrack) failed:",h),J(p),c("Failed to attach the microphone track to the connection");return}if(!f()){try{await K.replaceTrack(null)}catch(h){y("replaceTrack(null) on stale mic attach failed:",h)}J(p);return}te=p,C.onended=()=>{te===p&&Je("microphone capture ended by the browser")},ht(d),F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},Je=n=>(++qe,pe=null,Et(async()=>{const f=ve,c=te;if(te=null,f&&c)try{await f.replaceTrack(null)}catch(K){y("replaceTrack(null) on mic detach failed:",K)}c&&J(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const K=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:K}))}(c||n)&&F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),mt=(n,f)=>{let c;try{c=$r(f),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){y("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:f.label||void 0}}}n.send(JSON.stringify(c)),F("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},Xt=n=>{if(!n)return;const f=n.indexOf("/"),d=(f>=0?n.slice(f+1):n).toUpperCase();return d==="HEVC"?"H265":d},Qt=async()=>{const n=ue,f=e.onCameraStats;if(!n||!f)return;let c;try{c=await n.getStats()}catch{return}let d,K,p;if(c.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?d=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(p=U)}),d?.codecId){const U=c.get(d.codecId);U&&(K=U.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),h=We;let R,b,G;if(h&&C>h.timestamp){const U=(C-h.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof h.framesEncoded=="number"&&(R=Math.max(0,(d.framesEncoded-h.framesEncoded)/U)),typeof d.bytesSent=="number"&&typeof h.bytesSent=="number"&&(b=Math.max(0,(d.bytesSent-h.bytesSent)*8/U)),typeof d.packetsSent=="number"&&typeof h.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof h.packetsLost=="number"){const A=d.packetsSent-h.packetsSent,je=p.packetsLost-h.packetsLost;A>0&&(G=Math.max(0,Math.min(100,je/A*100)))}}We={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:p?.packetsLost};const v={codec:Xt(K),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:R,framesEncoded:d.framesEncoded,bitrateBps:b,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof p?.roundTripTime=="number"?p.roundTripTime*1e3:void 0,packetsLostPct:G};F("onCameraStats",e.onCameraStats,v)},pt=()=>{Me===null&&(We=null,Me=setInterval(()=>{Qt()},1e3))},Ge=()=>{Me!==null&&(clearInterval(Me),Me=null),We=null,F("onCameraStats",e.onCameraStats,null)},zt=(n,f,c,d)=>Ze.enqueue(async({isCurrent:K})=>{const p=()=>K()&&d()&&g===f&&ue===c;if(!p())return;if(!n.active){const v=Q;try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) on camera detach failed:",U)}if(Q===v&&(Q=null,fe=void 0,v&&J(v)),Ge(),!p())return;F("onCameraDemandChange",e.onCameraDemandChange,!1);return}F("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,h=C?.getVideoTracks()[0],R=fe;if(h?.readyState==="live"&&R&&!qr(R,n)){fe=n,mt(f,h),pt();return}if(C){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) before camera switch failed:",v)}if(Q===C&&(Q=null,fe=void 0,J(C)),Ge(),!p())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let b=null;try{b=await navigator.mediaDevices.getUserMedia({video:Wr(n),audio:!1})}catch(v){console.warn("[RemoteControl] getUserMedia denied/failed:",v)}if(!p()){b&&J(b);return}if(!b){f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const G=b.getVideoTracks()[0]??null;if(!G){if(J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{G.contentHint="motion"}catch{}try{await c.replaceTrack(G)}catch(v){if(y("replaceTrack(videoTrack) failed:",v),J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera attach failed:",v)}J(b);return}try{const v=c.getParameters();(!v.encodings||v.encodings.length===0)&&(v.encodings=[{}]),v.encodings[0].maxBitrate=8e6,v.encodings[0].maxFramerate=30,v.degradationPreference="maintain-framerate",await c.setParameters(v)}catch(v){y("setParameters on outbound camera failed:",v)}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera finalize failed:",v)}J(b);return}Q=b,fe=n,G.onended=()=>{Q===b&&Ze.enqueueCurrent(async({isCurrent:v})=>{if(!(!v()||Q!==b||!d()||g!==f||ue!==c)){try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) after camera ended failed:",U)}!v()||Q!==b||!d()||g!==f||ue!==c||(Q=null,fe=void 0,J(b),Ge(),f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(v=>y("camera ended cleanup failed:",v))},p()&&(mt(f,G),pt())}),_e=()=>{for(const n of ce)n();ce.clear();for(const n of Y.values())clearTimeout(n);Y.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),ne.clear(),ie.clear(),le.clear(),L?.(),L=void 0,Vt(),H=null;for(const n of Oe.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));Oe.clear(),w(null),m({controlReady:!1,videoReady:!1}),He(),Ie(),Ye(),$&&($.stop(),$=null),Ne!==null&&Ve(null),Ze.invalidate(),Ge(),Gt(),fe=void 0,ue=null,++qe,tt=!1,pe=null,te&&(J(te),te=null,F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),ve=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),Fe?.close(),Fe=null,I&&(I.onconnectionstatechange=null,I.oniceconnectionstatechange=null,I.ontrack=null,I.onicecandidate=null,I.close(),I=null),x&&(x.onopen=null,x.onclose=null,x.onerror=null,x.close(),x=null)},Ct=()=>{document.hidden?be():ft()},Zt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const d=new URL(r);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,n=Mt(d.toString(),u)}catch{return!1}const f=new AbortController,c=window.setTimeout(()=>f.abort(),jr);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:f.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},er=()=>{Ee||(Ee=!0,de+=1,$e(),He(),Ie(),_e(),D("Instance terminated"),be(),De("terminated"),F("onTerminated",e.onTerminated))},tr=()=>{if(Ee||Se)return;Se=!0;const n=Le;Zt().catch(()=>!1).then(f=>{n===Le&&(Se=!1,f&&er())})},ge=(n,f)=>{if(Ee||f!==de)return;if(tr(),re){if(e.autoReconnect===!1){D(`Connection failed after it was established: ${n}`),be(),De("failed"),_e();return}D(`Reconnecting after established session dropped: ${n}`),re=!1,xe=-1}$e();const c=xe+1;if(c>=st){D(`Connection failed after ${st} attempts: ${n}`),be(),De("failed"),_e();return}D(`Retrying connection (${c+1}/${st})`),De("reconnecting"),_e(),Ke=window.setTimeout(()=>{Ke=void 0,f===de&&Ot(c)},Hr)},Ot=async(n=0)=>{const{openUrl:f,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:K}=e;if(Ee)return;const p=de+1;de=p,xe=n,re=!1,n===0&&Ce!=="reconnecting"&&De("connecting"),$e(),He(),Ye(),we=!1,S(!1),_e();const C=()=>p===de;Ae=window.setTimeout(()=>{Ae=void 0,!(!C()||re)&&ge("Connection did not succeed within 15 seconds",p)},Jr);try{const h=e.transport?await e.transport.connect():new WebSocket(Mt(r,u));if(!C()){h.close();return}if(g=h,await new Promise((_,s)=>{let k=!1;const W=()=>M(()=>s(new Error("Connection stopped")));ce.add(W);const T=window.setTimeout(()=>M(()=>s(new Error("WebSocket connection timeout"))),3e4),M=z=>{k||(k=!0,ce.delete(W),window.clearTimeout(T),z())};h.onopen=()=>{!C()||g!==h||M(_)},h.onerror=z=>{!C()||g!==h||(D("WebSocket error: "+z),M(()=>s(new Error("WebSocket connection failed"))))},h.onclose=()=>{!C()||g!==h||(D("WebSocket closed"),M(()=>s(new Error("WebSocket closed before connection was established"))))},h.readyState===WebSocket.OPEN?M(_):h.readyState!==WebSocket.CONNECTING&&M(()=>s(new Error("WebSocket is closed")))}),!C()||g!==h)return;h.onerror=_=>{!C()||g!==h||D("WebSocket error: "+_)},h.onclose=()=>{!C()||g!==h||D("WebSocket closed")};const R=new Promise((_,s)=>{let k=!1;const W=()=>T(()=>s(new Error("Connection stopped")));ce.add(W);const T=j=>{k||(k=!0,ce.delete(W),window.clearTimeout(M),h.removeEventListener("message",z),j())},M=window.setTimeout(()=>T(()=>s(new Error("RTCConfiguration timeout"))),3e4),z=j=>{if(!(!C()||g!==h))try{const X=JSON.parse(j.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===i){const ir=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>s(new Error(ir)))}else X.type==="rtcConfiguration"&&T(()=>_({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>s(X))}};h.addEventListener("message",z),h.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:i}))}),{rtcConfiguration:b,cameraSupported:G,foldSupported:v}=await R;if(!C()||g!==h)return;const U=a==="iphone-duo"||v;q(U);const A=new RTCPeerConnection({...b,iceTransportPolicy:"relay"});I=A;const je={peer:A,displays:new Map};H=je,P(),A.addTransceiver("audio",{direction:"recvonly"});const rr=A.addTransceiver("video",{direction:"recvonly"}),nr=U?A.addTransceiver("video",{direction:"recvonly"}):null,Tt=!l&&(E==="ios"||G),it=Tt?A.addTransceiver("video",{direction:"sendonly"}):null;if(ue=it?.sender??null,ve=(Tt?A.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const _=RTCRtpReceiver.getCapabilities("video");if(_&&_.codecs){const k=_.codecs.sort((W,T)=>{const M=z=>{const j=z.mimeType.toLowerCase();return j.includes("h265")||j.includes("hevc")?1:j.includes("h264")||j.includes("avc")?2:3};return M(W)-M(T)});rr.setCodecPreferences(k),nr?.setCodecPreferences(k),se("Set codec preferences:",k.map(W=>W.mimeType).join(", "))}}if(it&&RTCRtpSender.getCapabilities){const _=RTCRtpSender.getCapabilities("video");if(_&&_.codecs){const s=new Set(["42e01f","42e028","640c1f"]),k=T=>{const M=T.mimeType.toLowerCase(),j=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=j?j[1]:"";return M==="video/h265"||M==="video/hevc"?1:M==="video/h264"&&s.has(X)?2:M==="video/h264"?3:M==="video/vp9"?4:M==="video/vp8"?5:M==="video/rtx"||M==="video/red"||M==="video/ulpfec"?0:6},W=[..._.codecs].sort((T,M)=>k(T)-k(M));try{it.setCodecPreferences(W),se("Outbound camera codec preferences:",W.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){y("Failed to set outbound camera codec preferences:",T)}}}const ae=A.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});x=ae;const ot=!l&&!U&&e.onTrace?Fr(A,_=>{C()&&I===A&&F("onTrace",e.onTrace,_)}):null;if(Fe=ot,ae.onopen=()=>{if(!C()||x!==ae||g!==h)return;re=!0,m({controlReady:!l}),He(),D("Control channel opened"),U&&h.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),!$&&E!=="macos"&&($=new Rr({platform:E,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:K,send:s=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(s)),!0}catch{return!1}},onSnapshot:Ve,onStatusChange:(s,k)=>{F("onAxStatusChange",e.onAxStatusChange,s,k)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&$.start());const _=()=>{!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN||h.send(JSON.stringify({type:"requestFrame",sessionId:i}))};if(_(),Ye(),Be=window.setInterval(()=>{if(!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN){Ye();return}_()},250),!l&&f){try{const s=decodeURIComponent(f);D("Opening URL"),h.send(JSON.stringify({type:"openUrl",url:s,sessionId:i}))}catch(s){console.error({error:s},"Error decoding URL, falling back to the original URL"),h.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}$?.bumpActivity()}},ae.onclose=()=>{!C()||x!==ae||(m({controlReady:!1}),D("Control channel closed"))},ae.onerror=_=>{!C()||x!==ae||(console.error("Control channel error:",_),D("Control channel error: "+_))},A.onconnectionstatechange=()=>{!C()||I!==A||(D("Connection state: "+A.connectionState),A.connectionState==="failed"&&re&&ge("WebRTC connection entered failed state",p))},A.oniceconnectionstatechange=()=>{if(!C()||I!==A)return;const _=A.iceConnectionState;if(D("ICE state: "+_),_==="connected"||_==="completed"){Ie(),rt()&&!te&&nt();return}if(_==="failed"){Ie(),re&&ge("ICE connection entered failed state",p);return}_==="disconnected"&&re&&e.autoReconnect!==!1&&me===void 0&&(me=window.setTimeout(()=>{me=void 0,!(!C()||I!==A)&&A.iceConnectionState==="disconnected"&&ge("ICE stayed disconnected past grace period",p)},Gr))},A.ontrack=_=>{if(!C()||I!==A)return;Kt(_.receiver,e.jitterBufferTargetMs);const s=_.track.id==="duo-inner"||_.streams.some(k=>k.id==="duo-inner");if(_.track.kind==="video"&&je.displays.set(_.receiver,s?"inner":"primary"),D("Received remote track: "+_.track.kind),_.track.kind==="video"){const k=s?"inner":"primary",W=U?new MediaStream([_.track]):_.streams[0]??new MediaStream([_.track]);Pe.set(k,W);for(const[T,M]of B)M.display===k&&lt(T,M,W)}},A.onicecandidate=_=>{if(!(!C()||I!==A||g!==h))if(_.candidate&&h.readyState===WebSocket.OPEN){const s={type:"candidate",candidate:_.candidate.candidate,sdpMid:_.candidate.sdpMid,sdpMLineIndex:_.candidate.sdpMLineIndex,sessionId:i};h.send(JSON.stringify(s)),D("Sent ICE candidate")}else D("ICE candidate gathering completed")},h.onmessage=async _=>{if(!C()||g!==h)return;let s;try{s=JSON.parse(_.data)}catch(k){y("Error parsing message:",k);return}if(!$?.handleMessage(s))switch(D("Received: "+s.type),s.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!U)break;s.state?(w(s.state),N(void 0)):s.id==="duo-capabilities"&&N(s.error||"This instance does not support native iPhone Duo displays.");const T=Oe.get(s.id);T&&(clearTimeout(T.timer),Oe.delete(s.id),s.error?T.reject(new Error(s.error)):T.resolve());break}case"signalingError":{if(s.requestType!=="offer"||s.sessionId!==i)break;const T=typeof s.error=="string"?s.error:"Unable to establish the streaming connection";D("Error: "+T),ge(T,p);break}case"answer":if(!I||I!==A){D("No peer connection, skipping answer");break}if(ot?.accept(s.latencyTraceVersion),await A.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:s.sdp})),!C()||I!==A)return;D("Set remote description");break;case"candidate":if(!I||I!==A){D("No peer connection, skipping candidate");break}if(await A.addIceCandidate(new RTCIceCandidate({candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex})),!C()||I!==A)return;D("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof s.id!="string"){y("Received invalid screenshot success message:",s);break}const T=Qr(s);if(T){const j=ee.get(s.id);if(typeof j!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${T}`),j(new Error(T)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const M=zr(s);if(!M){y("Received screenshot message without image data:",s);break}const z=ne.get(s.id);if(typeof z!="function"){y(`Received screenshot data for unknown or handled id: ${s.id}`);break}se(`Received screenshot data for id ${s.id}`),z(M),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}case"screenshotError":if(typeof s.id!="string"||typeof s.message!="string"){y("Received invalid screenshot error message:",s);break}const k=ee.get(s.id);if(typeof k!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${s.message}`),k(new Error(s.message)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;case"cameraRequest":{const T=ue;if(!T)break;const M=xr(s);if(!M){y("Received invalid cameraRequest:",s);break}console.info("[RemoteControl] cameraRequest received:",M.active,M.facingMode),await zt(M,h,T,C);break}case"microphoneRequest":{if(!ve)break;const T=s.active===!0;if(tt=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){et||await Je();break}if(te){ht(h);break}await nt();break}case"microphoneStartResult":{if(pe===null||s.id!==pe)break;pe=null,typeof s.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",s.error),Je(s.error));break}case"terminateAppResult":if(typeof s.id!="string"){y("Received invalid terminateApp result message:",s);break}if(typeof s.error=="string"){const T=ie.get(s.id);if(typeof T!="function"){y(`Received terminateApp error for unknown or handled id: ${s.id}`);break}y(`Received terminateApp error for id ${s.id}: ${s.error}`),T(new Error(s.error)),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const W=le.get(s.id);if(typeof W!="function"){y(`Received terminateApp result for unknown or handled id: ${s.id}`);break}se(`Received terminateApp success for id ${s.id}`),W(),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;default:y(`Received unhandled message type: ${s.type}`,s);break}},I===A){const _=await A.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!C()||I!==A||(await A.setLocalDescription(_),!C()||I!==A))return;C()&&g===h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({type:"offer",...U?{displayStreams:!0}:{},...ot?{latencyTraceVersion:1}:{},sdp:_.sdp,sessionId:i})),D("Sent offer")}}catch(h){if(!C()||h instanceof Error&&h.message==="Connection stopped")return;const R=h instanceof Error?h.message:String(h);D("Error: "+R),ge(R,p)}},Dt=()=>{if(ye)throw new Error("Device stream is disposed");Le++,Se=!1,Ve(null),Ce!=="reconnecting"&&(Ce=null),document.addEventListener("visibilitychange",Ct),document.hidden||ft(),Ee=!1,Ot(0)},_t=()=>{Le++,Se=!1,be(),document.removeEventListener("visibilitychange",Ct),de+=1,xe=0,re=!1,$e(),Ie(),_e(),Ce=null,m({connection:"idle",videoReady:!1,controlReady:!1}),D("Stopped")},gt=(n,f="primary")=>{if(ye)throw new Error("Device stream is disposed");if(B.has(n))throw new Error("Video element is already attached");const c={display:f};B.set(n,c);const d=()=>{f==="primary"&&Pe.has(f)&&Jt()};n.addEventListener("loadeddata",d);const K=Pe.get(f);K&&lt(n,c,K);let p=!1;const C=()=>{p||(p=!0,V.delete(C),n.removeEventListener("loadeddata",d),c.stop?.(),B.delete(n),n.srcObject=null)};return V.add(C),C};return{start:Dt,stop:_t,attachVideo:gt,attachFrameSink:(n,f="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=gt(c,f);let K=!1,p=0,C=0;const h=()=>{c.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},R=()=>{K||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&F("present",(...v)=>n.present(...v),c,c.videoWidth,c.videoHeight,f),!(K||!c.srcObject)&&(c.requestVideoFrameCallback?p=c.requestVideoFrameCallback(R):C=requestAnimationFrame(R)))},b=()=>{h(),R()};B.get(c).clear=h,c.addEventListener("loadeddata",b);const G=()=>{K||(K=!0,V.delete(G),h(),c.removeEventListener("loadeddata",b),d(),c.remove())};return V.delete(d),V.add(G),c.readyState>=2&&b(),G},dispose:()=>{if(!ye){ye=!0,_t();for(const n of V)n();V.clear()}},getState:()=>O,updateOptions:({token:n,...f})=>{if(ye)throw new Error("Device stream is disposed");n!==void 0&&!e.transport&&(u=n);const c=e;if(e={...e,...f},c.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const d of I?.getTransceivers()??[])(d.currentDirection==="recvonly"||d.currentDirection==="sendrecv")&&Kt(d.receiver,e.jitterBufferTargetMs);!!c.onPlaybackStats!=!!e.onPlaybackStats&&P(),!!c.microphoneEnabled!=!!e.microphoneEnabled&&(et=!l&&(e.microphoneEnabled??!1),rt()?nt():Je()),!!c.inspectMode!=!!e.inspectMode&&(e.inspectMode?$?.start():($?.stop(),Ne!==null&&Ve(null)))},sendControl:oe,sendTouch:(n,f,c,d,K,p=0)=>oe(Nt(n==="begin"?0:n==="end"?1:2,p,d,K,f,c,n==="end"?0:1)),sendText:n=>oe(bt(n)),sendDisplayTouch:(n,f,c,d)=>oe(Ut(n,f,c,d)),sendDuoControl:$t,pressButton:n=>{const f={home:3,back:4,recents:187,power:26}[n];oe(Xe(0,f,0,0)),oe(Xe(1,f,0,0))},rotate:()=>oe(new Uint8Array([11]).buffer),bumpActivity:()=>$?.bumpActivity(),getAxStatus:()=>$?.getStatus()??"idle",openUrl:n=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){y("WebSocket not open, cannot send open_url command.");return}try{const f=decodeURIComponent(n);D("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}catch(f){y("Error decoding or sending URL :",{error:f,url:n}),g.send(JSON.stringify({type:"openUrl",url:n,sessionId:i}))}$?.bumpActivity()}},sendKeyEvent:n=>{if(!x||x.readyState!=="open"){y("Data channel not ready for imperative key command:",x?.readyState);return}if(E==="macos"){const p=ct(n.code);if(p===void 0){y(`Unknown event.code for imperative command: ${n.code}`);return}const C=[[n.metaKey,"Meta"],[n.ctrlKey,"Control"],[n.altKey,"Alt"],[n.shiftKey,"Shift"]].filter(([R,b])=>R&&!n.code.startsWith(b)).map(([,R])=>ct(`${R}Left`)),h=(R,b)=>oe(Yt(R,b));if(n.type==="keydown"){for(const R of C)h(Re.DOWN,R);h(Re.DOWN,p)}else{h(Re.UP,p);for(const R of[...C].reverse())h(Re.UP,R)}return}const f=wt[n.code];if(!f){y(`Unknown event.code for imperative command: ${n.code}`);return}let c=o.META_NONE;n.shiftKey&&(c|=o.META_SHIFT_ON),n.altKey&&(c|=o.META_ALT_ON),n.ctrlKey&&(c|=o.META_CTRL_ON),n.metaKey&&(c|=o.META_META_ON);const d=n.type==="keydown"?o.ACTION_DOWN:o.ACTION_UP;se(`Sending Imperative Key Command: code=${n.code}, keycode=${f}, action=${d}, meta=${c}`);const K=Xe(d,f,0,c);K&&oe(K)},screenshot:n=>new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:d};ne.set(d,f),ee.set(d,c),se("Sending screenshot request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send screenshot request immediately:",p),ne.delete(d),ee.delete(d),c(p);return}Y.set(d,setTimeout(()=>{Y.delete(d),ne.has(d)&&(y(`Screenshot request timed out for id ${d}`),ee.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),ee.delete(d))},3e4))}),terminateApp:n=>l?Promise.reject(new Error("Device is watch-only")):new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:"terminateApp",id:d,bundleId:n};le.set(d,f),ie.set(d,c),se("Sending terminateApp request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send terminateApp request immediately:",p),le.delete(d),ie.delete(d),c(p);return}$?.bumpActivity(),Y.set(d,setTimeout(()=>{Y.delete(d),le.has(d)&&(y(`terminateApp request timed out for id ${d}`),ie.get(d)?.(new Error("terminateApp request timed out")),le.delete(d),ie.delete(d))},3e4))}),reconnect:()=>Dt(),refreshAxTree:async()=>{const n=$;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ne}}const Qr=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,zr=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Ue;exports.ANDROID_KEYS=o;exports.AX_UNAVAILABLE_ERROR=Qe;exports.CONTROL_MSG_TYPE=Z;exports.DUO_BUTTONS=pr;exports.DUO_DIMENSIONS=ur;exports.DuoButtonSender=Cr;exports.DuoTouchController=dr;exports.HingeSender=mr;exports.MAC_INPUT_ACTION=Re;exports.axElementAtPoint=Kr;exports.axElementRoleLabel=xt;exports.axElementSelectorExpression=Ar;exports.axElementSummary=Mr;exports.axElementsEqual=Ft;exports.axSnapshotsEqual=Bt;exports.clampAxFrameForScreen=Sr;exports.codeMap=wt;exports.createDeviceStream=Xr;exports.createDisplayTouchMessage=Ut;exports.createInjectKeycodeMessage=Xe;exports.createMacKeyMessage=Yt;exports.createMacScrollMessage=cr;exports.createMouseControlMessage=sr;exports.createSetClipboardMessage=bt;exports.createTouchControlMessage=Nt;exports.createTwoFingerTouchControlMessage=ar;exports.debugLog=se;exports.debugWarn=y;exports.detectPlatform=qt;exports.duoDisplayTurns=It;exports.duoPointerMode=hr;exports.flatDisplayTouch=Rt;exports.getDuoDisplay=lr;exports.macKeyCodeFor=ct;exports.normalizeAndroidTree=Lt;exports.normalizeIosTree=Pt;exports.panelTouch=Er;exports.safeInvoke=F;