@xiboplayer/pwa 0.7.1 → 0.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/assets/{chunk-config-DqswDQz2.js → chunk-config-BqpCSJ87.js} +2 -2
- package/dist/assets/{chunk-config-DqswDQz2.js.map → chunk-config-BqpCSJ87.js.map} +1 -1
- package/dist/assets/{index-Bn7yexJC.js → index-BBp7Yeqp.js} +2 -2
- package/dist/assets/{index-Bn7yexJC.js.map → index-BBp7Yeqp.js.map} +1 -1
- package/dist/assets/{index-DOWqpi1W.js → index-BGzZpdzW.js} +2 -2
- package/dist/assets/{index-DOWqpi1W.js.map → index-BGzZpdzW.js.map} +1 -1
- package/dist/assets/{index-K17x7fv_.js → index-Bj01q2d4.js} +2 -2
- package/dist/assets/{index-K17x7fv_.js.map → index-Bj01q2d4.js.map} +1 -1
- package/dist/assets/{index-Bgo3B90-.js → index-BmnGgxhy.js} +2 -2
- package/dist/assets/{index-Bgo3B90-.js.map → index-BmnGgxhy.js.map} +1 -1
- package/dist/assets/{index-DYMccG7M.js → index-DNyHrXGf.js} +2 -2
- package/dist/assets/{index-DYMccG7M.js.map → index-DNyHrXGf.js.map} +1 -1
- package/dist/assets/{index--0TbPToz.js → index-DPUPuUO8.js} +2 -2
- package/dist/assets/{index--0TbPToz.js.map → index-DPUPuUO8.js.map} +1 -1
- package/dist/assets/index-DwQpyIXq.js +2 -0
- package/dist/assets/{index-xijlgGv2.js.map → index-DwQpyIXq.js.map} +1 -1
- package/dist/assets/{index-CpSQnOTy.js → index-O4mn_OO0.js} +2 -2
- package/dist/assets/{index-CpSQnOTy.js.map → index-O4mn_OO0.js.map} +1 -1
- package/dist/assets/{index-CdHwqlmo.js → index-mYGuS183.js} +2 -2
- package/dist/assets/{index-CdHwqlmo.js.map → index-mYGuS183.js.map} +1 -1
- package/dist/assets/{index-9iMTvtYp.js → index-zursmDNN.js} +2 -2
- package/dist/assets/{index-9iMTvtYp.js.map → index-zursmDNN.js.map} +1 -1
- package/dist/assets/{main-Brs62d3-.js → main-Ddgs1h5h.js} +4 -4
- package/dist/assets/main-Ddgs1h5h.js.map +1 -0
- package/dist/assets/{protocol-detector-TSZru2q-.js → protocol-detector-UOvkmuFn.js} +2 -2
- package/dist/assets/{protocol-detector-TSZru2q-.js.map → protocol-detector-UOvkmuFn.js.map} +1 -1
- package/dist/assets/{setup-C2E5DwAO.js → setup-DcthBcbI.js} +2 -2
- package/dist/assets/{setup-C2E5DwAO.js.map → setup-DcthBcbI.js.map} +1 -1
- package/dist/assets/{sync-manager-C-mx1NcP.js → sync-manager-4de0XUYN.js} +2 -2
- package/dist/assets/{sync-manager-C-mx1NcP.js.map → sync-manager-4de0XUYN.js.map} +1 -1
- package/dist/assets/{widget-html-7qheOFv5.js → widget-html-p3dC5HGH.js} +2 -2
- package/dist/assets/{widget-html-7qheOFv5.js.map → widget-html-p3dC5HGH.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +16 -14
- package/dist/assets/index-xijlgGv2.js +0 -2
- package/dist/assets/main-Brs62d3-.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
var Ue=Object.defineProperty;var qe=(p,e,t)=>e in p?Ue(p,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[e]=t;var $=(p,e,t)=>qe(p,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{createLogger as V,EventEmitter as de,PLAYER_API as H,isDebug as Ne,fetchWithRetry as Be,applyCmsLogLevel as He,openIDB as Ve,config as ze,registerLogSink as ge}from"./index-Bgo3B90-.js";import{c as je,C as Ge,D as Ke,B as fe,S as Xe}from"./widget-html-7qheOFv5.js";const Qe="modulepreload",Ye=function(p,e){return new URL(p,e).href},ye={},N=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){const s=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),a=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(l=>{if(l=Ye(l,i),l in ye)return;ye[l]=!0;const d=l.endsWith(".css"),c=d?'[rel="stylesheet"]':"";if(!!i)for(let m=s.length-1;m>=0;m--){const w=s[m];if(w.href===l&&(!d||w.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${c}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Qe,d||(h.as="script"),h.crossOrigin="",h.href=l,a&&h.setAttribute("nonce",a),document.head.appendChild(h),d)return new Promise((m,w)=>{h.addEventListener("load",m),h.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=s,window.dispatchEvent(r),!r.defaultPrevented)throw s}return n.then(s=>{for(const r of s||[])r.status==="rejected"&&o(r.reason);return e().catch(o)})},se=V("schedule:criteria"),Je=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pe={weatherTemp:"temperature",weatherHumidity:"humidity",weatherWindSpeed:"windSpeed",weatherCondition:"condition",weatherCloudCover:"cloudCover"};function Ze(p,e,t={},i={}){switch(p){case"dayOfWeek":return Je[e.getDay()];case"dayOfMonth":return String(e.getDate());case"month":return String(e.getMonth()+1);case"hour":return String(e.getHours());case"isoDay":return String(e.getDay()===0?7:e.getDay());default:if(pe[p]){const n=pe[p];return i[n]!==void 0?String(i[n]):(se.debug(`Weather metric "${p}" requested but no weather data available`),null)}return t[p]!==void 0?String(t[p]):(se.debug(`Unknown metric: ${p}`),null)}}function et(p,e,t,i){if(p===null)return!1;if(i==="number"){const s=parseFloat(p),r=parseFloat(t);if(isNaN(s)||isNaN(r))return!1;switch(e){case"equals":return s===r;case"notEquals":return s!==r;case"greaterThan":return s>r;case"greaterThanOrEquals":return s>=r;case"lessThan":return s<r;case"lessThanOrEquals":return s<=r;default:return!1}}const n=p.toLowerCase(),o=t.toLowerCase();switch(e){case"equals":return n===o;case"notEquals":return n!==o;case"contains":return n.includes(o);case"notContains":return!n.includes(o);case"startsWith":return n.startsWith(o);case"endsWith":return n.endsWith(o);case"in":return o.split(",").map(s=>s.trim().toLowerCase()).includes(n);case"greaterThan":return n>o;case"lessThan":return n<o;default:return se.debug(`Unknown condition: ${e}`),!1}}function ce(p,e={}){if(!p||p.length===0)return!0;const t=e.now||new Date,i=e.displayProperties||{},n=e.weatherData||{};for(const o of p){const s=Ze(o.metric,t,i,n);if(!et(s,o.condition,o.value,o.type))return se.debug(`Criteria failed: ${o.metric} ${o.condition} "${o.value}" (actual: "${s}")`),!1}return!0}function q(p){return parseInt(String(p).replace(".xlf",""),10)}function We(p,e=null){const i=new DOMParser().parseFromString(p,"text/xml").querySelector("layout");if(!i)return{duration:60,isDynamic:!1};const n=parseInt(i.getAttribute("duration")||"0",10);if(n>0)return{duration:n,isDynamic:!1};let o=0,s=!1;for(const a of i.querySelectorAll("region")){const l=a.getAttribute("type");if(l==="drawer")continue;const d=l==="canvas";let c=0;for(const g of a.querySelectorAll("media")){const h=parseInt(g.getAttribute("duration")||"0",10),m=parseInt(g.getAttribute("useDuration")||"1",10),w=g.getAttribute("fileId")||"",y=e==null?void 0:e.get(w);let b;y!==void 0?b=y:h>0&&m!==0?b=h:(b=60,s=!0),d?c=Math.max(c,b):c+=b}o=Math.max(o,c)}return{duration:o>0?o:60,isDynamic:s}}function tt(p,e){if(p.length!==e.length)return!1;for(let t=0;t<p.length;t++)if(p[t]!==e[t])return!1;return!0}function it(p,e,t){if(!e||e===0)return!0;const i=t-36e5,n=p.filter(o=>o>i);if(n.length>=e)return!1;if(n.length>0){const o=36e5/e,s=Math.max(...n);if(t-s<o)return!1}return!0}function me(p,e,t){const i=p.filter(o=>{if(!o.maxPlaysPerHour||o.maxPlaysPerHour===0)return!0;const s=e.get(o.file)||[];return it(s,o.maxPlaysPerHour,t)});if(i.length===0)return[];const n=Math.max(...i.map(o=>o.priority));return i.filter(o=>o.priority===n).map(o=>o.file)}function nt(p,e,t={}){const i=t.from||new Date,n=t.hours||2,o=new Date(i.getTime()+n*36e5);t.currentLayoutStartedAt;const s=t.defaultLayout||null,r=t.durations||null;if(!p||p.length===0)return[];const a=[];let l=new Date(i),d=e%p.length;const c=500;for(;l<o&&a.length<c;){const g=p[d];let h=r&&r.get(g.layoutId)||g.duration;const m=l.getTime()+h*1e3;a.push({layoutFile:g.layoutId,startTime:new Date(l),endTime:new Date(m),duration:h,isDefault:s?g.layoutId===s:!1}),l=new Date(m),d=(d+1)%p.length}return a}function ot(p,e){for(p=Math.abs(Math.round(p)),e=Math.abs(Math.round(e));e;)[p,e]=[e,p%e];return p}function st(p,e){return p===0||e===0?0:Math.abs(Math.round(p)*Math.round(e))/ot(p,e)}function rt(p){return p.reduce((e,t)=>st(e,t),1)}function at(p,e,t={}){const{defaultLayout:i=null,defaultDuration:n=60}=t;if(p.length===0&&!i)return{queue:[],periodSeconds:0};const o=new Map;for(const m of p)m.duration>0&&o.set(m.file,m.duration);const s=m=>e.get(m)||o.get(m)||n,r=p.filter(m=>m.maxPlaysPerHour>0);let a;if(r.length>0){const m=r.map(w=>Math.round(3600/w.maxPlaysPerHour));a=rt(m),a>7200&&(a=7200)}else a=p.reduce((w,y)=>w+s(y.file),0)+(i&&!p.some(w=>w.file===i)?s(i):0)||n;const l=[],d=new Map;let c=0;const g=a*1e3,h=500;for(;c<g&&l.length<h;){const m=me(p,d,c);if(m.length===0){if(i){const w=s(i);l.push({layoutId:i,duration:w}),c+=w*1e3}else c+=6e4;continue}for(let w=0;w<m.length&&c<g&&l.length<h;w++){const y=m[w],b=s(y);l.push({layoutId:y,duration:b}),d.has(y)||d.set(y,[]),d.get(y).push(c),c+=b*1e3;const C=me(p,d,c);if(!tt(m,C))break}}if(l.length===0&&i){const m=s(i);l.push({layoutId:i,duration:m})}return{queue:l,periodSeconds:a}}const B=V("Schedule");class lt{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){var e;return((e=this.schedule)==null?void 0:e.dataConnectors)||[]}getDependantsMap(){const e=new Map;if(!this.schedule)return e;const t=this.schedule.dependants||[],i=n=>{const o=q(n.file||n.id),s=[...t,...n.dependants||[]];s.length>0&&e.set(o,s)};if(this.schedule.layouts)for(const n of this.schedule.layouts)i(n);if(this.schedule.campaigns)for(const n of this.schedule.campaigns)for(const o of n.layouts)i(o);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange){const i=new Date(e.recurrenceRange);if(t>i)return!1}switch(e.recurrenceType){case"Week":{if(e.recurrenceRepeatsOn){const i=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(",").map(o=>parseInt(o.trim())).includes(i))return!1}return!0}case"Day":{const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=t.getTime()-n.getTime(),s=Math.floor(o/864e5);if(s<0||s%i!==0)return!1}return!0}case"Month":{if(e.recurrenceRepeatsOn){const n=e.recurrenceRepeatsOn.split(",").map(s=>parseInt(s.trim())),o=t.getDate();if(!n.includes(o))return!1}const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();if(o<0||o%i!==0)return!1}return!0}default:return B.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){const t=e.getDay();return t===0?7:t}isTimeActive(e,t){const i=e.fromdt?new Date(e.fromdt):null,n=e.todt?new Date(e.todt):null;if(e.recurrenceType==="Week"||e.recurrenceType==="Day"||e.recurrenceType==="Month"){if(i&&n){const o=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),s=i.getHours()*3600+i.getMinutes()*60+i.getSeconds(),r=n.getHours()*3600+n.getMinutes()*60+n.getSeconds();return s<=r?o>=s&&o<=r:o>=s||o<=r}return!0}return!(i&&t<i||n&&t>n)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];const t=e,i=[];if(this.schedule.layouts)for(const n of this.schedule.layouts)this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t)&&(n.criteria&&n.criteria.length>0&&!ce(n.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||n.isGeoAware&&n.geoLocation&&!this.isWithinGeoFence(n.geoLocation)||i.push({file:n.file,priority:n.priority||0,maxPlaysPerHour:n.maxPlaysPerHour||0,duration:n.duration||0}));if(this.schedule.campaigns){for(const n of this.schedule.campaigns)if(this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t))for(const o of n.layouts)i.push({file:o.file,priority:n.priority||0,maxPlaysPerHour:o.maxPlaysPerHour||0,duration:o.duration||0})}return i}detectConflicts(e={}){const t=e.from||new Date,i=e.hours||24,n=new Date(t.getTime()+i*36e5),o=6e4,s=[];let r=null;for(let a=t.getTime();a<n.getTime();a+=o){const l=new Date(a),d=this.getAllLayoutsAtTime(l);if(d.length===0){r&&(s.push(r),r=null);continue}const c=Math.max(...d.map(y=>y.priority)),g=d.filter(y=>y.priority<c);if(g.length===0){r&&(s.push(r),r=null);continue}const h=d.filter(y=>y.priority===c),m=h.map(y=>y.file).sort().join(","),w=g.map(y=>`${y.file}:${y.priority}`).sort().join(",");r&&r._winnerKey===m&&r._hiddenKey===w?r.endTime=new Date(a+o):(r&&s.push(r),r={startTime:new Date(a),endTime:new Date(a+o),winner:{file:h[0].file,priority:c},hidden:g.map(y=>({file:y.file,priority:y.priority})),_winnerKey:m,_hiddenKey:w})}r&&s.push(r);for(const a of s)delete a._winnerKey,delete a._hiddenKey;return s}_getLayoutsAt(e,t={}){if(!this.schedule)return[];const{skipRateLimiting:i=!1,skipInterrupts:n=!1,quiet:o=!1}=t,s=o?()=>{}:(...c)=>B.info(...c),r=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(const c of this.schedule.campaigns)this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),r.push({type:"campaign",priority:c.priority,layouts:c.layouts,campaignId:c.id}));if(this.schedule.layouts){for(const c of this.schedule.layouts)if(this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)){if(c.criteria&&c.criteria.length>0&&!ce(c.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){s("[Schedule] Layout",c.id,"filtered by criteria");continue}if(c.isGeoAware&&c.geoLocation&&!this.isWithinGeoFence(c.geoLocation)){s("[Schedule] Layout",c.id,"filtered by geofence");continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),!i&&!this.canPlayLayout(c.id,c.maxPlaysPerHour)){s("[Schedule] Layout",c.id,"filtered by maxPlaysPerHour (limit:",c.maxPlaysPerHour,")");continue}r.push({type:"layout",priority:c.priority||0,layouts:[c],layoutId:c.id})}}if(r.length===0)return this.schedule.default?[this.schedule.default]:[];let a=Math.max(...r.map(c=>c.priority));s("[Schedule] Max priority:",a,"from",r.length,"active items");let l=[];for(const c of r)c.priority===a?(s("[Schedule] Including priority",c.priority,"layouts:",c.layouts.map(g=>g.file)),l.push(...c.layouts)):s("[Schedule] Skipping priority",c.priority,"< max",a);this._layoutMetadata.clear();for(const c of l)this._layoutMetadata.set(c.file,{syncEvent:c.syncEvent||!1,shareOfVoice:c.shareOfVoice||0,scheduleid:c.scheduleid,priority:c.priority||0});if(!n&&this.interruptScheduler){const{normalLayouts:c,interruptLayouts:g}=this.interruptScheduler.separateLayouts(l);if(g.length>0){s("[Schedule] Found",g.length,"interrupt layouts with shareOfVoice");const m=this.interruptScheduler.processInterrupts(c,g).map(w=>w.file);return s("[Schedule] Final layouts (with interrupts):",m),m}}const d=l.map(c=>c.file);return s("[Schedule] Final layouts:",d),d}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){if(!t||t===0)return!0;const i=Date.now(),n=i-60*60*1e3,s=(this.playHistory.get(e)||[]).filter(r=>r>n);if(s.length>=t)return B.info(`Layout ${e} has reached max plays per hour (${s.length}/${t})`),!1;if(s.length>0){const r=36e5/t,a=Math.max(...s),l=i-a;if(l<r){const d=((r-l)/6e4).toFixed(1);return B.info(`Layout ${e} spacing: next play in ${d} min (${s.length}/${t} plays, ${Math.round(r/6e4)} min gap)`),!1}}return!0}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);const t=this.playHistory.get(e);t.push(Date.now());const i=Date.now()-60*60*1e3,n=t.filter(o=>o>i);this.playHistory.set(e,n),B.info(`Recorded play for layout ${e} (${n.length} plays in last hour)`)}getMaxActivePriority(){return this._maxActivePriority||0}isSyncEvent(e){const t=this._layoutMetadata.get(e);return(t==null?void 0:t.syncEvent)===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){var r;const i=this.getAllLayoutsAtTime(new Date),n=i.map(a=>`${a.file}:${a.priority}:${a.maxPlaysPerHour}`).sort().join("|");if(this._scheduleQueue&&this._queueLayoutSet===n)return this._scheduleQueue;const o=at(i,e,{defaultLayout:((r=this.schedule)==null?void 0:r.default)||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),s=this._queueLayoutSet;return this._scheduleQueue=o,this._queueLayoutSet=n,s!==n&&(this._queuePosition=0),o.queue.length>0&&(B.info(`[Schedule] Built queue: ${o.queue.length} entries, period ${o.periodSeconds}s (pos ${this._queuePosition})`),B.info(`[Schedule] Queue: ${o.queue.map(a=>`${a.layoutId}(${a.duration}s)`).join(" → ")}`)),o}popNextFromQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);if(i.length===0)return null;const n=i[this._queuePosition%i.length];return this._queuePosition=(this._queuePosition+1)%i.length,n}getQueuePosition(){return this._queuePosition}rewindQueue(e,t,i={}){const{queue:n}=this.getScheduleQueue(t,i);if(n.length===0)return null;this._queuePosition=(this._queuePosition-e+n.length*e)%n.length;const o=n[this._queuePosition];return this._queuePosition=(this._queuePosition+1)%n.length,o}peekNextInQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length===0?null:i[this._queuePosition%i.length]}peekAfterNext(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length<=1?null:i[(this._queuePosition+1)%i.length]}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(const e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){var t;if(!((t=this.schedule)!=null&&t.actions))return[];const e=new Date;return this.schedule.actions.filter(i=>this.isTimeActive(i,e))}getCommands(){var e;return((e=this.schedule)==null?void 0:e.commands)||[]}findActionByTrigger(e){return this.getActiveActions().find(i=>i.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),B.info("Play history cleared")}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},B.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return B.debug("No player location, skipping geofence check"),!0;if(!e)return!0;const i=e.split(",").map(l=>parseFloat(l.trim()));if(i.length<2||isNaN(i[0])||isNaN(i[1]))return B.warn("Invalid geoLocation format:",e),!0;const n=i[0],o=i[1],s=i[2]||t,r=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,n,o),a=r<=s;return B.info(`Geofence: ${r.toFixed(0)}m from (${n},${o}), radius ${s}m → ${a?"WITHIN":"OUTSIDE"}`),a}haversineDistance(e,t,i,n){const s=d=>d*Math.PI/180,r=s(i-e),a=s(n-t),l=Math.sin(r/2)**2+Math.cos(s(e))*Math.cos(s(i))*Math.sin(a/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}}const Lt=new lt,z=V("schedule:interrupts");class Tt{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),z.debug("Reset interrupt committed durations")}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){const i=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,i+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;const t=e.id||e.file,i=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=i}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return z.debug("No interrupt layouts, returning normal layouts"),e;if(!e||e.length===0)return z.warn("No normal layouts available, interrupts will fill entire hour"),this.fillHourWithInterrupts(t);z.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(const d of t){const c=d.id||d.file;this.interruptCommittedDurations.set(c,0)}const i=[];let n=0,o=0,s=!1;for(;!s;){if(o>=t.length){o=0;let c=!0;for(const g of t)if(!this.isInterruptDurationSatisfied(g)){c=!1;break}if(c){s=!0;break}}const d=t[o];if(!this.isInterruptDurationSatisfied(d)){const c=d.id||d.file;this.addCommittedDuration(c,d.duration),n+=d.duration,i.push(d)}o++}if(z.debug(`Resolved ${i.length} interrupt plays (${n}s total)`),n>=3600)return z.info("Interrupts fill entire hour (>= 3600s), no room for normal layouts"),i;const r=3600-n,a=this.fillTimeWithLayouts(e,r);z.debug(`Resolved ${a.length} normal plays (${r}s target)`);const l=this.interleaveLayouts(a,i);return z.info(`Final loop: ${l.length} layouts (${a.length} normal + ${i.length} interrupts)`),l}fillTimeWithLayouts(e,t){const i=[];let n=t,o=0;for(;n>0;){o>=e.length&&(o=0);const s=e[o];i.push(s),n-=s.duration,o++}return i}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){const i=[],n=Math.max(e.length,t.length),o=Math.ceil(1*n/e.length),s=Math.floor(1*n/t.length);z.debug(`Interleaving: pickCount=${n}, normalPick=${o}, interruptPick=${s}`);let r=0,a=0,l=0;for(let d=0;d<n;d++)d%o===0&&(r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++),d%s===0&&a<t.length&&(i.push(t[a]),l+=t[a].duration,a++);for(;l<3600;)r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++;return z.debug(`Interleaved ${i.length} layouts, total duration: ${l}s`),i}separateLayouts(e){const t=[],i=[];for(const n of e)this.isInterrupt(n)?i.push(n):t.push(n);return{normalLayouts:t,interruptLayouts:i}}}const J=V("schedule:overlays");class ct{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,J.debug("OverlayScheduler initialized")}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],J.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];const e=new Date,t=[];for(const i of this.overlays){if(!this.isTimeActive(i,e)){J.debug(`Overlay ${i.file} not in time window`);continue}if(i.isGeoAware&&i.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(i.geoLocation)){J.debug(`Overlay ${i.file} filtered by geofence`);continue}if(i.criteria&&i.criteria.length>0&&!ce(i.criteria,{now:e,displayProperties:this.displayProperties})){J.debug(`Overlay ${i.file} filtered by criteria`);continue}t.push(i)}return t.sort((i,n)=>{const o=i.priority||0;return(n.priority||0)-o}),t.length>0&&J.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){const i=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,n=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(i&&t<i||n&&t>n)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],J.debug("Cleared all overlays")}processOverlays(e,t){return this.setOverlays(t),e}}new ct;const Z=V("LayoutPool");class ne{constructor(e=2){this.layouts=new Map,this.maxSize=e,this.hotLayoutId=null}has(e){return this.layouts.has(e)}get(e){return this.layouts.get(e)}add(e,t){if(this.layouts.has(e)){const i=this.layouts.get(e);Object.assign(i,t),i.lastAccess=Date.now();return}this.layouts.size>=this.maxSize&&this.evictLRU(),t.status="warm",t.lastAccess=Date.now(),this.layouts.set(e,t),Z.info(`Added layout ${e} to pool (size: ${this.layouts.size}/${this.maxSize})`)}setHot(e){if(this.hotLayoutId!==null&&this.layouts.has(this.hotLayoutId)&&(this.layouts.get(this.hotLayoutId).status="warm"),this.layouts.has(e)){const t=this.layouts.get(e);t.status="hot",t.lastAccess=Date.now()}this.hotLayoutId=e}evict(e){const t=this.layouts.get(e);if(t){if(Z.info(`Evicting layout ${e} from pool`),t.regions)for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null);if(t.container&&ne.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),Z.info(`Revoked ${t.blobUrls.size} blob URLs for layout ${e}`)),t.mediaUrlCache)for(const[i,n]of t.mediaUrlCache)n&&typeof n=="string"&&n.startsWith("blob:")&&URL.revokeObjectURL(n);t.container&&t.container.parentNode&&t.container.remove(),this.layouts.delete(e),this.hotLayoutId===e&&(this.hotLayoutId=null)}}static releaseMediaElements(e){let t=0,i=0;e.querySelectorAll("video").forEach(n=>{n._hlsInstance&&(n._hlsInstance.destroy(),n._hlsInstance=null,i++),n._mediaStream&&(n._mediaStream.getTracks().forEach(o=>o.stop()),n._mediaStream=null,n.srcObject=null),n.pause(),n.removeAttribute("src"),n.load(),t++}),e.querySelectorAll("audio").forEach(n=>{n.pause(),n.removeAttribute("src"),n.load()}),e.querySelectorAll(".pdf-widget").forEach(n=>{n._pdfDestroy&&n._pdfDestroy()}),t>0&&Z.info(`Released ${t} video(s)${i?` (${i} HLS)`:""}`)}evictLRU(){let e=null,t=1/0;for(const[i,n]of this.layouts)n.status==="warm"&&n.lastAccess<t&&(e=i,t=n.lastAccess);e!==null&&this.evict(e)}clearWarm(){let e=0;const t=[];for(const[i,n]of this.layouts)n.status==="warm"&&t.push(i);for(const i of t)this.evict(i),e++;return e>0&&Z.info(`Cleared ${e} warm layout(s) from pool`),e}clearWarmNotIn(e){let t=0;const i=[];for(const[n,o]of this.layouts)o.status==="warm"&&!e.has(n)&&i.push(n);for(const n of i)this.evict(n),t++;return t>0&&Z.info(`Cleared ${t} warm layout(s) no longer in schedule`),t}getLatest(){let e;for(const t of this.layouts.keys())e=t;return e}clear(){const e=Array.from(this.layouts.keys());for(const t of e)this.evict(t);this.hotLayoutId=null}get size(){return this.layouts.size}}const oe={fadeIn(p,e){const t=[{opacity:0},{opacity:1}],i={duration:e,easing:"linear",fill:"forwards"};return p.animate(t,i)},fadeOut(p,e){const t=[{opacity:1},{opacity:0}],i={duration:e,easing:"linear",fill:"forwards"};return p.animate(t,i)},getFlyKeyframes(p,e,t,i){const n={N:{x:0,y:i?-t:t},NE:{x:i?e:-e,y:i?-t:t},E:{x:i?e:-e,y:0},SE:{x:i?e:-e,y:i?t:-t},S:{x:0,y:i?t:-t},SW:{x:i?-e:e,y:i?t:-t},W:{x:i?-e:e,y:0},NW:{x:i?-e:e,y:i?-t:t}},o=n[p]||n.N;return i?{from:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0},to:{transform:"translate(0, 0)",opacity:1}}:{from:{transform:"translate(0, 0)",opacity:1},to:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0}}},flyIn(p,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!0),s={duration:e,easing:"ease-out",fill:"forwards"};return p.animate([o.from,o.to],s)},flyOut(p,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!1),s={duration:e,easing:"ease-in",fill:"forwards"};return p.animate([o.from,o.to],s)},apply(p,e,t,i,n){if(!e||!e.type)return null;const o=e.type.toLowerCase(),s=e.duration||1e3,r=e.direction||"N";switch(o){case"fade":return t?this.fadeIn(p,s):this.fadeOut(p,s);case"fadein":return t?this.fadeIn(p,s):null;case"fadeout":return t?null:this.fadeOut(p,s);case"fly":return t?this.flyIn(p,s,r,i,n):this.flyOut(p,s,r,i,n);case"flyin":return t?this.flyIn(p,s,r,i,n):null;case"flyout":return t?null:this.flyOut(p,s,r,i,n);default:return null}}};class dt{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=V("RendererLite",i.logLevel),this.emitter=new de,this.currentLayout=null,this.currentLayoutId=null,this._preloadingLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback=null,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=new Map,this.layoutBlobUrls=new Map,this.audioOverlays=new Map,this._stopWidgetBound=(n,o)=>this.stopWidget(n,o),this._renderWidgetBound=(n,o)=>this.renderWidget(n,o),this.scaleFactor=1,this.offsetX=0,this.offsetY=0,this.overlayContainer=null,this.activeOverlays=new Map,this._keydownHandler=null,this._keyboardActions=[],this._subPlaylistCycleIndex=new Map,this._startedWidgets=new Set,this.layoutPool=new ne(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.emitter.on("interactiveTrigger",n=>this._handleInteractiveTrigger(n)),this.emitter.on("widgetExpire",n=>this._handleWidgetExpire(n)),this.emitter.on("widgetExtendDuration",n=>this._handleWidgetExtendDuration(n)),this.emitter.on("widgetSetDuration",n=>this._handleWidgetSetDuration(n)),this.log.info("Initialized")}setupContainer(){if(this.container.style.position="relative",this.container.style.width="100%",this.container.style.height="100vh",this.container.style.overflow="hidden",this._resizeSuppressed=!1,typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{this._resizeSuppressed||(e&&clearTimeout(e),e=setTimeout(()=>this.rescaleRegions(),150))}),this.resizeObserver.observe(this.container)}this.overlayContainer=document.createElement("div"),this.overlayContainer.id="overlay-container",this.overlayContainer.style.position="absolute",this.overlayContainer.style.top="0",this.overlayContainer.style.left="0",this.overlayContainer.style.width="100%",this.overlayContainer.style.height="100%",this.overlayContainer.style.zIndex="1000",this.overlayContainer.style.pointerEvents="none",this.container.appendChild(this.overlayContainer)}calculateScale(e){const t=this.container.clientWidth,i=this.container.clientHeight;if(!t||!i)return;const n=t/e.width,o=i/e.height;this.scaleFactor=Math.min(n,o),this.offsetX=(t-e.width*this.scaleFactor)/2,this.offsetY=(i-e.height*this.scaleFactor)/2,this.log.info(`Scale: ${this.scaleFactor.toFixed(3)} (${e.width}x${e.height} → ${t}x${i}, offset ${Math.round(this.offsetX)},${Math.round(this.offsetY)})`)}applyRegionScale(e,t){const i=this.scaleFactor;e.style.left=`${t.left*i+this.offsetX}px`,e.style.top=`${t.top*i+this.offsetY}px`,e.style.width=`${t.width*i}px`,e.style.height=`${t.height*i}px`}rescaleRegions(){if(this.currentLayout){this.calculateScale(this.currentLayout);for(const[e,t]of this.regions)this.applyRegionScale(t.element,t.config),t.width=t.config.width*this.scaleFactor,t.height=t.config.height*this.scaleFactor;for(const[e,t]of this.activeOverlays){this.calculateScale(t.layout);for(const[i,n]of t.regions)this.applyRegionScale(n.element,n.config),n.width=n.config.width*this.scaleFactor,n.height=n.config.height*this.scaleFactor}}}on(e,t){this.emitter.on(e,t)}emit(e,...t){this.emitter.emit(e,...t)}parseActions(e){const t=[];for(const i of e.children)i.tagName==="action"&&t.push({id:i.getAttribute("id")||"",actionType:i.getAttribute("actionType")||"",triggerType:i.getAttribute("triggerType")||"",triggerCode:i.getAttribute("triggerCode")||"",source:i.getAttribute("source")||"",sourceId:i.getAttribute("sourceId")||"",target:i.getAttribute("target")||"",targetId:i.getAttribute("targetId")||"",widgetId:i.getAttribute("widgetId")||"",layoutCode:i.getAttribute("layoutCode")||"",commandCode:i.getAttribute("commandCode")||""});return t}parseXlf(e){const n=new DOMParser().parseFromString(e,"text/xml").querySelector("layout");if(!n)throw new Error("Invalid XLF: no <layout> element");const o=n.getAttribute("duration"),s={schemaVersion:parseInt(n.getAttribute("schemaVersion")||"1"),width:parseInt(n.getAttribute("width")||"1920"),height:parseInt(n.getAttribute("height")||"1080"),duration:o?parseInt(o):0,bgcolor:n.getAttribute("backgroundColor")||n.getAttribute("bgcolor")||"#000000",background:n.getAttribute("background")||null,enableStat:n.getAttribute("enableStat")!=="0",actions:this.parseActions(n),regions:[]};s.schemaVersion>1&&this.log.debug(`XLF schema version: ${s.schemaVersion}`),o?this.log.info(`Layout duration from XLF: ${s.duration}s`):this.log.info("Layout duration NOT in XLF, will calculate from widgets");const r=n.querySelectorAll(":scope > region, :scope > drawer");for(const a of r){const l=a.tagName==="drawer",d=a.getAttribute("type")||null,c={id:a.getAttribute("id"),width:parseInt(a.getAttribute("width")||"0"),height:parseInt(a.getAttribute("height")||"0"),top:parseInt(a.getAttribute("top")||"0"),left:parseInt(a.getAttribute("left")||"0"),zindex:parseInt(a.getAttribute("zindex")||(l?"2000":"0")),enableStat:a.getAttribute("enableStat")!=="0",actions:this.parseActions(a),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:l,isCanvas:d==="canvas",widgets:[]},g=Array.from(a.children).find(h=>h.tagName==="options");if(g){const h=g.querySelector("exitTransType");if(h&&h.textContent){const y=g.querySelector("exitTransDuration"),b=g.querySelector("exitTransDirection");c.exitTransition={type:h.textContent,duration:parseInt(y&&y.textContent||"1000"),direction:b&&b.textContent||"N"}}const m=g.querySelector("loop");m&&(c.loop=m.textContent!=="0");const w=g.querySelector("transitionType");if(w&&w.textContent){c.transitionType=w.textContent;const y=g.querySelector("transitionDuration"),b=g.querySelector("transitionDirection");c.transitionDuration=parseInt(y&&y.textContent||"1000"),c.transitionDirection=b&&b.textContent||"N"}}for(const h of a.children){if(h.tagName!=="media")continue;const m=this.parseWidget(h);c.widgets.push(m)}!c.isCanvas&&c.widgets.some(h=>h.type==="global")&&(c.isCanvas=!0),s.regions.push(c),l&&this.log.info(`Parsed drawer: id=${c.id} with ${c.widgets.length} widgets`),c.isCanvas&&this.log.info(`Parsed canvas region: id=${c.id} with ${c.widgets.length} widgets (all render simultaneously)`)}if(s.duration===0){const{duration:a,isDynamic:l}=We(e);s.duration=a,s.isDynamic=l,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)${l?" [dynamic — has useDuration=0 video]":""}`)}return s}parseWidget(e){const t=e.getAttribute("type"),i=parseInt(e.getAttribute("duration")||"10"),n=parseInt(e.getAttribute("useDuration")||"1"),o=e.getAttribute("id"),s=e.getAttribute("fileId"),r={},a=e.querySelector("options");if(a)for(const _ of a.children)r[_.tagName]=_.textContent;const l=e.querySelector("raw"),d=l?l.textContent:"",c={in:null,out:null};r.transIn&&(c.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(c.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const g=this.parseActions(e),h=[];for(const _ of e.children)if(_.tagName.toLowerCase()==="audio"){const L=_.querySelector("uri");L?h.push({mediaId:L.getAttribute("mediaId")||null,uri:L.textContent||"",volume:parseInt(L.getAttribute("volume")||"100"),loop:L.getAttribute("loop")==="1"}):h.push({mediaId:_.getAttribute("mediaId")||null,uri:_.getAttribute("uri")||"",volume:parseInt(_.getAttribute("volume")||"100"),loop:_.getAttribute("loop")==="1"})}const m=[],w=Array.from(e.children).find(_=>_.tagName==="commands");if(w)for(const _ of w.children)_.tagName==="command"&&m.push({commandCode:_.getAttribute("commandCode")||"",commandString:_.getAttribute("commandString")||""});const y=e.getAttribute("parentWidgetId")||null,b=parseInt(e.getAttribute("displayOrder")||"0"),C=e.getAttribute("cyclePlayback")==="1",I=parseInt(e.getAttribute("playCount")||"0"),M=e.getAttribute("isRandom")==="1",D=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,S=e.getAttribute("toDt")||e.getAttribute("todt")||null,T=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:T,fromDt:D,toDt:S,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:d,transitions:c,actions:g,audioNodes:h,commands:m,parentWidgetId:y,displayOrder:b,cyclePlayback:C,playCount:I,isRandom:M}}trackBlobUrl(e){const t=this._preloadingLayoutId||this.currentLayoutId||0;t||this.log.warn("trackBlobUrl called without currentLayoutId, tracking under key 0"),this.layoutBlobUrls.has(t)||this.layoutBlobUrls.set(t,new Set),this.layoutBlobUrls.get(t).add(e)}revokeBlobUrlsForLayout(e){const t=this.layoutBlobUrls.get(e);t&&(t.forEach(i=>{URL.revokeObjectURL(i)}),this.layoutBlobUrls.delete(e),this.log.info(`Revoked ${t.size} blob URLs for layout ${e}`))}updateLayoutDuration(){if(!this.currentLayout)return;let e=0;for(const t of this.currentLayout.regions){if(t.isDrawer)continue;let i=0;for(const n of t.widgets)n.duration>0&&(i+=n.duration);e=Math.max(e,i)}if(e>0&&e!==this.currentLayout.duration){const t=this.currentLayout.duration;this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`);const i=!this._hasUnprobedVideos();if(this.emit("layoutDurationUpdated",this.currentLayoutId,e,i),this._deferredTimerLayoutId===this.currentLayoutId&&!this.layoutTimer)if(this._hasUnprobedVideos())this.log.info(`Layout duration updated to ${e}s but still has unprobed videos — keeping timer deferred`);else{this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,e*1e3-n);this._deferredTimerLayoutId=null,this._layoutTimerDurationMs=o,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},o),this.log.info(`All video durations resolved — deferred timer started: ${(o/1e3).toFixed(1)}s remaining (waited ${(n/1e3).toFixed(1)}s for metadata)`)}else if(this.layoutTimer){clearTimeout(this.layoutTimer);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,this.currentLayout.duration*1e3-n);this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},o),this.log.info(`Layout timer adjusted to ${(o/1e3).toFixed(1)}s remaining (elapsed ${(n/1e3).toFixed(1)}s of ${this.currentLayout.duration}s)`)}else this.log.info(`Layout duration updated to ${e}s (timer not yet started, will use new value)`);this._scheduleNextLayoutPreload(this.currentLayout)}}attachActionListeners(e){var n;const t=[];let i=0;for(const o of e.actions||[])o.triggerType==="touch"?(this.attachTouchAction(this.container,o,null,null),i++):(n=o.triggerType)!=null&&n.startsWith("keyboard:")&&t.push(o);for(const o of e.regions){const s=this.regions.get(o.id);if(s){for(const r of o.actions||[])r.triggerType==="touch"?(this.attachTouchAction(s.element,r,o.id,null),i++):r.triggerType.startsWith("keyboard:")&&t.push(r);for(const r of o.widgets){if(!r.actions||r.actions.length===0)continue;const a=s.widgetElements.get(r.id);if(a)for(const l of r.actions)l.triggerType==="touch"?(this.attachTouchAction(a,l,o.id,r.id),i++):l.triggerType.startsWith("keyboard:")&&t.push(l)}}}this.setupKeyboardListener(t),(i>0||t.length>0)&&this.log.info(`Actions attached: ${i} touch, ${t.length} keyboard`)}attachTouchAction(e,t,i,n){e.style.cursor="pointer";const o=s=>{s.stopPropagation();const r=n?`widget ${n}`:`region ${i}`;this.log.info(`Touch action fired on ${r}: ${t.actionType}`),this.emit("action-trigger",{actionType:t.actionType,triggerType:"touch",triggerCode:t.triggerCode,layoutCode:t.layoutCode,targetId:t.targetId,commandCode:t.commandCode,source:{regionId:i,widgetId:n}})};e.addEventListener("click",o),e._actionHandlers||(e._actionHandlers=[]),e._actionHandlers.push(o)}setupKeyboardListener(e){this.removeKeyboardListener(),this._keyboardActions=e,e.length!==0&&(this._keydownHandler=t=>{const i=t.key;for(const n of this._keyboardActions){const o=n.triggerType.substring(9);if(i===o){this.log.info(`Keyboard action (key: ${i}): ${n.actionType}`),this.emit("action-trigger",{actionType:n.actionType,triggerType:n.triggerType,triggerCode:n.triggerCode,layoutCode:n.layoutCode,targetId:n.targetId,commandCode:n.commandCode,source:{key:i}});break}}},document.addEventListener("keydown",this._keydownHandler))}removeKeyboardListener(){this._keydownHandler&&(document.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),this._keyboardActions=[]}removeActionListeners(){for(const[,e]of this.regions){this._cleanElementActionHandlers(e.element);for(const[,t]of e.widgetElements)this._cleanElementActionHandlers(t)}this.removeKeyboardListener()}_cleanElementActionHandlers(e){if(e._actionHandlers){for(const t of e._actionHandlers)e.removeEventListener("click",t);delete e._actionHandlers,e.style.cursor=""}}_findRegionByWidgetId(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1)return{regionId:t,region:i,widget:i.widgets[n],widgetIndex:n,regionMap:this.regions}}for(const t of this.activeOverlays.values())if(t.regions)for(const[i,n]of t.regions){const o=n.widgets.findIndex(s=>s.id===e);if(o!==-1)return{regionId:i,region:n,widget:n.widgets[o],widgetIndex:o,regionMap:t.regions}}return null}_advanceRegion(e,t){const i=t.get(e);if(!i)return;i.currentIndex=(i.currentIndex+1)%i.widgets.length;const n=t===this.regions;this._startRegionCycle(i,e,n?this._renderWidgetBound:this._renderWidgetBound,n?this._stopWidgetBound:this._stopWidgetBound,n?()=>this.checkLayoutComplete():void 0)}_handleInteractiveTrigger({targetId:e,triggerCode:t}){this.log.info(`XIC interactiveTrigger: target=${e} code=${t}`),this._findRegionByWidgetId(e)?this.navigateToWidget(e):this.log.warn(`XIC interactiveTrigger: widget ${e} not found`)}_handleWidgetExpire({widgetId:e}){const t=this._findRegionByWidgetId(e);if(!t){this.log.warn(`XIC widgetExpire: widget ${e} not found`);return}const{regionId:i,region:n,widgetIndex:o,regionMap:s}=t;this.log.info(`XIC widgetExpire: widget=${e} region=${i}`),n.timer&&(clearTimeout(n.timer),n.timer=null),this.stopWidget(i,o),this._advanceRegion(i,s)}_handleWidgetExtendDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetExtendDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetExtendDuration: widget=${e} +${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}_handleWidgetSetDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetSetDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetSetDuration: widget=${e} ${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}navigateToWidget(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1){if(this.log.info(`Navigating to widget ${e} in region ${t} (index ${n})`),i.isDrawer&&i.element.style.display==="none"&&(i.element.style.display="",this.log.info(`Drawer region ${t} revealed`)),i.timer&&(clearTimeout(i.timer),i.timer=null),this.stopWidget(t,i.currentIndex),i.currentIndex=n,this.renderWidget(t,n),i.widgets.length>1){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n);const r=(n+1)%i.widgets.length;i.currentIndex=r,i.isDrawer&&r===0?(i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (cycle complete)`)):i.isDrawer?this.navigateToWidget(i.widgets[r].id):this.startRegion(t)},s)}else if(i.isDrawer){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n),i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (single widget done)`)},s)}return}}this.log.warn(`Target widget ${e} not found in any region`)}nextWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex+1)%t.widgets.length,n=t.widgets[i];this.log.info(`nextWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}previousWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex-1+t.widgets.length)%t.widgets.length,n=t.widgets[i];this.log.info(`previousWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}_mediaFileUrl(e){return`${window.location.origin}${H}/media/file/${e}`}_positionWidgetElement(e){Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",visibility:"hidden",opacity:"0"})}_applyBackgroundImage(e,t){Object.assign(e.style,{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"})}_clearRegionTimers(e){for(const[,t]of e)t.timer&&(clearTimeout(t.timer),t.timer=null)}async renderLayout(e,t){var i;try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,s]of this.regions)s.currentIndex=0,s.complete=!1;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null),this.emit("layoutStart",t,this.currentLayout);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,this.currentLayout),this.log.info(`Layout ${t} restarted (reused elements)`),this._scheduleNextLayoutPreload(this.currentLayout);return}if(this.layoutPool.has(t)){this.log.info(`Layout ${t} found in preload pool - instant swap!`),await this._swapToPreloadedLayout(t);return}this.log.info(`Switching to new layout ${t}`),this.stopCurrentLayout();const o=this.parseXlf(e);if(this.currentLayout=o,this.currentLayoutId=t,this.calculateScale(o),this.container.style.backgroundColor=o.bgcolor,this.container.style.backgroundImage="",o.background){const s=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(o.background)))||o.background;this._applyBackgroundImage(this.container,this._mediaFileUrl(s)),this.log.info(`Background image set: ${o.background} → ${s}`)}for(const s of o.regions)await this.createRegion(s);this.log.info("Pre-creating widget elements for instant transitions...");for(const[s,r]of this.regions)for(let a=0;a<r.widgets.length;a++){const l=r.widgets[a];l.layoutId=this.currentLayoutId,l.regionId=s;try{const d=await this.createWidgetElement(l,r);this._positionWidgetElement(d),r.element.appendChild(d),r.widgetElements.set(l.id,d)}catch(d){this.log.error(`Failed to pre-create widget ${l.id}:`,d)}}if(this.log.info("All widget elements pre-created"),this.attachActionListeners(o),this.emit("layoutStart",t,o),o.duration>0){const s=!this._hasUnprobedVideos();this.emit("layoutDurationUpdated",t,o.duration,s)}for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,o),this._scheduleNextLayoutPreload(o),this.log.info(`Layout ${t} started`)}catch(n){throw this.log.error("Error rendering layout:",n),this.emit("error",{type:"layoutError",error:n,layoutId:t}),n}}async createRegion(e){const t=document.createElement("div");t.id=`region_${e.id}`,t.className="renderer-lite-region",t.style.position="absolute",t.style.zIndex=e.zindex,t.style.overflow="hidden",e.isDrawer&&(t.style.display="none"),this.applyRegionScale(t,e),this.container.appendChild(t);let i=e.widgets.filter(o=>this._isWidgetActive(o));i.some(o=>o.cyclePlayback)&&(i=this._applyCyclePlayback(i));const n=this.scaleFactor;this.regions.set(e.id,{element:t,config:e,widgets:i,currentIndex:0,timer:null,width:e.width*n,height:e.height*n,complete:!1,isDrawer:e.isDrawer||!1,isCanvas:e.isCanvas||!1,widgetElements:new Map})}startRegion(e){const t=this.regions.get(e);this._startRegionCycle(t,e,this._renderWidgetBound,this._stopWidgetBound,()=>{this.log.info(`Region ${e} completed one full cycle`),this.checkLayoutComplete()})}async createWidgetElement(e,t){if(e.render==="html"&&e.type!=="pdf")return await this.renderGenericWidget(e,t);switch(e.type){case"image":return await this.renderImage(e,t);case"video":return await this.renderVideo(e,t);case"audio":return await this.renderAudio(e,t);case"text":case"ticker":return await this.renderTextWidget(e,t);case"pdf":return await this.renderPdf(e,t);case"webpage":return await this.renderWebpage(e,t);case"localvideo":return await this.renderVideo(e,t);case"videoin":return await this.renderVideoIn(e,t);case"powerpoint":case"flash":return this.log.warn(`Widget type '${e.type}' is not supported on web players (widget ${e.id})`),this._renderUnsupportedPlaceholder(e,t);default:return await this.renderGenericWidget(e,t)}}findMediaElement(e,t){return e.tagName===t?e:e.querySelector(t.toLowerCase())}updateMediaElement(e,t){const i=this.findMediaElement(e,"VIDEO")||this.findMediaElement(e,"AUDIO");if(i){if(i.tagName==="VIDEO"&&i._mediaConstraints&&!i._mediaStream){navigator.mediaDevices.getUserMedia(i._mediaConstraints).then(n=>{i.srcObject=n,i._mediaStream=n,this.log.info(`Webcam stream re-acquired for widget ${t.id}`)}).catch(n=>{this.log.warn("Failed to re-acquire webcam stream:",n.message)});return}this._restartMediaElement(i),this.log.info(`${i.tagName==="VIDEO"?"Video":"Audio"} restarted: ${t.fileId||t.id}`)}}_restartMediaElement(e){e.currentTime=0;const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t),e.currentTime===0&&e.readyState>=2&&(e.removeEventListener("seeked",t),e.play().catch(()=>{}))}waitForWidgetReady(e,t){const n=this.findMediaElement(e,"VIDEO");if(n)return!n.paused&&n.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{n.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",l)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{o.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",l)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()},l=setTimeout(()=>{s.removeEventListener("load",a),this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4);s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[n,o]of this.regions){if(o.widgets.length===0)continue;const s=o.widgets[o.currentIndex||0],r=o.widgetElements.get(s.id);r&&i.push(this.waitForWidgetReady(r,s))}if(i.length>0&&(this.log.info(`Waiting for ${i.length} widget(s) to be ready before starting layout timer...`),await Promise.all(i),this.log.info("All widgets ready — starting layout timer")),this.currentLayoutId!==e){this.log.warn(`Layout changed while waiting for widgets — skipping timer for ${e}`);return}if(t.isDynamic&&this._hasUnprobedVideos()){this._deferredTimerLayoutId=e,this._layoutTimerStartedAt=Date.now(),this.log.info(`Layout ${e} has unprobed videos — deferring timer until metadata loads`),this._deferredTimerFallback=setTimeout(()=>{this._deferredTimerFallback=null,this._deferredTimerLayoutId===e&&!this.layoutTimer&&(this.log.warn(`Layout ${e}: metadata timeout after 30s — starting timer with ${t.duration}s estimate`),this._deferredTimerLayoutId=null,this._startLayoutTimer(e,t))},3e4);return}this._startLayoutTimer(e,t)}_hasUnprobedVideos(){for(const[,e]of this.regions)for(const t of e.widgets)if(t.useDuration===0&&t.duration===0)return!0;return!1}_startLayoutTimer(e,t){this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null);const i=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=i,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},i)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);if(n||(this.log.warn(`Widget ${i.id} not pre-created, creating now`),n=await this.createWidgetElement(i,e),n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",e.widgetElements.set(i.id,n),e.element.appendChild(n)),!e.isCanvas)for(const[r,a]of e.widgetElements)r!==i.id&&((o=a.getAnimations)==null||o.call(a).forEach(l=>l.cancel()),a.style.visibility="hidden",a.style.opacity="0");return this.updateMediaElement(n,i),(s=n.getAnimations)==null||s.call(n).forEach(r=>r.cancel()),n.style.visibility="visible",i.transitions.in?oe.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",n._pdfResume&&n._pdfResume(),this._startAudioOverlays(i),i}_startAudioOverlays(e){if(!e.audioNodes||e.audioNodes.length===0)return;this._stopAudioOverlays(e.id);const t=[];for(const i of e.audioNodes){if(!i.uri)continue;const n=document.createElement("audio");n.autoplay=!0,n.loop=i.loop,n.volume=Math.max(0,Math.min(1,i.volume/100)),n.src=i.uri?this._mediaFileUrl(i.uri):"",n.style.display="none",this.container.appendChild(n);const o=n.play();o&&o.catch&&o.catch(()=>{}),t.push(n),this.log.info(`Audio overlay started for widget ${e.id}: ${i.uri} (loop=${i.loop}, vol=${i.volume})`)}t.length>0&&this.audioOverlays.set(e.id,t)}_stopAudioOverlays(e){const t=this.audioOverlays.get(e);if(t){for(const i of t)i.pause(),i.removeAttribute("src"),i.load(),i.parentNode&&i.parentNode.removeChild(i);this.audioOverlays.delete(e),this.log.info(`Audio overlays stopped for widget ${e}`)}}_hideWidget(e,t){const i=e.widgets[t];if(!i)return{widget:null,animPromise:null};const n=e.widgetElements.get(i.id);if(!n)return{widget:null,animPromise:null};let o=null;if(i.transitions.out){const a=oe.apply(n,i.transitions.out,!1,e.width,e.height);a&&(o=new Promise(l=>{a.onfinish=l}))}const s=n.querySelector("video");if(s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(a=>a.stop()),s._mediaStream=null,s.srcObject=null),s!=null&&s._hlsInstance&&(s._hlsInstance.destroy(),s._hlsInstance=null),s!=null&&s._eventCleanup){for(const[a,l]of s._eventCleanup)s.removeEventListener(a,l);s._eventCleanup=null}const r=n.querySelector("audio");if(r&&i.options.loop!=="1"&&r.pause(),r!=null&&r._eventCleanup){for(const[a,l]of r._eventCleanup)r.removeEventListener(a,l);r._eventCleanup=null}return this._stopAudioOverlays(i.id),n._pdfCleanup&&n._pdfCleanup(),{widget:i,animPromise:o}}_isWidgetActive(e){const t=new Date;if(e.fromDt){const i=new Date(e.fromDt);if(t<i)return!1}if(e.toDt){const i=new Date(e.toDt);if(t>i)return!1}return!0}_parseDurationComments(e,t){const i=t.duration,n=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(n){const s=parseInt(n[1],10);if(s>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${s}s`),t.duration=s,t.duration!==i&&this.updateLayoutDuration();return}}const o=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(o){const s=parseInt(o[1],10);if(s>0&&t.duration>0){const r=s*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${s} × ${t.duration}s = ${r}s`),t.duration=r}}t.duration!==i&&this.updateLayoutDuration()}_applyCyclePlayback(e){this._subPlaylistCycleIndex||(this._subPlaylistCycleIndex=new Map);const t=new Map,i=[];for(const n of e)n.parentWidgetId&&n.cyclePlayback?(t.has(n.parentWidgetId)||t.set(n.parentWidgetId,[]),t.get(n.parentWidgetId).push(n)):i.push({type:"direct",widget:n});for(const[n,o]of t){o.sort((r,a)=>r.displayOrder-a.displayOrder);let s;if(o.some(r=>r.isRandom)){const r=Math.floor(Math.random()*o.length);s=o[r]}else{const r=this._subPlaylistCycleIndex.get(n)||{widgetIdx:0,playsDone:0};s=o[r.widgetIdx%o.length];const a=s.playCount||1;r.playsDone++,r.playsDone>=a&&(r.widgetIdx++,r.playsDone=0),this._subPlaylistCycleIndex.set(n,r)}this.log.info(`Sub-playlist cycle: group ${n} selected widget ${s.id} (${o.length} in group)`),i.push({type:"direct",widget:s})}return i.map(n=>n.widget)}_startRegionCycle(e,t,i,n,o){if(!e||e.widgets.length===0)return;if(e.isCanvas){this._startCanvasRegion(e,t,i,o);return}if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,a=e.widgets[r];i(t,r);const l=a.duration*1e3;this.log.info(`Region ${t} widget ${a.id} (${a.type}) playing for ${a.duration}s (useDuration=${a.useDuration}, index ${r}/${e.widgets.length})`),e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(a,e,t,r,i,n,o,s)},l)};s()}_startCanvasRegion(e,t,i,n){for(let s=0;s<e.widgets.length;s++)i(t,s);const o=Math.max(...e.widgets.map(s=>s.duration))*1e3;o>0?e.timer=setTimeout(()=>{e.complete||(e.complete=!0,n==null||n())},o):(e.complete=!0,n==null||n())}_handleWidgetCycleEnd(e,t,i,n,o,s,r,a){var d;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const l=(t.currentIndex+1)%t.widgets.length;if(l===0&&!t.complete&&(t.complete=!0,r==null||r()),l===0&&((d=t.config)==null?void 0:d.loop)===!1&&t.widgets.length===1){o(i,0);return}this.layoutEndEmitted||(t.currentIndex=l,a())}async renderWidget(e,t){var n;const i=this.regions.get(e);if(i)try{const o=await this._showWidget(i,t);if(o&&(this.log.info(`Showing widget ${o.type} (${o.id}) in region ${e}`),this._startedWidgets.add(`${e}:${t}`),this.emit("widgetStart",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,duration:o.duration,enableStat:o.enableStat}),o.commands&&o.commands.length>0))for(const s of o.commands)this.emit("widgetCommand",{commandCode:s.commandCode,commandString:s.commandString,widgetId:o.id,regionId:e,layoutId:this.currentLayoutId})}catch(o){this.log.error("Error rendering widget:",o),this.emit("error",{type:"widgetError",error:o,widgetId:(n=i.widgets[t])==null?void 0:n.id,regionId:e})}}async stopWidget(e,t){const i=`${e}:${t}`;if(!this._startedWidgets.delete(i))return;const n=this.regions.get(e);if(!n)return;const{widget:o,animPromise:s}=this._hideWidget(n,t);o&&this.emit("widgetEnd",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,enableStat:o.enableStat}),s&&await s}_stopAllRegionWidgets(e,t){for(const[i,n]of e)if(n.isCanvas)for(let o=0;o<n.widgets.length;o++)t(i,o);else n.widgets.length>0&&t(i,n.currentIndex)}async renderImage(e,t){const i=document.createElement("img");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"contain",fit:"cover"};i.style.objectFit=o[n]||"contain";const s={left:"left",center:"center",right:"right"},r={top:"top",middle:"center",bottom:"bottom"},a=s[e.options.alignId]||"center",l=r[e.options.valignId]||"center";i.style.objectPosition=`${a} ${l}`,i.style.opacity="0";const d=e.options.uri?this._mediaFileUrl(e.options.uri):"";return i.src=d,i}async renderVideo(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"none",fit:"contain"};i.style.objectFit=o[n]||"contain",i.style.opacity="1",i.autoplay=!0,i.preload="auto",i.muted=e.options.mute==="1",i.loop=!1,i.controls=!1,i.playsInline=!0;const s=e.options.uri||"",r=e.fileId||e.id,a=()=>{e.options.loop==="1"?(i.currentTime=0,this.log.info(`Video ${s} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Video ${s} ended - paused on last frame`)};i.addEventListener("ended",a);let l=s?this._mediaFileUrl(s):"";if(l.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${r}`),i.src=l;else try{const{default:y}=await N(async()=>{const{default:b}=await import("hls.js");return{default:b}},[],import.meta.url);if(y.isSupported()){const b=new y({enableWorker:!0,lowLatencyMode:!0});b.loadSource(l),b.attachMedia(i),i._hlsInstance=b,b.on(y.Events.ERROR,(C,I)=>{I.fatal&&(this.log.error(`HLS fatal error: ${I.type}`,I.details),b.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${r}`)}else this.log.warn(`HLS not supported on this browser for ${r}`),i.src=l}catch(y){this.log.warn(`hls.js not available, falling back to native: ${y.message}`),i.src=l}else i.src=l;const c=this.currentLayoutId,g=()=>{const y=i.duration;this.log.info(`Video ${s} duration detected: ${y}s`),(e.duration===0||e.useDuration===0)&&(e.duration=y,this.log.info(`Updated widget ${e.id} duration to ${y}s (useDuration=0)`),this.currentLayoutId===c?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${c}, current is ${this.currentLayoutId})`))};i.addEventListener("loadedmetadata",g);const h=()=>{this.log.info("Video loaded and ready:",s)};i.addEventListener("loadeddata",h);const m=()=>{const y=i.error,b=y==null?void 0:y.code,C=(y==null?void 0:y.message)||"Unknown error";this.log.warn(`Video error: ${s}, code: ${b}, time: ${i.currentTime.toFixed(1)}s, message: ${C}`),e.useDuration===0&&e.duration===0&&(e.duration=60,this.log.info(`Set fallback duration 60s for errored widget ${e.id}`),this.currentLayoutId===c&&this.updateLayoutDuration()),this.emit("videoError",{storedAs:s,fileId:r,errorCode:b,errorMessage:C,currentTime:i.currentTime})};i.addEventListener("error",m);const w=()=>{this.log.info("Video playing:",s)};return i.addEventListener("playing",w),i._eventCleanup=[["ended",a],["loadedmetadata",g],["loadeddata",h],["error",m],["playing",w]],this.log.info("Video element created:",s,i.src),i}async renderVideoIn(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.objectFit=e.options.showFullScreen==="1"?"cover":"contain",i.autoplay=!0,i.playsInline=!0,i.controls=!1,i.muted=e.options.mute!=="0",e.options.mirror==="1"&&(i.style.transform="scaleX(-1)");const n={width:{ideal:t.width},height:{ideal:t.height}},o=e.options.sourceId||e.options.deviceId;o?n.deviceId={exact:o}:n.facingMode=e.options.facingMode||"environment";const s={video:n,audio:e.options.captureAudio==="1"};i._mediaConstraints=s;try{const r=await navigator.mediaDevices.getUserMedia(s);i.srcObject=r,i._mediaStream=r,this.log.info(`Webcam stream acquired for widget ${e.id} (tracks: ${r.getTracks().length})`)}catch(r){return this.log.warn(`getUserMedia failed for widget ${e.id}: ${r.message}`),this._renderUnsupportedPlaceholder({...e,type:"Camera unavailable"},t)}return i}async renderAudio(e,t){const i=document.createElement("div");i.className="renderer-lite-widget audio-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.background="linear-gradient(135deg, #667eea 0%, #764ba2 100%)",i.style.opacity="0";const n=document.createElement("audio");n.autoplay=!0,n.loop=e.options.loop==="1",n.volume=parseFloat(e.options.volume||"100")/100;const o=e.options.uri||"";e.fileId||e.id,n.src=o?this._mediaFileUrl(o):"";const s=()=>{e.options.loop==="1"?(n.currentTime=0,this.log.info(`Audio ${o} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Audio ${o} ended - playback complete`)};n.addEventListener("ended",s);const r=this.currentLayoutId,a=()=>{const h=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${h}s`),(e.duration===0||e.useDuration===0)&&(e.duration=h,this.log.info(`Updated widget ${e.id} duration to ${h}s (useDuration=0)`),this.currentLayoutId===r?this.updateLayoutDuration():this.log.info(`Audio ${o} duration set but layout timer not updated (preloaded for layout ${r}, current is ${this.currentLayoutId})`))};n.addEventListener("loadedmetadata",a);const l=()=>{const h=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${h==null?void 0:h.code}, message: ${(h==null?void 0:h.message)||"Unknown"}`)};n.addEventListener("error",l),n._eventCleanup=[["ended",s],["loadedmetadata",a],["error",l]];const d=document.createElement("div");d.innerHTML="♪",d.style.fontSize="120px",d.style.color="white",d.style.marginBottom="20px";const c=document.createElement("div");c.style.color="white",c.style.fontSize="24px",c.textContent="Playing Audio";const g=document.createElement("div");return g.style.color="rgba(255,255,255,0.7)",g.style.fontSize="16px",g.style.marginTop="10px",g.textContent=e.options.uri,i.appendChild(n),i.appendChild(d),i.appendChild(c),i.appendChild(g),i}async renderTextWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const r=await this.options.getWidgetHtml(e);if(r&&typeof r=="object"&&r.url)return i.src=r.url,r.fallback&&this._parseDurationComments(r.fallback,e),i;n=r}n&&this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);return i.src=s,this.trackBlobUrl(s),i}async renderPdf(e,t){const i=document.createElement("div");if(i.className="renderer-lite-widget pdf-widget",i.style.width="100%",i.style.height="100%",i.style.backgroundColor="transparent",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const o=await N(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=o;const s=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${s}pdf.worker.min.mjs`}catch(o){return this.log.error("PDF.js not available:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}let n=e.options.uri?this._mediaFileUrl(e.options.uri):"";try{const s=await window.pdfjsLib.getDocument(n).promise,r=s.numPages,a=e.duration||60,l=a*1e3/r;this.log.info(`[pdf] PDF loaded: ${r} pages, ${a}s duration, ${(l/1e3).toFixed(1)}s/page`);const d=await s.getPage(1),c=d.getViewport({scale:1}),g=Math.min(t.width/c.width,t.height/c.height);d.cleanup();const h=document.createElement("canvas");h.className="pdf-page",h.width=Math.floor(c.width*g),h.height=Math.floor(c.height*g),h.style.cssText="display:block;margin:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);";const m=h.getContext("2d");i.appendChild(h);const w=document.createElement("div");w.style.cssText="position:absolute;bottom:10px;right:10px;background:rgba(0,0,0,0.7);color:white;padding:8px 12px;border-radius:4px;font:14px system-ui;z-index:1;",Ne()||(w.style.display="none"),i.appendChild(w);let y=1,b=null,C=null,I=!1;const M=async()=>{if(I)return;w.textContent=`Page ${y} / ${r}`;const S=await s.getPage(y),T=S.getViewport({scale:g});m.clearRect(0,0,h.width,h.height),C=S.render({canvasContext:m,viewport:T});try{await C.promise}catch(_){if(I)return;throw _}C=null,S.cleanup(),r>1&&!I&&(b=setTimeout(()=>{y=y>=r?1:y+1,M()},l))};await M();let D=null;i._pdfCleanup=()=>{if(I=!0,b&&clearTimeout(b),b=null,C){const S=C;C=null,S.cancel(),D=S.promise.catch(()=>{})}},i._pdfResume=async()=>{i._pdfCleanup(),D&&(await D,D=null),I=!1,y=1,M()},i._pdfDestroy=()=>{i._pdfCleanup(),h.width=0,h.height=0,s.destroy()}}catch(o){this.log.error("PDF render failed:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">Failed to load PDF</div>'}return i.style.opacity="1",i}async renderWebpage(e,t){if(parseInt(e.options.modeId||"1")===0)return await this.renderGenericWidget(e,t);const n=document.createElement("iframe");n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0";const o=decodeURIComponent(e.options.uri||"");return n.src=o,n}async renderGenericWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const o=await this.options.getWidgetHtml(e);if(o&&typeof o=="object"&&o.url)return i.src=o.url,o.fallback&&this._parseDurationComments(o.fallback,e),i;n=o}if(n){this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);i.src=s,this.trackBlobUrl(s)}else this.log.warn(`No HTML for widget ${e.id}`),i.srcdoc='<div style="padding:20px;">Widget content unavailable</div>';return i}_renderUnsupportedPlaceholder(e,t){const i=document.createElement("div");return i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.backgroundColor="#111",i.style.color="#666",i.style.fontSize="14px",i.textContent=`Unsupported: ${e.type}`,i}_scheduleNextLayoutPreload(e){this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const t=e.duration||60,i=t*1e3*.75,n=t*1e3*.9;this.log.info(`Scheduling next layout preload in ${(i/1e3).toFixed(1)}s (75% of ${t}s)`),this.preloadTimer=setTimeout(()=>{this.preloadTimer=null,this.emit("request-next-layout-preload")},i),this._preloadRetryTimer=setTimeout(()=>{this._preloadRetryTimer=null,this.emit("request-next-layout-preload")},n)}hasPreloadedLayout(e){return this.layoutPool.has(e)}async preloadLayout(e,t){var i;if(this.layoutPool.has(t))return this.log.info(`Layout ${t} already in preload pool, skipping`),!0;if(this.currentLayoutId===t)return this.log.info(`Layout ${t} is current, skipping preload`),!0;try{this.log.info(`Preloading layout ${t} into pool...`);const n=this.parseXlf(e);this.calculateScale(n);const o=document.createElement("div");if(o.id=`preload_layout_${t}`,o.className="renderer-lite-preload-wrapper",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.visibility="hidden",o.style.zIndex="-1",o.style.backgroundColor=n.bgcolor,n.background){const g=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(n.background)))||n.background;this._applyBackgroundImage(o,this._mediaFileUrl(g))}const s=this.currentLayoutId,r=new Map,a=this.scaleFactor;for(const g of n.regions){const h=document.createElement("div");h.id=`preload_region_${t}_${g.id}`,h.className="renderer-lite-region",h.style.position="absolute",h.style.zIndex=g.zindex,h.style.overflow="hidden",this.applyRegionScale(h,g),o.appendChild(h);const m={element:h,config:g,widgets:g.widgets,currentIndex:0,timer:null,width:g.width*a,height:g.height*a,complete:!1,widgetElements:new Map};r.set(g.id,m)}const l=new Set,d=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,l),this._preloadingLayoutId=t;for(const[g,h]of r)for(let m=0;m<h.widgets.length;m++){const w=h.widgets[m];w.layoutId=t,w.regionId=g;try{const y=await this.createWidgetElement(w,h);this._positionWidgetElement(y),h.element.appendChild(y),h.widgetElements.set(w.id,y)}catch(y){this.log.error(`Preload: Failed to create widget ${w.id}:`,y)}}return this.currentLayoutId=s,o.querySelectorAll("video").forEach(g=>g.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(g=>l.add(g)),this.layoutBlobUrls=d,this.container.appendChild(o),this.layoutPool.add(t,{container:o,layout:n,regions:r,blobUrls:l}),this.log.info(`Layout ${t} preloaded into pool (${r.size} regions)`),!0}catch(n){return this.log.error(`Preload failed for layout ${t}:`,n),!1}}async _swapToPreloadedLayout(e){var o;const t=this.layoutPool.get(e);if(!t){this.log.error(`Cannot swap: layout ${e} not in pool`);return}this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const i=this.currentLayoutId,n=this.layoutEndEmitted;if(this.layoutEndEmitted=!1,i&&this.layoutPool.has(i))this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound),this.layoutPool.evict(i);else{this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,s]of this.regions)if(ne.releaseMediaElements(s.element),(o=s.config)!=null&&o.exitTransition){const r=oe.apply(s.element,s.config.exitTransition,!1,s.width,s.height);if(r){const a=s.element;r.onfinish=()=>a.remove()}else s.element.remove()}else s.element.remove();i&&this.revokeBlobUrlsForLayout(i)}if(this.currentLayout=null,this.currentLayoutId=null,this.regions.clear(),t.container.style.visibility="visible",t.container.style.zIndex="0",this.layoutPool.setHot(e),this.currentLayout=t.layout,this.currentLayoutId=e,this.regions=t.regions,i&&!n&&this.emit("layoutEnd",i),this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage)for(const s of["backgroundImage","backgroundSize","backgroundPosition","backgroundRepeat"])this.container.style[s]=t.container.style[s];else this.container.style.backgroundImage="";this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[s,r]of this.regions)r.currentIndex=0,r.complete=!1,this.startRegion(s);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this.preloadTimer||this._scheduleNextLayoutPreload(t.layout),this.log.info(`Swapped to preloaded layout ${e} (instant transition)`)}getCurrentLayoutId(){return this.currentLayoutId}showLayout(e){if(e===void 0&&(e=this.layoutPool.getLatest(),e===void 0)){this.log.warn("showLayout: no preloaded layout to show");return}if(this.currentLayoutId===e){this.log.info(`showLayout: layout ${e} already showing`);return}if(!this.layoutPool.has(e)){this.log.warn(`showLayout: layout ${e} not in preload pool`);return}this._swapToPreloadedLayout(e)}checkLayoutComplete(){let e=!0;for(const[t,i]of this.regions)if(i.widgets.length>1&&!i.complete){e=!1;break}e&&this.currentLayoutId&&this.log.info("All multi-widget regions completed one cycle")}stopCurrentLayout(){var i;if(!this.currentLayout)return;this.log.info(`Stopping layout ${this.currentLayoutId}`);const e=this.currentLayoutId,t=e&&!this.layoutEndEmitted;if(this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null),this.currentLayout=null,this.currentLayoutId=null,this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.removeActionListeners(),e&&this.layoutPool.has(e))this.layoutPool.evict(e);else{e&&this.revokeBlobUrlsForLayout(e),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,n]of this.regions)if(ne.releaseMediaElements(n.element),(i=n.config)!=null&&i.exitTransition){const o=oe.apply(n.element,n.config.exitTransition,!1,n.width,n.height);if(o){const s=n.element;o.onfinish=()=>s.remove()}else n.element.remove()}else n.element.remove()}this.regions.clear(),t&&this.emit("layoutEnd",e)}async renderOverlay(e,t,i=0){try{if(this.log.info(`Rendering overlay ${t} (priority ${i})`),this.activeOverlays.has(t)){this.log.warn(`Overlay ${t} already active, skipping`);return}const n=this.parseXlf(e),o=document.createElement("div");o.id=`overlay_${t}`,o.className="renderer-lite-overlay",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.zIndex=String(1e3+i),o.style.pointerEvents="auto",o.style.backgroundColor=n.bgcolor,this.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const a of n.regions){const l=document.createElement("div");l.id=`overlay_${t}_region_${a.id}`,l.className="renderer-lite-region overlay-region",l.style.position="absolute",l.style.zIndex=String(a.zindex),l.style.overflow="hidden",this.applyRegionScale(l,a),o.appendChild(l),s.set(a.id,{element:l,config:a,widgets:a.widgets,currentIndex:0,timer:null,width:a.width*r,height:a.height*r,complete:!1,isCanvas:a.isCanvas||!1,widgetElements:new Map})}for(const[a,l]of s)for(const d of l.widgets){d.layoutId=t,d.regionId=a;try{const c=await this.createWidgetElement(d,l);this._positionWidgetElement(c),l.element.appendChild(c),l.widgetElements.set(d.id,c)}catch(c){this.log.error(`Failed to pre-create overlay widget ${d.id}:`,c)}}this.overlayContainer.appendChild(o),this.activeOverlays.set(t,{container:o,layout:n,regions:s,timer:null,priority:i}),this.emit("overlayStart",t,n);for(const[a,l]of s)this.startOverlayRegion(t,a);if(n.duration>0){const a=n.duration*1e3,l=this.activeOverlays.get(t);l&&(l.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},a))}this.log.info(`Overlay ${t} started`)}catch(n){throw this.log.error("Error rendering overlay:",n),this.emit("error",{type:"overlayError",error:n,layoutId:t}),n}}startOverlayRegion(e,t){const i=this.activeOverlays.get(e);if(!i)return;const n=i.regions.get(t);this._startRegionCycle(n,t,(o,s)=>this.renderOverlayWidget(e,o,s),(o,s)=>this.stopOverlayWidget(e,o,s),()=>this.log.info(`Overlay ${e} region ${t} completed one full cycle`))}async renderOverlayWidget(e,t,i){var s;const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(o)try{const r=await this._showWidget(o,i);r&&(this.log.info(`Showing overlay widget ${r.type} (${r.id}) in overlay ${e} region ${t}`),this._startedWidgets.add(`overlay:${e}:${t}:${i}`),this.emit("overlayWidgetStart",{overlayId:e,widgetId:r.id,regionId:t,type:r.type,duration:r.duration}))}catch(r){this.log.error("Error rendering overlay widget:",r),this.emit("error",{type:"overlayWidgetError",error:r,widgetId:(s=o.widgets[i])==null?void 0:s.id,regionId:t,overlayId:e})}}async stopOverlayWidget(e,t,i){const n=`overlay:${e}:${t}:${i}`;if(!this._startedWidgets.delete(n))return;const o=this.activeOverlays.get(e);if(!o)return;const s=o.regions.get(t);if(!s)return;const{widget:r,animPromise:a}=this._hideWidget(s,i);r&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:r.id,regionId:t,type:r.type}),a&&await a}stopOverlay(e){const t=this.activeOverlays.get(e);if(!t){this.log.warn(`Overlay ${e} not active`);return}this.log.info(`Stopping overlay ${e}`),t.timer&&(clearTimeout(t.timer),t.timer=null);for(const[,i]of t.regions)i.timer&&(clearTimeout(i.timer),i.timer=null);this._stopAllRegionWidgets(t.regions,(i,n)=>this.stopOverlayWidget(e,i,n)),t.container&&t.container.remove(),this.revokeBlobUrlsForLayout(e),this.activeOverlays.delete(e),this.emit("overlayEnd",e),this.log.info(`Overlay ${e} stopped`)}stopAllOverlays(){const e=Array.from(this.activeOverlays.keys());for(const t of e)this.stopOverlay(t);this.log.info("All overlays stopped")}getActiveOverlays(){return Array.from(this.activeOverlays.keys())}pause(){if(!this._paused){this._paused=!0;for(const[,e]of this.regions)e.timer&&(clearTimeout(e.timer),e.timer=null);this._forEachMedia(e=>e.pause()),this.emit("paused"),this.log.info("Playback paused (layout timer continues)")}}isPaused(){return this._paused}resume(){if(this._paused){this._paused=!1,this._forEachMedia(e=>e.play().catch(()=>{}));for(const[e]of this.regions)this.startRegion(e);this.emit("resumed"),this.log.info("Playback resumed")}}_forEachMedia(e){var t;for(const[,i]of this.regions)(t=i.element)==null||t.querySelectorAll("video, audio").forEach(e)}cleanup(){this.stopAllOverlays(),this.stopCurrentLayout(),this._startedWidgets.clear();for(const e of this.audioOverlays.keys())this._stopAudioOverlays(e);this.layoutPool.clear(),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.innerHTML="",this.log.info("Cleaned up")}}const K=V("Layout");class $t{constructor(e){this.xmds=e}async translateXLF(e,t){const n=new DOMParser().parseFromString(t,"text/xml"),o=n.querySelector("layout");if(!o)throw new Error("Invalid XLF: no <layout> element");const s=parseInt(o.getAttribute("width")||"1920"),r=parseInt(o.getAttribute("height")||"1080"),a=o.getAttribute("bgcolor")||"#000000",l=[];for(const d of n.querySelectorAll("region"))l.push(await this.translateRegion(e,d));return this.generateHTML(s,r,a,l)}async translateRegion(e,t){const i=t.getAttribute("id"),n=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("height")),s=parseInt(t.getAttribute("top")),r=parseInt(t.getAttribute("left")),a=parseInt(t.getAttribute("zindex")||"0"),l=[];for(const d of t.querySelectorAll("media"))l.push(await this.translateMedia(e,i,d));return{id:i,width:n,height:o,top:s,left:r,zindex:a,media:l}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),a=i.querySelector("raw"),l={};if(r)for(const I of r.children)l[I.tagName]=I.textContent;const d={in:null,out:null},c=i.querySelector("options > transIn"),g=i.querySelector("options > transOut"),h=i.querySelector("options > transInDuration"),m=i.querySelector("options > transOutDuration"),w=i.querySelector("options > transInDirection"),y=i.querySelector("options > transOutDirection");c&&c.textContent&&(d.in={type:c.textContent,duration:parseInt((h==null?void 0:h.textContent)||"1000"),direction:(w==null?void 0:w.textContent)||"N"}),g&&g.textContent&&(d.out={type:g.textContent,duration:parseInt((m==null?void 0:m.textContent)||"1000"),direction:(y==null?void 0:y.textContent)||"N"});let b=a?a.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some(I=>n.includes(I))){let I=3,M=null;for(let D=1;D<=I;D++)try{K.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${D}/${I}`),b=await this.xmds.getResource(e,t,s),K.info(`Got resource HTML (${b.length} chars)`);const S=await je(e,t,s,b);l.widgetCacheKey=S;break}catch(S){if(M=S,K.warn(`Failed to get resource (attempt ${D}/${I}):`,S.message),D<I){const T=D*2e3;K.info(`Retrying in ${T}ms...`),await new Promise(_=>setTimeout(_,T))}}if(!b&&M){K.warn("All retries failed, checking for cached widget HTML...");try{const D=await fetch(`/store${H}/widgets/${e}/${t}/${s}`);D.ok?(b=await D.text(),l.widgetCacheKey=`${H}/widgets/${e}/${t}/${s}`,K.info(`Using stored widget HTML (${b.length} chars) - CMS update pending`)):(K.error(`No stored version available for widget ${s}`),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>')}catch(D){K.error("Store fallback failed:",D),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>'}}}return{type:n,duration:o,id:s,options:l,raw:b,transitions:d}}generateHTML(e,t,i,n){const o=n.map(r=>this.generateRegionHTML(r)).join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-O4mn_OO0.js","./chunk-config-BqpCSJ87.js","./index-BmnGgxhy.js","./index-DPUPuUO8.js","./widget-html-p3dC5HGH.js","./index-Bj01q2d4.js","./protocol-detector-UOvkmuFn.js","./index-zursmDNN.js","./modulepreload-polyfill-B5Qt9EMX.js","./index-mYGuS183.js","./index-BBp7Yeqp.js","./index-DNyHrXGf.js","./index-BGzZpdzW.js","./index-DwQpyIXq.js","./sync-manager-4de0XUYN.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Ue=Object.defineProperty;var qe=(p,e,t)=>e in p?Ue(p,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[e]=t;var $=(p,e,t)=>qe(p,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{createLogger as V,EventEmitter as de,PLAYER_API as H,isDebug as Ne,fetchWithRetry as Be,applyCmsLogLevel as He,openIDB as Ve,config as ze,registerLogSink as ge}from"./index-BmnGgxhy.js";import{c as je,C as Ge,D as Ke,B as fe,S as Xe}from"./widget-html-p3dC5HGH.js";const Qe="modulepreload",Ye=function(p,e){return new URL(p,e).href},ye={},N=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){const s=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),a=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(l=>{if(l=Ye(l,i),l in ye)return;ye[l]=!0;const d=l.endsWith(".css"),c=d?'[rel="stylesheet"]':"";if(!!i)for(let m=s.length-1;m>=0;m--){const w=s[m];if(w.href===l&&(!d||w.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${c}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Qe,d||(h.as="script"),h.crossOrigin="",h.href=l,a&&h.setAttribute("nonce",a),document.head.appendChild(h),d)return new Promise((m,w)=>{h.addEventListener("load",m),h.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=s,window.dispatchEvent(r),!r.defaultPrevented)throw s}return n.then(s=>{for(const r of s||[])r.status==="rejected"&&o(r.reason);return e().catch(o)})},se=V("schedule:criteria"),Je=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pe={weatherTemp:"temperature",weatherHumidity:"humidity",weatherWindSpeed:"windSpeed",weatherCondition:"condition",weatherCloudCover:"cloudCover"};function Ze(p,e,t={},i={}){switch(p){case"dayOfWeek":return Je[e.getDay()];case"dayOfMonth":return String(e.getDate());case"month":return String(e.getMonth()+1);case"hour":return String(e.getHours());case"isoDay":return String(e.getDay()===0?7:e.getDay());default:if(pe[p]){const n=pe[p];return i[n]!==void 0?String(i[n]):(se.debug(`Weather metric "${p}" requested but no weather data available`),null)}return t[p]!==void 0?String(t[p]):(se.debug(`Unknown metric: ${p}`),null)}}function et(p,e,t,i){if(p===null)return!1;if(i==="number"){const s=parseFloat(p),r=parseFloat(t);if(isNaN(s)||isNaN(r))return!1;switch(e){case"equals":return s===r;case"notEquals":return s!==r;case"greaterThan":return s>r;case"greaterThanOrEquals":return s>=r;case"lessThan":return s<r;case"lessThanOrEquals":return s<=r;default:return!1}}const n=p.toLowerCase(),o=t.toLowerCase();switch(e){case"equals":return n===o;case"notEquals":return n!==o;case"contains":return n.includes(o);case"notContains":return!n.includes(o);case"startsWith":return n.startsWith(o);case"endsWith":return n.endsWith(o);case"in":return o.split(",").map(s=>s.trim().toLowerCase()).includes(n);case"greaterThan":return n>o;case"lessThan":return n<o;default:return se.debug(`Unknown condition: ${e}`),!1}}function ce(p,e={}){if(!p||p.length===0)return!0;const t=e.now||new Date,i=e.displayProperties||{},n=e.weatherData||{};for(const o of p){const s=Ze(o.metric,t,i,n);if(!et(s,o.condition,o.value,o.type))return se.debug(`Criteria failed: ${o.metric} ${o.condition} "${o.value}" (actual: "${s}")`),!1}return!0}function q(p){return parseInt(String(p).replace(".xlf",""),10)}function We(p,e=null){const i=new DOMParser().parseFromString(p,"text/xml").querySelector("layout");if(!i)return{duration:60,isDynamic:!1};const n=parseInt(i.getAttribute("duration")||"0",10);if(n>0)return{duration:n,isDynamic:!1};let o=0,s=!1;for(const a of i.querySelectorAll("region")){const l=a.getAttribute("type");if(l==="drawer")continue;const d=l==="canvas";let c=0;for(const g of a.querySelectorAll("media")){const h=parseInt(g.getAttribute("duration")||"0",10),m=parseInt(g.getAttribute("useDuration")||"1",10),w=g.getAttribute("fileId")||"",y=e==null?void 0:e.get(w);let b;y!==void 0?b=y:h>0&&m!==0?b=h:(b=60,s=!0),d?c=Math.max(c,b):c+=b}o=Math.max(o,c)}return{duration:o>0?o:60,isDynamic:s}}function tt(p,e){if(p.length!==e.length)return!1;for(let t=0;t<p.length;t++)if(p[t]!==e[t])return!1;return!0}function it(p,e,t){if(!e||e===0)return!0;const i=t-36e5,n=p.filter(o=>o>i);if(n.length>=e)return!1;if(n.length>0){const o=36e5/e,s=Math.max(...n);if(t-s<o)return!1}return!0}function me(p,e,t){const i=p.filter(o=>{if(!o.maxPlaysPerHour||o.maxPlaysPerHour===0)return!0;const s=e.get(o.file)||[];return it(s,o.maxPlaysPerHour,t)});if(i.length===0)return[];const n=Math.max(...i.map(o=>o.priority));return i.filter(o=>o.priority===n).map(o=>o.file)}function nt(p,e,t={}){const i=t.from||new Date,n=t.hours||2,o=new Date(i.getTime()+n*36e5);t.currentLayoutStartedAt;const s=t.defaultLayout||null,r=t.durations||null;if(!p||p.length===0)return[];const a=[];let l=new Date(i),d=e%p.length;const c=500;for(;l<o&&a.length<c;){const g=p[d];let h=r&&r.get(g.layoutId)||g.duration;const m=l.getTime()+h*1e3;a.push({layoutFile:g.layoutId,startTime:new Date(l),endTime:new Date(m),duration:h,isDefault:s?g.layoutId===s:!1}),l=new Date(m),d=(d+1)%p.length}return a}function ot(p,e){for(p=Math.abs(Math.round(p)),e=Math.abs(Math.round(e));e;)[p,e]=[e,p%e];return p}function st(p,e){return p===0||e===0?0:Math.abs(Math.round(p)*Math.round(e))/ot(p,e)}function rt(p){return p.reduce((e,t)=>st(e,t),1)}function at(p,e,t={}){const{defaultLayout:i=null,defaultDuration:n=60}=t;if(p.length===0&&!i)return{queue:[],periodSeconds:0};const o=new Map;for(const m of p)m.duration>0&&o.set(m.file,m.duration);const s=m=>e.get(m)||o.get(m)||n,r=p.filter(m=>m.maxPlaysPerHour>0);let a;if(r.length>0){const m=r.map(w=>Math.round(3600/w.maxPlaysPerHour));a=rt(m),a>7200&&(a=7200)}else a=p.reduce((w,y)=>w+s(y.file),0)+(i&&!p.some(w=>w.file===i)?s(i):0)||n;const l=[],d=new Map;let c=0;const g=a*1e3,h=500;for(;c<g&&l.length<h;){const m=me(p,d,c);if(m.length===0){if(i){const w=s(i);l.push({layoutId:i,duration:w}),c+=w*1e3}else c+=6e4;continue}for(let w=0;w<m.length&&c<g&&l.length<h;w++){const y=m[w],b=s(y);l.push({layoutId:y,duration:b}),d.has(y)||d.set(y,[]),d.get(y).push(c),c+=b*1e3;const C=me(p,d,c);if(!tt(m,C))break}}if(l.length===0&&i){const m=s(i);l.push({layoutId:i,duration:m})}return{queue:l,periodSeconds:a}}const B=V("Schedule");class lt{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){var e;return((e=this.schedule)==null?void 0:e.dataConnectors)||[]}getDependantsMap(){const e=new Map;if(!this.schedule)return e;const t=this.schedule.dependants||[],i=n=>{const o=q(n.file||n.id),s=[...t,...n.dependants||[]];s.length>0&&e.set(o,s)};if(this.schedule.layouts)for(const n of this.schedule.layouts)i(n);if(this.schedule.campaigns)for(const n of this.schedule.campaigns)for(const o of n.layouts)i(o);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange){const i=new Date(e.recurrenceRange);if(t>i)return!1}switch(e.recurrenceType){case"Week":{if(e.recurrenceRepeatsOn){const i=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(",").map(o=>parseInt(o.trim())).includes(i))return!1}return!0}case"Day":{const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=t.getTime()-n.getTime(),s=Math.floor(o/864e5);if(s<0||s%i!==0)return!1}return!0}case"Month":{if(e.recurrenceRepeatsOn){const n=e.recurrenceRepeatsOn.split(",").map(s=>parseInt(s.trim())),o=t.getDate();if(!n.includes(o))return!1}const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();if(o<0||o%i!==0)return!1}return!0}default:return B.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){const t=e.getDay();return t===0?7:t}isTimeActive(e,t){const i=e.fromdt?new Date(e.fromdt):null,n=e.todt?new Date(e.todt):null;if(e.recurrenceType==="Week"||e.recurrenceType==="Day"||e.recurrenceType==="Month"){if(i&&n){const o=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),s=i.getHours()*3600+i.getMinutes()*60+i.getSeconds(),r=n.getHours()*3600+n.getMinutes()*60+n.getSeconds();return s<=r?o>=s&&o<=r:o>=s||o<=r}return!0}return!(i&&t<i||n&&t>n)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];const t=e,i=[];if(this.schedule.layouts)for(const n of this.schedule.layouts)this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t)&&(n.criteria&&n.criteria.length>0&&!ce(n.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||n.isGeoAware&&n.geoLocation&&!this.isWithinGeoFence(n.geoLocation)||i.push({file:n.file,priority:n.priority||0,maxPlaysPerHour:n.maxPlaysPerHour||0,duration:n.duration||0}));if(this.schedule.campaigns){for(const n of this.schedule.campaigns)if(this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t))for(const o of n.layouts)i.push({file:o.file,priority:n.priority||0,maxPlaysPerHour:o.maxPlaysPerHour||0,duration:o.duration||0})}return i}detectConflicts(e={}){const t=e.from||new Date,i=e.hours||24,n=new Date(t.getTime()+i*36e5),o=6e4,s=[];let r=null;for(let a=t.getTime();a<n.getTime();a+=o){const l=new Date(a),d=this.getAllLayoutsAtTime(l);if(d.length===0){r&&(s.push(r),r=null);continue}const c=Math.max(...d.map(y=>y.priority)),g=d.filter(y=>y.priority<c);if(g.length===0){r&&(s.push(r),r=null);continue}const h=d.filter(y=>y.priority===c),m=h.map(y=>y.file).sort().join(","),w=g.map(y=>`${y.file}:${y.priority}`).sort().join(",");r&&r._winnerKey===m&&r._hiddenKey===w?r.endTime=new Date(a+o):(r&&s.push(r),r={startTime:new Date(a),endTime:new Date(a+o),winner:{file:h[0].file,priority:c},hidden:g.map(y=>({file:y.file,priority:y.priority})),_winnerKey:m,_hiddenKey:w})}r&&s.push(r);for(const a of s)delete a._winnerKey,delete a._hiddenKey;return s}_getLayoutsAt(e,t={}){if(!this.schedule)return[];const{skipRateLimiting:i=!1,skipInterrupts:n=!1,quiet:o=!1}=t,s=o?()=>{}:(...c)=>B.info(...c),r=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(const c of this.schedule.campaigns)this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),r.push({type:"campaign",priority:c.priority,layouts:c.layouts,campaignId:c.id}));if(this.schedule.layouts){for(const c of this.schedule.layouts)if(this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)){if(c.criteria&&c.criteria.length>0&&!ce(c.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){s("[Schedule] Layout",c.id,"filtered by criteria");continue}if(c.isGeoAware&&c.geoLocation&&!this.isWithinGeoFence(c.geoLocation)){s("[Schedule] Layout",c.id,"filtered by geofence");continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),!i&&!this.canPlayLayout(c.id,c.maxPlaysPerHour)){s("[Schedule] Layout",c.id,"filtered by maxPlaysPerHour (limit:",c.maxPlaysPerHour,")");continue}r.push({type:"layout",priority:c.priority||0,layouts:[c],layoutId:c.id})}}if(r.length===0)return this.schedule.default?[this.schedule.default]:[];let a=Math.max(...r.map(c=>c.priority));s("[Schedule] Max priority:",a,"from",r.length,"active items");let l=[];for(const c of r)c.priority===a?(s("[Schedule] Including priority",c.priority,"layouts:",c.layouts.map(g=>g.file)),l.push(...c.layouts)):s("[Schedule] Skipping priority",c.priority,"< max",a);this._layoutMetadata.clear();for(const c of l)this._layoutMetadata.set(c.file,{syncEvent:c.syncEvent||!1,shareOfVoice:c.shareOfVoice||0,scheduleid:c.scheduleid,priority:c.priority||0});if(!n&&this.interruptScheduler){const{normalLayouts:c,interruptLayouts:g}=this.interruptScheduler.separateLayouts(l);if(g.length>0){s("[Schedule] Found",g.length,"interrupt layouts with shareOfVoice");const m=this.interruptScheduler.processInterrupts(c,g).map(w=>w.file);return s("[Schedule] Final layouts (with interrupts):",m),m}}const d=l.map(c=>c.file);return s("[Schedule] Final layouts:",d),d}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){if(!t||t===0)return!0;const i=Date.now(),n=i-60*60*1e3,s=(this.playHistory.get(e)||[]).filter(r=>r>n);if(s.length>=t)return B.info(`Layout ${e} has reached max plays per hour (${s.length}/${t})`),!1;if(s.length>0){const r=36e5/t,a=Math.max(...s),l=i-a;if(l<r){const d=((r-l)/6e4).toFixed(1);return B.info(`Layout ${e} spacing: next play in ${d} min (${s.length}/${t} plays, ${Math.round(r/6e4)} min gap)`),!1}}return!0}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);const t=this.playHistory.get(e);t.push(Date.now());const i=Date.now()-60*60*1e3,n=t.filter(o=>o>i);this.playHistory.set(e,n),B.info(`Recorded play for layout ${e} (${n.length} plays in last hour)`)}getMaxActivePriority(){return this._maxActivePriority||0}isSyncEvent(e){const t=this._layoutMetadata.get(e);return(t==null?void 0:t.syncEvent)===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){var r;const i=this.getAllLayoutsAtTime(new Date),n=i.map(a=>`${a.file}:${a.priority}:${a.maxPlaysPerHour}`).sort().join("|");if(this._scheduleQueue&&this._queueLayoutSet===n)return this._scheduleQueue;const o=at(i,e,{defaultLayout:((r=this.schedule)==null?void 0:r.default)||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),s=this._queueLayoutSet;return this._scheduleQueue=o,this._queueLayoutSet=n,s!==n&&(this._queuePosition=0),o.queue.length>0&&(B.info(`[Schedule] Built queue: ${o.queue.length} entries, period ${o.periodSeconds}s (pos ${this._queuePosition})`),B.info(`[Schedule] Queue: ${o.queue.map(a=>`${a.layoutId}(${a.duration}s)`).join(" → ")}`)),o}popNextFromQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);if(i.length===0)return null;const n=i[this._queuePosition%i.length];return this._queuePosition=(this._queuePosition+1)%i.length,n}getQueuePosition(){return this._queuePosition}rewindQueue(e,t,i={}){const{queue:n}=this.getScheduleQueue(t,i);if(n.length===0)return null;this._queuePosition=(this._queuePosition-e+n.length*e)%n.length;const o=n[this._queuePosition];return this._queuePosition=(this._queuePosition+1)%n.length,o}peekNextInQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length===0?null:i[this._queuePosition%i.length]}peekAfterNext(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length<=1?null:i[(this._queuePosition+1)%i.length]}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(const e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){var t;if(!((t=this.schedule)!=null&&t.actions))return[];const e=new Date;return this.schedule.actions.filter(i=>this.isTimeActive(i,e))}getCommands(){var e;return((e=this.schedule)==null?void 0:e.commands)||[]}findActionByTrigger(e){return this.getActiveActions().find(i=>i.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),B.info("Play history cleared")}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},B.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return B.debug("No player location, skipping geofence check"),!0;if(!e)return!0;const i=e.split(",").map(l=>parseFloat(l.trim()));if(i.length<2||isNaN(i[0])||isNaN(i[1]))return B.warn("Invalid geoLocation format:",e),!0;const n=i[0],o=i[1],s=i[2]||t,r=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,n,o),a=r<=s;return B.info(`Geofence: ${r.toFixed(0)}m from (${n},${o}), radius ${s}m → ${a?"WITHIN":"OUTSIDE"}`),a}haversineDistance(e,t,i,n){const s=d=>d*Math.PI/180,r=s(i-e),a=s(n-t),l=Math.sin(r/2)**2+Math.cos(s(e))*Math.cos(s(i))*Math.sin(a/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}}const Lt=new lt,z=V("schedule:interrupts");class Tt{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),z.debug("Reset interrupt committed durations")}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){const i=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,i+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;const t=e.id||e.file,i=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=i}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return z.debug("No interrupt layouts, returning normal layouts"),e;if(!e||e.length===0)return z.warn("No normal layouts available, interrupts will fill entire hour"),this.fillHourWithInterrupts(t);z.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(const d of t){const c=d.id||d.file;this.interruptCommittedDurations.set(c,0)}const i=[];let n=0,o=0,s=!1;for(;!s;){if(o>=t.length){o=0;let c=!0;for(const g of t)if(!this.isInterruptDurationSatisfied(g)){c=!1;break}if(c){s=!0;break}}const d=t[o];if(!this.isInterruptDurationSatisfied(d)){const c=d.id||d.file;this.addCommittedDuration(c,d.duration),n+=d.duration,i.push(d)}o++}if(z.debug(`Resolved ${i.length} interrupt plays (${n}s total)`),n>=3600)return z.info("Interrupts fill entire hour (>= 3600s), no room for normal layouts"),i;const r=3600-n,a=this.fillTimeWithLayouts(e,r);z.debug(`Resolved ${a.length} normal plays (${r}s target)`);const l=this.interleaveLayouts(a,i);return z.info(`Final loop: ${l.length} layouts (${a.length} normal + ${i.length} interrupts)`),l}fillTimeWithLayouts(e,t){const i=[];let n=t,o=0;for(;n>0;){o>=e.length&&(o=0);const s=e[o];i.push(s),n-=s.duration,o++}return i}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){const i=[],n=Math.max(e.length,t.length),o=Math.ceil(1*n/e.length),s=Math.floor(1*n/t.length);z.debug(`Interleaving: pickCount=${n}, normalPick=${o}, interruptPick=${s}`);let r=0,a=0,l=0;for(let d=0;d<n;d++)d%o===0&&(r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++),d%s===0&&a<t.length&&(i.push(t[a]),l+=t[a].duration,a++);for(;l<3600;)r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++;return z.debug(`Interleaved ${i.length} layouts, total duration: ${l}s`),i}separateLayouts(e){const t=[],i=[];for(const n of e)this.isInterrupt(n)?i.push(n):t.push(n);return{normalLayouts:t,interruptLayouts:i}}}const J=V("schedule:overlays");class ct{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,J.debug("OverlayScheduler initialized")}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],J.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];const e=new Date,t=[];for(const i of this.overlays){if(!this.isTimeActive(i,e)){J.debug(`Overlay ${i.file} not in time window`);continue}if(i.isGeoAware&&i.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(i.geoLocation)){J.debug(`Overlay ${i.file} filtered by geofence`);continue}if(i.criteria&&i.criteria.length>0&&!ce(i.criteria,{now:e,displayProperties:this.displayProperties})){J.debug(`Overlay ${i.file} filtered by criteria`);continue}t.push(i)}return t.sort((i,n)=>{const o=i.priority||0;return(n.priority||0)-o}),t.length>0&&J.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){const i=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,n=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(i&&t<i||n&&t>n)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],J.debug("Cleared all overlays")}processOverlays(e,t){return this.setOverlays(t),e}}new ct;const Z=V("LayoutPool");class ne{constructor(e=2){this.layouts=new Map,this.maxSize=e,this.hotLayoutId=null}has(e){return this.layouts.has(e)}get(e){return this.layouts.get(e)}add(e,t){if(this.layouts.has(e)){const i=this.layouts.get(e);Object.assign(i,t),i.lastAccess=Date.now();return}this.layouts.size>=this.maxSize&&this.evictLRU(),t.status="warm",t.lastAccess=Date.now(),this.layouts.set(e,t),Z.info(`Added layout ${e} to pool (size: ${this.layouts.size}/${this.maxSize})`)}setHot(e){if(this.hotLayoutId!==null&&this.layouts.has(this.hotLayoutId)&&(this.layouts.get(this.hotLayoutId).status="warm"),this.layouts.has(e)){const t=this.layouts.get(e);t.status="hot",t.lastAccess=Date.now()}this.hotLayoutId=e}evict(e){const t=this.layouts.get(e);if(t){if(Z.info(`Evicting layout ${e} from pool`),t.regions)for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null);if(t.container&&ne.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),Z.info(`Revoked ${t.blobUrls.size} blob URLs for layout ${e}`)),t.mediaUrlCache)for(const[i,n]of t.mediaUrlCache)n&&typeof n=="string"&&n.startsWith("blob:")&&URL.revokeObjectURL(n);t.container&&t.container.parentNode&&t.container.remove(),this.layouts.delete(e),this.hotLayoutId===e&&(this.hotLayoutId=null)}}static releaseMediaElements(e){let t=0,i=0;e.querySelectorAll("video").forEach(n=>{n._hlsInstance&&(n._hlsInstance.destroy(),n._hlsInstance=null,i++),n._mediaStream&&(n._mediaStream.getTracks().forEach(o=>o.stop()),n._mediaStream=null,n.srcObject=null),n.pause(),n.removeAttribute("src"),n.load(),t++}),e.querySelectorAll("audio").forEach(n=>{n.pause(),n.removeAttribute("src"),n.load()}),e.querySelectorAll(".pdf-widget").forEach(n=>{n._pdfDestroy&&n._pdfDestroy()}),t>0&&Z.info(`Released ${t} video(s)${i?` (${i} HLS)`:""}`)}evictLRU(){let e=null,t=1/0;for(const[i,n]of this.layouts)n.status==="warm"&&n.lastAccess<t&&(e=i,t=n.lastAccess);e!==null&&this.evict(e)}clearWarm(){let e=0;const t=[];for(const[i,n]of this.layouts)n.status==="warm"&&t.push(i);for(const i of t)this.evict(i),e++;return e>0&&Z.info(`Cleared ${e} warm layout(s) from pool`),e}clearWarmNotIn(e){let t=0;const i=[];for(const[n,o]of this.layouts)o.status==="warm"&&!e.has(n)&&i.push(n);for(const n of i)this.evict(n),t++;return t>0&&Z.info(`Cleared ${t} warm layout(s) no longer in schedule`),t}getLatest(){let e;for(const t of this.layouts.keys())e=t;return e}clear(){const e=Array.from(this.layouts.keys());for(const t of e)this.evict(t);this.hotLayoutId=null}get size(){return this.layouts.size}}const oe={fadeIn(p,e){const t=[{opacity:0},{opacity:1}],i={duration:e,easing:"linear",fill:"forwards"};return p.animate(t,i)},fadeOut(p,e){const t=[{opacity:1},{opacity:0}],i={duration:e,easing:"linear",fill:"forwards"};return p.animate(t,i)},getFlyKeyframes(p,e,t,i){const n={N:{x:0,y:i?-t:t},NE:{x:i?e:-e,y:i?-t:t},E:{x:i?e:-e,y:0},SE:{x:i?e:-e,y:i?t:-t},S:{x:0,y:i?t:-t},SW:{x:i?-e:e,y:i?t:-t},W:{x:i?-e:e,y:0},NW:{x:i?-e:e,y:i?-t:t}},o=n[p]||n.N;return i?{from:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0},to:{transform:"translate(0, 0)",opacity:1}}:{from:{transform:"translate(0, 0)",opacity:1},to:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0}}},flyIn(p,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!0),s={duration:e,easing:"ease-out",fill:"forwards"};return p.animate([o.from,o.to],s)},flyOut(p,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!1),s={duration:e,easing:"ease-in",fill:"forwards"};return p.animate([o.from,o.to],s)},apply(p,e,t,i,n){if(!e||!e.type)return null;const o=e.type.toLowerCase(),s=e.duration||1e3,r=e.direction||"N";switch(o){case"fade":return t?this.fadeIn(p,s):this.fadeOut(p,s);case"fadein":return t?this.fadeIn(p,s):null;case"fadeout":return t?null:this.fadeOut(p,s);case"fly":return t?this.flyIn(p,s,r,i,n):this.flyOut(p,s,r,i,n);case"flyin":return t?this.flyIn(p,s,r,i,n):null;case"flyout":return t?null:this.flyOut(p,s,r,i,n);default:return null}}};class dt{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=V("RendererLite",i.logLevel),this.emitter=new de,this.currentLayout=null,this.currentLayoutId=null,this._preloadingLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback=null,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=new Map,this.layoutBlobUrls=new Map,this.audioOverlays=new Map,this._stopWidgetBound=(n,o)=>this.stopWidget(n,o),this._renderWidgetBound=(n,o)=>this.renderWidget(n,o),this.scaleFactor=1,this.offsetX=0,this.offsetY=0,this.overlayContainer=null,this.activeOverlays=new Map,this._keydownHandler=null,this._keyboardActions=[],this._subPlaylistCycleIndex=new Map,this._startedWidgets=new Set,this.layoutPool=new ne(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.emitter.on("interactiveTrigger",n=>this._handleInteractiveTrigger(n)),this.emitter.on("widgetExpire",n=>this._handleWidgetExpire(n)),this.emitter.on("widgetExtendDuration",n=>this._handleWidgetExtendDuration(n)),this.emitter.on("widgetSetDuration",n=>this._handleWidgetSetDuration(n)),this.log.info("Initialized")}setupContainer(){if(this.container.style.position="relative",this.container.style.width="100%",this.container.style.height="100vh",this.container.style.overflow="hidden",this._resizeSuppressed=!1,typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{this._resizeSuppressed||(e&&clearTimeout(e),e=setTimeout(()=>this.rescaleRegions(),150))}),this.resizeObserver.observe(this.container)}this.overlayContainer=document.createElement("div"),this.overlayContainer.id="overlay-container",this.overlayContainer.style.position="absolute",this.overlayContainer.style.top="0",this.overlayContainer.style.left="0",this.overlayContainer.style.width="100%",this.overlayContainer.style.height="100%",this.overlayContainer.style.zIndex="1000",this.overlayContainer.style.pointerEvents="none",this.container.appendChild(this.overlayContainer)}calculateScale(e){const t=this.container.clientWidth,i=this.container.clientHeight;if(!t||!i)return;const n=t/e.width,o=i/e.height;this.scaleFactor=Math.min(n,o),this.offsetX=(t-e.width*this.scaleFactor)/2,this.offsetY=(i-e.height*this.scaleFactor)/2,this.log.info(`Scale: ${this.scaleFactor.toFixed(3)} (${e.width}x${e.height} → ${t}x${i}, offset ${Math.round(this.offsetX)},${Math.round(this.offsetY)})`)}applyRegionScale(e,t){const i=this.scaleFactor;e.style.left=`${t.left*i+this.offsetX}px`,e.style.top=`${t.top*i+this.offsetY}px`,e.style.width=`${t.width*i}px`,e.style.height=`${t.height*i}px`}rescaleRegions(){if(this.currentLayout){this.calculateScale(this.currentLayout);for(const[e,t]of this.regions)this.applyRegionScale(t.element,t.config),t.width=t.config.width*this.scaleFactor,t.height=t.config.height*this.scaleFactor;for(const[e,t]of this.activeOverlays){this.calculateScale(t.layout);for(const[i,n]of t.regions)this.applyRegionScale(n.element,n.config),n.width=n.config.width*this.scaleFactor,n.height=n.config.height*this.scaleFactor}}}on(e,t){this.emitter.on(e,t)}emit(e,...t){this.emitter.emit(e,...t)}parseActions(e){const t=[];for(const i of e.children)i.tagName==="action"&&t.push({id:i.getAttribute("id")||"",actionType:i.getAttribute("actionType")||"",triggerType:i.getAttribute("triggerType")||"",triggerCode:i.getAttribute("triggerCode")||"",source:i.getAttribute("source")||"",sourceId:i.getAttribute("sourceId")||"",target:i.getAttribute("target")||"",targetId:i.getAttribute("targetId")||"",widgetId:i.getAttribute("widgetId")||"",layoutCode:i.getAttribute("layoutCode")||"",commandCode:i.getAttribute("commandCode")||""});return t}parseXlf(e){const n=new DOMParser().parseFromString(e,"text/xml").querySelector("layout");if(!n)throw new Error("Invalid XLF: no <layout> element");const o=n.getAttribute("duration"),s={schemaVersion:parseInt(n.getAttribute("schemaVersion")||"1"),width:parseInt(n.getAttribute("width")||"1920"),height:parseInt(n.getAttribute("height")||"1080"),duration:o?parseInt(o):0,bgcolor:n.getAttribute("backgroundColor")||n.getAttribute("bgcolor")||"#000000",background:n.getAttribute("background")||null,enableStat:n.getAttribute("enableStat")!=="0",actions:this.parseActions(n),regions:[]};s.schemaVersion>1&&this.log.debug(`XLF schema version: ${s.schemaVersion}`),o?this.log.info(`Layout duration from XLF: ${s.duration}s`):this.log.info("Layout duration NOT in XLF, will calculate from widgets");const r=n.querySelectorAll(":scope > region, :scope > drawer");for(const a of r){const l=a.tagName==="drawer",d=a.getAttribute("type")||null,c={id:a.getAttribute("id"),width:parseInt(a.getAttribute("width")||"0"),height:parseInt(a.getAttribute("height")||"0"),top:parseInt(a.getAttribute("top")||"0"),left:parseInt(a.getAttribute("left")||"0"),zindex:parseInt(a.getAttribute("zindex")||(l?"2000":"0")),enableStat:a.getAttribute("enableStat")!=="0",actions:this.parseActions(a),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:l,isCanvas:d==="canvas",widgets:[]},g=Array.from(a.children).find(h=>h.tagName==="options");if(g){const h=g.querySelector("exitTransType");if(h&&h.textContent){const y=g.querySelector("exitTransDuration"),b=g.querySelector("exitTransDirection");c.exitTransition={type:h.textContent,duration:parseInt(y&&y.textContent||"1000"),direction:b&&b.textContent||"N"}}const m=g.querySelector("loop");m&&(c.loop=m.textContent!=="0");const w=g.querySelector("transitionType");if(w&&w.textContent){c.transitionType=w.textContent;const y=g.querySelector("transitionDuration"),b=g.querySelector("transitionDirection");c.transitionDuration=parseInt(y&&y.textContent||"1000"),c.transitionDirection=b&&b.textContent||"N"}}for(const h of a.children){if(h.tagName!=="media")continue;const m=this.parseWidget(h);c.widgets.push(m)}!c.isCanvas&&c.widgets.some(h=>h.type==="global")&&(c.isCanvas=!0),s.regions.push(c),l&&this.log.info(`Parsed drawer: id=${c.id} with ${c.widgets.length} widgets`),c.isCanvas&&this.log.info(`Parsed canvas region: id=${c.id} with ${c.widgets.length} widgets (all render simultaneously)`)}if(s.duration===0){const{duration:a,isDynamic:l}=We(e);s.duration=a,s.isDynamic=l,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)${l?" [dynamic — has useDuration=0 video]":""}`)}return s}parseWidget(e){const t=e.getAttribute("type"),i=parseInt(e.getAttribute("duration")||"10"),n=parseInt(e.getAttribute("useDuration")||"1"),o=e.getAttribute("id"),s=e.getAttribute("fileId"),r={},a=e.querySelector("options");if(a)for(const _ of a.children)r[_.tagName]=_.textContent;const l=e.querySelector("raw"),d=l?l.textContent:"",c={in:null,out:null};r.transIn&&(c.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(c.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const g=this.parseActions(e),h=[];for(const _ of e.children)if(_.tagName.toLowerCase()==="audio"){const L=_.querySelector("uri");L?h.push({mediaId:L.getAttribute("mediaId")||null,uri:L.textContent||"",volume:parseInt(L.getAttribute("volume")||"100"),loop:L.getAttribute("loop")==="1"}):h.push({mediaId:_.getAttribute("mediaId")||null,uri:_.getAttribute("uri")||"",volume:parseInt(_.getAttribute("volume")||"100"),loop:_.getAttribute("loop")==="1"})}const m=[],w=Array.from(e.children).find(_=>_.tagName==="commands");if(w)for(const _ of w.children)_.tagName==="command"&&m.push({commandCode:_.getAttribute("commandCode")||"",commandString:_.getAttribute("commandString")||""});const y=e.getAttribute("parentWidgetId")||null,b=parseInt(e.getAttribute("displayOrder")||"0"),C=e.getAttribute("cyclePlayback")==="1",I=parseInt(e.getAttribute("playCount")||"0"),M=e.getAttribute("isRandom")==="1",D=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,S=e.getAttribute("toDt")||e.getAttribute("todt")||null,T=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:T,fromDt:D,toDt:S,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:d,transitions:c,actions:g,audioNodes:h,commands:m,parentWidgetId:y,displayOrder:b,cyclePlayback:C,playCount:I,isRandom:M}}trackBlobUrl(e){const t=this._preloadingLayoutId||this.currentLayoutId||0;t||this.log.warn("trackBlobUrl called without currentLayoutId, tracking under key 0"),this.layoutBlobUrls.has(t)||this.layoutBlobUrls.set(t,new Set),this.layoutBlobUrls.get(t).add(e)}revokeBlobUrlsForLayout(e){const t=this.layoutBlobUrls.get(e);t&&(t.forEach(i=>{URL.revokeObjectURL(i)}),this.layoutBlobUrls.delete(e),this.log.info(`Revoked ${t.size} blob URLs for layout ${e}`))}updateLayoutDuration(){if(!this.currentLayout)return;let e=0;for(const t of this.currentLayout.regions){if(t.isDrawer)continue;let i=0;for(const n of t.widgets)n.duration>0&&(i+=n.duration);e=Math.max(e,i)}if(e>0&&e!==this.currentLayout.duration){const t=this.currentLayout.duration;this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`);const i=!this._hasUnprobedVideos();if(this.emit("layoutDurationUpdated",this.currentLayoutId,e,i),this._deferredTimerLayoutId===this.currentLayoutId&&!this.layoutTimer)if(this._hasUnprobedVideos())this.log.info(`Layout duration updated to ${e}s but still has unprobed videos — keeping timer deferred`);else{this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,e*1e3-n);this._deferredTimerLayoutId=null,this._layoutTimerDurationMs=o,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},o),this.log.info(`All video durations resolved — deferred timer started: ${(o/1e3).toFixed(1)}s remaining (waited ${(n/1e3).toFixed(1)}s for metadata)`)}else if(this.layoutTimer){clearTimeout(this.layoutTimer);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,this.currentLayout.duration*1e3-n);this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},o),this.log.info(`Layout timer adjusted to ${(o/1e3).toFixed(1)}s remaining (elapsed ${(n/1e3).toFixed(1)}s of ${this.currentLayout.duration}s)`)}else this.log.info(`Layout duration updated to ${e}s (timer not yet started, will use new value)`);this._scheduleNextLayoutPreload(this.currentLayout)}}attachActionListeners(e){var n;const t=[];let i=0;for(const o of e.actions||[])o.triggerType==="touch"?(this.attachTouchAction(this.container,o,null,null),i++):(n=o.triggerType)!=null&&n.startsWith("keyboard:")&&t.push(o);for(const o of e.regions){const s=this.regions.get(o.id);if(s){for(const r of o.actions||[])r.triggerType==="touch"?(this.attachTouchAction(s.element,r,o.id,null),i++):r.triggerType.startsWith("keyboard:")&&t.push(r);for(const r of o.widgets){if(!r.actions||r.actions.length===0)continue;const a=s.widgetElements.get(r.id);if(a)for(const l of r.actions)l.triggerType==="touch"?(this.attachTouchAction(a,l,o.id,r.id),i++):l.triggerType.startsWith("keyboard:")&&t.push(l)}}}this.setupKeyboardListener(t),(i>0||t.length>0)&&this.log.info(`Actions attached: ${i} touch, ${t.length} keyboard`)}attachTouchAction(e,t,i,n){e.style.cursor="pointer";const o=s=>{s.stopPropagation();const r=n?`widget ${n}`:`region ${i}`;this.log.info(`Touch action fired on ${r}: ${t.actionType}`),this.emit("action-trigger",{actionType:t.actionType,triggerType:"touch",triggerCode:t.triggerCode,layoutCode:t.layoutCode,targetId:t.targetId,commandCode:t.commandCode,source:{regionId:i,widgetId:n}})};e.addEventListener("click",o),e._actionHandlers||(e._actionHandlers=[]),e._actionHandlers.push(o)}setupKeyboardListener(e){this.removeKeyboardListener(),this._keyboardActions=e,e.length!==0&&(this._keydownHandler=t=>{const i=t.key;for(const n of this._keyboardActions){const o=n.triggerType.substring(9);if(i===o){this.log.info(`Keyboard action (key: ${i}): ${n.actionType}`),this.emit("action-trigger",{actionType:n.actionType,triggerType:n.triggerType,triggerCode:n.triggerCode,layoutCode:n.layoutCode,targetId:n.targetId,commandCode:n.commandCode,source:{key:i}});break}}},document.addEventListener("keydown",this._keydownHandler))}removeKeyboardListener(){this._keydownHandler&&(document.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),this._keyboardActions=[]}removeActionListeners(){for(const[,e]of this.regions){this._cleanElementActionHandlers(e.element);for(const[,t]of e.widgetElements)this._cleanElementActionHandlers(t)}this.removeKeyboardListener()}_cleanElementActionHandlers(e){if(e._actionHandlers){for(const t of e._actionHandlers)e.removeEventListener("click",t);delete e._actionHandlers,e.style.cursor=""}}_findRegionByWidgetId(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1)return{regionId:t,region:i,widget:i.widgets[n],widgetIndex:n,regionMap:this.regions}}for(const t of this.activeOverlays.values())if(t.regions)for(const[i,n]of t.regions){const o=n.widgets.findIndex(s=>s.id===e);if(o!==-1)return{regionId:i,region:n,widget:n.widgets[o],widgetIndex:o,regionMap:t.regions}}return null}_advanceRegion(e,t){const i=t.get(e);if(!i)return;i.currentIndex=(i.currentIndex+1)%i.widgets.length;const n=t===this.regions;this._startRegionCycle(i,e,n?this._renderWidgetBound:this._renderWidgetBound,n?this._stopWidgetBound:this._stopWidgetBound,n?()=>this.checkLayoutComplete():void 0)}_handleInteractiveTrigger({targetId:e,triggerCode:t}){this.log.info(`XIC interactiveTrigger: target=${e} code=${t}`),this._findRegionByWidgetId(e)?this.navigateToWidget(e):this.log.warn(`XIC interactiveTrigger: widget ${e} not found`)}_handleWidgetExpire({widgetId:e}){const t=this._findRegionByWidgetId(e);if(!t){this.log.warn(`XIC widgetExpire: widget ${e} not found`);return}const{regionId:i,region:n,widgetIndex:o,regionMap:s}=t;this.log.info(`XIC widgetExpire: widget=${e} region=${i}`),n.timer&&(clearTimeout(n.timer),n.timer=null),this.stopWidget(i,o),this._advanceRegion(i,s)}_handleWidgetExtendDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetExtendDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetExtendDuration: widget=${e} +${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}_handleWidgetSetDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetSetDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetSetDuration: widget=${e} ${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}navigateToWidget(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1){if(this.log.info(`Navigating to widget ${e} in region ${t} (index ${n})`),i.isDrawer&&i.element.style.display==="none"&&(i.element.style.display="",this.log.info(`Drawer region ${t} revealed`)),i.timer&&(clearTimeout(i.timer),i.timer=null),this.stopWidget(t,i.currentIndex),i.currentIndex=n,this.renderWidget(t,n),i.widgets.length>1){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n);const r=(n+1)%i.widgets.length;i.currentIndex=r,i.isDrawer&&r===0?(i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (cycle complete)`)):i.isDrawer?this.navigateToWidget(i.widgets[r].id):this.startRegion(t)},s)}else if(i.isDrawer){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n),i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (single widget done)`)},s)}return}}this.log.warn(`Target widget ${e} not found in any region`)}nextWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex+1)%t.widgets.length,n=t.widgets[i];this.log.info(`nextWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}previousWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex-1+t.widgets.length)%t.widgets.length,n=t.widgets[i];this.log.info(`previousWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}_mediaFileUrl(e){return`${window.location.origin}${H}/media/file/${e}`}_positionWidgetElement(e){Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",visibility:"hidden",opacity:"0"})}_applyBackgroundImage(e,t){Object.assign(e.style,{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"})}_clearRegionTimers(e){for(const[,t]of e)t.timer&&(clearTimeout(t.timer),t.timer=null)}async renderLayout(e,t){var i;try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,s]of this.regions)s.currentIndex=0,s.complete=!1;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null),this.emit("layoutStart",t,this.currentLayout);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,this.currentLayout),this.log.info(`Layout ${t} restarted (reused elements)`),this._scheduleNextLayoutPreload(this.currentLayout);return}if(this.layoutPool.has(t)){this.log.info(`Layout ${t} found in preload pool - instant swap!`),await this._swapToPreloadedLayout(t);return}this.log.info(`Switching to new layout ${t}`),this.stopCurrentLayout();const o=this.parseXlf(e);if(this.currentLayout=o,this.currentLayoutId=t,this.calculateScale(o),this.container.style.backgroundColor=o.bgcolor,this.container.style.backgroundImage="",o.background){const s=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(o.background)))||o.background;this._applyBackgroundImage(this.container,this._mediaFileUrl(s)),this.log.info(`Background image set: ${o.background} → ${s}`)}for(const s of o.regions)await this.createRegion(s);this.log.info("Pre-creating widget elements for instant transitions...");for(const[s,r]of this.regions)for(let a=0;a<r.widgets.length;a++){const l=r.widgets[a];l.layoutId=this.currentLayoutId,l.regionId=s;try{const d=await this.createWidgetElement(l,r);this._positionWidgetElement(d),r.element.appendChild(d),r.widgetElements.set(l.id,d)}catch(d){this.log.error(`Failed to pre-create widget ${l.id}:`,d)}}if(this.log.info("All widget elements pre-created"),this.attachActionListeners(o),this.emit("layoutStart",t,o),o.duration>0){const s=!this._hasUnprobedVideos();this.emit("layoutDurationUpdated",t,o.duration,s)}for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,o),this._scheduleNextLayoutPreload(o),this.log.info(`Layout ${t} started`)}catch(n){throw this.log.error("Error rendering layout:",n),this.emit("error",{type:"layoutError",error:n,layoutId:t}),n}}async createRegion(e){const t=document.createElement("div");t.id=`region_${e.id}`,t.className="renderer-lite-region",t.style.position="absolute",t.style.zIndex=e.zindex,t.style.overflow="hidden",e.isDrawer&&(t.style.display="none"),this.applyRegionScale(t,e),this.container.appendChild(t);let i=e.widgets.filter(o=>this._isWidgetActive(o));i.some(o=>o.cyclePlayback)&&(i=this._applyCyclePlayback(i));const n=this.scaleFactor;this.regions.set(e.id,{element:t,config:e,widgets:i,currentIndex:0,timer:null,width:e.width*n,height:e.height*n,complete:!1,isDrawer:e.isDrawer||!1,isCanvas:e.isCanvas||!1,widgetElements:new Map})}startRegion(e){const t=this.regions.get(e);this._startRegionCycle(t,e,this._renderWidgetBound,this._stopWidgetBound,()=>{this.log.info(`Region ${e} completed one full cycle`),this.checkLayoutComplete()})}async createWidgetElement(e,t){if(e.render==="html"&&e.type!=="pdf")return await this.renderGenericWidget(e,t);switch(e.type){case"image":return await this.renderImage(e,t);case"video":return await this.renderVideo(e,t);case"audio":return await this.renderAudio(e,t);case"text":case"ticker":return await this.renderTextWidget(e,t);case"pdf":return await this.renderPdf(e,t);case"webpage":return await this.renderWebpage(e,t);case"localvideo":return await this.renderVideo(e,t);case"videoin":return await this.renderVideoIn(e,t);case"powerpoint":case"flash":return this.log.warn(`Widget type '${e.type}' is not supported on web players (widget ${e.id})`),this._renderUnsupportedPlaceholder(e,t);default:return await this.renderGenericWidget(e,t)}}findMediaElement(e,t){return e.tagName===t?e:e.querySelector(t.toLowerCase())}updateMediaElement(e,t){const i=this.findMediaElement(e,"VIDEO")||this.findMediaElement(e,"AUDIO");if(i){if(i.tagName==="VIDEO"&&i._mediaConstraints&&!i._mediaStream){navigator.mediaDevices.getUserMedia(i._mediaConstraints).then(n=>{i.srcObject=n,i._mediaStream=n,this.log.info(`Webcam stream re-acquired for widget ${t.id}`)}).catch(n=>{this.log.warn("Failed to re-acquire webcam stream:",n.message)});return}this._restartMediaElement(i),this.log.info(`${i.tagName==="VIDEO"?"Video":"Audio"} restarted: ${t.fileId||t.id}`)}}_restartMediaElement(e){e.currentTime=0;const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t),e.currentTime===0&&e.readyState>=2&&(e.removeEventListener("seeked",t),e.play().catch(()=>{}))}waitForWidgetReady(e,t){const n=this.findMediaElement(e,"VIDEO");if(n)return!n.paused&&n.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{n.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",l)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{o.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",l)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()},l=setTimeout(()=>{s.removeEventListener("load",a),this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4);s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[n,o]of this.regions){if(o.widgets.length===0)continue;const s=o.widgets[o.currentIndex||0],r=o.widgetElements.get(s.id);r&&i.push(this.waitForWidgetReady(r,s))}if(i.length>0&&(this.log.info(`Waiting for ${i.length} widget(s) to be ready before starting layout timer...`),await Promise.all(i),this.log.info("All widgets ready — starting layout timer")),this.currentLayoutId!==e){this.log.warn(`Layout changed while waiting for widgets — skipping timer for ${e}`);return}if(t.isDynamic&&this._hasUnprobedVideos()){this._deferredTimerLayoutId=e,this._layoutTimerStartedAt=Date.now(),this.log.info(`Layout ${e} has unprobed videos — deferring timer until metadata loads`),this._deferredTimerFallback=setTimeout(()=>{this._deferredTimerFallback=null,this._deferredTimerLayoutId===e&&!this.layoutTimer&&(this.log.warn(`Layout ${e}: metadata timeout after 30s — starting timer with ${t.duration}s estimate`),this._deferredTimerLayoutId=null,this._startLayoutTimer(e,t))},3e4);return}this._startLayoutTimer(e,t)}_hasUnprobedVideos(){for(const[,e]of this.regions)for(const t of e.widgets)if(t.useDuration===0&&!t._probed)return!0;return!1}_startLayoutTimer(e,t){this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null);const i=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=i,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},i)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);if(n||(this.log.warn(`Widget ${i.id} not pre-created, creating now`),n=await this.createWidgetElement(i,e),n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",e.widgetElements.set(i.id,n),e.element.appendChild(n)),!e.isCanvas)for(const[r,a]of e.widgetElements)r!==i.id&&((o=a.getAnimations)==null||o.call(a).forEach(l=>l.cancel()),a.style.visibility="hidden",a.style.opacity="0");return this.updateMediaElement(n,i),(s=n.getAnimations)==null||s.call(n).forEach(r=>r.cancel()),n.style.visibility="visible",i.transitions.in?oe.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",n._pdfResume&&n._pdfResume(),this._startAudioOverlays(i),i}_startAudioOverlays(e){if(!e.audioNodes||e.audioNodes.length===0)return;this._stopAudioOverlays(e.id);const t=[];for(const i of e.audioNodes){if(!i.uri)continue;const n=document.createElement("audio");n.autoplay=!0,n.loop=i.loop,n.volume=Math.max(0,Math.min(1,i.volume/100)),n.src=i.uri?this._mediaFileUrl(i.uri):"",n.style.display="none",this.container.appendChild(n);const o=n.play();o&&o.catch&&o.catch(()=>{}),t.push(n),this.log.info(`Audio overlay started for widget ${e.id}: ${i.uri} (loop=${i.loop}, vol=${i.volume})`)}t.length>0&&this.audioOverlays.set(e.id,t)}_stopAudioOverlays(e){const t=this.audioOverlays.get(e);if(t){for(const i of t)i.pause(),i.removeAttribute("src"),i.load(),i.parentNode&&i.parentNode.removeChild(i);this.audioOverlays.delete(e),this.log.info(`Audio overlays stopped for widget ${e}`)}}_hideWidget(e,t){const i=e.widgets[t];if(!i)return{widget:null,animPromise:null};const n=e.widgetElements.get(i.id);if(!n)return{widget:null,animPromise:null};let o=null;if(i.transitions.out){const a=oe.apply(n,i.transitions.out,!1,e.width,e.height);a&&(o=new Promise(l=>{a.onfinish=l}))}const s=n.querySelector("video");if(s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(a=>a.stop()),s._mediaStream=null,s.srcObject=null),s!=null&&s._hlsInstance&&(s._hlsInstance.destroy(),s._hlsInstance=null),s!=null&&s._eventCleanup){for(const[a,l]of s._eventCleanup)s.removeEventListener(a,l);s._eventCleanup=null}const r=n.querySelector("audio");if(r&&i.options.loop!=="1"&&r.pause(),r!=null&&r._eventCleanup){for(const[a,l]of r._eventCleanup)r.removeEventListener(a,l);r._eventCleanup=null}return this._stopAudioOverlays(i.id),n._pdfCleanup&&n._pdfCleanup(),{widget:i,animPromise:o}}_isWidgetActive(e){const t=new Date;if(e.fromDt){const i=new Date(e.fromDt);if(t<i)return!1}if(e.toDt){const i=new Date(e.toDt);if(t>i)return!1}return!0}_parseDurationComments(e,t){const i=t.duration,n=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(n){const s=parseInt(n[1],10);if(s>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${s}s`),t.duration=s,t.duration!==i&&this.updateLayoutDuration();return}}const o=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(o){const s=parseInt(o[1],10);if(s>0&&t.duration>0){const r=s*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${s} × ${t.duration}s = ${r}s`),t.duration=r}}t.duration!==i&&this.updateLayoutDuration()}_applyCyclePlayback(e){this._subPlaylistCycleIndex||(this._subPlaylistCycleIndex=new Map);const t=new Map,i=[];for(const n of e)n.parentWidgetId&&n.cyclePlayback?(t.has(n.parentWidgetId)||t.set(n.parentWidgetId,[]),t.get(n.parentWidgetId).push(n)):i.push({type:"direct",widget:n});for(const[n,o]of t){o.sort((r,a)=>r.displayOrder-a.displayOrder);let s;if(o.some(r=>r.isRandom)){const r=Math.floor(Math.random()*o.length);s=o[r]}else{const r=this._subPlaylistCycleIndex.get(n)||{widgetIdx:0,playsDone:0};s=o[r.widgetIdx%o.length];const a=s.playCount||1;r.playsDone++,r.playsDone>=a&&(r.widgetIdx++,r.playsDone=0),this._subPlaylistCycleIndex.set(n,r)}this.log.info(`Sub-playlist cycle: group ${n} selected widget ${s.id} (${o.length} in group)`),i.push({type:"direct",widget:s})}return i.map(n=>n.widget)}_startRegionCycle(e,t,i,n,o){if(!e||e.widgets.length===0)return;if(e.isCanvas){this._startCanvasRegion(e,t,i,o);return}if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,a=e.widgets[r];i(t,r);const l=a.duration*1e3;this.log.info(`Region ${t} widget ${a.id} (${a.type}) playing for ${a.duration}s (useDuration=${a.useDuration}, index ${r}/${e.widgets.length})`),e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(a,e,t,r,i,n,o,s)},l)};s()}_startCanvasRegion(e,t,i,n){for(let s=0;s<e.widgets.length;s++)i(t,s);const o=Math.max(...e.widgets.map(s=>s.duration))*1e3;o>0?e.timer=setTimeout(()=>{e.complete||(e.complete=!0,n==null||n())},o):(e.complete=!0,n==null||n())}_handleWidgetCycleEnd(e,t,i,n,o,s,r,a){var d;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const l=(t.currentIndex+1)%t.widgets.length;if(l===0&&!t.complete&&(t.complete=!0,r==null||r()),l===0&&((d=t.config)==null?void 0:d.loop)===!1&&t.widgets.length===1){o(i,0);return}this.layoutEndEmitted||(t.currentIndex=l,a())}async renderWidget(e,t){var n;const i=this.regions.get(e);if(i)try{const o=await this._showWidget(i,t);if(o&&(this.log.info(`Showing widget ${o.type} (${o.id}) in region ${e}`),this._startedWidgets.add(`${e}:${t}`),this.emit("widgetStart",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,duration:o.duration,enableStat:o.enableStat}),o.commands&&o.commands.length>0))for(const s of o.commands)this.emit("widgetCommand",{commandCode:s.commandCode,commandString:s.commandString,widgetId:o.id,regionId:e,layoutId:this.currentLayoutId})}catch(o){this.log.error("Error rendering widget:",o),this.emit("error",{type:"widgetError",error:o,widgetId:(n=i.widgets[t])==null?void 0:n.id,regionId:e})}}async stopWidget(e,t){const i=`${e}:${t}`;if(!this._startedWidgets.delete(i))return;const n=this.regions.get(e);if(!n)return;const{widget:o,animPromise:s}=this._hideWidget(n,t);o&&this.emit("widgetEnd",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,enableStat:o.enableStat}),s&&await s}_stopAllRegionWidgets(e,t){for(const[i,n]of e)if(n.isCanvas)for(let o=0;o<n.widgets.length;o++)t(i,o);else n.widgets.length>0&&t(i,n.currentIndex)}async renderImage(e,t){const i=document.createElement("img");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"contain",fit:"cover"};i.style.objectFit=o[n]||"contain";const s={left:"left",center:"center",right:"right"},r={top:"top",middle:"center",bottom:"bottom"},a=s[e.options.alignId]||"center",l=r[e.options.valignId]||"center";i.style.objectPosition=`${a} ${l}`,i.style.opacity="0";const d=e.options.uri?this._mediaFileUrl(e.options.uri):"";return i.src=d,i}async renderVideo(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"none",fit:"contain"};i.style.objectFit=o[n]||"contain",i.style.opacity="1",i.autoplay=!0,i.preload="auto",i.muted=e.options.mute==="1",i.loop=!1,i.controls=!1,i.playsInline=!0;const s=e.options.uri||"",r=e.fileId||e.id,a=()=>{e.options.loop==="1"?(i.currentTime=0,this.log.info(`Video ${s} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Video ${s} ended - paused on last frame`)};i.addEventListener("ended",a);let l=s?this._mediaFileUrl(s):"";if(l.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${r}`),i.src=l;else try{const{default:y}=await N(async()=>{const{default:b}=await import("hls.js");return{default:b}},[],import.meta.url);if(y.isSupported()){const b=new y({enableWorker:!0,lowLatencyMode:!0});b.loadSource(l),b.attachMedia(i),i._hlsInstance=b,b.on(y.Events.ERROR,(C,I)=>{I.fatal&&(this.log.error(`HLS fatal error: ${I.type}`,I.details),b.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${r}`)}else this.log.warn(`HLS not supported on this browser for ${r}`),i.src=l}catch(y){this.log.warn(`hls.js not available, falling back to native: ${y.message}`),i.src=l}else i.src=l;const c=this.currentLayoutId,g=()=>{const y=i.duration;this.log.info(`Video ${s} duration detected: ${y}s`),(e.duration===0||e.useDuration===0)&&(e.duration=y,e._probed=!0,this.log.info(`Updated widget ${e.id} duration to ${y}s (useDuration=0)`),this.currentLayoutId===c?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${c}, current is ${this.currentLayoutId})`))};i.addEventListener("loadedmetadata",g);const h=()=>{this.log.info("Video loaded and ready:",s)};i.addEventListener("loadeddata",h);const m=()=>{const y=i.error,b=y==null?void 0:y.code,C=(y==null?void 0:y.message)||"Unknown error";this.log.warn(`Video error: ${s}, code: ${b}, time: ${i.currentTime.toFixed(1)}s, message: ${C}`),e.useDuration===0&&e.duration===0&&(e.duration=60,this.log.info(`Set fallback duration 60s for errored widget ${e.id}`),this.currentLayoutId===c&&this.updateLayoutDuration()),this.emit("videoError",{storedAs:s,fileId:r,errorCode:b,errorMessage:C,currentTime:i.currentTime})};i.addEventListener("error",m);const w=()=>{this.log.info("Video playing:",s)};return i.addEventListener("playing",w),i._eventCleanup=[["ended",a],["loadedmetadata",g],["loadeddata",h],["error",m],["playing",w]],this.log.info("Video element created:",s,i.src),i}async renderVideoIn(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.objectFit=e.options.showFullScreen==="1"?"cover":"contain",i.autoplay=!0,i.playsInline=!0,i.controls=!1,i.muted=e.options.mute!=="0",e.options.mirror==="1"&&(i.style.transform="scaleX(-1)");const n={width:{ideal:t.width},height:{ideal:t.height}},o=e.options.sourceId||e.options.deviceId;o?n.deviceId={exact:o}:n.facingMode=e.options.facingMode||"environment";const s={video:n,audio:e.options.captureAudio==="1"};i._mediaConstraints=s;try{const r=await navigator.mediaDevices.getUserMedia(s);i.srcObject=r,i._mediaStream=r,this.log.info(`Webcam stream acquired for widget ${e.id} (tracks: ${r.getTracks().length})`)}catch(r){return this.log.warn(`getUserMedia failed for widget ${e.id}: ${r.message}`),this._renderUnsupportedPlaceholder({...e,type:"Camera unavailable"},t)}return i}async renderAudio(e,t){const i=document.createElement("div");i.className="renderer-lite-widget audio-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.background="linear-gradient(135deg, #667eea 0%, #764ba2 100%)",i.style.opacity="0";const n=document.createElement("audio");n.autoplay=!0,n.loop=e.options.loop==="1",n.volume=parseFloat(e.options.volume||"100")/100;const o=e.options.uri||"";e.fileId||e.id,n.src=o?this._mediaFileUrl(o):"";const s=()=>{e.options.loop==="1"?(n.currentTime=0,this.log.info(`Audio ${o} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Audio ${o} ended - playback complete`)};n.addEventListener("ended",s);const r=this.currentLayoutId,a=()=>{const h=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${h}s`),(e.duration===0||e.useDuration===0)&&(e.duration=h,this.log.info(`Updated widget ${e.id} duration to ${h}s (useDuration=0)`),this.currentLayoutId===r?this.updateLayoutDuration():this.log.info(`Audio ${o} duration set but layout timer not updated (preloaded for layout ${r}, current is ${this.currentLayoutId})`))};n.addEventListener("loadedmetadata",a);const l=()=>{const h=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${h==null?void 0:h.code}, message: ${(h==null?void 0:h.message)||"Unknown"}`)};n.addEventListener("error",l),n._eventCleanup=[["ended",s],["loadedmetadata",a],["error",l]];const d=document.createElement("div");d.innerHTML="♪",d.style.fontSize="120px",d.style.color="white",d.style.marginBottom="20px";const c=document.createElement("div");c.style.color="white",c.style.fontSize="24px",c.textContent="Playing Audio";const g=document.createElement("div");return g.style.color="rgba(255,255,255,0.7)",g.style.fontSize="16px",g.style.marginTop="10px",g.textContent=e.options.uri,i.appendChild(n),i.appendChild(d),i.appendChild(c),i.appendChild(g),i}async renderTextWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const r=await this.options.getWidgetHtml(e);if(r&&typeof r=="object"&&r.url)return i.src=r.url,r.fallback&&this._parseDurationComments(r.fallback,e),i;n=r}n&&this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);return i.src=s,this.trackBlobUrl(s),i}async renderPdf(e,t){const i=document.createElement("div");if(i.className="renderer-lite-widget pdf-widget",i.style.width="100%",i.style.height="100%",i.style.backgroundColor="transparent",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const o=await N(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=o;const s=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${s}pdf.worker.min.mjs`}catch(o){return this.log.error("PDF.js not available:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}let n=e.options.uri?this._mediaFileUrl(e.options.uri):"";try{const s=await window.pdfjsLib.getDocument(n).promise,r=s.numPages,a=e.duration||60,l=a*1e3/r;this.log.info(`[pdf] PDF loaded: ${r} pages, ${a}s duration, ${(l/1e3).toFixed(1)}s/page`);const d=await s.getPage(1),c=d.getViewport({scale:1}),g=Math.min(t.width/c.width,t.height/c.height);d.cleanup();const h=document.createElement("canvas");h.className="pdf-page",h.width=Math.floor(c.width*g),h.height=Math.floor(c.height*g),h.style.cssText="display:block;margin:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);";const m=h.getContext("2d");i.appendChild(h);const w=document.createElement("div");w.style.cssText="position:absolute;bottom:10px;right:10px;background:rgba(0,0,0,0.7);color:white;padding:8px 12px;border-radius:4px;font:14px system-ui;z-index:1;",Ne()||(w.style.display="none"),i.appendChild(w);let y=1,b=null,C=null,I=!1;const M=async()=>{if(I)return;w.textContent=`Page ${y} / ${r}`;const S=await s.getPage(y),T=S.getViewport({scale:g});m.clearRect(0,0,h.width,h.height),C=S.render({canvasContext:m,viewport:T});try{await C.promise}catch(_){if(I)return;throw _}C=null,S.cleanup(),r>1&&!I&&(b=setTimeout(()=>{y=y>=r?1:y+1,M()},l))};await M();let D=null;i._pdfCleanup=()=>{if(I=!0,b&&clearTimeout(b),b=null,C){const S=C;C=null,S.cancel(),D=S.promise.catch(()=>{})}},i._pdfResume=async()=>{i._pdfCleanup(),D&&(await D,D=null),I=!1,y=1,M()},i._pdfDestroy=()=>{i._pdfCleanup(),h.width=0,h.height=0,s.destroy()}}catch(o){this.log.error("PDF render failed:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">Failed to load PDF</div>'}return i.style.opacity="1",i}async renderWebpage(e,t){if(parseInt(e.options.modeId||"1")===0)return await this.renderGenericWidget(e,t);const n=document.createElement("iframe");n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0";const o=decodeURIComponent(e.options.uri||"");return n.src=o,n}async renderGenericWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const o=await this.options.getWidgetHtml(e);if(o&&typeof o=="object"&&o.url)return i.src=o.url,o.fallback&&this._parseDurationComments(o.fallback,e),i;n=o}if(n){this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);i.src=s,this.trackBlobUrl(s)}else this.log.warn(`No HTML for widget ${e.id}`),i.srcdoc='<div style="padding:20px;">Widget content unavailable</div>';return i}_renderUnsupportedPlaceholder(e,t){const i=document.createElement("div");return i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.backgroundColor="#111",i.style.color="#666",i.style.fontSize="14px",i.textContent=`Unsupported: ${e.type}`,i}_scheduleNextLayoutPreload(e){this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const t=e.duration||60,i=t*1e3*.75,n=t*1e3*.9;this.log.info(`Scheduling next layout preload in ${(i/1e3).toFixed(1)}s (75% of ${t}s)`),this.preloadTimer=setTimeout(()=>{this.preloadTimer=null,this.emit("request-next-layout-preload")},i),this._preloadRetryTimer=setTimeout(()=>{this._preloadRetryTimer=null,this.emit("request-next-layout-preload")},n)}hasPreloadedLayout(e){return this.layoutPool.has(e)}async preloadLayout(e,t){var i;if(this.layoutPool.has(t))return this.log.info(`Layout ${t} already in preload pool, skipping`),!0;if(this.currentLayoutId===t)return this.log.info(`Layout ${t} is current, skipping preload`),!0;try{this.log.info(`Preloading layout ${t} into pool...`);const n=this.parseXlf(e);this.calculateScale(n);const o=document.createElement("div");if(o.id=`preload_layout_${t}`,o.className="renderer-lite-preload-wrapper",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.visibility="hidden",o.style.zIndex="-1",o.style.backgroundColor=n.bgcolor,n.background){const g=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(n.background)))||n.background;this._applyBackgroundImage(o,this._mediaFileUrl(g))}const s=this.currentLayoutId,r=new Map,a=this.scaleFactor;for(const g of n.regions){const h=document.createElement("div");h.id=`preload_region_${t}_${g.id}`,h.className="renderer-lite-region",h.style.position="absolute",h.style.zIndex=g.zindex,h.style.overflow="hidden",this.applyRegionScale(h,g),o.appendChild(h);const m={element:h,config:g,widgets:g.widgets,currentIndex:0,timer:null,width:g.width*a,height:g.height*a,complete:!1,widgetElements:new Map};r.set(g.id,m)}const l=new Set,d=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,l),this._preloadingLayoutId=t;for(const[g,h]of r)for(let m=0;m<h.widgets.length;m++){const w=h.widgets[m];w.layoutId=t,w.regionId=g;try{const y=await this.createWidgetElement(w,h);this._positionWidgetElement(y),h.element.appendChild(y),h.widgetElements.set(w.id,y)}catch(y){this.log.error(`Preload: Failed to create widget ${w.id}:`,y)}}return this.currentLayoutId=s,o.querySelectorAll("video").forEach(g=>g.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(g=>l.add(g)),this.layoutBlobUrls=d,this.container.appendChild(o),this.layoutPool.add(t,{container:o,layout:n,regions:r,blobUrls:l}),this.log.info(`Layout ${t} preloaded into pool (${r.size} regions)`),!0}catch(n){return this.log.error(`Preload failed for layout ${t}:`,n),!1}}async _swapToPreloadedLayout(e){var o;const t=this.layoutPool.get(e);if(!t){this.log.error(`Cannot swap: layout ${e} not in pool`);return}this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const i=this.currentLayoutId,n=this.layoutEndEmitted;if(this.layoutEndEmitted=!1,i&&this.layoutPool.has(i))this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound),this.layoutPool.evict(i);else{this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,s]of this.regions)if(ne.releaseMediaElements(s.element),(o=s.config)!=null&&o.exitTransition){const r=oe.apply(s.element,s.config.exitTransition,!1,s.width,s.height);if(r){const a=s.element;r.onfinish=()=>a.remove()}else s.element.remove()}else s.element.remove();i&&this.revokeBlobUrlsForLayout(i)}if(this.currentLayout=null,this.currentLayoutId=null,this.regions.clear(),t.container.style.visibility="visible",t.container.style.zIndex="0",this.layoutPool.setHot(e),this.currentLayout=t.layout,this.currentLayoutId=e,this.regions=t.regions,i&&!n&&this.emit("layoutEnd",i),this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage)for(const s of["backgroundImage","backgroundSize","backgroundPosition","backgroundRepeat"])this.container.style[s]=t.container.style[s];else this.container.style.backgroundImage="";this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[s,r]of this.regions)r.currentIndex=0,r.complete=!1,this.startRegion(s);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this.preloadTimer||this._scheduleNextLayoutPreload(t.layout),this.log.info(`Swapped to preloaded layout ${e} (instant transition)`)}getCurrentLayoutId(){return this.currentLayoutId}showLayout(e){if(e===void 0&&(e=this.layoutPool.getLatest(),e===void 0)){this.log.warn("showLayout: no preloaded layout to show");return}if(this.currentLayoutId===e){this.log.info(`showLayout: layout ${e} already showing`);return}if(!this.layoutPool.has(e)){this.log.warn(`showLayout: layout ${e} not in preload pool`);return}this._swapToPreloadedLayout(e)}checkLayoutComplete(){let e=!0;for(const[t,i]of this.regions)if(i.widgets.length>1&&!i.complete){e=!1;break}e&&this.currentLayoutId&&this.log.info("All multi-widget regions completed one cycle")}stopCurrentLayout(){var i;if(!this.currentLayout)return;this.log.info(`Stopping layout ${this.currentLayoutId}`);const e=this.currentLayoutId,t=e&&!this.layoutEndEmitted;if(this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._deferredTimerFallback&&(clearTimeout(this._deferredTimerFallback),this._deferredTimerFallback=null),this.currentLayout=null,this.currentLayoutId=null,this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.removeActionListeners(),e&&this.layoutPool.has(e))this.layoutPool.evict(e);else{e&&this.revokeBlobUrlsForLayout(e),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,this._stopWidgetBound);for(const[,n]of this.regions)if(ne.releaseMediaElements(n.element),(i=n.config)!=null&&i.exitTransition){const o=oe.apply(n.element,n.config.exitTransition,!1,n.width,n.height);if(o){const s=n.element;o.onfinish=()=>s.remove()}else n.element.remove()}else n.element.remove()}this.regions.clear(),t&&this.emit("layoutEnd",e)}async renderOverlay(e,t,i=0){try{if(this.log.info(`Rendering overlay ${t} (priority ${i})`),this.activeOverlays.has(t)){this.log.warn(`Overlay ${t} already active, skipping`);return}const n=this.parseXlf(e),o=document.createElement("div");o.id=`overlay_${t}`,o.className="renderer-lite-overlay",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.zIndex=String(1e3+i),o.style.pointerEvents="auto",o.style.backgroundColor=n.bgcolor,this.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const a of n.regions){const l=document.createElement("div");l.id=`overlay_${t}_region_${a.id}`,l.className="renderer-lite-region overlay-region",l.style.position="absolute",l.style.zIndex=String(a.zindex),l.style.overflow="hidden",this.applyRegionScale(l,a),o.appendChild(l),s.set(a.id,{element:l,config:a,widgets:a.widgets,currentIndex:0,timer:null,width:a.width*r,height:a.height*r,complete:!1,isCanvas:a.isCanvas||!1,widgetElements:new Map})}for(const[a,l]of s)for(const d of l.widgets){d.layoutId=t,d.regionId=a;try{const c=await this.createWidgetElement(d,l);this._positionWidgetElement(c),l.element.appendChild(c),l.widgetElements.set(d.id,c)}catch(c){this.log.error(`Failed to pre-create overlay widget ${d.id}:`,c)}}this.overlayContainer.appendChild(o),this.activeOverlays.set(t,{container:o,layout:n,regions:s,timer:null,priority:i}),this.emit("overlayStart",t,n);for(const[a,l]of s)this.startOverlayRegion(t,a);if(n.duration>0){const a=n.duration*1e3,l=this.activeOverlays.get(t);l&&(l.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},a))}this.log.info(`Overlay ${t} started`)}catch(n){throw this.log.error("Error rendering overlay:",n),this.emit("error",{type:"overlayError",error:n,layoutId:t}),n}}startOverlayRegion(e,t){const i=this.activeOverlays.get(e);if(!i)return;const n=i.regions.get(t);this._startRegionCycle(n,t,(o,s)=>this.renderOverlayWidget(e,o,s),(o,s)=>this.stopOverlayWidget(e,o,s),()=>this.log.info(`Overlay ${e} region ${t} completed one full cycle`))}async renderOverlayWidget(e,t,i){var s;const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(o)try{const r=await this._showWidget(o,i);r&&(this.log.info(`Showing overlay widget ${r.type} (${r.id}) in overlay ${e} region ${t}`),this._startedWidgets.add(`overlay:${e}:${t}:${i}`),this.emit("overlayWidgetStart",{overlayId:e,widgetId:r.id,regionId:t,type:r.type,duration:r.duration}))}catch(r){this.log.error("Error rendering overlay widget:",r),this.emit("error",{type:"overlayWidgetError",error:r,widgetId:(s=o.widgets[i])==null?void 0:s.id,regionId:t,overlayId:e})}}async stopOverlayWidget(e,t,i){const n=`overlay:${e}:${t}:${i}`;if(!this._startedWidgets.delete(n))return;const o=this.activeOverlays.get(e);if(!o)return;const s=o.regions.get(t);if(!s)return;const{widget:r,animPromise:a}=this._hideWidget(s,i);r&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:r.id,regionId:t,type:r.type}),a&&await a}stopOverlay(e){const t=this.activeOverlays.get(e);if(!t){this.log.warn(`Overlay ${e} not active`);return}this.log.info(`Stopping overlay ${e}`),t.timer&&(clearTimeout(t.timer),t.timer=null);for(const[,i]of t.regions)i.timer&&(clearTimeout(i.timer),i.timer=null);this._stopAllRegionWidgets(t.regions,(i,n)=>this.stopOverlayWidget(e,i,n)),t.container&&t.container.remove(),this.revokeBlobUrlsForLayout(e),this.activeOverlays.delete(e),this.emit("overlayEnd",e),this.log.info(`Overlay ${e} stopped`)}stopAllOverlays(){const e=Array.from(this.activeOverlays.keys());for(const t of e)this.stopOverlay(t);this.log.info("All overlays stopped")}getActiveOverlays(){return Array.from(this.activeOverlays.keys())}pause(){if(!this._paused){this._paused=!0;for(const[,e]of this.regions)e.timer&&(clearTimeout(e.timer),e.timer=null);this._forEachMedia(e=>e.pause()),this.emit("paused"),this.log.info("Playback paused (layout timer continues)")}}isPaused(){return this._paused}resume(){if(this._paused){this._paused=!1,this._forEachMedia(e=>e.play().catch(()=>{}));for(const[e]of this.regions)this.startRegion(e);this.emit("resumed"),this.log.info("Playback resumed")}}_forEachMedia(e){var t;for(const[,i]of this.regions)(t=i.element)==null||t.querySelectorAll("video, audio").forEach(e)}cleanup(){this.stopAllOverlays(),this.stopCurrentLayout(),this._startedWidgets.clear();for(const e of this.audioOverlays.keys())this._stopAudioOverlays(e);this.layoutPool.clear(),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.innerHTML="",this.log.info("Cleaned up")}}const K=V("Layout");class $t{constructor(e){this.xmds=e}async translateXLF(e,t){const n=new DOMParser().parseFromString(t,"text/xml"),o=n.querySelector("layout");if(!o)throw new Error("Invalid XLF: no <layout> element");const s=parseInt(o.getAttribute("width")||"1920"),r=parseInt(o.getAttribute("height")||"1080"),a=o.getAttribute("bgcolor")||"#000000",l=[];for(const d of n.querySelectorAll("region"))l.push(await this.translateRegion(e,d));return this.generateHTML(s,r,a,l)}async translateRegion(e,t){const i=t.getAttribute("id"),n=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("height")),s=parseInt(t.getAttribute("top")),r=parseInt(t.getAttribute("left")),a=parseInt(t.getAttribute("zindex")||"0"),l=[];for(const d of t.querySelectorAll("media"))l.push(await this.translateMedia(e,i,d));return{id:i,width:n,height:o,top:s,left:r,zindex:a,media:l}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),a=i.querySelector("raw"),l={};if(r)for(const I of r.children)l[I.tagName]=I.textContent;const d={in:null,out:null},c=i.querySelector("options > transIn"),g=i.querySelector("options > transOut"),h=i.querySelector("options > transInDuration"),m=i.querySelector("options > transOutDuration"),w=i.querySelector("options > transInDirection"),y=i.querySelector("options > transOutDirection");c&&c.textContent&&(d.in={type:c.textContent,duration:parseInt((h==null?void 0:h.textContent)||"1000"),direction:(w==null?void 0:w.textContent)||"N"}),g&&g.textContent&&(d.out={type:g.textContent,duration:parseInt((m==null?void 0:m.textContent)||"1000"),direction:(y==null?void 0:y.textContent)||"N"});let b=a?a.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some(I=>n.includes(I))){let I=3,M=null;for(let D=1;D<=I;D++)try{K.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${D}/${I}`),b=await this.xmds.getResource(e,t,s),K.info(`Got resource HTML (${b.length} chars)`);const S=await je(e,t,s,b);l.widgetCacheKey=S;break}catch(S){if(M=S,K.warn(`Failed to get resource (attempt ${D}/${I}):`,S.message),D<I){const T=D*2e3;K.info(`Retrying in ${T}ms...`),await new Promise(_=>setTimeout(_,T))}}if(!b&&M){K.warn("All retries failed, checking for cached widget HTML...");try{const D=await fetch(`/store${H}/widgets/${e}/${t}/${s}`);D.ok?(b=await D.text(),l.widgetCacheKey=`${H}/widgets/${e}/${t}/${s}`,K.info(`Using stored widget HTML (${b.length} chars) - CMS update pending`)):(K.error(`No stored version available for widget ${s}`),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>')}catch(D){K.error("Store fallback failed:",D),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>'}}}return{type:n,duration:o,id:s,options:l,raw:b,transitions:d}}generateHTML(e,t,i,n){const o=n.map(r=>this.generateRegionHTML(r)).join(`
|
|
3
3
|
`),s=n.map(r=>this.generateRegionJS(r)).join(`,
|
|
4
4
|
`);return`<!DOCTYPE html>
|
|
5
5
|
<html>
|
|
@@ -732,5 +732,5 @@ ${a.join(`
|
|
|
732
732
|
border: none;
|
|
733
733
|
background: #1D1D1D;
|
|
734
734
|
display: none;
|
|
735
|
-
`,this.iframe.addEventListener("load",()=>{var o,s;try{if((((s=(o=this.iframe.contentWindow)==null?void 0:o.location)==null?void 0:s.href)||"").includes("index.html")){this.hide(),window.location.reload();return}const a=this.iframe.contentDocument;if(!a)return;a.addEventListener("keydown",l=>{l.key==="Escape"&&(l.preventDefault(),this.hide())})}catch{}}),this.backdrop.appendChild(this.cancelBtn),this.backdrop.appendChild(this.gateCard),this.backdrop.appendChild(this.iframe),document.body.appendChild(this.backdrop);const e=this.gateCard.querySelector("#gate-form"),t=this.gateCard.querySelector("#gate-key"),i=this.gateCard.querySelector("#gate-error"),n=this.gateCard.querySelector("#gate-cancel");t.addEventListener("focus",()=>{t.style.borderColor="#0097D8"}),t.addEventListener("blur",()=>{t.style.borderColor="#3A3A3A"}),e.addEventListener("submit",o=>{o.preventDefault(),t.value.trim()===ze.cmsKey?this.showSetup():(i.textContent="Incorrect CMS key",i.style.display="block",t.focus(),t.select())}),n.addEventListener("click",()=>this.hide()),this.backdrop.addEventListener("keydown",o=>{o.key==="Escape"&&(o.preventDefault(),this.hide()),o.stopPropagation()})}}const u=V("PWA"),X=H.slice(1),le=new URL("./",window.location.href).pathname.replace(/\/$/,"");let $e,Q,E,Ce,Ie,Ee,De,U,O,xe,ke,Ae,Re,Me,Oe,Pe;const j={};class wt{constructor(){$(this,"renderer");$(this,"core");$(this,"xmds");$(this,"downloadOverlay",null);$(this,"timelineOverlay",null);$(this,"setupOverlay",null);$(this,"statsCollector",null);$(this,"logReporter",null);$(this,"displaySettings",null);$(this,"currentScheduleId",-1);$(this,"scheduledLayoutIds",new Set);$(this,"preparingLayoutId",null);$(this,"_pendingRetryLayoutId",null);$(this,"_screenshotInterval",null);$(this,"_screenshotMethod",null);$(this,"_html2canvasMod",null);$(this,"_screenshotInFlight",!1);$(this,"_wakeLock",null);$(this,"syncManager",null);$(this,"_currentLayoutEnableStat",!0);$(this,"_probeTimer",null);$(this,"_mediaStatusTimer",null);$(this,"_pendingFollowerStats",null);$(this,"_pendingFollowerLogs",null);$(this,"_iframeObserver",null);$(this,"_swIcHandler",null);$(this,"_chunkConfig",null);$(this,"_fileIdToSaveAs",new Map);$(this,"protocolDetector",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const s=await navigator.serviceWorker.register(`${le}/sw-pwa.js?v=${Date.now()}`,{scope:`${le}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",s.scope),navigator.storage&&navigator.storage.persist&&(await navigator.storage.persist()?u.info("Persistent storage granted - cache won't be evicted"):u.warn("Persistent storage denied - cache may be evicted"))}catch(s){u.warn("Service Worker registration failed:",s)}u.info("Initializing cache clients..."),U=new Xe;const{calculateChunkConfig:e}=await N(async()=>{const{calculateChunkConfig:s}=await import("./index-CpSQnOTy.js");return{calculateChunkConfig:s}},__vite__mapDeps([0,1,2]),import.meta.url);this._chunkConfig=e(u),O=new Ke({concurrency:this._chunkConfig.concurrency,chunkSize:this._chunkConfig.chunkSize,chunksPerFile:2}),u.info("Cache clients ready — StoreClient + DownloadManager");const t=document.getElementById("player-container");if(!t)throw new Error("No #player-container found");this.renderer=new dt({cmsUrl:E.cmsUrl,hardwareKey:E.hardwareKey},t,{fileIdToSaveAs:this._fileIdToSaveAs,getWidgetHtml:async s=>{const r=`${H}/widgets/${s.layoutId}/${s.regionId}/${s.id}`;u.debug(`Looking for widget HTML at: ${r}`,s);try{if(await U.has(`${X}/widgets`,`${s.layoutId}/${s.regionId}/${s.id}`))return u.debug("Widget HTML found in store, using mirror URL for iframe"),{url:r,fallback:s.raw||""};u.warn(`No widget HTML found in store: ${r}`)}catch(a){u.error(`Failed to check widget HTML for ${s.id}:`,a)}return u.warn(`Using widget.raw fallback for ${s.id}`),s.raw||""}}),this.core=new yt({config:E,xmds:this.xmds,cache:U,schedule:Q,renderer:this.renderer,xmrWrapper:De,statsCollector:this.statsCollector,displaySettings:this.displaySettings,cmsId:E.activeCmsId}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupInteractiveControl(),this.setupDataConnectorNotify(),this.setupRemoteControls(),this.core.on(v.REGISTER_COMPLETE,s=>{var l,d;const r=parseFloat((l=s==null?void 0:s.settings)==null?void 0:l.latitude),a=parseFloat((d=s==null?void 0:s.settings)==null?void 0:d.longitude);r&&a&&!isNaN(r)&&!isNaN(a)?(u.info(`Display location from CMS: ${r.toFixed(4)}, ${a.toFixed(4)}`),Q!=null&&Q.setLocation&&Q.setLocation(r,a)):this.core.requestGeoLocation&&(u.info("No CMS coordinates, requesting browser geolocation..."),this.core.requestGeoLocation())}),this.updateConfigDisplay(),window.addEventListener("online",()=>{u.info("Browser reports online — triggering immediate collection"),this.updateStatus("Back online, syncing..."),this.removeOfflineIndicator(),this.core.collectNow().catch(s=>{u.error("Failed to collect after coming online:",s)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const n=(this.getControls().keyboard||{}).debugOverlays===!0,o=pt();o.enabled&&n&&(this.downloadOverlay=new be(o),this.downloadOverlay.setProgressCallback(()=>O.getProgress()),u.info("Download overlay enabled (hover bottom-right corner)")),mt()&&n&&(this.timelineOverlay=new Se(!0,s=>this.skipToLayout(s))),this.setupCertWarnings(),this.setupXmrWarning(),await this.requestWakeLock(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.requestWakeLock()}),await this.core.collect(),u.info("Player initialized successfully")}async requestWakeLock(){if(!("wakeLock"in navigator)){u.debug("Wake Lock API not supported");return}try{this._wakeLock=await navigator.wakeLock.request("screen"),u.info("Screen Wake Lock acquired — display will stay on"),this._wakeLock.addEventListener("release",()=>{u.debug("Screen Wake Lock released"),this._wakeLock=null})}catch(e){u.warn("Wake Lock request failed:",e==null?void 0:e.message)}}setupCertWarnings(){const e=new Set;window.addEventListener("cert-warning",t=>{const{host:i,error:n}=t.detail;if(e.has(i))return;e.add(i),u.warn(`Invalid SSL certificate accepted for stream: ${i} (${n})`);let o=document.getElementById("overlay"),s=!1;if(!o){o=document.createElement("div"),o.id="overlay";const l=document.createElement("div");l.id="config-info",o.appendChild(l);const d=document.createElement("div");d.id="status",o.appendChild(d),document.body.appendChild(o),s=!0}let r=document.getElementById("cert-warnings");if(!r){r=document.createElement("span"),r.id="cert-warnings",r.style.cssText="color: #ffaa33; flex: 0 0 auto;";const l=document.getElementById("status");o.insertBefore(r,l)}const a=[...e].join(", ");r.textContent=`⚠ SSL: ${a}`,s&&this.updateConfigDisplay()})}setupXmrWarning(){this.core.on("xmr-status",({connected:e})=>{const t=document.getElementById("overlay");if(!t)return;let i=document.getElementById("xmr-warning");if(e)i==null||i.remove();else{if(!i){i=document.createElement("span"),i.id="xmr-warning",i.style.cssText="color: #ff6666; flex: 0 0 auto;";const n=document.getElementById("cert-warnings")||document.getElementById("status");t.insertBefore(i,n)}i.textContent="⚠ XMR disconnected"}})}async loadCoreModules(){var e,t,i;try{const[n,o,s,r,a,l,d,c,g,h]=await Promise.all([N(()=>import("./index--0TbPToz.js"),__vite__mapDeps([3,4,2]),import.meta.url),N(()=>import("./index-K17x7fv_.js"),__vite__mapDeps([5,6,2]),import.meta.url),N(()=>import("./index-9iMTvtYp.js"),__vite__mapDeps([7,8,2,4]),import.meta.url),N(()=>import("./index-Bgo3B90-.js"),[],import.meta.url),N(()=>import("./index-CdHwqlmo.js"),__vite__mapDeps([9,2]),import.meta.url),N(()=>import("./index-Bn7yexJC.js"),__vite__mapDeps([10,2]),import.meta.url),N(()=>import("./index-DYMccG7M.js"),__vite__mapDeps([11,2]),import.meta.url),N(()=>import("./index-DOWqpi1W.js"),__vite__mapDeps([12,2,8,4]),import.meta.url),N(()=>import("./index-xijlgGv2.js"),__vite__mapDeps([13,8,2,4]),import.meta.url),N(()=>import("./sync-manager-C-mx1NcP.js"),__vite__mapDeps([14,2]),import.meta.url)]);if($e=n.cacheWidgetHtml,Oe=h.SyncManager,Pe=h.computeStagger,Q=s.scheduleManager,E=r.config,Ce=o.RestClient,Ie=o.XmdsClient,Ee=o.ProtocolDetector,De=a.XmrWrapper,xe=l.StatsCollector,ke=l.formatStats,Ae=l.LogReporter,Re=l.formatLogs,Me=d.DisplaySettings,j.core=c.VERSION||"?",j.cache=n.VERSION||"?",j.renderer=g.VERSION||"?",j.schedule=s.VERSION||"?",j.xmds=o.VERSION||"?",j.xmr=a.VERSION||"?",j.utils=r.VERSION||"?",j.stats=l.VERSION||"?",j.settings=d.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const x=await window.electronAPI.getSystemInfo();x.macAddress&&(E.macAddress=x.macAddress)}catch{}const m=E.transport!=="auto"?E.transport:void 0,y=new URLSearchParams(window.location.search).get("transport")||(le.includes("pwa-xmds")?"xmds":null)||m||"auto";this.protocolDetector=new Ee(E.cmsUrl,Ce,Ie);const b=y==="auto"?void 0:y,{client:C}=await this.protocolDetector.detect(E,b);this.xmds=C;const I=E.activeCmsId;this.statsCollector=new xe(I),await this.statsCollector.init(),u.info(`Stats collector initialized${I?` (CMS: ${I})`:""}`),this.logReporter=new Ae(I),await this.logReporter.init(),u.info(`Log reporter initialized${I?` (CMS: ${I})`:""}`);const M=x=>x.map(k=>typeof k=="string"?k:JSON.stringify(k)).join(" ");ge(({level:x,name:k,args:P})=>{if(!this.logReporter)return;const G=M(P);this.logReporter.log(x,`[${k}] ${G}`,"PLAYER").catch(()=>{})});const D=E.debug;if(D!=null&&D.consoleLogs){const x=(D.consoleLogsInterval||10)*1e3;let k=[],P=null;const G=()=>{if(k.length===0)return;const Y=k;k=[],P=null,fetch("/debug/log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}).catch(()=>{})};ge(({level:Y,name:re,args:ee})=>{const te=M(ee);k.push({level:Y,name:re,message:te,ts:new Date().toISOString()}),P||(P=setTimeout(G,x))}),u.info(`Console log forwarding to proxy enabled (flush every ${x/1e3}s)`)}this.displaySettings=new Me,u.info("Display settings manager initialized");const S="2026-03-19T17:56:08.790Z",T="0.7.1";u.info(`v${T} built ${S}`);const _=Object.entries(j).map(([x,k])=>`${x}=${k}`).join(" ");u.info(`SDK: ${_}`);const L=!!window.electronAPI,A=L?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,R=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",W=L?`Electron ${A} / Chrome ${R}`:`Chrome ${R}`;u.info(`Env: PWA v${T} | ${W} | ${navigator.platform} | ${screen.width}x${screen.height}`),u.info("Core modules loaded")}catch(n){throw u.error("Failed to load core modules:",n),n}}setupCoreEventHandlers(){this.core.on(v.COLLECTION_START,()=>{this.updateStatus("Collecting data from CMS...")}),this.core.on(v.REGISTER_COMPLETE,e=>{var i;const t=((i=this.displaySettings)==null?void 0:i.getDisplayName())||e.displayName||E.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on(v.REGISTER_COMPLETE,e=>{var t;!e.syncConfig&&((t=E.data)!=null&&t.sync)&&(u.info("[Sync] Using local sync config (CMS did not provide syncConfig)"),this.core.syncConfig=E.data.sync,this.core.emit(v.SYNC_CONFIG,E.data.sync))}),this.core.on(v.OFFLINE_MODE,e=>{var t;e&&!this.syncManager&&((t=E.data)!=null&&t.sync)&&(u.info("[Sync] Offline mode with local sync config — starting sync"),this.core.syncConfig=E.data.sync,this.core.emit(v.SYNC_CONFIG,E.data.sync))}),this.core.on(v.SYNC_CONFIG,async e=>{var o,s;if(this.syncManager&&this.syncManager.stop(),e.syncPublisherPort)if(e.syncGroupId&&(e.syncGroup=String(e.syncGroupId)),e.isLead)e.relayUrl=`ws://localhost:${e.syncPublisherPort}/sync`,fetch("/system/advertise-sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({syncGroupId:e.syncGroupId,port:e.syncPublisherPort,displayId:E.hardwareKey})}).catch(()=>{});else{let r=e.syncGroup;try{const a=await fetch(`/system/discover-lead?syncGroupId=${e.syncGroupId}`);if(a.ok){const{host:l,port:d}=await a.json();r=l,u.info(`mDNS discovered lead at ${l}:${d}`)}}catch{u.warn("mDNS discovery failed, using CMS-provided IP")}e.relayUrl=`ws://${r}:${e.syncPublisherPort}/sync`}const{syncToken:t,...i}=e,n={...((o=E.data)==null?void 0:o.sync)||{},...i};(s=window.electronAPI)!=null&&s.setConfig?window.electronAPI.setConfig({sync:n}):fetch("/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sync:n})}).catch(()=>{}),e.syncToken||(e.syncToken=E.cmsKey),this.syncManager=new Oe({displayId:E.hardwareKey,syncConfig:e,onLayoutChange:async r=>{var d,c;const a=e.layoutMap||((d=E.sync)==null?void 0:d.layoutMap),l=(a==null?void 0:a[r])??r;l!==r&&u.info(`[Sync] Wall mode: lead layout ${r} → local layout ${l}`),u.info(`[Sync] Preparing layout ${l} (waiting for show signal)`),await this.prepareLayout(parseInt(String(l),10)),(c=this.syncManager)==null||c.reportReady(r)},onLayoutShow:r=>{var w;const a=e.layoutMap||((w=E.sync)==null?void 0:w.layoutMap),l=(a==null?void 0:a[r])??r,d=parseInt(String(l),10),c=e.choreography||"simultaneous",g=e.staggerMs??150,h={choreography:c,staggerMs:g};e.topology?(h.topology=e.topology,h.gridCols=e.gridCols??1,h.gridRows=e.gridRows??1):(h.position=e.position??0,h.totalDisplays=e.totalDisplays??1);const m=Pe(h);m>0?(u.info(`[Sync] Show layout ${d} with ${m}ms choreography delay (${c})`),setTimeout(()=>this.renderer.showLayout(d),m)):(u.info(`[Sync] Show layout ${d}`),this.renderer.showLayout(d))},onVideoStart:(r,a)=>{var l,d;u.info(`[Sync] Video start: layout ${r} region ${a}`),(d=(l=this.renderer).resumeRegionMedia)==null||d.call(l,a)},onStatsReport:async(r,a,l)=>{u.info(`[Sync] Submitting stats for follower ${r}`);try{await this.xmds.submitStats(a,r)&&l()}catch(d){u.warn(`[Sync] Stats submission failed for follower ${r}:`,d)}},onLogsReport:async(r,a,l)=>{u.info(`[Sync] Submitting logs for follower ${r}`);try{await this.xmds.submitLog(a,r)&&l()}catch(d){u.warn(`[Sync] Log submission failed for follower ${r}:`,d)}},onStatsAck:async r=>{u.info("[Sync] Lead confirmed stats submission"),this._pendingFollowerStats&&this.statsCollector&&(await this.statsCollector.clearSubmittedStats(this._pendingFollowerStats),this._pendingFollowerStats=null)},onLogsAck:async r=>{u.info("[Sync] Lead confirmed logs submission"),this._pendingFollowerLogs&&this.logReporter&&(await this.logReporter.clearSubmittedLogs(this._pendingFollowerLogs),this._pendingFollowerLogs=null)},onGroupUpdate:(r,a)=>{u.info(`[Sync] Group update: ${r} displays, topology: ${JSON.stringify(a)}`),e.totalDisplays=r}}),this.core.setSyncManager(this.syncManager),this.syncManager.start(),u.info(`[Sync] SyncManager started as ${e.isLead?"LEAD":"FOLLOWER"}`),this.updateConfigDisplay()}),this.core.on(v.FILES_RECEIVED,e=>{this.updateStatus(`Downloading ${e.length} files...`)}),this.core.on(v.OFFLINE_MODE,e=>{e?(this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()):(this.updateStatus("Back online"),this.removeOfflineIndicator())}),this.core.on(v.PURGE_REQUEST,async e=>{try{const t=await U.remove(e);u.info(`Purge complete: ${t.deleted}/${t.total} files deleted`)}catch(t){u.warn("Purge failed:",t)}}),this.core.on(v.DOWNLOAD_REQUEST,async e=>{var t,i,n;(t=this.downloadOverlay)==null||t.startUpdating();try{const o=((n=(i=this.xmds)==null?void 0:i.getToken)==null?void 0:n.call(i))||null;o&&await fetch("/auth-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:o})}),await this.enqueueDownloads(e),u.info("Download enqueue complete")}catch(o){u.error("Download request failed:",o),this.updateStatus("Download failed: "+o,"error")}}),this.core.on(v.SCHEDULE_RECEIVED,e=>{var t;if(this.updateStatus("Processing schedule..."),e.layouts&&e.layouts.length>0?this.currentScheduleId=parseInt(e.layouts[0].scheduleid)||-1:e.campaigns&&e.campaigns.length>0&&(this.currentScheduleId=parseInt(e.campaigns[0].scheduleid)||-1),(t=this.renderer)!=null&&t.layoutPool){const i=new Set;if(e.layouts)for(const o of e.layouts){const s=q(o.file||o.id||o);s&&i.add(s)}if(e.campaigns){for(const o of e.campaigns)if(o.layouts)for(const s of o.layouts){const r=q(s.file||s.id||s);r&&i.add(r)}}const n=this.renderer.layoutPool.clearWarmNotIn(i);n>0&&u.info(`Cleared ${n} preloaded layout(s) no longer in schedule`),this.scheduledLayoutIds=i}u.debug("Current scheduleId for stats:",this.currentScheduleId)}),this.core.on(v.LAYOUT_PREPARE_REQUEST,async e=>{await this.prepareLayout(e),(!this.syncManager||this.renderer.getCurrentLayoutId()===null)&&this.renderer.showLayout(e)}),this.core.on(v.LAYOUT_EXPIRE_CURRENT,()=>{u.info("Schedule changed — expiring current layout"),this.renderer.stopCurrentLayout()}),this.core.on(v.NO_LAYOUTS_SCHEDULED,()=>{this.updateStatus("No layouts scheduled")}),this.core.on(v.COLLECTION_COMPLETE,()=>{const e=this.core.getCurrentLayoutId();e?this.updateStatus(`Playing layout ${e}`):this.preparingLayoutId&&this.updateStatus(`Downloading layout ${this.preparingLayoutId}...`)}),this.core.on(v.COLLECTION_ERROR,async e=>{var i;this.updateStatus(`Collection error: ${e}`,"error");const t=(e==null?void 0:e.message)||String(e);if(t.includes("403")&&(t.includes("Display not found")||t.includes("not authorized"))){u.warn("Display not registered or not authorized — showing setup screen"),this.setupOverlay||(this.setupOverlay=new Te),this.setupOverlay.show();return}(i=this.logReporter)==null||i.reportFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.submitFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`)}),this.core.on(v.XMR_CONNECTED,e=>{u.info("XMR connected:",e)}),this.core.on(v.XMR_MISCONFIGURED,e=>{u.warn(`XMR misconfigured (${e.reason}): ${e.message}`)}),this.core.on(v.LOG_LEVEL_CHANGED,()=>{u.info("Log level changed")}),this.core.on(v.OVERLAY_LAYOUT_REQUEST,async e=>{u.info("Overlay layout requested:",e),await this.prepareLayout(e),this.renderer.showLayout(e)}),this.core.on(v.REVERT_TO_SCHEDULE,()=>{u.info("Reverting to scheduled content"),this.updateStatus("Reverting to schedule...")}),this.core.on(v.PURGE_ALL_REQUEST,async()=>{u.info("Purging all cached content..."),this.updateStatus("Purging cache...");try{const e=await U.list();if(e.length>0){const i=await U.remove(e);u.info(`Purged ${i.deleted} files from ContentStore`)}const t=await caches.keys();t.length>0&&(await Promise.all(t.map(i=>caches.delete(i))),u.info(`Purged ${t.length} legacy caches`))}catch(e){u.error("Cache purge failed:",e)}}),this.core.on(v.COMMAND_RESULT,e=>{var t;u.info("Command result:",e),e.success||((t=this.logReporter)==null||t.reportFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`),this.submitFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`))}),this.core.on(v.SCHEDULED_COMMAND,e=>{u.info(`Scheduled command: ${e.code}`),this.core.executeCommand(e.code)}),this.core.on(v.EXECUTE_NATIVE_COMMAND,async e=>{var i;let t;if((i=window.electronAPI)!=null&&i.executeShellCommand)t=await window.electronAPI.executeShellCommand({commandString:e.commandString});else try{t=await(await fetch("/shell-command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commandString:e.commandString})})).json()}catch(n){t={success:!1,reason:n.message}}this.core.emit(v.COMMAND_RESULT,{code:e.code,...t})}),this.displaySettings&&(this.displaySettings.on("interval-changed",e=>{u.info(`Collection interval changed to ${e}s`)}),this.displaySettings.on("settings-applied",(e,t)=>{t.length>0&&u.info("Settings updated from CMS:",t.join(", ")),this._screenshotInterval||this.startScreenshotInterval()})),this.core.on(v.SUBMIT_STATS_REQUEST,async()=>{await this.submitStats()}),this.core.on(v.SUBMIT_LOGS_REQUEST,async()=>{await this.submitLogs()}),this.core.on(v.SCREENSHOT_REQUEST,async()=>{await this.captureAndSubmitScreenshot()}),this.core.on(v.CHECK_PENDING_LAYOUT,async e=>{await this.prepareLayout(e),this.renderer.showLayout(e)}),this.core.on(v.NAVIGATE_TO_WIDGET,e=>{e.targetId?this.renderer.navigateToWidget(e.targetId):u.warn("navigate-to-widget action has no targetId:",e)}),this.core.on(v.TIMELINE_UPDATED,e=>{var n;const t=this.core.getCurrentLayoutId(),i=t?this.core.getLayoutDuration(t):void 0;(n=this.timelineOverlay)==null||n.update(e,t,i)})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var l,d;if(((l=t.data)==null?void 0:l.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(d=t.ports)==null?void 0:d[0];if(!r)return;const a=this.handleInteractiveControl(i,n,o,s);r.postMessage(a)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupDataConnectorNotify(){this.core.getDataConnectorManager().on("data-changed",t=>{var o;const i=document.querySelectorAll("iframe"),n={ctrl:"rtNotifyData",data:{dataKey:t}};for(const s of i)try{(o=s.contentWindow)==null||o.postMessage(n,"*")}catch{}})}setupRemoteControls(){window.addEventListener("blur",()=>{var a;(a=this.setupOverlay)!=null&&a.isVisible()||setTimeout(()=>window.focus(),200)});const e=a=>{const l=()=>{var d;try{const c=a.contentDocument||((d=a.contentWindow)==null?void 0:d.document);if(!c||a.__keyForwarderAttached)return;a.__keyForwarderAttached=!0,c.addEventListener("keydown",g=>{var m;if((m=this.setupOverlay)!=null&&m.isVisible())return;const h=new KeyboardEvent("keydown",{key:g.key,code:g.code,keyCode:g.keyCode,ctrlKey:g.ctrlKey,shiftKey:g.shiftKey,altKey:g.altKey,metaKey:g.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(h)||g.preventDefault()})}catch{}};a.addEventListener("load",l),l()};Array.from(document.querySelectorAll("iframe")).forEach(a=>e(a)),this._iframeObserver=new MutationObserver(a=>{for(const l of a)for(const d of l.addedNodes)d instanceof HTMLIFrameElement&&e(d),d instanceof HTMLElement&&d.querySelectorAll("iframe").forEach(c=>e(c))}),this._iframeObserver.observe(document.body,{childList:!0,subtree:!0});const t=this.getControls(),{keyboard:i={}}=t,n=i.debugOverlays===!0,o=i.setupKey===!0,s=i.playbackControl===!0,r=i.videoControls===!0;document.addEventListener("keydown",a=>{if(a.key==="q"&&(a.ctrlKey||a.metaKey)){a.preventDefault(),u.info("[Remote] Quit requested (Ctrl+Q)"),fetch("/quit",{method:"POST"}).catch(()=>{});return}switch(a.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new Se(!0,l=>this.skipToLayout(l))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new be({enabled:!0,autoHide:!1}),this.downloadOverlay.setProgressCallback(()=>O.getProgress())),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const l=[...document.querySelectorAll("video")];document.querySelectorAll("iframe").forEach(c=>{try{l.push(...c.contentDocument.querySelectorAll("video"))}catch{}});const d=l.length>0&&!l[0].controls;l.forEach(c=>c.controls=d);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),a.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),a.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),a.preventDefault();break;case"r":case"R":if(!s)break;this.core.isLayoutOverridden()&&(u.info("[Remote] Revert to schedule (keyboard)"),this.core.revertToSchedule());break;case"s":case"S":if(!o)break;this.setupOverlay||(this.setupOverlay=new Te),this.setupOverlay.toggle(),a.preventDefault();break}}),s&&"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("nexttrack",()=>{u.info("[Remote] Next layout (MediaSession)"),this.core.advanceToNextLayout()}),navigator.mediaSession.setActionHandler("previoustrack",()=>{u.info("[Remote] Previous layout (MediaSession)"),this.core.advanceToPreviousLayout()}),navigator.mediaSession.setActionHandler("pause",()=>{u.info("[Remote] Pause (MediaSession)"),this.renderer.pause()}),navigator.mediaSession.setActionHandler("play",()=>{u.info("[Remote] Resume (MediaSession)"),this.renderer.resume()})),u.info("Remote controls initialized (keyboard + MediaSession)")}getControls(){return E.controls}skipToLayout(e){u.info(`Skipping to layout ${e} (timeline click)`),this.core.changeLayout(e)}parseBody(e){try{return e?JSON.parse(e):{}}catch{return{}}}handleInteractiveControl(e,t,i,n){var o;switch(u.debug("IC request:",e,t,i),t){case"/info":return{status:200,body:JSON.stringify({hardwareKey:E.hardwareKey,displayName:E.displayName,playerType:"pwa",currentLayoutId:this.core.getCurrentLayoutId()})};case"/trigger":{const s=this.parseBody(n);return this.renderer.emit("interactiveTrigger",{targetId:s.id,triggerCode:s.trigger}),s.trigger&&this.core.handleTrigger(s.trigger),{status:200,body:"OK"}}case"/duration/expire":{const s=this.parseBody(n);return u.info("IC: Widget duration expire requested for",s.id),this.renderer.emit("widgetExpire",{widgetId:s.id}),{status:200,body:"OK"}}case"/duration/extend":{const s=this.parseBody(n);return u.info("IC: Widget duration extend by",s.duration,"for",s.id),this.renderer.emit("widgetExtendDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/duration/set":{const s=this.parseBody(n);return u.info("IC: Widget duration set to",s.duration,"for",s.id),this.renderer.emit("widgetSetDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/fault":{const s=this.parseBody(n);return(o=this.logReporter)==null||o.reportFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault"),this.submitFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault",{layoutId:s.layoutId,regionId:s.regionId,widgetId:s.widgetId}),{status:200,body:"OK"}}case"/realtime":{const r=new URLSearchParams(i).get("dataKey");if(u.debug("IC: Realtime data request for key:",r),!r)return{status:400,body:JSON.stringify({error:"Missing dataKey parameter"})};const l=this.core.getDataConnectorManager().getData(r);return l===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof l=="string"?l:JSON.stringify(l)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:E.displayId,hardwareKey:E.hardwareKey,displayName:E.displayName,width:window.innerWidth,height:window.innerHeight,latitude:E.latitude||null,longitude:E.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}notifyFileCached(e,t){if(u.debug(`Download complete: ${t}/${e}`),t==="layout")this.core.notifyMediaReady(parseInt(e),t);else if(t==="media"){const i=this._fileIdToSaveAs.get(e)||e;this.core.notifyMediaReady(i,t)}this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3),this._mediaStatusTimer&&clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=setTimeout(()=>{this._mediaStatusTimer=null,this.checkTimelineMediaStatus().catch(()=>{})},2e3)}async enqueueDownloads(e){const{extractMediaIdsFromXlf:t}=await N(async()=>{const{extractMediaIdsFromXlf:S}=await import("./index-CpSQnOTy.js");return{extractMediaIdsFromXlf:S}},__vite__mapDeps([0,1,2]),import.meta.url),{layoutOrder:i,files:n,layoutDependants:o}=e,s=S=>(S.path||"").split("?")[0].replace(/^\/+/,"")||`${S.type||"media"}/${S.id}`;for(const S of n)S.saveAs&&this._fileIdToSaveAs.set(String(S.id),S.saveAs);const r=new Map,a=[],l=new Map,d=new Map;for(const S of n)if(S.type==="layout")r.set(parseInt(S.id),S);else if(S.type==="static")a.push(S);else{const T=`${S.type}:${S.id}`;l.set(T,S);const _=String(S.id);d.has(_)||d.set(_,[]),d.get(_).push(T)}u.info(`Download: ${i.length} layouts, ${l.size} media, ${a.length} resources`);const c=new Map,h=[...i,...[...r.keys()].filter(S=>!i.includes(S))].map(async S=>{const T=r.get(S);if(!(T!=null&&T.path))return;let _;try{const L={};T.cmsDownloadUrl&&(L["X-Cms-Download-Url"]=T.cmsDownloadUrl);const A=await fetch(T.path,Object.keys(L).length?{headers:L}:void 0);A.ok&&(_=await A.text(),u.info(`Fetched XLF ${S} (${_.length} bytes)`),this.notifyFileCached(String(S),"layout"))}catch{}_&&c.set(S,t(_,u))});await Promise.allSettled(h),u.info(`Parsed ${c.size} XLFs`);const m=async(S,T)=>{if(!T.path||T.path==="null"||T.path==="undefined")return!1;const _=s(T);try{if((await fetch(`/store/${_}`,{method:"HEAD"})).ok)return!1}catch{}if(O.getTask(_))return!1;try{const A=await fetch(`/store/missing-chunks/${_}`);if(A.ok){const{missing:R,numChunks:W}=await A.json();if(W>0&&R.length<W){const x=new Set;for(let k=0;k<W;k++)R.includes(k)||x.add(k);T.skipChunks=x,u.info(`Resuming ${_}: ${x.size}/${W} chunks cached, ${R.length} to download`)}}}catch{}const L=S.addFile(T);return L.state!=="pending"?!1:(L.wait().then(A=>{const R=parseInt(T.size)||A.size;u.info("Download complete:",_,`(${R} bytes)`),R>this._chunkConfig.chunkSize&&fetch("/store/mark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:_})}).catch(W=>u.warn("mark-complete failed:",_,W.message)),this.notifyFileCached(String(T.id),T.type),O.removeCompleted(_)}).catch(A=>{u.error("Download failed:",T.id,A),O.removeCompleted(s(T))}),!0)},w=O.createTaskBuilder();await Promise.all(a.map(S=>m(w,S)));const y=await w.build();y.length>0&&(y.push(fe),O.enqueueOrderedTasks(y));const b=new Set,C=[...c.keys()].filter(S=>!i.includes(S)),I=new Map;for(const[S,T]of l)T.saveAs&&I.set(T.saveAs,S);const M=new Map;if(o)for(const[S,T]of Object.entries(o))M.set(parseInt(S,10),T);for(const S of i){const T=c.get(S);if(!T)continue;const _=new Set(T);for(const x of C){const k=c.get(x);if(k)for(const P of k)_.add(P)}const L=M.get(S)||[];for(const x of L){const k=I.get(x);k&&_.add(k)}const A=[];for(const x of _){if(l.has(x)&&!b.has(x)){A.push(l.get(x)),b.add(x);continue}const k=d.get(String(x))||[];for(const P of k)b.has(P)||(A.push(l.get(P)),b.add(P))}if(A.length===0)continue;u.info(`Layout ${S}: ${A.length} media`),A.sort((x,k)=>(x.size||0)-(k.size||0));const R=O.createTaskBuilder();await Promise.all(A.map(x=>m(R,x)));const W=await R.build();W.length>0&&(W.push(fe),O.enqueueOrderedTasks(W))}const D=[...l.keys()].filter(S=>!b.has(S));if(D.length>0){u.info(`${D.length} media not in any XLF`);const S=O.createTaskBuilder();await Promise.all(D.map(_=>{const L=l.get(_);return L?m(S,L):Promise.resolve(!1)}));const T=await S.build();T.length>0&&O.enqueueOrderedTasks(T)}u.info("Downloads active:",O.running,", queued:",O.queued)}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var n;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1;const i=this.core.getLayoutDuration(e)||(t==null?void 0:t.duration);(n=this.timelineOverlay)==null||n.update(null,e,i),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(o=>{u.error("Failed to start layout stat:",o)})}),this.renderer.on("layoutEnd",e=>{if(u.info("Layout ended:",e),Q==null||Q.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.renderer.getCurrentLayoutId()&&this.renderer.getCurrentLayoutId()!==e){u.debug(`Layout ${e} ended but ${this.renderer.getCurrentLayoutId()} already playing, skipping advance`);return}if(this.preparingLayoutId&&this.preparingLayoutId!==e){u.debug(`Layout ${e} ended but ${this.preparingLayoutId} being prepared, skipping advance`);return}this.core.notifyLayoutStatus(e),this.core.clearCurrentLayout();const t=this.core.getPendingLayouts();if(t.length>0){u.info(`Layout ${t[0]} pending download, skipping advance`);return}u.info("Layout cycle completed, advancing to next layout..."),this.core.advanceToNextLayout()}),this.renderer.on("widgetStart",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget started:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.startWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to start widget stat:",o)})}),this.renderer.on("widgetEnd",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget ended:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.endWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to end widget stat:",o)})}),this.renderer.on("widgetCommand",e=>{u.info("Widget command:",e.commandCode);const t={[e.commandCode]:{commandString:e.commandString}};this.core.executeCommand(e.commandCode,t)}),this.renderer.on("error",e=>{var t;u.error("Renderer error:",e),this.updateStatus(`Error: ${e.type}`,"error"),(t=this.logReporter)==null||t.reportFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type} (layout ${e.layoutId||"unknown"})`),this.submitFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type}`,{layoutId:e.layoutId,regionId:e.regionId,widgetId:e.widgetId})}),this.renderer.on("action-trigger",e=>{var r,a;const{actionType:t,triggerCode:i,layoutCode:n,targetId:o,commandCode:s}=e;switch(u.info("Action trigger:",t,e),t){case"navLayout":case"navigateToLayout":i?this.core.handleTrigger(i):n&&this.core.changeLayout(n);break;case"navWidget":case"navigateToWidget":i?this.core.handleTrigger(i):o&&this.renderer.navigateToWidget(o);break;case"previousWidget":this.renderer.previousWidget((r=e.source)==null?void 0:r.regionId);break;case"nextWidget":this.renderer.nextWidget((a=e.source)==null?void 0:a.regionId);break;case"command":s&&this.core.executeCommand(s);break;default:u.warn("Unknown action type:",t)}this.statsCollector&&this.statsCollector.recordEvent("touch",this.core.getCurrentLayoutId(),e.targetId||null,this.currentScheduleId)}),this.renderer.on("widgetAction",e=>{e.type==="durationEnd"&&e.url&&(u.info(`Widget ${e.widgetId} duration ended, calling webhook: ${e.url}`),this.statsCollector&&this.statsCollector.recordEvent("webhook",e.layoutId,e.widgetId,this.currentScheduleId),fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:e.widgetId,layoutId:e.layoutId,regionId:e.regionId,event:"durationEnd",timestamp:new Date().toISOString()})}).catch(t=>u.warn("Webhook failed (non-critical):",t)))}),this.renderer.on("layoutDurationUpdated",(e,t,i)=>{this.core.recordLayoutDuration(String(e),t,i)}),this.renderer.on("request-next-layout-preload",async()=>{try{const e=this.core.peekNextLayout();if(!e){u.debug("No next layout to preload (single layout schedule or same layout)");return}const t=e.layoutId;if(this.renderer.layoutPool.has(t)){u.debug(`Layout ${t} already in preload pool`);return}u.info(`Preloading next layout ${t}...`);const i=await U.get(`${X}/layouts`,t);if(!i){u.debug(`Layout ${t} XLF not cached, skipping preload`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){u.debug(`Media not fully cached for layout ${t}, skipping preload`);return}await this.fetchWidgetHtml(n,t),await this.renderer.preloadLayout(n,t)?u.info(`Layout ${t} preloaded successfully`):u.warn(`Layout ${t} preload failed (will fall back to normal render)`)}catch(e){u.warn("Layout preload failed (non-blocking):",e)}}),this.renderer.on("videoError",async({storedAs:e})=>{if(!e)return;const t=`${H.slice(1)}/media/file/${e}`;try{const i=await fetch(`/store/missing-chunks/${t}`),{missing:n}=await i.json();if(n.length===0){u.warn(`Video ${e}: corrupt file (all chunks present), deleting for re-download`),await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{key:t}]})});const o=this.core.getCurrentLayoutId();o&&this.core.setPendingLayout(o,[e]),this.core.collectNow().catch(s=>{u.error(`Failed to trigger re-download for ${e}:`,s.message)});return}u.warn(`Video ${e}: ${n.length} missing chunks (${n.join(", ")}), re-downloading`),await fetch("/store/unmark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:t})}),this.core.collectNow().catch(o=>{u.error(`Failed to trigger re-download for ${e}:`,o.message)})}catch(i){u.error(`Failed to check/re-download ${e}:`,i.message)}})}async prepareLayout(e){var t;if(this.renderer.getCurrentLayoutId()===e){u.debug(`Layout ${e} replay`),this.core.clearPreparingLayout(),await this.renderer.renderLayout("",e);return}if(this.preparingLayoutId===e){u.debug(`Layout ${e} preparation in progress, will retry after it completes`),this._pendingRetryLayoutId=e;return}this.preparingLayoutId=e;try{const i=await U.get(`${X}/layouts`,e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[String(e)]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),o=new DOMParser().parseFromString(n,"text/xml"),{allMedia:s}=this.getMediaIds(o);if(!await this.checkAllMediaCached(s)){O.prioritizeLayoutFiles(s.map(String)),u.info(`Waiting for media to finish downloading for layout ${e}`),this.updateStatus(`Preparing layout ${e}...`),this.core.setPendingLayout(e,s);return}this.renderer.hasPreloadedLayout(e)||await this.fetchWidgetHtml(o,e),await this.renderer.preloadLayout(n,e),u.info(`Layout ${e} ready`)}catch(i){u.error("Failed to prepare layout:",e,i),this.updateStatus(`Failed to load layout ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`),this.submitFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`,{layoutId:e})}finally{this.preparingLayoutId=null,this.core.clearPreparingLayout();const i=this._pendingRetryLayoutId;this._pendingRetryLayoutId=null,i!=null&&this.core.getCurrentLayoutId()!==i&&(u.debug(`Retrying preparation for layout ${i} after 500ms`),setTimeout(()=>this.prepareLayout(i),500))}}getMediaIds(e){var s;const t=typeof e=="string"?new DOMParser().parseFromString(e,"text/xml"):e,i=[],n=[];t.querySelectorAll("media[fileId]").forEach(r=>{const a=r.getAttribute("fileId");if(a){const l=this._fileIdToSaveAs.get(a)||a;if(l.endsWith(".xlf"))return;i.push(l),r.getAttribute("type")==="video"&&n.push(l)}});const o=(s=t.querySelector("layout"))==null?void 0:s.getAttribute("background");if(o){const r=this._fileIdToSaveAs.get(o)||o;i.includes(r)||i.push(r)}return{allMedia:i,videoMedia:n}}async checkAllMediaCached(e){const t=await Promise.all(e.map(async n=>{try{return await U.has(X,`media/file/${n}`)}catch{return u.warn(`Unable to verify media ${n}, assuming cached (offline mode)`),!0}})),i=e.filter((n,o)=>!t[o]);return i.length>0?(u.debug(`Media not yet cached: ${i.join(", ")}`),!1):!0}async fetchWidgetHtml(e,t){const i=typeof e=="string"?new DOMParser().parseFromString(e,"text/xml"):e,n=[];for(const o of i.querySelectorAll("region")){const s=o.getAttribute("id");for(const r of o.querySelectorAll("media")){const a=r.getAttribute("type"),l=r.getAttribute("id");r.getAttribute("render")==="html"&&n.push((async()=>{try{const c=`${t}/${s}/${l}`;let g=null;const h=await U.get(`${X}/widgets`,c);h&&(g=await h.text(),u.debug(`Found cached widget HTML for ${a} ${l}`)),g||(g=await this.xmds.getResource(t,s,l),u.debug(`Retrieved widget HTML for ${a} ${l} from CMS`)),g=(await $e(t,s,l,g)).html;const w=r.querySelector("raw");if(w)w.textContent=g;else{const y=i.createElement("raw");y.textContent=g,r.appendChild(y)}}catch(c){u.warn(`Failed to get widget HTML for ${a} ${l}:`,c)}})())}}n.length>0&&(u.info(`Fetching ${n.length} widget HTML resources in parallel...`),await Promise.all(n),u.debug("All widget HTML fetched"))}async checkTimelineMediaStatus(){if(this.scheduledLayoutIds.size!==0){for(const e of this.scheduledLayoutIds){const t=`${e}.xlf`;try{const i=await U.get(`${X}/layouts`,e);if(!i)continue;const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(o.length===0){this.core.setLayoutMediaStatus(t,!0);continue}const s=[];for(const r of o)try{await U.has(X,`media/file/${r}`)||s.push(r)}catch{}this.core.setLayoutMediaStatus(t,s.length===0,s)}catch{}}this.core.logUpcomingTimeline()}}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await U.get(`${X}/layouts`,e);if(!t)continue;const i=await t.text(),{videoMedia:n}=this.getMediaIds(i);if(n.length===0)continue;const s=new DOMParser().parseFromString(i,"text/xml"),r=new Map;let a=0;for(const c of s.querySelectorAll('media[type="video"]')){if(c.getAttribute("useDuration")==="1")continue;const h=c.getAttribute("fileId");if(!h)continue;a++;const m=this._fileIdToSaveAs.get(h)||h;if(!await U.has(X,`media/file/${m}`))continue;const y=await this.probeVideoDuration(`${window.location.origin}${H}/media/file/${m}`);y>0&&r.set(h,y)}if(r.size===0)continue;const l=r.size>=a,{duration:d}=We(i,r);d>0&&this.core.recordLayoutDuration(String(e),d,l)}catch(t){u.debug(`Duration probe failed for layout ${e}:`,t)}}probeVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.muted=!0;const n=()=>{i.removeAttribute("src"),i.load()};i.addEventListener("loadedmetadata",()=>{const o=i.duration;n(),t(o)},{once:!0}),i.addEventListener("error",()=>{n(),t(0)},{once:!0}),setTimeout(()=>{n(),t(0)},5e3),i.src=e})}updateConfigDisplay(){var t,i;const e=document.getElementById("config-info");if(e){const n="0.7.1",o="2026-03-19T17:56:08.790Z".replace("T"," ").replace(/\.\d+Z$/,"");let r=`${o?`v${n} (${o})`:`v${n}`} | CMS: ${E.cmsUrl} | Display: ${E.displayName||"Unknown"} | HW: ${E.hardwareKey}`;const a=(i=(t=this.core)==null?void 0:t.getSyncConfig)==null?void 0:i.call(t);if(a){const l=a.relayUrl?new URL(a.relayUrl).host:"";r+=` | Sync: ${a.isLead?"LEAD":`FOLLOWER → ${l}`} (group ${a.syncGroupId||a.syncGroup})`}e.textContent=r}}async submitStats(){var e;if(!this.statsCollector){u.warn("Stats collector not initialized");return}if(this._pendingFollowerStats!==null){u.debug("Stats delegation in-flight, skipping");return}try{const i=(((e=this.displaySettings)==null?void 0:e.getSetting("aggregationLevel"))||"Individual")==="Aggregate"?await this.statsCollector.getAggregatedStatsForSubmission(50):await this.statsCollector.getStatsForSubmission(50);if(i.length===0){u.debug("No stats to submit");return}const n=ke(i);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${i.length} stats to lead`),this._pendingFollowerStats=i,this.syncManager.reportStats(n);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting stats directly"),u.info(`Submitting ${i.length} proof of play stats...`),await this.xmds.submitStats(n)?(u.info("Stats submitted successfully"),await this.statsCollector.clearSubmittedStats(i),u.debug(`Cleared ${i.length} submitted stats from database`)):u.warn("Stats submission failed (CMS returned false)")}catch(t){u.error("Failed to submit stats:",t)}}async submitLogs(){if(this.logReporter){if(this._pendingFollowerLogs!==null){u.debug("Logs delegation in-flight, skipping");return}try{const e=await this.logReporter.getLogsForSubmission();if(e.length===0){u.debug("No logs to submit");return}const t=Re(e);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${e.length} logs to lead`),this._pendingFollowerLogs=e,this.syncManager.reportLogs(t);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting logs directly"),u.info(`Submitting ${e.length} logs to CMS...`),await this.xmds.submitLog(t)?(u.info("Logs submitted successfully"),await this.logReporter.clearSubmittedLogs(e)):u.warn("Log submission failed (CMS returned false)")}catch(e){u.error("Failed to submit logs:",e)}}}submitFault(e,t,i){if(!this.xmds)return;const n=JSON.stringify([{code:e,reason:t,date:new Date().toISOString().replace("T"," ").substring(0,19),...i}]);this.xmds.reportFaults(n).catch(o=>{u.debug("reportFaults failed (non-critical):",o)})}async captureAndSubmitScreenshot(){var e,t;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let i;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const o=await window.electronAPI.captureScreenshot();if(o)this._screenshotMethod="electron",i=o;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else if(this._screenshotMethod==="displayMedia"||this._screenshotMethod===null&&typeof((t=navigator.mediaDevices)==null?void 0:t.getDisplayMedia)=="function")try{i=await this.captureDisplayMedia(),this._screenshotMethod="displayMedia"}catch(o){u.warn("getDisplayMedia failed, falling back to html2canvas:",o.message||o),this._screenshotMethod=null,i=await this.captureHtml2CanvasIsolated(),this._screenshotMethod="html2canvas"}else this._screenshotMethod="html2canvas",i=await this.captureHtml2CanvasIsolated();await this.xmds.submitScreenShot(i)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(i){u.error("Failed to capture screenshot:",i)}finally{this._screenshotInFlight=!1}}async captureDisplayMedia(){const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});try{const t=e.getVideoTracks()[0],n=await new window.ImageCapture(t).grabFrame(),o=document.createElement("canvas");return o.width=n.width,o.height=n.height,o.getContext("2d").drawImage(n,0,0),n.close(),o.toDataURL("image/jpeg",.8).split(",")[1]}finally{e.getTracks().forEach(t=>t.stop())}}async captureHtml2CanvasIsolated(){var o,s;const e=document.createElement("canvas");e.width=window.innerWidth,e.height=window.innerHeight;const t=e.getContext("2d");t.fillStyle="#000",t.fillRect(0,0,e.width,e.height);const i=document.getElementById("player-container");if(!i)return e.toDataURL("image/jpeg",.8).split(",")[1];this._html2canvasMod||(this._html2canvasMod=(await N(async()=>{const{default:r}=await import("./html2canvas.esm-CBrSDip1.js");return{default:r}},[],import.meta.url)).default),this.renderer&&(this.renderer._resizeSuppressed=!0);const n=i.style.contain||"";i.style.contain="strict";try{const r=i.getBoundingClientRect(),a=getComputedStyle(i),l=a.backgroundColor;l&&l!=="transparent"&&l!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=l,t.fillRect(r.left,r.top,r.width,r.height));const d=a.backgroundImage;if(d&&d!=="none"){const h=d.match(/url\(["']?(.*?)["']?\)/);if(h)try{const m=new Image;m.crossOrigin="anonymous",await new Promise(w=>{m.onload=()=>w(),m.onerror=()=>w(),setTimeout(()=>w(),2e3),m.src=h[1]}),m.naturalWidth&&t.drawImage(m,r.left,r.top,r.width,r.height)}catch{}}const c=i.querySelectorAll("img, video, iframe, canvas");let g=0;for(const h of c){const m=h;if(m.style.visibility==="hidden"||m.style.display==="none")continue;const w=h.getBoundingClientRect();if(!(w.width===0||w.height===0))try{if(h instanceof HTMLImageElement){if(!h.complete||!h.naturalWidth)continue;if(getComputedStyle(h).objectFit==="contain"&&h.naturalWidth&&h.naturalHeight){const b=this.containedRect(h.naturalWidth,h.naturalHeight,w);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,w.left,w.top,w.width,w.height);g++}else if(h instanceof HTMLVideoElement){if(h.readyState<2)continue;if(getComputedStyle(h).objectFit==="contain"&&h.videoWidth&&h.videoHeight){const b=this.containedRect(h.videoWidth,h.videoHeight,w);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,w.left,w.top,w.width,w.height);g++}else if(h instanceof HTMLCanvasElement)t.drawImage(h,w.left,w.top,w.width,w.height),g++;else if(h instanceof HTMLIFrameElement){const y=h.contentDocument;if(!(y!=null&&y.body))continue;const b=document.createElement("div");b.style.cssText=`position:fixed;left:-9999px;top:0;width:${w.width}px;height:${w.height}px;overflow:hidden;`;const C=[];for(const _ of y.querySelectorAll("style"))b.appendChild(_.cloneNode(!0));for(const _ of y.querySelectorAll('link[rel="stylesheet"]')){const L=document.createElement("link");L.rel="stylesheet",L.href=new URL(_.getAttribute("href")||"",y.baseURI).href,b.appendChild(L),C.push(new Promise(A=>{L.onload=()=>A(),L.onerror=()=>A()}))}const I=y.body.cloneNode(!0);for(const _ of I.querySelectorAll("img[src]")){const L=_.getAttribute("src")||"";L&&!L.startsWith("http")&&!L.startsWith("data:")&&!L.startsWith("blob:")&&_.setAttribute("src",new URL(L,y.baseURI).href)}b.appendChild(I),document.body.appendChild(b);const M=y.querySelectorAll("img"),D=new Map;M.forEach((_,L)=>{_.naturalWidth&&_.naturalHeight&&D.set(String(L),{nw:_.naturalWidth,nh:_.naturalHeight})}),C.length>0&&await Promise.race([Promise.all(C),new Promise(_=>setTimeout(_,500))]);const S=await this._html2canvasMod(b,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:w.width,height:w.height,onclone:_=>{const L=_.createElement("style");L.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",_.head.appendChild(L),_.querySelectorAll("img").forEach((R,W)=>{var ue,he;const x=(ue=_.defaultView)==null?void 0:ue.getComputedStyle(R);if(!x||x.objectFit!=="contain")return;const k=D.get(String(W));if(!k)return;const P=R.clientWidth||parseFloat(x.width)||0,G=R.clientHeight||parseFloat(x.height)||0;if(!P||!G)return;const Y=k.nw/k.nh,re=P/G;let ee,te;Y>re?(ee=P,te=P/Y):(te=G,ee=G*Y);const ae=_.createElement("div");ae.style.cssText=`width:${P}px;height:${G}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,R.style.objectFit="fill",R.style.width=`${ee}px`,R.style.height=`${te}px`,(he=R.parentNode)==null||he.insertBefore(ae,R),ae.appendChild(R)})}});document.body.removeChild(b),t.drawImage(S,w.left,w.top,w.width,w.height);const T=h.getBoundingClientRect();for(const _ of y.querySelectorAll("video")){if(_.readyState<2)continue;const L=_.getBoundingClientRect();if(!(L.width===0||L.height===0))try{if(((s=(o=y.defaultView)==null?void 0:o.getComputedStyle(_))==null?void 0:s.objectFit)==="contain"&&_.videoWidth&&_.videoHeight){const R=this.containedRect(_.videoWidth,_.videoHeight,new DOMRect(T.left+L.left,T.top+L.top,L.width,L.height));t.drawImage(_,R.x,R.y,R.w,R.h)}else t.drawImage(_,T.left+L.left,T.top+L.top,L.width,L.height)}catch{}}for(const _ of y.querySelectorAll("canvas")){const L=_.getBoundingClientRect();if(!(L.width===0||L.height===0))try{t.drawImage(_,T.left+L.left,T.top+L.top,L.width,L.height)}catch{}}g++}}catch(y){u.warn("Screenshot: failed to draw element",h.tagName,y)}}return u.debug(`Screenshot: composed ${g}/${c.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}finally{i.style.contain=n,this.renderer&&(this.renderer._resizeSuppressed=!1)}}containedRect(e,t,i){const n=e/t,o=i.width/i.height;let s,r;return n>o?(s=i.width,r=i.width/n):(r=i.height,s=i.height*n),{x:i.left+(i.width-s)/2,y:i.top+(i.height-r)/2,w:s,h:r}}startScreenshotInterval(){var i;const e=((i=this.displaySettings)==null?void 0:i.getSetting("screenshotInterval"))||0;if(!e||e<=0)return;!this._html2canvasMod&&!window.electronAPI&&N(()=>import("./html2canvas.esm-CBrSDip1.js"),[],import.meta.url).then(n=>{this._html2canvasMod=n.default});const t=e*1e3;u.info(`Starting periodic screenshots every ${e}s`),this._screenshotInterval=setInterval(()=>{this.captureAndSubmitScreenshot()},t)}updateStatus(e,t="info"){const i=document.getElementById("status");i&&(i.textContent=e,i.className=`status status-${t}`),t==="error"?u.error("Status:",e):u.info("Status:",e)}showOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!0)}removeOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!1)}_syncLeadAlive(){if(!this.syncManager)return!1;for(const[,e]of this.syncManager.followers)if(e.role==="lead"&&Date.now()-e.lastSeen<15e3)return!0;return!1}cleanup(){this.core.cleanup(),this.renderer.cleanup(),this._screenshotInterval&&(clearInterval(this._screenshotInterval),this._screenshotInterval=null),this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.downloadOverlay&&this.downloadOverlay.destroy(),this.timelineOverlay&&this.timelineOverlay.destroy(),this._iframeObserver&&(this._iframeObserver.disconnect(),this._iframeObserver=null),navigator.serviceWorker&&this._swIcHandler&&(navigator.serviceWorker.removeEventListener("message",this._swIcHandler),this._swIcHandler=null),O==null||O.clear(),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null),this._mediaStatusTimer&&(clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=null)}}function Fe(){const p=new wt;p.init().catch(e=>{u.error("Failed to initialize:",e),u.warn("Redirecting to setup screen..."),window.location.href="./setup.html"}),window.addEventListener("beforeunload",()=>{p.cleanup()})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe):Fe();export{v as C,ht as D,Tt as I,ne as L,ct as O,yt as P,dt as R,lt as S,q as a,at as b,nt as c,$t as d,We as p,Lt as s};
|
|
736
|
-
//# sourceMappingURL=main-
|
|
735
|
+
`,this.iframe.addEventListener("load",()=>{var o,s;try{if((((s=(o=this.iframe.contentWindow)==null?void 0:o.location)==null?void 0:s.href)||"").includes("index.html")){this.hide(),window.location.reload();return}const a=this.iframe.contentDocument;if(!a)return;a.addEventListener("keydown",l=>{l.key==="Escape"&&(l.preventDefault(),this.hide())})}catch{}}),this.backdrop.appendChild(this.cancelBtn),this.backdrop.appendChild(this.gateCard),this.backdrop.appendChild(this.iframe),document.body.appendChild(this.backdrop);const e=this.gateCard.querySelector("#gate-form"),t=this.gateCard.querySelector("#gate-key"),i=this.gateCard.querySelector("#gate-error"),n=this.gateCard.querySelector("#gate-cancel");t.addEventListener("focus",()=>{t.style.borderColor="#0097D8"}),t.addEventListener("blur",()=>{t.style.borderColor="#3A3A3A"}),e.addEventListener("submit",o=>{o.preventDefault(),t.value.trim()===ze.cmsKey?this.showSetup():(i.textContent="Incorrect CMS key",i.style.display="block",t.focus(),t.select())}),n.addEventListener("click",()=>this.hide()),this.backdrop.addEventListener("keydown",o=>{o.key==="Escape"&&(o.preventDefault(),this.hide()),o.stopPropagation()})}}const u=V("PWA"),X=H.slice(1),le=new URL("./",window.location.href).pathname.replace(/\/$/,"");let $e,Q,E,Ce,Ie,Ee,De,U,O,xe,ke,Ae,Re,Me,Oe,Pe;const j={};class wt{constructor(){$(this,"renderer");$(this,"core");$(this,"xmds");$(this,"downloadOverlay",null);$(this,"timelineOverlay",null);$(this,"setupOverlay",null);$(this,"statsCollector",null);$(this,"logReporter",null);$(this,"displaySettings",null);$(this,"currentScheduleId",-1);$(this,"scheduledLayoutIds",new Set);$(this,"preparingLayoutId",null);$(this,"_pendingRetryLayoutId",null);$(this,"_screenshotInterval",null);$(this,"_screenshotMethod",null);$(this,"_html2canvasMod",null);$(this,"_screenshotInFlight",!1);$(this,"_wakeLock",null);$(this,"syncManager",null);$(this,"_currentLayoutEnableStat",!0);$(this,"_probeTimer",null);$(this,"_mediaStatusTimer",null);$(this,"_pendingFollowerStats",null);$(this,"_pendingFollowerLogs",null);$(this,"_iframeObserver",null);$(this,"_swIcHandler",null);$(this,"_chunkConfig",null);$(this,"_fileIdToSaveAs",new Map);$(this,"protocolDetector",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const s=await navigator.serviceWorker.register(`${le}/sw-pwa.js?v=${Date.now()}`,{scope:`${le}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",s.scope),navigator.storage&&navigator.storage.persist&&(await navigator.storage.persist()?u.info("Persistent storage granted - cache won't be evicted"):u.warn("Persistent storage denied - cache may be evicted"))}catch(s){u.warn("Service Worker registration failed:",s)}u.info("Initializing cache clients..."),U=new Xe;const{calculateChunkConfig:e}=await N(async()=>{const{calculateChunkConfig:s}=await import("./index-O4mn_OO0.js");return{calculateChunkConfig:s}},__vite__mapDeps([0,1,2]),import.meta.url);this._chunkConfig=e(u),O=new Ke({concurrency:this._chunkConfig.concurrency,chunkSize:this._chunkConfig.chunkSize,chunksPerFile:2}),u.info("Cache clients ready — StoreClient + DownloadManager");const t=document.getElementById("player-container");if(!t)throw new Error("No #player-container found");this.renderer=new dt({cmsUrl:E.cmsUrl,hardwareKey:E.hardwareKey},t,{fileIdToSaveAs:this._fileIdToSaveAs,getWidgetHtml:async s=>{const r=`${H}/widgets/${s.layoutId}/${s.regionId}/${s.id}`;u.debug(`Looking for widget HTML at: ${r}`,s);try{if(await U.has(`${X}/widgets`,`${s.layoutId}/${s.regionId}/${s.id}`))return u.debug("Widget HTML found in store, using mirror URL for iframe"),{url:r,fallback:s.raw||""};u.warn(`No widget HTML found in store: ${r}`)}catch(a){u.error(`Failed to check widget HTML for ${s.id}:`,a)}return u.warn(`Using widget.raw fallback for ${s.id}`),s.raw||""}}),this.core=new yt({config:E,xmds:this.xmds,cache:U,schedule:Q,renderer:this.renderer,xmrWrapper:De,statsCollector:this.statsCollector,displaySettings:this.displaySettings,cmsId:E.activeCmsId}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupInteractiveControl(),this.setupDataConnectorNotify(),this.setupRemoteControls(),this.core.on(v.REGISTER_COMPLETE,s=>{var l,d;const r=parseFloat((l=s==null?void 0:s.settings)==null?void 0:l.latitude),a=parseFloat((d=s==null?void 0:s.settings)==null?void 0:d.longitude);r&&a&&!isNaN(r)&&!isNaN(a)?(u.info(`Display location from CMS: ${r.toFixed(4)}, ${a.toFixed(4)}`),Q!=null&&Q.setLocation&&Q.setLocation(r,a)):this.core.requestGeoLocation&&(u.info("No CMS coordinates, requesting browser geolocation..."),this.core.requestGeoLocation())}),this.updateConfigDisplay(),window.addEventListener("online",()=>{u.info("Browser reports online — triggering immediate collection"),this.updateStatus("Back online, syncing..."),this.removeOfflineIndicator(),this.core.collectNow().catch(s=>{u.error("Failed to collect after coming online:",s)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const n=(this.getControls().keyboard||{}).debugOverlays===!0,o=pt();o.enabled&&n&&(this.downloadOverlay=new be(o),this.downloadOverlay.setProgressCallback(()=>O.getProgress()),u.info("Download overlay enabled (hover bottom-right corner)")),mt()&&n&&(this.timelineOverlay=new Se(!0,s=>this.skipToLayout(s))),this.setupCertWarnings(),this.setupXmrWarning(),await this.requestWakeLock(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.requestWakeLock()}),await this.core.collect(),u.info("Player initialized successfully")}async requestWakeLock(){if(!("wakeLock"in navigator)){u.debug("Wake Lock API not supported");return}try{this._wakeLock=await navigator.wakeLock.request("screen"),u.info("Screen Wake Lock acquired — display will stay on"),this._wakeLock.addEventListener("release",()=>{u.debug("Screen Wake Lock released"),this._wakeLock=null})}catch(e){u.warn("Wake Lock request failed:",e==null?void 0:e.message)}}setupCertWarnings(){const e=new Set;window.addEventListener("cert-warning",t=>{const{host:i,error:n}=t.detail;if(e.has(i))return;e.add(i),u.warn(`Invalid SSL certificate accepted for stream: ${i} (${n})`);let o=document.getElementById("overlay"),s=!1;if(!o){o=document.createElement("div"),o.id="overlay";const l=document.createElement("div");l.id="config-info",o.appendChild(l);const d=document.createElement("div");d.id="status",o.appendChild(d),document.body.appendChild(o),s=!0}let r=document.getElementById("cert-warnings");if(!r){r=document.createElement("span"),r.id="cert-warnings",r.style.cssText="color: #ffaa33; flex: 0 0 auto;";const l=document.getElementById("status");o.insertBefore(r,l)}const a=[...e].join(", ");r.textContent=`⚠ SSL: ${a}`,s&&this.updateConfigDisplay()})}setupXmrWarning(){this.core.on("xmr-status",({connected:e})=>{const t=document.getElementById("overlay");if(!t)return;let i=document.getElementById("xmr-warning");if(e)i==null||i.remove();else{if(!i){i=document.createElement("span"),i.id="xmr-warning",i.style.cssText="color: #ff6666; flex: 0 0 auto;";const n=document.getElementById("cert-warnings")||document.getElementById("status");t.insertBefore(i,n)}i.textContent="⚠ XMR disconnected"}})}async loadCoreModules(){var e,t,i;try{const[n,o,s,r,a,l,d,c,g,h]=await Promise.all([N(()=>import("./index-DPUPuUO8.js"),__vite__mapDeps([3,4,2]),import.meta.url),N(()=>import("./index-Bj01q2d4.js"),__vite__mapDeps([5,6,2]),import.meta.url),N(()=>import("./index-zursmDNN.js"),__vite__mapDeps([7,8,2,4]),import.meta.url),N(()=>import("./index-BmnGgxhy.js"),[],import.meta.url),N(()=>import("./index-mYGuS183.js"),__vite__mapDeps([9,2]),import.meta.url),N(()=>import("./index-BBp7Yeqp.js"),__vite__mapDeps([10,2]),import.meta.url),N(()=>import("./index-DNyHrXGf.js"),__vite__mapDeps([11,2]),import.meta.url),N(()=>import("./index-BGzZpdzW.js"),__vite__mapDeps([12,2,8,4]),import.meta.url),N(()=>import("./index-DwQpyIXq.js"),__vite__mapDeps([13,8,2,4]),import.meta.url),N(()=>import("./sync-manager-4de0XUYN.js"),__vite__mapDeps([14,2]),import.meta.url)]);if($e=n.cacheWidgetHtml,Oe=h.SyncManager,Pe=h.computeStagger,Q=s.scheduleManager,E=r.config,Ce=o.RestClient,Ie=o.XmdsClient,Ee=o.ProtocolDetector,De=a.XmrWrapper,xe=l.StatsCollector,ke=l.formatStats,Ae=l.LogReporter,Re=l.formatLogs,Me=d.DisplaySettings,j.core=c.VERSION||"?",j.cache=n.VERSION||"?",j.renderer=g.VERSION||"?",j.schedule=s.VERSION||"?",j.xmds=o.VERSION||"?",j.xmr=a.VERSION||"?",j.utils=r.VERSION||"?",j.stats=l.VERSION||"?",j.settings=d.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const x=await window.electronAPI.getSystemInfo();x.macAddress&&(E.macAddress=x.macAddress)}catch{}const m=E.transport!=="auto"?E.transport:void 0,y=new URLSearchParams(window.location.search).get("transport")||(le.includes("pwa-xmds")?"xmds":null)||m||"auto";this.protocolDetector=new Ee(E.cmsUrl,Ce,Ie);const b=y==="auto"?void 0:y,{client:C}=await this.protocolDetector.detect(E,b);this.xmds=C;const I=E.activeCmsId;this.statsCollector=new xe(I),await this.statsCollector.init(),u.info(`Stats collector initialized${I?` (CMS: ${I})`:""}`),this.logReporter=new Ae(I),await this.logReporter.init(),u.info(`Log reporter initialized${I?` (CMS: ${I})`:""}`);const M=x=>x.map(k=>typeof k=="string"?k:JSON.stringify(k)).join(" ");ge(({level:x,name:k,args:P})=>{if(!this.logReporter)return;const G=M(P);this.logReporter.log(x,`[${k}] ${G}`,"PLAYER").catch(()=>{})});const D=E.debug;if(D!=null&&D.consoleLogs){const x=(D.consoleLogsInterval||10)*1e3;let k=[],P=null;const G=()=>{if(k.length===0)return;const Y=k;k=[],P=null,fetch("/debug/log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}).catch(()=>{})};ge(({level:Y,name:re,args:ee})=>{const te=M(ee);k.push({level:Y,name:re,message:te,ts:new Date().toISOString()}),P||(P=setTimeout(G,x))}),u.info(`Console log forwarding to proxy enabled (flush every ${x/1e3}s)`)}this.displaySettings=new Me,u.info("Display settings manager initialized");const S="2026-03-20T19:48:56.043Z",T="0.7.2";u.info(`v${T} built ${S}`);const _=Object.entries(j).map(([x,k])=>`${x}=${k}`).join(" ");u.info(`SDK: ${_}`);const L=!!window.electronAPI,A=L?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,R=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",W=L?`Electron ${A} / Chrome ${R}`:`Chrome ${R}`;u.info(`Env: PWA v${T} | ${W} | ${navigator.platform} | ${screen.width}x${screen.height}`),u.info("Core modules loaded")}catch(n){throw u.error("Failed to load core modules:",n),n}}setupCoreEventHandlers(){this.core.on(v.COLLECTION_START,()=>{this.updateStatus("Collecting data from CMS...")}),this.core.on(v.REGISTER_COMPLETE,e=>{var i;const t=((i=this.displaySettings)==null?void 0:i.getDisplayName())||e.displayName||E.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on(v.REGISTER_COMPLETE,e=>{var t;!e.syncConfig&&((t=E.data)!=null&&t.sync)&&(u.info("[Sync] Using local sync config (CMS did not provide syncConfig)"),this.core.syncConfig=E.data.sync,this.core.emit(v.SYNC_CONFIG,E.data.sync))}),this.core.on(v.OFFLINE_MODE,e=>{var t;e&&!this.syncManager&&((t=E.data)!=null&&t.sync)&&(u.info("[Sync] Offline mode with local sync config — starting sync"),this.core.syncConfig=E.data.sync,this.core.emit(v.SYNC_CONFIG,E.data.sync))}),this.core.on(v.SYNC_CONFIG,async e=>{var o,s;if(this.syncManager&&this.syncManager.stop(),e.syncPublisherPort)if(e.syncGroupId&&(e.syncGroup=String(e.syncGroupId)),e.isLead)e.relayUrl=`ws://localhost:${e.syncPublisherPort}/sync`,fetch("/system/advertise-sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({syncGroupId:e.syncGroupId,port:e.syncPublisherPort,displayId:E.hardwareKey})}).catch(()=>{});else{let r=e.syncGroup;try{const a=await fetch(`/system/discover-lead?syncGroupId=${e.syncGroupId}`);if(a.ok){const{host:l,port:d}=await a.json();r=l,u.info(`mDNS discovered lead at ${l}:${d}`)}}catch{u.warn("mDNS discovery failed, using CMS-provided IP")}e.relayUrl=`ws://${r}:${e.syncPublisherPort}/sync`}const{syncToken:t,...i}=e,n={...((o=E.data)==null?void 0:o.sync)||{},...i};(s=window.electronAPI)!=null&&s.setConfig?window.electronAPI.setConfig({sync:n}):fetch("/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sync:n})}).catch(()=>{}),e.syncToken||(e.syncToken=E.cmsKey),this.syncManager=new Oe({displayId:E.hardwareKey,syncConfig:e,onLayoutChange:async r=>{var d,c;const a=e.layoutMap||((d=E.sync)==null?void 0:d.layoutMap),l=(a==null?void 0:a[r])??r;l!==r&&u.info(`[Sync] Wall mode: lead layout ${r} → local layout ${l}`),u.info(`[Sync] Preparing layout ${l} (waiting for show signal)`),await this.prepareLayout(parseInt(String(l),10)),(c=this.syncManager)==null||c.reportReady(r)},onLayoutShow:r=>{var w;const a=e.layoutMap||((w=E.sync)==null?void 0:w.layoutMap),l=(a==null?void 0:a[r])??r,d=parseInt(String(l),10),c=e.choreography||"simultaneous",g=e.staggerMs??150,h={choreography:c,staggerMs:g};e.topology?(h.topology=e.topology,h.gridCols=e.gridCols??1,h.gridRows=e.gridRows??1):(h.position=e.position??0,h.totalDisplays=e.totalDisplays??1);const m=Pe(h);m>0?(u.info(`[Sync] Show layout ${d} with ${m}ms choreography delay (${c})`),setTimeout(()=>this.renderer.showLayout(d),m)):(u.info(`[Sync] Show layout ${d}`),this.renderer.showLayout(d))},onVideoStart:(r,a)=>{var l,d;u.info(`[Sync] Video start: layout ${r} region ${a}`),(d=(l=this.renderer).resumeRegionMedia)==null||d.call(l,a)},onStatsReport:async(r,a,l)=>{u.info(`[Sync] Submitting stats for follower ${r}`);try{await this.xmds.submitStats(a,r)&&l()}catch(d){u.warn(`[Sync] Stats submission failed for follower ${r}:`,d)}},onLogsReport:async(r,a,l)=>{u.info(`[Sync] Submitting logs for follower ${r}`);try{await this.xmds.submitLog(a,r)&&l()}catch(d){u.warn(`[Sync] Log submission failed for follower ${r}:`,d)}},onStatsAck:async r=>{u.info("[Sync] Lead confirmed stats submission"),this._pendingFollowerStats&&this.statsCollector&&(await this.statsCollector.clearSubmittedStats(this._pendingFollowerStats),this._pendingFollowerStats=null)},onLogsAck:async r=>{u.info("[Sync] Lead confirmed logs submission"),this._pendingFollowerLogs&&this.logReporter&&(await this.logReporter.clearSubmittedLogs(this._pendingFollowerLogs),this._pendingFollowerLogs=null)},onGroupUpdate:(r,a)=>{u.info(`[Sync] Group update: ${r} displays, topology: ${JSON.stringify(a)}`),e.totalDisplays=r}}),this.core.setSyncManager(this.syncManager),this.syncManager.start(),u.info(`[Sync] SyncManager started as ${e.isLead?"LEAD":"FOLLOWER"}`),this.updateConfigDisplay()}),this.core.on(v.FILES_RECEIVED,e=>{this.updateStatus(`Downloading ${e.length} files...`)}),this.core.on(v.OFFLINE_MODE,e=>{e?(this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()):(this.updateStatus("Back online"),this.removeOfflineIndicator())}),this.core.on(v.PURGE_REQUEST,async e=>{try{const t=await U.remove(e);u.info(`Purge complete: ${t.deleted}/${t.total} files deleted`)}catch(t){u.warn("Purge failed:",t)}}),this.core.on(v.DOWNLOAD_REQUEST,async e=>{var t,i,n;(t=this.downloadOverlay)==null||t.startUpdating();try{const o=((n=(i=this.xmds)==null?void 0:i.getToken)==null?void 0:n.call(i))||null;o&&await fetch("/auth-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:o})}),await this.enqueueDownloads(e),u.info("Download enqueue complete")}catch(o){u.error("Download request failed:",o),this.updateStatus("Download failed: "+o,"error")}}),this.core.on(v.SCHEDULE_RECEIVED,e=>{var t;if(this.updateStatus("Processing schedule..."),e.layouts&&e.layouts.length>0?this.currentScheduleId=parseInt(e.layouts[0].scheduleid)||-1:e.campaigns&&e.campaigns.length>0&&(this.currentScheduleId=parseInt(e.campaigns[0].scheduleid)||-1),(t=this.renderer)!=null&&t.layoutPool){const i=new Set;if(e.layouts)for(const o of e.layouts){const s=q(o.file||o.id||o);s&&i.add(s)}if(e.campaigns){for(const o of e.campaigns)if(o.layouts)for(const s of o.layouts){const r=q(s.file||s.id||s);r&&i.add(r)}}const n=this.renderer.layoutPool.clearWarmNotIn(i);n>0&&u.info(`Cleared ${n} preloaded layout(s) no longer in schedule`),this.scheduledLayoutIds=i}u.debug("Current scheduleId for stats:",this.currentScheduleId)}),this.core.on(v.LAYOUT_PREPARE_REQUEST,async e=>{await this.prepareLayout(e),(!this.syncManager||this.renderer.getCurrentLayoutId()===null)&&this.renderer.showLayout(e)}),this.core.on(v.LAYOUT_EXPIRE_CURRENT,()=>{u.info("Schedule changed — expiring current layout"),this.renderer.stopCurrentLayout()}),this.core.on(v.NO_LAYOUTS_SCHEDULED,()=>{this.updateStatus("No layouts scheduled")}),this.core.on(v.COLLECTION_COMPLETE,()=>{const e=this.core.getCurrentLayoutId();e?this.updateStatus(`Playing layout ${e}`):this.preparingLayoutId&&this.updateStatus(`Downloading layout ${this.preparingLayoutId}...`)}),this.core.on(v.COLLECTION_ERROR,async e=>{var i;this.updateStatus(`Collection error: ${e}`,"error");const t=(e==null?void 0:e.message)||String(e);if(t.includes("403")&&(t.includes("Display not found")||t.includes("not authorized"))){u.warn("Display not registered or not authorized — showing setup screen"),this.setupOverlay||(this.setupOverlay=new Te),this.setupOverlay.show();return}(i=this.logReporter)==null||i.reportFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.submitFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`)}),this.core.on(v.XMR_CONNECTED,e=>{u.info("XMR connected:",e)}),this.core.on(v.XMR_MISCONFIGURED,e=>{u.warn(`XMR misconfigured (${e.reason}): ${e.message}`)}),this.core.on(v.LOG_LEVEL_CHANGED,()=>{u.info("Log level changed")}),this.core.on(v.OVERLAY_LAYOUT_REQUEST,async e=>{u.info("Overlay layout requested:",e),await this.prepareLayout(e),this.renderer.showLayout(e)}),this.core.on(v.REVERT_TO_SCHEDULE,()=>{u.info("Reverting to scheduled content"),this.updateStatus("Reverting to schedule...")}),this.core.on(v.PURGE_ALL_REQUEST,async()=>{u.info("Purging all cached content..."),this.updateStatus("Purging cache...");try{const e=await U.list();if(e.length>0){const i=await U.remove(e);u.info(`Purged ${i.deleted} files from ContentStore`)}const t=await caches.keys();t.length>0&&(await Promise.all(t.map(i=>caches.delete(i))),u.info(`Purged ${t.length} legacy caches`))}catch(e){u.error("Cache purge failed:",e)}}),this.core.on(v.COMMAND_RESULT,e=>{var t;u.info("Command result:",e),e.success||((t=this.logReporter)==null||t.reportFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`),this.submitFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`))}),this.core.on(v.SCHEDULED_COMMAND,e=>{u.info(`Scheduled command: ${e.code}`),this.core.executeCommand(e.code)}),this.core.on(v.EXECUTE_NATIVE_COMMAND,async e=>{var i;let t;if((i=window.electronAPI)!=null&&i.executeShellCommand)t=await window.electronAPI.executeShellCommand({commandString:e.commandString});else try{t=await(await fetch("/shell-command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commandString:e.commandString})})).json()}catch(n){t={success:!1,reason:n.message}}this.core.emit(v.COMMAND_RESULT,{code:e.code,...t})}),this.displaySettings&&(this.displaySettings.on("interval-changed",e=>{u.info(`Collection interval changed to ${e}s`)}),this.displaySettings.on("settings-applied",(e,t)=>{t.length>0&&u.info("Settings updated from CMS:",t.join(", ")),this._screenshotInterval||this.startScreenshotInterval()})),this.core.on(v.SUBMIT_STATS_REQUEST,async()=>{await this.submitStats()}),this.core.on(v.SUBMIT_LOGS_REQUEST,async()=>{await this.submitLogs()}),this.core.on(v.SCREENSHOT_REQUEST,async()=>{await this.captureAndSubmitScreenshot()}),this.core.on(v.CHECK_PENDING_LAYOUT,async e=>{await this.prepareLayout(e),this.renderer.showLayout(e)}),this.core.on(v.NAVIGATE_TO_WIDGET,e=>{e.targetId?this.renderer.navigateToWidget(e.targetId):u.warn("navigate-to-widget action has no targetId:",e)}),this.core.on(v.TIMELINE_UPDATED,e=>{var n;const t=this.core.getCurrentLayoutId(),i=t?this.core.getLayoutDuration(t):void 0;(n=this.timelineOverlay)==null||n.update(e,t,i)})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var l,d;if(((l=t.data)==null?void 0:l.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(d=t.ports)==null?void 0:d[0];if(!r)return;const a=this.handleInteractiveControl(i,n,o,s);r.postMessage(a)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupDataConnectorNotify(){this.core.getDataConnectorManager().on("data-changed",t=>{var o;const i=document.querySelectorAll("iframe"),n={ctrl:"rtNotifyData",data:{dataKey:t}};for(const s of i)try{(o=s.contentWindow)==null||o.postMessage(n,"*")}catch{}})}setupRemoteControls(){window.addEventListener("blur",()=>{var a;(a=this.setupOverlay)!=null&&a.isVisible()||setTimeout(()=>window.focus(),200)});const e=a=>{const l=()=>{var d;try{const c=a.contentDocument||((d=a.contentWindow)==null?void 0:d.document);if(!c||a.__keyForwarderAttached)return;a.__keyForwarderAttached=!0,c.addEventListener("keydown",g=>{var m;if((m=this.setupOverlay)!=null&&m.isVisible())return;const h=new KeyboardEvent("keydown",{key:g.key,code:g.code,keyCode:g.keyCode,ctrlKey:g.ctrlKey,shiftKey:g.shiftKey,altKey:g.altKey,metaKey:g.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(h)||g.preventDefault()})}catch{}};a.addEventListener("load",l),l()};Array.from(document.querySelectorAll("iframe")).forEach(a=>e(a)),this._iframeObserver=new MutationObserver(a=>{for(const l of a)for(const d of l.addedNodes)d instanceof HTMLIFrameElement&&e(d),d instanceof HTMLElement&&d.querySelectorAll("iframe").forEach(c=>e(c))}),this._iframeObserver.observe(document.body,{childList:!0,subtree:!0});const t=this.getControls(),{keyboard:i={}}=t,n=i.debugOverlays===!0,o=i.setupKey===!0,s=i.playbackControl===!0,r=i.videoControls===!0;document.addEventListener("keydown",a=>{if(a.key==="q"&&(a.ctrlKey||a.metaKey)){a.preventDefault(),u.info("[Remote] Quit requested (Ctrl+Q)"),fetch("/quit",{method:"POST"}).catch(()=>{});return}switch(a.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new Se(!0,l=>this.skipToLayout(l))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new be({enabled:!0,autoHide:!1}),this.downloadOverlay.setProgressCallback(()=>O.getProgress())),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const l=[...document.querySelectorAll("video")];document.querySelectorAll("iframe").forEach(c=>{try{l.push(...c.contentDocument.querySelectorAll("video"))}catch{}});const d=l.length>0&&!l[0].controls;l.forEach(c=>c.controls=d);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),a.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),a.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),a.preventDefault();break;case"r":case"R":if(!s)break;this.core.isLayoutOverridden()&&(u.info("[Remote] Revert to schedule (keyboard)"),this.core.revertToSchedule());break;case"s":case"S":if(!o)break;this.setupOverlay||(this.setupOverlay=new Te),this.setupOverlay.toggle(),a.preventDefault();break}}),s&&"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("nexttrack",()=>{u.info("[Remote] Next layout (MediaSession)"),this.core.advanceToNextLayout()}),navigator.mediaSession.setActionHandler("previoustrack",()=>{u.info("[Remote] Previous layout (MediaSession)"),this.core.advanceToPreviousLayout()}),navigator.mediaSession.setActionHandler("pause",()=>{u.info("[Remote] Pause (MediaSession)"),this.renderer.pause()}),navigator.mediaSession.setActionHandler("play",()=>{u.info("[Remote] Resume (MediaSession)"),this.renderer.resume()})),u.info("Remote controls initialized (keyboard + MediaSession)")}getControls(){return E.controls}skipToLayout(e){u.info(`Skipping to layout ${e} (timeline click)`),this.core.changeLayout(e)}parseBody(e){try{return e?JSON.parse(e):{}}catch{return{}}}handleInteractiveControl(e,t,i,n){var o;switch(u.debug("IC request:",e,t,i),t){case"/info":return{status:200,body:JSON.stringify({hardwareKey:E.hardwareKey,displayName:E.displayName,playerType:"pwa",currentLayoutId:this.core.getCurrentLayoutId()})};case"/trigger":{const s=this.parseBody(n);return this.renderer.emit("interactiveTrigger",{targetId:s.id,triggerCode:s.trigger}),s.trigger&&this.core.handleTrigger(s.trigger),{status:200,body:"OK"}}case"/duration/expire":{const s=this.parseBody(n);return u.info("IC: Widget duration expire requested for",s.id),this.renderer.emit("widgetExpire",{widgetId:s.id}),{status:200,body:"OK"}}case"/duration/extend":{const s=this.parseBody(n);return u.info("IC: Widget duration extend by",s.duration,"for",s.id),this.renderer.emit("widgetExtendDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/duration/set":{const s=this.parseBody(n);return u.info("IC: Widget duration set to",s.duration,"for",s.id),this.renderer.emit("widgetSetDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/fault":{const s=this.parseBody(n);return(o=this.logReporter)==null||o.reportFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault"),this.submitFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault",{layoutId:s.layoutId,regionId:s.regionId,widgetId:s.widgetId}),{status:200,body:"OK"}}case"/realtime":{const r=new URLSearchParams(i).get("dataKey");if(u.debug("IC: Realtime data request for key:",r),!r)return{status:400,body:JSON.stringify({error:"Missing dataKey parameter"})};const l=this.core.getDataConnectorManager().getData(r);return l===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof l=="string"?l:JSON.stringify(l)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:E.displayId,hardwareKey:E.hardwareKey,displayName:E.displayName,width:window.innerWidth,height:window.innerHeight,latitude:E.latitude||null,longitude:E.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}notifyFileCached(e,t){if(u.debug(`Download complete: ${t}/${e}`),t==="layout")this.core.notifyMediaReady(parseInt(e),t);else if(t==="media"){const i=this._fileIdToSaveAs.get(e)||e;this.core.notifyMediaReady(i,t)}this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3),this._mediaStatusTimer&&clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=setTimeout(()=>{this._mediaStatusTimer=null,this.checkTimelineMediaStatus().catch(()=>{})},2e3)}async enqueueDownloads(e){const{extractMediaIdsFromXlf:t}=await N(async()=>{const{extractMediaIdsFromXlf:S}=await import("./index-O4mn_OO0.js");return{extractMediaIdsFromXlf:S}},__vite__mapDeps([0,1,2]),import.meta.url),{layoutOrder:i,files:n,layoutDependants:o}=e,s=S=>(S.path||"").split("?")[0].replace(/^\/+/,"")||`${S.type||"media"}/${S.id}`;for(const S of n)S.saveAs&&this._fileIdToSaveAs.set(String(S.id),S.saveAs);const r=new Map,a=[],l=new Map,d=new Map;for(const S of n)if(S.type==="layout")r.set(parseInt(S.id),S);else if(S.type==="static")a.push(S);else{const T=`${S.type}:${S.id}`;l.set(T,S);const _=String(S.id);d.has(_)||d.set(_,[]),d.get(_).push(T)}u.info(`Download: ${i.length} layouts, ${l.size} media, ${a.length} resources`);const c=new Map,h=[...i,...[...r.keys()].filter(S=>!i.includes(S))].map(async S=>{const T=r.get(S);if(!(T!=null&&T.path))return;let _;try{const L={};T.cmsDownloadUrl&&(L["X-Cms-Download-Url"]=T.cmsDownloadUrl);const A=await fetch(T.path,Object.keys(L).length?{headers:L}:void 0);A.ok&&(_=await A.text(),u.info(`Fetched XLF ${S} (${_.length} bytes)`),this.notifyFileCached(String(S),"layout"))}catch{}_&&c.set(S,t(_,u))});await Promise.allSettled(h),u.info(`Parsed ${c.size} XLFs`);const m=async(S,T)=>{if(!T.path||T.path==="null"||T.path==="undefined")return!1;const _=s(T);try{if((await fetch(`/store/${_}`,{method:"HEAD"})).ok)return!1}catch{}if(O.getTask(_))return!1;try{const A=await fetch(`/store/missing-chunks/${_}`);if(A.ok){const{missing:R,numChunks:W}=await A.json();if(W>0&&R.length<W){const x=new Set;for(let k=0;k<W;k++)R.includes(k)||x.add(k);T.skipChunks=x,u.info(`Resuming ${_}: ${x.size}/${W} chunks cached, ${R.length} to download`)}}}catch{}const L=S.addFile(T);return L.state!=="pending"?!1:(L.wait().then(A=>{const R=parseInt(T.size)||A.size;u.info("Download complete:",_,`(${R} bytes)`),R>this._chunkConfig.chunkSize&&fetch("/store/mark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:_})}).catch(W=>u.warn("mark-complete failed:",_,W.message)),this.notifyFileCached(String(T.id),T.type),O.removeCompleted(_)}).catch(A=>{u.error("Download failed:",T.id,A),O.removeCompleted(s(T))}),!0)},w=O.createTaskBuilder();await Promise.all(a.map(S=>m(w,S)));const y=await w.build();y.length>0&&(y.push(fe),O.enqueueOrderedTasks(y));const b=new Set,C=[...c.keys()].filter(S=>!i.includes(S)),I=new Map;for(const[S,T]of l)T.saveAs&&I.set(T.saveAs,S);const M=new Map;if(o)for(const[S,T]of Object.entries(o))M.set(parseInt(S,10),T);for(const S of i){const T=c.get(S);if(!T)continue;const _=new Set(T);for(const x of C){const k=c.get(x);if(k)for(const P of k)_.add(P)}const L=M.get(S)||[];for(const x of L){const k=I.get(x);k&&_.add(k)}const A=[];for(const x of _){if(l.has(x)&&!b.has(x)){A.push(l.get(x)),b.add(x);continue}const k=d.get(String(x))||[];for(const P of k)b.has(P)||(A.push(l.get(P)),b.add(P))}if(A.length===0)continue;u.info(`Layout ${S}: ${A.length} media`),A.sort((x,k)=>(x.size||0)-(k.size||0));const R=O.createTaskBuilder();await Promise.all(A.map(x=>m(R,x)));const W=await R.build();W.length>0&&(W.push(fe),O.enqueueOrderedTasks(W))}const D=[...l.keys()].filter(S=>!b.has(S));if(D.length>0){u.info(`${D.length} media not in any XLF`);const S=O.createTaskBuilder();await Promise.all(D.map(_=>{const L=l.get(_);return L?m(S,L):Promise.resolve(!1)}));const T=await S.build();T.length>0&&O.enqueueOrderedTasks(T)}u.info("Downloads active:",O.running,", queued:",O.queued)}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var n;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1;const i=this.core.getLayoutDuration(e)||(t==null?void 0:t.duration);(n=this.timelineOverlay)==null||n.update(null,e,i),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(o=>{u.error("Failed to start layout stat:",o)})}),this.renderer.on("layoutEnd",e=>{if(u.info("Layout ended:",e),Q==null||Q.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.renderer.getCurrentLayoutId()&&this.renderer.getCurrentLayoutId()!==e){u.debug(`Layout ${e} ended but ${this.renderer.getCurrentLayoutId()} already playing, skipping advance`);return}if(this.preparingLayoutId&&this.preparingLayoutId!==e){u.debug(`Layout ${e} ended but ${this.preparingLayoutId} being prepared, skipping advance`);return}this.core.notifyLayoutStatus(e),this.core.clearCurrentLayout();const t=this.core.getPendingLayouts();if(t.length>0){u.info(`Layout ${t[0]} pending download, skipping advance`);return}u.info("Layout cycle completed, advancing to next layout..."),this.core.advanceToNextLayout()}),this.renderer.on("widgetStart",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget started:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.startWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to start widget stat:",o)})}),this.renderer.on("widgetEnd",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget ended:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.endWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to end widget stat:",o)})}),this.renderer.on("widgetCommand",e=>{u.info("Widget command:",e.commandCode);const t={[e.commandCode]:{commandString:e.commandString}};this.core.executeCommand(e.commandCode,t)}),this.renderer.on("error",e=>{var t;u.error("Renderer error:",e),this.updateStatus(`Error: ${e.type}`,"error"),(t=this.logReporter)==null||t.reportFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type} (layout ${e.layoutId||"unknown"})`),this.submitFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type}`,{layoutId:e.layoutId,regionId:e.regionId,widgetId:e.widgetId})}),this.renderer.on("action-trigger",e=>{var r,a;const{actionType:t,triggerCode:i,layoutCode:n,targetId:o,commandCode:s}=e;switch(u.info("Action trigger:",t,e),t){case"navLayout":case"navigateToLayout":i?this.core.handleTrigger(i):n&&this.core.changeLayout(n);break;case"navWidget":case"navigateToWidget":i?this.core.handleTrigger(i):o&&this.renderer.navigateToWidget(o);break;case"previousWidget":this.renderer.previousWidget((r=e.source)==null?void 0:r.regionId);break;case"nextWidget":this.renderer.nextWidget((a=e.source)==null?void 0:a.regionId);break;case"command":s&&this.core.executeCommand(s);break;default:u.warn("Unknown action type:",t)}this.statsCollector&&this.statsCollector.recordEvent("touch",this.core.getCurrentLayoutId(),e.targetId||null,this.currentScheduleId)}),this.renderer.on("widgetAction",e=>{e.type==="durationEnd"&&e.url&&(u.info(`Widget ${e.widgetId} duration ended, calling webhook: ${e.url}`),this.statsCollector&&this.statsCollector.recordEvent("webhook",e.layoutId,e.widgetId,this.currentScheduleId),fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:e.widgetId,layoutId:e.layoutId,regionId:e.regionId,event:"durationEnd",timestamp:new Date().toISOString()})}).catch(t=>u.warn("Webhook failed (non-critical):",t)))}),this.renderer.on("layoutDurationUpdated",(e,t,i)=>{this.core.recordLayoutDuration(String(e),t,i)}),this.renderer.on("request-next-layout-preload",async()=>{try{const e=this.core.peekNextLayout();if(!e){u.debug("No next layout to preload (single layout schedule or same layout)");return}const t=e.layoutId;if(this.renderer.layoutPool.has(t)){u.debug(`Layout ${t} already in preload pool`);return}u.info(`Preloading next layout ${t}...`);const i=await U.get(`${X}/layouts`,t);if(!i){u.debug(`Layout ${t} XLF not cached, skipping preload`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){u.debug(`Media not fully cached for layout ${t}, skipping preload`);return}await this.fetchWidgetHtml(n,t),await this.renderer.preloadLayout(n,t)?u.info(`Layout ${t} preloaded successfully`):u.warn(`Layout ${t} preload failed (will fall back to normal render)`)}catch(e){u.warn("Layout preload failed (non-blocking):",e)}}),this.renderer.on("videoError",async({storedAs:e})=>{if(!e)return;const t=`${H.slice(1)}/media/file/${e}`;try{const i=await fetch(`/store/missing-chunks/${t}`),{missing:n}=await i.json();if(n.length===0){u.warn(`Video ${e}: corrupt file (all chunks present), deleting for re-download`),await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{key:t}]})});const o=this.core.getCurrentLayoutId();o&&this.core.setPendingLayout(o,[e]),this.core.collectNow().catch(s=>{u.error(`Failed to trigger re-download for ${e}:`,s.message)});return}u.warn(`Video ${e}: ${n.length} missing chunks (${n.join(", ")}), re-downloading`),await fetch("/store/unmark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:t})}),this.core.collectNow().catch(o=>{u.error(`Failed to trigger re-download for ${e}:`,o.message)})}catch(i){u.error(`Failed to check/re-download ${e}:`,i.message)}})}async prepareLayout(e){var t;if(this.renderer.getCurrentLayoutId()===e){u.debug(`Layout ${e} replay`),this.core.clearPreparingLayout(),await this.renderer.renderLayout("",e);return}if(this.preparingLayoutId===e){u.debug(`Layout ${e} preparation in progress, will retry after it completes`),this._pendingRetryLayoutId=e;return}this.preparingLayoutId=e;try{const i=await U.get(`${X}/layouts`,e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[String(e)]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),o=new DOMParser().parseFromString(n,"text/xml"),{allMedia:s}=this.getMediaIds(o);if(!await this.checkAllMediaCached(s)){O.prioritizeLayoutFiles(s.map(String)),u.info(`Waiting for media to finish downloading for layout ${e}`),this.updateStatus(`Preparing layout ${e}...`),this.core.setPendingLayout(e,s);return}this.renderer.hasPreloadedLayout(e)||await this.fetchWidgetHtml(o,e),await this.renderer.preloadLayout(n,e),u.info(`Layout ${e} ready`)}catch(i){u.error("Failed to prepare layout:",e,i),this.updateStatus(`Failed to load layout ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`),this.submitFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`,{layoutId:e})}finally{this.preparingLayoutId=null,this.core.clearPreparingLayout();const i=this._pendingRetryLayoutId;this._pendingRetryLayoutId=null,i!=null&&this.core.getCurrentLayoutId()!==i&&(u.debug(`Retrying preparation for layout ${i} after 500ms`),setTimeout(()=>this.prepareLayout(i),500))}}getMediaIds(e){var s;const t=typeof e=="string"?new DOMParser().parseFromString(e,"text/xml"):e,i=[],n=[];t.querySelectorAll("media[fileId]").forEach(r=>{const a=r.getAttribute("fileId");if(a){const l=this._fileIdToSaveAs.get(a)||a;if(l.endsWith(".xlf"))return;i.push(l),r.getAttribute("type")==="video"&&n.push(l)}});const o=(s=t.querySelector("layout"))==null?void 0:s.getAttribute("background");if(o){const r=this._fileIdToSaveAs.get(o)||o;i.includes(r)||i.push(r)}return{allMedia:i,videoMedia:n}}async checkAllMediaCached(e){const t=await Promise.all(e.map(async n=>{try{return await U.has(X,`media/file/${n}`)}catch{return u.warn(`Unable to verify media ${n}, assuming cached (offline mode)`),!0}})),i=e.filter((n,o)=>!t[o]);return i.length>0?(u.debug(`Media not yet cached: ${i.join(", ")}`),!1):!0}async fetchWidgetHtml(e,t){const i=typeof e=="string"?new DOMParser().parseFromString(e,"text/xml"):e,n=[];for(const o of i.querySelectorAll("region")){const s=o.getAttribute("id");for(const r of o.querySelectorAll("media")){const a=r.getAttribute("type"),l=r.getAttribute("id");r.getAttribute("render")==="html"&&n.push((async()=>{try{const c=`${t}/${s}/${l}`;let g=null;const h=await U.get(`${X}/widgets`,c);h&&(g=await h.text(),u.debug(`Found cached widget HTML for ${a} ${l}`)),g||(g=await this.xmds.getResource(t,s,l),u.debug(`Retrieved widget HTML for ${a} ${l} from CMS`)),g=(await $e(t,s,l,g)).html;const w=r.querySelector("raw");if(w)w.textContent=g;else{const y=i.createElement("raw");y.textContent=g,r.appendChild(y)}}catch(c){u.warn(`Failed to get widget HTML for ${a} ${l}:`,c)}})())}}n.length>0&&(u.info(`Fetching ${n.length} widget HTML resources in parallel...`),await Promise.all(n),u.debug("All widget HTML fetched"))}async checkTimelineMediaStatus(){if(this.scheduledLayoutIds.size!==0){for(const e of this.scheduledLayoutIds){const t=`${e}.xlf`;try{const i=await U.get(`${X}/layouts`,e);if(!i)continue;const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(o.length===0){this.core.setLayoutMediaStatus(t,!0);continue}const s=[];for(const r of o)try{await U.has(X,`media/file/${r}`)||s.push(r)}catch{}this.core.setLayoutMediaStatus(t,s.length===0,s)}catch{}}this.core.logUpcomingTimeline()}}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await U.get(`${X}/layouts`,e);if(!t)continue;const i=await t.text(),{videoMedia:n}=this.getMediaIds(i);if(n.length===0)continue;const s=new DOMParser().parseFromString(i,"text/xml"),r=new Map;let a=0;for(const c of s.querySelectorAll('media[type="video"]')){if(c.getAttribute("useDuration")==="1")continue;const h=c.getAttribute("fileId");if(!h)continue;a++;const m=this._fileIdToSaveAs.get(h)||h;if(!await U.has(X,`media/file/${m}`))continue;const y=await this.probeVideoDuration(`${window.location.origin}${H}/media/file/${m}`);y>0&&r.set(h,y)}if(r.size===0)continue;const l=r.size>=a,{duration:d}=We(i,r);d>0&&this.core.recordLayoutDuration(String(e),d,l)}catch(t){u.debug(`Duration probe failed for layout ${e}:`,t)}}probeVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.muted=!0;const n=()=>{i.removeAttribute("src"),i.load()};i.addEventListener("loadedmetadata",()=>{const o=i.duration;n(),t(o)},{once:!0}),i.addEventListener("error",()=>{n(),t(0)},{once:!0}),setTimeout(()=>{n(),t(0)},5e3),i.src=e})}updateConfigDisplay(){var t,i;const e=document.getElementById("config-info");if(e){const n="0.7.2",o="2026-03-20T19:48:56.043Z".replace("T"," ").replace(/\.\d+Z$/,"");let r=`${o?`v${n} (${o})`:`v${n}`} | CMS: ${E.cmsUrl} | Display: ${E.displayName||"Unknown"} | HW: ${E.hardwareKey}`;const a=(i=(t=this.core)==null?void 0:t.getSyncConfig)==null?void 0:i.call(t);if(a){const l=a.relayUrl?new URL(a.relayUrl).host:"";r+=` | Sync: ${a.isLead?"LEAD":`FOLLOWER → ${l}`} (group ${a.syncGroupId||a.syncGroup})`}e.textContent=r}}async submitStats(){var e;if(!this.statsCollector){u.warn("Stats collector not initialized");return}if(this._pendingFollowerStats!==null){u.debug("Stats delegation in-flight, skipping");return}try{const i=(((e=this.displaySettings)==null?void 0:e.getSetting("aggregationLevel"))||"Individual")==="Aggregate"?await this.statsCollector.getAggregatedStatsForSubmission(50):await this.statsCollector.getStatsForSubmission(50);if(i.length===0){u.debug("No stats to submit");return}const n=ke(i);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${i.length} stats to lead`),this._pendingFollowerStats=i,this.syncManager.reportStats(n);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting stats directly"),u.info(`Submitting ${i.length} proof of play stats...`),await this.xmds.submitStats(n)?(u.info("Stats submitted successfully"),await this.statsCollector.clearSubmittedStats(i),u.debug(`Cleared ${i.length} submitted stats from database`)):u.warn("Stats submission failed (CMS returned false)")}catch(t){u.error("Failed to submit stats:",t)}}async submitLogs(){if(this.logReporter){if(this._pendingFollowerLogs!==null){u.debug("Logs delegation in-flight, skipping");return}try{const e=await this.logReporter.getLogsForSubmission();if(e.length===0){u.debug("No logs to submit");return}const t=Re(e);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${e.length} logs to lead`),this._pendingFollowerLogs=e,this.syncManager.reportLogs(t);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting logs directly"),u.info(`Submitting ${e.length} logs to CMS...`),await this.xmds.submitLog(t)?(u.info("Logs submitted successfully"),await this.logReporter.clearSubmittedLogs(e)):u.warn("Log submission failed (CMS returned false)")}catch(e){u.error("Failed to submit logs:",e)}}}submitFault(e,t,i){if(!this.xmds)return;const n=JSON.stringify([{code:e,reason:t,date:new Date().toISOString().replace("T"," ").substring(0,19),...i}]);this.xmds.reportFaults(n).catch(o=>{u.debug("reportFaults failed (non-critical):",o)})}async captureAndSubmitScreenshot(){var e,t;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let i;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const o=await window.electronAPI.captureScreenshot();if(o)this._screenshotMethod="electron",i=o;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else if(this._screenshotMethod==="displayMedia"||this._screenshotMethod===null&&typeof((t=navigator.mediaDevices)==null?void 0:t.getDisplayMedia)=="function")try{i=await this.captureDisplayMedia(),this._screenshotMethod="displayMedia"}catch(o){u.warn("getDisplayMedia failed, falling back to html2canvas:",o.message||o),this._screenshotMethod=null,i=await this.captureHtml2CanvasIsolated(),this._screenshotMethod="html2canvas"}else this._screenshotMethod="html2canvas",i=await this.captureHtml2CanvasIsolated();await this.xmds.submitScreenShot(i)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(i){u.error("Failed to capture screenshot:",i)}finally{this._screenshotInFlight=!1}}async captureDisplayMedia(){const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});try{const t=e.getVideoTracks()[0],n=await new window.ImageCapture(t).grabFrame(),o=document.createElement("canvas");return o.width=n.width,o.height=n.height,o.getContext("2d").drawImage(n,0,0),n.close(),o.toDataURL("image/jpeg",.8).split(",")[1]}finally{e.getTracks().forEach(t=>t.stop())}}async captureHtml2CanvasIsolated(){var o,s;const e=document.createElement("canvas");e.width=window.innerWidth,e.height=window.innerHeight;const t=e.getContext("2d");t.fillStyle="#000",t.fillRect(0,0,e.width,e.height);const i=document.getElementById("player-container");if(!i)return e.toDataURL("image/jpeg",.8).split(",")[1];this._html2canvasMod||(this._html2canvasMod=(await N(async()=>{const{default:r}=await import("./html2canvas.esm-CBrSDip1.js");return{default:r}},[],import.meta.url)).default),this.renderer&&(this.renderer._resizeSuppressed=!0);const n=i.style.contain||"";i.style.contain="strict";try{const r=i.getBoundingClientRect(),a=getComputedStyle(i),l=a.backgroundColor;l&&l!=="transparent"&&l!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=l,t.fillRect(r.left,r.top,r.width,r.height));const d=a.backgroundImage;if(d&&d!=="none"){const h=d.match(/url\(["']?(.*?)["']?\)/);if(h)try{const m=new Image;m.crossOrigin="anonymous",await new Promise(w=>{m.onload=()=>w(),m.onerror=()=>w(),setTimeout(()=>w(),2e3),m.src=h[1]}),m.naturalWidth&&t.drawImage(m,r.left,r.top,r.width,r.height)}catch{}}const c=i.querySelectorAll("img, video, iframe, canvas");let g=0;for(const h of c){const m=h;if(m.style.visibility==="hidden"||m.style.display==="none")continue;const w=h.getBoundingClientRect();if(!(w.width===0||w.height===0))try{if(h instanceof HTMLImageElement){if(!h.complete||!h.naturalWidth)continue;if(getComputedStyle(h).objectFit==="contain"&&h.naturalWidth&&h.naturalHeight){const b=this.containedRect(h.naturalWidth,h.naturalHeight,w);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,w.left,w.top,w.width,w.height);g++}else if(h instanceof HTMLVideoElement){if(h.readyState<2)continue;if(getComputedStyle(h).objectFit==="contain"&&h.videoWidth&&h.videoHeight){const b=this.containedRect(h.videoWidth,h.videoHeight,w);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,w.left,w.top,w.width,w.height);g++}else if(h instanceof HTMLCanvasElement)t.drawImage(h,w.left,w.top,w.width,w.height),g++;else if(h instanceof HTMLIFrameElement){const y=h.contentDocument;if(!(y!=null&&y.body))continue;const b=document.createElement("div");b.style.cssText=`position:fixed;left:-9999px;top:0;width:${w.width}px;height:${w.height}px;overflow:hidden;`;const C=[];for(const _ of y.querySelectorAll("style"))b.appendChild(_.cloneNode(!0));for(const _ of y.querySelectorAll('link[rel="stylesheet"]')){const L=document.createElement("link");L.rel="stylesheet",L.href=new URL(_.getAttribute("href")||"",y.baseURI).href,b.appendChild(L),C.push(new Promise(A=>{L.onload=()=>A(),L.onerror=()=>A()}))}const I=y.body.cloneNode(!0);for(const _ of I.querySelectorAll("img[src]")){const L=_.getAttribute("src")||"";L&&!L.startsWith("http")&&!L.startsWith("data:")&&!L.startsWith("blob:")&&_.setAttribute("src",new URL(L,y.baseURI).href)}b.appendChild(I),document.body.appendChild(b);const M=y.querySelectorAll("img"),D=new Map;M.forEach((_,L)=>{_.naturalWidth&&_.naturalHeight&&D.set(String(L),{nw:_.naturalWidth,nh:_.naturalHeight})}),C.length>0&&await Promise.race([Promise.all(C),new Promise(_=>setTimeout(_,500))]);const S=await this._html2canvasMod(b,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:w.width,height:w.height,onclone:_=>{const L=_.createElement("style");L.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",_.head.appendChild(L),_.querySelectorAll("img").forEach((R,W)=>{var ue,he;const x=(ue=_.defaultView)==null?void 0:ue.getComputedStyle(R);if(!x||x.objectFit!=="contain")return;const k=D.get(String(W));if(!k)return;const P=R.clientWidth||parseFloat(x.width)||0,G=R.clientHeight||parseFloat(x.height)||0;if(!P||!G)return;const Y=k.nw/k.nh,re=P/G;let ee,te;Y>re?(ee=P,te=P/Y):(te=G,ee=G*Y);const ae=_.createElement("div");ae.style.cssText=`width:${P}px;height:${G}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,R.style.objectFit="fill",R.style.width=`${ee}px`,R.style.height=`${te}px`,(he=R.parentNode)==null||he.insertBefore(ae,R),ae.appendChild(R)})}});document.body.removeChild(b),t.drawImage(S,w.left,w.top,w.width,w.height);const T=h.getBoundingClientRect();for(const _ of y.querySelectorAll("video")){if(_.readyState<2)continue;const L=_.getBoundingClientRect();if(!(L.width===0||L.height===0))try{if(((s=(o=y.defaultView)==null?void 0:o.getComputedStyle(_))==null?void 0:s.objectFit)==="contain"&&_.videoWidth&&_.videoHeight){const R=this.containedRect(_.videoWidth,_.videoHeight,new DOMRect(T.left+L.left,T.top+L.top,L.width,L.height));t.drawImage(_,R.x,R.y,R.w,R.h)}else t.drawImage(_,T.left+L.left,T.top+L.top,L.width,L.height)}catch{}}for(const _ of y.querySelectorAll("canvas")){const L=_.getBoundingClientRect();if(!(L.width===0||L.height===0))try{t.drawImage(_,T.left+L.left,T.top+L.top,L.width,L.height)}catch{}}g++}}catch(y){u.warn("Screenshot: failed to draw element",h.tagName,y)}}return u.debug(`Screenshot: composed ${g}/${c.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}finally{i.style.contain=n,this.renderer&&(this.renderer._resizeSuppressed=!1)}}containedRect(e,t,i){const n=e/t,o=i.width/i.height;let s,r;return n>o?(s=i.width,r=i.width/n):(r=i.height,s=i.height*n),{x:i.left+(i.width-s)/2,y:i.top+(i.height-r)/2,w:s,h:r}}startScreenshotInterval(){var i;const e=((i=this.displaySettings)==null?void 0:i.getSetting("screenshotInterval"))||0;if(!e||e<=0)return;!this._html2canvasMod&&!window.electronAPI&&N(()=>import("./html2canvas.esm-CBrSDip1.js"),[],import.meta.url).then(n=>{this._html2canvasMod=n.default});const t=e*1e3;u.info(`Starting periodic screenshots every ${e}s`),this._screenshotInterval=setInterval(()=>{this.captureAndSubmitScreenshot()},t)}updateStatus(e,t="info"){const i=document.getElementById("status");i&&(i.textContent=e,i.className=`status status-${t}`),t==="error"?u.error("Status:",e):u.info("Status:",e)}showOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!0)}removeOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!1)}_syncLeadAlive(){if(!this.syncManager)return!1;for(const[,e]of this.syncManager.followers)if(e.role==="lead"&&Date.now()-e.lastSeen<15e3)return!0;return!1}cleanup(){this.core.cleanup(),this.renderer.cleanup(),this._screenshotInterval&&(clearInterval(this._screenshotInterval),this._screenshotInterval=null),this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.downloadOverlay&&this.downloadOverlay.destroy(),this.timelineOverlay&&this.timelineOverlay.destroy(),this._iframeObserver&&(this._iframeObserver.disconnect(),this._iframeObserver=null),navigator.serviceWorker&&this._swIcHandler&&(navigator.serviceWorker.removeEventListener("message",this._swIcHandler),this._swIcHandler=null),O==null||O.clear(),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null),this._mediaStatusTimer&&(clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=null)}}function Fe(){const p=new wt;p.init().catch(e=>{u.error("Failed to initialize:",e),u.warn("Redirecting to setup screen..."),window.location.href="./setup.html"}),window.addEventListener("beforeunload",()=>{p.cleanup()})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe):Fe();export{v as C,ht as D,Tt as I,ne as L,ct as O,yt as P,dt as R,lt as S,q as a,at as b,nt as c,$t as d,We as p,Lt as s};
|
|
736
|
+
//# sourceMappingURL=main-Ddgs1h5h.js.map
|