@titan-os/sdk 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/umd/sdk.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("rollbar")):"function"==typeof define&&define.amd?define(["exports","rollbar"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TitanSDK={},e.Rollbar)}(this,(function(e,t){"use strict";var i=Object.defineProperty,n=(e=>(e.PHILIPS="PHILIPS",e.PHILIPS_OLD="PHILIPS_OLD",e.VESTEL="VESTEL",e.BROWSER="BROWSER",e.UNKNOWN="UNKNOWN",e))(n||{}),r=(e=>(e.NOT_INITIALIZED="NOT_INITIALIZED",e.NOT_SUPPORTED="NOT_SUPPORTED",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.INVALID_ARGUMENTS="INVALID_ARGUMENTS",e.INVALID_PARAMETER="INVALID_PARAMETER",e.PLATFORM_NOT_DETECTED="PLATFORM_NOT_DETECTED",e.COMMUNICATION_ERROR="COMMUNICATION_ERROR",e.TIMEOUT="TIMEOUT",e.UNKNOWN="UNKNOWN",e))(r||{});class s extends Error{code;details;constructor(e,t="UNKNOWN",i){super(e),this.name="SDKError",this.code=t,this.details=i,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toString(){return`SDKError [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const o=new class{subscriptions=new Map;logBuffer=[];maxBufferSize=1e3;nextId=1;debugMode=!1;constructor(e=1e3){this.maxBufferSize=e}setDebugMode(e){this.debugMode=e}subscribe(e,t={}){const i="sub-"+this.nextId++,n={id:i,levels:t.levels||["debug","info","warn","error"],modules:t.modules,callback:e,created:Date.now()};if(this.subscriptions.set(i,n),t.includeHistory){this.getFilteredHistory(n.levels,n.modules).forEach((t=>{try{e(t)}catch(i){}}))}return i}unsubscribe(e){return this.subscriptions.delete(e)}addLogEntry(e){this.logBuffer.push(e),this.logBuffer.length>this.maxBufferSize&&this.logBuffer.shift(),this.subscriptions.forEach((t=>{if(this.shouldNotifySubscription(t,e))try{t.callback(e)}catch(i){}}))}getHistory(e,t,i){return this.getFilteredHistory(e,t,i)}clear(){this.logBuffer=[]}getSubscriptionCount(){return this.subscriptions.size}getMetrics(){const e={totalEntries:this.logBuffer.length,entriesByLevel:{},entriesByModule:{},memoryUsageKB:Math.round(JSON.stringify(this.logBuffer).length/1024)};return this.logBuffer.length>0&&(e.oldestEntry=new Date(this.logBuffer[0].timestamp),e.newestEntry=new Date(this.logBuffer[this.logBuffer.length-1].timestamp)),this.logBuffer.forEach((t=>{e.entriesByLevel[t.level]=(e.entriesByLevel[t.level]||0)+1,e.entriesByModule[t.module]=(e.entriesByModule[t.module]||0)+1})),e}exportLogs(e,t){const i=this.getFilteredHistory(e,t);return JSON.stringify(i,null,2)}isDebugMode(){return this.debugMode}shouldNotifySubscription(e,t){return!!e.levels.includes(t.level)&&!(e.modules&&!e.modules.includes(t.module))}getFilteredHistory(e,t,i){let n=this.logBuffer;return e&&(n=n.filter((t=>e.includes(t.level)))),t&&(n=n.filter((e=>t.includes(e.module)))),i&&i>0&&(n=n.slice(-i)),[...n]}};function a(e){const t=(t,i,...n)=>{var r;const s=(()=>{try{const e=(new Error).stack;if(!e)return"";const t=e.split("\n");for(let i=3;i<t.length;i++){const e=t[i];if(e&&!e.includes("logger.ts")&&!e.includes("Logger")){const t=e.match(/\((.*):(\d+):(\d+)\)/)||e.match(/at (.*):(\d+):(\d+)/);if(t){const[,e,i]=t;return`${e.split("/").pop()||e}:${i}`}}}return""}catch{return""}})(),a=(e=>{var t;try{const i=null==(t=e.stack)?void 0:t.split("\n");if(!i||i.length<4)return"Unknown location";const n=i[3].replace("at","").trim()||"Unknown location",{fnName:r,fnPath:s}=(e=>{let t="",i="";return 1===e.split(" ").length?{fnName:"",fnPath:e.split(" ")[0]}:(3===e.split(" ").length?(t=e.split(" (")[0],i=e.split(" (")[1].replace(")","")):(t=e.split(" ")[0],i=e.split(" ")[1].replace(/\((.*)\)/,"$1")),{fnName:t,fnPath:i})})(n);return r?`${r}[${s}]`:`[${s}]`}catch{return"Unknown location"}})(new Error),c={id:`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),level:t,module:e,message:i,args:n,metadata:{url:"undefined"!=typeof window?null==(r=window.location)?void 0:r.href:void 0,caller:s}};o.addLogEntry(c);if(o.isDebugMode()||"warn"===t||"error"===t){t}};return{debug:(e,...i)=>t("debug",e,...i),info:(e,...i)=>t("info",e,...i),warn:(e,...i)=>t("warn",e,...i),error:(e,...i)=>t("error",e,...i),subscribe:(e,t)=>o.subscribe(e,t),unsubscribe:e=>o.unsubscribe(e),getHistory:(e,t,i)=>o.getHistory(e,t,i),clear:()=>o.clear()}}function c(e){return a(e)}const l=(e,t)=>o.subscribe(e,t),d=e=>o.unsubscribe(e),u=(e,t,i)=>o.getHistory(e,t,i),g=()=>o.clear(),h=e=>o.addLogEntry(e),p=c("PlatformDetection");class f{strategies=[];register(e){this.strategies.push(e),this.strategies.sort(((e,t)=>t.getPriority()-e.getPriority()))}getStrategies(){return[...this.strategies]}}class m{canDetect(){return"undefined"!=typeof window&&("t9_core"in window||"vestel"===window.deviceBrand||navigator.userAgent.toLowerCase().includes("vestel"))}getPlatform(){return this.canDetect()?n.VESTEL:null}getPriority(){return 3}}class v{canDetect(){return"undefined"!=typeof window&&("jwt"in window||"launcher_env"in window||"undefined"!=typeof navigator&&navigator.userAgent.toLowerCase().indexOf("philips")>-1)}getPlatform(){return this.canDetect()?n.PHILIPS:null}getPriority(){return 5}}class S{canDetect(){if("undefined"==typeof window)return!1;const e=(()=>{const e=navigator.userAgent.match(/Chrome\/(\d+)\./);return e?parseInt(e[1],10):null})(),t=null!==e&&e<=84;return"undefined"!=typeof navigator&&navigator.userAgent.includes("Philips")&&(document.cookie.includes("tos-session")||t)}getPlatform(){return this.canDetect()?n.PHILIPS_OLD:null}getPriority(){return 10}}class y{canDetect(){return!0}getPlatform(){return n.BROWSER}getPriority(){return 1}}const b=new class{factory;lastDetectedPlatform=null;constructor(){this.factory=new f,this.factory.register(new v),this.factory.register(new m),this.factory.register(new S),this.factory.register(new y)}registerStrategy(e){this.factory.register(e)}detectPlatform(e={}){if(e.forcePlatform)return{platform:e.forcePlatform,detectedBy:"forced",confidence:1};if(this.lastDetectedPlatform)return{...this.lastDetectedPlatform};const t=this.factory.getStrategies();for(const n of t)if(n.canDetect()){const t=n.getPlatform();if(null!==t){const i={platform:t,detectedBy:n.constructor.name,confidence:.9};return this.lastDetectedPlatform=i,e.debug&&p.info(`Platform detected as ${t}`),{...i}}}if(!1===e.fallbackToBrowser)throw new s("Could not detect platform and fallback is disabled",r.PLATFORM_NOT_DETECTED);const i={platform:n.BROWSER,detectedBy:"fallback",confidence:.1};return this.lastDetectedPlatform=i,e.debug&&p.info("Fallback to browser platform - no strategy matched"),{...i}}reset(){this.lastDetectedPlatform=null}},w={LAUNCH_APP_REQUEST:"LAUNCH_APP_REQUEST",DEVICE_INFO_REQUEST:"DEVICE_INFO_REQUEST",TTS_REQUEST_SETTINGS:"TTS_REQUEST_SETTINGS",TTS_REQUEST_START_SPEAKING:"TTS_REQUEST_START_SPEAKING",TTS_REQUEST_STOP_SPEAKING:"TTS_REQUEST_STOP_SPEAKING",ERROR_SIMULATION:"ERROR_SIMULATION",LAUNCH_APP_RESPONSE:"LAUNCH_APP_RESPONSE",DEVICE_INFO_RESPONSE:"DEVICE_INFO_RESPONSE",TTS_RESPONSE_SETTINGS:"TTS_RESPONSE_SETTINGS",TTS_RESPONSE_START_SPEAKING:"TTS_RESPONSE_START_SPEAKING",TTS_RESPONSE_STOP_SPEAKING:"TTS_RESPONSE_STOP_SPEAKING",ERROR_SIMULATION_RESPONSE:"ERROR_SIMULATION_RESPONSE",LAUNCHER_READY:"LAUNCHER_READY",BRIDGE_READY:"BRIDGE_READY",TTS_SETTINGS_CHANGE:"TTS_SETTINGS_CHANGE",TM_SETTINGS_CHANGE:"TM_SETTINGS_CHANGE",LOG_ENTRY:"LOG_ENTRY",ERROR_RESPONSE:"ERROR_RESPONSE",TRANSFER_DATA:"TRANSFER_DATA"},T={TTS_SETTINGS_CHANGE:w.TTS_SETTINGS_CHANGE,TM_SETTINGS_CHANGE:w.TM_SETTINGS_CHANGE,LOG_ENTRY:w.LOG_ENTRY},E={enabled:!1,available:!1},I={enabled:!1,available:!1},D={tts:E,tm:I},C="TIMEOUT",R="NOT_SUPPORTED",A="INVALID_REQUEST",M="COMMUNICATION_ERROR",P="LAUNCH_FAILED",k="APP_NOT_FOUND",O="APP_NOT_AVAILABLE",_="INVALID_APP_CODE";var N=(e=>(e.PHILIPS="philips",e.VESTEL="vestel",e.BROWSER="browser",e))(N||{});class L{mocks={};constructor(e){e&&(this.mocks={...e})}get(e){return e in this.mocks?this.mocks[e]:"undefined"!=typeof window&&e in window?window[e]:void 0}has(e){return e in this.mocks||"undefined"!=typeof window&&e in window}get proxy(){return new Proxy({},{get:(e,t)=>{const i=t,n=this.get(i);return"function"==typeof n?(...e)=>{try{return n(...e)}catch(t){return}}:n}})}setMocks(e){this.mocks={...this.mocks,...e}}clearMocks(){this.mocks={}}removeMock(e){const t={};for(const i in this.mocks)i!==e&&(t[i]=this.mocks[i]);this.mocks=t}getAvailableMethods(){const e=new Set;for(const t in this.mocks)Object.prototype.hasOwnProperty.call(this.mocks,t)&&e.add(t);if("undefined"!=typeof window)for(const t in window)Object.prototype.hasOwnProperty.call(window,t)&&t in window&&e.add(t);return Array.from(e)}create(e,t){"undefined"!=typeof window&&(window[e]=t)}removeGlobal(e){"undefined"!=typeof window&&e in window&&delete window[e]}}function x(e,t,i="titanos"){return new Promise(((e,n)=>{const r=new L,s="deviceInfoCallback_"+Date.now()+"_"+Math.floor(1e4*Math.random());r.create(s,(t=>{e(t),r.removeGlobal(s)}));const o=`https://${t}/potamoi/v1/device_info?callback=${s}`,a=`https://smarttv.zeasn.tv/homepage_api/device/clientInfo?callback=${s}`,c=document.createElement("script");c.src="titanos"===i?o:a,c.type="text/javascript",c.onerror=()=>{n(new Error("Failed to load device info script.")),delete r.proxy[s]},document.head.appendChild(c),setTimeout((()=>{r.has(s)&&(n(new Error("Device info request timed out.")),delete r.proxy[s]),c.parentNode&&c.parentNode.removeChild(c)}),7e3)}))}const H=()=>{const e=e=>{const t=(Math.random().toString(16)+"000000000").substring(2,10);return e?"-"+t.substring(0,4)+"-"+t.substring(4,8):t};return e(!1)+e(!0)+e(!0)+e(!1)},U=1e4,F=[{time:3e4,message:"DOM still not ready after 30 seconds"},{time:6e4,message:"DOM still not ready after 1 minute"},{time:12e4,message:"DOM still not ready after 2 minutes"},{time:18e4,message:"DOM still not ready after 3 minutes"},{time:24e4,message:"DOM still not ready after 4 minutes"},{time:3e5,message:"DOM still not ready after 5 minutes - this may indicate serious page issues"}],K=c("DOM-Utils");function B(){return"undefined"!=typeof document&&!!document.body}const z=(e="en-US")=>"undefined"!=typeof navigator&&navigator.language&&navigator.language||e,V=c("BaseBridge");class ${src="";isInitialized=!1;iframe=null;iframeOrigin="";pendingRequests=new Map;messageTimeout=1e4;iframeTimeout=3e3;connected=!1;debug=!1;initializationPromise=null;aborted=!1;initReject;MESSAGE_TYPES=w;eventHandlers=new Map;constructor(e){this.debug=(null==e?void 0:e.debug)||!1,(null==e?void 0:e.gatewayUrl)&&(this.src=e.gatewayUrl),V.debug("bridge: constructor",this.src)}async initialize(){if(this.isInitialized)return!0;if(this.initializationPromise)return V.debug("bridge: initialization already in progress, waiting..."),this.initializationPromise;V.debug("bridge: initialization not in progress, starting new one"),this.initializationPromise=this.performInitialization();try{return await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}async performInitialization(){return new Promise(((e,t)=>{this.aborted=!1,this.initReject=t,V.debug("bridge: starting initialization process"),window.addEventListener("message",this.handleMessage.bind(this));const i=()=>{this.aborted||(this.isInitialized=!0,V.debug("bridge initialized successfully"),e(!0))},n=()=>{this.aborted||(V.error("Bridge iframe failed to load or initialize."),this.isInitialized=!1,t(new Error("Bridge iframe failed to load or initialize.")))};(async()=>{try{await this.setupIframe(i,n)}catch(e){V.error("Failed to setup iframe:",e),this.isInitialized=!1,t(e)}})()}))}async sendMessage(e,t){this.isInitialized||await this.initialize();try{const i=this.prepareMessage(e,t);return new Promise(((e,t)=>{const n=setTimeout((()=>{this.pendingRequests.delete(i.requestId),t(new s("Bridge request timeout",r.TIMEOUT))}),this.messageTimeout);this.pendingRequests.set(i.requestId,{resolve:e,reject:t,timeout:n}),this.iframe&&this.iframe.contentWindow?(V.debug("bridge: sendMessage",i),this.iframe.contentWindow.postMessage(i,this.iframeOrigin||"*")):(clearTimeout(n),this.pendingRequests.delete(i.requestId),t(new s("Bridge iframe not available",r.COMMUNICATION_ERROR)))}))}catch(i){V.error("bridge: error sending message:",i);return(await Promise.resolve().then((()=>_t)).then((e=>e.rollbarClient))).reportError(i instanceof Error?i:new Error("Unknown error"),{component:"SDK",operation:"sendMessage",requestId:this.prepareMessage(e,t).requestId}),Promise.reject({success:!1,type:e,error:{code:r.COMMUNICATION_ERROR,message:i instanceof Error?i.message:"Unknown error"}})}}disconnect(){this.aborted=!0,this.initReject&&(this.initReject(new Error("Bridge initialization aborted")),this.initReject=void 0),this.iframe&&(window.removeEventListener("message",this.handleMessage.bind(this)),document.body.removeChild(this.iframe),this.iframe=null),this.isInitialized=!1,this.connected=!1,this.initializationPromise=null,this.pendingRequests.clear(),this.eventHandlers.clear()}isConnected(){return this.isInitialized&&this.connected}getBridgeHealth(){return{connected:this.isConnected()}}registerEventHandler(e,t){var i;this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set);const n=e=>{t(e)};return null==(i=this.eventHandlers.get(e))||i.add(n),window.addEventListener("message",(e=>n(e.data.data))),()=>{var t;window.removeEventListener("message",(e=>{var t;return n(null==(t=e.data)?void 0:t.data)})),null==(t=this.eventHandlers.get(e))||t.delete(n)}}handleMessage(e){var t;if(!this.iframeOrigin||e.origin===this.iframeOrigin)try{const i=e.data;if(this.debug&&i&&i.requestId&&V.debug("bridge handleMessage",i),i&&("BRIDGE_READY"===i.type||"LAUNCHER_READY"===i.type)&&(null==(t=this.iframe)?void 0:t.contentWindow)===e.source)return void(this.connected=!0);if(i&&i.type&&Object.values(T).includes(i.type)&&!i.requestId)return void this.handleNotification(i);if(i&&i.requestId&&this.pendingRequests.has(i.requestId)){const{resolve:e,reject:t,timeout:n}=this.pendingRequests.get(i.requestId);if(clearTimeout(n),this.pendingRequests.delete(i.requestId),!1===i.success&&i.error){const e=this.getOperationFromMessageType(i.type||"unknown");t(this.createSDKErrorFromGatewayResponse(i.error,e))}else e({success:!0,data:i.response||i.data||i.result,requestId:i.requestId,timestamp:i.timestamp||Date.now()})}}catch(i){V.error("Error handling message:",i)}}handleNotification(e){V.debug("bridge notification received:",e);const t=this.eventHandlers.get(e.type);t&&t.forEach((t=>{try{t(e.data)}catch(i){V.error(`Error in ${e.type} handler:`,i)}}))}prepareMessage(e,t){return{payload:t,type:e,requestId:this.generateRequestId(),timestamp:Date.now()}}generateRequestId(){return`bridge_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}createSDKErrorFromGatewayResponse(e,t){const i=this.mapGatewayErrorCodeToSDK(e.code);return new s(e.message,i,{operation:t,gatewayErrorCode:e.code,gatewayErrorMessage:e.message})}mapGatewayErrorCodeToSDK(e){switch(e){case P:case k:case O:case _:return r.INVALID_PARAMETER;case C:return r.TIMEOUT;case R:return r.NOT_SUPPORTED;case M:return r.COMMUNICATION_ERROR;case A:return r.INVALID_ARGUMENTS;default:return r.UNKNOWN}}getOperationFromMessageType(e){switch(e){case w.LAUNCH_APP_REQUEST:return"launchApp";case w.DEVICE_INFO_REQUEST:return"getDeviceInfo";case w.TTS_REQUEST_START_SPEAKING:return"startSpeaking";case w.TTS_REQUEST_STOP_SPEAKING:return"stopSpeaking";case w.TTS_REQUEST_SETTINGS:return"getTTSSettings";default:return"sdkOperation"}}async setupIframe(e,t){if(!this.iframe&&this.src){if(await new Promise((e=>{"undefined"!=typeof document&&"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>e()),{once:!0}):e()})),this.iframe=document.createElement("iframe"),this.iframe.style.display="none",this.iframe.src=this.src,this.iframe.setAttribute("sandbox","allow-scripts"),!B())try{await function(e=1e4){return new Promise(((t,i)=>{if(B())return void t();const n=Date.now();let r=0,s="initial";K.debug("Waiting for document.body:",{readyState:document.readyState,bodyExists:!!document.body,htmlExists:!!document.documentElement,headExists:!!document.head,timeout:e});let o=null,a=null,c=null;const l=[];function d(){a&&(clearInterval(a),a=null),o&&(o.disconnect(),o=null),c&&(clearTimeout(c),c=null),l.forEach(clearTimeout),l.length=0}const u=(e,t)=>{if(s!==e){const i=Date.now()-n;K.debug(`DOM strategy changed: ${s} → ${e}`,{elapsed:i,reason:t||"strategy switch",checkCount:r}),s=e}},g=(e,t="warn")=>{const i=Date.now()-n,s=Math.floor(i/6e4),o=Math.floor(i%6e4/1e3);"error"===t?K.error(`${e} after ${s}m ${o}s`,{elapsed:i,checkCount:r,readyState:document.readyState,bodyExists:!!document.body}):K.warn(`${e} after ${s}m ${o}s`,{elapsed:i,checkCount:r,readyState:document.readyState})},h=e=>{u("mutation-observer","DOMContentLoaded completed but body not ready"),o=new MutationObserver((()=>{r++;const e=Date.now()-n;B()&&(d(),K.debug("document.body ready via MutationObserver:",{elapsed:e,checkCount:r}),t())})),o.observe(document.documentElement,{childList:!0,subtree:!1}),c=setTimeout((()=>{B()||(g("DOM still not ready, switching to polling fallback"),u("polling","MutationObserver timeout"),a=setInterval((()=>{r++;const e=Date.now()-n;B()&&(d(),K.debug("document.body ready via polling fallback:",{elapsed:e,checkCount:r}),t())}),50))}),3e4)};if("loading"===document.readyState){u("dom-content-loaded","document still loading");const s=()=>{var e;clearTimeout(o);const i=Date.now()-n;B()?(d(),K.debug("document.body ready after DOMContentLoaded:",{elapsed:i}),t()):(K.warn("DOMContentLoaded fired but body still not ready:",{elapsed:i,childNodes:(null==(e=document.documentElement)?void 0:e.childNodes.length)||0}),h())},o=setTimeout((()=>{var e;document.removeEventListener("DOMContentLoaded",s),d();const t=Date.now()-n;K.error("Timeout waiting for document.body:",{elapsed:t,readyState:document.readyState,bodyExists:!!document.body,checkCount:r,html:!!document.documentElement,head:!!document.head,childNodesCount:(null==(e=document.documentElement)?void 0:e.childNodes.length)||0}),i(new Error(`Timeout waiting for document.body after ${t}ms. readyState: ${document.readyState}, checks: ${r}. Initialize SDK after DOMContentLoaded or use defer/async script.`))}),e);document.addEventListener("DOMContentLoaded",s,{once:!0})}else K.debug("DOM already loaded, using MutationObserver + polling"),h();F.forEach((({time:t,message:i})=>{if(t<e){const e=setTimeout((()=>{B()||g(i)}),t);l.push(e)}}))}))}(U)}catch(i){throw V.error("Document body unavailable:",{readyState:document.readyState,bodyExists:!!document.body,timeout:10}),new Error("Document body is not available. SDK initialized too early - ensure DOM is ready before calling getTitanSDK(). Consider initializing SDK after DOMContentLoaded event or in a defer/async script.")}document.body.appendChild(this.iframe),await new Promise((i=>{const n=setTimeout((()=>{this.aborted||(V.warn("Bridge iframe ready timeout - continuing anyway"),i())}),this.iframeTimeout),r=t=>{var s;this.aborted||t.data&&t.data.type===w.LAUNCHER_READY&&(null==(s=this.iframe)?void 0:s.contentWindow)===t.source&&(V.debug("bridge iframe ready:",t.data),window.removeEventListener("message",r),clearTimeout(n),this.connected=!0,e&&e(),i())};window.addEventListener("message",r),window.addEventListener("message",(e=>{var t;this.aborted||e.data&&e.data.type===w.TRANSFER_DATA&&(null==(t=this.iframe)?void 0:t.contentWindow)===e.source&&V.debug("bridge transferData:",e.data)})),this.iframe&&(this.iframe.onload=()=>{this.aborted||V.debug("bridge iframe loaded: ",this.src)},this.iframe.onerror=()=>{this.aborted||(V.error("bridge iframe error: ",this.src),t&&t())})}))}}promisify(e){return(...t)=>new Promise(((i,n)=>{try{i(e.apply(null,t))}catch(r){n(r)}}))}async getDeviceInfo(){this.isInitialized||await this.initialize();const e=await this.sendMessage(w.DEVICE_INFO_REQUEST,void 0);if(e.success&&"data"in e)return e.data}async launchApp(e){this.isInitialized||await this.initialize();const t={code:e.appId,query:e.deepLink||""};return(await this.sendMessage(w.LAUNCH_APP_REQUEST,t)).success}onLogEntry(e){return this.registerEventHandler(w.LOG_ENTRY,(t=>{h({...t,metadata:{...t.metadata,source:"Gateway",tunneled:!0}}),e(t)}))}}const G=c("CSPDetector");let j=[];const W=class{static getViolations(){return[...this.violations]}static clearViolations(){this.violations.length=0}static onViolation(e){return j.push(e),()=>{j=j.filter((t=>t!==e))}}static checkWebAPISupport(){return{hasPostMessage:"undefined"!=typeof window&&"postMessage"in window,hasIframe:"undefined"!=typeof document&&"createElement"in document,hasMessageEvent:"undefined"!=typeof MessageEvent,hasDocument:"undefined"!=typeof document}}};var q;((e,t,n)=>{t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(W,"symbol"!=typeof(q="violations")?q+"":q,[]),"undefined"!=typeof document&&document.addEventListener("securitypolicyviolation",(e=>{const t=`${e.violatedDirective}: ${e.blockedURI}`;W.violations.push(t),G.warn("CSP Violation detected:",t);const i={directive:e.violatedDirective,blockedURI:e.blockedURI,originalEvent:e};j.forEach((e=>{try{e(i)}catch(t){G.error("CSPDetector listener error",t)}}))}));let Q=W;const J=c("EnhancedBridge");class Y extends ${bridgeHealthStatus={connected:!1,cspBlocked:!1,iframeCreated:!1,communicationWorking:!1,cspViolations:[]};cspUnsubscribe;constructor(e){super(e),this.bridgeHealthStatus.gatewayUrl=this.src,this.setupCspViolationListener()}setupCspViolationListener(){this.cspUnsubscribe=Q.onViolation((e=>{(function(e,t){return!("frame-src"!==e.directive||!e.blockedURI||!t)&&(t.includes(e.blockedURI)||e.blockedURI.includes(t))})(e,this.src)&&(J.warn("CSP violation detected for bridge:",{directive:e.directive,blockedURI:e.blockedURI,gatewayUrl:this.src}),this.bridgeHealthStatus.cspBlocked=!0,this.bridgeHealthStatus.lastError=`CSP blocked: ${e.directive}`)}))}async initialize(){try{J.debug("Starting enhanced bridge initialization");const e=await super.initialize();return this.bridgeHealthStatus.connected=!!e,!!e}catch(e){const t=e instanceof Error?e.message:"Unknown error";return this.bridgeHealthStatus.lastError=t,J.error("Enhanced bridge initialization failed:",e),!1}}getBridgeHealth(){return{...this.bridgeHealthStatus,connected:this.isConnected(),iframeCreated:null!==this.iframe}}disconnect(){this.aborted||(super.disconnect(),this.bridgeHealthStatus.connected=!1,this.bridgeHealthStatus.communicationWorking=!1,this.cspUnsubscribe&&(this.cspUnsubscribe(),this.cspUnsubscribe=void 0),this.bridgeHealthStatus={connected:!1,cspBlocked:!1,iframeCreated:!1,communicationWorking:!1,gatewayUrl:this.src,cspViolations:[]},this.aborted=!0)}async setupIframe(e,t){try{J.debug("Setting up bridge iframe"),await super.setupIframe(e,t),this.bridgeHealthStatus.iframeCreated=!0}catch(i){this.bridgeHealthStatus.iframeCreated=!1;const e=i instanceof Error?i.message:"Unknown error";throw this.bridgeHealthStatus.lastError=e,J.error("Failed to setup iframe:",{error:e,gatewayUrl:this.src,documentReady:document.readyState,bodyExists:!!document.body}),i}}async executeBridgeFunction(e,t){const i=this.getBridgeHealth();if(!i.connected){if(t)return J.debug("Bridge not connected, using fallback function"),await t();throw new s("Bridge not connected",r.COMMUNICATION_ERROR,{healthStatus:i})}return await e()}async executeWithFallback(e,t){return await this.executeBridgeFunction(e,t)}async sendMessage(e,t){return await this.executeBridgeFunction((()=>super.sendMessage(e,t)))}getConnectionResult(){const e=this.getBridgeHealth();return{success:e.connected&&!e.cspBlocked,healthStatus:e,error:e.lastError}}}class Z extends Y{constructor(e){if(null==e?void 0:e.gatewayUrl)super({gatewayUrl:e.gatewayUrl});else{const e=window.location.hostname.includes("dev01.devview"),t=window.location.hostname.startsWith("dev");super({gatewayUrl:`http://localhost:4660/gateway/${e||t?"dev01":"index"}.html`})}}}const X=new L;class ee extends Y{constructor(e){var t,i;if(null==e?void 0:e.gatewayUrl)super({gatewayUrl:e.gatewayUrl});else{let e="app";if(X.proxy.jwt&&!X.proxy.jwt.includes("null")){const t=(e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT token format");try{const e=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=window.atob(e),n=decodeURIComponent(Array.from(i).map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));return JSON.parse(n)}catch(i){throw new Error("Error decoding JWT token: "+(i instanceof Error?i.message:String(i)))}})(X.proxy.jwt);e=("production"===t.iss?"app":t.iss)||"app"}let n=`https://${e}.titanos.tv/gateway/${e.startsWith("dev")?"dev01":"index"}.html`;((null==(i=null==(t=X.proxy.location)?void 0:t.host)?void 0:i.includes("dev01.devview"))||e.startsWith("dev"))&&(n="https://dev01.devview.titanos.tv/gateway/dev01.html"),super({gatewayUrl:n})}}async getTTSSettings(){return(await this.getA11ySettings()).tts||E}async getTMSettings(){return(await this.getA11ySettings()).tm||I}async getA11ySettings(){const e=await this.sendMessage(w.TTS_REQUEST_SETTINGS,void 0);return e.success&&"data"in e?e.data:D}async startSpeaking(e){this.isInitialized||await this.initialize();return(await this.sendMessage(w.TTS_REQUEST_START_SPEAKING,e)).success}async stopSpeaking(){return(await this.sendMessage(w.TTS_REQUEST_STOP_SPEAKING,void 0)).success}onTTSSettingsChange(e){return this.registerEventHandler(w.TTS_SETTINGS_CHANGE,(t=>{e(t)}))}onTMSettingsChange(e){return this.registerEventHandler(w.TM_SETTINGS_CHANGE,(t=>{e(t)}))}}const te={HIGH:["button","link","heading","listitem"],MEDIUM:["textbox","combobox","checkbox","radio","slider"],LOW:["list","navigation","main","dialog","grid"]},ie=c("AriaProcessor");class ne{config;implicitRoles={button:"button",a:"link",'input[type="text"]':"textbox",'input[type="email"]':"textbox",'input[type="password"]':"textbox",'input[type="search"]':"textbox",'input[type="tel"]':"textbox",'input[type="url"]':"textbox",'input[type="checkbox"]':"checkbox",'input[type="radio"]':"radio",'input[type="range"]':"slider",textarea:"textbox",select:"combobox",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",nav:"navigation",main:"main",aside:"complementary",section:"region",article:"article",ul:"list",ol:"list",li:"listitem",table:"table",tr:"row",td:"cell",th:"columnheader",img:"img",dialog:"dialog"};tvElementTypes={navigation:["nav","menu",'[role="navigation"]','[role="menubar"]'],mediaControl:['[role="button"][aria-label*="play"]','[role="button"][aria-label*="pause"]','[role="slider"][aria-label*="volume"]','[role="progressbar"]'],contentGrid:['[role="grid"]','[role="gridcell"]',".content-grid",".video-grid"],mainContent:["main",'[role="main"]',".main-content","#main"]};constructor(e){this.config={...e}}updateConfig(e){this.config={...e}}async processElement(e){try{if(this.isElementHidden(e))return null;const t=this.getElementRole(e);if(this.config.tvOptimized&&!this.isRelevantForTV(t))return null;const i=this.computeAccessibleName(e);if(!i&&this.isInteractiveElement(t))return ie.warn("Interactive element without accessible name:",e),null;const n=this.getAccessibleDescription(e),r=this.computeElementState(e),s=this.computePositionInfo(e,t),o=this.getAvailableActions(e,t),a=this.config.tvOptimized?this.getTVSpecificProperties(e,t):void 0,c={element:e,role:t,name:i,description:n,state:r,position:s,actions:o,tvProperties:a};return ie.debug("Processed accessibility element:",{role:t,name:i.substring(0,50),state:r,tvOptimized:!!a}),c}catch(t){return ie.error("Error processing element:",t),null}}isElementHidden(e){if("true"===e.getAttribute("aria-hidden"))return!0;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||"0"===t.opacity)return!0;if(this.config.tvOptimized){const t=e.getBoundingClientRect();if(0===t.width&&0===t.height)return!0}return!1}getElementRole(e){const t=e.getAttribute("role");if(t)return t;const i=e.tagName.toLowerCase(),n=e.getAttribute("type");if("input"===i&&n){const e=`input[type="${n}"]`;if(this.implicitRoles[e])return this.implicitRoles[e]}return this.implicitRoles[i]||"generic"}computeAccessibleName(e){const t=e.getAttribute("aria-labelledby");if(t){const e=[];for(const i of t.split(/\s+/)){const t=document.getElementById(i);t&&e.push(this.getTextContent(t))}if(e.length>0)return e.join(" ").trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();if(this.isFormControl(e)){const t=this.getAssociatedLabels(e);if(t.length>0)return t.map((e=>this.getTextContent(e))).join(" ").trim()}if("input"===e.tagName.toLowerCase()){const t=e.getAttribute("placeholder");if(t)return t.trim()}if("img"===e.tagName.toLowerCase()){const t=e.getAttribute("alt");if(null!==t)return t.trim()}return this.getTextContent(e)}getAccessibleDescription(e){const t=e.getAttribute("aria-describedby");if(!t)return;const i=[];for(const n of t.split(/\s+/)){const e=document.getElementById(n);e&&i.push(this.getTextContent(e))}return i.length>0?i.join(" ").trim():void 0}computeElementState(e){const t={},i=e.getAttribute("aria-expanded");null!==i&&(t.expanded="true"===i);const n=e.getAttribute("aria-checked");null!==n&&(t.checked="mixed"===n?"mixed":"true"===n);const r=e.getAttribute("aria-selected");null!==r&&(t.selected="true"===r);const s=e.getAttribute("aria-disabled")||e.getAttribute("disabled");null!==s&&(t.disabled="true"===s||""===s);const o=e.getAttribute("aria-invalid");null!==o&&(t.invalid="true"===o||o);const a=e.getAttribute("aria-level");null!==a?t.level=parseInt(a,10):e.tagName.match(/^H[1-6]$/)&&(t.level=parseInt(e.tagName.charAt(1),10));const c=e.getAttribute("aria-valuenow");null!==c&&(t.valueNow=parseFloat(c));const l=e.getAttribute("aria-valuetext");return null!==l&&(t.valueText=l),t.focused=document.activeElement===e,t}computePositionInfo(e,t){return"listitem"===t?this.computeListItemPosition(e):"gridcell"===t||"cell"===t?this.computeGridCellPosition(e):void 0}computeListItemPosition(e){const t=e.getAttribute("aria-posinset"),i=e.getAttribute("aria-setsize");if(t&&i)return{position:parseInt(t,10),setSize:parseInt(i,10)};const n=e.closest('ul, ol, [role="list"]');if(n){const t=Array.from(n.querySelectorAll('li, [role="listitem"]')),i=t.indexOf(e)+1;if(i>0)return{position:i,setSize:t.length}}}computeGridCellPosition(e){const t=e.closest('[role="row"], tr'),i=e.closest('[role="grid"], table');if(t&&i){const n=Array.from(i.querySelectorAll('[role="row"], tr')),r=Array.from(t.querySelectorAll('[role="gridcell"], [role="cell"], td, th')),s=n.indexOf(t)+1,o=r.indexOf(e)+1;if(s>0&&o>0)return{position:o,setSize:r.length,row:s,column:o,totalRows:n.length,totalColumns:r.length}}}getAvailableActions(e,t){const i=[];if(this.isClickableElement(e,t)&&i.push({name:"activate",description:this.getActivationDescription(t),tvButton:"OK"}),e.hasAttribute("aria-expanded")){const t="true"===e.getAttribute("aria-expanded");i.push({name:t?"collapse":"expand",description:t?"Collapse":"Expand",tvButton:"OK"})}return"textbox"!==t&&"combobox"!==t||i.push({name:"edit",description:"Enter text",tvButton:"OK"}),i}getTVSpecificProperties(e,t){const i={};return this.matchesSelectors(e,this.tvElementTypes.navigation)&&(i.isMainNavigation=!0,i.priority="high"),this.matchesSelectors(e,this.tvElementTypes.mediaControl)&&(i.isMediaControl=!0,i.priority="high"),this.matchesSelectors(e,this.tvElementTypes.contentGrid)&&(i.isContentGrid=!0,i.priority="medium"),i.priority||(te.HIGH.includes(t)?i.priority="high":te.MEDIUM.includes(t)?i.priority="medium":i.priority="low"),Object.keys(i).length>0?i:void 0}isRelevantForTV(e){return[...te.HIGH,...te.MEDIUM,...te.LOW].includes(e)}isInteractiveElement(e){return["button","link","textbox","combobox","checkbox","radio","slider"].includes(e)}isFormControl(e){return["input","textarea","select","button"].includes(e.tagName.toLowerCase())}isClickableElement(e,t){return["button","link","checkbox","radio","menuitem"].includes(t)||e.hasAttribute("onclick")}getActivationDescription(e){return{button:"Press button",link:"Follow link",checkbox:"Toggle checkbox",radio:"Select option",menuitem:"Select menu item"}[e]||"Activate"}getTextContent(e){let t="";for(const i of e.childNodes)if(i.nodeType===Node.TEXT_NODE)t+=i.textContent||"";else if(i.nodeType===Node.ELEMENT_NODE){const e=i;this.isElementHidden(e)||(t+=this.getTextContent(e))}return t.replace(/\s+/g," ").trim()}getAssociatedLabels(e){const t=[],i=e.getAttribute("id");if(i){const e=document.querySelectorAll(`label[for="${i}"]`);t.push(...Array.from(e))}const n=e.closest("label");return n&&t.push(n),t}matchesSelectors(e,t){return t.some((t=>{try{return e.matches(t)}catch{return!1}}))}}const re=c("DOMMonitor");class se{config;ariaProcessor;isTracking=!1;focusHandler;liveRegionHandler;focusListener;keydownListener;mutationObserver;currentFocusedElement=null;liveRegions=new Map;previousFocusedElement=null;constructor(e,t){this.config={...e},this.focusHandler=t,this.ariaProcessor=new ne(e)}updateConfig(e){this.config={...e},this.ariaProcessor.updateConfig(e)}async startFocusTracking(){if(this.isTracking)return void re.debug("Focus tracking already active");re.info("Starting focus tracking"),this.focusListener=this.handleFocusEvent.bind(this),document.addEventListener("focusin",this.focusListener,!0),document.addEventListener("focusout",this.focusListener,!0),this.keydownListener=this.handleKeydownEvent.bind(this),document.addEventListener("keydown",this.keydownListener,!0);const e=document.activeElement;e&&e!==document.body&&(this.currentFocusedElement=e,await this.processFocusChange(e,"initial")),this.isTracking=!0,re.info("Focus tracking started")}async startLiveRegionMonitoring(e){this.liveRegionHandler=e,re.info("Starting live region monitoring"),await this.scanForLiveRegions(),this.mutationObserver=new MutationObserver(this.handleMutations.bind(this)),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["aria-live","aria-atomic","aria-relevant","aria-busy"]}),re.info("Live region monitoring started")}async stop(){re.info("Stopping DOM monitoring"),this.focusListener&&(document.removeEventListener("focusin",this.focusListener,!0),document.removeEventListener("focusout",this.focusListener,!0),this.focusListener=void 0),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener,!0),this.keydownListener=void 0),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=void 0),this.currentFocusedElement=null,this.previousFocusedElement=null,this.liveRegions.clear(),this.isTracking=!1,this.liveRegionHandler=void 0,re.info("DOM monitoring stopped")}async restart(){await this.stop(),this.config.focusTracking&&await this.startFocusTracking(),this.config.liveRegions&&this.liveRegionHandler&&await this.startLiveRegionMonitoring(this.liveRegionHandler)}async handleFocusEvent(e){try{const t=e.target;"focusin"===e.type?t&&t!==this.currentFocusedElement&&(this.currentFocusedElement=t,await this.processFocusChange(t,"user")):"focusout"===e.type&&t===this.currentFocusedElement&&(this.currentFocusedElement=null)}catch(t){re.error("Error handling focus event:",t)}}async handleKeydownEvent(e){const t={ArrowUp:"UP",ArrowDown:"DOWN",ArrowLeft:"LEFT",ArrowRight:"RIGHT",Enter:"OK",Escape:"BACK",Tab:"TAB"}[e.key];t&&this.currentFocusedElement&&re.debug("TV remote button pressed:",t)}async processFocusChange(e,t){try{if(this.ariaProcessor.isElementHidden(e))return;const i=await this.ariaProcessor.processElement(e);if(i&&this.focusHandler){const e={previousElement:this.previousFocusedElement||void 0,currentElement:i,reason:t};await this.focusHandler(e),this.previousFocusedElement=i}}catch(i){re.error("Error processing focus change:",i)}}async scanForLiveRegions(){const e=document.querySelectorAll("[aria-live]");for(const t of e){const e=this.createLiveRegion(t);e&&(this.liveRegions.set(t,e),re.debug("Found live region:",{politeness:e.politeness,atomic:e.atomic}))}}createLiveRegion(e){const t=e.getAttribute("aria-live");if(!t||"off"===t)return null;const i=t,n="true"===e.getAttribute("aria-atomic"),r=(e.getAttribute("aria-relevant")||"additions text").split(" "),s="true"===e.getAttribute("aria-busy");return{element:e,politeness:i,atomic:n,relevant:r,busy:s}}async handleMutations(e){for(const i of e)try{"attributes"===i.type&&await this.handleAttributeChange(i),"childList"!==i.type&&"characterData"!==i.type||await this.handleContentChange(i)}catch(t){re.error("Error handling mutation:",t)}}async handleAttributeChange(e){const t=e.target,i=e.attributeName;if("aria-live"===i){const e=this.createLiveRegion(t);e?this.liveRegions.set(t,e):this.liveRegions.delete(t)}else if("aria-busy"===i){const e=this.liveRegions.get(t);e&&(e.busy="true"===t.getAttribute("aria-busy"))}}async handleContentChange(e){let t=e.target;for(;t&&t!==document.body;){const i=this.liveRegions.get(t);if(i&&!i.busy&&this.liveRegionHandler){const n=i.atomic?t.textContent||"":this.extractChangedContent(e);n.trim()&&await this.liveRegionHandler(i,n);break}t=t.parentElement}}extractChangedContent(e){if("characterData"===e.type)return e.target.textContent||"";if("childList"===e.type){let t="";for(const i of e.addedNodes)(i.nodeType===Node.TEXT_NODE||i.nodeType===Node.ELEMENT_NODE)&&(t+=i.textContent||"");return t}return""}}const oe=c("AnnouncementProcessor");class ae{config;ttsFunction;stopTtsFunction;lastAnnouncementTime=0;announcementQueue=[];isProcessingQueue=!1;tvTimings={minInterval:100,maxQueueSize:5,priorityDelay:50,politeDelay:200};constructor(e,t,i){this.config={...e},this.ttsFunction=t,this.stopTtsFunction=i}updateConfig(e){this.config={...e}}async announce(e,t="polite"){const i=this.processAnnouncementText(e);if(!i||0===i.length)return oe.debug("No text to announce after processing"),!1;const n={text:i,priority:t,timestamp:Date.now()};return"assertive"===t?(this.announcementQueue.length=0,await this.speakNow(n)):(this.queueAnnouncement(n),this.processQueue(),!0)}async stopAnnouncement(){try{if(this.announcementQueue.length=0,this.isProcessingQueue=!1,this.stopTtsFunction){const e=await this.stopTtsFunction();return oe.debug("TTS stop result:",e),e}return oe.debug("No stopTtsFunction available"),!0}catch(e){return oe.error("Error stopping announcement:",e),!1}}async announceFocusChange(e){const{currentElement:t}=e;if(!t)return;const i=this.buildFocusAnnouncement(t);i.length>0&&await this.announce(i,"polite")}async announceLiveRegion(e,t){if(!e.trim())return;const i=this.processLiveRegionContent(e);i&&await this.announce([i],t)}buildFocusAnnouncement(e){const t=[],i=this.getRoleAnnouncement(e.role);i&&t.push(i),e.name&&t.push(e.name);const n=this.getStateAnnouncement(e.state,e.role);n.length>0&&t.push(...n);const r=this.getPositionAnnouncement(e.position,e.role);r&&t.push(r),e.description&&this.shouldIncludeDescription()&&t.push(e.description);const s=this.getActionAnnouncement(e.actions||[]);return s&&t.push(s),this.filterAnnouncementContent(t,e.role)}shouldIncludeDescription(){return"concise"!==this.config.verbosity&&(this.config.verbosity,!0)}filterAnnouncementContent(e,t){if(!this.config.tvOptimized)return e;const i=["button","link","heading","alert","dialog"].includes(t);return"concise"===this.config.verbosity?i?e.slice(0,2):e.slice(1,2):"standard"===this.config.verbosity?e.slice(0,4):e}getRoleAnnouncement(e){const t={button:{concise:"",standard:"button",detailed:"button"},link:{concise:"",standard:"link",detailed:"link"},heading:{concise:"",standard:"heading",detailed:"heading"},listitem:{concise:"",standard:"list item",detailed:"list item"},textbox:{concise:"",standard:"text field",detailed:"text field"},combobox:{concise:"",standard:"dropdown",detailed:"combo box"},checkbox:{concise:"check box",standard:"check box",detailed:"check box"},radio:{concise:"radio",standard:"radio button",detailed:"radio button"},slider:{concise:"slider",standard:"slider",detailed:"slider"},navigation:{concise:"",standard:"navigation",detailed:"navigation menu"},main:{concise:"",standard:"main content",detailed:"main content area"},dialog:{concise:"dialog",standard:"dialog",detailed:"dialog box"},grid:{concise:"",standard:"grid",detailed:"content grid"},gridcell:{concise:"",standard:"",detailed:"grid cell"},list:{concise:"",standard:"list",detailed:"list"},menu:{concise:"menu",standard:"menu",detailed:"menu"},menuitem:{concise:"",standard:"menu item",detailed:"menu item"},tab:{concise:"tab",standard:"tab",detailed:"tab"},tabpanel:{concise:"",standard:"tab panel",detailed:"tab panel"},progressbar:{concise:"progress",standard:"progress bar",detailed:"progress indicator"},alert:{concise:"alert",standard:"alert",detailed:"alert message"},status:{concise:"",standard:"status",detailed:"status update"}}[e];if(!t)return null;return t[this.config.verbosity]||t.standard||null}getStateAnnouncement(e,t){const i=[];if(!e)return i;const n="concise"===this.config.verbosity,r="detailed"===this.config.verbosity;if(void 0!==e.expanded&&(n?i.push(e.expanded?"open":"closed"):i.push(e.expanded?"expanded":"collapsed")),void 0!==e.checked&&("mixed"===e.checked?i.push(n?"mixed":"partially checked"):n?i.push(e.checked?"on":"off"):i.push(e.checked?"checked":"not checked")),e.selected&&i.push(n?"on":"selected"),e.disabled&&i.push("disabled"),e.invalid&&(r?i.push("string"==typeof e.invalid?e.invalid:"invalid"):i.push("invalid")),"heading"===t&&e.level&&(n?i.push(`h${e.level}`):i.push(`level ${e.level}`)),e.valueText)i.push(e.valueText);else if(void 0!==e.valueNow)if("progressbar"===t){const t=e.valueMax?Math.round(e.valueNow/e.valueMax*100):e.valueNow;i.push(n?`${t}%`:`${t} percent`)}else"slider"===t?i.push(n?`${e.valueNow}`:`value ${e.valueNow}`):i.push(`${e.valueNow}`);return this.config.tvOptimized&&e.focused&&r&&i.push("focused"),i}getPositionAnnouncement(e,t){if(!e)return null;const i="concise"===this.config.verbosity,n="detailed"===this.config.verbosity;return"listitem"===t?i?null:`${e.position} of ${e.setSize}`:"gridcell"===t&&e.row&&e.column?this.config.tvOptimized?i?`${e.row},${e.column}`:n&&e.totalRows&&e.totalColumns?`row ${e.row} of ${e.totalRows}, column ${e.column} of ${e.totalColumns}`:`row ${e.row}, column ${e.column}`:`row ${e.row}, column ${e.column}`:"tab"===t&&e.position&&e.setSize?i?null:`tab ${e.position} of ${e.setSize}`:"menuitem"===t&&e.position&&e.setSize?i?null:`${e.position} of ${e.setSize}`:null}getActionAnnouncement(e){if(!e||0===e.length)return null;const t="concise"===this.config.verbosity,i="detailed"===this.config.verbosity;if(!this.config.tvOptimized){return`available actions: ${e.map((e=>e.name)).slice(0,2).join(", ")}`}const n=e[0];if(!n)return null;if(n.tvButton){if(t)return null;const e=this.getTVButtonText(n.tvButton),r=n.description||"activate";return i?`press ${e} to ${r.toLowerCase()}`:`press ${e}`}if(n.name){if(t)return null;const e=this.getCommonTVAction(n.name);if(e)return i?`available actions: ${e}`:e}return null}getTVButtonText(e){return{OK:"OK",BACK:"Back",UP:"Up",DOWN:"Down",LEFT:"Left",RIGHT:"Right",MENU:"Menu"}[e]||e}getCommonTVAction(e){return{activate:"activate",click:"select",toggle:"toggle",expand:"expand",collapse:"collapse",select:"select",play:"play",pause:"pause",stop:"stop",mute:"mute",unmute:"unmute"}[e.toLowerCase()]||null}processAnnouncementText(e){if(!e)return[];if("string"==typeof e&&(e=[e]),!Array.isArray(e))return[];let t=[...e];return this.config.tvOptimized&&(t=this.applyTVOptimizations(t)),t=this.applyVerbosityFilter(t),t=t.map((e=>e.trim())).filter((e=>e.length>0)).map((e=>this.cleanupText(e))),t}applyTVOptimizations(e){return e.map((e=>{let t=e.replace(/\bnavigation\b/gi,"nav").replace(/\bmenuitem\b/gi,"menu").replace(/\btextbox\b/gi,"text field").replace(/\bcombobox\b/gi,"dropdown").replace(/\bcheckbox\b/gi,"check box");return t=t.replace(/\bapplication\b/gi,"").replace(/\bregion\b/gi,"").replace(/\blandmark\b/gi,""),t.trim()}))}applyVerbosityFilter(e){switch(this.config.verbosity){case"concise":return e.slice(0,2);case"detailed":return e;default:return e.slice(0,4)}}cleanupText(e){return e.replace(/\s+/g," ").replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim()}processLiveRegionContent(e){const t=this.cleanupText(e);return t.length<3||/^\s*[.!?]*\s*$/.test(t)?null:this.config.tvOptimized?this.applyTVOptimizations([t])[0]:t}queueAnnouncement(e){this.announcementQueue.length>=this.tvTimings.maxQueueSize&&this.announcementQueue.shift(),this.announcementQueue.push(e)}async processQueue(){if(!this.isProcessingQueue&&0!==this.announcementQueue.length){for(this.isProcessingQueue=!0;this.announcementQueue.length>0;){const e=this.announcementQueue.shift();if(e){await this.speakNow(e);const t="assertive"===e.priority?this.tvTimings.priorityDelay:this.tvTimings.politeDelay;await this.delay(t)}}this.isProcessingQueue=!1}}async speakNow(e){const t=Date.now()-this.lastAnnouncementTime;t<this.tvTimings.minInterval&&await this.delay(this.tvTimings.minInterval-t);try{const t=await this.ttsFunction(e.text);return this.lastAnnouncementTime=Date.now(),oe.debug("Announced:",{text:e.text.join(" ").substring(0,100),priority:e.priority,success:t}),t}catch(i){return oe.error("Error speaking announcement:",i),!1}}delay(e){return new Promise((t=>setTimeout(t,e)))}}const ce=c("AccessibilityReader");class le{config;isActive=!1;domMonitor;ariaProcessor;announcementProcessor;currentElement=null;liveRegions=new Map;constructor(e,t,i){this.config={...e},this.ariaProcessor=new ne(e),this.announcementProcessor=new ae(e,t,i),this.domMonitor=new se(e,this.handleFocusChange.bind(this))}async start(){if(this.isActive)return ce.debug("Accessibility Reader already active"),!0;try{ce.info("Starting Accessibility Reader",this.config),this.config.focusTracking&&await this.domMonitor.startFocusTracking(),this.config.liveRegions&&await this.domMonitor.startLiveRegionMonitoring(this.handleLiveRegionChange.bind(this));const e=document.activeElement;return e&&e!==document.body&&await this.announceElement(e),this.isActive=!0,ce.info("Accessibility Reader started successfully"),!0}catch(e){return ce.error("Failed to start Accessibility Reader:",e),!1}}async stop(){if(!this.isActive)return ce.debug("Accessibility Reader not active"),!0;try{return ce.info("Stopping Accessibility Reader"),await this.domMonitor.stop(),this.currentElement=null,this.liveRegions.clear(),this.isActive=!1,ce.info("Accessibility Reader stopped"),!0}catch(e){return ce.error("Failed to stop Accessibility Reader:",e),!1}}async updateConfig(e){try{const t={...this.config};if(this.config={...this.config,...e},this.ariaProcessor.updateConfig(this.config),this.announcementProcessor.updateConfig(this.config),this.domMonitor.updateConfig(this.config),this.isActive){const e=t.focusTracking!==this.config.focusTracking,i=t.liveRegions!==this.config.liveRegions;(e||i)&&await this.domMonitor.restart()}return ce.info("Accessibility Reader configuration updated",this.config),!0}catch(t){return ce.error("Failed to update Accessibility Reader config:",t),!1}}getConfig(){return{...this.config}}isReaderActive(){return this.isActive}async announce(e,t="polite"){return this.isActive?await this.announcementProcessor.announce(e,t):(ce.debug("Accessibility Reader not active, skipping announcement"),!1)}async stopAnnouncement(){return this.isActive?await this.announcementProcessor.stopAnnouncement():(ce.debug("Accessibility Reader not active, skipping stop"),!1)}getCurrentElement(){return this.currentElement}async handleFocusChange(e){var t,i;try{ce.debug("Focus changed",{from:null==(t=e.previousElement)?void 0:t.role,to:null==(i=e.currentElement)?void 0:i.role,reason:e.reason}),this.currentElement=e.currentElement||null,e.currentElement&&await this.announcementProcessor.announceFocusChange(e)}catch(n){ce.error("Error handling focus change:",n)}}async handleLiveRegionChange(e,t){try{if(ce.debug("Live region changed",{politeness:e.politeness,content:t.substring(0,100)}),e.busy)return;const i="assertive"===e.politeness?"assertive":"polite";await this.announcementProcessor.announceLiveRegion(t,i)}catch(i){ce.error("Error handling live region change:",i)}}async announceElement(e){try{const t=await this.ariaProcessor.processElement(e);if(t){const e={previousElement:this.currentElement||void 0,currentElement:t,reason:"programmatic"};await this.handleFocusChange(e)}}catch(t){ce.error("Error announcing element:",t)}}}class de{static sanitizeSpeechCues(e){return e.map((e=>this.sanitizeSpeechCue(e)))}static sanitizeSpeechCue(e){return"string"==typeof e?this.sanitizeText(e):{...e,Name:this.sanitizeText(e.Name),Value:e.Value?this.sanitizeText(e.Value):void 0,ItemSubType:e.ItemSubType?this.sanitizeText(e.ItemSubType):void 0,Status:e.Status?this.sanitizeText(e.Status):void 0}}static sanitizeText(e){return e?e.replace(/<[^>]*>/g,"").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/(javascript|data|vbscript):/gi,"blocked:").replace(/\\{2,}/g,"\\").slice(0,1e3):e}static sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+=/gi,"disabled-event=").replace(/allow=/gi,"data-blocked-allow=").replace(/(javascript|data|vbscript):/gi,"blocked:")}static sanitizeInput(e){return e.replace(/[\x00-\x1F\x7F]/g,"").replace(/['"\\]/g,"\\$&").replace(/\0/g,"").slice(0,500)}static checkRateLimit(e,t=10,i=6e4){const n=Date.now();return e.filter((e=>n-e.timestamp<i)).length<t}}const ue=c("PhilipsTTS"),ge=e=>e?{available:!0,enabled:"1"===e.setVoiceGuidance,rate:e.speechRate?Number(e.speechRate):1,volume:e.speechVolume?Number(e.speechVolume):1}:E,he=e=>e?{available:!0,enabled:"on"===e.setTextMagnification,scale:e.fontSizeBase?Number(e.fontSizeBase):1}:I;class pe{windowApi;constructor(e){this.windowApi=e||new L}messageToJSON(e){const t=JSON.stringify(e.info).replace(/'/g,"''");return JSON.stringify({...e,info:t})}getSettings(){const e=this.windowApi.get("getDeviceContent");if(!e)return D;const t=e("getVoiceGuidance",!1)??"",i=e("getTextMagnification",!1)??"";try{return{tts:ge(this.hexToObject(t)),tm:he(this.hexToObject(i))}}catch(n){return ue.warn("JSON Parsing Error:",n),D}}sendTTSMessage(e){const t=this.windowApi.get("omi_platform");if(t)try{t.sendPlatformMessage(this.messageToJSON(e))}catch(i){ue.warn("Failed to send platform message:",i)}}startSpeaking(e){const t=de.sanitizeSpeechCues(e).filter((e=>!(e=>"string"==typeof e?""===e.trim():""===e.Name.trim())(e)));if(0===t.length)return!1;const i=Object.fromEntries(t.map(((e,t)=>[`tts${t+1}`,e])));return this.sendTTSMessage({cmd:"startToSpeak",info:i}),!0}stopSpeaking(){return this.sendTTSMessage({cmd:"stopToSpeak",info:{param1:"false"}}),!0}stopSpeakingButKeepHighlightTask(){this.sendTTSMessage({cmd:"stopSpeakAndKeepInHighlightTask",info:{param1:"false"}})}hexToString(e){var t;return(null==(t=e.match(/.{2}/g))?void 0:t.map((e=>String.fromCharCode(parseInt(e,16)))).join(""))||""}hexToObject(e){if(!e)return null;try{let t=this.hexToString(e).replace(/\\/g,"").trim();t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));return JSON.parse(t)}catch(t){return null}}getTTSSettings(){return this.getSettings().tts}getTMSettings(){return this.getSettings().tm}createPlatformEventHandler(e,t){return i=>{try{const r=JSON.parse(i),s=decodeURIComponent(r.data),o=/cmd:\s*'(?<command>[^']+)'\s*,\s*info:\s*'(?<info>[^']+)'\s*;/,a=s.match(o);if(!a||!a.groups)return;if(a.groups.command!==e)return;try{let e=JSON.parse(a.groups.info);"string"==typeof e&&(e=JSON.parse(e)),t(e)}catch(n){ue.warn(`[tts] Could not parse info as JSON: ${n}`)}}catch(r){ue.warn(`[tts] Failed to parse platform event: ${r}`)}}}onTTSSettingsChange(e){var t;const i=this.windowApi.get("omi_platform");if(!i)return()=>{};const n=this.createPlatformEventHandler("VoiceGuidanceNotify",(t=>e(ge(t))));return null==(t=i.addPlatformEventListener)||t.call(i,n),()=>{var e;null==(e=i.removePlatformEventListener)||e.call(i,n)}}onTMSettingsChange(e){var t;const i=this.windowApi.get("omi_platform");if(!i)return()=>{};const n=this.createPlatformEventHandler("TextMagnificationNotify",(t=>e(he(t))));return null==(t=i.addPlatformEventListener)||t.call(i,n),()=>{var e;null==(e=i.removePlatformEventListener)||e.call(i,n)}}}const fe=c("AccessibilityService");class me{tts;reader=null;ttsSettings=E;tmSettings=I;constructor(){this.tts=new pe,this.tts.onTTSSettingsChange((e=>{this.ttsSettings=e})),this.tts.onTMSettingsChange((e=>{this.tmSettings=e}))}async startSpeaking(e){if("string"==typeof e&&(e=[e]),await this.isTTSEnabled())try{return this.tts.startSpeaking(e),!0}catch(t){return fe.error("Error starting speaking:",t),!1}return!0}async stopSpeaking(){return await this.isTTSEnabled()&&this.tts.stopSpeaking(),!0}async enableReader(e){try{if(!(await this.isTTSSupported()))return fe.warn("Cannot enable Reader: TTS not supported"),!1;if(!(await this.isTTSEnabled()))return fe.warn("Cannot enable Reader: TTS not enabled"),!1;this.reader=new le(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(fe.info("Reader enabled"),!0)}catch(t){return fe.error("Error enabling Reader:",t),!1}}async disableReader(){try{if(this.reader){const e=await this.reader.stop();return this.reader=null,e&&fe.info("Reader disabled"),e}return fe.debug("Reader was not active"),!0}catch(e){return fe.error("Error disabling Reader:",e),!1}}getReader(){if(!this.reader)throw new Error("Reader is not active");return this.reader}async isTTSSupported(){try{return(await this.getTTSSettings()).available}catch(e){return fe.error("Error checking TTS support:",e),!1}}async isTextMagnificationSupported(){try{return(await this.getTMSettings()).available}catch(e){return fe.error("Error checking magnification support:",e),!1}}onTTSSettingsChange(e){return this.tts.onTTSSettingsChange(e)}onTMSettingsChange(e){return this.tts.onTMSettingsChange(e)}async getTTSSettings(){return this.ttsSettings}async getTMSettings(){return this.tmSettings}async isTTSEnabled(){return(await this.getTTSSettings()).enabled}async isTMEnabled(){return(await this.getTMSettings()).enabled}}class ve{config;waitReady=new Promise((()=>{}));waitReadyResolver;constructor(e){this.config=e,this.waitReady=new Promise((e=>{this.waitReadyResolver=e}))}logError(...e){this.config.debug}}var Se,ye={exports:{}};var be,we,Te=(Se||(Se=1,be=ye,we=function(){var e=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function r(e,t){if(!n[e]){n[e]={};for(var i=0;i<e.length;i++)n[e][e.charAt(i)]=i}return n[e][t]}var s={compressToBase64:function(e){if(null==e)return"";var i=s._compress(e,6,(function(e){return t.charAt(e)}));switch(i.length%4){default:case 0:return i;case 1:return i+"===";case 2:return i+"==";case 3:return i+"="}},decompressFromBase64:function(e){return null==e?"":""==e?null:s._decompress(e.length,32,(function(i){return r(t,e.charAt(i))}))},compressToUTF16:function(t){return null==t?"":s._compress(t,15,(function(t){return e(t+32)}))+" "},decompressFromUTF16:function(e){return null==e?"":""==e?null:s._decompress(e.length,16384,(function(t){return e.charCodeAt(t)-32}))},compressToUint8Array:function(e){for(var t=s.compress(e),i=new Uint8Array(2*t.length),n=0,r=t.length;n<r;n++){var o=t.charCodeAt(n);i[2*n]=o>>>8,i[2*n+1]=o%256}return i},decompressFromUint8Array:function(t){if(null==t)return s.decompress(t);for(var i=new Array(t.length/2),n=0,r=i.length;n<r;n++)i[n]=256*t[2*n]+t[2*n+1];var o=[];return i.forEach((function(t){o.push(e(t))})),s.decompress(o.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":s._compress(e,6,(function(e){return i.charAt(e)}))},decompressFromEncodedURIComponent:function(e){return null==e?"":""==e?null:(e=e.replace(/ /g,"+"),s._decompress(e.length,32,(function(t){return r(i,e.charAt(t))})))},compress:function(t){return s._compress(t,16,(function(t){return e(t)}))},_compress:function(e,t,i){if(null==e)return"";var n,r,s,o={},a={},c="",l="",d="",u=2,g=3,h=2,p=[],f=0,m=0;for(s=0;s<e.length;s+=1)if(c=e.charAt(s),Object.prototype.hasOwnProperty.call(o,c)||(o[c]=g++,a[c]=!0),l=d+c,Object.prototype.hasOwnProperty.call(o,l))d=l;else{if(Object.prototype.hasOwnProperty.call(a,d)){if(d.charCodeAt(0)<256){for(n=0;n<h;n++)f<<=1,m==t-1?(m=0,p.push(i(f)),f=0):m++;for(r=d.charCodeAt(0),n=0;n<8;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}else{for(r=1,n=0;n<h;n++)f=f<<1|r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r=0;for(r=d.charCodeAt(0),n=0;n<16;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}0==--u&&(u=Math.pow(2,h),h++),delete a[d]}else for(r=o[d],n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;0==--u&&(u=Math.pow(2,h),h++),o[l]=g++,d=String(c)}if(""!==d){if(Object.prototype.hasOwnProperty.call(a,d)){if(d.charCodeAt(0)<256){for(n=0;n<h;n++)f<<=1,m==t-1?(m=0,p.push(i(f)),f=0):m++;for(r=d.charCodeAt(0),n=0;n<8;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}else{for(r=1,n=0;n<h;n++)f=f<<1|r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r=0;for(r=d.charCodeAt(0),n=0;n<16;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}0==--u&&(u=Math.pow(2,h),h++),delete a[d]}else for(r=o[d],n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;0==--u&&(u=Math.pow(2,h),h++)}for(r=2,n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;for(;;){if(f<<=1,m==t-1){p.push(i(f));break}m++}return p.join("")},decompress:function(e){return null==e?"":""==e?null:s._decompress(e.length,32768,(function(t){return e.charCodeAt(t)}))},_decompress:function(t,i,n){var r,s,o,a,c,l,d,u=[],g=4,h=4,p=3,f="",m=[],v={val:n(0),position:i,index:1};for(r=0;r<3;r+=1)u[r]=r;for(o=0,c=Math.pow(2,2),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;switch(o){case 0:for(o=0,c=Math.pow(2,8),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;d=e(o);break;case 1:for(o=0,c=Math.pow(2,16),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;d=e(o);break;case 2:return""}for(u[3]=d,s=d,m.push(d);;){if(v.index>t)return"";for(o=0,c=Math.pow(2,p),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;switch(d=o){case 0:for(o=0,c=Math.pow(2,8),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;u[h++]=e(o),d=h-1,g--;break;case 1:for(o=0,c=Math.pow(2,16),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;u[h++]=e(o),d=h-1,g--;break;case 2:return m.join("")}if(0==g&&(g=Math.pow(2,p),p++),u[d])f=u[d];else{if(d!==h)return null;f=s+s.charAt(0)}m.push(f),u[h++]=s+f.charAt(0),s=f,0==--g&&(g=Math.pow(2,p),p++)}}};return s}(),null!=be?be.exports=we:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",(function(){return we}))),ye.exports);const Ee="1.7.0",Ie=c("TVPlatform");class De extends ve{DEFAULT_DEVICE_INFO={};bridge;isInitialized=!1;CACHE_KEY="titansdk";CACHE_EXPIRY=6048e5;constructor(e,t){if(super(e),t)this.bridge=t;else{const e={gatewayUrl:this.config.gatewayUrl};this.bridge=new Y(e)}this.initializeBridgeSafely()}async initializeBridgeSafely(){try{await this.bridge.initialize()&&(this.isInitialized=!0)}catch(e){Ie.warn("Bridge initialization failed:",e)}this.waitReadyResolver(!0)}getFromLocalStorage(){try{if("undefined"==typeof localStorage)return null;if(!localStorage.getItem)return null;const e=localStorage.getItem(this.CACHE_KEY);if(!e)return null;const t=JSON.parse(e);return Date.now()-t.timestamp>this.CACHE_EXPIRY||t.lastVersion!==Ee?(localStorage.removeItem(this.CACHE_KEY),null):(Ie.debug("Device info loaded from localStorage cache"),t)}catch(e){return Ie.warn("Failed to load device info from localStorage:",e),null}}getFromURL(){try{const i=new URLSearchParams(window.location.search).get("titandata");if(!i)return null;let n=null;const r=new L;try{n=Te.decompressFromEncodedURIComponent(i),n&&Ie.debug("Device info loaded from URL parameter (lz-string)")}catch(e){Ie.debug("lz-string decompression failed, trying base64")}if(!n)try{const e=r.get("atob");if(!e)return Ie.warn("atob function not available"),null;n=e(decodeURIComponent(i)),Ie.debug("Device info loaded from URL parameter (base64)")}catch(t){return Ie.warn("Both lz-string and base64 decoding failed"),null}if(!n)return Ie.warn("Failed to decode URL parameter"),null;return JSON.parse(n)}catch(i){return Ie.warn("Failed to load device info from URL parameter:",i),null}}saveToLocalStorage(e){try{if("undefined"==typeof localStorage)return;if(!(e&&e.deviceId&&e.brand&&e.model))return void Ie.warn("Skipping cache save - invalid or empty device info");const t={data:e,timestamp:Date.now(),lastVersion:Ee};localStorage.setItem(this.CACHE_KEY,JSON.stringify(t)),Ie.debug("Device info saved to localStorage cache")}catch(t){Ie.warn("Failed to save device info to localStorage:",t)}}async getBaseDeviceInfo(){const e=this.getFromURL();if(e)return this.saveToLocalStorage(e),this.waitReadyResolver(!0),{deviceInfo:e,tts:E,tm:I};if(!1!==this.config.useCache){const e=this.getFromLocalStorage();if(e)return this.waitReadyResolver(!0),{deviceInfo:e.data,tts:E,tm:I}}else this.config.debug&&Ie.debug("Debug mode: skipping cache, fetching fresh data from iframe");try{return await this.waitReady,await this.bridge.executeWithFallback((async()=>{const e=await this.bridge.getDeviceInfo();if(!e)throw new Error("Failed to get device info");return e.deviceInfo&&this.saveToLocalStorage(e.deviceInfo),e}),(async()=>{Ie.warn("Bridge unavailable, returning fallback device info");return{deviceInfo:null,tts:E,tm:I}}))}catch(t){return Ie.warn("Failed to get device info from bridge:",t),{deviceInfo:null,tts:E,tm:I}}}isTV(){return"undefined"!=typeof window&&(navigator.userAgent.includes("TV")||navigator.userAgent.includes("SmartTV")||navigator.userAgent.includes("SMART-TV")||window.location.href.includes("file://"))}}const Ce=new L,Re=new L;function Ae(){const e=document.createElement("video");return e.canPlayType&&"function"==typeof e.canPlayType?{supportAppleHLS:""!==e.canPlayType("application/vnd.apple.mpegURL")||""!==e.canPlayType("audio/mpegurl"),supportMSSmoothStreaming:""!==e.canPlayType("application/vnd.ms-sstr+xml"),supportMSSInitiator:""!==e.canPlayType("application/vnd.ms-playready.initiator+xml"),supportMPEG_DASH:""!==e.canPlayType("application/dash+xml")||"unknown"}:{supportAppleHLS:!1,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:"unknown"}}function Me(){try{if(void 0!==Ce.get("oipfObjectFactory"))return{supportOIPF:!0};const e=document.createElement("object");e.type="application/oipfdrmagent";return"function"==typeof e.sendDRMMessage?{supportOIPF:!0}:{supportOIPF:!1}}catch(e){return{supportOIPF:!1}}}function Pe(){try{const e=(new L).get("navigator"),t=void 0!==e&&"function"==typeof e.requestMediaKeySystemAccess,i=Re.has("MSMediaKeys");return{supportWebSocket:Re.has("WebSocket"),supportEME:t||i,hasStorage:Re.has("localStorage")&&Re.has("sessionStorage")}}catch(e){return{supportWebSocket:!1,supportEME:!1,hasStorage:!1}}}const ke=new L;function Oe(){let e="";e=function(){try{const e=document.createElement("object");e.type="application/oipfdrmagent";return"function"==typeof e.sendDRMMessage?"OIPF":""}catch(e){return""}}();try{const t=ke.has("MediaKeys"),i=ke.has("WebKitMediaKeys"),n=ke.has("MSMediaKeys");return e=t||i||n?"EME":e,{drmMethod:e}}catch(t){return{drmMethod:""}}}function _e(){try{const e=ke.has("MediaKeys"),t=ke.has("WebKitMediaKeys"),i=ke.has("MSMediaKeys");return{supportEME:e||t||i}}catch(e){return{supportEME:!1}}}const Ne=c("PhilipsCapabilities");async function Le(e){const t={os:"Linux",browserEngine:"Blink",supportPlayready:!0===await function(){const e=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}];return new Promise((t=>{try{navigator.requestMediaKeySystemAccess("com.microsoft.playready",e).then((()=>{t(!0)})).catch((()=>{t(!1)}))}catch(i){t(!1)}}))}()||"unknown",supportWidevineModular:!0===await function(){const e=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}];return new Promise((t=>{try{navigator.requestMediaKeySystemAccess("com.widevine.alpha",e).then((()=>{t(!0)})).catch((()=>{t(!1)}))}catch(i){t(!1)}}))}()||"unknown"},i=function(){try{const e={support3d:!1,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportUHD:!1,supportFHD:!0,supportHDR_HDR10:!1,supportHDR_DV:!1,supportHDR:"unknown",supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportAdobeHDS:!1,supportWidevineClassic:!1,supportDolbyAtmos:"unknown"},t=xe.get("ols3DSupport");t&&t()&&(e.support3d=!0);const i=xe.get("olsAtmosSupport");i&&i()&&(e.supportDolbyAtmos=!0),e.supportKeyNumeric=!0,e.supportKeyColor=!0,e.supportMultiscreen=!1,e.supportMultiAudio=!0,e.supportTTMLInband=!0,e.supportTTMLOutofband=!0,e.supportFHD=!0;const n=xe.get("olsUHD");n&&n()&&(e.supportUHD=n()),e.supportHDR_HDR10=!0;const r=xe.get("olsDVSupport");return r&&r()&&(e.supportHDR_DV=!0),e.supportHDR=e.supportHDR_HDR10||e.supportHDR_DV||!1,e}catch(e){return Ne.error("Error detecting SmartTV API capabilities:",e),{support3d:!1,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportUHD:!1,supportFHD:!0,supportHDR_HDR10:!1,supportHDR_DV:!1,supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportAdobeHDS:!1,supportHDR:"unknown",supportWidevineClassic:!1,supportDolbyAtmos:"unknown"}}}();return{...t,...i,...Pe(),...Ae(),...Oe(),..._e(),...Me(),supportFairplay:!1,supportPrimetime:!1,supportClearKey:!0}}const xe=new L;const He=c("PhilipsCompat");class Ue extends De{deviceInfo=null;deviceInfoPromise=null;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"TPV",brand:"Philips"},Product:{platform:"TitanOS",year:"2025",deviceID:"philips-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:H(),language:"en"}};constructor(e,t){super(e,t)}async isSupported(){return this.isTV()}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["philips","saphi","nettv","tpvision"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{const e=await this.getBaseDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product},i=this.formatBridgeResponse(e,t),n=(i.Product.platform,await Le());return{...i,Capability:n}}catch(e){throw He.error("Error getting device info:",e),e}}formatBridgeResponse(e,t){if(!e.deviceInfo)return t;let i=e.deviceInfo.platformName;e.deviceInfo.profileId&&(i=(e.deviceInfo.profileId.split("_")[1]||i).replace(/\d+$/,""));return t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country,t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=i,t.Product.language=e.deviceInfo.language,t.Product.mac=e.deviceInfo.mac,t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.year=e.deviceInfo.year||"",t.Product.firmwareComponentID=i||"",t}getPriority(){return 100}getId(){return"philips"}}const Fe=c("PhilipsDeviceInfoService");class Ke{platform;info;bridge;constructor(e,t){this.platform=new Ue(e,t),this.bridge=t,this.info=null}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw Fe.error("Failed to get device info:",e),e}}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}const Be=c("PhilipsAppControlService");class ze{bridge;constructor(e){this.bridge=e}async launch(e,t){return await this.bridge.executeWithFallback((()=>this.bridge.launchApp({appId:e,deepLink:t})),(async()=>(Be.warn("Function unavailable, app launch failed gracefully",{appId:e,deepLink:t}),!1)))}}const Ve=c("ChromeTTS");class $e{voices=[];currentVoice=null;settings={available:!0,enabled:!0,rate:1,volume:1};speechSynthesis;constructor(){const e=new L;this.speechSynthesis=e.get("speechSynthesis"),this.speechSynthesis&&(this.initVoices(),"onvoiceschanged"in this.speechSynthesis&&(this.speechSynthesis.onvoiceschanged=()=>{this.initVoices()}))}initVoices(){var e,t,i,n,r,s;if(!("speechSynthesis"in window))return;const o=null==(e=this.speechSynthesis)?void 0:e.getVoices();this.voices=null==o?void 0:o.map((e=>({voiceName:e.name,lang:e.lang,gender:e.name.toLowerCase().includes("female")?"female":"male",remote:!1===e.localService}))),this.currentVoice=(null==(t=this.voices)?void 0:t.find((e=>"en-GB"===e.lang)))||(null==(i=this.voices)?void 0:i.find((e=>e.lang.startsWith("en-"))))||(null==(n=this.voices)?void 0:n[0]),Ve.info(`Initialized with ${null==(r=this.voices)?void 0:r.length} voices, using ${null==(s=this.currentVoice)?void 0:s.voiceName}`)}getTTSSettings(){return this.settings}getTMSettings(){return{available:!0,enabled:!1,scale:1}}getSettings(){return{tts:this.getTTSSettings(),tm:this.getTMSettings()}}startSpeaking(e){return Ve.info("Starting speaking:",e),!(!("speechSynthesis"in window)||!e||0===e.length)&&(e.forEach(((e,t)=>{var i,n,r,s;if(!e)return;const o=new SpeechSynthesisUtterance(e);if(o.rate=this.settings.rate??1,o.volume=this.settings.volume??1,o.lang=(null==(i=this.currentVoice)?void 0:i.lang)??"en-GB",this.currentVoice){const e=null==(n=this.speechSynthesis)?void 0:n.getVoices().find((e=>e.name===this.currentVoice.voiceName));e&&(o.voice=e)}0===t&&(null==(r=this.speechSynthesis)||r.cancel()),null==(s=this.speechSynthesis)||s.speak(o)})),!0)}stopSpeaking(){var e;return"speechSynthesis"in window&&(null==(e=this.speechSynthesis)||e.cancel(),!0)}stopSpeakingButKeepHighlightTask(){this.stopSpeaking()}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}sendTTSMessage(e){}}const Ge=c("VestelTTS"),je=e=>({available:!0,enabled:e.enabled,rate:e.rate,pitch:e.pitch,volume:e.level});class We extends $e{vestelSettings={available:!0,enabled:!1,rate:1,volume:1};windowApi=new L;ttsCallbacks=new Set;tmCallbacks=new Set;settingsInitialized=!1;constructor(){super(),this.initializeSettings()}async initializeSettings(){var e,t;const i=this.windowApi.get("TTSHelper");if(!i)return void Ge.warn("TTSHelper not available during initialization");const n={onSuccess:e=>{this.vestelSettings=je(e),this.settingsInitialized=!0},onError:e=>{Ge.error("Error initializing TTS settings:",e),this.settingsInitialized=!0}},r={onSuccess:e=>{this.vestelSettings=je(e)},onError:e=>{Ge.error("Error getting TTS info:",e)}};null==(e=i.getTextToSpeechSettings)||e.call(i,n,!1),null==(t=i.getTTSInfo)||t.call(i,r)}getTTSSettings(){var e;if(!this.settingsInitialized){const t=this.windowApi.get("TTSHelper");if(t){const i={onSuccess:e=>{Ge.info("Current TTS settings:",e,e.toString()),this.vestelSettings=je(e)},onError:e=>{Ge.error("Error getting current TTS settings:",e)}};null==(e=t.getTextToSpeechSettings)||e.call(t,i,!1)}}return this.vestelSettings}getTMSettings(){return{available:this.getTTSSettings().available,enabled:!1,scale:1}}getSettings(){return{tts:this.getTTSSettings(),tm:this.getTMSettings()}}stopSpeakingButKeepHighlightTask(){this.stopSpeaking()}onTTSSettingsChange(e){var t;const i=this.windowApi.get("TTSHelper");if(!i)return Ge.warn("TTSHelper not available"),()=>{};const n={onSuccess:t=>{Ge.info("TTS settings changed:",t,t.toString()),e(je(t)),this.settingsInitialized=!0},onError:e=>{Ge.error("Error getting TTS settings:",e)}};return this.ttsCallbacks.add(n),null==(t=i.getTextToSpeechSettings)||t.call(i,n,!0),()=>{var e;i&&this.ttsCallbacks.has(n)&&(null==(e=i.unsubscribe)||e.call(i,n),this.ttsCallbacks.delete(n))}}onTMSettingsChange(e){this.tmCallbacks.add(e);const t=this.onTTSSettingsChange((t=>{const i={available:t.available,enabled:!1,scale:1};e(i)})),i=this.getTMSettings();return e(i),()=>{this.tmCallbacks.delete(e),t()}}destroy(){const e=this.windowApi.get("TTSHelper");e&&this.ttsCallbacks.forEach((t=>{var i;null==(i=e.unsubscribe)||i.call(e,t)})),this.ttsCallbacks.clear(),this.tmCallbacks.clear()}}const qe=c("AccessibilityService"),Qe=e=>{const{available:t,...i}=e;return i};class Je{tts;reader=null;constructor(){this.tts=new We}async startSpeaking(e){if("string"==typeof e&&(e=[e]),await this.isTTSEnabled())try{return this.tts.startSpeaking(e),!0}catch(t){return qe.error("Error starting speaking:",t),!1}return!1}async stopSpeaking(){return await this.isTTSEnabled()&&this.tts.stopSpeaking(),!0}async enableReader(e){try{if(!(await this.isTTSSupported()))return qe.warn("Cannot enable Reader: TTS not supported"),!1;if(!(await this.isTTSEnabled()))return qe.warn("Cannot enable Reader: TTS not enabled"),!1;this.reader=new le(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(qe.info("Reader enabled"),!0)}catch(t){return qe.error("Error enabling Reader:",t),!1}}async disableReader(){try{if(this.reader){const e=await this.reader.stop();return this.reader=null,e&&qe.info("Reader disabled"),e}return qe.debug("Reader was not active"),!0}catch(e){return qe.error("Error disabling Reader:",e),!1}}getReader(){if(!this.reader)throw new Error("Reader is not active");return this.reader}async isTTSSupported(){try{return(await this.getTTSSettings()).available}catch(e){return qe.error("Error checking TTS support:",e),!1}}async isTextMagnificationSupported(){try{return(await this.getTMSettings()).available}catch(e){return qe.error("Error checking magnification support:",e),!1}}onTTSSettingsChange(e){return this.tts.onTTSSettingsChange(e)}onTMSettingsChange(e){return this.tts.onTMSettingsChange(e)}async getTTSSettings(){return this.tts.getTTSSettings()}async getTMSettings(){return this.tts.getTMSettings()}async isTTSEnabled(){return(await this.getTTSSettings()).enabled}async isTMEnabled(){return(await this.getTMSettings()).enabled}}class Ye{subscribe(e,t){const i=l(e,t);return()=>{d(i)}}getHistory(){return u()}clear(){g()}}const Ze=c("PhilipsSDK");class Xe{bridge;accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new me,this.bridge=new ee({gatewayUrl:null==e?void 0:e.gatewayUrl,debug:null==e?void 0:e.debug}),this.deviceInfoService=new Ke(e,this.bridge),this.appControlService=new ze(this.bridge)}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>Qe(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>Qe(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(Qe(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(Qe(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new Ye}get dev(){return{isBridgeConnected:async()=>{try{return this.bridge.isConnected()}catch(e){return!1}}}}async init(){try{return await this.deviceInfo.getDeviceInfo(),!0}catch(e){throw Ze.error("TitanSDK initialization failed:",e),e}}}function et(e){const t=function(){var e;try{const t=document.createElement("object");t.setAttribute("id","sysinfo"),t.setAttribute("type","systeminfoobject"),document.body.appendChild(t);const i=t;return{support3d:Boolean(i.has3D),supportUHD:"3840x2160"===(null==(e=i.panelinfo)?void 0:e.toLowerCase()),supportFHD:!0}}catch(t){return{support3d:!1,supportUHD:!1,supportFHD:!0}}}(),i=Pe(),n=Ae(),r=Oe(),s=_e(),o=Me(),a={os:"Linux",browserEngine:"Blink",hasStorage:!0,support3d:!1,supportUHD:!0,supportFHD:!0,supportHDR:!0,supportHDR_HDR10:!0,supportHDR_DV:!0,supportWebSocket:!0,supportPlayready:!0,supportWidevineModular:!0,supportAppleHLS:!0,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:!0,drmMethod:"widevine",supportOIPF:!1,supportEME:!0,supportKeyNumeric:!0,supportKeyColor:!0,supportFairplay:!1,supportAdobeHDS:!1,supportPrimetime:!1,supportClearKey:!0,supportWidevineClassic:!0,supportDolbyAtmos:!0,supportMultiscreen:!0,supportMultiAudio:!0,supportTTMLInband:!0,supportTTMLOutofband:!0};return"MB191"===e&&(a.supportHDR_DV=!1,a.supportHDR_HDR10=!1,a.supportDolbyAtmos=!1),{...a,...t,...i,...n,...r,...s,...o}}const tt=c("VestelCompat");class it extends De{deviceInfo=null;deviceInfoPromise=null;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"Vestel",brand:"JVC"},Product:{platform:"TitanOS",year:"2025",deviceID:"vestel-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:H(),language:"en"}};constructor(e,t){super(e,t)}async isSupported(){return this.isTV()}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["vestel"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{if(await this.waitReady){const e=await this.getBaseDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product},i=this.formatBridgeResponse(e,t),n=et(i.Product.platform);return{...i,Capability:n}}const e=et();return{Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product,Capability:e}}catch(e){throw tt.error("Error getting device info:",e),e}}formatBridgeResponse(e,t){return e.deviceInfo?(t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country.toUpperCase(),t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=e.deviceInfo.model,t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.mac=e.deviceInfo.mac,t.Product.year=e.deviceInfo.year||"",t):t}getPriority(){return 90}getId(){return"vestel"}}const nt=c("VestelDeviceInfoService");class rt{platform;info;bridge;constructor(e,t){this.platform=new it(e,t),this.bridge=t,this.info=null}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw nt.error("Failed to get device info:",e),e}}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}const st=c("VestelAppControlService");class ot{bridge;constructor(e){this.bridge=e}async launch(e,t){return await this.bridge.executeWithFallback((()=>this.bridge.launchApp({appId:e,deepLink:t})),(async()=>(st.warn("Function unavailable, app launch failed gracefully",{appId:e,deepLink:t}),!1)))}}const at=c("VestelSDK");class ct{bridge;accessibilityService;deviceInfoService;appControlService;constructor(e){this.bridge=new Z({gatewayUrl:null==e?void 0:e.gatewayUrl,debug:null==e?void 0:e.debug}),this.accessibilityService=new Je,this.deviceInfoService=new rt(e,this.bridge),this.appControlService=new ot(this.bridge)}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),getTTSSettings:async()=>Qe(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>Qe(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(Qe(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(Qe(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new Ye}get dev(){return{isBridgeConnected:async()=>{try{return this.bridge.isConnected()}catch(e){return!1}}}}async init(){try{return await this.deviceInfo.getDeviceInfo(),!0}catch(e){throw at.error("TitanSDK initialization failed:",e),e}}}const lt="titanSDK_tts_settings",dt="titanSDK_tm_settings",ut=c("BrowserAccessibilityService"),gt=e=>{const{available:t,...i}=e;return i};class ht{reader=null;chromeTTS;windowMock;mockStorage;ttsSettings;tmSettings;constructor(e,t,i=!1){this.windowMock=e,this.mockStorage=t,this.chromeTTS=new $e,this.ttsSettings=this.loadTTSSettings(),this.tmSettings=this.loadTMSettings()}loadTTSSettings(){try{const e=localStorage.getItem(lt);if(e)return{...this.getDefaultTTSSettings(),...JSON.parse(e)}}catch(e){}return this.getDefaultTTSSettings()}loadTMSettings(){try{const e=localStorage.getItem(dt);if(e)return{...this.getDefaultTMSettings(),...JSON.parse(e)}}catch(e){}return this.getDefaultTMSettings()}getDefaultTTSSettings(){return{available:!0,enabled:!0,rate:1,volume:1}}getDefaultTMSettings(){return{available:!0,enabled:!1,scale:1}}saveTTSSettings(){try{localStorage.setItem(lt,JSON.stringify(this.ttsSettings))}catch(e){}}saveTMSettings(){try{localStorage.setItem(dt,JSON.stringify(this.tmSettings))}catch(e){}}async startSpeaking(e){try{if(!this.ttsSettings.enabled)return ut.info("TTS is disabled in settings"),!1;const t=Array.isArray(e)?e.join(" "):e,i=this.chromeTTS.startSpeaking([t]);return i&&ut.info("🔊 Speaking:",t),i}catch(t){return ut.error("Error starting speech:",t),!1}}async stopSpeaking(){try{const e=this.chromeTTS.stopSpeaking();return e&&ut.info("🔇 Speech stopped"),e}catch(e){return ut.error("Error stopping speech:",e),!1}}async enableReader(e){try{if(!(await this.isTTSSupported()))return ut.warn("Cannot enable Reader: TTS not supported"),!1;this.reader=new le(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(ut.info("Reader enabled"),!0)}catch(t){return ut.error("Error enabling Reader:",t),!1}}async disableReader(){try{return!!this.reader&&(await this.reader.stop(),this.reader=null,ut.info("Reader disabled"),!0)}catch(e){return ut.error("Error disabling Reader:",e),!1}}getReader(){return this.reader}async isTTSSupported(){var e,t;return void 0!==(null==(t=null==(e=this.mockStorage)?void 0:e.features)?void 0:t.tts)?this.mockStorage.features.tts:"undefined"!=typeof window&&"speechSynthesis"in window}async isTextMagnificationSupported(){var e,t;return void 0===(null==(t=null==(e=this.mockStorage)?void 0:e.features)?void 0:t.magnification)||this.mockStorage.features.magnification}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}async getTTSSettings(){return{...this.ttsSettings}}async getTMSettings(){return{...this.tmSettings}}async isTTSEnabled(){const e=await this.getTTSSettings();return e.available&&e.enabled}async isTMEnabled(){const e=await this.getTMSettings();return e.available&&e.enabled}updateTTSSettings(e){this.ttsSettings={...this.ttsSettings,...e},this.saveTTSSettings(),ut.info("TTS settings updated:",this.ttsSettings)}updateTMSettings(e){this.tmSettings={...this.tmSettings,...e},this.saveTMSettings(),ut.info("TM settings updated:",this.tmSettings)}}const pt=c("BrowserPlatform");class ft extends ve{constructor(e){super(e),this.waitReady=new Promise((e=>{this.waitReadyResolver=e})),this.waitReadyResolver(!0)}async isSupported(){return!0}async canHandle(){return!0}async getDeviceInfo(){return pt.debug("Getting default device info for browser"),this.getDefaultDeviceInfo()}getDefaultDeviceInfo(){return{Channel:{appStore:"browser",vendor:"browser",brand:"browser"},Product:{platform:"browser",year:(new Date).getFullYear().toString(),deviceID:"browser-"+Math.random().toString(36).substring(2,10),firmwareVersion:"unknown",firmwareComponentID:"unknown",mac:"unknown"},Capability:{os:(null==navigator?void 0:navigator.platform)||"unknown",browserEngine:this.detectBrowserEngine(),hasStorage:this.hasLocalStorage(),support3d:!1,supportUHD:!1,supportHDR:!1,supportWebSocket:"WebSocket"in window,supportPlayready:!1,supportWidevineModular:!1,supportAppleHLS:!1,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:!1,drmMethod:"",supportOIPF:!1,supportEME:"mediaKeys"in Document.prototype,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportFHD:!1,supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportFairplay:!1,supportAdobeHDS:!1,supportPrimetime:!1,supportClearKey:!1,supportWidevineClassic:!1,supportDolbyAtmos:!1,supportHDR_HDR10:!1,supportHDR_DV:!1}}}detectBrowserEngine(){const e=navigator.userAgent;return e.includes("Chrome")?"Blink":e.includes("Firefox")?"Gecko":e.includes("Safari")?"WebKit":e.includes("Edge")?"EdgeHTML":e.includes("Trident")?"Trident":"unknown"}hasLocalStorage(){try{return"localStorage"in window&&null!==window.localStorage}catch(e){return!1}}getPriority(){return 10}getId(){return"browser"}}const mt=c("BrowserDeviceInfoService");class vt{platform;info;options;constructor(e,t,i){this.options=e,this.info=null;const n={debug:null==e?void 0:e.debug,timeout:(null==e?void 0:e.legacyDeviceInfoTimeout)||5e3,gatewayUrl:null==e?void 0:e.gatewayUrl,useCache:!0};this.platform=new ft(n)}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw mt.error("Error getting device info:",e),e}}async getCapabilities(){try{return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}catch(e){throw mt.error("Error getting device capabilities:",e),e}}}const St=c("BrowserAppControlService");class yt{windowMock;constructor(e){this.windowMock=e}async launch(e,t){St.debug(`Launching app: ${e} with deepLink: ${t||"none"}`);const i=this.windowMock||window;if(!i||"function"!=typeof i.open)throw new s("Cannot open new window for app launch (window.open not available)",r.NOT_SUPPORTED,{operation:"launch",appId:e,deepLink:t,platform:"browser"});try{return i.open(t||e,"_blank"),St.info(`Opened new tab for app: ${e}`),!0}catch(n){throw St.error("Error opening new window for app launch:",n),new s(`Failed to launch app: ${e}`,r.COMMUNICATION_ERROR,{operation:"launch",appId:e,deepLink:t,platform:"browser",originalError:n})}}}const bt=c("BrowserSDK");class wt{accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new ht(null==e?void 0:e.windowMock,null==e?void 0:e.mockStorage,(null==e?void 0:e.dev)||!1),this.deviceInfoService=new vt(e,null==e?void 0:e.windowMock,null==e?void 0:e.mockStorage),this.appControlService=new yt(null==e?void 0:e.windowMock),"undefined"!=typeof window&&Object.defineProperty(window,"titanSDK",{value:this,writable:!0,configurable:!0}),(null==e?void 0:e.debug)&&bt.debug("BrowserSDK constructor finished")}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>gt(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>gt(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(gt(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(gt(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new Ye}get dev(){return{updateTTSSettings:e=>{this.accessibilityService.updateTTSSettings(e)},updateTMSettings:e=>{this.accessibilityService.updateTMSettings(e)}}}async init(){try{return bt.debug("BrowserSDK initialization started"),bt.info("BrowserSDK initialized successfully"),!0}catch(e){throw bt.error("BrowserSDK initialization failed:",e),e}}}const Tt=c("AccessibilityService"),Et=e=>{const{available:t,...i}=e;return i};class It{reader=null;async startSpeaking(e){return!1}async stopSpeaking(){return!1}async enableReader(e){return Tt.warn("Cannot enable Reader: TTS not supported"),!1}async disableReader(){return!1}getReader(){return null}async isTTSSupported(){return!1}async isTextMagnificationSupported(){return!1}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}async getTTSSettings(){return E}async getTMSettings(){return I}async isTTSEnabled(){return!1}async isTMEnabled(){return!1}}const Dt=c("PhilipsOldPlatform");class Ct extends ve{deviceInfo=null;deviceInfoPromise=null;timeout=7e3;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"TPV",brand:"Philips"},Product:{platform:"TitanOS",year:"2023",deviceID:"philips-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:H(),language:"en"}};constructor(e){super(e),this.waitReady=new Promise((e=>{this.waitReadyResolver=e})),this.waitReadyResolver(!0)}async isSupported(){return"undefined"!=typeof window&&(navigator.userAgent.includes("TV")||navigator.userAgent.includes("SmartTV")||navigator.userAgent.includes("SMART-TV")||window.location.href.includes("file://"))}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["philips","saphi","nettv","tpvision"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{if(await this.waitReady){const e=await this.fetchDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product};if(!e){const e=await Le();return{...t,Capability:e}}const i=this.formatBridgeResponse({deviceInfo:e,tts:E,tm:I},t),n=(i.Product.platform,await Le());return{...i,Capability:n}}const e=await Le();return{Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product,Capability:e}}catch(e){throw Dt.warn("Error getting device info:",e),e}}async fetchDeviceInfo(){var e;try{const t="app.titanos.tv",i=await Promise.race([x(0,t,"zeasn"),new Promise((e=>{setTimeout((()=>{Dt.warn("Zeasn backend device info request timed out"),e(null)}),this.timeout)}))]);if(!i||!(null==(e=i.datas)?void 0:e.cookies))return null;const n=i.datas.cookies.profileid;return{profileId:n,deviceId:decodeURIComponent(i.datas.cookies.deviceid||""),model:i.datas.cookies.deviceYear||"",year:i.datas.cookies.deviceYear||"",firmwareVersion:i.datas.cookies.ufversion||"",country:i.datas.cookies.country||"",language:z("en"),brand:N.PHILIPS,platformName:N.PHILIPS,mac:decodeURIComponent(i.datas.cookies.mac||""),ifa:"",ifaType:""}}catch(t){return Dt.warn("Error fetching device info from backend",t),null}}formatBridgeResponse(e,t){let i="TitanOS",n="unknown";if(!e.deviceInfo)return t;if(e.deviceInfo.profileId&&(i=e.deviceInfo.platformName,e.deviceInfo.profileId)){var r=e.deviceInfo.profileId.split("_");i=(r[1]||i).replace(/\d+$/,""),n=r[1]?decodeURIComponent(r[1]):"unknown"}return t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country,t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=i,t.Product.language=e.deviceInfo.language,t.Product.mac=e.deviceInfo.mac,t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.year=e.deviceInfo.year||"",t.Product.firmwareComponentID=n,t}getPriority(){return 100}getId(){return"philips"}}class Rt{platform;info;constructor(e){this.platform=new Ct(e),this.info=null}async getDeviceInfo(){const e=await this.platform.getDeviceInfo();return this.info=e,this.info}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}class At{async launch(e,t){return!1}}class Mt{accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new It,this.deviceInfoService=new Rt(e),this.appControlService=new At}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>Et(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>Et(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>()=>{},onTMSettingsChange:e=>()=>{}};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new Ye}async init(){return!0}}const Pt=c("RollbarClient"),kt=["chrome://userjs/","chrome-extension://","moz-extension://","getJWTString","getjwtstring","user.js","userscript","tampermonkey","greasemonkey","can't find variable getjwtstring","referenceerror: can't find variable: getjwtstring","unexpected end of json input","jsonparse"];const Ot=new class{rollbar=null;config=null;windowWrapper=new L;initialize(e){if(e.enabled&&e.accessToken)try{this.config=e,this.rollbar=new t({accessToken:e.accessToken,environment:e.environment||"development",captureUncaught:!0,captureUnhandledRejections:!0,verbose:!1,reportLevel:"error",captureIp:!1,captureUsername:!1,captureEmail:!1,maxItems:100,itemsPerMinute:60,captureLambdaTimeouts:!1,endpoint:"https://sdk.titanos.tv/logs/",autoInstrument:{network:!1,log:!1,dom:!1,navigation:!1,connectivity:!1},payload:{client:{javascript:{code_version:"unknown",source_map_enabled:!0}}},transform:e=>{e.context&&(e.context=`hephaestus-${e.context}`)},checkIgnore:(e,t,i)=>{const n=t[0],r="string"==typeof n?n:null==n?void 0:n.message,s="object"==typeof n&&n?n.stack:"",o=String(n).toLowerCase();return kt.some((e=>(null==r?void 0:r.toLowerCase().includes(e.toLowerCase()))||(null==s?void 0:s.toLowerCase().includes(e.toLowerCase()))||o.includes(e.toLowerCase())))}}),this.setupGlobalErrorHandlers(),Pt.info("Rollbar initialized successfully",{environment:e.environment})}catch(i){Pt.error("Failed to initialize Rollbar",{error:i,config:e})}else Pt.warn("Rollbar not initialized - disabled or missing access token")}shouldIgnoreError(e){if(!e)return!0;const t="string"==typeof e?e:e.message||"",i="object"==typeof e&&e.stack||"",n=String(e).toLowerCase();return kt.some((e=>(null==t?void 0:t.toLowerCase().includes(e.toLowerCase()))||(null==i?void 0:i.toLowerCase().includes(e.toLowerCase()))||n.includes(e.toLowerCase())))}async reportError(e,t,i="error"){var n;return this.rollbar&&(null==(n=this.config)?void 0:n.enabled)&&e?this.shouldIgnoreError(e)?Promise.resolve(null):new Promise((n=>{this.getDeviceContext().then((r=>{var s,o,a;try{const c=u().filter((e=>!e.module.includes("RollbarClient")&&!e.message.includes("Rollbar")&&"debug"!==e.level)).slice(-20),l={logs:c.map((e=>`[${e.timestamp}] ${e.module}: ${e.message}${e.args&&e.args.length>0?"\n Args: "+JSON.stringify(e.args):""}`)).join("\n"),component:(null==t?void 0:t.component)||"SDK",operation:null==t?void 0:t.operation,requestId:null==t?void 0:t.requestId,timestamp:Date.now(),url:"undefined"!=typeof window?null==(s=window.location)?void 0:s.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",sessionId:this.generateSessionId(),errorStack:"object"==typeof e?e.stack:void 0,version:"undefined"!=typeof window&&(null==(o=this.windowWrapper.get("TitanSDK"))?void 0:o.VERSION)||"unknown",...r,...t},d="critical"===i?"critical":"error",g="critical"===i?"critical_error_with_logs":"error_with_logs";null==(a=this.rollbar)||a[d](e,{custom:{type:g,context:l,logCount:c.length}},((t,r)=>{var s;if(t)this.shouldIgnoreError(t)||Pt.error(`Failed to send ${i} error to Rollbar`,{error:t,originalError:e}),n(null);else{const t=r&&(r.uuid||(null==(s=r.result)?void 0:s.uuid))||null;Pt.info(("critical"===i?"Critical error":"Error")+" sent to Rollbar",{message:"string"==typeof e?e:(null==e?void 0:e.message)||"Unknown error",component:l.component,rollbarId:t,logCount:c.length}),n(t)}}))}catch(c){Pt.error(`Failed to send ${i} error to Rollbar`,{error:c,originalError:e}),n(null)}})).catch((e=>{Pt.error(`Failed to get device context for ${i} error`,{error:e}),n(null)}))})):Promise.resolve(null)}collectSDKUsage(e,t,i,n){var r,s;if(this.rollbar&&(null==(r=this.config)?void 0:r.enabled))try{const r=i?"info":"warning";this.rollbar[r](`SDK function execution: ${e}`,{custom:{type:"sdk_function_execution",functionName:e,success:i,component:n,result:i?t:void 0,error:i?void 0:t,timestamp:Date.now(),url:"undefined"!=typeof window?null==(s=window.location)?void 0:s.href:void 0}}),Pt.info("SDK function execution logged",{functionName:e,success:i,component:n})}catch(o){Pt.error("Failed to log SDK function execution",{error:o,functionName:e,component:n})}}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async getDeviceContext(){var e,t,i;try{if(null==window?void 0:window.TitanSDK)try{const n=await(null==(i=null==(t=null==(e=null==window?void 0:window.TitanSDK)?void 0:e.deviceInfo)?void 0:t.getDeviceInfo)?void 0:i.call(t));return{deviceInfo:n?JSON.stringify(n):"unavailable"}}catch(n){}return{deviceInfo:`OS: ${(null==navigator?void 0:navigator.platform)||"unknown"}, Browser: ${this.detectBrowserEngine()}, Storage: ${"localStorage"in(window||{})}`}}catch(r){return{}}}detectBrowserEngine(){if("undefined"==typeof navigator)return"unknown";const e=navigator.userAgent;return e.includes("Chrome")?"Blink":e.includes("Firefox")?"Gecko":e.includes("Safari")&&!e.includes("Chrome")?"WebKit":e.includes("Edge")?"EdgeHTML":"unknown"}setupGlobalErrorHandlers(){if("undefined"==typeof window)return;const e=console.error;console.error=(...t)=>{e.apply(console,t);const i=t.find((e=>e instanceof Error||"string"==typeof e&&e.includes("Error")));i&&!this.shouldIgnoreError(i)&&this.reportError(i,{component:"SDK",operation:"console.error"})},"undefined"!=typeof window&&(window.addEventListener("error",(e=>{this.shouldIgnoreError(e.error)||this.reportError(e.error||e.message,{component:"SDK",operation:"window.onerror"})})),window.addEventListener("unhandledrejection",(e=>{this.shouldIgnoreError(e.reason)||this.reportError(e.reason,{component:"SDK",operation:"unhandledrejection"})})))}isInitialized(){var e;return null!==this.rollbar&&!0===(null==(e=this.config)?void 0:e.enabled)}},_t=Object.freeze(Object.defineProperty({__proto__:null,rollbarClient:Ot},Symbol.toStringTag,{value:"Module"})),Nt=c("SmartTvA_API"),Lt=(e,t)=>{var i,n,r,s;try{if(!t)return Nt.warn(`Device info not available, cannot check capability: ${e}`),!1;const o=t.Product||{},a=t.Channel||{},c=t.Capability||{};switch(e){case"3d":return Boolean(c.support3d);case"uhd":return Boolean(c.supportUHD);case"dolby-vision":return Boolean(c.supportHDR&&((null==(i=o.platform)?void 0:i.toLowerCase().includes("dolby"))||(null==(n=a.brand)?void 0:n.toLowerCase().includes("dolby"))));case"atmos":return Boolean((null==(r=o.platform)?void 0:r.toLowerCase().includes("atmos"))||(null==(s=a.brand)?void 0:s.toLowerCase().includes("dolby")));default:return Nt.warn(`Unknown device capability: ${e}`),!1}}catch(o){return Nt.error(`Error checking device capability ${e}:`,o),!1}},xt=async e=>{if("undefined"==typeof window)return void Nt.warn("Window object not available, cannot attach SmartTvA_API");if("object"==typeof window.SmartTvA_API)return void Nt.info("SmartTvA_API already exists on window, skipping initialization");const t=await(async e=>{Nt.info("Initializing SmartTvA_API with TitanSDK");let t=null;try{Nt.info("Waiting for device info to be ready..."),t=await e.deviceInfo.getDeviceInfo(),Nt.info("Device info is ready, proceeding with SmartTvA_API initialization")}catch(i){Nt.warn("Failed to get device info during SmartTvA_API initialization:",i)}return{exit:()=>{Nt.info("SmartTvA_API.exit() called"),window.close()},hasCapability:(e,...i)=>{switch(Nt.debug(`SmartTvA_API.hasCapability('${e}', ${i.join(", ")})`),e){case"3DSupport":return Lt("3d",t);case"MultiScreen":return 1===i.length&&i[0],!1;case"DRM":if(2===i.length){const[e,t]=i;if("PlayReady"===e&&"DASH"===t)return!0;if("Widevine"===e&&"AdaptiveStreaming"===t)return!1}return!1;case"Key":if(1===i.length)switch(i[0]){case"numerickeys":case"colorkeys":case"prev_next":return!0;default:return!1}return!1;case"UHD":return Lt("uhd",t);case"FHD":case"Multiaudio":return!0;case"TTML":if(1===i.length)switch(i[0]){case"inband":case"outofband":case"EBU-TT-D":case"CFF-TT":return!0;default:return!1}return!1;case"HLS":return 1===i.length&&"DISCONTINUITY"===i[0];case"HDR":if(1===i.length){const e=i[0];if(!Lt("uhd",t))return!1;switch(e){case"HDR10":case"DA":case"HDR10+":return!0;case"DV":return Lt("dolby-vision",t);default:return!1}}return!1;case"8K":case"WidevineClassic":case"AdobeHDS":return!1;case"ATMOS":return Lt("atmos",t);default:return Nt.warn(`Unknown capability requested: ${e}`),!1}}}})(e);Object.defineProperty(window,"SmartTvA_API",{value:t,writable:!1,configurable:!0}),Nt.info("SmartTvA_API successfully attached to window object")},Ht=c("WrapperUtils");function Ut(e){return{getTTSSettings:async()=>(await e()).accessibility.getTTSSettings(),getTMSettings:async()=>(await e()).accessibility.getTMSettings(),isTTSSupported:async()=>(await e()).accessibility.isTTSSupported(),isTTSEnabled:async()=>(await e()).accessibility.isTTSEnabled(),isTMEnabled:async()=>(await e()).accessibility.isTMEnabled(),isTextMagnificationSupported:async()=>(await e()).accessibility.isTextMagnificationSupported(),startSpeaking:async t=>(await e()).accessibility.startSpeaking(t),stopSpeaking:async()=>(await e()).accessibility.stopSpeaking(),enableReader:async t=>(await e()).accessibility.enableReader(t),disableReader:async()=>(await e()).accessibility.disableReader(),onTTSSettingsChange:t=>{let i=null;return e().then((e=>{i=e.accessibility.onTTSSettingsChange(t)})).catch((e=>{Ht.error("Failed to set up TTS settings change handler:",e)})),()=>{i&&i()}},onTMSettingsChange:t=>{let i=null;return e().then((e=>{i=e.accessibility.onTMSettingsChange(t)})).catch((e=>{Ht.error("Failed to set up TM settings change handler:",e)})),()=>{i&&i()}}}}function Ft(e){return{launch:async(t,i)=>(await e()).apps.launch(t,i)}}const Kt=c("AnalyticsService");class Bt{sdkVersion;constructor(e){this.sdkVersion=e}getEventUrl(){return"https://sdk.titanos.tv/events"}async track(e){if("undefined"==typeof window||void 0===window.fetch)return Promise.resolve();try{const t={event_name:e.eventName,event_type:e.eventType,event_params:e.eventParams,event_timestamp:(new Date).toISOString().replace("T"," ").slice(0,-1)};await window.fetch(this.getEventUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(t){Kt.warn("TitanSDK: Usage tracking event failed to send.",t)}}trackUsage(){const e={eventName:"sdk",eventType:"sdk-initialized",eventParams:{appHostname:window.location.hostname,sdkVersion:this.sdkVersion}};return this.track(e)}}const zt=c("SDK"),Vt={debug:!1,useLegacyDeviceInfo:!1,legacyDeviceInfoTimeout:5e3,fallbackToBrowser:!0},$t="TITAN_SDK_USAGE_SENT";let Gt=null,jt=null,Wt=null,qt=null;Ot.initialize({accessToken:"",enabled:!1});const Qt=async()=>{if(!Gt)throw new s("SDK not created. Call getTitanSDK() first.",r.NOT_INITIALIZED);if(!Wt)throw zt.error("SDK initialization not started"),new s("SDK initialization not started.",r.NOT_INITIALIZED);if(!(await Wt))throw new s("SDK initialization failed.",r.UNKNOWN);return Gt},Jt=e=>{if(jt)return jt;const t={...Vt,...e};o.setDebugMode(t.debug??!1);const i=b.detectPlatform(t).platform;zt.info("Platform detected:",i);try{switch(i){case n.PHILIPS:Gt=new Xe(t);break;case n.PHILIPS_OLD:Gt=new Mt(t);break;case n.VESTEL:Gt=new ct(t);break;case n.BROWSER:default:i!==n.BROWSER&&t.debug&&zt.warn(`Platform ${i} detected but no specific SDK found, using BrowserSDK as fallback.`),Gt=new wt(t)}if(!Gt)throw new s("Failed to create SDK instance after platform detection",r.UNKNOWN)}catch(d){throw zt.error("Error creating SDK instance:",d),new s(`Failed to create SDK instance after platform detection: ${d}`,r.UNKNOWN)}Wt=Gt.init(),zt.info("SDK Version:",Ee);const a={VERSION:Ee,isReady:Wt,deviceInfo:(c=Qt,l=e=>{qt=e},{getDeviceInfo:async()=>{const e=await c(),t=await e.deviceInfo.getDeviceInfo();return null==l||l(t),t}}),accessibility:Ut(Qt),apps:Ft(Qt)};var c,l;return t.debug&&(zt.info("🔧 [DEBUG MODE] TitanSDK debug access enabled"),a.logging=function(e){let t=null;return{subscribe:(i,n)=>{let r=null;return e().then((e=>{t=e,e.logging&&(r=e.logging.subscribe(i,n))})).catch((e=>{Ht.error("Failed to set up logging subscription:",e)})),()=>{r&&r()}},getHistory:()=>(null==t?void 0:t.logging)?t.logging.getHistory():[],clear:()=>{(null==t?void 0:t.logging)&&t.logging.clear()}}}(Qt)),t.dev&&(t.debug&&zt.info("🔧 [DEV MODE] TitanSDK dev access enabled"),i===n.BROWSER&&t.dev&&(zt.info("Available dev methods:"),zt.info(" sdk.dev.updateTTSSettings({ enabled: true, rate: 1.5 })"),zt.info(" sdk.dev.updateTMSettings({ enabled: true, scale: 1.8 })")),a.dev=function(e){return{updateTTSSettings:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.updateTTSSettings)?void 0:n.call(i,t)},updateTMSettings:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.updateTMSettings)?void 0:n.call(i,t)},simulateError:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.simulateError)?void 0:n.call(i,t)},simulateGatewayError:async(t,i)=>{var n,r;return null==(r=null==(n=(await e()).dev)?void 0:n.simulateGatewayError)?void 0:r.call(n,t,i)},isBridgeConnected:async()=>{var t,i;return(null==(i=null==(t=(await e()).dev)?void 0:t.isBridgeConnected)?void 0:i.call(t))??!1}}}(Qt)),jt=a,Wt.then((async()=>{try{qt=await Gt.deviceInfo.getDeviceInfo();const e=new Bt(Ee);if(!(()=>{try{return!("undefined"==typeof window||!window.localStorage)&&"1"===window.localStorage.getItem($t)}catch{return!1}})())try{await e.trackUsage(),(()=>{try{if("undefined"==typeof window||!window.localStorage)return;window.localStorage.setItem($t,"1")}catch{}})()}catch{}}catch(d){t.debug&&zt.warn("Failed to pre-cache device info:",d)}})).catch((e=>{zt.error(`Initialization failed for platform ${i}:`,e)})),jt},Yt=async()=>{const e=await Qt(),t=await e.deviceInfo.getDeviceInfo();return qt=t,t};if("undefined"!=typeof document&&document.addEventListener("securitypolicyviolation",(e=>{Q.getViolations()})),"undefined"!=typeof window)if(window.TitanSDK&&window.TitanSDK.deviceInfo)zt.info("TitanSDK already exists on window, skipping initialization"),zt.info("You can still create a new SDK instance using window.getTitanSDK(options)"),window.getTitanSDK=Jt;else{const e=()=>{window.onDeviceInfoReady=function(e){Yt().then((t=>e(t))).catch((t=>e({},String(t))))},Object.defineProperty(window,"DeviceInfo",{get:()=>{if(qt)return qt;if(Gt&&jt)try{return Gt.deviceInfo.getDeviceInfo()}catch{return null}return null},configurable:!0}),void 0===window.SmartTvA_API&&Object.defineProperty(window,"SmartTvA_API",{value:{exit:()=>window.close()},writable:!1,configurable:!0})},t=e=>{try{const t=null==localStorage?void 0:localStorage.getItem(e);return t?JSON.parse(t):{}}catch(t){return o.isDebugMode()&&zt.error(`Failed to parse localStorage key ${e}:`,t),{}}},i=(new L).get("TITAN_SDK_PARAMS")||t("TITAN_SDK_PARAMS");i&&zt.info("Initializing TitanSDK with params:",i),window.TitanSDK=Jt(i),e(),xt(window.TitanSDK).catch((e=>{zt.error("Failed to initialize SmartTvA_API:",e)}))}e.VERSION=Ee,e.getDeviceInfo=Yt,e.getTitanSDK=Jt,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("rollbar")):"function"==typeof define&&define.amd?define(["exports","rollbar"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TitanSDK={},e.Rollbar)}(this,(function(e,t){"use strict";var i=Object.defineProperty,n=(e=>(e.PHILIPS="PHILIPS",e.PHILIPS_OLD="PHILIPS_OLD",e.VESTEL="VESTEL",e.BROWSER="BROWSER",e.UNKNOWN="UNKNOWN",e))(n||{}),r=(e=>(e.NOT_INITIALIZED="NOT_INITIALIZED",e.NOT_SUPPORTED="NOT_SUPPORTED",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.INVALID_ARGUMENTS="INVALID_ARGUMENTS",e.INVALID_PARAMETER="INVALID_PARAMETER",e.PLATFORM_NOT_DETECTED="PLATFORM_NOT_DETECTED",e.COMMUNICATION_ERROR="COMMUNICATION_ERROR",e.TIMEOUT="TIMEOUT",e.UNKNOWN="UNKNOWN",e))(r||{});class s extends Error{code;details;constructor(e,t="UNKNOWN",i){super(e),this.name="SDKError",this.code=t,this.details=i,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toString(){return`SDKError [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}function o(e,t,i,n){return[`${`[TitanSDK][${e}]`} ${t}`,...i,"\n",n]}function a(e,t){e}const c=new class{subscriptions=new Map;logBuffer=[];maxBufferSize=1e3;nextId=1;debugMode=!1;constructor(e=1e3){this.maxBufferSize=e}setDebugMode(e){this.debugMode=e}subscribe(e,t={}){const i="sub-"+this.nextId++,n={id:i,levels:t.levels||["debug","info","warn","error"],modules:t.modules,callback:e,created:Date.now()};if(this.subscriptions.set(i,n),t.includeHistory){this.getFilteredHistory(n.levels,n.modules).forEach((t=>{try{e(t)}catch(i){}}))}return i}unsubscribe(e){return this.subscriptions.delete(e)}addLogEntry(e){var t,i,n;this.logBuffer.push(e),this.logBuffer.length>this.maxBufferSize&&this.logBuffer.shift();if(("Gateway"===(null==(t=e.metadata)?void 0:t.source)||!0===(null==(i=e.metadata)?void 0:i.tunneled))&&"error"===e.level){const t=(null==(n=e.metadata)?void 0:n.caller)||"[Gateway]";a("error",o(e.module,e.message,e.args||[],t))}this.subscriptions.forEach((t=>{if(this.shouldNotifySubscription(t,e))try{t.callback(e)}catch(i){}}))}getHistory(e,t,i){return this.getFilteredHistory(e,t,i)}clear(){this.logBuffer=[]}getSubscriptionCount(){return this.subscriptions.size}getMetrics(){const e={totalEntries:this.logBuffer.length,entriesByLevel:{},entriesByModule:{},memoryUsageKB:Math.round(JSON.stringify(this.logBuffer).length/1024)};return this.logBuffer.length>0&&(e.oldestEntry=new Date(this.logBuffer[0].timestamp),e.newestEntry=new Date(this.logBuffer[this.logBuffer.length-1].timestamp)),this.logBuffer.forEach((t=>{e.entriesByLevel[t.level]=(e.entriesByLevel[t.level]||0)+1,e.entriesByModule[t.module]=(e.entriesByModule[t.module]||0)+1})),e}exportLogs(e,t){const i=this.getFilteredHistory(e,t);return JSON.stringify(i,null,2)}isDebugMode(){return this.debugMode}shouldNotifySubscription(e,t){return!!e.levels.includes(t.level)&&!(e.modules&&!e.modules.includes(t.module))}getFilteredHistory(e,t,i){let n=this.logBuffer;return e&&(n=n.filter((t=>e.includes(t.level)))),t&&(n=n.filter((e=>t.includes(e.module)))),i&&i>0&&(n=n.slice(-i)),[...n]}};function l(e){const t=(t,i,...n)=>{var r;const s=(()=>{try{const e=(new Error).stack;if(!e)return"";const t=e.split("\n");for(let i=3;i<t.length;i++){const e=t[i];if(e&&!e.includes("logger.ts")&&!e.includes("Logger")){const t=e.match(/\((.*):(\d+):(\d+)\)/)||e.match(/at (.*):(\d+):(\d+)/);if(t){const[,e,i]=t;return`${e.split("/").pop()||e}:${i}`}}}return""}catch{return""}})(),l=(e=>{var t;try{const i=null==(t=e.stack)?void 0:t.split("\n");if(!i||i.length<4)return"Unknown location";const n=i[3].replace("at","").trim()||"Unknown location",{fnName:r,fnPath:s}=(e=>{let t="",i="";return 1===e.split(" ").length?{fnName:"",fnPath:e.split(" ")[0]}:(3===e.split(" ").length?(t=e.split(" (")[0],i=e.split(" (")[1].replace(")","")):(t=e.split(" ")[0],i=e.split(" ")[1].replace(/\((.*)\)/,"$1")),{fnName:t,fnPath:i})})(n);return r?`${r}[${s}]`:`[${s}]`}catch{return"Unknown location"}})(new Error),d={id:`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),level:t,module:e,message:i,args:n,metadata:{url:"undefined"!=typeof window?null==(r=window.location)?void 0:r.href:void 0,caller:s}};c.addLogEntry(d);if(c.isDebugMode()||"error"===t){o(e,i,n,l);a(t)}};return{debug:(e,...i)=>t("debug",e,...i),info:(e,...i)=>t("info",e,...i),warn:(e,...i)=>t("warn",e,...i),error:(e,...i)=>t("error",e,...i),subscribe:(e,t)=>c.subscribe(e,t),unsubscribe:e=>c.unsubscribe(e),getHistory:(e,t,i)=>c.getHistory(e,t,i),clear:()=>c.clear()}}function d(e){return l(e)}const u=(e,t)=>c.subscribe(e,t),g=e=>c.unsubscribe(e),h=(e,t,i)=>c.getHistory(e,t,i),p=()=>c.clear(),f=e=>c.addLogEntry(e),m=d("PlatformDetection");class v{strategies=[];register(e){this.strategies.push(e),this.strategies.sort(((e,t)=>t.getPriority()-e.getPriority()))}getStrategies(){return[...this.strategies]}}class S{canDetect(){return"undefined"!=typeof window&&("t9_core"in window||"vestel"===window.deviceBrand||navigator.userAgent.toLowerCase().includes("vestel"))}getPlatform(){return this.canDetect()?n.VESTEL:null}getPriority(){return 3}}class b{canDetect(){return"undefined"!=typeof window&&("jwt"in window||"launcher_env"in window||"undefined"!=typeof navigator&&navigator.userAgent.toLowerCase().indexOf("philips")>-1)}getPlatform(){return this.canDetect()?n.PHILIPS:null}getPriority(){return 5}}class y{canDetect(){if("undefined"==typeof window)return!1;const e=(()=>{const e=navigator.userAgent.match(/Chrome\/(\d+)\./);return e?parseInt(e[1],10):null})(),t=null!==e&&e<=84;return"undefined"!=typeof navigator&&navigator.userAgent.includes("Philips")&&(document.cookie.includes("tos-session")||t)}getPlatform(){return this.canDetect()?n.PHILIPS_OLD:null}getPriority(){return 10}}class w{canDetect(){return!0}getPlatform(){return n.BROWSER}getPriority(){return 1}}const T=new class{factory;lastDetectedPlatform=null;constructor(){this.factory=new v,this.factory.register(new b),this.factory.register(new S),this.factory.register(new y),this.factory.register(new w)}registerStrategy(e){this.factory.register(e)}detectPlatform(e={}){if(e.forcePlatform)return{platform:e.forcePlatform,detectedBy:"forced",confidence:1};if(this.lastDetectedPlatform)return{...this.lastDetectedPlatform};const t=this.factory.getStrategies();for(const n of t)if(n.canDetect()){const t=n.getPlatform();if(null!==t){const i={platform:t,detectedBy:n.constructor.name,confidence:.9};return this.lastDetectedPlatform=i,e.debug&&m.info(`Platform detected as ${t}`),{...i}}}if(!1===e.fallbackToBrowser)throw new s("Could not detect platform and fallback is disabled",r.PLATFORM_NOT_DETECTED);const i={platform:n.BROWSER,detectedBy:"fallback",confidence:.1};return this.lastDetectedPlatform=i,e.debug&&m.info("Fallback to browser platform - no strategy matched"),{...i}}reset(){this.lastDetectedPlatform=null}},E={LAUNCH_APP_REQUEST:"LAUNCH_APP_REQUEST",DEVICE_INFO_REQUEST:"DEVICE_INFO_REQUEST",TTS_REQUEST_SETTINGS:"TTS_REQUEST_SETTINGS",TTS_REQUEST_START_SPEAKING:"TTS_REQUEST_START_SPEAKING",TTS_REQUEST_STOP_SPEAKING:"TTS_REQUEST_STOP_SPEAKING",ERROR_SIMULATION:"ERROR_SIMULATION",LAUNCH_APP_RESPONSE:"LAUNCH_APP_RESPONSE",DEVICE_INFO_RESPONSE:"DEVICE_INFO_RESPONSE",TTS_RESPONSE_SETTINGS:"TTS_RESPONSE_SETTINGS",TTS_RESPONSE_START_SPEAKING:"TTS_RESPONSE_START_SPEAKING",TTS_RESPONSE_STOP_SPEAKING:"TTS_RESPONSE_STOP_SPEAKING",ERROR_SIMULATION_RESPONSE:"ERROR_SIMULATION_RESPONSE",LAUNCHER_READY:"LAUNCHER_READY",BRIDGE_READY:"BRIDGE_READY",TTS_SETTINGS_CHANGE:"TTS_SETTINGS_CHANGE",TM_SETTINGS_CHANGE:"TM_SETTINGS_CHANGE",LOG_ENTRY:"LOG_ENTRY",ERROR_RESPONSE:"ERROR_RESPONSE",TRANSFER_DATA:"TRANSFER_DATA"},I={TTS_SETTINGS_CHANGE:E.TTS_SETTINGS_CHANGE,TM_SETTINGS_CHANGE:E.TM_SETTINGS_CHANGE,LOG_ENTRY:E.LOG_ENTRY},D={enabled:!1,available:!1},C={enabled:!1,available:!1},R={tts:D,tm:C},A="TIMEOUT",P="NOT_SUPPORTED",k="INVALID_REQUEST",M="COMMUNICATION_ERROR",_="LAUNCH_FAILED",O="APP_NOT_FOUND",N="APP_NOT_AVAILABLE",L="INVALID_APP_CODE";var x=(e=>(e.PHILIPS="philips",e.VESTEL="vestel",e.BROWSER="browser",e))(x||{});class H{mocks={};constructor(e){e&&(this.mocks={...e})}get(e){return e in this.mocks?this.mocks[e]:"undefined"!=typeof window&&e in window?window[e]:void 0}has(e){return e in this.mocks||"undefined"!=typeof window&&e in window}get proxy(){return new Proxy({},{get:(e,t)=>{const i=t,n=this.get(i);return"function"==typeof n?(...e)=>{try{return n(...e)}catch(t){return}}:n}})}setMocks(e){this.mocks={...this.mocks,...e}}clearMocks(){this.mocks={}}removeMock(e){const t={};for(const i in this.mocks)i!==e&&(t[i]=this.mocks[i]);this.mocks=t}getAvailableMethods(){const e=new Set;for(const t in this.mocks)Object.prototype.hasOwnProperty.call(this.mocks,t)&&e.add(t);if("undefined"!=typeof window)for(const t in window)Object.prototype.hasOwnProperty.call(window,t)&&t in window&&e.add(t);return Array.from(e)}create(e,t){"undefined"!=typeof window&&(window[e]=t)}removeGlobal(e){"undefined"!=typeof window&&e in window&&delete window[e]}}function U(e,t,i="titanos"){return new Promise(((e,n)=>{const r=new H,s="deviceInfoCallback_"+Date.now()+"_"+Math.floor(1e4*Math.random());r.create(s,(t=>{e(t),r.removeGlobal(s)}));const o=`https://${t}/potamoi/v1/device_info?callback=${s}`,a=`https://smarttv.zeasn.tv/homepage_api/device/clientInfo?callback=${s}`,c=document.createElement("script");c.src="titanos"===i?o:a,c.type="text/javascript",c.onerror=()=>{n(new Error("Failed to load device info script.")),delete r.proxy[s]},document.head.appendChild(c),setTimeout((()=>{r.has(s)&&(n(new Error("Device info request timed out.")),delete r.proxy[s]),c.parentNode&&c.parentNode.removeChild(c)}),7e3)}))}const F=()=>{const e=e=>{const t=(Math.random().toString(16)+"000000000").substring(2,10);return e?"-"+t.substring(0,4)+"-"+t.substring(4,8):t};return e(!1)+e(!0)+e(!0)+e(!1)},K=1e4,B=[{time:3e4,message:"DOM still not ready after 30 seconds"},{time:6e4,message:"DOM still not ready after 1 minute"},{time:12e4,message:"DOM still not ready after 2 minutes"},{time:18e4,message:"DOM still not ready after 3 minutes"},{time:24e4,message:"DOM still not ready after 4 minutes"},{time:3e5,message:"DOM still not ready after 5 minutes - this may indicate serious page issues"}],z=d("DOM-Utils");function V(){return"undefined"!=typeof document&&!!document.body}const $=(e="en-US")=>"undefined"!=typeof navigator&&navigator.language&&navigator.language||e,G=d("BaseBridge");class j{src="";isInitialized=!1;iframe=null;iframeOrigin="";pendingRequests=new Map;messageTimeout=1e4;iframeTimeout=3e3;connected=!1;debug=!1;initializationPromise=null;aborted=!1;initReject;MESSAGE_TYPES=E;eventHandlers=new Map;constructor(e){this.debug=(null==e?void 0:e.debug)||!1,(null==e?void 0:e.gatewayUrl)&&(this.src=e.gatewayUrl),G.debug("bridge: constructor",this.src)}async initialize(){if(this.isInitialized)return!0;if(this.initializationPromise)return G.debug("bridge: initialization already in progress, waiting..."),this.initializationPromise;G.debug("bridge: initialization not in progress, starting new one"),this.initializationPromise=this.performInitialization();try{return await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}async performInitialization(){return new Promise(((e,t)=>{this.aborted=!1,this.initReject=t,G.debug("bridge: starting initialization process"),window.addEventListener("message",this.handleMessage.bind(this));let i=!1;const n=()=>{this.aborted||i||(i=!0,this.isInitialized=!0,G.debug("bridge initialized successfully"),e(!0))},r=()=>{this.aborted||i||(i=!0,G.error("Bridge iframe failed to load or initialize."),this.isInitialized=!1,t(new Error("Bridge iframe failed to load or initialize.")))};(async()=>{try{await this.setupIframe(n,r),i||(i=!0,G.warn("Bridge initialization timeout - setupIframe completed but LAUNCHER_READY not received"),this.isInitialized=!1,e(!1))}catch(s){if(i)return;i=!0,G.error("Failed to setup iframe:",s),this.isInitialized=!1,t(s)}})()}))}async sendMessage(e,t){this.isInitialized||await this.initialize();try{const i=this.prepareMessage(e,t);return new Promise(((e,t)=>{const n=setTimeout((()=>{this.pendingRequests.delete(i.requestId),t(new s("Bridge request timeout",r.TIMEOUT))}),this.messageTimeout);this.pendingRequests.set(i.requestId,{resolve:e,reject:t,timeout:n}),this.iframe&&this.iframe.contentWindow?(G.debug("bridge: sendMessage",i),this.iframe.contentWindow.postMessage(i,this.iframeOrigin||"*")):(clearTimeout(n),this.pendingRequests.delete(i.requestId),t(new s("Bridge iframe not available",r.COMMUNICATION_ERROR)))}))}catch(i){G.error("bridge: error sending message:",i);return(await Promise.resolve().then((()=>Oe)).then((e=>e.rollbarClient))).reportError(i instanceof Error?i:new Error("Unknown error"),{component:"SDK",operation:"sendMessage",requestId:this.prepareMessage(e,t).requestId}),Promise.reject({success:!1,type:e,error:{code:r.COMMUNICATION_ERROR,message:i instanceof Error?i.message:"Unknown error"}})}}disconnect(){this.aborted=!0,this.initReject&&(this.initReject(new Error("Bridge initialization aborted")),this.initReject=void 0),this.iframe&&(window.removeEventListener("message",this.handleMessage.bind(this)),document.body.removeChild(this.iframe),this.iframe=null),this.isInitialized=!1,this.connected=!1,this.initializationPromise=null,this.pendingRequests.clear(),this.eventHandlers.clear()}isConnected(){return this.isInitialized&&this.connected}getBridgeHealth(){return{connected:this.isConnected()}}registerEventHandler(e,t){var i;this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set);const n=e=>{t(e)};return null==(i=this.eventHandlers.get(e))||i.add(n),window.addEventListener("message",(e=>n(e.data.data))),()=>{var t;window.removeEventListener("message",(e=>{var t;return n(null==(t=e.data)?void 0:t.data)})),null==(t=this.eventHandlers.get(e))||t.delete(n)}}handleMessage(e){var t;if(!this.iframeOrigin||e.origin===this.iframeOrigin)try{const i=e.data;if(this.debug&&i&&i.requestId&&G.debug("bridge handleMessage",i),i&&("BRIDGE_READY"===i.type||"LAUNCHER_READY"===i.type)&&(null==(t=this.iframe)?void 0:t.contentWindow)===e.source)return void(this.connected=!0);if(i&&i.type&&Object.values(I).includes(i.type)&&!i.requestId)return void this.handleNotification(i);if(i&&i.requestId&&this.pendingRequests.has(i.requestId)){const{resolve:e,reject:t,timeout:n}=this.pendingRequests.get(i.requestId);if(clearTimeout(n),this.pendingRequests.delete(i.requestId),!1===i.success&&i.error){const e=this.getOperationFromMessageType(i.type||"unknown");t(this.createSDKErrorFromGatewayResponse(i.error,e))}else e({success:!0,data:i.response||i.data||i.result,requestId:i.requestId,timestamp:i.timestamp||Date.now()})}}catch(i){G.error("Error handling message:",i)}}handleNotification(e){G.debug("bridge notification received:",e);const t=this.eventHandlers.get(e.type);t&&t.forEach((t=>{try{t(e.data)}catch(i){G.error(`Error in ${e.type} handler:`,i)}}))}prepareMessage(e,t){return{payload:t,type:e,requestId:this.generateRequestId(),timestamp:Date.now()}}generateRequestId(){return`bridge_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}createSDKErrorFromGatewayResponse(e,t){const i=this.mapGatewayErrorCodeToSDK(e.code);return new s(e.message,i,{operation:t,gatewayErrorCode:e.code,gatewayErrorMessage:e.message})}mapGatewayErrorCodeToSDK(e){switch(e){case _:case O:case N:case L:return r.INVALID_PARAMETER;case A:return r.TIMEOUT;case P:return r.NOT_SUPPORTED;case M:return r.COMMUNICATION_ERROR;case k:return r.INVALID_ARGUMENTS;default:return r.UNKNOWN}}getOperationFromMessageType(e){switch(e){case E.LAUNCH_APP_REQUEST:return"launchApp";case E.DEVICE_INFO_REQUEST:return"getDeviceInfo";case E.TTS_REQUEST_START_SPEAKING:return"startSpeaking";case E.TTS_REQUEST_STOP_SPEAKING:return"stopSpeaking";case E.TTS_REQUEST_SETTINGS:return"getTTSSettings";default:return"sdkOperation"}}async setupIframe(e,t){if(!this.iframe&&this.src){if(await new Promise((e=>{"undefined"!=typeof document&&"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>e()),{once:!0}):e()})),this.iframe=document.createElement("iframe"),this.iframe.style.display="none",this.iframe.src=this.src,this.iframe.setAttribute("sandbox","allow-scripts"),!V())try{await function(e=1e4){return new Promise(((t,i)=>{if(V())return void t();const n=Date.now();let r=0,s="initial";z.debug("Waiting for document.body:",{readyState:document.readyState,bodyExists:!!document.body,htmlExists:!!document.documentElement,headExists:!!document.head,timeout:e});let o=null,a=null,c=null;const l=[];function d(){a&&(clearInterval(a),a=null),o&&(o.disconnect(),o=null),c&&(clearTimeout(c),c=null),l.forEach(clearTimeout),l.length=0}const u=(e,t)=>{if(s!==e){const i=Date.now()-n;z.debug(`DOM strategy changed: ${s} → ${e}`,{elapsed:i,reason:t||"strategy switch",checkCount:r}),s=e}},g=(e,t="warn")=>{const i=Date.now()-n,s=Math.floor(i/6e4),o=Math.floor(i%6e4/1e3);"error"===t?z.error(`${e} after ${s}m ${o}s`,{elapsed:i,checkCount:r,readyState:document.readyState,bodyExists:!!document.body}):z.warn(`${e} after ${s}m ${o}s`,{elapsed:i,checkCount:r,readyState:document.readyState})},h=e=>{u("mutation-observer","DOMContentLoaded completed but body not ready"),o=new MutationObserver((()=>{r++;const e=Date.now()-n;V()&&(d(),z.debug("document.body ready via MutationObserver:",{elapsed:e,checkCount:r}),t())})),o.observe(document.documentElement,{childList:!0,subtree:!1}),c=setTimeout((()=>{V()||(g("DOM still not ready, switching to polling fallback"),u("polling","MutationObserver timeout"),a=setInterval((()=>{r++;const e=Date.now()-n;V()&&(d(),z.debug("document.body ready via polling fallback:",{elapsed:e,checkCount:r}),t())}),50))}),3e4)};if("loading"===document.readyState){u("dom-content-loaded","document still loading");const s=()=>{var e;clearTimeout(o);const i=Date.now()-n;V()?(d(),z.debug("document.body ready after DOMContentLoaded:",{elapsed:i}),t()):(z.warn("DOMContentLoaded fired but body still not ready:",{elapsed:i,childNodes:(null==(e=document.documentElement)?void 0:e.childNodes.length)||0}),h())},o=setTimeout((()=>{var e;document.removeEventListener("DOMContentLoaded",s),d();const t=Date.now()-n;z.error("Timeout waiting for document.body:",{elapsed:t,readyState:document.readyState,bodyExists:!!document.body,checkCount:r,html:!!document.documentElement,head:!!document.head,childNodesCount:(null==(e=document.documentElement)?void 0:e.childNodes.length)||0}),i(new Error(`Timeout waiting for document.body after ${t}ms. readyState: ${document.readyState}, checks: ${r}. Initialize SDK after DOMContentLoaded or use defer/async script.`))}),e);document.addEventListener("DOMContentLoaded",s,{once:!0})}else z.debug("DOM already loaded, using MutationObserver + polling"),h();B.forEach((({time:t,message:i})=>{if(t<e){const e=setTimeout((()=>{V()||g(i)}),t);l.push(e)}}))}))}(K)}catch(i){throw G.error("Document body unavailable:",{readyState:document.readyState,bodyExists:!!document.body,timeout:10}),new Error("Document body is not available. SDK initialized too early - ensure DOM is ready before calling getTitanSDK(). Consider initializing SDK after DOMContentLoaded event or in a defer/async script.")}document.body.appendChild(this.iframe),await new Promise((i=>{const n=setTimeout((()=>{this.aborted||(G.warn("Bridge iframe ready timeout - continuing anyway"),i())}),this.iframeTimeout),r=t=>{var s;this.aborted||t.data&&t.data.type===E.LAUNCHER_READY&&(null==(s=this.iframe)?void 0:s.contentWindow)===t.source&&(G.debug("bridge iframe ready:",t.data),window.removeEventListener("message",r),clearTimeout(n),this.connected=!0,e&&e(),i())};window.addEventListener("message",r),window.addEventListener("message",(e=>{var t;this.aborted||e.data&&e.data.type===E.TRANSFER_DATA&&(null==(t=this.iframe)?void 0:t.contentWindow)===e.source&&G.debug("bridge transferData:",e.data)})),this.iframe&&(this.iframe.onload=()=>{this.aborted||G.debug("bridge iframe loaded: ",this.src)},this.iframe.onerror=()=>{this.aborted||(G.error("bridge iframe error: ",this.src),t&&t())})}))}}promisify(e){return(...t)=>new Promise(((i,n)=>{try{i(e.apply(null,t))}catch(r){n(r)}}))}async getDeviceInfo(){this.isInitialized||await this.initialize();const e=await this.sendMessage(E.DEVICE_INFO_REQUEST,void 0);if(e.success&&"data"in e)return e.data}async launchApp(e){this.isInitialized||await this.initialize();const t={code:e.appId,query:e.deepLink||""};return(await this.sendMessage(E.LAUNCH_APP_REQUEST,t)).success}onLogEntry(e){return this.registerEventHandler(E.LOG_ENTRY,(t=>{f({...t,metadata:{...t.metadata,source:"Gateway",tunneled:!0}}),e(t)}))}}const W=d("CSPDetector");let q=[];const Q=class{static getViolations(){return[...this.violations]}static clearViolations(){this.violations.length=0}static onViolation(e){return q.push(e),()=>{q=q.filter((t=>t!==e))}}static checkWebAPISupport(){return{hasPostMessage:"undefined"!=typeof window&&"postMessage"in window,hasIframe:"undefined"!=typeof document&&"createElement"in document,hasMessageEvent:"undefined"!=typeof MessageEvent,hasDocument:"undefined"!=typeof document}}};var J;((e,t,n)=>{t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(Q,"symbol"!=typeof(J="violations")?J+"":J,[]),"undefined"!=typeof document&&document.addEventListener("securitypolicyviolation",(e=>{const t=`${e.violatedDirective}: ${e.blockedURI}`;Q.violations.push(t),W.warn("CSP Violation detected:",t);const i={directive:e.violatedDirective,blockedURI:e.blockedURI,originalEvent:e};q.forEach((e=>{try{e(i)}catch(t){W.error("CSPDetector listener error",t)}}))}));let Y=Q;const Z=d("EnhancedBridge");function X(e,t){if(!["frame-src","child-src","connect-src"].includes(e.directive)||!e.blockedURI||!t)return!1;const i=e.blockedURI,n=e=>e.replace(/\/+$/,"").toLowerCase(),r=n(i),s=n(t),o=e=>{try{return new URL(e).hostname}catch{const t=e.match(/^(?:https?:\/\/)?([^\/]+)/);return t?t[1]:""}},a=o(i),c=o(t);return s.includes(r)||r.includes(s)||a&&c&&a===c||i.includes("titanos.tv")&&t.includes("titanos.tv")||i.includes("localhost")&&t.includes("localhost")}class ee extends j{bridgeHealthStatus={connected:!1,cspBlocked:!1,iframeCreated:!1,communicationWorking:!1,cspViolations:[]};cspUnsubscribe;cspViolationDetected=!1;cspViolationPromise;cspViolationResolver=null;constructor(e){super(e),this.bridgeHealthStatus.gatewayUrl=this.src,this.cspViolationPromise=new Promise((e=>{this.cspViolationResolver=e})),this.setupCspViolationListener()}setupCspViolationListener(){this.cspUnsubscribe=Y.onViolation((e=>{if(Z.debug("CSP violation received in EnhancedBaseBridge:",{directive:e.directive,blockedURI:e.blockedURI,gatewayUrl:this.src,isBridgeViolation:X(e,this.src)}),X(e,this.src)){const t=`${e.directive}: ${e.blockedURI||"unknown"}`;this.bridgeHealthStatus.cspViolations.includes(t)||this.bridgeHealthStatus.cspViolations.push(t),Z.warn("CSP violation detected for bridge:",{directive:e.directive,blockedURI:e.blockedURI,gatewayUrl:this.src}),this.bridgeHealthStatus.cspBlocked=!0,this.bridgeHealthStatus.lastError=`CSP ${e.directive} blocked: ${e.blockedURI||"unknown"}`,!this.cspViolationDetected&&this.cspViolationResolver&&(this.cspViolationDetected=!0,Z.debug("Resolving CSP violation Promise"),this.cspViolationResolver(),this.cspViolationResolver=null)}}))}async initialize(){try{Z.debug("Starting enhanced bridge initialization");const e=await super.initialize();return this.bridgeHealthStatus.connected=!!e,!!e}catch(e){const t=e instanceof Error?e.message:"Unknown error";return this.bridgeHealthStatus.lastError=t,Z.error("Enhanced bridge initialization failed:",e),!1}}getBridgeHealth(){return{...this.bridgeHealthStatus,connected:this.isConnected(),iframeCreated:null!==this.iframe}}disconnect(){this.aborted||(super.disconnect(),this.bridgeHealthStatus.connected=!1,this.bridgeHealthStatus.communicationWorking=!1,this.cspUnsubscribe&&(this.cspUnsubscribe(),this.cspUnsubscribe=void 0),this.cspViolationDetected=!1,this.cspViolationPromise=new Promise((e=>{this.cspViolationResolver=e})),this.bridgeHealthStatus={connected:!1,cspBlocked:!1,iframeCreated:!1,communicationWorking:!1,gatewayUrl:this.src,cspViolations:[]},this.aborted=!0)}async setupIframe(e,t){try{Z.debug("Setting up bridge iframe"),await super.setupIframe(e,t),this.bridgeHealthStatus.iframeCreated=!0}catch(i){this.bridgeHealthStatus.iframeCreated=!1;const e=i instanceof Error?i.message:"Unknown error";throw this.bridgeHealthStatus.lastError=e,Z.error("Failed to setup iframe:",{error:e,gatewayUrl:this.src,documentReady:document.readyState,bodyExists:!!document.body}),i}}async executeBridgeFunction(e,t){const i=this.getBridgeHealth();if(!i.connected){if(t)return Z.debug("Bridge not connected, using fallback function"),await t();throw new s("Bridge not connected",r.COMMUNICATION_ERROR,{healthStatus:i})}return await e()}async executeWithFallback(e,t){return await this.executeBridgeFunction(e,t)}async sendMessage(e,t){return await this.executeBridgeFunction((()=>super.sendMessage(e,t)))}getConnectionResult(){const e=this.getBridgeHealth();return{success:e.connected&&!e.cspBlocked,healthStatus:e,error:e.lastError}}async waitForInitializationAttempt(){if(this.isConnected())return void Z.debug("Bridge already initialized, no need to wait");const e=this;if(e.initializationPromise){Z.debug("Bridge initialization in progress, waiting for completion...");try{await e.initializationPromise,Z.debug("Bridge initialization attempt completed")}catch{Z.debug("Bridge initialization attempt completed (with error)")}}else{Z.debug("No bridge initialization in progress, starting new attempt...");try{await this.initialize(),Z.debug("Bridge initialization attempt completed")}catch{Z.debug("Bridge initialization attempt completed (with error)")}}this.bridgeHealthStatus.iframeCreated&&!this.isConnected()&&(this.cspViolationDetected||this.bridgeHealthStatus.cspBlocked?Z.debug("CSP violation already detected, no need to wait"):(Z.debug("Iframe created but connection not established, waiting for CSP violation detection..."),await this.cspViolationPromise,Z.debug("CSP violation detection completed (or connection established)")))}}class te extends ee{constructor(e){if(null==e?void 0:e.gatewayUrl)super({gatewayUrl:e.gatewayUrl});else{const e=window.location.hostname.includes("dev01.devview"),t=window.location.hostname.startsWith("dev");super({gatewayUrl:`http://localhost:4660/gateway/${e||t?"dev01":"index"}.html`})}}}const ie=new H;class ne extends ee{constructor(e){var t,i;if(null==e?void 0:e.gatewayUrl)super({gatewayUrl:e.gatewayUrl});else{let e="app";if(ie.proxy.jwt&&!ie.proxy.jwt.includes("null")){const t=(e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT token format");try{const e=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=window.atob(e),n=decodeURIComponent(Array.from(i).map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));return JSON.parse(n)}catch(i){throw new Error("Error decoding JWT token: "+(i instanceof Error?i.message:String(i)))}})(ie.proxy.jwt);e=("production"===t.iss?"app":t.iss)||"app"}let n=`https://${e}.titanos.tv/gateway/${e.startsWith("dev")?"dev01":"index"}.html`;((null==(i=null==(t=ie.proxy.location)?void 0:t.host)?void 0:i.includes("dev01.devview"))||e.startsWith("dev"))&&(n="https://dev01.devview.titanos.tv/gateway/dev01.html"),super({gatewayUrl:n})}}async getTTSSettings(){return(await this.getA11ySettings()).tts||D}async getTMSettings(){return(await this.getA11ySettings()).tm||C}async getA11ySettings(){const e=await this.sendMessage(E.TTS_REQUEST_SETTINGS,void 0);return e.success&&"data"in e?e.data:R}async startSpeaking(e){this.isInitialized||await this.initialize();return(await this.sendMessage(E.TTS_REQUEST_START_SPEAKING,e)).success}async stopSpeaking(){return(await this.sendMessage(E.TTS_REQUEST_STOP_SPEAKING,void 0)).success}onTTSSettingsChange(e){return this.registerEventHandler(E.TTS_SETTINGS_CHANGE,(t=>{e(t)}))}onTMSettingsChange(e){return this.registerEventHandler(E.TM_SETTINGS_CHANGE,(t=>{e(t)}))}}const re={HIGH:["button","link","heading","listitem"],MEDIUM:["textbox","combobox","checkbox","radio","slider"],LOW:["list","navigation","main","dialog","grid"]},se=d("AriaProcessor");class oe{config;implicitRoles={button:"button",a:"link",'input[type="text"]':"textbox",'input[type="email"]':"textbox",'input[type="password"]':"textbox",'input[type="search"]':"textbox",'input[type="tel"]':"textbox",'input[type="url"]':"textbox",'input[type="checkbox"]':"checkbox",'input[type="radio"]':"radio",'input[type="range"]':"slider",textarea:"textbox",select:"combobox",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",nav:"navigation",main:"main",aside:"complementary",section:"region",article:"article",ul:"list",ol:"list",li:"listitem",table:"table",tr:"row",td:"cell",th:"columnheader",img:"img",dialog:"dialog"};tvElementTypes={navigation:["nav","menu",'[role="navigation"]','[role="menubar"]'],mediaControl:['[role="button"][aria-label*="play"]','[role="button"][aria-label*="pause"]','[role="slider"][aria-label*="volume"]','[role="progressbar"]'],contentGrid:['[role="grid"]','[role="gridcell"]',".content-grid",".video-grid"],mainContent:["main",'[role="main"]',".main-content","#main"]};constructor(e){this.config={...e}}updateConfig(e){this.config={...e}}async processElement(e){try{if(this.isElementHidden(e))return null;const t=this.getElementRole(e);if(this.config.tvOptimized&&!this.isRelevantForTV(t))return null;const i=this.computeAccessibleName(e);if(!i&&this.isInteractiveElement(t))return se.warn("Interactive element without accessible name:",e),null;const n=this.getAccessibleDescription(e),r=this.computeElementState(e),s=this.computePositionInfo(e,t),o=this.getAvailableActions(e,t),a=this.config.tvOptimized?this.getTVSpecificProperties(e,t):void 0,c={element:e,role:t,name:i,description:n,state:r,position:s,actions:o,tvProperties:a};return se.debug("Processed accessibility element:",{role:t,name:i.substring(0,50),state:r,tvOptimized:!!a}),c}catch(t){return se.error("Error processing element:",t),null}}isElementHidden(e){if("true"===e.getAttribute("aria-hidden"))return!0;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||"0"===t.opacity)return!0;if(this.config.tvOptimized){const t=e.getBoundingClientRect();if(0===t.width&&0===t.height)return!0}return!1}getElementRole(e){const t=e.getAttribute("role");if(t)return t;const i=e.tagName.toLowerCase(),n=e.getAttribute("type");if("input"===i&&n){const e=`input[type="${n}"]`;if(this.implicitRoles[e])return this.implicitRoles[e]}return this.implicitRoles[i]||"generic"}computeAccessibleName(e){const t=e.getAttribute("aria-labelledby");if(t){const e=[];for(const i of t.split(/\s+/)){const t=document.getElementById(i);t&&e.push(this.getTextContent(t))}if(e.length>0)return e.join(" ").trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();if(this.isFormControl(e)){const t=this.getAssociatedLabels(e);if(t.length>0)return t.map((e=>this.getTextContent(e))).join(" ").trim()}if("input"===e.tagName.toLowerCase()){const t=e.getAttribute("placeholder");if(t)return t.trim()}if("img"===e.tagName.toLowerCase()){const t=e.getAttribute("alt");if(null!==t)return t.trim()}return this.getTextContent(e)}getAccessibleDescription(e){const t=e.getAttribute("aria-describedby");if(!t)return;const i=[];for(const n of t.split(/\s+/)){const e=document.getElementById(n);e&&i.push(this.getTextContent(e))}return i.length>0?i.join(" ").trim():void 0}computeElementState(e){const t={},i=e.getAttribute("aria-expanded");null!==i&&(t.expanded="true"===i);const n=e.getAttribute("aria-checked");null!==n&&(t.checked="mixed"===n?"mixed":"true"===n);const r=e.getAttribute("aria-selected");null!==r&&(t.selected="true"===r);const s=e.getAttribute("aria-disabled")||e.getAttribute("disabled");null!==s&&(t.disabled="true"===s||""===s);const o=e.getAttribute("aria-invalid");null!==o&&(t.invalid="true"===o||o);const a=e.getAttribute("aria-level");null!==a?t.level=parseInt(a,10):e.tagName.match(/^H[1-6]$/)&&(t.level=parseInt(e.tagName.charAt(1),10));const c=e.getAttribute("aria-valuenow");null!==c&&(t.valueNow=parseFloat(c));const l=e.getAttribute("aria-valuetext");return null!==l&&(t.valueText=l),t.focused=document.activeElement===e,t}computePositionInfo(e,t){return"listitem"===t?this.computeListItemPosition(e):"gridcell"===t||"cell"===t?this.computeGridCellPosition(e):void 0}computeListItemPosition(e){const t=e.getAttribute("aria-posinset"),i=e.getAttribute("aria-setsize");if(t&&i)return{position:parseInt(t,10),setSize:parseInt(i,10)};const n=e.closest('ul, ol, [role="list"]');if(n){const t=Array.from(n.querySelectorAll('li, [role="listitem"]')),i=t.indexOf(e)+1;if(i>0)return{position:i,setSize:t.length}}}computeGridCellPosition(e){const t=e.closest('[role="row"], tr'),i=e.closest('[role="grid"], table');if(t&&i){const n=Array.from(i.querySelectorAll('[role="row"], tr')),r=Array.from(t.querySelectorAll('[role="gridcell"], [role="cell"], td, th')),s=n.indexOf(t)+1,o=r.indexOf(e)+1;if(s>0&&o>0)return{position:o,setSize:r.length,row:s,column:o,totalRows:n.length,totalColumns:r.length}}}getAvailableActions(e,t){const i=[];if(this.isClickableElement(e,t)&&i.push({name:"activate",description:this.getActivationDescription(t),tvButton:"OK"}),e.hasAttribute("aria-expanded")){const t="true"===e.getAttribute("aria-expanded");i.push({name:t?"collapse":"expand",description:t?"Collapse":"Expand",tvButton:"OK"})}return"textbox"!==t&&"combobox"!==t||i.push({name:"edit",description:"Enter text",tvButton:"OK"}),i}getTVSpecificProperties(e,t){const i={};return this.matchesSelectors(e,this.tvElementTypes.navigation)&&(i.isMainNavigation=!0,i.priority="high"),this.matchesSelectors(e,this.tvElementTypes.mediaControl)&&(i.isMediaControl=!0,i.priority="high"),this.matchesSelectors(e,this.tvElementTypes.contentGrid)&&(i.isContentGrid=!0,i.priority="medium"),i.priority||(re.HIGH.includes(t)?i.priority="high":re.MEDIUM.includes(t)?i.priority="medium":i.priority="low"),Object.keys(i).length>0?i:void 0}isRelevantForTV(e){return[...re.HIGH,...re.MEDIUM,...re.LOW].includes(e)}isInteractiveElement(e){return["button","link","textbox","combobox","checkbox","radio","slider"].includes(e)}isFormControl(e){return["input","textarea","select","button"].includes(e.tagName.toLowerCase())}isClickableElement(e,t){return["button","link","checkbox","radio","menuitem"].includes(t)||e.hasAttribute("onclick")}getActivationDescription(e){return{button:"Press button",link:"Follow link",checkbox:"Toggle checkbox",radio:"Select option",menuitem:"Select menu item"}[e]||"Activate"}getTextContent(e){let t="";for(const i of e.childNodes)if(i.nodeType===Node.TEXT_NODE)t+=i.textContent||"";else if(i.nodeType===Node.ELEMENT_NODE){const e=i;this.isElementHidden(e)||(t+=this.getTextContent(e))}return t.replace(/\s+/g," ").trim()}getAssociatedLabels(e){const t=[],i=e.getAttribute("id");if(i){const e=document.querySelectorAll(`label[for="${i}"]`);t.push(...Array.from(e))}const n=e.closest("label");return n&&t.push(n),t}matchesSelectors(e,t){return t.some((t=>{try{return e.matches(t)}catch{return!1}}))}}const ae=d("DOMMonitor");class ce{config;ariaProcessor;isTracking=!1;focusHandler;liveRegionHandler;focusListener;keydownListener;mutationObserver;currentFocusedElement=null;liveRegions=new Map;previousFocusedElement=null;constructor(e,t){this.config={...e},this.focusHandler=t,this.ariaProcessor=new oe(e)}updateConfig(e){this.config={...e},this.ariaProcessor.updateConfig(e)}async startFocusTracking(){if(this.isTracking)return void ae.debug("Focus tracking already active");ae.info("Starting focus tracking"),this.focusListener=this.handleFocusEvent.bind(this),document.addEventListener("focusin",this.focusListener,!0),document.addEventListener("focusout",this.focusListener,!0),this.keydownListener=this.handleKeydownEvent.bind(this),document.addEventListener("keydown",this.keydownListener,!0);const e=document.activeElement;e&&e!==document.body&&(this.currentFocusedElement=e,await this.processFocusChange(e,"initial")),this.isTracking=!0,ae.info("Focus tracking started")}async startLiveRegionMonitoring(e){this.liveRegionHandler=e,ae.info("Starting live region monitoring"),await this.scanForLiveRegions(),this.mutationObserver=new MutationObserver(this.handleMutations.bind(this)),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["aria-live","aria-atomic","aria-relevant","aria-busy"]}),ae.info("Live region monitoring started")}async stop(){ae.info("Stopping DOM monitoring"),this.focusListener&&(document.removeEventListener("focusin",this.focusListener,!0),document.removeEventListener("focusout",this.focusListener,!0),this.focusListener=void 0),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener,!0),this.keydownListener=void 0),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=void 0),this.currentFocusedElement=null,this.previousFocusedElement=null,this.liveRegions.clear(),this.isTracking=!1,this.liveRegionHandler=void 0,ae.info("DOM monitoring stopped")}async restart(){await this.stop(),this.config.focusTracking&&await this.startFocusTracking(),this.config.liveRegions&&this.liveRegionHandler&&await this.startLiveRegionMonitoring(this.liveRegionHandler)}async handleFocusEvent(e){try{const t=e.target;"focusin"===e.type?t&&t!==this.currentFocusedElement&&(this.currentFocusedElement=t,await this.processFocusChange(t,"user")):"focusout"===e.type&&t===this.currentFocusedElement&&(this.currentFocusedElement=null)}catch(t){ae.error("Error handling focus event:",t)}}async handleKeydownEvent(e){const t={ArrowUp:"UP",ArrowDown:"DOWN",ArrowLeft:"LEFT",ArrowRight:"RIGHT",Enter:"OK",Escape:"BACK",Tab:"TAB"}[e.key];t&&this.currentFocusedElement&&ae.debug("TV remote button pressed:",t)}async processFocusChange(e,t){try{if(this.ariaProcessor.isElementHidden(e))return;const i=await this.ariaProcessor.processElement(e);if(i&&this.focusHandler){const e={previousElement:this.previousFocusedElement||void 0,currentElement:i,reason:t};await this.focusHandler(e),this.previousFocusedElement=i}}catch(i){ae.error("Error processing focus change:",i)}}async scanForLiveRegions(){const e=document.querySelectorAll("[aria-live]");for(const t of e){const e=this.createLiveRegion(t);e&&(this.liveRegions.set(t,e),ae.debug("Found live region:",{politeness:e.politeness,atomic:e.atomic}))}}createLiveRegion(e){const t=e.getAttribute("aria-live");if(!t||"off"===t)return null;const i=t,n="true"===e.getAttribute("aria-atomic"),r=(e.getAttribute("aria-relevant")||"additions text").split(" "),s="true"===e.getAttribute("aria-busy");return{element:e,politeness:i,atomic:n,relevant:r,busy:s}}async handleMutations(e){for(const i of e)try{"attributes"===i.type&&await this.handleAttributeChange(i),"childList"!==i.type&&"characterData"!==i.type||await this.handleContentChange(i)}catch(t){ae.error("Error handling mutation:",t)}}async handleAttributeChange(e){const t=e.target,i=e.attributeName;if("aria-live"===i){const e=this.createLiveRegion(t);e?this.liveRegions.set(t,e):this.liveRegions.delete(t)}else if("aria-busy"===i){const e=this.liveRegions.get(t);e&&(e.busy="true"===t.getAttribute("aria-busy"))}}async handleContentChange(e){let t=e.target;for(;t&&t!==document.body;){const i=this.liveRegions.get(t);if(i&&!i.busy&&this.liveRegionHandler){const n=i.atomic?t.textContent||"":this.extractChangedContent(e);n.trim()&&await this.liveRegionHandler(i,n);break}t=t.parentElement}}extractChangedContent(e){if("characterData"===e.type)return e.target.textContent||"";if("childList"===e.type){let t="";for(const i of e.addedNodes)(i.nodeType===Node.TEXT_NODE||i.nodeType===Node.ELEMENT_NODE)&&(t+=i.textContent||"");return t}return""}}const le=d("AnnouncementProcessor");class de{config;ttsFunction;stopTtsFunction;lastAnnouncementTime=0;announcementQueue=[];isProcessingQueue=!1;tvTimings={minInterval:100,maxQueueSize:5,priorityDelay:50,politeDelay:200};constructor(e,t,i){this.config={...e},this.ttsFunction=t,this.stopTtsFunction=i}updateConfig(e){this.config={...e}}async announce(e,t="polite"){const i=this.processAnnouncementText(e);if(!i||0===i.length)return le.debug("No text to announce after processing"),!1;const n={text:i,priority:t,timestamp:Date.now()};return"assertive"===t?(this.announcementQueue.length=0,await this.speakNow(n)):(this.queueAnnouncement(n),this.processQueue(),!0)}async stopAnnouncement(){try{if(this.announcementQueue.length=0,this.isProcessingQueue=!1,this.stopTtsFunction){const e=await this.stopTtsFunction();return le.debug("TTS stop result:",e),e}return le.debug("No stopTtsFunction available"),!0}catch(e){return le.error("Error stopping announcement:",e),!1}}async announceFocusChange(e){const{currentElement:t}=e;if(!t)return;const i=this.buildFocusAnnouncement(t);i.length>0&&await this.announce(i,"polite")}async announceLiveRegion(e,t){if(!e.trim())return;const i=this.processLiveRegionContent(e);i&&await this.announce([i],t)}buildFocusAnnouncement(e){const t=[],i=this.getRoleAnnouncement(e.role);i&&t.push(i),e.name&&t.push(e.name);const n=this.getStateAnnouncement(e.state,e.role);n.length>0&&t.push(...n);const r=this.getPositionAnnouncement(e.position,e.role);r&&t.push(r),e.description&&this.shouldIncludeDescription()&&t.push(e.description);const s=this.getActionAnnouncement(e.actions||[]);return s&&t.push(s),this.filterAnnouncementContent(t,e.role)}shouldIncludeDescription(){return"concise"!==this.config.verbosity&&(this.config.verbosity,!0)}filterAnnouncementContent(e,t){if(!this.config.tvOptimized)return e;const i=["button","link","heading","alert","dialog"].includes(t);return"concise"===this.config.verbosity?i?e.slice(0,2):e.slice(1,2):"standard"===this.config.verbosity?e.slice(0,4):e}getRoleAnnouncement(e){const t={button:{concise:"",standard:"button",detailed:"button"},link:{concise:"",standard:"link",detailed:"link"},heading:{concise:"",standard:"heading",detailed:"heading"},listitem:{concise:"",standard:"list item",detailed:"list item"},textbox:{concise:"",standard:"text field",detailed:"text field"},combobox:{concise:"",standard:"dropdown",detailed:"combo box"},checkbox:{concise:"check box",standard:"check box",detailed:"check box"},radio:{concise:"radio",standard:"radio button",detailed:"radio button"},slider:{concise:"slider",standard:"slider",detailed:"slider"},navigation:{concise:"",standard:"navigation",detailed:"navigation menu"},main:{concise:"",standard:"main content",detailed:"main content area"},dialog:{concise:"dialog",standard:"dialog",detailed:"dialog box"},grid:{concise:"",standard:"grid",detailed:"content grid"},gridcell:{concise:"",standard:"",detailed:"grid cell"},list:{concise:"",standard:"list",detailed:"list"},menu:{concise:"menu",standard:"menu",detailed:"menu"},menuitem:{concise:"",standard:"menu item",detailed:"menu item"},tab:{concise:"tab",standard:"tab",detailed:"tab"},tabpanel:{concise:"",standard:"tab panel",detailed:"tab panel"},progressbar:{concise:"progress",standard:"progress bar",detailed:"progress indicator"},alert:{concise:"alert",standard:"alert",detailed:"alert message"},status:{concise:"",standard:"status",detailed:"status update"}}[e];if(!t)return null;return t[this.config.verbosity]||t.standard||null}getStateAnnouncement(e,t){const i=[];if(!e)return i;const n="concise"===this.config.verbosity,r="detailed"===this.config.verbosity;if(void 0!==e.expanded&&(n?i.push(e.expanded?"open":"closed"):i.push(e.expanded?"expanded":"collapsed")),void 0!==e.checked&&("mixed"===e.checked?i.push(n?"mixed":"partially checked"):n?i.push(e.checked?"on":"off"):i.push(e.checked?"checked":"not checked")),e.selected&&i.push(n?"on":"selected"),e.disabled&&i.push("disabled"),e.invalid&&(r?i.push("string"==typeof e.invalid?e.invalid:"invalid"):i.push("invalid")),"heading"===t&&e.level&&(n?i.push(`h${e.level}`):i.push(`level ${e.level}`)),e.valueText)i.push(e.valueText);else if(void 0!==e.valueNow)if("progressbar"===t){const t=e.valueMax?Math.round(e.valueNow/e.valueMax*100):e.valueNow;i.push(n?`${t}%`:`${t} percent`)}else"slider"===t?i.push(n?`${e.valueNow}`:`value ${e.valueNow}`):i.push(`${e.valueNow}`);return this.config.tvOptimized&&e.focused&&r&&i.push("focused"),i}getPositionAnnouncement(e,t){if(!e)return null;const i="concise"===this.config.verbosity,n="detailed"===this.config.verbosity;return"listitem"===t?i?null:`${e.position} of ${e.setSize}`:"gridcell"===t&&e.row&&e.column?this.config.tvOptimized?i?`${e.row},${e.column}`:n&&e.totalRows&&e.totalColumns?`row ${e.row} of ${e.totalRows}, column ${e.column} of ${e.totalColumns}`:`row ${e.row}, column ${e.column}`:`row ${e.row}, column ${e.column}`:"tab"===t&&e.position&&e.setSize?i?null:`tab ${e.position} of ${e.setSize}`:"menuitem"===t&&e.position&&e.setSize?i?null:`${e.position} of ${e.setSize}`:null}getActionAnnouncement(e){if(!e||0===e.length)return null;const t="concise"===this.config.verbosity,i="detailed"===this.config.verbosity;if(!this.config.tvOptimized){return`available actions: ${e.map((e=>e.name)).slice(0,2).join(", ")}`}const n=e[0];if(!n)return null;if(n.tvButton){if(t)return null;const e=this.getTVButtonText(n.tvButton),r=n.description||"activate";return i?`press ${e} to ${r.toLowerCase()}`:`press ${e}`}if(n.name){if(t)return null;const e=this.getCommonTVAction(n.name);if(e)return i?`available actions: ${e}`:e}return null}getTVButtonText(e){return{OK:"OK",BACK:"Back",UP:"Up",DOWN:"Down",LEFT:"Left",RIGHT:"Right",MENU:"Menu"}[e]||e}getCommonTVAction(e){return{activate:"activate",click:"select",toggle:"toggle",expand:"expand",collapse:"collapse",select:"select",play:"play",pause:"pause",stop:"stop",mute:"mute",unmute:"unmute"}[e.toLowerCase()]||null}processAnnouncementText(e){if(!e)return[];if("string"==typeof e&&(e=[e]),!Array.isArray(e))return[];let t=[...e];return this.config.tvOptimized&&(t=this.applyTVOptimizations(t)),t=this.applyVerbosityFilter(t),t=t.map((e=>e.trim())).filter((e=>e.length>0)).map((e=>this.cleanupText(e))),t}applyTVOptimizations(e){return e.map((e=>{let t=e.replace(/\bnavigation\b/gi,"nav").replace(/\bmenuitem\b/gi,"menu").replace(/\btextbox\b/gi,"text field").replace(/\bcombobox\b/gi,"dropdown").replace(/\bcheckbox\b/gi,"check box");return t=t.replace(/\bapplication\b/gi,"").replace(/\bregion\b/gi,"").replace(/\blandmark\b/gi,""),t.trim()}))}applyVerbosityFilter(e){switch(this.config.verbosity){case"concise":return e.slice(0,2);case"detailed":return e;default:return e.slice(0,4)}}cleanupText(e){return e.replace(/\s+/g," ").replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim()}processLiveRegionContent(e){const t=this.cleanupText(e);return t.length<3||/^\s*[.!?]*\s*$/.test(t)?null:this.config.tvOptimized?this.applyTVOptimizations([t])[0]:t}queueAnnouncement(e){this.announcementQueue.length>=this.tvTimings.maxQueueSize&&this.announcementQueue.shift(),this.announcementQueue.push(e)}async processQueue(){if(!this.isProcessingQueue&&0!==this.announcementQueue.length){for(this.isProcessingQueue=!0;this.announcementQueue.length>0;){const e=this.announcementQueue.shift();if(e){await this.speakNow(e);const t="assertive"===e.priority?this.tvTimings.priorityDelay:this.tvTimings.politeDelay;await this.delay(t)}}this.isProcessingQueue=!1}}async speakNow(e){const t=Date.now()-this.lastAnnouncementTime;t<this.tvTimings.minInterval&&await this.delay(this.tvTimings.minInterval-t);try{const t=await this.ttsFunction(e.text);return this.lastAnnouncementTime=Date.now(),le.debug("Announced:",{text:e.text.join(" ").substring(0,100),priority:e.priority,success:t}),t}catch(i){return le.error("Error speaking announcement:",i),!1}}delay(e){return new Promise((t=>setTimeout(t,e)))}}const ue=d("AccessibilityReader");class ge{config;isActive=!1;domMonitor;ariaProcessor;announcementProcessor;currentElement=null;liveRegions=new Map;constructor(e,t,i){this.config={...e},this.ariaProcessor=new oe(e),this.announcementProcessor=new de(e,t,i),this.domMonitor=new ce(e,this.handleFocusChange.bind(this))}async start(){if(this.isActive)return ue.debug("Accessibility Reader already active"),!0;try{ue.info("Starting Accessibility Reader",this.config),this.config.focusTracking&&await this.domMonitor.startFocusTracking(),this.config.liveRegions&&await this.domMonitor.startLiveRegionMonitoring(this.handleLiveRegionChange.bind(this));const e=document.activeElement;return e&&e!==document.body&&await this.announceElement(e),this.isActive=!0,ue.info("Accessibility Reader started successfully"),!0}catch(e){return ue.error("Failed to start Accessibility Reader:",e),!1}}async stop(){if(!this.isActive)return ue.debug("Accessibility Reader not active"),!0;try{return ue.info("Stopping Accessibility Reader"),await this.domMonitor.stop(),this.currentElement=null,this.liveRegions.clear(),this.isActive=!1,ue.info("Accessibility Reader stopped"),!0}catch(e){return ue.error("Failed to stop Accessibility Reader:",e),!1}}async updateConfig(e){try{const t={...this.config};if(this.config={...this.config,...e},this.ariaProcessor.updateConfig(this.config),this.announcementProcessor.updateConfig(this.config),this.domMonitor.updateConfig(this.config),this.isActive){const e=t.focusTracking!==this.config.focusTracking,i=t.liveRegions!==this.config.liveRegions;(e||i)&&await this.domMonitor.restart()}return ue.info("Accessibility Reader configuration updated",this.config),!0}catch(t){return ue.error("Failed to update Accessibility Reader config:",t),!1}}getConfig(){return{...this.config}}isReaderActive(){return this.isActive}async announce(e,t="polite"){return this.isActive?await this.announcementProcessor.announce(e,t):(ue.debug("Accessibility Reader not active, skipping announcement"),!1)}async stopAnnouncement(){return this.isActive?await this.announcementProcessor.stopAnnouncement():(ue.debug("Accessibility Reader not active, skipping stop"),!1)}getCurrentElement(){return this.currentElement}async handleFocusChange(e){var t,i;try{ue.debug("Focus changed",{from:null==(t=e.previousElement)?void 0:t.role,to:null==(i=e.currentElement)?void 0:i.role,reason:e.reason}),this.currentElement=e.currentElement||null,e.currentElement&&await this.announcementProcessor.announceFocusChange(e)}catch(n){ue.error("Error handling focus change:",n)}}async handleLiveRegionChange(e,t){try{if(ue.debug("Live region changed",{politeness:e.politeness,content:t.substring(0,100)}),e.busy)return;const i="assertive"===e.politeness?"assertive":"polite";await this.announcementProcessor.announceLiveRegion(t,i)}catch(i){ue.error("Error handling live region change:",i)}}async announceElement(e){try{const t=await this.ariaProcessor.processElement(e);if(t){const e={previousElement:this.currentElement||void 0,currentElement:t,reason:"programmatic"};await this.handleFocusChange(e)}}catch(t){ue.error("Error announcing element:",t)}}}class he{static sanitizeSpeechCues(e){return e.map((e=>this.sanitizeSpeechCue(e)))}static sanitizeSpeechCue(e){return"string"==typeof e?this.sanitizeText(e):{...e,Name:this.sanitizeText(e.Name),Value:e.Value?this.sanitizeText(e.Value):void 0,ItemSubType:e.ItemSubType?this.sanitizeText(e.ItemSubType):void 0,Status:e.Status?this.sanitizeText(e.Status):void 0}}static sanitizeText(e){return e?e.replace(/<[^>]*>/g,"").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/(javascript|data|vbscript):/gi,"blocked:").replace(/\\{2,}/g,"\\").slice(0,1e3):e}static sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+=/gi,"disabled-event=").replace(/allow=/gi,"data-blocked-allow=").replace(/(javascript|data|vbscript):/gi,"blocked:")}static sanitizeInput(e){return e.replace(/[\x00-\x1F\x7F]/g,"").replace(/['"\\]/g,"\\$&").replace(/\0/g,"").slice(0,500)}static checkRateLimit(e,t=10,i=6e4){const n=Date.now();return e.filter((e=>n-e.timestamp<i)).length<t}}const pe=d("PhilipsTTS"),fe=e=>e?{available:!0,enabled:"1"===e.setVoiceGuidance,rate:e.speechRate?Number(e.speechRate):1,volume:e.speechVolume?Number(e.speechVolume):1}:D,me=e=>e?{available:!0,enabled:"on"===e.setTextMagnification,scale:e.fontSizeBase?Number(e.fontSizeBase):1}:C;class ve{windowApi;constructor(e){this.windowApi=e||new H}messageToJSON(e){const t=JSON.stringify(e.info).replace(/'/g,"''");return JSON.stringify({...e,info:t})}getSettings(){const e=this.windowApi.get("getDeviceContent");if(!e)return R;const t=e("getVoiceGuidance",!1)??"",i=e("getTextMagnification",!1)??"";try{return{tts:fe(this.hexToObject(t)),tm:me(this.hexToObject(i))}}catch(n){return pe.warn("JSON Parsing Error:",n),R}}sendTTSMessage(e){const t=this.windowApi.get("omi_platform");if(t)try{t.sendPlatformMessage(this.messageToJSON(e))}catch(i){pe.warn("Failed to send platform message:",i)}}startSpeaking(e){const t=he.sanitizeSpeechCues(e).filter((e=>!(e=>"string"==typeof e?""===e.trim():""===e.Name.trim())(e)));if(0===t.length)return!1;const i=Object.fromEntries(t.map(((e,t)=>[`tts${t+1}`,e])));return this.sendTTSMessage({cmd:"startToSpeak",info:i}),!0}stopSpeaking(){return this.sendTTSMessage({cmd:"stopToSpeak",info:{param1:"false"}}),!0}stopSpeakingButKeepHighlightTask(){this.sendTTSMessage({cmd:"stopSpeakAndKeepInHighlightTask",info:{param1:"false"}})}hexToString(e){var t;return(null==(t=e.match(/.{2}/g))?void 0:t.map((e=>String.fromCharCode(parseInt(e,16)))).join(""))||""}hexToObject(e){if(!e)return null;try{let t=this.hexToString(e).replace(/\\/g,"").trim();t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));return JSON.parse(t)}catch(t){return null}}getTTSSettings(){return this.getSettings().tts}getTMSettings(){return this.getSettings().tm}createPlatformEventHandler(e,t){return i=>{try{const r=JSON.parse(i),s=decodeURIComponent(r.data),o=/cmd:\s*'(?<command>[^']+)'\s*,\s*info:\s*'(?<info>[^']+)'\s*;/,a=s.match(o);if(!a||!a.groups)return;if(a.groups.command!==e)return;try{let e=JSON.parse(a.groups.info);"string"==typeof e&&(e=JSON.parse(e)),t(e)}catch(n){pe.warn(`[tts] Could not parse info as JSON: ${n}`)}}catch(r){pe.warn(`[tts] Failed to parse platform event: ${r}`)}}}onTTSSettingsChange(e){var t;const i=this.windowApi.get("omi_platform");if(!i)return()=>{};const n=this.createPlatformEventHandler("VoiceGuidanceNotify",(t=>e(fe(t))));return null==(t=i.addPlatformEventListener)||t.call(i,n),()=>{var e;null==(e=i.removePlatformEventListener)||e.call(i,n)}}onTMSettingsChange(e){var t;const i=this.windowApi.get("omi_platform");if(!i)return()=>{};const n=this.createPlatformEventHandler("TextMagnificationNotify",(t=>e(me(t))));return null==(t=i.addPlatformEventListener)||t.call(i,n),()=>{var e;null==(e=i.removePlatformEventListener)||e.call(i,n)}}}const Se=d("AccessibilityService");class be{tts;reader=null;ttsSettings=D;tmSettings=C;constructor(){this.tts=new ve,this.tts.onTTSSettingsChange((e=>{this.ttsSettings=e})),this.tts.onTMSettingsChange((e=>{this.tmSettings=e}))}async startSpeaking(e){if("string"==typeof e&&(e=[e]),await this.isTTSEnabled())try{return this.tts.startSpeaking(e),!0}catch(t){return Se.error("Error starting speaking:",t),!1}return!0}async stopSpeaking(){return await this.isTTSEnabled()&&this.tts.stopSpeaking(),!0}async enableReader(e){try{if(!(await this.isTTSSupported()))return Se.warn("Cannot enable Reader: TTS not supported"),!1;if(!(await this.isTTSEnabled()))return Se.warn("Cannot enable Reader: TTS not enabled"),!1;this.reader=new ge(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(Se.info("Reader enabled"),!0)}catch(t){return Se.error("Error enabling Reader:",t),!1}}async disableReader(){try{if(this.reader){const e=await this.reader.stop();return this.reader=null,e&&Se.info("Reader disabled"),e}return Se.debug("Reader was not active"),!0}catch(e){return Se.error("Error disabling Reader:",e),!1}}getReader(){if(!this.reader)throw new Error("Reader is not active");return this.reader}async isTTSSupported(){try{return(await this.getTTSSettings()).available}catch(e){return Se.error("Error checking TTS support:",e),!1}}async isTextMagnificationSupported(){try{return(await this.getTMSettings()).available}catch(e){return Se.error("Error checking magnification support:",e),!1}}onTTSSettingsChange(e){return this.tts.onTTSSettingsChange(e)}onTMSettingsChange(e){return this.tts.onTMSettingsChange(e)}async getTTSSettings(){return this.ttsSettings}async getTMSettings(){return this.tmSettings}async isTTSEnabled(){return(await this.getTTSSettings()).enabled}async isTMEnabled(){return(await this.getTMSettings()).enabled}}class ye{config;waitReady=new Promise((()=>{}));waitReadyResolver;constructor(e){this.config=e,this.waitReady=new Promise((e=>{this.waitReadyResolver=e}))}logError(...e){this.config.debug}}var we,Te={exports:{}};var Ee,Ie,De=(we||(we=1,Ee=Te,Ie=function(){var e=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function r(e,t){if(!n[e]){n[e]={};for(var i=0;i<e.length;i++)n[e][e.charAt(i)]=i}return n[e][t]}var s={compressToBase64:function(e){if(null==e)return"";var i=s._compress(e,6,(function(e){return t.charAt(e)}));switch(i.length%4){default:case 0:return i;case 1:return i+"===";case 2:return i+"==";case 3:return i+"="}},decompressFromBase64:function(e){return null==e?"":""==e?null:s._decompress(e.length,32,(function(i){return r(t,e.charAt(i))}))},compressToUTF16:function(t){return null==t?"":s._compress(t,15,(function(t){return e(t+32)}))+" "},decompressFromUTF16:function(e){return null==e?"":""==e?null:s._decompress(e.length,16384,(function(t){return e.charCodeAt(t)-32}))},compressToUint8Array:function(e){for(var t=s.compress(e),i=new Uint8Array(2*t.length),n=0,r=t.length;n<r;n++){var o=t.charCodeAt(n);i[2*n]=o>>>8,i[2*n+1]=o%256}return i},decompressFromUint8Array:function(t){if(null==t)return s.decompress(t);for(var i=new Array(t.length/2),n=0,r=i.length;n<r;n++)i[n]=256*t[2*n]+t[2*n+1];var o=[];return i.forEach((function(t){o.push(e(t))})),s.decompress(o.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":s._compress(e,6,(function(e){return i.charAt(e)}))},decompressFromEncodedURIComponent:function(e){return null==e?"":""==e?null:(e=e.replace(/ /g,"+"),s._decompress(e.length,32,(function(t){return r(i,e.charAt(t))})))},compress:function(t){return s._compress(t,16,(function(t){return e(t)}))},_compress:function(e,t,i){if(null==e)return"";var n,r,s,o={},a={},c="",l="",d="",u=2,g=3,h=2,p=[],f=0,m=0;for(s=0;s<e.length;s+=1)if(c=e.charAt(s),Object.prototype.hasOwnProperty.call(o,c)||(o[c]=g++,a[c]=!0),l=d+c,Object.prototype.hasOwnProperty.call(o,l))d=l;else{if(Object.prototype.hasOwnProperty.call(a,d)){if(d.charCodeAt(0)<256){for(n=0;n<h;n++)f<<=1,m==t-1?(m=0,p.push(i(f)),f=0):m++;for(r=d.charCodeAt(0),n=0;n<8;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}else{for(r=1,n=0;n<h;n++)f=f<<1|r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r=0;for(r=d.charCodeAt(0),n=0;n<16;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}0==--u&&(u=Math.pow(2,h),h++),delete a[d]}else for(r=o[d],n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;0==--u&&(u=Math.pow(2,h),h++),o[l]=g++,d=String(c)}if(""!==d){if(Object.prototype.hasOwnProperty.call(a,d)){if(d.charCodeAt(0)<256){for(n=0;n<h;n++)f<<=1,m==t-1?(m=0,p.push(i(f)),f=0):m++;for(r=d.charCodeAt(0),n=0;n<8;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}else{for(r=1,n=0;n<h;n++)f=f<<1|r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r=0;for(r=d.charCodeAt(0),n=0;n<16;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1}0==--u&&(u=Math.pow(2,h),h++),delete a[d]}else for(r=o[d],n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;0==--u&&(u=Math.pow(2,h),h++)}for(r=2,n=0;n<h;n++)f=f<<1|1&r,m==t-1?(m=0,p.push(i(f)),f=0):m++,r>>=1;for(;;){if(f<<=1,m==t-1){p.push(i(f));break}m++}return p.join("")},decompress:function(e){return null==e?"":""==e?null:s._decompress(e.length,32768,(function(t){return e.charCodeAt(t)}))},_decompress:function(t,i,n){var r,s,o,a,c,l,d,u=[],g=4,h=4,p=3,f="",m=[],v={val:n(0),position:i,index:1};for(r=0;r<3;r+=1)u[r]=r;for(o=0,c=Math.pow(2,2),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;switch(o){case 0:for(o=0,c=Math.pow(2,8),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;d=e(o);break;case 1:for(o=0,c=Math.pow(2,16),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;d=e(o);break;case 2:return""}for(u[3]=d,s=d,m.push(d);;){if(v.index>t)return"";for(o=0,c=Math.pow(2,p),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;switch(d=o){case 0:for(o=0,c=Math.pow(2,8),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;u[h++]=e(o),d=h-1,g--;break;case 1:for(o=0,c=Math.pow(2,16),l=1;l!=c;)a=v.val&v.position,v.position>>=1,0==v.position&&(v.position=i,v.val=n(v.index++)),o|=(a>0?1:0)*l,l<<=1;u[h++]=e(o),d=h-1,g--;break;case 2:return m.join("")}if(0==g&&(g=Math.pow(2,p),p++),u[d])f=u[d];else{if(d!==h)return null;f=s+s.charAt(0)}m.push(f),u[h++]=s+f.charAt(0),s=f,0==--g&&(g=Math.pow(2,p),p++)}}};return s}(),null!=Ee?Ee.exports=Ie:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",(function(){return Ie}))),Te.exports);const Ce="1.7.2",Re=d("RollbarClient"),Ae=["chrome://userjs/","chrome-extension://","moz-extension://","getJWTString","getjwtstring","user.js","userscript","tampermonkey","greasemonkey","can't find variable getjwtstring","referenceerror: can't find variable: getjwtstring","unexpected end of json input","jsonparse"];const Pe=new class{rollbar=null;config=null;windowWrapper=new H;isSDKError(e){return e instanceof s||e instanceof Error&&"SDKError"===e.name}initialize(e){if(e.enabled&&e.accessToken)try{this.config=e,this.rollbar=new t({accessToken:e.accessToken,environment:e.environment||"development",captureUncaught:!0,captureUnhandledRejections:!0,verbose:!1,reportLevel:"error",captureIp:!1,captureUsername:!1,captureEmail:!1,maxItems:100,itemsPerMinute:60,captureLambdaTimeouts:!1,endpoint:"https://sdk.titanos.tv/logs/",autoInstrument:{network:!1,log:!1,dom:!1,navigation:!1,connectivity:!1},payload:{client:{javascript:{code_version:"unknown",source_map_enabled:!0}}},transform:e=>{e.context&&(e.context=`hephaestus-${e.context}`)},checkIgnore:(e,t,i)=>{const n=t[0],r="string"==typeof n?n:null==n?void 0:n.message,s="object"==typeof n&&n?n.stack:"",o=String(n).toLowerCase();return Ae.some((e=>(null==r?void 0:r.toLowerCase().includes(e.toLowerCase()))||(null==s?void 0:s.toLowerCase().includes(e.toLowerCase()))||o.includes(e.toLowerCase())))}}),this.setupGlobalErrorHandlers(),Re.info("Rollbar initialized successfully",{environment:e.environment})}catch(i){Re.error("Failed to initialize Rollbar",{error:i,config:e})}else Re.warn("Rollbar not initialized - disabled or missing access token")}shouldIgnoreError(e){if(!e)return!0;const t="string"==typeof e?e:e.message||"",i="object"==typeof e&&e.stack||"",n=String(e).toLowerCase();return Ae.some((e=>(null==t?void 0:t.toLowerCase().includes(e.toLowerCase()))||(null==i?void 0:i.toLowerCase().includes(e.toLowerCase()))||n.includes(e.toLowerCase())))}async reportError(e,t,i="error"){var n;return this.rollbar&&(null==(n=this.config)?void 0:n.enabled)&&e&&this.isSDKError(e)?this.shouldIgnoreError(e)?Promise.resolve(null):new Promise((n=>{this.getDeviceContext().then((r=>{var s,o,a;try{const c=h().filter((e=>!e.module.includes("RollbarClient")&&!e.message.includes("Rollbar")&&"debug"!==e.level)).slice(-20),l={logs:c.map((e=>`[${e.timestamp}] ${e.module}: ${e.message}${e.args&&e.args.length>0?"\n Args: "+JSON.stringify(e.args):""}`)).join("\n"),component:(null==t?void 0:t.component)||"SDK",operation:null==t?void 0:t.operation,requestId:null==t?void 0:t.requestId,timestamp:Date.now(),url:"undefined"!=typeof window?null==(s=window.location)?void 0:s.href:void 0,userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",sessionId:this.generateSessionId(),errorStack:"object"==typeof e?e.stack:void 0,version:"undefined"!=typeof window&&(null==(o=this.windowWrapper.get("TitanSDK"))?void 0:o.VERSION)||"unknown",...r,...t},d="critical"===i?"critical":"error",u="critical"===i?"critical_error_with_logs":"error_with_logs";null==(a=this.rollbar)||a[d](e,{custom:{type:u,context:l,logCount:c.length}},((t,r)=>{var s;if(t)this.shouldIgnoreError(t)||Re.error(`Failed to send ${i} error to Rollbar`,{error:t,originalError:e}),n(null);else{const t=r&&(r.uuid||(null==(s=r.result)?void 0:s.uuid))||null;Re.info(("critical"===i?"Critical error":"Error")+" sent to Rollbar",{message:"string"==typeof e?e:(null==e?void 0:e.message)||"Unknown error",component:l.component,rollbarId:t,logCount:c.length}),n(t)}}))}catch(c){Re.error(`Failed to send ${i} error to Rollbar`,{error:c,originalError:e}),n(null)}})).catch((e=>{Re.error(`Failed to get device context for ${i} error`,{error:e}),n(null)}))})):Promise.resolve(null)}collectSDKUsage(e,t,i,n){var r,s;if(this.rollbar&&(null==(r=this.config)?void 0:r.enabled))try{const r=i?"info":"warning";this.rollbar[r](`SDK function execution: ${e}`,{custom:{type:"sdk_function_execution",functionName:e,success:i,component:n,result:i?t:void 0,error:i?void 0:t,timestamp:Date.now(),url:"undefined"!=typeof window?null==(s=window.location)?void 0:s.href:void 0}}),Re.info("SDK function execution logged",{functionName:e,success:i,component:n})}catch(o){Re.error("Failed to log SDK function execution",{error:o,functionName:e,component:n})}}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async getDeviceContext(){var e,t,i;try{if(null==window?void 0:window.TitanSDK)try{const n=await(null==(i=null==(t=null==(e=null==window?void 0:window.TitanSDK)?void 0:e.deviceInfo)?void 0:t.getDeviceInfo)?void 0:i.call(t));return{deviceInfo:n?JSON.stringify(n):"unavailable"}}catch(n){}return{deviceInfo:`OS: ${(null==navigator?void 0:navigator.platform)||"unknown"}, Browser: ${this.detectBrowserEngine()}, Storage: ${"localStorage"in(window||{})}`}}catch(r){return{}}}detectBrowserEngine(){if("undefined"==typeof navigator)return"unknown";const e=navigator.userAgent;return e.includes("Chrome")?"Blink":e.includes("Firefox")?"Gecko":e.includes("Safari")&&!e.includes("Chrome")?"WebKit":e.includes("Edge")?"EdgeHTML":"unknown"}setupGlobalErrorHandlers(){if("undefined"==typeof window)return;const e=console.error;console.error=(...t)=>{e.apply(console,t);const i=t.find((e=>e instanceof Error||"string"==typeof e&&e.includes("Error")));i&&this.isSDKError(i)&&!this.shouldIgnoreError(i)&&this.reportError(i,{component:"SDK",operation:"console.error"})},"undefined"!=typeof window&&(window.addEventListener("error",(e=>{this.isSDKError(e.error)&&!this.shouldIgnoreError(e.error)&&this.reportError(e.error||e.message,{component:"SDK",operation:"window.onerror"})})),window.addEventListener("unhandledrejection",(e=>{this.isSDKError(e.reason)&&!this.shouldIgnoreError(e.reason)&&this.reportError(e.reason,{component:"SDK",operation:"unhandledrejection"})})))}isInitialized(){var e;return null!==this.rollbar&&!0===(null==(e=this.config)?void 0:e.enabled)}},ke={};function Me(e){const t={},i=/jwt|token|authorization|cookie|password|secret/i;return Object.keys(e).forEach((n=>{const r=e[n];i.test(n)?t[n]="[REDACTED]":t[n]=(e=>{if("string"==typeof e)return e.length>500?`${e.slice(0,500)}…`:e;if(Array.isArray(e))return e.slice(-50).map((e=>"string"==typeof e&&e.length>500?`${e.slice(0,500)}…`:e));return e})(r)})),t}function _e(e,t,i,n={}){try{const o=Date.now();if(o-(ke[e]||0)<5e3)return Promise.resolve(null);ke[e]=o;const a={userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",component:t,operation:i,context:n?Me(n):void 0,version:Ce};Re.error("SDK_CRITICAL",{code:e,component:t,operation:i,...a.context?{context:a.context}:{}});const c=new s(e,r.UNKNOWN,{component:t,operation:i,...a.context?{context:a.context}:{}});return Pe.reportError(c,a,"critical")}catch{return Promise.resolve(null)}}const Oe=Object.freeze(Object.defineProperty({__proto__:null,reportCriticalCode:_e,rollbarClient:Pe},Symbol.toStringTag,{value:"Module"})),Ne=d("TVPlatform");class Le extends ye{DEFAULT_DEVICE_INFO={};bridge;isInitialized=!1;CACHE_KEY="titansdk";CACHE_EXPIRY=6048e5;constructor(e,t){if(super(e),t)this.bridge=t;else{const e={gatewayUrl:this.config.gatewayUrl};this.bridge=new ee(e)}this.initializeBridgeSafely()}async initializeBridgeSafely(){try{await this.bridge.initialize()&&(this.isInitialized=!0)}catch(e){Ne.warn("Bridge initialization failed:",e)}this.waitReadyResolver(!0)}getFromLocalStorage(){try{if("undefined"==typeof localStorage)return null;if(!localStorage.getItem)return null;const e=localStorage.getItem(this.CACHE_KEY);if(!e)return null;const t=JSON.parse(e);return Date.now()-t.timestamp>this.CACHE_EXPIRY||t.lastVersion!==Ce?(localStorage.removeItem(this.CACHE_KEY),null):(Ne.debug("Device info loaded from localStorage cache"),t)}catch(e){return Ne.warn("Failed to load device info from localStorage:",e),null}}getFromURL(){try{const i=new URLSearchParams(window.location.search).get("titandata");if(!i)return null;let n=null;const r=new H;try{n=De.decompressFromEncodedURIComponent(i),n&&Ne.debug("Device info loaded from URL parameter (lz-string)")}catch(e){Ne.debug("lz-string decompression failed, trying base64")}if(!n)try{const e=r.get("atob");if(!e)return Ne.warn("atob function not available"),null;n=e(decodeURIComponent(i)),Ne.debug("Device info loaded from URL parameter (base64)")}catch(t){return Ne.warn("Both lz-string and base64 decoding failed"),null}if(!n)return Ne.warn("Failed to decode URL parameter"),null;return JSON.parse(n)}catch(i){return Ne.warn("Failed to load device info from URL parameter:",i),null}}saveToLocalStorage(e){try{if("undefined"==typeof localStorage)return;if(!(e&&e.deviceId&&e.brand&&e.model))return void Ne.warn("Skipping cache save - invalid or empty device info");const t={data:e,timestamp:Date.now(),lastVersion:Ce};localStorage.setItem(this.CACHE_KEY,JSON.stringify(t)),Ne.debug("Device info saved to localStorage cache")}catch(t){Ne.warn("Failed to save device info to localStorage:",t)}}async getBaseDeviceInfo(){const e=this.getFromURL();if(e)return this.saveToLocalStorage(e),this.waitReadyResolver(!0),{deviceInfo:e,tts:D,tm:C};if(!1!==this.config.useCache){const e=this.getFromLocalStorage();if(e)return this.waitReadyResolver(!0),{deviceInfo:e.data,tts:D,tm:C}}else this.config.debug&&Ne.debug("Debug mode: skipping cache, fetching fresh data from iframe");try{return await this.waitReady,await this.bridge.executeWithFallback((async()=>{const e=await this.bridge.getDeviceInfo();if(!e)throw new Error("Failed to get device info");return e.deviceInfo&&this.saveToLocalStorage(e.deviceInfo),e}),(async()=>{Ne.warn("Bridge unavailable, returning fallback device info");const e={deviceInfo:null,tts:D,tm:C};return _e("SDK_BRIDGE_FALLBACK","SDK","bridge.executeWithFallback",{reason:"bridge unavailable",platformId:this.getId(),isInitialized:this.isInitialized}),e}))}catch(t){return Ne.warn("Failed to get device info from bridge:",t),_e("SDK_BRIDGE_FALLBACK","SDK","bridge.executeWithFallback",{reason:"bridge exception",platformId:this.getId(),isInitialized:this.isInitialized,error:t instanceof Error?t.message:String(t)}),{deviceInfo:null,tts:D,tm:C}}}isTV(){return"undefined"!=typeof window&&(navigator.userAgent.includes("TV")||navigator.userAgent.includes("SmartTV")||navigator.userAgent.includes("SMART-TV")||window.location.href.includes("file://"))}}const xe=new H,He=new H;function Ue(){const e=document.createElement("video");return e.canPlayType&&"function"==typeof e.canPlayType?{supportAppleHLS:""!==e.canPlayType("application/vnd.apple.mpegURL")||""!==e.canPlayType("audio/mpegurl"),supportMSSmoothStreaming:""!==e.canPlayType("application/vnd.ms-sstr+xml"),supportMSSInitiator:""!==e.canPlayType("application/vnd.ms-playready.initiator+xml"),supportMPEG_DASH:""!==e.canPlayType("application/dash+xml")||"unknown"}:{supportAppleHLS:!1,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:"unknown"}}function Fe(){try{if(void 0!==xe.get("oipfObjectFactory"))return{supportOIPF:!0};const e=document.createElement("object");e.type="application/oipfdrmagent";return"function"==typeof e.sendDRMMessage?{supportOIPF:!0}:{supportOIPF:!1}}catch(e){return{supportOIPF:!1}}}function Ke(){try{const e=(new H).get("navigator"),t=void 0!==e&&"function"==typeof e.requestMediaKeySystemAccess,i=He.has("MSMediaKeys");return{supportWebSocket:He.has("WebSocket"),supportEME:t||i,hasStorage:He.has("localStorage")&&He.has("sessionStorage")}}catch(e){return{supportWebSocket:!1,supportEME:!1,hasStorage:!1}}}const Be=new H;function ze(){let e="";e=function(){try{const e=document.createElement("object");e.type="application/oipfdrmagent";return"function"==typeof e.sendDRMMessage?"OIPF":""}catch(e){return""}}();try{const t=Be.has("MediaKeys"),i=Be.has("WebKitMediaKeys"),n=Be.has("MSMediaKeys");return e=t||i||n?"EME":e,{drmMethod:e}}catch(t){return{drmMethod:""}}}function Ve(){try{const e=Be.has("MediaKeys"),t=Be.has("WebKitMediaKeys"),i=Be.has("MSMediaKeys");return{supportEME:e||t||i}}catch(e){return{supportEME:!1}}}const $e=d("PhilipsCapabilities");async function Ge(e){const t={os:"Linux",browserEngine:"Blink",supportPlayready:!0===await function(){const e=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}];return new Promise((t=>{try{navigator.requestMediaKeySystemAccess("com.microsoft.playready",e).then((()=>{t(!0)})).catch((()=>{t(!1)}))}catch(i){t(!1)}}))}()||"unknown",supportWidevineModular:!0===await function(){const e=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}];return new Promise((t=>{try{navigator.requestMediaKeySystemAccess("com.widevine.alpha",e).then((()=>{t(!0)})).catch((()=>{t(!1)}))}catch(i){t(!1)}}))}()||"unknown"},i=function(){try{const e={support3d:!1,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportUHD:!1,supportFHD:!0,supportHDR_HDR10:!1,supportHDR_DV:!1,supportHDR:"unknown",supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportAdobeHDS:!1,supportWidevineClassic:!1,supportDolbyAtmos:"unknown"},t=je.get("ols3DSupport");t&&t()&&(e.support3d=!0);const i=je.get("olsAtmosSupport");i&&i()&&(e.supportDolbyAtmos=!0),e.supportKeyNumeric=!0,e.supportKeyColor=!0,e.supportMultiscreen=!1,e.supportMultiAudio=!0,e.supportTTMLInband=!0,e.supportTTMLOutofband=!0,e.supportFHD=!0;const n=je.get("olsUHD");n&&n()&&(e.supportUHD=n()),e.supportHDR_HDR10=!0;const r=je.get("olsDVSupport");return r&&r()&&(e.supportHDR_DV=!0),e.supportHDR=e.supportHDR_HDR10||e.supportHDR_DV||!1,e}catch(e){return $e.error("Error detecting SmartTV API capabilities:",e),{support3d:!1,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportUHD:!1,supportFHD:!0,supportHDR_HDR10:!1,supportHDR_DV:!1,supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportAdobeHDS:!1,supportHDR:"unknown",supportWidevineClassic:!1,supportDolbyAtmos:"unknown"}}}();return{...t,...i,...Ke(),...Ue(),...ze(),...Ve(),...Fe(),supportFairplay:!1,supportPrimetime:!1,supportClearKey:!0}}const je=new H;const We=d("PhilipsCompat");class qe extends Le{deviceInfo=null;deviceInfoPromise=null;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"TPV",brand:"Philips"},Product:{platform:"TitanOS",year:"2025",deviceID:"philips-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:F(),language:"en"}};constructor(e,t){super(e,t)}async isSupported(){return this.isTV()}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["philips","saphi","nettv","tpvision"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{const e=await this.getBaseDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product},i=this.formatBridgeResponse(e,t),n=(i.Product.platform,await Ge());return{...i,Capability:n}}catch(e){throw We.error("Error getting device info:",e),e}}formatBridgeResponse(e,t){if(!e.deviceInfo)return t;let i=e.deviceInfo.platformName;e.deviceInfo.profileId&&(i=(e.deviceInfo.profileId.split("_")[1]||i).replace(/\d+$/,""));return t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country,t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=i,t.Product.language=e.deviceInfo.language,t.Product.mac=e.deviceInfo.mac,t.Product.mac||_e("SDK_BRIDGE_NO_MAC","SDK","formatBridgeResponse",{deviceInfo:e.deviceInfo}),t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.year=e.deviceInfo.year||"",t.Product.firmwareComponentID=i||"",t}getPriority(){return 100}getId(){return"philips"}}const Qe=d("PhilipsDeviceInfoService");class Je{platform;info;bridge;constructor(e,t){this.platform=new qe(e,t),this.bridge=t,this.info=null}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw Qe.error("Failed to get device info:",e),e}}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}const Ye=d("PhilipsAppControlService");class Ze{bridge;constructor(e){this.bridge=e}async launch(e,t){return await this.bridge.executeWithFallback((()=>this.bridge.launchApp({appId:e,deepLink:t})),(async()=>(Ye.warn("Function unavailable, app launch failed gracefully",{appId:e,deepLink:t}),!1)))}}const Xe=d("ChromeTTS");class et{voices=[];currentVoice=null;settings={available:!0,enabled:!0,rate:1,volume:1};speechSynthesis;constructor(){const e=new H;this.speechSynthesis=e.get("speechSynthesis"),this.speechSynthesis&&(this.initVoices(),"onvoiceschanged"in this.speechSynthesis&&(this.speechSynthesis.onvoiceschanged=()=>{this.initVoices()}))}initVoices(){var e,t,i,n,r,s;if(!("speechSynthesis"in window))return;const o=null==(e=this.speechSynthesis)?void 0:e.getVoices();this.voices=null==o?void 0:o.map((e=>({voiceName:e.name,lang:e.lang,gender:e.name.toLowerCase().includes("female")?"female":"male",remote:!1===e.localService}))),this.currentVoice=(null==(t=this.voices)?void 0:t.find((e=>"en-GB"===e.lang)))||(null==(i=this.voices)?void 0:i.find((e=>e.lang.startsWith("en-"))))||(null==(n=this.voices)?void 0:n[0]),Xe.info(`Initialized with ${null==(r=this.voices)?void 0:r.length} voices, using ${null==(s=this.currentVoice)?void 0:s.voiceName}`)}getTTSSettings(){return this.settings}getTMSettings(){return{available:!0,enabled:!1,scale:1}}getSettings(){return{tts:this.getTTSSettings(),tm:this.getTMSettings()}}startSpeaking(e){return Xe.info("Starting speaking:",e),!(!("speechSynthesis"in window)||!e||0===e.length)&&(e.forEach(((e,t)=>{var i,n,r,s;if(!e)return;const o=new SpeechSynthesisUtterance(e);if(o.rate=this.settings.rate??1,o.volume=this.settings.volume??1,o.lang=(null==(i=this.currentVoice)?void 0:i.lang)??"en-GB",this.currentVoice){const e=null==(n=this.speechSynthesis)?void 0:n.getVoices().find((e=>e.name===this.currentVoice.voiceName));e&&(o.voice=e)}0===t&&(null==(r=this.speechSynthesis)||r.cancel()),null==(s=this.speechSynthesis)||s.speak(o)})),!0)}stopSpeaking(){var e;return"speechSynthesis"in window&&(null==(e=this.speechSynthesis)||e.cancel(),!0)}stopSpeakingButKeepHighlightTask(){this.stopSpeaking()}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}sendTTSMessage(e){}}const tt=d("VestelTTS"),it=e=>({available:!0,enabled:e.enabled,rate:e.rate,pitch:e.pitch,volume:e.level});class nt extends et{vestelSettings={available:!0,enabled:!1,rate:1,volume:1};windowApi=new H;ttsCallbacks=new Set;tmCallbacks=new Set;settingsInitialized=!1;constructor(){super(),this.initializeSettings()}async initializeSettings(){var e,t;const i=this.windowApi.get("TTSHelper");if(!i)return void tt.warn("TTSHelper not available during initialization");const n={onSuccess:e=>{this.vestelSettings=it(e),this.settingsInitialized=!0},onError:e=>{tt.error("Error initializing TTS settings:",e),this.settingsInitialized=!0}},r={onSuccess:e=>{this.vestelSettings=it(e)},onError:e=>{tt.error("Error getting TTS info:",e)}};null==(e=i.getTextToSpeechSettings)||e.call(i,n,!1),null==(t=i.getTTSInfo)||t.call(i,r)}getTTSSettings(){var e;if(!this.settingsInitialized){const t=this.windowApi.get("TTSHelper");if(t){const i={onSuccess:e=>{tt.info("Current TTS settings:",e,e.toString()),this.vestelSettings=it(e)},onError:e=>{tt.error("Error getting current TTS settings:",e)}};null==(e=t.getTextToSpeechSettings)||e.call(t,i,!1)}}return this.vestelSettings}getTMSettings(){return{available:this.getTTSSettings().available,enabled:!1,scale:1}}getSettings(){return{tts:this.getTTSSettings(),tm:this.getTMSettings()}}stopSpeakingButKeepHighlightTask(){this.stopSpeaking()}onTTSSettingsChange(e){var t;const i=this.windowApi.get("TTSHelper");if(!i)return tt.warn("TTSHelper not available"),()=>{};const n={onSuccess:t=>{tt.info("TTS settings changed:",t,t.toString()),e(it(t)),this.settingsInitialized=!0},onError:e=>{tt.error("Error getting TTS settings:",e)}};return this.ttsCallbacks.add(n),null==(t=i.getTextToSpeechSettings)||t.call(i,n,!0),()=>{var e;i&&this.ttsCallbacks.has(n)&&(null==(e=i.unsubscribe)||e.call(i,n),this.ttsCallbacks.delete(n))}}onTMSettingsChange(e){this.tmCallbacks.add(e);const t=this.onTTSSettingsChange((t=>{const i={available:t.available,enabled:!1,scale:1};e(i)})),i=this.getTMSettings();return e(i),()=>{this.tmCallbacks.delete(e),t()}}destroy(){const e=this.windowApi.get("TTSHelper");e&&this.ttsCallbacks.forEach((t=>{var i;null==(i=e.unsubscribe)||i.call(e,t)})),this.ttsCallbacks.clear(),this.tmCallbacks.clear()}}const rt=d("AccessibilityService"),st=e=>{const{available:t,...i}=e;return i};class ot{tts;reader=null;constructor(){this.tts=new nt}async startSpeaking(e){if("string"==typeof e&&(e=[e]),await this.isTTSEnabled())try{return this.tts.startSpeaking(e),!0}catch(t){return rt.error("Error starting speaking:",t),!1}return!1}async stopSpeaking(){return await this.isTTSEnabled()&&this.tts.stopSpeaking(),!0}async enableReader(e){try{if(!(await this.isTTSSupported()))return rt.warn("Cannot enable Reader: TTS not supported"),!1;if(!(await this.isTTSEnabled()))return rt.warn("Cannot enable Reader: TTS not enabled"),!1;this.reader=new ge(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(rt.info("Reader enabled"),!0)}catch(t){return rt.error("Error enabling Reader:",t),!1}}async disableReader(){try{if(this.reader){const e=await this.reader.stop();return this.reader=null,e&&rt.info("Reader disabled"),e}return rt.debug("Reader was not active"),!0}catch(e){return rt.error("Error disabling Reader:",e),!1}}getReader(){if(!this.reader)throw new Error("Reader is not active");return this.reader}async isTTSSupported(){try{return(await this.getTTSSettings()).available}catch(e){return rt.error("Error checking TTS support:",e),!1}}async isTextMagnificationSupported(){try{return(await this.getTMSettings()).available}catch(e){return rt.error("Error checking magnification support:",e),!1}}onTTSSettingsChange(e){return this.tts.onTTSSettingsChange(e)}onTMSettingsChange(e){return this.tts.onTMSettingsChange(e)}async getTTSSettings(){return this.tts.getTTSSettings()}async getTMSettings(){return this.tts.getTMSettings()}async isTTSEnabled(){return(await this.getTTSSettings()).enabled}async isTMEnabled(){return(await this.getTMSettings()).enabled}}class at{subscribe(e,t){const i=u(e,t);return()=>{g(i)}}getHistory(){return h()}clear(){p()}}const ct=d("PhilipsSDK");class lt{bridge;accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new be,this.bridge=new ne({gatewayUrl:null==e?void 0:e.gatewayUrl,debug:null==e?void 0:e.debug}),this.deviceInfoService=new Je(e,this.bridge),this.appControlService=new Ze(this.bridge)}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>st(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>st(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(st(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(st(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new at}get dev(){return{isBridgeConnected:async()=>{try{return this.bridge.isConnected()}catch(e){return!1}}}}async init(){try{return await this.deviceInfo.getDeviceInfo(),!0}catch(e){throw ct.error("TitanSDK initialization failed:",e),e}}}function dt(e){const t=function(){var e;try{const t=document.createElement("object");t.setAttribute("id","sysinfo"),t.setAttribute("type","systeminfoobject"),document.body.appendChild(t);const i=t;return{support3d:Boolean(i.has3D),supportUHD:"3840x2160"===(null==(e=i.panelinfo)?void 0:e.toLowerCase()),supportFHD:!0}}catch(t){return{support3d:!1,supportUHD:!1,supportFHD:!0}}}(),i=Ke(),n=Ue(),r=ze(),s=Ve(),o=Fe(),a={os:"Linux",browserEngine:"Blink",hasStorage:!0,support3d:!1,supportUHD:!0,supportFHD:!0,supportHDR:!0,supportHDR_HDR10:!0,supportHDR_DV:!0,supportWebSocket:!0,supportPlayready:!0,supportWidevineModular:!0,supportAppleHLS:!0,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:!0,drmMethod:"widevine",supportOIPF:!1,supportEME:!0,supportKeyNumeric:!0,supportKeyColor:!0,supportFairplay:!1,supportAdobeHDS:!1,supportPrimetime:!1,supportClearKey:!0,supportWidevineClassic:!0,supportDolbyAtmos:!0,supportMultiscreen:!0,supportMultiAudio:!0,supportTTMLInband:!0,supportTTMLOutofband:!0};return"MB191"===e&&(a.supportHDR_DV=!1,a.supportHDR_HDR10=!0,a.supportDolbyAtmos=!1),{...a,...t,...i,...n,...r,...s,...o}}const ut=d("VestelCompat");class gt extends Le{deviceInfo=null;deviceInfoPromise=null;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"Vestel",brand:"JVC"},Product:{platform:"TitanOS",year:"2025",deviceID:"vestel-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:F(),language:"en"}};constructor(e,t){super(e,t)}async isSupported(){return this.isTV()}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["vestel"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{const e=await this.getBaseDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product},i=this.formatBridgeResponse(e,t),n=dt(i.Product.platform);return{...i,Capability:n}}catch(e){ut.error("Error getting device info:",e);const t=dt();return{Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product,Capability:t}}}formatBridgeResponse(e,t){return e.deviceInfo?(t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country.toUpperCase(),t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=e.deviceInfo.model,t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.mac=e.deviceInfo.mac,t.Product.year=e.deviceInfo.year||"",t):t}getPriority(){return 90}getId(){return"vestel"}}const ht=d("VestelDeviceInfoService");class pt{platform;info;bridge;constructor(e,t){this.platform=new gt(e,t),this.bridge=t,this.info=null}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw ht.error("Failed to get device info:",e),e}}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}const ft=d("VestelAppControlService");class mt{bridge;constructor(e){this.bridge=e}async launch(e,t){return await this.bridge.executeWithFallback((()=>this.bridge.launchApp({appId:e,deepLink:t})),(async()=>(ft.warn("Function unavailable, app launch failed gracefully",{appId:e,deepLink:t}),!1)))}}const vt=d("VestelSDK");class St{bridge;accessibilityService;deviceInfoService;appControlService;constructor(e){this.bridge=new te({gatewayUrl:null==e?void 0:e.gatewayUrl,debug:null==e?void 0:e.debug}),this.accessibilityService=new ot,this.deviceInfoService=new pt(e,this.bridge),this.appControlService=new mt(this.bridge)}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),getTTSSettings:async()=>st(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>st(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(st(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(st(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new at}get dev(){return{isBridgeConnected:async()=>{try{return this.bridge.isConnected()}catch(e){return!1}}}}async init(){try{return await this.deviceInfo.getDeviceInfo(),!0}catch(e){throw vt.error("TitanSDK initialization failed:",e),e}}}const bt="titanSDK_tts_settings",yt="titanSDK_tm_settings",wt=d("BrowserAccessibilityService"),Tt=e=>{const{available:t,...i}=e;return i};class Et{reader=null;chromeTTS;windowMock;mockStorage;ttsSettings;tmSettings;constructor(e,t,i=!1){this.windowMock=e,this.mockStorage=t,this.chromeTTS=new et,this.ttsSettings=this.loadTTSSettings(),this.tmSettings=this.loadTMSettings()}loadTTSSettings(){try{const e=localStorage.getItem(bt);if(e)return{...this.getDefaultTTSSettings(),...JSON.parse(e)}}catch(e){}return this.getDefaultTTSSettings()}loadTMSettings(){try{const e=localStorage.getItem(yt);if(e)return{...this.getDefaultTMSettings(),...JSON.parse(e)}}catch(e){}return this.getDefaultTMSettings()}getDefaultTTSSettings(){return{available:!0,enabled:!0,rate:1,volume:1}}getDefaultTMSettings(){return{available:!0,enabled:!1,scale:1}}saveTTSSettings(){try{localStorage.setItem(bt,JSON.stringify(this.ttsSettings))}catch(e){}}saveTMSettings(){try{localStorage.setItem(yt,JSON.stringify(this.tmSettings))}catch(e){}}async startSpeaking(e){try{if(!this.ttsSettings.enabled)return wt.info("TTS is disabled in settings"),!1;const t=Array.isArray(e)?e.join(" "):e,i=this.chromeTTS.startSpeaking([t]);return i&&wt.info("🔊 Speaking:",t),i}catch(t){return wt.error("Error starting speech:",t),!1}}async stopSpeaking(){try{const e=this.chromeTTS.stopSpeaking();return e&&wt.info("🔇 Speech stopped"),e}catch(e){return wt.error("Error stopping speech:",e),!1}}async enableReader(e){try{if(!(await this.isTTSSupported()))return wt.warn("Cannot enable Reader: TTS not supported"),!1;this.reader=new ge(e,this.startSpeaking.bind(this),this.stopSpeaking.bind(this));return!!(await this.reader.start())&&(wt.info("Reader enabled"),!0)}catch(t){return wt.error("Error enabling Reader:",t),!1}}async disableReader(){try{return!!this.reader&&(await this.reader.stop(),this.reader=null,wt.info("Reader disabled"),!0)}catch(e){return wt.error("Error disabling Reader:",e),!1}}getReader(){return this.reader}async isTTSSupported(){var e,t;return void 0!==(null==(t=null==(e=this.mockStorage)?void 0:e.features)?void 0:t.tts)?this.mockStorage.features.tts:"undefined"!=typeof window&&"speechSynthesis"in window}async isTextMagnificationSupported(){var e,t;return void 0===(null==(t=null==(e=this.mockStorage)?void 0:e.features)?void 0:t.magnification)||this.mockStorage.features.magnification}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}async getTTSSettings(){return{...this.ttsSettings}}async getTMSettings(){return{...this.tmSettings}}async isTTSEnabled(){const e=await this.getTTSSettings();return e.available&&e.enabled}async isTMEnabled(){const e=await this.getTMSettings();return e.available&&e.enabled}updateTTSSettings(e){this.ttsSettings={...this.ttsSettings,...e},this.saveTTSSettings(),wt.info("TTS settings updated:",this.ttsSettings)}updateTMSettings(e){this.tmSettings={...this.tmSettings,...e},this.saveTMSettings(),wt.info("TM settings updated:",this.tmSettings)}}const It=d("BrowserPlatform");class Dt extends ye{constructor(e){super(e),this.waitReady=new Promise((e=>{this.waitReadyResolver=e})),this.waitReadyResolver(!0)}async isSupported(){return!0}async canHandle(){return!0}async getDeviceInfo(){return It.debug("Getting default device info for browser"),this.getDefaultDeviceInfo()}getDefaultDeviceInfo(){return{Channel:{appStore:"browser",vendor:"browser",brand:"browser"},Product:{platform:"browser",year:(new Date).getFullYear().toString(),deviceID:"browser-"+Math.random().toString(36).substring(2,10),firmwareVersion:"unknown",firmwareComponentID:"unknown",mac:"unknown"},Capability:{os:(null==navigator?void 0:navigator.platform)||"unknown",browserEngine:this.detectBrowserEngine(),hasStorage:this.hasLocalStorage(),support3d:!1,supportUHD:!1,supportHDR:!1,supportWebSocket:"WebSocket"in window,supportPlayready:!1,supportWidevineModular:!1,supportAppleHLS:!1,supportMSSmoothStreaming:!1,supportMSSInitiator:!1,supportMPEG_DASH:!1,drmMethod:"",supportOIPF:!1,supportEME:"mediaKeys"in Document.prototype,supportKeyNumeric:!1,supportKeyColor:!1,supportMultiscreen:!1,supportFHD:!1,supportMultiAudio:!1,supportTTMLInband:!1,supportTTMLOutofband:!1,supportFairplay:!1,supportAdobeHDS:!1,supportPrimetime:!1,supportClearKey:!1,supportWidevineClassic:!1,supportDolbyAtmos:!1,supportHDR_HDR10:!1,supportHDR_DV:!1}}}detectBrowserEngine(){const e=navigator.userAgent;return e.includes("Chrome")?"Blink":e.includes("Firefox")?"Gecko":e.includes("Safari")?"WebKit":e.includes("Edge")?"EdgeHTML":e.includes("Trident")?"Trident":"unknown"}hasLocalStorage(){try{return"localStorage"in window&&null!==window.localStorage}catch(e){return!1}}getPriority(){return 10}getId(){return"browser"}}const Ct=d("BrowserDeviceInfoService");class Rt{platform;info;options;constructor(e,t,i){this.options=e,this.info=null;const n={debug:null==e?void 0:e.debug,timeout:(null==e?void 0:e.legacyDeviceInfoTimeout)||5e3,gatewayUrl:null==e?void 0:e.gatewayUrl,useCache:!0};this.platform=new Dt(n)}async getDeviceInfo(){try{const e=await this.platform.getDeviceInfo();return this.info=e,this.info}catch(e){throw Ct.error("Error getting device info:",e),e}}async getCapabilities(){try{return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}catch(e){throw Ct.error("Error getting device capabilities:",e),e}}}const At=d("BrowserAppControlService");class Pt{windowMock;constructor(e){this.windowMock=e}async launch(e,t){At.debug(`Launching app: ${e} with deepLink: ${t||"none"}`);const i=this.windowMock||window;if(!i||"function"!=typeof i.open)throw new s("Cannot open new window for app launch (window.open not available)",r.NOT_SUPPORTED,{operation:"launch",appId:e,deepLink:t,platform:"browser"});try{return i.open(t||e,"_blank"),At.info(`Opened new tab for app: ${e}`),!0}catch(n){throw At.error("Error opening new window for app launch:",n),new s(`Failed to launch app: ${e}`,r.COMMUNICATION_ERROR,{operation:"launch",appId:e,deepLink:t,platform:"browser",originalError:n})}}}const kt=d("BrowserSDK");class Mt{accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new Et(null==e?void 0:e.windowMock,null==e?void 0:e.mockStorage,(null==e?void 0:e.dev)||!1),this.deviceInfoService=new Rt(e,null==e?void 0:e.windowMock,null==e?void 0:e.mockStorage),this.appControlService=new Pt(null==e?void 0:e.windowMock),"undefined"!=typeof window&&Object.defineProperty(window,"titanSDK",{value:this,writable:!0,configurable:!0}),(null==e?void 0:e.debug)&&kt.debug("BrowserSDK constructor finished")}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>Tt(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>Tt(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>this.accessibilityService.onTTSSettingsChange((t=>{e(Tt(t))})),onTMSettingsChange:e=>this.accessibilityService.onTMSettingsChange((t=>{e(Tt(t))}))};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new at}get dev(){return{updateTTSSettings:e=>{this.accessibilityService.updateTTSSettings(e)},updateTMSettings:e=>{this.accessibilityService.updateTMSettings(e)}}}async init(){try{return kt.debug("BrowserSDK initialization started"),kt.info("BrowserSDK initialized successfully"),!0}catch(e){throw kt.error("BrowserSDK initialization failed:",e),e}}}const _t=d("AccessibilityService"),Ot=e=>{const{available:t,...i}=e;return i};class Nt{reader=null;async startSpeaking(e){return!1}async stopSpeaking(){return!1}async enableReader(e){return _t.warn("Cannot enable Reader: TTS not supported"),!1}async disableReader(){return!1}getReader(){return null}async isTTSSupported(){return!1}async isTextMagnificationSupported(){return!1}onTTSSettingsChange(e){return()=>{}}onTMSettingsChange(e){return()=>{}}async getTTSSettings(){return D}async getTMSettings(){return C}async isTTSEnabled(){return!1}async isTMEnabled(){return!1}}const Lt=d("PhilipsOldPlatform");class xt extends ye{deviceInfo=null;deviceInfoPromise=null;timeout=7e3;DEFAULT_DEVICE_INFO={Channel:{appStore:"TitanOS",vendor:"TPV",brand:"Philips"},Product:{platform:"TitanOS",year:"2023",deviceID:"philips-device",firmwareVersion:"1.0.0",firmwareComponentID:"",mac:"",WhaleAdID:F(),language:"en"}};constructor(e){super(e),this.waitReady=new Promise((e=>{this.waitReadyResolver=e})),this.waitReadyResolver(!0)}async isSupported(){return"undefined"!=typeof window&&(navigator.userAgent.includes("TV")||navigator.userAgent.includes("SmartTV")||navigator.userAgent.includes("SMART-TV")||window.location.href.includes("file://"))}async canHandle(){if(this.config.forcePlatform===this.getId())return!0;const e=navigator.userAgent.toLowerCase();return["philips","saphi","nettv","tpvision"].some((t=>e.includes(t)))}async getDeviceInfo(){if(this.deviceInfo)return this.deviceInfo;if(this.deviceInfoPromise)return await this.deviceInfoPromise;this.deviceInfoPromise=this.fetchDeviceInfoInternal();try{const e=await this.deviceInfoPromise;return this.deviceInfo=e,e}catch(e){throw this.deviceInfoPromise=null,e}}async fetchDeviceInfoInternal(){try{if(await this.waitReady){const e=await this.fetchDeviceInfo(),t={Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product};if(!e){const e=await Ge();return{...t,Capability:e}}const i=this.formatBridgeResponse({deviceInfo:e,tts:D,tm:C},t),n=(i.Product.platform,await Ge());return{...i,Capability:n}}const e=await Ge();return{Channel:this.DEFAULT_DEVICE_INFO.Channel,Product:this.DEFAULT_DEVICE_INFO.Product,Capability:e}}catch(e){throw Lt.warn("Error getting device info:",e),e}}async fetchDeviceInfo(){var e;try{const t="app.titanos.tv",i=await Promise.race([U(0,t,"zeasn"),new Promise((e=>{setTimeout((()=>{Lt.warn("Zeasn backend device info request timed out"),e(null)}),this.timeout)}))]);if(!i||!(null==(e=i.datas)?void 0:e.cookies))return null;const n=i.datas.cookies.profileid;return{profileId:n,deviceId:decodeURIComponent(i.datas.cookies.deviceid||""),model:i.datas.cookies.deviceYear||"",year:i.datas.cookies.deviceYear||"",firmwareVersion:i.datas.cookies.ufversion||"",country:i.datas.cookies.country||"",language:$("en"),brand:x.PHILIPS,platformName:x.PHILIPS,mac:decodeURIComponent(i.datas.cookies.mac||""),ifa:"",ifaType:""}}catch(t){return Lt.warn("Error fetching device info from backend",t),null}}formatBridgeResponse(e,t){let i="TitanOS",n="unknown";if(!e.deviceInfo)return t;if(e.deviceInfo.profileId&&(i=e.deviceInfo.platformName,e.deviceInfo.profileId)){var r=e.deviceInfo.profileId.split("_");i=(r[1]||i).replace(/\d+$/,""),n=r[1]?decodeURIComponent(r[1]):"unknown"}return t.Product.firmwareVersion=e.deviceInfo.firmwareVersion,t.Product.country=e.deviceInfo.country,t.Product.deviceID=e.deviceInfo.deviceId,t.Product.platform=i,t.Product.language=e.deviceInfo.language,t.Product.mac=e.deviceInfo.mac,t.Product.ifa=e.deviceInfo.ifa||"",t.Product.ifaType=e.deviceInfo.ifaType||"",t.Product.year=e.deviceInfo.year||"",t.Product.firmwareComponentID=n,t}getPriority(){return 100}getId(){return"philips"}}class Ht{platform;info;constructor(e){this.platform=new xt(e),this.info=null}async getDeviceInfo(){const e=await this.platform.getDeviceInfo();return this.info=e,this.info}async getCapabilities(){return this.info||(this.info=await this.getDeviceInfo()),this.info.Capability}}class Ut{async launch(e,t){return!1}}class Ft{accessibilityService;deviceInfoService;appControlService;constructor(e){this.accessibilityService=new Nt,this.deviceInfoService=new Ht(e),this.appControlService=new Ut}deviceInfo={getDeviceInfo:()=>this.deviceInfoService.getDeviceInfo(),getCapabilities:()=>this.deviceInfoService.getCapabilities()};accessibility={enableReader:e=>this.accessibilityService.enableReader(e),disableReader:()=>this.accessibilityService.disableReader(),isTTSSupported:()=>this.accessibilityService.isTTSSupported(),isTTSEnabled:()=>this.accessibilityService.isTTSEnabled(),isTMEnabled:()=>this.accessibilityService.isTMEnabled(),isTextMagnificationSupported:()=>this.accessibilityService.isTextMagnificationSupported(),getTTSSettings:async()=>Ot(await this.accessibilityService.getTTSSettings()),getTMSettings:async()=>Ot(await this.accessibilityService.getTMSettings()),startSpeaking:e=>this.accessibilityService.startSpeaking(e),stopSpeaking:()=>this.accessibilityService.stopSpeaking(),onTTSSettingsChange:e=>()=>{},onTMSettingsChange:e=>()=>{}};apps={launch:(e,t)=>this.appControlService.launch(e,t)};get logging(){return new at}async init(){return!0}}const Kt=d("SmartTvA_API"),Bt=(e,t)=>{var i,n,r,s;try{if(!t)return Kt.warn(`Device info not available, cannot check capability: ${e}`),!1;const o=t.Product||{},a=t.Channel||{},c=t.Capability||{};switch(e){case"3d":return Boolean(c.support3d);case"uhd":return Boolean(c.supportUHD);case"dolby-vision":return Boolean(c.supportHDR&&((null==(i=o.platform)?void 0:i.toLowerCase().includes("dolby"))||(null==(n=a.brand)?void 0:n.toLowerCase().includes("dolby"))));case"atmos":return Boolean((null==(r=o.platform)?void 0:r.toLowerCase().includes("atmos"))||(null==(s=a.brand)?void 0:s.toLowerCase().includes("dolby")));default:return Kt.warn(`Unknown device capability: ${e}`),!1}}catch(o){return Kt.error(`Error checking device capability ${e}:`,o),!1}},zt=async e=>{if("undefined"==typeof window)return void Kt.warn("Window object not available, cannot attach SmartTvA_API");if("object"==typeof window.SmartTvA_API)return void Kt.info("SmartTvA_API already exists on window, skipping initialization");const t=await(async e=>{Kt.info("Initializing SmartTvA_API with TitanSDK");let t=null;try{Kt.info("Waiting for device info to be ready..."),t=await e.deviceInfo.getDeviceInfo(),Kt.info("Device info is ready, proceeding with SmartTvA_API initialization")}catch(i){Kt.warn("Failed to get device info during SmartTvA_API initialization:",i)}return{exit:()=>{Kt.info("SmartTvA_API.exit() called"),window.close()},hasCapability:(e,...i)=>{switch(Kt.debug(`SmartTvA_API.hasCapability('${e}', ${i.join(", ")})`),e){case"3DSupport":return Bt("3d",t);case"MultiScreen":return 1===i.length&&i[0],!1;case"DRM":if(2===i.length){const[e,t]=i;if("PlayReady"===e&&"DASH"===t)return!0;if("Widevine"===e&&"AdaptiveStreaming"===t)return!1}return!1;case"Key":if(1===i.length)switch(i[0]){case"numerickeys":case"colorkeys":case"prev_next":return!0;default:return!1}return!1;case"UHD":return Bt("uhd",t);case"FHD":case"Multiaudio":return!0;case"TTML":if(1===i.length)switch(i[0]){case"inband":case"outofband":case"EBU-TT-D":case"CFF-TT":return!0;default:return!1}return!1;case"HLS":return 1===i.length&&"DISCONTINUITY"===i[0];case"HDR":if(1===i.length){const e=i[0];if(!Bt("uhd",t))return!1;switch(e){case"HDR10":case"DA":case"HDR10+":return!0;case"DV":return Bt("dolby-vision",t);default:return!1}}return!1;case"8K":case"WidevineClassic":case"AdobeHDS":return!1;case"ATMOS":return Bt("atmos",t);default:return Kt.warn(`Unknown capability requested: ${e}`),!1}}}})(e);Object.defineProperty(window,"SmartTvA_API",{value:t,writable:!1,configurable:!0}),Kt.info("SmartTvA_API successfully attached to window object")},Vt=d("WrapperUtils");function $t(e){return{getTTSSettings:async()=>(await e()).accessibility.getTTSSettings(),getTMSettings:async()=>(await e()).accessibility.getTMSettings(),isTTSSupported:async()=>(await e()).accessibility.isTTSSupported(),isTTSEnabled:async()=>(await e()).accessibility.isTTSEnabled(),isTMEnabled:async()=>(await e()).accessibility.isTMEnabled(),isTextMagnificationSupported:async()=>(await e()).accessibility.isTextMagnificationSupported(),startSpeaking:async t=>(await e()).accessibility.startSpeaking(t),stopSpeaking:async()=>(await e()).accessibility.stopSpeaking(),enableReader:async t=>(await e()).accessibility.enableReader(t),disableReader:async()=>(await e()).accessibility.disableReader(),onTTSSettingsChange:t=>{let i=null;return e().then((e=>{i=e.accessibility.onTTSSettingsChange(t)})).catch((e=>{Vt.error("Failed to set up TTS settings change handler:",e)})),()=>{i&&i()}},onTMSettingsChange:t=>{let i=null;return e().then((e=>{i=e.accessibility.onTMSettingsChange(t)})).catch((e=>{Vt.error("Failed to set up TM settings change handler:",e)})),()=>{i&&i()}}}}function Gt(e){return{launch:async(t,i)=>(await e()).apps.launch(t,i)}}const jt=d("AnalyticsService");class Wt{sdkVersion;constructor(e){this.sdkVersion=e}getEventUrl(){return"https://sdk.titanos.tv/events"}async track(e){if("undefined"==typeof window||void 0===window.fetch)return Promise.resolve();try{const t={event_name:e.eventName,event_type:e.eventType,event_params:e.eventParams,event_timestamp:(new Date).toISOString().replace("T"," ").slice(0,-1)};await window.fetch(this.getEventUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(t){jt.warn("TitanSDK: Usage tracking event failed to send.",t)}}trackUsage(){const e={eventName:"sdk",eventType:"sdk-initialized",eventParams:{appHostname:window.location.hostname,sdkVersion:this.sdkVersion}};return this.track(e)}}const qt=d("SDK"),Qt={debug:!1,useLegacyDeviceInfo:!1,legacyDeviceInfoTimeout:5e3,fallbackToBrowser:!0},Jt="TITAN_SDK_USAGE_SENT";let Yt=null,Zt=null,Xt=null,ei=null,ti=!1;const ii=async()=>{if(!Yt)throw new s("SDK not created. Call getTitanSDK() first.",r.NOT_INITIALIZED);if(!Xt)throw qt.error("SDK initialization not started"),new s("SDK initialization not started.",r.NOT_INITIALIZED);if(!(await Xt))throw new s("SDK initialization failed.",r.UNKNOWN);return Yt},ni=e=>{if(Zt)return Zt;const t={...Qt,...e};if(c.setDebugMode(t.debug??!1),!ti){const e="",t=!1;Pe.initialize({accessToken:e,enabled:t}),ti=!0}const i=T.detectPlatform(t).platform;qt.info("Platform detected:",i);try{switch(i){case n.PHILIPS:Yt=new lt(t);break;case n.PHILIPS_OLD:Yt=new Ft(t);break;case n.VESTEL:Yt=new St(t);break;case n.BROWSER:default:i!==n.BROWSER&&t.debug&&qt.warn(`Platform ${i} detected but no specific SDK found, using BrowserSDK as fallback.`),Yt=new Mt(t)}if(!Yt)throw new s("Failed to create SDK instance after platform detection",r.UNKNOWN)}catch(d){throw qt.error("Error creating SDK instance:",d),new s(`Failed to create SDK instance after platform detection: ${d}`,r.UNKNOWN)}Xt=Yt.init(),qt.info("SDK Version:",Ce);const o={VERSION:Ce,isReady:Xt,deviceInfo:(a=ii,l=e=>{ei=e},{getDeviceInfo:async()=>{const e=await a(),t=await e.deviceInfo.getDeviceInfo();return null==l||l(t),t}}),accessibility:$t(ii),apps:Gt(ii)};var a,l;return t.debug&&(qt.info("🔧 [DEBUG MODE] TitanSDK debug access enabled"),o.logging=function(e){let t=null;return{subscribe:(i,n)=>{let r=null;return e().then((e=>{t=e,e.logging&&(r=e.logging.subscribe(i,n))})).catch((e=>{Vt.error("Failed to set up logging subscription:",e)})),()=>{r&&r()}},getHistory:()=>(null==t?void 0:t.logging)?t.logging.getHistory():[],clear:()=>{(null==t?void 0:t.logging)&&t.logging.clear()}}}(ii)),t.dev&&(t.debug&&qt.info("🔧 [DEV MODE] TitanSDK dev access enabled"),i===n.BROWSER&&t.dev&&(qt.info("Available dev methods:"),qt.info(" sdk.dev.updateTTSSettings({ enabled: true, rate: 1.5 })"),qt.info(" sdk.dev.updateTMSettings({ enabled: true, scale: 1.8 })")),o.dev=function(e){return{updateTTSSettings:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.updateTTSSettings)?void 0:n.call(i,t)},updateTMSettings:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.updateTMSettings)?void 0:n.call(i,t)},simulateError:async t=>{var i,n;return null==(n=null==(i=(await e()).dev)?void 0:i.simulateError)?void 0:n.call(i,t)},simulateGatewayError:async(t,i)=>{var n,r;return null==(r=null==(n=(await e()).dev)?void 0:n.simulateGatewayError)?void 0:r.call(n,t,i)},isBridgeConnected:async()=>{var t,i;return(null==(i=null==(t=(await e()).dev)?void 0:t.isBridgeConnected)?void 0:i.call(t))??!1}}}(ii)),Zt=o,Xt.then((async()=>{try{ei=await Yt.deviceInfo.getDeviceInfo();const e=new Wt(Ce);if(!(()=>{try{return!("undefined"==typeof window||!window.localStorage)&&"1"===window.localStorage.getItem(Jt)}catch{return!1}})())try{await e.trackUsage(),(()=>{try{if("undefined"==typeof window||!window.localStorage)return;window.localStorage.setItem(Jt,"1")}catch{}})()}catch{}}catch(d){t.debug&&qt.warn("Failed to pre-cache device info:",d)}})).catch((e=>{qt.error(`Initialization failed for platform ${i}:`,e)})),Zt},ri=async()=>{const e=await ii(),t=await e.deviceInfo.getDeviceInfo();return ei=t,t};if("undefined"!=typeof document&&document.addEventListener("securitypolicyviolation",(e=>{Y.getViolations()})),"undefined"!=typeof window)if(window.TitanSDK&&window.TitanSDK.deviceInfo)qt.info("TitanSDK already exists on window, skipping initialization"),qt.info("You can still create a new SDK instance using window.getTitanSDK(options)"),window.getTitanSDK=ni;else{const e=()=>{window.onDeviceInfoReady=function(e){ri().then((t=>e(t))).catch((t=>e({},String(t))))},Object.defineProperty(window,"DeviceInfo",{get:()=>{if(ei)return ei;if(Yt&&Zt)try{return Yt.deviceInfo.getDeviceInfo()}catch{return null}return null},configurable:!0}),void 0===window.SmartTvA_API&&Object.defineProperty(window,"SmartTvA_API",{value:{exit:()=>window.close()},writable:!1,configurable:!0})},t=e=>{try{const t=null==localStorage?void 0:localStorage.getItem(e);return t?JSON.parse(t):{}}catch(t){return c.isDebugMode()&&qt.error(`Failed to parse localStorage key ${e}:`,t),{}}},i=(new H).get("TITAN_SDK_PARAMS")||t("TITAN_SDK_PARAMS");i&&qt.info("Initializing TitanSDK with params:",i),window.TitanSDK=ni(i),e(),zt(window.TitanSDK).catch((e=>{qt.error("Failed to initialize SmartTvA_API:",e)}))}e.VERSION=Ce,e.getDeviceInfo=ri,e.getTitanSDK=ni,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));