@xiboplayer/pwa 0.6.1 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/{chunk-config-oTovBPVw.js → chunk-config-BqCdX6OJ.js} +2 -2
- package/dist/assets/{chunk-config-oTovBPVw.js.map → chunk-config-BqCdX6OJ.js.map} +1 -1
- package/dist/assets/{index-CleHw0Tc.js → index-BHPUGsQU.js} +2 -2
- package/dist/assets/{index-CleHw0Tc.js.map → index-BHPUGsQU.js.map} +1 -1
- package/dist/assets/{index-C3Orblel.js → index-BS70-4bE.js} +2 -2
- package/dist/assets/{index-C3Orblel.js.map → index-BS70-4bE.js.map} +1 -1
- package/dist/assets/index-BftPXCfG.js +13 -0
- package/dist/assets/index-BftPXCfG.js.map +1 -0
- package/dist/assets/index-C122u38X.js +5 -0
- package/dist/assets/index-C122u38X.js.map +1 -0
- package/dist/assets/{index-B6MdC-Qx.js → index-C9mU5kWi.js} +2 -2
- package/dist/assets/{index-B6MdC-Qx.js.map → index-C9mU5kWi.js.map} +1 -1
- package/dist/assets/index-CThL7HEa.js +2 -0
- package/dist/assets/{index-Cq9aOTTR.js.map → index-CThL7HEa.js.map} +1 -1
- package/dist/assets/{index-D_aTOqNE.js → index-DTsYjcZZ.js} +2 -2
- package/dist/assets/{index-D_aTOqNE.js.map → index-DTsYjcZZ.js.map} +1 -1
- package/dist/assets/{index-BWvWWyDc.js → index-H79-vv8p.js} +2 -2
- package/dist/assets/{index-BWvWWyDc.js.map → index-H79-vv8p.js.map} +1 -1
- package/dist/assets/index-gRI8sFgQ.js +2 -0
- package/dist/assets/{index-Dj2ND9Mx.js.map → index-gRI8sFgQ.js.map} +1 -1
- package/dist/assets/index-xcL2piI3.js +2 -0
- package/dist/assets/index-xcL2piI3.js.map +1 -0
- package/dist/assets/main-DGfrcKkR.js +735 -0
- package/dist/assets/main-DGfrcKkR.js.map +1 -0
- package/dist/assets/protocol-detector-bDP-d2EL.js +16 -0
- package/dist/assets/protocol-detector-bDP-d2EL.js.map +1 -0
- package/dist/assets/setup-D3frvQ4W.js +2 -0
- package/dist/assets/{setup-KpkKDvsj.js.map → setup-D3frvQ4W.js.map} +1 -1
- package/dist/assets/{sync-manager-DEght5gK.js → sync-manager-ljAFKrR5.js} +2 -2
- package/dist/assets/{sync-manager-DEght5gK.js.map → sync-manager-ljAFKrR5.js.map} +1 -1
- package/dist/assets/widget-html-tM9V3Qlc.js +2 -0
- package/dist/assets/widget-html-tM9V3Qlc.js.map +1 -0
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +13 -13
- package/dist/assets/index-BVIXBw9z.js +0 -13
- package/dist/assets/index-BVIXBw9z.js.map +0 -1
- package/dist/assets/index-Cq9aOTTR.js +0 -2
- package/dist/assets/index-D81Qhc3r.js +0 -2
- package/dist/assets/index-D81Qhc3r.js.map +0 -1
- package/dist/assets/index-Dj2ND9Mx.js +0 -2
- package/dist/assets/index-leM889oV.js +0 -5
- package/dist/assets/index-leM889oV.js.map +0 -1
- package/dist/assets/main-DvteKhS8.js +0 -729
- package/dist/assets/main-DvteKhS8.js.map +0 -1
- package/dist/assets/setup-KpkKDvsj.js +0 -2
- package/dist/assets/widget-html-BAV4ZZd8.js +0 -2
- package/dist/assets/widget-html-BAV4ZZd8.js.map +0 -1
- package/dist/assets/xmds-client-Dyy8ex-B.js +0 -16
- package/dist/assets/xmds-client-Dyy8ex-B.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createLogger as $,PLAYER_API as q}from"./index-C122u38X.js";const B=$("Cache"),P=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class R{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${P}/cache/${e}/${s||t}`}addDependant(e,t){const s=String(e);this.dependants.has(s)||this.dependants.set(s,new Set),this.dependants.get(s).add(String(t))}removeLayoutDependants(e){const t=String(e),s=[];for(const[n,i]of this.dependants)i.delete(t),i.size===0&&(this.dependants.delete(n),s.push(n));return s.length>0&&B.info(`${s.length} media files orphaned after layout ${e} removed:`,s),s}isMediaReferenced(e){const t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){this.dependants.clear()}}const N=new R,C=$("StoreClient");class O{async has(e,t){try{return(await fetch(`/store/${e}/${t}`,{method:"HEAD"})).ok}catch{return!1}}async get(e,t){var s;try{const n=await fetch(`/store/${e}/${t}`);if(!n.ok){if((s=n.body)==null||s.cancel(),n.status===404)return null;throw new Error(`Failed to get file: ${n.status}`)}return await n.blob()}catch(n){return C.error("get error:",n.message),null}}async put(e,t,s,n="application/octet-stream"){var i;try{const r=await fetch(`/store/${e}/${t}`,{method:"PUT",headers:{"Content-Type":n},body:s});return(i=r.body)==null||i.cancel(),r.ok}catch(r){return C.error("put error:",r.message),!1}}async remove(e){try{const s=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:s.deleted||0,total:s.total||e.length}}catch(t){return C.error("remove error:",t.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return C.error("list error:",e.message),[]}}}const D={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function I(c){return D[c]||D.media}const u=$("Download"),A=6,F=50*1024*1024,M=3,Q=100*1024*1024,z=2,b=6e5,L=15e3;function U(c){var n,i;const t=(i=(n=(c.path||c.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:i.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const p={normal:0,layout:1,high:2,urgent:3},_=Symbol("BARRIER");function k(c){try{const e=c.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function S(c,e=30){const t=k(c);return t===1/0?!1:Date.now()/1e3>=t-e}class x{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=p.normal,this._typeConfig=I(e.type)}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){var s;this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e["X-Store-Chunk-Index"]=String(this.chunkIndex),this._parentFile&&(e["X-Store-Num-Chunks"]=String(this._parentFile.totalChunks),e["X-Store-Chunk-Size"]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e["X-Store-MD5"]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e["X-Cache-TTL"]=String(this.fileInfo.updateInterval));const t=this._typeConfig.maxRetries;for(let n=1;n<=t;n++){const i=new AbortController,r=setTimeout(()=>i.abort(),b);try{const a=this.getUrl(),h={signal:i.signal};Object.keys(e).length>0&&(h.headers=e);const o=await fetch(a,h);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(a){const h=i.signal.aborted?`Timeout after ${b/1e3}s`:a.message;if(n<t){const o=((s=this._typeConfig.retryDelays)==null?void 0:s[n-1])??this._typeConfig.retryDelayMs*n,l=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";u.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${l} attempt ${n}/${t} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(g=>setTimeout(g,o))}else throw this.state="failed",i.signal.aborted?new Error(h):a}finally{clearTimeout(r)}}}}class E{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,n)=>{this._resolve=s,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:n}=this.fileInfo;u.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=U(this.fileInfo);const i=I(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!i){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),L);try{const l=await fetch(a,{method:"HEAD",signal:h.signal});l.ok&&(this.totalBytes=parseInt(l.headers.get("Content-Length")||"0"),this._contentType=l.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}u.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const r=this.options.chunkSize||F;if(this.totalBytes>Q){const a=[];for(let d=0;d<this.totalBytes;d+=r)a.push({start:d,end:Math.min(d+r-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(d=>!this.skipChunks.has(d.index)),o=a.length-h.length;for(const d of a)this.skipChunks.has(d.index)&&(this.downloadedBytes+=d.end-d.start+1);if(h.length===0){u.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&u.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const l=o>0;if(l){const d=h.sort((f,m)=>f.index-m.index);for(const f of d){const m=new x(this.fileInfo,{chunkIndex:f.index,rangeStart:f.start,rangeEnd:f.end});m._parentFile=this,m._priority=p.normal,this.tasks.push(m)}}else for(const d of h){const f=new x(this.fileInfo,{chunkIndex:d.index,rangeStart:d.start,rangeEnd:d.end});f._parentFile=this,f._priority=d.index===0||d.index===a.length-1?p.high:p.normal,this.tasks.push(f)}const g=this.tasks.filter(d=>d._priority>=p.high).length;u.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(g>0?` (${g} priority)`:"")+(l?" (resume)":""))}else{this.totalChunks=1;const a=new x(this.fileInfo,{});a._parentFile=this,this.tasks.push(a)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){u.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){u.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)u.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)u.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let r=0;r<this.totalChunks;r++){const a=this._chunkBlobs.get(r);a&&n.push(a)}const i=new Blob(n,{type:this._contentType});u.info("[FileDownload] Complete:",`${t}/${s}`,`(${i.size} bytes, reassembled)`),this._resolve(i)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(i=>i!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}u.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class K{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=T.stableKey(e);if(this.queue.active.has(t)){const n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=k(n.fileInfo.path);k(e.path)>i&&(n.fileInfo.path=e.path)}return n}const s=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const n=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const i=this._filesToPrepare[s++];t++,i.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var r;const e=[],t=[],s=[],n=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)t.push(a);else{const h=((r=a._parentFile)==null?void 0:r.totalChunks)||0;h>1&&a.chunkIndex===h-1?s.push(a):n.push(a)}e.sort((a,h)=>{var o,l;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((l=h._parentFile)==null?void 0:l.totalBytes)||0)}),n.sort((a,h)=>a.chunkIndex-h.chunkIndex);const i=[...e,...t,...s];return n.length>0&&i.push(_,...n),i}}class T{constructor(e={}){this.concurrency=e.concurrency||A,this.chunkSize=e.chunkSize||F,this.maxChunksPerFile=e.chunksPerFile||M,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=T.stableKey(e);if(this.active.has(t)){const n=this.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=k(n.fileInfo.path);k(e.path)>i&&(u.info("[DownloadQueue] Refreshing URL for",t),n.fileInfo.path=e.path)}return n}const s=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),u.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),u.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const n of e)n===_?(this.queue.push(_),s++):(this.queue.push(n),t++);u.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,n=this.active.get(s);if(!n)return u.info("[DownloadQueue] Not found:",s),!1;let i=0;for(const r of this.queue)r._parentFile===n&&r._priority<p.high&&(r._priority=p.high,i++);return this._sortQueue(),u.info("[DownloadQueue] Prioritized:",s,`(${i} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=p.high){var i,r,a,h;const s=new Set(e.map(String));let n=0;for(const o of this.queue){const l=((i=o._parentFile)==null?void 0:i.fileInfo.saveAs)||String((r=o._parentFile)==null?void 0:r.fileInfo.id);s.has(l)&&o._priority<t&&(o._priority=t,n++)}for(const o of this._activeTasks){const l=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);s.has(l)&&o._priority<t&&(o._priority=t)}this._sortQueue(),u.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",n,"tasks boosted to",t)}urgentChunk(e,t,s){const n=`${e}/${t}`,i=this.active.get(n);if(!i)return u.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",s),!1;if(this._activeTasks.some(o=>o._parentFile===i&&o.chunkIndex===s&&o.state==="downloading")){const o=this._activeTasks.find(l=>l._parentFile===i&&l.chunkIndex===s);return o&&o._priority<p.urgent?(o._priority=p.urgent,u.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (already in-flight, limiting slots)`),!0):(u.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",s),!1)}const a=this.queue.findIndex(o=>o!==_&&o._parentFile===i&&o.chunkIndex===s);if(a===-1)return u.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",s),!1;const h=this.queue.splice(a,1)[0];return h._priority=p.urgent,this.queue.unshift(h),u.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(i=>i!==_&&i._priority>=p.urgent)||((n=this._activeTasks)==null?void 0:n.some(i=>i._priority>=p.urgent&&i.state==="downloading")),t=e?z:this.concurrency,s=e?p.urgent:0;for(;this.running<t&&this.queue.length>0;){const i=this.queue[0];if(i===_){if(this.running>0)break;this.queue.shift();continue}if(i._priority<s||!this._canStartTask(i)){let r=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==_;a++){const h=this.queue[a];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(i)}this.queue.length===0&&this.running===0&&u.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),u.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(a=>a!==e);const{maxReenqueues:i,reenqueueDelayMs:r}=e._typeConfig;if(i>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>i){u.error(`[DownloadQueue] ${t} exceeded ${i} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}u.warn(`[DownloadQueue] ${t} failed all retries (attempt ${e._reenqueueCount}/${i}), scheduling re-enqueue in ${r/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),u.info(`[DownloadQueue] ${t} re-enqueued for retry`),this.processQueue()},r);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===_||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())s.state==="complete"||s.state==="failed"||(e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(const e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}}class X{constructor(e={}){this.queue=new T(e)}enqueue(e){return this.queue.enqueue(e)}enqueueForLayout(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,s){return this.queue.urgentChunk(e,t,s)}clear(){this.queue.clear()}}const y=$("CacheAnalyzer");function w(c){if(c===0)return"0 B";if(!Number.isFinite(c))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(c)/Math.log(1024));return`${(c/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class Y{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.list(),s=await this._getStorageEstimate(),n=new Set(e.map(o=>String(o.id))),i=[],r=[];for(const o of t)if(n.has(String(o.id)))i.push(o);else if(o.type==="widget"){const l=String(o.id).split("/")[0];n.has(l)?i.push(o):r.push(o)}else o.type==="static"?i.push(o):r.push(o);r.sort((o,l)=>(o.cachedAt||0)-(l.cachedAt||0));const a=r.reduce((o,l)=>o+(l.size||0),0),h={timestamp:Date.now(),storage:{usage:s.usage,quota:s.quota,percent:s.quota>0?Math.round(s.usage/s.quota*100):0},files:{required:i.length,orphaned:r.length,total:t.length},orphaned:r.map(o=>({id:o.id,type:o.type,size:o.size||0,cachedAt:o.cachedAt||0})),orphanedSize:a,evicted:[],threshold:this.threshold};if(y.info(`Storage: ${w(s.usage)} / ${w(s.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${i.length} required, ${r.length} orphaned (${w(a)} reclaimable)`),r.length>0)for(const o of r){const l=Date.now()-(o.cachedAt||0),g=Math.floor(l/864e5),d=Math.floor(l%864e5/36e5),f=g>0?`${g}d ago`:`${d}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${w(o.size||0)}, cached ${f})`)}if(h.storage.percent>this.threshold&&r.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(r,o)}else y.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:t,quota:s}=await navigator.storage.estimate();return{usage:t||0,quota:s||1/0}}}catch(t){y.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let n=0;for(const i of e){if(n>=t)break;s.push(i),n+=i.size||0}if(s.length===0)return[];try{const i=s.map(r=>({type:r.type,id:r.id}));await this.cache.remove(i);for(const r of s)y.info(` Evicted: ${r.type}/${r.id} (${w(r.size||0)})`);y.info(`Evicted ${s.length} files, freed ${w(n)}`)}catch(i){return y.warn("Eviction failed:",i.message),[]}return s.map(i=>({id:i.id,type:i.type,size:i.size||0,cachedAt:i.cachedAt||0}))}}const v=$("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function G(c,e,t,s){var o;const n=`${q}/widgets/${c}/${e}/${t}`,i=`<base href="${q}/media/file/">`;let r=s;s.includes("<base ")||(s.includes("<head>")?r=s.replace("<head>","<head>"+i):s.includes("<HEAD>")?r=s.replace("<HEAD>","<HEAD>"+i):r=i+s);const a="<style>img,video{object-position:center center}</style>";if(r.includes("object-position:center center")||(r.includes("</head>")?r=r.replace("</head>",a+"</head>"):r.includes("</HEAD>")&&(r=r.replace("</HEAD>",a+"</HEAD>"))),r=r.replace(/https?:\/\/[^"'\s)]+?(\/api\/v2\/player\/dependencies\/[^"'\s?)]+)(\?[^"'\s)]*)?/g,(l,g)=>g),!r.includes("xiboICTargetId")){const l=`<script>var xiboICTargetId = '${t}';<\/script>`;r.includes(i)?r=r.replace(i,i+l):r.includes("<head>")?r=r.replace("<head>","<head>"+l):r=l+r}return r=r.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),v.info("Injected base tag in widget HTML"),(o=(await fetch(`/store${q}/widgets/${c}/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:r})).body)==null||o.cancel(),v.info(`Stored widget HTML at ${n} (${r.length} bytes)`),n}export{_ as B,Y as C,X as D,D as F,K as L,O as S,R as a,E as b,G as c,N as d,I as g,S as i};
|
|
2
|
+
//# sourceMappingURL=widget-html-tM9V3Qlc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widget-html-tM9V3Qlc.js","sources":["../../../cache/src/cache.js","../../../cache/src/store-client.js","../../../cache/src/file-types.js","../../../cache/src/download-manager.js","../../../cache/src/cache-analyzer.js","../../../cache/src/widget-html.js"],"sourcesContent":["/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the storage unification, all downloads and file retrieval go through\n * the proxy's ContentStore (via StoreClient/DownloadClient). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Get cache key for a file\n * For media, uses the actual filename; for layouts, uses the ID\n */\n getCacheKey(type, id, filename = null) {\n const key = filename || id;\n return `${BASE}/cache/${type}/${key}`;\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files via proxy\n */\n async clearAll() {\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","/**\n * StoreClient — Pure REST client for ContentStore\n *\n * Communicates with the proxy's /store/* endpoints via fetch().\n * No Service Worker dependency — works immediately after construction.\n *\n * Usage:\n * const store = new StoreClient();\n * const exists = await store.has('media', '123');\n * const blob = await store.get('media', '123');\n * await store.put('widget', 'layout/1/region/2/media/3', htmlBlob, 'text/html');\n * await store.remove([{ type: 'media', id: '456' }]);\n * const files = await store.list();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('StoreClient');\n\nexport class StoreClient {\n /**\n * Check if a file exists in the store.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<boolean>}\n */\n async has(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`, { method: 'HEAD' });\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Get a file from the store as a Blob.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<Blob|null>}\n */\n async get(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`);\n if (!response.ok) {\n response.body?.cancel();\n if (response.status === 404) return null;\n throw new Error(`Failed to get file: ${response.status}`);\n }\n return await response.blob();\n } catch (error) {\n log.error('get error:', error.message);\n return null;\n }\n }\n\n /**\n * Store a file in the ContentStore.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @param {Blob|ArrayBuffer|string} body - Content to store\n * @param {string} [contentType='application/octet-stream'] - MIME type\n * @returns {Promise<boolean>} true if stored successfully\n */\n async put(type, id, body, contentType = 'application/octet-stream') {\n try {\n const response = await fetch(`/store/${type}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body,\n });\n response.body?.cancel();\n return response.ok;\n } catch (error) {\n log.error('put error:', error.message);\n return false;\n }\n }\n\n /**\n * Delete files from the store.\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async remove(files) {\n try {\n const response = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n const result = await response.json();\n return { deleted: result.deleted || 0, total: result.total || files.length };\n } catch (error) {\n log.error('remove error:', error.message);\n return { deleted: 0, total: files.length };\n }\n }\n\n /**\n * List all files in the store.\n * @returns {Promise<Array<{id: string, type: string, size: number}>>}\n */\n async list() {\n try {\n const response = await fetch('/store/list');\n const data = await response.json();\n return data.files || [];\n } catch (error) {\n log.error('list error:', error.message);\n return [];\n }\n }\n}\n","/**\n * FILE_TYPES — centralized download behavior per file type.\n *\n * Each type declares retry strategy, HEAD skip, and cache TTL.\n * Used by DownloadTask/FileDownload instead of ad-hoc isGetData checks.\n */\n\nexport const FILE_TYPES = {\n media: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n layout: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n dataset: { maxRetries: 4, retryDelayMs: 0,\n retryDelays: [15_000, 30_000, 60_000, 120_000],\n maxReenqueues: 5, reenqueueDelayMs: 60_000,\n skipHead: true, cacheTtl: 300 },\n static: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n};\n\nexport function getFileTypeConfig(type) {\n return FILE_TYPES[type] || FILE_TYPES.media;\n}\n","/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { getFileTypeConfig } from './file-types.js';\n\nconst log = createLogger('Download');\nconst DEFAULT_CONCURRENCY = 6; // Max concurrent HTTP connections (matches Chromium per-host limit)\nconst DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB chunks\nconst DEFAULT_MAX_CHUNKS_PER_FILE = 3; // Max parallel chunk downloads per file\nconst CHUNK_THRESHOLD = 100 * 1024 * 1024; // Files > 100MB get chunked\nconst URGENT_CONCURRENCY = 2; // Slots when urgent chunk is active (bandwidth focus)\nconst FETCH_TIMEOUT_MS = 600_000; // 10 minutes — 100MB chunk at ~2 Mbps\nconst HEAD_TIMEOUT_MS = 15_000; // 15 seconds for HEAD requests\n\n/**\n * Infer Content-Type from file path extension.\n * Used when we skip HEAD (size already known from RequiredFiles).\n */\nfunction inferContentType(fileInfo) {\n const path = fileInfo.path || fileInfo.code || '';\n const ext = path.split('.').pop()?.split('?')[0]?.toLowerCase();\n const types = {\n mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',\n gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',\n css: 'text/css', js: 'application/javascript',\n ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2',\n xml: 'application/xml', xlf: 'application/xml',\n };\n return types[ext] || 'application/octet-stream';\n}\n\n// Priority levels — higher number = starts first\nexport const PRIORITY = { normal: 0, layout: 1, high: 2, urgent: 3 };\n\n/**\n * BARRIER sentinel — hard gate in the download queue.\n *\n * When processQueue() encounters a BARRIER:\n * - If tasks are still in-flight above it → STOP (slots stay empty)\n * - If running === 0 → remove barrier, continue with tasks below\n *\n * Used by LayoutQueueBuilder to separate critical chunks (chunk-0, chunk-last)\n * from remaining bulk chunks. Ensures video playback can start before all\n * chunks finish downloading.\n */\nexport const BARRIER = Symbol('BARRIER');\n\n/**\n * Parse the X-Amz-Expires absolute timestamp from a signed URL.\n * Returns the expiry as a Unix timestamp (seconds), or Infinity if not found.\n */\nfunction getUrlExpiry(url) {\n try {\n const match = url.match(/X-Amz-Expires=(\\d+)/);\n return match ? parseInt(match[1], 10) : Infinity;\n } catch {\n return Infinity;\n }\n}\n\n/**\n * Check if a signed URL has expired (or will expire within a grace period).\n * @param {string} url - Signed URL with X-Amz-Expires parameter\n * @param {number} graceSeconds - Seconds before actual expiry to consider it expired (default: 30)\n * @returns {boolean}\n */\nexport function isUrlExpired(url, graceSeconds = 30) {\n const expiry = getUrlExpiry(url);\n if (expiry === Infinity) return false;\n return (Date.now() / 1000) >= (expiry - graceSeconds);\n}\n\n\n/**\n * DownloadTask - Single HTTP fetch unit\n *\n * Handles exactly one HTTP request: either a full small file GET or a single Range GET\n * for one chunk of a larger file. Includes retry logic with exponential backoff.\n */\nexport class DownloadTask {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.chunkIndex = options.chunkIndex ?? null;\n this.rangeStart = options.rangeStart ?? null;\n this.rangeEnd = options.rangeEnd ?? null;\n this.state = 'pending';\n this.blob = null;\n this._parentFile = null;\n this._priority = PRIORITY.normal;\n this._typeConfig = getFileTypeConfig(fileInfo.type);\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n async start() {\n this.state = 'downloading';\n const headers = {};\n if (this.rangeStart != null) {\n headers['Range'] = `bytes=${this.rangeStart}-${this.rangeEnd}`;\n }\n // Pass chunk metadata and MD5 via custom headers for cache-through proxy\n if (this.chunkIndex != null) {\n headers['X-Store-Chunk-Index'] = String(this.chunkIndex);\n if (this._parentFile) {\n headers['X-Store-Num-Chunks'] = String(this._parentFile.totalChunks);\n headers['X-Store-Chunk-Size'] = String(this._parentFile.options.chunkSize || 104857600);\n }\n }\n if (this.fileInfo.md5) {\n headers['X-Store-MD5'] = this.fileInfo.md5;\n }\n if (this.fileInfo.updateInterval) {\n headers['X-Cache-TTL'] = String(this.fileInfo.updateInterval);\n }\n\n const maxRetries = this._typeConfig.maxRetries;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);\n try {\n const url = this.getUrl();\n const fetchOpts = { signal: ac.signal };\n if (Object.keys(headers).length > 0) fetchOpts.headers = headers;\n const response = await fetch(url, fetchOpts);\n\n if (!response.ok && response.status !== 206) {\n throw new Error(`Fetch failed: ${response.status}`);\n }\n\n this.blob = await response.blob();\n this.state = 'complete';\n return this.blob;\n\n } catch (error) {\n const msg = ac.signal.aborted ? `Timeout after ${FETCH_TIMEOUT_MS / 1000}s` : error.message;\n if (attempt < maxRetries) {\n const delay = this._typeConfig.retryDelays?.[attempt - 1]\n ?? this._typeConfig.retryDelayMs * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${maxRetries} failed: ${msg}. Retrying in ${delay / 1000}s...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n this.state = 'failed';\n throw ac.signal.aborted ? new Error(msg) : error;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n }\n}\n\n/**\n * FileDownload - Orchestrates downloading a single file\n *\n * Does the HEAD request to determine file size, then:\n * - Small file (≤ 100MB): creates 1 DownloadTask for the full file\n * - Large file (> 100MB): creates N DownloadTasks, one per chunk\n *\n * All tasks are enqueued into the flat DownloadQueue where they compete\n * equally for HTTP connection slots with tasks from other files.\n *\n * Provides wait() that resolves when ALL tasks for this file complete.\n * Supports progressive caching via onChunkDownloaded callback.\n */\nexport class FileDownload {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.options = options;\n this.state = 'pending';\n this.tasks = [];\n this.completedChunks = 0;\n this.totalChunks = 0;\n this.totalBytes = 0;\n this.downloadedBytes = 0;\n this.onChunkDownloaded = null;\n this.skipChunks = fileInfo.skipChunks || new Set();\n this._contentType = 'application/octet-stream';\n this._chunkBlobs = new Map();\n this._runningCount = 0; // Currently running tasks for this file\n this._resolve = null;\n this._reject = null;\n this._promise = new Promise((res, rej) => {\n this._resolve = res;\n this._reject = rej;\n });\n this._promise.catch(() => {});\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n wait() {\n return this._promise;\n }\n\n /**\n * Determine file size and create DownloadTasks.\n * Uses RequiredFiles size when available (instant, no network).\n * Falls back to HEAD request only when size is unknown.\n */\n async prepare(queue) {\n try {\n this.state = 'preparing';\n const { id, type, size } = this.fileInfo;\n log.info('[FileDownload] Starting:', `${type}/${id}`);\n\n // Use declared size from RequiredFiles — no HEAD needed for queue building\n this.totalBytes = (size && size > 0) ? parseInt(size) : 0;\n this._contentType = inferContentType(this.fileInfo);\n\n // Skip HEAD for types that declare skipHead (e.g. datasets — dynamic API endpoints).\n // These generate responses server-side; HEAD triggers the full handler for nothing\n // and may fail if the CMS cache isn't warm yet. They're always small, never chunked.\n const skipHead = getFileTypeConfig(this.fileInfo.type).skipHead;\n\n if (this.totalBytes === 0 && !skipHead) {\n // No size declared — HEAD fallback (rare: only for files without CMS size)\n const url = this.getUrl();\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), HEAD_TIMEOUT_MS);\n try {\n const head = await fetch(url, { method: 'HEAD', signal: ac.signal });\n if (head.ok) {\n this.totalBytes = parseInt(head.headers.get('Content-Length') || '0');\n this._contentType = head.headers.get('Content-Type') || this._contentType;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n log.info('[FileDownload] File size:', (this.totalBytes / 1024 / 1024).toFixed(1), 'MB');\n\n const chunkSize = this.options.chunkSize || DEFAULT_CHUNK_SIZE;\n\n if (this.totalBytes > CHUNK_THRESHOLD) {\n const ranges = [];\n for (let start = 0; start < this.totalBytes; start += chunkSize) {\n ranges.push({\n start,\n end: Math.min(start + chunkSize - 1, this.totalBytes - 1),\n index: ranges.length\n });\n }\n this.totalChunks = ranges.length;\n\n const needed = ranges.filter(r => !this.skipChunks.has(r.index));\n const skippedCount = ranges.length - needed.length;\n\n for (const r of ranges) {\n if (this.skipChunks.has(r.index)) {\n this.downloadedBytes += (r.end - r.start + 1);\n }\n }\n\n if (needed.length === 0) {\n log.info('[FileDownload] All chunks already cached, nothing to download');\n this.state = 'complete';\n this._resolve(new Blob([], { type: this._contentType }));\n return;\n }\n\n if (skippedCount > 0) {\n log.info(`[FileDownload] Resuming: ${skippedCount} chunks cached, ${needed.length} to download`);\n }\n\n const isResume = skippedCount > 0;\n\n if (isResume) {\n const sorted = needed.sort((a, b) => a.index - b.index);\n for (const r of sorted) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = PRIORITY.normal;\n this.tasks.push(task);\n }\n } else {\n for (const r of needed) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = (r.index === 0 || r.index === ranges.length - 1) ? PRIORITY.high : PRIORITY.normal;\n this.tasks.push(task);\n }\n }\n\n const highCount = this.tasks.filter(t => t._priority >= PRIORITY.high).length;\n log.info(`[FileDownload] ${type}/${id}: ${this.tasks.length} chunks` +\n (highCount > 0 ? ` (${highCount} priority)` : '') +\n (isResume ? ' (resume)' : ''));\n\n } else {\n this.totalChunks = 1;\n const task = new DownloadTask(this.fileInfo, {});\n task._parentFile = this;\n this.tasks.push(task);\n }\n\n queue.enqueueChunkTasks(this.tasks);\n this.state = 'downloading';\n\n } catch (error) {\n log.error('[FileDownload] Prepare failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n }\n\n async onTaskComplete(task) {\n this.completedChunks++;\n this.downloadedBytes += task.blob.size;\n\n if (task.chunkIndex != null) {\n this._chunkBlobs.set(task.chunkIndex, task.blob);\n }\n\n if (this.options.onProgress) {\n this.options.onProgress(this.downloadedBytes, this.totalBytes);\n }\n\n // Fire progressive chunk callback\n if (this.onChunkDownloaded && task.chunkIndex != null) {\n try {\n await this.onChunkDownloaded(task.chunkIndex, task.blob, this.totalChunks);\n } catch (e) {\n log.warn('[FileDownload] onChunkDownloaded callback error:', e);\n }\n }\n\n if (this.completedChunks === this.tasks.length && this.state !== 'complete') {\n this.state = 'complete';\n const { type, id } = this.fileInfo;\n\n if (task.chunkIndex == null) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${task.blob.size} bytes)`);\n this._resolve(task.blob);\n } else if (this.onChunkDownloaded) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(progressive, ${this.totalChunks} chunks)`);\n this._resolve(new Blob([], { type: this._contentType }));\n } else {\n const ordered = [];\n for (let i = 0; i < this.totalChunks; i++) {\n const blob = this._chunkBlobs.get(i);\n if (blob) ordered.push(blob);\n }\n const assembled = new Blob(ordered, { type: this._contentType });\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${assembled.size} bytes, reassembled)`);\n this._resolve(assembled);\n }\n\n this._chunkBlobs.clear();\n }\n }\n\n onTaskFailed(task, error) {\n if (this.state === 'complete' || this.state === 'failed') return;\n\n // URL expiration is transient — drop this task, don't fail the file.\n // Already-downloaded chunks are safe in cache. Next collection cycle\n // provides fresh URLs and the resume logic (skipChunks) fills the gaps.\n if (error.message?.includes('URL expired')) {\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.warn(`[FileDownload] URL expired, dropping${chunkLabel}:`, `${this.fileInfo.type}/${this.fileInfo.id}`);\n this.tasks = this.tasks.filter(t => t !== task);\n // If all remaining tasks completed, resolve as partial\n if (this.tasks.length === 0 || this.completedChunks >= this.tasks.length) {\n this.state = 'complete';\n this._urlExpired = true;\n this._resolve(new Blob([], { type: this._contentType }));\n }\n return;\n }\n\n log.error('[FileDownload] Failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n}\n\n/**\n * LayoutTaskBuilder — Smart builder that produces a sorted, barrier-embedded\n * task list for a single layout.\n *\n * Usage:\n * const builder = new LayoutTaskBuilder(queue);\n * builder.addFile(fileInfo);\n * const orderedTasks = await builder.build();\n * queue.enqueueOrderedTasks(orderedTasks);\n *\n * The builder runs HEAD requests (throttled), collects the resulting\n * DownloadTasks, sorts them optimally, and embeds BARRIERs between\n * critical chunks (chunk-0, chunk-last) and bulk chunks.\n *\n * Duck-typing: implements enqueueChunkTasks() so FileDownload.prepare()\n * works unchanged — it just collects tasks instead of processing them.\n */\nexport class LayoutTaskBuilder {\n constructor(queue) {\n this.queue = queue; // Main DownloadQueue (for dedup via active map)\n this._filesToPrepare = []; // FileDownloads needing HEAD requests\n this._tasks = []; // Collected DownloadTasks (from prepare callbacks)\n this._maxPreparing = 2; // HEAD request throttle\n }\n\n /**\n * Register a file. Uses queue.active for dedup/URL refresh.\n * Does NOT trigger prepare — that happens in build().\n */\n addFile(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.queue.active.has(key)) {\n const existing = this.queue.active.get(key);\n // URL refresh (same logic as queue.enqueue)\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.queue.chunkSize,\n calculateMD5: this.queue.calculateMD5,\n onProgress: this.queue.onProgress\n });\n\n this.queue.active.set(key, file);\n this._filesToPrepare.push(file);\n return file;\n }\n\n /**\n * Duck-type interface for FileDownload.prepare().\n * Collects tasks instead of processing them.\n */\n enqueueChunkTasks(tasks) {\n this._tasks.push(...tasks);\n }\n\n /**\n * Run all HEAD requests (throttled) and return sorted tasks with barriers.\n */\n async build() {\n await this._prepareAll();\n return this._sortWithBarriers();\n }\n\n async _prepareAll() {\n await new Promise((resolve) => {\n let running = 0;\n let idx = 0;\n const next = () => {\n while (running < this._maxPreparing && idx < this._filesToPrepare.length) {\n const file = this._filesToPrepare[idx++];\n running++;\n file.prepare(this).finally(() => {\n running--;\n if (idx >= this._filesToPrepare.length && running === 0) {\n resolve();\n } else {\n next();\n }\n });\n }\n };\n if (this._filesToPrepare.length === 0) resolve();\n else next();\n });\n }\n\n _sortWithBarriers() {\n const nonChunked = [];\n const chunk0s = [];\n const chunkLasts = [];\n const remaining = [];\n\n for (const t of this._tasks) {\n if (t.chunkIndex == null) {\n nonChunked.push(t);\n } else if (t.chunkIndex === 0) {\n chunk0s.push(t);\n } else {\n const total = t._parentFile?.totalChunks || 0;\n if (total > 1 && t.chunkIndex === total - 1) {\n chunkLasts.push(t);\n } else {\n remaining.push(t);\n }\n }\n }\n\n nonChunked.sort((a, b) => (a._parentFile?.totalBytes || 0) - (b._parentFile?.totalBytes || 0));\n remaining.sort((a, b) => a.chunkIndex - b.chunkIndex);\n\n // Build: small files + critical chunks → BARRIER → bulk chunks\n const result = [...nonChunked, ...chunk0s, ...chunkLasts];\n if (remaining.length > 0) {\n result.push(BARRIER, ...remaining);\n }\n return result;\n }\n}\n\n/**\n * DownloadQueue - Flat queue with per-file and global concurrency limits\n *\n * Global concurrency limit (e.g., 6) controls total HTTP connections.\n * Per-file chunk limit (e.g., 2) prevents one large file from hogging all\n * connections, ensuring bandwidth per chunk is high and chunk 0 arrives fast.\n * HEAD requests are throttled to avoid flooding browser connection pool.\n */\nexport class DownloadQueue {\n constructor(options = {}) {\n this.concurrency = options.concurrency || DEFAULT_CONCURRENCY;\n this.chunkSize = options.chunkSize || DEFAULT_CHUNK_SIZE;\n this.maxChunksPerFile = options.chunksPerFile || DEFAULT_MAX_CHUNKS_PER_FILE;\n this.calculateMD5 = options.calculateMD5;\n this.onProgress = options.onProgress;\n\n this.queue = []; // DownloadTask[] — flat queue of chunk/file tasks\n this.active = new Map(); // stableKey → FileDownload\n this._activeTasks = []; // DownloadTask[] — currently in-flight tasks\n this.running = 0;\n\n // HEAD request throttling: prevents prepare() from flooding browser connections\n this._prepareQueue = [];\n this._preparingCount = 0;\n this._maxPreparing = 2; // Max concurrent HEAD requests\n\n // When paused, processQueue() is a no-op (used during barrier setup)\n this.paused = false;\n\n // Track getData re-enqueue timers so clear() can cancel them\n this._reenqueueTimers = new Set();\n }\n\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n prioritize(fileType, fileId) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] Not found:', key);\n return false;\n }\n\n let boosted = 0;\n for (const t of this.queue) {\n if (t._parentFile === file && t._priority < PRIORITY.high) {\n t._priority = PRIORITY.high;\n boosted++;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Prioritized:', key, `(${boosted} tasks boosted)`);\n return true;\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Layout files prioritized:', idSet.size, 'files,', boosted, 'tasks boosted to', priority);\n }\n\n /**\n * Emergency priority for a specific streaming chunk.\n * Called by the Service Worker when a video is stalled waiting for chunk N.\n * Sets urgent priority → queue re-sorts → processQueue() limits concurrency.\n */\n urgentChunk(fileType, fileId, chunkIndex) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] urgentChunk: file not active:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Already in-flight — nothing to do\n const isActive = this._activeTasks.some(\n t => t._parentFile === file && t.chunkIndex === chunkIndex && t.state === 'downloading'\n );\n if (isActive) {\n // Mark the in-flight task as urgent so processQueue() limits concurrency\n const activeTask = this._activeTasks.find(\n t => t._parentFile === file && t.chunkIndex === chunkIndex\n );\n if (activeTask && activeTask._priority < PRIORITY.urgent) {\n activeTask._priority = PRIORITY.urgent;\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (already in-flight, limiting slots)`);\n // Don't call processQueue() — can't stop in-flight tasks, but next\n // processQueue() call (when any task completes) will see hasUrgent\n // and limit new starts to URGENT_CONCURRENCY.\n return true;\n }\n log.info('[DownloadQueue] urgentChunk: already urgent:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Find task in queue (may be past a barrier)\n const idx = this.queue.findIndex(\n t => t !== BARRIER && t._parentFile === file && t.chunkIndex === chunkIndex\n );\n\n if (idx === -1) {\n log.info('[DownloadQueue] urgentChunk: chunk not in queue:', key, 'chunk', chunkIndex);\n return false;\n }\n\n const task = this.queue.splice(idx, 1)[0];\n task._priority = PRIORITY.urgent;\n // Move to front of queue (past any barriers)\n this.queue.unshift(task);\n\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (moved to front)`);\n this.processQueue();\n return true;\n }\n\n /**\n * Process queue — barrier-aware loop.\n *\n * Supports two modes:\n * 1. Priority-sorted (legacy): queue sorted by priority, urgent reduces concurrency\n * 2. Barrier-ordered: queue contains BARRIER sentinels that act as hard gates\n *\n * BARRIER behavior:\n * - When processQueue() hits a BARRIER and running > 0 → STOP (slots stay empty)\n * - When running === 0 → remove barrier, continue with tasks below\n * - Tasks are never reordered past a BARRIER (except urgentChunk which bypasses)\n *\n * Urgent mode: when any task has PRIORITY.urgent, concurrency drops to\n * URGENT_CONCURRENCY so the stalled chunk gets maximum bandwidth.\n */\n processQueue() {\n if (this.paused) return;\n\n // Determine effective concurrency and minimum priority to start\n const hasUrgent = this.queue.some(t => t !== BARRIER && t._priority >= PRIORITY.urgent) ||\n this._activeTasks?.some(t => t._priority >= PRIORITY.urgent && t.state === 'downloading');\n const maxSlots = hasUrgent ? URGENT_CONCURRENCY : this.concurrency;\n const minPriority = hasUrgent ? PRIORITY.urgent : 0; // Urgent = only urgent tasks run\n\n // Fill slots from front of queue\n while (this.running < maxSlots && this.queue.length > 0) {\n const next = this.queue[0];\n\n // Hit a BARRIER — hard gate\n if (next === BARRIER) {\n if (this.running > 0) {\n break; // In-flight tasks still running — slots stay empty\n }\n // All above-barrier tasks done → raise barrier, continue\n this.queue.shift();\n continue;\n }\n\n // Per-file limit: skip to next eligible task (but don't cross barrier)\n if (next._priority < minPriority || !this._canStartTask(next)) {\n let found = false;\n for (let i = 1; i < this.queue.length; i++) {\n if (this.queue[i] === BARRIER) break; // Don't look past barrier\n const task = this.queue[i];\n if (task._priority >= minPriority && this._canStartTask(task)) {\n this.queue.splice(i, 1);\n this._startTask(task);\n found = true;\n break;\n }\n }\n if (!found) break;\n continue;\n }\n\n this.queue.shift();\n this._startTask(next);\n }\n\n if (this.queue.length === 0 && this.running === 0) {\n log.info('[DownloadQueue] All downloads complete');\n }\n }\n\n /**\n * Per-file concurrency check. Priority sorting decides order,\n * this just prevents one file from hogging all connections.\n */\n _canStartTask(task) {\n return task._parentFile._runningCount < this.maxChunksPerFile;\n }\n\n _startTask(task) {\n this.running++;\n task._parentFile._runningCount++;\n this._activeTasks.push(task);\n const key = `${task.fileInfo.type}/${task.fileInfo.id}`;\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.info(`[DownloadQueue] Starting: ${key}${chunkLabel} (${this.running}/${this.concurrency} active)`);\n\n task.start()\n .then(() => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n log.info(`[DownloadQueue] Fetched: ${key}${chunkLabel} (${this.running} active, ${this.queue.length} pending)`);\n this.processQueue();\n return task._parentFile.onTaskComplete(task);\n })\n .catch(err => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n\n // Re-enqueueable types (e.g. datasets): defer re-enqueue instead of permanent failure.\n // CMS \"cache not ready\" resolves when the XTR task runs (30-120s).\n const { maxReenqueues, reenqueueDelayMs } = task._typeConfig;\n if (maxReenqueues > 0) {\n task._reenqueueCount = (task._reenqueueCount || 0) + 1;\n if (task._reenqueueCount > maxReenqueues) {\n log.error(`[DownloadQueue] ${key} exceeded ${maxReenqueues} re-enqueues, failing permanently`);\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n return;\n }\n log.warn(`[DownloadQueue] ${key} failed all retries (attempt ${task._reenqueueCount}/${maxReenqueues}), scheduling re-enqueue in ${reenqueueDelayMs / 1000}s`);\n const timerId = setTimeout(() => {\n this._reenqueueTimers.delete(timerId);\n task.state = 'pending';\n task._parentFile.state = 'downloading';\n this.queue.push(task);\n log.info(`[DownloadQueue] ${key} re-enqueued for retry`);\n this.processQueue();\n }, reenqueueDelayMs);\n this._reenqueueTimers.add(timerId);\n this.processQueue();\n return;\n }\n\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n /**\n * Wait for all queued prepare (HEAD) operations to finish.\n * Returns when the prepare queue is drained and all FileDownloads have\n * either created their tasks or failed.\n */\n awaitAllPrepared() {\n return new Promise((resolve) => {\n const check = () => {\n if (this._preparingCount === 0 && this._prepareQueue.length === 0) {\n resolve();\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n // Skip completed/failed — they stay in active until removeCompleted() runs\n if (file.state === 'complete' || file.state === 'failed') continue;\n progress[key] = {\n downloaded: file.downloadedBytes,\n total: file.totalBytes,\n percent: file.totalBytes > 0 ? (file.downloadedBytes / file.totalBytes * 100).toFixed(1) : 0,\n state: file.state\n };\n }\n return progress;\n }\n\n clear() {\n this.queue = [];\n this.active.clear();\n this.running = 0;\n this._prepareQueue = [];\n this._preparingCount = 0;\n // Cancel any pending getData re-enqueue timers\n for (const id of this._reenqueueTimers) clearTimeout(id);\n this._reenqueueTimers.clear();\n }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n /**\n * Enqueue a file for layout-grouped downloading.\n * Layout grouping is now handled externally by LayoutTaskBuilder.\n * @param {Object} fileInfo - File info\n * @returns {FileDownload}\n */\n enqueueForLayout(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through StoreClient (REST to proxy) — no IndexedDB,\n * no direct Cache API access.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheAnalyzer');\n\n/**\n * Format bytes into human-readable string (e.g. 1.2 GB, 350 MB)\n */\nfunction formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n if (!Number.isFinite(bytes)) return '∞';\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n const value = bytes / Math.pow(1024, i);\n return `${value.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;\n}\n\nexport class CacheAnalyzer {\n /**\n * @param {import('./store-client.js').StoreClient} cache - StoreClient instance\n * @param {object} [options]\n * @param {number} [options.threshold=80] - Storage usage % above which eviction triggers\n */\n constructor(cache, { threshold = 80 } = {}) {\n this.cache = cache;\n this.threshold = threshold;\n }\n\n /**\n * Analyze cache health by comparing cached files against required files.\n *\n * @param {Array<{id: string, type: string}>} requiredFiles - Current RequiredFiles from CMS\n * @returns {Promise<object>} Analysis report\n */\n async analyze(requiredFiles) {\n const cachedFiles = await this.cache.list();\n const storage = await this._getStorageEstimate();\n\n // Build set of required file IDs (as strings for consistent comparison)\n const requiredIds = new Set(requiredFiles.map(f => String(f.id)));\n\n // Categorize cached files\n const required = [];\n const orphaned = [];\n\n for (const file of cachedFiles) {\n if (requiredIds.has(String(file.id))) {\n required.push(file);\n } else if (file.type === 'widget') {\n // Widget HTML IDs are \"layoutId/regionId/widgetId\" — check parent layout\n const parentLayoutId = String(file.id).split('/')[0];\n if (requiredIds.has(parentLayoutId)) {\n required.push(file);\n } else {\n orphaned.push(file);\n }\n } else if (file.type === 'static') {\n // Static files (bundle.min.js, fonts.css, fonts, images) are shared widget\n // dependencies — never orphan them, they're referenced from widget HTML\n required.push(file);\n } else {\n orphaned.push(file);\n }\n }\n\n // Sort orphaned by cachedAt ascending (oldest first — evict these first)\n orphaned.sort((a, b) => (a.cachedAt || 0) - (b.cachedAt || 0));\n\n const orphanedSize = orphaned.reduce((sum, f) => sum + (f.size || 0), 0);\n\n const report = {\n timestamp: Date.now(),\n storage: {\n usage: storage.usage,\n quota: storage.quota,\n percent: storage.quota > 0 ? Math.round((storage.usage / storage.quota) * 100) : 0,\n },\n files: {\n required: required.length,\n orphaned: orphaned.length,\n total: cachedFiles.length,\n },\n orphaned: orphaned.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n })),\n orphanedSize,\n evicted: [],\n threshold: this.threshold,\n };\n\n // Log summary\n log.info(`Storage: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)} (${report.storage.percent}%)`);\n log.info(`Cache: ${required.length} required, ${orphaned.length} orphaned (${formatBytes(orphanedSize)} reclaimable)`);\n\n if (orphaned.length > 0) {\n for (const f of orphaned) {\n const age = Date.now() - (f.cachedAt || 0);\n const days = Math.floor(age / 86400000);\n const hours = Math.floor((age % 86400000) / 3600000);\n const ageStr = days > 0 ? `${days}d ago` : `${hours}h ago`;\n log.info(` Orphaned: ${f.type}/${f.id} (${formatBytes(f.size || 0)}, cached ${ageStr})`);\n }\n }\n\n // Evict only when storage exceeds threshold\n if (report.storage.percent > this.threshold && orphaned.length > 0) {\n log.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);\n const targetBytes = storage.usage - (storage.quota * this.threshold / 100);\n report.evicted = await this._evict(orphaned, targetBytes);\n } else {\n log.info(`No eviction needed (threshold: ${this.threshold}%)`);\n }\n\n return report;\n }\n\n /**\n * Get storage estimate from the browser.\n * Falls back to { usage: 0, quota: Infinity } in environments without the API.\n */\n async _getStorageEstimate() {\n try {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n const { usage, quota } = await navigator.storage.estimate();\n return { usage: usage || 0, quota: quota || Infinity };\n }\n } catch (e) {\n log.warn('Storage estimate unavailable:', e.message);\n }\n return { usage: 0, quota: Infinity };\n }\n\n /**\n * Evict orphaned files (oldest first) until targetBytes are freed.\n * Delegates deletion to StoreClient.remove() which routes to proxy.\n *\n * @param {Array} orphanedFiles - Files to evict, sorted oldest-first\n * @param {number} targetBytes - Bytes to free\n * @returns {Promise<Array>} Evicted file records\n */\n async _evict(orphanedFiles, targetBytes) {\n const toEvict = [];\n let plannedBytes = 0;\n\n for (const file of orphanedFiles) {\n if (plannedBytes >= targetBytes) break;\n toEvict.push(file);\n plannedBytes += file.size || 0;\n }\n\n if (toEvict.length === 0) return [];\n\n try {\n const filesToDelete = toEvict.map(f => ({ type: f.type, id: f.id }));\n await this.cache.remove(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","/**\n * Widget HTML processing — preprocesses widget HTML and stores via REST\n *\n * Handles:\n * - <base> tag injection for relative path resolution (CMS mirror paths)\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * URL rewriting is no longer needed — the CMS serves CSS with relative paths\n * (/api/v2/player/dependencies/font.otf), and the <base> tag resolves widget\n * media references via mirror routes. Zero translation, zero regex.\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Stores content via PUT /store/... — no Cache API needed.\n */\n\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\n/**\n * Store widget HTML in ContentStore for iframe loading.\n * Stored at mirror path /api/v2/player/widgets/{L}/{R}/{M} — same URL the\n * CMS serves from, so iframes load directly from Express mirror routes.\n *\n * @param {string} layoutId - Layout ID\n * @param {string} regionId - Region ID\n * @param {string} mediaId - Media ID\n * @param {string} html - Widget HTML content\n * @returns {Promise<string>} Cache key URL (absolute path for iframe src)\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`;\n\n // Inject <base> tag — resolves relative media refs (e.g. \"42\") to mirror route\n const baseTag = `<base href=\"${PLAYER_API}/media/file/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag (skip if already present)\n if (!html.includes('<base ')) {\n if (html.includes('<head>')) {\n modifiedHtml = html.replace('<head>', '<head>' + baseTag);\n } else if (html.includes('<HEAD>')) {\n modifiedHtml = html.replace('<HEAD>', '<HEAD>' + baseTag);\n } else {\n modifiedHtml = baseTag + html;\n }\n }\n\n // Inject CSS default for object-position to suppress CMS template warning\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Rewrite dependency URLs to local mirror paths. CMS sends absolute URLs\n // like https://cms.example.com/api/v2/player/dependencies/bundle.min.js\n // which fail due to CORS/auth. Replace with local /api/v2/player/dependencies/...\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\"'\\s)]+?(\\/api\\/v2\\/player\\/dependencies\\/[^\"'\\s?)]+)(\\?[^\"'\\s)]*)?/g,\n (_, path) => path\n );\n\n // Inject xiboICTargetId — XIC library reads this global before its IIFE runs\n // to set _lib.targetId, which is included in every IC HTTP request as {id: ...}\n if (!modifiedHtml.includes('xiboICTargetId')) {\n const targetIdScript = `<script>var xiboICTargetId = '${mediaId}';</script>`;\n if (modifiedHtml.includes(baseTag)) {\n modifiedHtml = modifiedHtml.replace(baseTag, baseTag + targetIdScript);\n } else if (modifiedHtml.includes('<head>')) {\n modifiedHtml = modifiedHtml.replace('<head>', '<head>' + targetIdScript);\n } else {\n modifiedHtml = targetIdScript + modifiedHtml;\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag in widget HTML');\n\n // Store widget HTML — deps are already downloaded by the pipeline\n const putResp = await fetch(`/store${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n body: modifiedHtml,\n });\n putResp.body?.cancel();\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n return cacheKey;\n}\n"],"names":["log","createLogger","BASE","CacheManager","type","id","filename","mediaId","layoutId","key","lid","orphaned","layouts","cacheManager","StoreClient","response","_a","error","body","contentType","files","result","FILE_TYPES","getFileTypeConfig","DEFAULT_CONCURRENCY","DEFAULT_CHUNK_SIZE","DEFAULT_MAX_CHUNKS_PER_FILE","CHUNK_THRESHOLD","URGENT_CONCURRENCY","FETCH_TIMEOUT_MS","HEAD_TIMEOUT_MS","inferContentType","fileInfo","ext","_b","PRIORITY","BARRIER","getUrlExpiry","url","match","isUrlExpired","graceSeconds","expiry","DownloadTask","options","headers","maxRetries","attempt","ac","timer","fetchOpts","msg","delay","chunkLabel","resolve","FileDownload","res","rej","queue","size","skipHead","head","chunkSize","ranges","start","needed","r","skippedCount","isResume","sorted","a","b","task","highCount","t","e","ordered","i","blob","assembled","LayoutTaskBuilder","DownloadQueue","existing","oldExpiry","file","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","total","items","taskCount","barrierCount","item","fileType","fileId","boosted","fileIds","priority","idSet","matchValue","_c","_d","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","err","maxReenqueues","reenqueueDelayMs","timerId","check","progress","DownloadManager","formatBytes","bytes","units","CacheAnalyzer","cache","threshold","requiredFiles","cachedFiles","storage","requiredIds","f","required","parentLayoutId","orphanedSize","sum","report","age","days","hours","ageStr","targetBytes","usage","quota","orphanedFiles","toEvict","plannedBytes","filesToDelete","cacheWidgetHtml","regionId","html","cacheKey","PLAYER_API","baseTag","modifiedHtml","cssFixTag","_","path","targetIdScript"],"mappings":"mEAWA,MAAMA,EAAMC,EAAa,OAAO,EAG1BC,EAAQ,OAAO,OAAW,KAC5B,OAAO,SAAS,SAAS,QAAQ,WAAY,EAAE,EAAE,QAAQ,MAAO,EAAE,GAAK,cAGpE,MAAMC,CAAa,CACxB,aAAc,CAEZ,KAAK,WAAa,IAAI,GACxB,CAMA,YAAYC,EAAMC,EAAIC,EAAW,KAAM,CAErC,MAAO,GAAGJ,CAAI,UAAUE,CAAI,IADhBE,GAAYD,CACW,EACrC,CAOA,aAAaE,EAASC,EAAU,CAC9B,MAAMC,EAAM,OAAOF,CAAO,EACrB,KAAK,WAAW,IAAIE,CAAG,GAC1B,KAAK,WAAW,IAAIA,EAAK,IAAI,GAAK,EAEpC,KAAK,WAAW,IAAIA,CAAG,EAAE,IAAI,OAAOD,CAAQ,CAAC,CAC/C,CAOA,uBAAuBA,EAAU,CAC/B,MAAME,EAAM,OAAOF,CAAQ,EACrBG,EAAW,CAAA,EAEjB,SAAW,CAACJ,EAASK,CAAO,IAAK,KAAK,WACpCA,EAAQ,OAAOF,CAAG,EACdE,EAAQ,OAAS,IACnB,KA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Aa,QAAQ,UAAWC,EAAY,SAAS,EAC3DD,EAAa,SAAS,SAAS,IACxCA,EAAeA,EAAa,QAAQ,UAAWC,EAAY,SAAS,IAOxED,EAAeA,EAAa,QAC1B,oFACA,CAACE,EAAGC,IAASA,CACjB,EAIM,CAACH,EAAa,SAAS,gBAAgB,EAAG,CAC5C,MAAMI,EAAiB,iCAAiCtJ,CAAO,eAC3DkJ,EAAa,SAASD,CAAO,EAC/BC,EAAeA,EAAa,QAAQD,EAASA,EAAUK,CAAc,EAC5DJ,EAAa,SAAS,QAAQ,EACvCA,EAAeA,EAAa,QAAQ,SAAU,SAAWI,CAAc,EAEvEJ,EAAeI,EAAiBJ,CAEpC,CAGA,OAAAA,EAAeA,EAAa,QAC1B,+CACA,iBAAiBvJ,CAAI,MACzB,EAEEF,EAAI,KAAK,kCAAkC,GAQ3CgB,GALgB,MAAM,MAAM,SAASuI,CAAU,YAAY/I,CAAQ,IAAI4I,CAAQ,IAAI7I,CAAO,GAAI,CAC5F,OAAQ,MACR,QAAS,CAAE,eAAgB,0BAA0B,EACrD,KAAMkJ,CACV,CAAG,GACO,OAAR,MAAAzI,EAAc,SACdhB,EAAI,KAAK,yBAAyBsJ,CAAQ,KAAKG,EAAa,MAAM,SAAS,EAEpEH,CACT"}
|
package/dist/index.html
CHANGED
|
@@ -94,10 +94,10 @@
|
|
|
94
94
|
height: 100%;
|
|
95
95
|
}
|
|
96
96
|
</style>
|
|
97
|
-
<script type="module" crossorigin src="./assets/main-
|
|
97
|
+
<script type="module" crossorigin src="./assets/main-DGfrcKkR.js"></script>
|
|
98
98
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
99
|
-
<link rel="modulepreload" crossorigin href="./assets/index-
|
|
100
|
-
<link rel="modulepreload" crossorigin href="./assets/widget-html-
|
|
99
|
+
<link rel="modulepreload" crossorigin href="./assets/index-C122u38X.js">
|
|
100
|
+
<link rel="modulepreload" crossorigin href="./assets/widget-html-tM9V3Qlc.js">
|
|
101
101
|
</head>
|
|
102
102
|
<body>
|
|
103
103
|
<!-- Status overlay -->
|
package/dist/setup.html
CHANGED
|
@@ -287,10 +287,10 @@
|
|
|
287
287
|
color: #444;
|
|
288
288
|
}
|
|
289
289
|
</style>
|
|
290
|
-
<script type="module" crossorigin src="./assets/setup-
|
|
290
|
+
<script type="module" crossorigin src="./assets/setup-D3frvQ4W.js"></script>
|
|
291
291
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
292
|
-
<link rel="modulepreload" crossorigin href="./assets/index-
|
|
293
|
-
<link rel="modulepreload" crossorigin href="./assets/
|
|
292
|
+
<link rel="modulepreload" crossorigin href="./assets/index-C122u38X.js">
|
|
293
|
+
<link rel="modulepreload" crossorigin href="./assets/protocol-detector-bDP-d2EL.js">
|
|
294
294
|
</head>
|
|
295
295
|
<body>
|
|
296
296
|
<div class="container">
|
package/dist/sw-pwa.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{D as C}from"./assets/widget-html-
|
|
1
|
+
import{D as C}from"./assets/widget-html-tM9V3Qlc.js";import{VERSION as S}from"./assets/index-BS70-4bE.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-BqCdX6OJ.js";import{createLogger as E}from"./assets/index-C122u38X.js";const o="2026-03-05T01:44:53.105Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
|
|
2
2
|
//# sourceMappingURL=sw-pwa.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xiboplayer/pwa",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "Lightweight PWA Xibo Player with RendererLite",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -10,18 +10,18 @@
|
|
|
10
10
|
"html2canvas": "^1.4.1",
|
|
11
11
|
"nanoevents": "^9.0.0",
|
|
12
12
|
"xml2js": "^0.6.2",
|
|
13
|
-
"@xiboplayer/
|
|
14
|
-
"@xiboplayer/
|
|
15
|
-
"@xiboplayer/
|
|
16
|
-
"@xiboplayer/
|
|
17
|
-
"@xiboplayer/
|
|
18
|
-
"@xiboplayer/
|
|
19
|
-
"@xiboplayer/stats": "0.6.
|
|
20
|
-
"@xiboplayer/
|
|
21
|
-
"@xiboplayer/
|
|
22
|
-
"@xiboplayer/
|
|
23
|
-
"@xiboplayer/
|
|
24
|
-
"@xiboplayer/xmr": "0.6.
|
|
13
|
+
"@xiboplayer/crypto": "0.6.3",
|
|
14
|
+
"@xiboplayer/renderer": "0.6.3",
|
|
15
|
+
"@xiboplayer/schedule": "0.6.3",
|
|
16
|
+
"@xiboplayer/cache": "0.6.3",
|
|
17
|
+
"@xiboplayer/core": "0.6.3",
|
|
18
|
+
"@xiboplayer/settings": "0.6.3",
|
|
19
|
+
"@xiboplayer/stats": "0.6.3",
|
|
20
|
+
"@xiboplayer/sw": "0.6.3",
|
|
21
|
+
"@xiboplayer/sync": "0.6.3",
|
|
22
|
+
"@xiboplayer/xmds": "0.6.3",
|
|
23
|
+
"@xiboplayer/utils": "0.6.3",
|
|
24
|
+
"@xiboplayer/xmr": "0.6.3"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/node": "^22.10.5",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{createLogger as w}from"./index-leM889oV.js";const m="0.6.1",$={version:m},c=w("@xiboplayer/stats"),D="xibo-player-stats",v=1,b="stats";class L{constructor(){this.db=null,this.inProgressStats=new Map}async init(){if(this.db){c.debug("Stats collector already initialized");return}return new Promise((r,t)=>{if(typeof indexedDB>"u"){const e=new Error("IndexedDB not available");c.error("IndexedDB not available - stats will not be persisted"),t(e);return}const s=indexedDB.open(D,v);s.onerror=()=>{const e=new Error(`Failed to open IndexedDB: ${s.error}`);c.error("Failed to open stats database:",s.error),t(e)},s.onsuccess=()=>{this.db=s.result,c.info("Stats database initialized"),r()},s.onupgradeneeded=e=>{const n=e.target.result;n.objectStoreNames.contains(b)||(n.createObjectStore(b,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),c.info("Stats store created"))}})}async startLayout(r,t,s){if(!this.db){c.warn("Stats database not initialized");return}if((s==null?void 0:s.enableStat)===!1){c.debug(`Stats disabled for layout ${r} (enableStat=false)`);return}const e=`layout-${r}`;if(this.inProgressStats.has(e)){const o=this.inProgressStats.get(e);o.end=new Date,o.duration=Math.floor((o.end-o.start)/1e3),await this._saveStatSplit(o),this.inProgressStats.delete(e),c.debug(`Layout ${r} replay - ended previous cycle (${o.duration}s)`)}const n={type:"layout",layoutId:r,scheduleId:t,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(e,n),c.debug(`Started tracking layout ${r} (schedule ${t})`)}async endLayout(r,t){if(!this.db){c.warn("Stats database not initialized");return}const s=`layout-${r}`,e=this.inProgressStats.get(s);if(!e){c.debug(`Layout ${r} not found in progress (may have been ended by replay)`);return}e.end=new Date,e.duration=Math.floor((e.end-e.start)/1e3);try{await this._saveStatSplit(e),this.inProgressStats.delete(s),c.debug(`Ended tracking layout ${r} (${e.duration}s)`)}catch(n){throw c.error(`Failed to save layout stat ${r}:`,n),n}}async startWidget(r,t,s,e,n){if(!this.db){c.warn("Stats database not initialized");return}if((n==null?void 0:n.enableStat)===!1){c.debug(`Stats disabled for widget ${r} (enableStat=false)`);return}const o=`media-${r}-${t}`;if(this.inProgressStats.has(o)){const d=this.inProgressStats.get(o);d.end=new Date,d.duration=Math.floor((d.end-d.start)/1e3),await this._saveStatSplit(d),this.inProgressStats.delete(o),c.debug(`Widget ${r} replay - ended previous cycle (${d.duration}s)`)}const a={type:"media",mediaId:r,widgetId:e||null,layoutId:t,scheduleId:s,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(o,a),c.debug(`Started tracking widget ${r} in layout ${t}`)}async endWidget(r,t,s){if(!this.db){c.warn("Stats database not initialized");return}const e=`media-${r}-${t}`,n=this.inProgressStats.get(e);if(!n){c.debug(`Widget ${r} not found in progress (expected during layout transitions)`);return}n.end=new Date,n.duration=Math.floor((n.end-n.start)/1e3);try{await this._saveStatSplit(n),this.inProgressStats.delete(e),c.debug(`Ended tracking widget ${r} (${n.duration}s)`)}catch(o){throw c.error(`Failed to save widget stat ${r}:`,o),o}}async recordEvent(r,t,s,e){if(!this.db){c.warn("Stats database not initialized");return}const n=new Date,o={type:"event",tag:r,layoutId:t,widgetId:s,scheduleId:e,start:n,end:n,duration:0,count:1,submitted:0};try{await this._saveStat(o),c.debug(`Recorded event '${r}' for widget ${s} in layout ${t}`)}catch(a){throw c.error(`Failed to record event '${r}':`,a),a}}async getStatsForSubmission(r=50){return this.db?new Promise((t,s)=>{const a=this.db.transaction([b],"readonly").objectStore(b).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(d.push(h.value),h.continue()):(c.debug(`Retrieved ${d.length} unsubmitted stats`),t(d))},a.onerror=()=>{c.error("Failed to retrieve stats:",a.error),s(new Error(`Failed to retrieve stats: ${a.error}`))}}):(c.warn("Stats database not initialized"),[])}async clearSubmittedStats(r){if(!this.db){c.warn("Stats database not initialized");return}if(!(!r||r.length===0))return new Promise((t,s)=>{const e=this.db.transaction([b],"readwrite"),n=e.objectStore(b);let o=0;r.forEach(a=>{if(a.id){const d=n.delete(a.id);d.onsuccess=()=>{o++},d.onerror=()=>{c.error(`Failed to delete stat ${a.id}:`,d.error)}}}),e.oncomplete=()=>{c.debug(`Deleted ${o} submitted stats`),t()},e.onerror=()=>{c.error("Failed to delete submitted stats:",e.error),s(new Error(`Failed to delete stats: ${e.error}`))}})}async getAggregatedStatsForSubmission(r=50){const t=await this.getStatsForSubmission(r);if(t.length===0)return[];const s=new Map;for(const e of t){const n=e.start instanceof Date?e.start.toISOString().slice(0,13):new Date(e.start).toISOString().slice(0,13),o=`${e.type}|${e.layoutId}|${e.mediaId||""}|${e.widgetId||""}|${e.tag||""}|${e.scheduleId}|${n}`;if(s.has(o)){const a=s.get(o);a.count+=e.count||1,a.duration+=e.duration||0;const d=e.start instanceof Date?e.start:new Date(e.start),u=e.end instanceof Date?e.end:new Date(e.end||e.start);d<a.start&&(a.start=d),u>a.end&&(a.end=u),a._rawIds.push(e.id)}else s.set(o,{...e,start:e.start instanceof Date?e.start:new Date(e.start),end:e.end instanceof Date?e.end:new Date(e.end||e.start),count:e.count||1,_rawIds:[e.id]})}return Array.from(s.values())}async getAllStats(){return this.db?new Promise((r,t)=>{const n=this.db.transaction([b],"readonly").objectStore(b).getAll();n.onsuccess=()=>{r(n.result)},n.onerror=()=>{c.error("Failed to get all stats:",n.error),t(new Error(`Failed to get all stats: ${n.error}`))}}):(c.warn("Stats database not initialized"),[])}async clearAllStats(){if(!this.db){c.warn("Stats database not initialized");return}return new Promise((r,t)=>{const n=this.db.transaction([b],"readwrite").objectStore(b).clear();n.onsuccess=()=>{c.debug("Cleared all stats"),this.inProgressStats.clear(),r()},n.onerror=()=>{c.error("Failed to clear all stats:",n.error),t(new Error(`Failed to clear stats: ${n.error}`))}})}async _saveStat(r){return new Promise((t,s)=>{const n=this.db.transaction([b],"readwrite").objectStore(b),o=n.add(r);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(c.error("IndexedDB quota exceeded - cleaning old stats"),this._cleanOldStats().then(()=>{const a=n.add(r);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}_splitAtHourBoundaries(r){const t=r.start,s=r.end;if(t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()&&t.getHours()===s.getHours())return[r];const e=[];let n=new Date(t.getTime());for(;n<s;){const o=new Date(n.getTime());o.setMinutes(0,0,0),o.setHours(o.getHours()+1);const a=o<s?o:s,d=Math.floor((a-n)/1e3);e.push({...r,start:new Date(n.getTime()),end:new Date(a.getTime()),duration:d,count:1}),n=a}return e}async _saveStatSplit(r){const t=this._splitAtHourBoundaries(r);for(const s of t)await this._saveStat(s)}async _cleanOldStats(){if(this.db)return new Promise((r,t)=>{const e=this.db.transaction([b],"readwrite").objectStore(b),o=e.index("submitted").openCursor(1),a=[];o.onsuccess=d=>{const u=d.target.result;u&&a.length<100?(a.push(u.value.id),u.continue()):(a.forEach(h=>{e.delete(h)}),c.info(`Cleaned ${a.length} old stats due to quota`),r())},o.onerror=()=>{c.error("Failed to clean old stats:",o.error),t(o.error)}})}}function E(i){return!i||i.length===0?"<stats></stats>":`<stats>
|
|
2
|
-
${i.map(t=>{const s=S(t.start),e=S(t.end||t.start),n=[`type="${f(t.type)}"`,`fromdt="${f(s)}"`,`todt="${f(e)}"`,`scheduleid="${t.scheduleId}"`,`layoutid="${t.layoutId}"`];return t.type==="media"&&(t.mediaId&&n.push(`mediaid="${t.mediaId}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),t.type==="event"&&(t.tag&&n.push(`tag="${f(t.tag)}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),n.push(`count="${t.count}"`),n.push(`duration="${t.duration}"`),` <stat ${n.join(" ")} />`}).join(`
|
|
3
|
-
`)}
|
|
4
|
-
</stats>`}function S(i){i instanceof Date||(i=new Date(i));const r=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),e=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${r}-${t}-${s} ${e}:${n}:${o}`}function f(i){return typeof i!="string"?i:i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const l=w("@xiboplayer/stats"),F="xibo-player-logs",P=1,g="logs";class _{constructor(){this.db=null,this._reportedFaults=new Map}async init(){if(this.db){l.debug("Log reporter already initialized");return}return new Promise((r,t)=>{if(typeof indexedDB>"u"){const e=new Error("IndexedDB not available");l.error("IndexedDB not available - logs will not be persisted"),t(e);return}const s=indexedDB.open(F,P);s.onerror=()=>{const e=new Error(`Failed to open IndexedDB: ${s.error}`);l.error("Failed to open logs database:",s.error),t(e)},s.onsuccess=()=>{this.db=s.result,l.info("Logs database initialized"),r()},s.onupgradeneeded=e=>{const n=e.target.result;n.objectStoreNames.contains(g)||(n.createObjectStore(g,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),l.info("Logs store created"))}})}async log(r,t,s="PLAYER",e=null){if(!this.db){console.warn("[LogReporter] Database not initialized, dropping log entry");return}["error","warning","audit","info","debug"].includes(r)||(r="info");const o={level:r,message:t,category:s,timestamp:new Date,submitted:0};e&&(e.alertType&&(o.alertType=e.alertType),e.eventType&&(o.eventType=e.eventType));try{await this._saveLog(o)}catch(a){throw console.error("[LogReporter] Failed to save log entry:",a),a}}async reportFault(r,t,s=3e5){const e=this._reportedFaults.get(r);e&&Date.now()-e<s||(this._reportedFaults.set(r,Date.now()),await this.log("error",t,"event",{alertType:"Player Fault",eventType:r}),l.info(`Fault reported: ${r} - ${t}`))}async getFaultsForSubmission(r=10){return this.db?new Promise((t,s)=>{const a=this.db.transaction([g],"readonly").objectStore(g).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(h.value.alertType==="Player Fault"&&d.push(h.value),h.continue()):t(d)},a.onerror=()=>{l.error("Failed to retrieve faults:",a.error),s(new Error(`Failed to retrieve faults: ${a.error}`))}}):[]}async error(r,t="PLAYER"){return this.log("error",r,t)}async audit(r,t="PLAYER"){return this.log("audit",r,t)}async info(r,t="PLAYER"){return this.log("info",r,t)}async debug(r,t="PLAYER"){return this.log("debug",r,t)}async getLogsForSubmission(r=50){return this.db?new Promise((t,s)=>{const a=this.db.transaction([g],"readonly").objectStore(g).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(d.push(h.value),h.continue()):(l.debug(`Retrieved ${d.length} unsubmitted logs (limit: ${r})`),t(d))},a.onerror=()=>{l.error("Failed to retrieve logs:",a.error),s(new Error(`Failed to retrieve logs: ${a.error}`))}}):(l.warn("Logs database not initialized"),[])}async _countUnsubmitted(){return new Promise(r=>{try{const n=this.db.transaction([g],"readonly").objectStore(g).index("submitted").count(IDBKeyRange.only(0));n.onsuccess=()=>r(n.result),n.onerror=()=>r(0)}catch{r(0)}})}async clearSubmittedLogs(r){if(!this.db){l.warn("Logs database not initialized");return}if(!(!r||r.length===0))return new Promise((t,s)=>{const e=this.db.transaction([g],"readwrite"),n=e.objectStore(g);let o=0;r.forEach(a=>{if(a.id){const d=n.delete(a.id);d.onsuccess=()=>{o++},d.onerror=()=>{l.error(`Failed to delete log ${a.id}:`,d.error)}}}),e.oncomplete=()=>{l.debug(`Deleted ${o} submitted logs`),t()},e.onerror=()=>{l.error("Failed to delete submitted logs:",e.error),s(new Error(`Failed to delete logs: ${e.error}`))}})}async getAllLogs(){return this.db?new Promise((r,t)=>{const n=this.db.transaction([g],"readonly").objectStore(g).getAll();n.onsuccess=()=>{r(n.result)},n.onerror=()=>{l.error("Failed to get all logs:",n.error),t(new Error(`Failed to get all logs: ${n.error}`))}}):(l.warn("Logs database not initialized"),[])}async clearAllLogs(){if(!this.db){l.warn("Logs database not initialized");return}return new Promise((r,t)=>{const n=this.db.transaction([g],"readwrite").objectStore(g).clear();n.onsuccess=()=>{l.debug("Cleared all logs"),r()},n.onerror=()=>{l.error("Failed to clear all logs:",n.error),t(new Error(`Failed to clear logs: ${n.error}`))}})}async _saveLog(r){return new Promise((t,s)=>{const n=this.db.transaction([g],"readwrite").objectStore(g),o=n.add(r);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(console.warn("[LogReporter] IndexedDB quota exceeded - cleaning old logs"),this._cleanOldLogs().then(()=>{const a=n.add(r);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}async _cleanOldLogs(){if(this.db)return new Promise((r,t)=>{const e=this.db.transaction([g],"readwrite").objectStore(g),o=e.index("submitted").openCursor(1),a=[];o.onsuccess=d=>{const u=d.target.result;u&&a.length<100?(a.push(u.value.id),u.continue()):(a.forEach(h=>{e.delete(h)}),console.log(`[LogReporter] Cleaned ${a.length} old logs due to quota`),r())},o.onerror=()=>{console.error("[LogReporter] Failed to clean old logs:",o.error),t(o.error)}})}}function R(i){return!i||i.length===0?"<logs></logs>":`<logs>
|
|
5
|
-
${i.map(t=>{const s=y(t.timestamp),e=t.level==="error"||t.level==="audit"?t.level:"audit",n=[`date="${p(s)}"`,`category="${p(e)}"`];t.alertType&&n.push(`alertType="${p(t.alertType)}"`),t.eventType&&n.push(`eventType="${p(t.eventType)}"`);const o=p(t.thread||"main"),a=p(t.method||t.category||"PLAYER"),d=p(t.message),u=p(String(t.scheduleId||"0"));return` <log ${n.join(" ")}>
|
|
6
|
-
<thread>${o}</thread>
|
|
7
|
-
<method>${a}</method>
|
|
8
|
-
<message>${d}</message>
|
|
9
|
-
<scheduleID>${u}</scheduleID>
|
|
10
|
-
</log>`}).join(`
|
|
11
|
-
`)}
|
|
12
|
-
</logs>`}function q(i){return!i||i.length===0?"[]":JSON.stringify(i.map(r=>({code:r.eventType||"UNKNOWN",reason:r.message||"",date:y(r.timestamp),layoutId:r.scheduleId||0})))}function y(i){i instanceof Date||(i=new Date(i));const r=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),e=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${r}-${t}-${s} ${e}:${n}:${o}`}function p(i){return typeof i!="string"?i:i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const T=$.version;export{_ as LogReporter,L as StatsCollector,T as VERSION,q as formatFaults,R as formatLogs,E as formatStats};
|
|
13
|
-
//# sourceMappingURL=index-BVIXBw9z.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-BVIXBw9z.js","sources":["../../../stats/src/stats-collector.js","../../../stats/src/log-reporter.js","../../../stats/src/index.js"],"sourcesContent":["/**\n * StatsCollector - Proof of play tracking for Xibo CMS\n *\n * Tracks layout and widget playback for reporting to CMS via XMDS.\n * Uses IndexedDB for persistent storage across sessions.\n *\n * @module @xiboplayer/stats/collector\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('@xiboplayer/stats');\n\n// IndexedDB configuration\nconst DB_NAME = 'xibo-player-stats';\nconst DB_VERSION = 1;\nconst STATS_STORE = 'stats';\n\n/**\n * Stats collector for proof of play tracking\n *\n * Stores layout and widget playback statistics in IndexedDB.\n * Stats are submitted to CMS via XMDS SubmitStats API.\n *\n * @example\n * const collector = new StatsCollector();\n * await collector.init();\n *\n * // Track layout\n * await collector.startLayout(123, 456);\n * // ... layout plays ...\n * await collector.endLayout(123, 456);\n *\n * // Get stats for submission\n * const stats = await collector.getStatsForSubmission(50);\n * const xml = formatStats(stats);\n * // ... submit to CMS ...\n * await collector.clearSubmittedStats(stats);\n */\nexport class StatsCollector {\n constructor() {\n this.db = null;\n this.inProgressStats = new Map(); // Track in-progress stats by key\n }\n\n /**\n * Initialize IndexedDB\n *\n * Creates stats store with index on 'submitted' field for fast queries.\n * Safe to call multiple times (idempotent).\n *\n * @returns {Promise<void>}\n * @throws {Error} If IndexedDB is not available or initialization fails\n */\n async init() {\n if (this.db) {\n log.debug('Stats collector already initialized');\n return;\n }\n\n return new Promise((resolve, reject) => {\n // Check if IndexedDB is available\n if (typeof indexedDB === 'undefined') {\n const error = new Error('IndexedDB not available');\n log.error('IndexedDB not available - stats will not be persisted');\n reject(error);\n return;\n }\n\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onerror = () => {\n const error = new Error(`Failed to open IndexedDB: ${request.error}`);\n log.error('Failed to open stats database:', request.error);\n reject(error);\n };\n\n request.onsuccess = () => {\n this.db = request.result;\n log.info('Stats database initialized');\n resolve();\n };\n\n request.onupgradeneeded = (event) => {\n const db = event.target.result;\n\n // Create stats store if it doesn't exist\n if (!db.objectStoreNames.contains(STATS_STORE)) {\n const store = db.createObjectStore(STATS_STORE, {\n keyPath: 'id',\n autoIncrement: true\n });\n\n // Index on 'submitted' for fast queries\n store.createIndex('submitted', 'submitted', { unique: false });\n\n log.info('Stats store created');\n }\n };\n });\n }\n\n /**\n * Start tracking a layout\n *\n * Creates a new layout stat entry and tracks it as in-progress.\n * If a layout with the same ID is already in progress (replay),\n * silently ends the previous cycle and starts a new one.\n *\n * @param {number} layoutId - Layout ID from CMS\n * @param {number} scheduleId - Schedule ID that triggered this layout\n * @param {Object} [options] - Options\n * @param {boolean} [options.enableStat=true] - Whether stats are enabled for this layout\n * @returns {Promise<void>}\n */\n async startLayout(layoutId, scheduleId, options) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n // Respect enableStat flag from XLF (layout/widget level stat suppression)\n if (options?.enableStat === false) {\n log.debug(`Stats disabled for layout ${layoutId} (enableStat=false)`);\n return;\n }\n\n // Key excludes scheduleId: only one layout instance can be in-progress at a time,\n // and scheduleId may change mid-play when a collection cycle completes.\n const key = `layout-${layoutId}`;\n\n // Layout replay: end previous cycle silently before starting new one\n if (this.inProgressStats.has(key)) {\n const prev = this.inProgressStats.get(key);\n prev.end = new Date();\n prev.duration = Math.floor((prev.end - prev.start) / 1000);\n await this._saveStatSplit(prev);\n this.inProgressStats.delete(key);\n log.debug(`Layout ${layoutId} replay - ended previous cycle (${prev.duration}s)`);\n }\n\n const stat = {\n type: 'layout',\n layoutId,\n scheduleId,\n start: new Date(),\n end: null,\n duration: 0,\n count: 1,\n submitted: 0 // Use 0/1 instead of boolean for IndexedDB compatibility\n };\n\n this.inProgressStats.set(key, stat);\n log.debug(`Started tracking layout ${layoutId} (schedule ${scheduleId})`);\n }\n\n /**\n * End tracking a layout\n *\n * Finalizes the layout stat entry and saves it to IndexedDB.\n * Calculates duration in seconds.\n *\n * @param {number} layoutId - Layout ID from CMS\n * @param {number} scheduleId - Schedule ID that triggered this layout\n * @returns {Promise<void>}\n */\n async endLayout(layoutId, scheduleId) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n const key = `layout-${layoutId}`;\n const stat = this.inProgressStats.get(key);\n\n if (!stat) {\n log.debug(`Layout ${layoutId} not found in progress (may have been ended by replay)`);\n return;\n }\n\n // Calculate duration in seconds\n stat.end = new Date();\n stat.duration = Math.floor((stat.end - stat.start) / 1000);\n\n // Save to database (splitting at hour boundaries for CMS aggregation)\n try {\n await this._saveStatSplit(stat);\n this.inProgressStats.delete(key);\n log.debug(`Ended tracking layout ${layoutId} (${stat.duration}s)`);\n } catch (error) {\n log.error(`Failed to save layout stat ${layoutId}:`, error);\n throw error;\n }\n }\n\n /**\n * Start tracking a widget/media\n *\n * Creates a new media stat entry and tracks it as in-progress.\n * If a widget with the same key is already in progress (replay),\n * silently ends the previous cycle and starts a new one.\n *\n * @param {number} mediaId - Media ID from CMS\n * @param {number} layoutId - Parent layout ID\n * @param {number} scheduleId - Schedule ID\n * @param {string|number} [widgetId] - Widget ID (for non-library widgets with no mediaId)\n * @param {Object} [options] - Options\n * @param {boolean} [options.enableStat=true] - Whether stats are enabled for this widget\n * @returns {Promise<void>}\n */\n async startWidget(mediaId, layoutId, scheduleId, widgetId, options) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n // Respect enableStat flag from XLF (layout/widget level stat suppression)\n if (options?.enableStat === false) {\n log.debug(`Stats disabled for widget ${mediaId} (enableStat=false)`);\n return;\n }\n\n // Key excludes scheduleId: it may change mid-play during collection cycles.\n const key = `media-${mediaId}-${layoutId}`;\n\n // Widget replay: end previous cycle silently before starting new one\n if (this.inProgressStats.has(key)) {\n const prev = this.inProgressStats.get(key);\n prev.end = new Date();\n prev.duration = Math.floor((prev.end - prev.start) / 1000);\n await this._saveStatSplit(prev);\n this.inProgressStats.delete(key);\n log.debug(`Widget ${mediaId} replay - ended previous cycle (${prev.duration}s)`);\n }\n\n const stat = {\n type: 'media',\n mediaId,\n widgetId: widgetId || null,\n layoutId,\n scheduleId,\n start: new Date(),\n end: null,\n duration: 0,\n count: 1,\n submitted: 0 // Use 0/1 instead of boolean for IndexedDB compatibility\n };\n\n this.inProgressStats.set(key, stat);\n log.debug(`Started tracking widget ${mediaId} in layout ${layoutId}`);\n }\n\n /**\n * End tracking a widget/media\n *\n * Finalizes the media stat entry and saves it to IndexedDB.\n * Calculates duration in seconds.\n *\n * @param {number} mediaId - Media ID from CMS\n * @param {number} layoutId - Parent layout ID\n * @param {number} scheduleId - Schedule ID\n * @returns {Promise<void>}\n */\n async endWidget(mediaId, layoutId, scheduleId) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n const key = `media-${mediaId}-${layoutId}`;\n const stat = this.inProgressStats.get(key);\n\n if (!stat) {\n log.debug(`Widget ${mediaId} not found in progress (expected during layout transitions)`);\n return;\n }\n\n // Calculate duration in seconds\n stat.end = new Date();\n stat.duration = Math.floor((stat.end - stat.start) / 1000);\n\n // Save to database (splitting at hour boundaries for CMS aggregation)\n try {\n await this._saveStatSplit(stat);\n this.inProgressStats.delete(key);\n log.debug(`Ended tracking widget ${mediaId} (${stat.duration}s)`);\n } catch (error) {\n log.error(`Failed to save widget stat ${mediaId}:`, error);\n throw error;\n }\n }\n\n /**\n * Record an event stat (point-in-time engagement data)\n *\n * Creates an instant stat entry with no duration. Used for tracking\n * interactive touches, webhook triggers, and other engagement events.\n * Unlike layout/widget stats, events have no start/end cycle.\n *\n * @param {string} tag - Event tag describing the interaction (e.g. 'touch', 'webhook')\n * @param {number} layoutId - Layout ID where the event occurred\n * @param {number} widgetId - Widget ID that triggered the event\n * @param {number} scheduleId - Schedule ID for the current schedule\n * @returns {Promise<void>}\n */\n async recordEvent(tag, layoutId, widgetId, scheduleId) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n const now = new Date();\n const stat = {\n type: 'event',\n tag,\n layoutId,\n widgetId,\n scheduleId,\n start: now,\n end: now,\n duration: 0,\n count: 1,\n submitted: 0\n };\n\n try {\n await this._saveStat(stat);\n log.debug(`Recorded event '${tag}' for widget ${widgetId} in layout ${layoutId}`);\n } catch (error) {\n log.error(`Failed to record event '${tag}':`, error);\n throw error;\n }\n }\n\n /**\n * Get stats ready for submission to CMS\n *\n * Returns unsubmitted stats up to the specified limit.\n * Stats are ordered by ID (oldest first).\n *\n * @param {number} limit - Maximum number of stats to return (default: 50)\n * @returns {Promise<Array>} Array of stat objects\n */\n async getStatsForSubmission(limit = 50) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return [];\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readonly');\n const store = transaction.objectStore(STATS_STORE);\n const index = store.index('submitted');\n\n // Query for unsubmitted stats (0 = false)\n const request = index.openCursor(IDBKeyRange.only(0));\n const stats = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n\n if (cursor && stats.length < limit) {\n stats.push(cursor.value);\n cursor.continue();\n } else {\n log.debug(`Retrieved ${stats.length} unsubmitted stats`);\n resolve(stats);\n }\n };\n\n request.onerror = () => {\n log.error('Failed to retrieve stats:', request.error);\n reject(new Error(`Failed to retrieve stats: ${request.error}`));\n };\n });\n }\n\n /**\n * Clear submitted stats from database\n *\n * Deletes stats that were successfully submitted to CMS.\n *\n * @param {Array} stats - Array of stat objects to delete\n * @returns {Promise<void>}\n */\n async clearSubmittedStats(stats) {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n if (!stats || stats.length === 0) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readwrite');\n const store = transaction.objectStore(STATS_STORE);\n\n let deletedCount = 0;\n\n stats.forEach((stat) => {\n if (stat.id) {\n const request = store.delete(stat.id);\n request.onsuccess = () => {\n deletedCount++;\n };\n request.onerror = () => {\n log.error(`Failed to delete stat ${stat.id}:`, request.error);\n };\n }\n });\n\n transaction.oncomplete = () => {\n log.debug(`Deleted ${deletedCount} submitted stats`);\n resolve();\n };\n\n transaction.onerror = () => {\n log.error('Failed to delete submitted stats:', transaction.error);\n reject(new Error(`Failed to delete stats: ${transaction.error}`));\n };\n });\n }\n\n /**\n * Get aggregated stats for submission\n *\n * Groups stats by (type, layoutId, mediaId, scheduleId, hour) and sums\n * durations/counts. Used when CMS aggregationLevel is 'Aggregate'.\n *\n * @param {number} limit - Maximum number of raw stats to read (default: 50)\n * @returns {Promise<Array>} Aggregated stat objects\n */\n async getAggregatedStatsForSubmission(limit = 50) {\n const rawStats = await this.getStatsForSubmission(limit);\n if (rawStats.length === 0) return [];\n\n // Group by (type, layoutId, mediaId, scheduleId, hour)\n const groups = new Map();\n for (const stat of rawStats) {\n const hour = stat.start instanceof Date\n ? stat.start.toISOString().slice(0, 13)\n : new Date(stat.start).toISOString().slice(0, 13);\n const key = `${stat.type}|${stat.layoutId}|${stat.mediaId || ''}|${stat.widgetId || ''}|${stat.tag || ''}|${stat.scheduleId}|${hour}`;\n\n if (groups.has(key)) {\n const group = groups.get(key);\n group.count += stat.count || 1;\n group.duration += stat.duration || 0;\n // Keep earliest start and latest end\n const statStart = stat.start instanceof Date ? stat.start : new Date(stat.start);\n const statEnd = stat.end instanceof Date ? stat.end : new Date(stat.end || stat.start);\n if (statStart < group.start) group.start = statStart;\n if (statEnd > group.end) group.end = statEnd;\n group._rawIds.push(stat.id);\n } else {\n groups.set(key, {\n ...stat,\n start: stat.start instanceof Date ? stat.start : new Date(stat.start),\n end: stat.end instanceof Date ? stat.end : new Date(stat.end || stat.start),\n count: stat.count || 1,\n _rawIds: [stat.id]\n });\n }\n }\n\n return Array.from(groups.values());\n }\n\n /**\n * Get all stats (for debugging)\n *\n * @returns {Promise<Array>} All stats in database\n */\n async getAllStats() {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return [];\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readonly');\n const store = transaction.objectStore(STATS_STORE);\n const request = store.getAll();\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n\n request.onerror = () => {\n log.error('Failed to get all stats:', request.error);\n reject(new Error(`Failed to get all stats: ${request.error}`));\n };\n });\n }\n\n /**\n * Clear all stats (for testing)\n *\n * @returns {Promise<void>}\n */\n async clearAllStats() {\n if (!this.db) {\n log.warn('Stats database not initialized');\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readwrite');\n const store = transaction.objectStore(STATS_STORE);\n const request = store.clear();\n\n request.onsuccess = () => {\n log.debug('Cleared all stats');\n this.inProgressStats.clear();\n resolve();\n };\n\n request.onerror = () => {\n log.error('Failed to clear all stats:', request.error);\n reject(new Error(`Failed to clear stats: ${request.error}`));\n };\n });\n }\n\n /**\n * Save a stat to IndexedDB\n * @private\n */\n async _saveStat(stat) {\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readwrite');\n const store = transaction.objectStore(STATS_STORE);\n const request = store.add(stat);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n\n request.onerror = () => {\n // Check for quota exceeded error\n if (request.error.name === 'QuotaExceededError') {\n log.error('IndexedDB quota exceeded - cleaning old stats');\n this._cleanOldStats().then(() => {\n // Retry once after cleanup\n const retryRequest = store.add(stat);\n retryRequest.onsuccess = () => resolve(retryRequest.result);\n retryRequest.onerror = () => reject(retryRequest.error);\n }).catch(reject);\n } else {\n reject(request.error);\n }\n };\n });\n }\n\n /**\n * Split a stat record at hour boundaries.\n * If a stat spans multiple hours (e.g. 12:50→13:10), it is split into\n * separate records at each hour boundary for correct CMS aggregation.\n * Returns an array of one or more stat objects.\n * @param {Object} stat - Finalized stat with start, end, duration\n * @returns {Object[]}\n * @private\n */\n _splitAtHourBoundaries(stat) {\n const start = stat.start;\n const end = stat.end;\n\n // No split needed if start and end are in the same hour\n if (start.getFullYear() === end.getFullYear() &&\n start.getMonth() === end.getMonth() &&\n start.getDate() === end.getDate() &&\n start.getHours() === end.getHours()) {\n return [stat];\n }\n\n const results = [];\n let segStart = new Date(start.getTime());\n\n while (segStart < end) {\n // Next hour boundary: top of the next hour from segStart\n const nextHour = new Date(segStart.getTime());\n nextHour.setMinutes(0, 0, 0);\n nextHour.setHours(nextHour.getHours() + 1);\n\n const segEnd = nextHour < end ? nextHour : end;\n const duration = Math.floor((segEnd - segStart) / 1000);\n\n results.push({\n ...stat,\n start: new Date(segStart.getTime()),\n end: new Date(segEnd.getTime()),\n duration,\n count: 1\n });\n\n segStart = segEnd;\n }\n\n return results;\n }\n\n /**\n * Save a stat to IndexedDB, splitting at hour boundaries first.\n * @param {Object} stat - Finalized stat with start, end, duration\n * @private\n */\n async _saveStatSplit(stat) {\n const parts = this._splitAtHourBoundaries(stat);\n for (const part of parts) {\n await this._saveStat(part);\n }\n }\n\n /**\n * Clean old stats when quota is exceeded\n * Deletes oldest 100 submitted stats\n * @private\n */\n async _cleanOldStats() {\n if (!this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([STATS_STORE], 'readwrite');\n const store = transaction.objectStore(STATS_STORE);\n const index = store.index('submitted');\n\n // Get oldest 100 submitted stats (use 1 for boolean true in IndexedDB)\n const request = index.openCursor(1);\n const toDelete = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n\n if (cursor && toDelete.length < 100) {\n toDelete.push(cursor.value.id);\n cursor.continue();\n } else {\n // Delete collected IDs\n toDelete.forEach((id) => {\n store.delete(id);\n });\n\n log.info(`Cleaned ${toDelete.length} old stats due to quota`);\n resolve();\n }\n };\n\n request.onerror = () => {\n log.error('Failed to clean old stats:', request.error);\n reject(request.error);\n };\n });\n }\n}\n\n/**\n * Format stats as XML for XMDS submission\n *\n * Converts array of stat objects to XML format expected by CMS.\n *\n * XML format:\n * ```xml\n * <stats>\n * <stat type=\"layout\" fromdt=\"2026-02-10 12:00:00\" todt=\"2026-02-10 12:05:00\"\n * scheduleid=\"123\" layoutid=\"456\" count=\"1\" duration=\"300\" />\n * <stat type=\"media\" fromdt=\"2026-02-10 12:00:00\" todt=\"2026-02-10 12:01:00\"\n * scheduleid=\"123\" layoutid=\"456\" mediaid=\"789\" count=\"1\" duration=\"60\" />\n * </stats>\n * ```\n *\n * @param {Array} stats - Array of stat objects from getStatsForSubmission()\n * @returns {string} XML string for XMDS SubmitStats\n *\n * @example\n * const stats = await collector.getStatsForSubmission(50);\n * const xml = formatStats(stats);\n * await xmds.submitStats(xml);\n */\nexport function formatStats(stats) {\n if (!stats || stats.length === 0) {\n return '<stats></stats>';\n }\n\n const statElements = stats.map((stat) => {\n // Format dates as \"YYYY-MM-DD HH:MM:SS\"\n const fromdt = formatDateTime(stat.start);\n const todt = formatDateTime(stat.end || stat.start);\n\n // Build attributes\n const attrs = [\n `type=\"${escapeXml(stat.type)}\"`,\n `fromdt=\"${escapeXml(fromdt)}\"`,\n `todt=\"${escapeXml(todt)}\"`,\n `scheduleid=\"${stat.scheduleId}\"`,\n `layoutid=\"${stat.layoutId}\"`,\n ];\n\n // Add mediaId and widgetId for media/widget stats\n if (stat.type === 'media') {\n if (stat.mediaId) {\n attrs.push(`mediaid=\"${stat.mediaId}\"`);\n }\n // Include widgetId for non-library widgets (native widgets have no mediaId)\n if (stat.widgetId) {\n attrs.push(`widgetid=\"${stat.widgetId}\"`);\n }\n }\n\n // Add tag and widgetId for event stats\n if (stat.type === 'event') {\n if (stat.tag) {\n attrs.push(`tag=\"${escapeXml(stat.tag)}\"`);\n }\n if (stat.widgetId) {\n attrs.push(`widgetid=\"${stat.widgetId}\"`);\n }\n }\n\n // Add count and duration\n attrs.push(`count=\"${stat.count}\"`);\n attrs.push(`duration=\"${stat.duration}\"`);\n\n return ` <stat ${attrs.join(' ')} />`;\n });\n\n return `<stats>\\n${statElements.join('\\n')}\\n</stats>`;\n}\n\n/**\n * Format Date object as \"YYYY-MM-DD HH:MM:SS\"\n * @private\n */\nfunction formatDateTime(date) {\n if (!(date instanceof Date)) {\n date = new Date(date);\n }\n\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n const seconds = String(date.getSeconds()).padStart(2, '0');\n\n return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;\n}\n\n/**\n * Escape XML special characters\n * @private\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return str;\n }\n\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","/**\n * LogReporter - CMS logging for Xibo Players\n *\n * Collects and submits logs to CMS via XMDS.\n * Uses IndexedDB for persistent storage across sessions.\n *\n * @module @xiboplayer/stats/logger\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('@xiboplayer/stats');\n\n// IndexedDB configuration\nconst DB_NAME = 'xibo-player-logs';\nconst DB_VERSION = 1;\nconst LOGS_STORE = 'logs';\n\n/**\n * Log reporter for CMS logging\n *\n * Stores log entries in IndexedDB and submits to CMS via XMDS.\n * Supports multiple log levels: error, audit, info, debug.\n *\n * @example\n * const reporter = new LogReporter();\n * await reporter.init();\n *\n * // Log messages\n * await reporter.error('Failed to load layout', 'PLAYER');\n * await reporter.info('Layout loaded successfully', 'PLAYER');\n *\n * // Get logs for submission\n * const logs = await reporter.getLogsForSubmission(100);\n * const xml = formatLogs(logs);\n * // ... submit to CMS ...\n * await reporter.clearSubmittedLogs(logs);\n */\nexport class LogReporter {\n constructor() {\n this.db = null;\n this._reportedFaults = new Map(); // code -> timestamp (deduplication)\n }\n\n /**\n * Initialize IndexedDB\n *\n * Creates logs store with index on 'submitted' field for fast queries.\n * Safe to call multiple times (idempotent).\n *\n * @returns {Promise<void>}\n * @throws {Error} If IndexedDB is not available or initialization fails\n */\n async init() {\n if (this.db) {\n log.debug('Log reporter already initialized');\n return;\n }\n\n return new Promise((resolve, reject) => {\n // Check if IndexedDB is available\n if (typeof indexedDB === 'undefined') {\n const error = new Error('IndexedDB not available');\n log.error('IndexedDB not available - logs will not be persisted');\n reject(error);\n return;\n }\n\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onerror = () => {\n const error = new Error(`Failed to open IndexedDB: ${request.error}`);\n log.error('Failed to open logs database:', request.error);\n reject(error);\n };\n\n request.onsuccess = () => {\n this.db = request.result;\n log.info('Logs database initialized');\n resolve();\n };\n\n request.onupgradeneeded = (event) => {\n const db = event.target.result;\n\n // Create logs store if it doesn't exist\n if (!db.objectStoreNames.contains(LOGS_STORE)) {\n const store = db.createObjectStore(LOGS_STORE, {\n keyPath: 'id',\n autoIncrement: true\n });\n\n // Index on 'submitted' for fast queries\n store.createIndex('submitted', 'submitted', { unique: false });\n\n log.info('Logs store created');\n }\n };\n });\n }\n\n /**\n * Log a message\n *\n * Stores a log entry in IndexedDB for later submission to CMS.\n *\n * @param {string} level - Log level: 'error', 'audit', 'info', or 'debug'\n * @param {string} message - Log message\n * @param {string} category - Log category (default: 'PLAYER')\n * @param {Object} [extra] - Optional extra fields (alertType, eventType)\n * @returns {Promise<void>}\n */\n async log(level, message, category = 'PLAYER', extra = null) {\n if (!this.db) {\n // Use console directly — NOT the logger — to avoid infinite feedback loop.\n // The logger dispatches to log sinks, and this method IS the sink target.\n console.warn('[LogReporter] Database not initialized, dropping log entry');\n return;\n }\n\n // Validate log level\n const validLevels = ['error', 'warning', 'audit', 'info', 'debug'];\n if (!validLevels.includes(level)) {\n level = 'info';\n }\n\n const logEntry = {\n level,\n message,\n category,\n timestamp: new Date(),\n submitted: 0 // Use 0/1 instead of boolean for IndexedDB compatibility\n };\n\n // Add alert fields for faults (triggers CMS dashboard alerts)\n if (extra) {\n if (extra.alertType) logEntry.alertType = extra.alertType;\n if (extra.eventType) logEntry.eventType = extra.eventType;\n }\n\n try {\n await this._saveLog(logEntry);\n // NOTE: Do NOT call log.debug() here — it dispatches to sinks, which call\n // logReporter.log() again, creating an infinite async loop.\n } catch (error) {\n // Use console directly to avoid feedback loop\n console.error('[LogReporter] Failed to save log entry:', error);\n throw error;\n }\n }\n\n /**\n * Report a fault to CMS (special log entry that triggers alerts)\n *\n * Faults are log entries with alertType/eventType fields that cause the\n * CMS to show alerts on the display dashboard and optionally send emails.\n * Deduplicates by code: same fault code won't be reported again within\n * the cooldown period (default 5 minutes).\n *\n * @param {string} code - Fault code (e.g., 'LAYOUT_LOAD_FAILED')\n * @param {string} reason - Human-readable description\n * @param {number} [cooldownMs=300000] - Dedup cooldown in ms (default 5 min)\n * @returns {Promise<void>}\n */\n async reportFault(code, reason, cooldownMs = 300000) {\n // Deduplication: skip if same code was reported recently\n const lastReported = this._reportedFaults.get(code);\n if (lastReported && (Date.now() - lastReported) < cooldownMs) {\n return;\n }\n\n this._reportedFaults.set(code, Date.now());\n\n await this.log('error', reason, 'event', {\n alertType: 'Player Fault',\n eventType: code\n });\n\n log.info(`Fault reported: ${code} - ${reason}`);\n }\n\n /**\n * Get unsubmitted fault entries for dedicated fault submission.\n * Returns log entries that have alertType='Player Fault' and submitted=0.\n * These are the high-priority entries that should be submitted faster\n * than the normal log collection cycle.\n *\n * @param {number} [limit=10] - Maximum faults to return per batch\n * @returns {Promise<Array>} Array of fault log objects\n */\n async getFaultsForSubmission(limit = 10) {\n if (!this.db) return [];\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readonly');\n const store = transaction.objectStore(LOGS_STORE);\n const index = store.index('submitted');\n\n const request = index.openCursor(IDBKeyRange.only(0));\n const faults = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n\n if (cursor && faults.length < limit) {\n if (cursor.value.alertType === 'Player Fault') {\n faults.push(cursor.value);\n }\n cursor.continue();\n } else {\n resolve(faults);\n }\n };\n\n request.onerror = () => {\n log.error('Failed to retrieve faults:', request.error);\n reject(new Error(`Failed to retrieve faults: ${request.error}`));\n };\n });\n }\n\n /**\n * Log an error message\n *\n * Shorthand for log('error', message, category)\n *\n * @param {string} message - Error message\n * @param {string} category - Log category (default: 'PLAYER')\n * @returns {Promise<void>}\n */\n async error(message, category = 'PLAYER') {\n return this.log('error', message, category);\n }\n\n /**\n * Log an audit message\n *\n * Shorthand for log('audit', message, category)\n *\n * @param {string} message - Audit message\n * @param {string} category - Log category (default: 'PLAYER')\n * @returns {Promise<void>}\n */\n async audit(message, category = 'PLAYER') {\n return this.log('audit', message, category);\n }\n\n /**\n * Log an info message\n *\n * Shorthand for log('info', message, category)\n *\n * @param {string} message - Info message\n * @param {string} category - Log category (default: 'PLAYER')\n * @returns {Promise<void>}\n */\n async info(message, category = 'PLAYER') {\n return this.log('info', message, category);\n }\n\n /**\n * Log a debug message\n *\n * Shorthand for log('debug', message, category)\n *\n * @param {string} message - Debug message\n * @param {string} category - Log category (default: 'PLAYER')\n * @returns {Promise<void>}\n */\n async debug(message, category = 'PLAYER') {\n return this.log('debug', message, category);\n }\n\n /**\n * Get logs ready for submission to CMS\n *\n * Returns unsubmitted logs up to the spec limit of 50 per batch.\n *\n * @param {number} [limit=50] - Maximum number of logs to return (spec max: 50)\n * @returns {Promise<Array>} Array of log objects\n */\n async getLogsForSubmission(limit = 50) {\n if (!this.db) {\n log.warn('Logs database not initialized');\n return [];\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readonly');\n const store = transaction.objectStore(LOGS_STORE);\n const index = store.index('submitted');\n\n // Query for unsubmitted logs (0 = false)\n const request = index.openCursor(IDBKeyRange.only(0));\n const logs = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n\n if (cursor && logs.length < limit) {\n logs.push(cursor.value);\n cursor.continue();\n } else {\n log.debug(`Retrieved ${logs.length} unsubmitted logs (limit: ${limit})`);\n resolve(logs);\n }\n };\n\n request.onerror = () => {\n log.error('Failed to retrieve logs:', request.error);\n reject(new Error(`Failed to retrieve logs: ${request.error}`));\n };\n });\n }\n\n /**\n * Count unsubmitted logs in the database.\n * @returns {Promise<number>}\n */\n async _countUnsubmitted() {\n return new Promise((resolve) => {\n try {\n const transaction = this.db.transaction([LOGS_STORE], 'readonly');\n const store = transaction.objectStore(LOGS_STORE);\n const index = store.index('submitted');\n const request = index.count(IDBKeyRange.only(0));\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => resolve(0);\n } catch (_) {\n resolve(0);\n }\n });\n }\n\n /**\n * Clear submitted logs from database\n *\n * Deletes logs that were successfully submitted to CMS.\n *\n * @param {Array} logs - Array of log objects to delete\n * @returns {Promise<void>}\n */\n async clearSubmittedLogs(logs) {\n if (!this.db) {\n log.warn('Logs database not initialized');\n return;\n }\n\n if (!logs || logs.length === 0) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readwrite');\n const store = transaction.objectStore(LOGS_STORE);\n\n let deletedCount = 0;\n\n logs.forEach((logEntry) => {\n if (logEntry.id) {\n const request = store.delete(logEntry.id);\n request.onsuccess = () => {\n deletedCount++;\n };\n request.onerror = () => {\n log.error(`Failed to delete log ${logEntry.id}:`, request.error);\n };\n }\n });\n\n transaction.oncomplete = () => {\n log.debug(`Deleted ${deletedCount} submitted logs`);\n resolve();\n };\n\n transaction.onerror = () => {\n log.error('Failed to delete submitted logs:', transaction.error);\n reject(new Error(`Failed to delete logs: ${transaction.error}`));\n };\n });\n }\n\n /**\n * Get all logs (for debugging)\n *\n * @returns {Promise<Array>} All logs in database\n */\n async getAllLogs() {\n if (!this.db) {\n log.warn('Logs database not initialized');\n return [];\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readonly');\n const store = transaction.objectStore(LOGS_STORE);\n const request = store.getAll();\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n\n request.onerror = () => {\n log.error('Failed to get all logs:', request.error);\n reject(new Error(`Failed to get all logs: ${request.error}`));\n };\n });\n }\n\n /**\n * Clear all logs (for testing)\n *\n * @returns {Promise<void>}\n */\n async clearAllLogs() {\n if (!this.db) {\n log.warn('Logs database not initialized');\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readwrite');\n const store = transaction.objectStore(LOGS_STORE);\n const request = store.clear();\n\n request.onsuccess = () => {\n log.debug('Cleared all logs');\n resolve();\n };\n\n request.onerror = () => {\n log.error('Failed to clear all logs:', request.error);\n reject(new Error(`Failed to clear logs: ${request.error}`));\n };\n });\n }\n\n /**\n * Save a log entry to IndexedDB\n * @private\n */\n async _saveLog(logEntry) {\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readwrite');\n const store = transaction.objectStore(LOGS_STORE);\n const request = store.add(logEntry);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n\n request.onerror = () => {\n // Check for quota exceeded error\n if (request.error.name === 'QuotaExceededError') {\n console.warn('[LogReporter] IndexedDB quota exceeded - cleaning old logs');\n this._cleanOldLogs().then(() => {\n // Retry once after cleanup\n const retryRequest = store.add(logEntry);\n retryRequest.onsuccess = () => resolve(retryRequest.result);\n retryRequest.onerror = () => reject(retryRequest.error);\n }).catch(reject);\n } else {\n reject(request.error);\n }\n };\n });\n }\n\n /**\n * Clean old logs when quota is exceeded\n * Deletes oldest 100 submitted logs\n * @private\n */\n async _cleanOldLogs() {\n if (!this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([LOGS_STORE], 'readwrite');\n const store = transaction.objectStore(LOGS_STORE);\n const index = store.index('submitted');\n\n // Get oldest 100 submitted logs (use 1 for boolean true in IndexedDB)\n const request = index.openCursor(1);\n const toDelete = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n\n if (cursor && toDelete.length < 100) {\n toDelete.push(cursor.value.id);\n cursor.continue();\n } else {\n // Delete collected IDs\n toDelete.forEach((id) => {\n store.delete(id);\n });\n\n console.log(`[LogReporter] Cleaned ${toDelete.length} old logs due to quota`);\n resolve();\n }\n };\n\n request.onerror = () => {\n console.error('[LogReporter] Failed to clean old logs:', request.error);\n reject(request.error);\n };\n });\n }\n}\n\n/**\n * Format logs as XML for XMDS submission\n *\n * Converts array of log objects to XML format expected by CMS.\n *\n * XML format (spec-compliant):\n * ```xml\n * <logs>\n * <log date=\"2026-02-10 12:00:00\" category=\"error\">\n * <thread>main</thread>\n * <method>collect</method>\n * <message>Failed to load layout 123</message>\n * <scheduleID>0</scheduleID>\n * </log>\n * </logs>\n * ```\n *\n * @param {Array} logs - Array of log objects from getLogsForSubmission()\n * @returns {string} XML string for XMDS SubmitLog\n *\n * @example\n * const logs = await reporter.getLogsForSubmission(100);\n * const xml = formatLogs(logs);\n * await xmds.submitLog(xml);\n */\nexport function formatLogs(logs) {\n if (!logs || logs.length === 0) {\n return '<logs></logs>';\n }\n\n const logElements = logs.map((logEntry) => {\n // Format date as \"YYYY-MM-DD HH:MM:SS\"\n const date = formatDateTime(logEntry.timestamp);\n\n // Spec categories: only \"error\" and \"audit\" are valid\n const category = (logEntry.level === 'error' || logEntry.level === 'audit')\n ? logEntry.level : 'audit';\n\n // Build attributes on <log> element\n const attrs = [\n `date=\"${escapeXml(date)}\"`,\n `category=\"${escapeXml(category)}\"`\n ];\n\n // Fault alert fields (triggers CMS dashboard alerts)\n if (logEntry.alertType) {\n attrs.push(`alertType=\"${escapeXml(logEntry.alertType)}\"`);\n }\n if (logEntry.eventType) {\n attrs.push(`eventType=\"${escapeXml(logEntry.eventType)}\"`);\n }\n\n // Build child elements (spec format: thread, method, message, scheduleID)\n const thread = escapeXml(logEntry.thread || 'main');\n const method = escapeXml(logEntry.method || logEntry.category || 'PLAYER');\n const message = escapeXml(logEntry.message);\n const scheduleId = escapeXml(String(logEntry.scheduleId || '0'));\n\n return ` <log ${attrs.join(' ')}>\\n <thread>${thread}</thread>\\n <method>${method}</method>\\n <message>${message}</message>\\n <scheduleID>${scheduleId}</scheduleID>\\n </log>`;\n });\n\n return `<logs>\\n${logElements.join('\\n')}\\n</logs>`;\n}\n\n/**\n * Format fault log entries as JSON for XMDS ReportFaults submission.\n *\n * Converts fault log objects (from getFaultsForSubmission) into the JSON\n * string format expected by xmds.reportFaults().\n *\n * @param {Array} faults - Array of fault log objects from getFaultsForSubmission()\n * @returns {string} JSON string for XMDS ReportFaults\n *\n * @example\n * const faults = await reporter.getFaultsForSubmission();\n * if (faults.length > 0) {\n * const json = formatFaults(faults);\n * await xmds.reportFaults(json);\n * }\n */\nexport function formatFaults(faults) {\n if (!faults || faults.length === 0) return '[]';\n\n return JSON.stringify(faults.map(f => ({\n code: f.eventType || 'UNKNOWN',\n reason: f.message || '',\n date: formatDateTime(f.timestamp),\n layoutId: f.scheduleId || 0\n })));\n}\n\n/**\n * Format Date object as \"YYYY-MM-DD HH:MM:SS\"\n * @private\n */\nfunction formatDateTime(date) {\n if (!(date instanceof Date)) {\n date = new Date(date);\n }\n\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n const seconds = String(date.getSeconds()).padStart(2, '0');\n\n return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;\n}\n\n/**\n * Escape XML special characters\n * @private\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return str;\n }\n\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","// @xiboplayer/stats - Proof of play and statistics reporting\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\n\n/**\n * Stats collector for proof of play tracking\n * @module @xiboplayer/stats/collector\n */\nexport { StatsCollector, formatStats } from './stats-collector.js';\n\n/**\n * Log reporter for CMS logging\n * @module @xiboplayer/stats/logger\n */\nexport { LogReporter, formatLogs, formatFaults } from './log-reporter.js';\n"],"names":["log","createLogger","DB_NAME","DB_VERSION","STATS_STORE","StatsCollector","resolve","reject","error","request","event","db","layoutId","scheduleId","options","key","prev","stat","mediaId","widgetId","tag","now","limit","stats","cursor","transaction","store","deletedCount","rawStats","groups","hour","group","statStart","statEnd","retryRequest","start","end","results","segStart","nextHour","segEnd","duration","parts","part","toDelete","id","formatStats","fromdt","formatDateTime","todt","attrs","escapeXml","date","year","month","day","hours","minutes","seconds","str","LOGS_STORE","LogReporter","level","message","category","extra","logEntry","code","reason","cooldownMs","lastReported","faults","logs","formatLogs","thread","method","formatFaults","f","VERSION","pkg"],"mappings":"iFAWMA,EAAMC,EAAa,mBAAmB,EAGtCC,EAAU,oBACVC,EAAa,EACbC,EAAc,QAuBb,MAAMC,CAAe,CAC1B,aAAc,CACZ,KAAK,GAAK,KACV,KAAK,gBAAkB,IAAI,GAC7B,CAWA,MAAM,MAAO,CACX,GAAI,KAAK,GAAI,CACXL,EAAI,MAAM,qCAAqC,EAC/C,MACF,CAEA,OAAO,IAAI,QAAQ,CAACM,EAASC,IAAW,CAEtC,GAAI,OAAO,UAAc,IAAa,CACpC,MAAMC,EAAQ,IAAI,MAAM,yBAAyB,EACjDR,EAAI,MAAM,uDAAuD,EACjEO,EAAOC,CAAK,EACZ,MACF,CAEA,MAAMC,EAAU,UAAU,KAAKP,EAASC,CAAU,EAElDM,EAAQ,QAAU,IAAM,CACtB,MAAMD,EAAQ,IAAI,MAAM,6BAA6BC,E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
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{L as p,a as m,R as L}from"./main-DvteKhS8.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./index-leM889oV.js";import"./widget-html-BAV4ZZd8.js";const o="0.6.1",r={version:o},a=r.version;export{p as LayoutPool,m as LayoutTranslator,L as RendererLite,a as VERSION};
|
|
2
|
-
//# sourceMappingURL=index-Cq9aOTTR.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-D81Qhc3r.js","sources":["../../../xmds/src/index.js"],"sourcesContent":["// @xiboplayer/xmds - XMDS clients (REST and SOAP)\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { RestClient } from './rest-client.js';\nexport { XmdsClient } from './xmds-client.js';\nexport { parseScheduleResponse } from './schedule-parser.js';\n"],"names":["VERSION","pkg"],"mappings":"sHAEaA,EAAUC,EAAI"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{I as n,O as i,S as l,b as p,c as d,p as S,s as h}from"./main-DvteKhS8.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./index-leM889oV.js";import"./widget-html-BAV4ZZd8.js";const e="0.6.1",r={version:e},t=r.version;export{n as InterruptScheduler,i as OverlayScheduler,l as ScheduleManager,t as VERSION,p as buildScheduleQueue,d as calculateTimeline,S as parseLayoutDuration,h as scheduleManager};
|
|
2
|
-
//# sourceMappingURL=index-Dj2ND9Mx.js.map
|