@xiboplayer/pwa 0.7.2 → 0.7.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.
Files changed (51) hide show
  1. package/dist/assets/{chunk-config-BqpCSJ87.js → chunk-config-CzWpgWbQ.js} +2 -2
  2. package/dist/assets/{chunk-config-BqpCSJ87.js.map → chunk-config-CzWpgWbQ.js.map} +1 -1
  3. package/dist/assets/index-18pbixOP.js +2 -0
  4. package/dist/assets/index-18pbixOP.js.map +1 -0
  5. package/dist/assets/{index-DNyHrXGf.js → index-B39fmBsd.js} +2 -2
  6. package/dist/assets/{index-DNyHrXGf.js.map → index-B39fmBsd.js.map} +1 -1
  7. package/dist/assets/{index-Bj01q2d4.js → index-C6m4trc1.js} +2 -2
  8. package/dist/assets/{index-Bj01q2d4.js.map → index-C6m4trc1.js.map} +1 -1
  9. package/dist/assets/{index-DPUPuUO8.js → index-CeqXK1Dq.js} +2 -2
  10. package/dist/assets/{index-DPUPuUO8.js.map → index-CeqXK1Dq.js.map} +1 -1
  11. package/dist/assets/index-CupWhQ-K.js +13 -0
  12. package/dist/assets/index-CupWhQ-K.js.map +1 -0
  13. package/dist/assets/index-Cv2QuVar.js +5 -0
  14. package/dist/assets/index-Cv2QuVar.js.map +1 -0
  15. package/dist/assets/{index-O4mn_OO0.js → index-D8A7foI9.js} +2 -2
  16. package/dist/assets/{index-O4mn_OO0.js.map → index-D8A7foI9.js.map} +1 -1
  17. package/dist/assets/{index-mYGuS183.js → index-Jbffurcq.js} +2 -2
  18. package/dist/assets/{index-mYGuS183.js.map → index-Jbffurcq.js.map} +1 -1
  19. package/dist/assets/index-N5JuX9oW.js +2 -0
  20. package/dist/assets/{index-DwQpyIXq.js.map → index-N5JuX9oW.js.map} +1 -1
  21. package/dist/assets/{index-zursmDNN.js → index-katGA0CR.js} +2 -2
  22. package/dist/assets/{index-zursmDNN.js.map → index-katGA0CR.js.map} +1 -1
  23. package/dist/assets/main-DmDlxZTo.js +736 -0
  24. package/dist/assets/main-DmDlxZTo.js.map +1 -0
  25. package/dist/assets/protocol-detector-BEOLJeK0.js +16 -0
  26. package/dist/assets/protocol-detector-BEOLJeK0.js.map +1 -0
  27. package/dist/assets/setup-Du8FebQP.js +2 -0
  28. package/dist/assets/setup-Du8FebQP.js.map +1 -0
  29. package/dist/assets/{sync-manager-4de0XUYN.js → sync-manager-CJz1dJMb.js} +2 -2
  30. package/dist/assets/{sync-manager-4de0XUYN.js.map → sync-manager-CJz1dJMb.js.map} +1 -1
  31. package/dist/assets/widget-html-D7RpRI2G.js +2 -0
  32. package/dist/assets/widget-html-D7RpRI2G.js.map +1 -0
  33. package/dist/index.html +3 -3
  34. package/dist/setup.html +3 -3
  35. package/dist/sw-pwa.js +1 -1
  36. package/package.json +16 -16
  37. package/dist/assets/index-BBp7Yeqp.js +0 -13
  38. package/dist/assets/index-BBp7Yeqp.js.map +0 -1
  39. package/dist/assets/index-BGzZpdzW.js +0 -2
  40. package/dist/assets/index-BGzZpdzW.js.map +0 -1
  41. package/dist/assets/index-BmnGgxhy.js +0 -5
  42. package/dist/assets/index-BmnGgxhy.js.map +0 -1
  43. package/dist/assets/index-DwQpyIXq.js +0 -2
  44. package/dist/assets/main-Ddgs1h5h.js +0 -736
  45. package/dist/assets/main-Ddgs1h5h.js.map +0 -1
  46. package/dist/assets/protocol-detector-UOvkmuFn.js +0 -16
  47. package/dist/assets/protocol-detector-UOvkmuFn.js.map +0 -1
  48. package/dist/assets/setup-DcthBcbI.js +0 -2
  49. package/dist/assets/setup-DcthBcbI.js.map +0 -1
  50. package/dist/assets/widget-html-p3dC5HGH.js +0 -2
  51. package/dist/assets/widget-html-p3dC5HGH.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sync-manager-4de0XUYN.js","sources":["../../../sync/src/bc-transport.js","../../../sync/src/ws-transport.js","../../../sync/src/choreography.js","../../../sync/src/sync-manager.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * BroadcastChannelTransport — same-machine sync transport\n *\n * Wraps the browser BroadcastChannel API behind the sync transport interface.\n * Used for multi-tab / multi-window sync on a single device.\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nconst DEFAULT_CHANNEL = 'xibo-sync';\n\nexport class BroadcastChannelTransport {\n /**\n * @param {string} [channelName='xibo-sync']\n */\n constructor(channelName = DEFAULT_CHANNEL) {\n this.channel = new BroadcastChannel(channelName);\n this._connected = true;\n }\n\n /**\n * Send a message to all other tabs/windows on this channel.\n * @param {Object} msg — plain object (structured-cloned by BroadcastChannel)\n */\n send(msg) {\n if (!this.channel) return;\n this.channel.postMessage(msg);\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the message data (already deserialized)\n */\n onMessage(callback) {\n this.channel.onmessage = (e) => callback(e.data);\n }\n\n /** Close the channel. */\n close() {\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n this._connected = false;\n }\n\n /** @returns {boolean} Whether the channel is open */\n get connected() {\n return this._connected && !!this.channel;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * WebSocketTransport — cross-device sync transport\n *\n * Connects to the lead player's proxy WebSocket relay at /sync.\n * Used for LAN video walls where each screen is a separate device.\n *\n * Features:\n * - Auto-reconnect with exponential backoff (1s → 2s → 4s → max 30s)\n * - JSON serialization (WebSocket sends strings, not structured clones)\n * - Same transport interface as BroadcastChannelTransport\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst INITIAL_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 30000;\nconst BACKOFF_FACTOR = 2;\n\nexport class WebSocketTransport {\n /**\n * @param {string} url — WebSocket URL, e.g. ws://192.168.1.100:8765/sync\n * @param {Object} [options]\n * @param {string} [options.syncGroup] — group name for relay isolation\n * @param {string} [options.displayId] — this display's unique ID\n * @param {Object} [options.topology] — this display's topology { x, y, orientation? }\n * @param {string} [options.token] — auth token for relay join validation\n */\n constructor(url, { syncGroup, displayId, topology, token } = {}) {\n this._url = url;\n this._syncGroup = syncGroup || null;\n this._displayId = displayId || null;\n this._topology = topology || null;\n this._token = token || null;\n this._callback = null;\n this._closed = false;\n this._retryMs = INITIAL_RETRY_MS;\n this._retryTimer = null;\n this._log = createLogger('WS-Sync');\n this.ws = null;\n\n this._connect();\n }\n\n /**\n * Send a message to the relay (which broadcasts to other clients).\n * @param {Object} msg — plain object (JSON-serialized for WebSocket)\n */\n send(msg) {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the parsed message object\n */\n onMessage(callback) {\n this._callback = callback;\n }\n\n /** Close the connection and stop reconnecting. */\n close() {\n this._closed = true;\n if (this._retryTimer) {\n clearTimeout(this._retryTimer);\n this._retryTimer = null;\n }\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /** @returns {boolean} Whether the WebSocket is open */\n get connected() {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** @private */\n _connect() {\n if (this._closed) return;\n\n try {\n this.ws = new WebSocket(this._url);\n } catch (e) {\n this._log.error('WebSocket creation failed:', e.message);\n this._scheduleReconnect();\n return;\n }\n\n this.ws.onopen = () => {\n this._log.info(`Connected to ${this._url}`);\n this._retryMs = INITIAL_RETRY_MS; // Reset backoff on success\n\n // Join sync group for relay isolation (+ topology for auto-detection)\n if (this._syncGroup) {\n const join = { type: 'join', syncGroup: this._syncGroup };\n if (this._displayId) join.displayId = this._displayId;\n if (this._topology) join.topology = this._topology;\n if (this._token) join.token = this._token;\n this.ws.send(JSON.stringify(join));\n }\n };\n\n this.ws.onmessage = async (event) => {\n if (!this._callback) return;\n try {\n // Browser WebSocket delivers string; Node ws delivers Buffer;\n // Node 22+ native WebSocket delivers Blob. Handle all three.\n let raw = event.data;\n if (typeof raw !== 'string') {\n raw = (raw instanceof Blob) ? await raw.text() : String(raw);\n }\n const msg = JSON.parse(raw);\n this._callback(msg);\n } catch (e) {\n this._log.warn('Failed to parse message:', e.message);\n }\n };\n\n this.ws.onclose = () => {\n if (!this._closed) {\n this._log.info('Connection closed — will reconnect');\n this._scheduleReconnect();\n }\n };\n\n this.ws.onerror = (e) => {\n // onclose will fire after onerror, triggering reconnect\n this._log.warn('WebSocket error');\n };\n }\n\n /** @private */\n _scheduleReconnect() {\n if (this._closed || this._retryTimer) return;\n\n this._log.info(`Reconnecting in ${this._retryMs}ms...`);\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._connect();\n }, this._retryMs);\n\n this._retryMs = Math.min(this._retryMs * BACKOFF_FACTOR, MAX_RETRY_MS);\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Transition choreography — compute stagger delays for cascading\n * layout transitions across multiple displays.\n *\n * Supports two modes:\n *\n * 1D mode (position-based):\n * Displays are numbered 0..N-1 in a row. Simple linear choreographies.\n * Config: { position, totalDisplays }\n *\n * 2D mode (topology-based):\n * Each display has (x, y) coordinates and an orientation vector.\n * Enables directional sweeps, diagonal cascades, and radial effects.\n * Config: { topology: { x, y, orientation? }, gridCols, gridRows }\n *\n * Topology format:\n * { x: 1, y: 0, orientation: 0 }\n * - x, y: grid coordinates (0-indexed)\n * - orientation: degrees clockwise from upright (0=landscape, 90=portrait-right,\n * 180=inverted, 270=portrait-left). Defaults to 0.\n *\n * Choreographies:\n * simultaneous — all at once (default, no delay)\n * wave-right — sweep left to right (by x)\n * wave-left — sweep right to left (by x)\n * wave-down — sweep top to bottom (by y, 2D only)\n * wave-up — sweep bottom to top (by y, 2D only)\n * diagonal-tl — cascade from top-left corner (2D only)\n * diagonal-tr — cascade from top-right corner (2D only)\n * diagonal-bl — cascade from bottom-left corner (2D only)\n * diagonal-br — cascade from bottom-right corner (2D only)\n * center-out — explode from center to edges\n * outside-in — implode from edges to center\n * random — random delay per display\n *\n * @module @xiboplayer/sync/choreography\n */\n\n/**\n * Compute the stagger delay for a display.\n *\n * @param {Object} options\n * @param {string} options.choreography — choreography name\n * @param {number} [options.position] — 1D: this display's 0-indexed position\n * @param {number} [options.totalDisplays] — 1D: total displays in the group\n * @param {Object} [options.topology] — 2D: this display's topology { x, y, orientation? }\n * @param {number} [options.gridCols] — 2D: grid width (columns)\n * @param {number} [options.gridRows] — 2D: grid height (rows)\n * @param {number} options.staggerMs — base delay between consecutive displays (ms)\n * @returns {number} delay in ms before this display should execute its transition\n *\n * @example\n * // 1D: 4 displays, wave-right with 150ms stagger\n * computeStagger({ choreography: 'wave-right', position: 2, totalDisplays: 4, staggerMs: 150 })\n * // → 300\n *\n * @example\n * // 2D: 3×2 grid, diagonal from top-left\n * computeStagger({\n * choreography: 'diagonal-tl',\n * topology: { x: 2, y: 1 },\n * gridCols: 3, gridRows: 2,\n * staggerMs: 100,\n * })\n * // → 300 (Manhattan distance 2+1=3, so 3×100)\n */\nexport function computeStagger({ choreography, position, totalDisplays, topology, gridCols, gridRows, staggerMs }) {\n if (!choreography || choreography === 'simultaneous' || !staggerMs) {\n return 0;\n }\n\n // 2D mode: topology with grid dimensions\n if (topology && gridCols != null && gridRows != null) {\n if (gridCols <= 1 && gridRows <= 1) return 0;\n return _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs);\n }\n\n // 1D mode: position-based\n if (totalDisplays == null || totalDisplays <= 1) return 0;\n return _computeStagger1D(choreography, position ?? 0, totalDisplays, staggerMs);\n}\n\n/** @private 1D stagger computation */\nfunction _computeStagger1D(choreography, position, totalDisplays, staggerMs) {\n const last = totalDisplays - 1;\n const center = last / 2;\n\n switch (choreography) {\n case 'wave-right':\n return position * staggerMs;\n\n case 'wave-left':\n return (last - position) * staggerMs;\n\n case 'center-out':\n return Math.round(Math.abs(position - center)) * staggerMs;\n\n case 'outside-in': {\n const maxDist = Math.round(center);\n return (maxDist - Math.round(Math.abs(position - center))) * staggerMs;\n }\n\n case 'random':\n return Math.floor(Math.random() * last * staggerMs);\n\n default:\n return 0;\n }\n}\n\n/** @private 2D stagger computation */\nfunction _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs) {\n const { x, y } = topology;\n const maxX = gridCols - 1;\n const maxY = gridRows - 1;\n const centerX = maxX / 2;\n const centerY = maxY / 2;\n\n switch (choreography) {\n // Axis-aligned sweeps\n case 'wave-right':\n return x * staggerMs;\n\n case 'wave-left':\n return (maxX - x) * staggerMs;\n\n case 'wave-down':\n return y * staggerMs;\n\n case 'wave-up':\n return (maxY - y) * staggerMs;\n\n // Corner diagonals (Manhattan distance from corner)\n case 'diagonal-tl':\n return (x + y) * staggerMs;\n\n case 'diagonal-tr':\n return ((maxX - x) + y) * staggerMs;\n\n case 'diagonal-bl':\n return (x + (maxY - y)) * staggerMs;\n\n case 'diagonal-br':\n return ((maxX - x) + (maxY - y)) * staggerMs;\n\n // Radial patterns (Euclidean distance from center)\n case 'center-out': {\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return Math.round(dist) * staggerMs;\n }\n\n case 'outside-in': {\n const maxDist = Math.round(Math.sqrt(centerX ** 2 + centerY ** 2));\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return (maxDist - Math.round(dist)) * staggerMs;\n }\n\n case 'random': {\n const maxSteps = maxX + maxY; // Manhattan extent\n return Math.floor(Math.random() * maxSteps * staggerMs);\n }\n\n default:\n return 0;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * SyncManager - Multi-display synchronization\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * (same machine via BroadcastChannel) or across devices on a LAN\n * (via WebSocket relay on the lead's proxy server).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * Transport:\n * Pluggable — BroadcastChannelTransport (same-machine) or\n * WebSocketTransport (cross-device via relay). Selected automatically\n * based on syncConfig.relayUrl.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (used for WebSocket relay URL)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n * @property {string} [relayUrl] - WebSocket relay URL for cross-device sync\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { BroadcastChannelTransport } from './bc-transport.js';\nimport { WebSocketTransport } from './ws-transport.js';\n\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Object} [options.transport] - Optional pre-built transport (for testing)\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n this.onGroupUpdate = options.onGroupUpdate || null;\n\n // State\n this.transport = options.transport || null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /** Backward-compatible alias for transport */\n get channel() { return this.transport; }\n set channel(v) { this.transport = v; }\n\n /**\n * Start the sync manager — selects transport, begins heartbeats.\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n // Select transport if none injected\n if (!this.transport) {\n if (this.syncConfig.relayUrl) {\n this.transport = new WebSocketTransport(this.syncConfig.relayUrl, {\n syncGroup: this.syncConfig.syncGroup,\n displayId: this.displayId,\n topology: this.syncConfig.topology,\n token: this.syncConfig.syncToken,\n });\n } else if (typeof BroadcastChannel !== 'undefined') {\n this.transport = new BroadcastChannelTransport();\n } else {\n this._log.warn('No transport available — sync disabled');\n return;\n }\n }\n\n this.transport.onMessage((msg) => this._handleMessage(msg));\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info('Started. DisplayId:', this.displayId,\n this.syncConfig.relayUrl ? `(relay: ${this.syncConfig.relayUrl})` : '(BroadcastChannel)');\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.transport) {\n this.transport.close();\n this.transport = null;\n }\n\n this.followers.clear();\n this._log.info('Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn('requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark active followers as not-ready for this layout (skip stale ones)\n for (const [, follower] of this.followers) {\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info(`Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info(`Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info(`Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Relay-originated messages (no displayId)\n if (msg.type === 'group-update') {\n this._log.info(`Group update: ${msg.totalDisplays} displays`);\n if (this.onGroupUpdate) {\n this.onGroupUpdate(msg.totalDisplays, msg.topology || {});\n }\n return;\n }\n\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info(`Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info(`Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info(`Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn('Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info(`Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info(`Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info('All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn(`Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info(`Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.transport) return;\n try {\n this.transport.send(msg);\n } catch (e) {\n this._log.error('Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n transport: this.syncConfig.relayUrl ? 'websocket' : 'broadcast-channel',\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n\nexport { BroadcastChannelTransport } from './bc-transport.js';\nexport { WebSocketTransport } from './ws-transport.js';\nexport { computeStagger } from './choreography.js';\n"],"names":["DEFAULT_CHANNEL","BroadcastChannelTransport","channelName","msg","callback","INITIAL_RETRY_MS","MAX_RETRY_MS","BACKOFF_FACTOR","WebSocketTransport","url","syncGroup","displayId","topology","token","createLogger","_a","e","join","event","raw","computeStagger","choreography","position","totalDisplays","gridCols","gridRows","staggerMs","_computeStagger2D","_computeStagger1D","last","center","x","y","maxX","maxY","centerX","centerY","dist","maxDist","maxSteps","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","v","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"mDAWA,MAAMA,EAAkB,YAEjB,MAAMC,CAA0B,CAIrC,YAAYC,EA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OW,CAAE,EAG9B,CAGA,MAAMvD,EAAK,CACT,GAAK,KAAK,UACV,GAAI,CACF,KAAK,UAAU,KAAKA,CAAG,CACzB,OAAS,EAAG,CACV,KAAK,KAAK,MAAM,kBAAmB,CAAC,CACtC,CACF,CAQA,WAAY,CACV,MAAO,CACL,QAAS,KAAK,SACd,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,UAAW,KAAK,UAAU,KAC1B,gBAAiB,KAAK,iBACtB,UAAW,KAAK,WAAW,SAAW,YAAc,oBACpD,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACuD,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWlB,CACzC,EAAQ,CACR,CACE,CACF"}
1
+ {"version":3,"file":"sync-manager-CJz1dJMb.js","sources":["../../../sync/src/bc-transport.js","../../../sync/src/ws-transport.js","../../../sync/src/choreography.js","../../../sync/src/sync-manager.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * BroadcastChannelTransport — same-machine sync transport\n *\n * Wraps the browser BroadcastChannel API behind the sync transport interface.\n * Used for multi-tab / multi-window sync on a single device.\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nconst DEFAULT_CHANNEL = 'xibo-sync';\n\nexport class BroadcastChannelTransport {\n /**\n * @param {string} [channelName='xibo-sync']\n */\n constructor(channelName = DEFAULT_CHANNEL) {\n this.channel = new BroadcastChannel(channelName);\n this._connected = true;\n }\n\n /**\n * Send a message to all other tabs/windows on this channel.\n * @param {Object} msg — plain object (structured-cloned by BroadcastChannel)\n */\n send(msg) {\n if (!this.channel) return;\n this.channel.postMessage(msg);\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the message data (already deserialized)\n */\n onMessage(callback) {\n this.channel.onmessage = (e) => callback(e.data);\n }\n\n /** Close the channel. */\n close() {\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n this._connected = false;\n }\n\n /** @returns {boolean} Whether the channel is open */\n get connected() {\n return this._connected && !!this.channel;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * WebSocketTransport — cross-device sync transport\n *\n * Connects to the lead player's proxy WebSocket relay at /sync.\n * Used for LAN video walls where each screen is a separate device.\n *\n * Features:\n * - Auto-reconnect with exponential backoff (1s → 2s → 4s → max 30s)\n * - JSON serialization (WebSocket sends strings, not structured clones)\n * - Same transport interface as BroadcastChannelTransport\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst INITIAL_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 30000;\nconst BACKOFF_FACTOR = 2;\n\nexport class WebSocketTransport {\n /**\n * @param {string} url — WebSocket URL, e.g. ws://192.168.1.100:8765/sync\n * @param {Object} [options]\n * @param {string} [options.syncGroup] — group name for relay isolation\n * @param {string} [options.displayId] — this display's unique ID\n * @param {Object} [options.topology] — this display's topology { x, y, orientation? }\n * @param {string} [options.token] — auth token for relay join validation\n */\n constructor(url, { syncGroup, displayId, topology, token } = {}) {\n this._url = url;\n this._syncGroup = syncGroup || null;\n this._displayId = displayId || null;\n this._topology = topology || null;\n this._token = token || null;\n this._callback = null;\n this._closed = false;\n this._retryMs = INITIAL_RETRY_MS;\n this._retryTimer = null;\n this._log = createLogger('WS-Sync');\n this.ws = null;\n\n this._connect();\n }\n\n /**\n * Send a message to the relay (which broadcasts to other clients).\n * @param {Object} msg — plain object (JSON-serialized for WebSocket)\n */\n send(msg) {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the parsed message object\n */\n onMessage(callback) {\n this._callback = callback;\n }\n\n /** Close the connection and stop reconnecting. */\n close() {\n this._closed = true;\n if (this._retryTimer) {\n clearTimeout(this._retryTimer);\n this._retryTimer = null;\n }\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /** @returns {boolean} Whether the WebSocket is open */\n get connected() {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** @private */\n _connect() {\n if (this._closed) return;\n\n try {\n this.ws = new WebSocket(this._url);\n } catch (e) {\n this._log.error('WebSocket creation failed:', e.message);\n this._scheduleReconnect();\n return;\n }\n\n this.ws.onopen = () => {\n this._log.info(`Connected to ${this._url}`);\n this._retryMs = INITIAL_RETRY_MS; // Reset backoff on success\n\n // Join sync group for relay isolation (+ topology for auto-detection)\n if (this._syncGroup) {\n const join = { type: 'join', syncGroup: this._syncGroup };\n if (this._displayId) join.displayId = this._displayId;\n if (this._topology) join.topology = this._topology;\n if (this._token) join.token = this._token;\n this.ws.send(JSON.stringify(join));\n }\n };\n\n this.ws.onmessage = async (event) => {\n if (!this._callback) return;\n try {\n // Browser WebSocket delivers string; Node ws delivers Buffer;\n // Node 22+ native WebSocket delivers Blob. Handle all three.\n let raw = event.data;\n if (typeof raw !== 'string') {\n raw = (raw instanceof Blob) ? await raw.text() : String(raw);\n }\n const msg = JSON.parse(raw);\n this._callback(msg);\n } catch (e) {\n this._log.warn('Failed to parse message:', e.message);\n }\n };\n\n this.ws.onclose = () => {\n if (!this._closed) {\n this._log.info('Connection closed — will reconnect');\n this._scheduleReconnect();\n }\n };\n\n this.ws.onerror = (e) => {\n // onclose will fire after onerror, triggering reconnect\n this._log.warn('WebSocket error');\n };\n }\n\n /** @private */\n _scheduleReconnect() {\n if (this._closed || this._retryTimer) return;\n\n this._log.info(`Reconnecting in ${this._retryMs}ms...`);\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._connect();\n }, this._retryMs);\n\n this._retryMs = Math.min(this._retryMs * BACKOFF_FACTOR, MAX_RETRY_MS);\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Transition choreography — compute stagger delays for cascading\n * layout transitions across multiple displays.\n *\n * Supports two modes:\n *\n * 1D mode (position-based):\n * Displays are numbered 0..N-1 in a row. Simple linear choreographies.\n * Config: { position, totalDisplays }\n *\n * 2D mode (topology-based):\n * Each display has (x, y) coordinates and an orientation vector.\n * Enables directional sweeps, diagonal cascades, and radial effects.\n * Config: { topology: { x, y, orientation? }, gridCols, gridRows }\n *\n * Topology format:\n * { x: 1, y: 0, orientation: 0 }\n * - x, y: grid coordinates (0-indexed)\n * - orientation: degrees clockwise from upright (0=landscape, 90=portrait-right,\n * 180=inverted, 270=portrait-left). Defaults to 0.\n *\n * Choreographies:\n * simultaneous — all at once (default, no delay)\n * wave-right — sweep left to right (by x)\n * wave-left — sweep right to left (by x)\n * wave-down — sweep top to bottom (by y, 2D only)\n * wave-up — sweep bottom to top (by y, 2D only)\n * diagonal-tl — cascade from top-left corner (2D only)\n * diagonal-tr — cascade from top-right corner (2D only)\n * diagonal-bl — cascade from bottom-left corner (2D only)\n * diagonal-br — cascade from bottom-right corner (2D only)\n * center-out — explode from center to edges\n * outside-in — implode from edges to center\n * random — random delay per display\n *\n * @module @xiboplayer/sync/choreography\n */\n\n/**\n * Compute the stagger delay for a display.\n *\n * @param {Object} options\n * @param {string} options.choreography — choreography name\n * @param {number} [options.position] — 1D: this display's 0-indexed position\n * @param {number} [options.totalDisplays] — 1D: total displays in the group\n * @param {Object} [options.topology] — 2D: this display's topology { x, y, orientation? }\n * @param {number} [options.gridCols] — 2D: grid width (columns)\n * @param {number} [options.gridRows] — 2D: grid height (rows)\n * @param {number} options.staggerMs — base delay between consecutive displays (ms)\n * @returns {number} delay in ms before this display should execute its transition\n *\n * @example\n * // 1D: 4 displays, wave-right with 150ms stagger\n * computeStagger({ choreography: 'wave-right', position: 2, totalDisplays: 4, staggerMs: 150 })\n * // → 300\n *\n * @example\n * // 2D: 3×2 grid, diagonal from top-left\n * computeStagger({\n * choreography: 'diagonal-tl',\n * topology: { x: 2, y: 1 },\n * gridCols: 3, gridRows: 2,\n * staggerMs: 100,\n * })\n * // → 300 (Manhattan distance 2+1=3, so 3×100)\n */\nexport function computeStagger({ choreography, position, totalDisplays, topology, gridCols, gridRows, staggerMs }) {\n if (!choreography || choreography === 'simultaneous' || !staggerMs) {\n return 0;\n }\n\n // 2D mode: topology with grid dimensions\n if (topology && gridCols != null && gridRows != null) {\n if (gridCols <= 1 && gridRows <= 1) return 0;\n return _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs);\n }\n\n // 1D mode: position-based\n if (totalDisplays == null || totalDisplays <= 1) return 0;\n return _computeStagger1D(choreography, position ?? 0, totalDisplays, staggerMs);\n}\n\n/** @private 1D stagger computation */\nfunction _computeStagger1D(choreography, position, totalDisplays, staggerMs) {\n const last = totalDisplays - 1;\n const center = last / 2;\n\n switch (choreography) {\n case 'wave-right':\n return position * staggerMs;\n\n case 'wave-left':\n return (last - position) * staggerMs;\n\n case 'center-out':\n return Math.round(Math.abs(position - center)) * staggerMs;\n\n case 'outside-in': {\n const maxDist = Math.round(center);\n return (maxDist - Math.round(Math.abs(position - center))) * staggerMs;\n }\n\n case 'random':\n return Math.floor(Math.random() * last * staggerMs);\n\n default:\n return 0;\n }\n}\n\n/** @private 2D stagger computation */\nfunction _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs) {\n const { x, y } = topology;\n const maxX = gridCols - 1;\n const maxY = gridRows - 1;\n const centerX = maxX / 2;\n const centerY = maxY / 2;\n\n switch (choreography) {\n // Axis-aligned sweeps\n case 'wave-right':\n return x * staggerMs;\n\n case 'wave-left':\n return (maxX - x) * staggerMs;\n\n case 'wave-down':\n return y * staggerMs;\n\n case 'wave-up':\n return (maxY - y) * staggerMs;\n\n // Corner diagonals (Manhattan distance from corner)\n case 'diagonal-tl':\n return (x + y) * staggerMs;\n\n case 'diagonal-tr':\n return ((maxX - x) + y) * staggerMs;\n\n case 'diagonal-bl':\n return (x + (maxY - y)) * staggerMs;\n\n case 'diagonal-br':\n return ((maxX - x) + (maxY - y)) * staggerMs;\n\n // Radial patterns (Euclidean distance from center)\n case 'center-out': {\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return Math.round(dist) * staggerMs;\n }\n\n case 'outside-in': {\n const maxDist = Math.round(Math.sqrt(centerX ** 2 + centerY ** 2));\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return (maxDist - Math.round(dist)) * staggerMs;\n }\n\n case 'random': {\n const maxSteps = maxX + maxY; // Manhattan extent\n return Math.floor(Math.random() * maxSteps * staggerMs);\n }\n\n default:\n return 0;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * SyncManager - Multi-display synchronization\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * (same machine via BroadcastChannel) or across devices on a LAN\n * (via WebSocket relay on the lead's proxy server).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * Transport:\n * Pluggable — BroadcastChannelTransport (same-machine) or\n * WebSocketTransport (cross-device via relay). Selected automatically\n * based on syncConfig.relayUrl.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (used for WebSocket relay URL)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n * @property {string} [relayUrl] - WebSocket relay URL for cross-device sync\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { BroadcastChannelTransport } from './bc-transport.js';\nimport { WebSocketTransport } from './ws-transport.js';\n\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Object} [options.transport] - Optional pre-built transport (for testing)\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n this.onGroupUpdate = options.onGroupUpdate || null;\n\n // State\n this.transport = options.transport || null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /** Backward-compatible alias for transport */\n get channel() { return this.transport; }\n set channel(v) { this.transport = v; }\n\n /**\n * Start the sync manager — selects transport, begins heartbeats.\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n // Select transport if none injected\n if (!this.transport) {\n if (this.syncConfig.relayUrl) {\n this.transport = new WebSocketTransport(this.syncConfig.relayUrl, {\n syncGroup: this.syncConfig.syncGroup,\n displayId: this.displayId,\n topology: this.syncConfig.topology,\n token: this.syncConfig.syncToken,\n });\n } else if (typeof BroadcastChannel !== 'undefined') {\n this.transport = new BroadcastChannelTransport();\n } else {\n this._log.warn('No transport available — sync disabled');\n return;\n }\n }\n\n this.transport.onMessage((msg) => this._handleMessage(msg));\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info('Started. DisplayId:', this.displayId,\n this.syncConfig.relayUrl ? `(relay: ${this.syncConfig.relayUrl})` : '(BroadcastChannel)');\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.transport) {\n this.transport.close();\n this.transport = null;\n }\n\n this.followers.clear();\n this._log.info('Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn('requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark active followers as not-ready for this layout (skip stale ones)\n for (const [, follower] of this.followers) {\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info(`Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info(`Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info(`Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Relay-originated messages (no displayId)\n if (msg.type === 'group-update') {\n this._log.info(`Group update: ${msg.totalDisplays} displays`);\n if (this.onGroupUpdate) {\n this.onGroupUpdate(msg.totalDisplays, msg.topology || {});\n }\n return;\n }\n\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info(`Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info(`Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info(`Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn('Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info(`Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info(`Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info('All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn(`Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info(`Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.transport) return;\n try {\n this.transport.send(msg);\n } catch (e) {\n this._log.error('Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n transport: this.syncConfig.relayUrl ? 'websocket' : 'broadcast-channel',\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n\nexport { BroadcastChannelTransport } from './bc-transport.js';\nexport { WebSocketTransport } from './ws-transport.js';\nexport { computeStagger } from './choreography.js';\n"],"names":["DEFAULT_CHANNEL","BroadcastChannelTransport","channelName","msg","callback","INITIAL_RETRY_MS","MAX_RETRY_MS","BACKOFF_FACTOR","WebSocketTransport","url","syncGroup","displayId","topology","token","createLogger","_a","e","join","event","raw","computeStagger","choreography","position","totalDisplays","gridCols","gridRows","staggerMs","_computeStagger2D","_computeStagger1D","last","center","x","y","maxX","maxY","centerX","centerY","dist","maxDist","maxSteps","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","v","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"mDAWA,MAAMA,EAAkB,YAEjB,MAAMC,CAA0B,CAIrC,YAAYC,EAAcF,EAAiB,CACzC,KAAK,QAAU,IAAI,iBAAiBE,CAAW,EAC/C,KAAK,WAAa,EACpB,CAMA,KAAKC,EAAK,CACH,KAAK,SACV,KAAK,QAAQ,YAAYA,CAAG,CAC9B,CAMA,UAAUC,EAAU,CAClB,KAAK,QAAQ,UAAa,GAAMA,EAAS,EAAE,IAAI,CACjD,CAGA,OAAQ,CACF,KAAK,UACP,KAAK,QAAQ,MAAK,EAClB,KAAK,QAAU,MAEjB,KAAK,WAAa,EACpB,CAGA,IAAI,WAAY,CACd,OAAO,KAAK,YAAc,CAAC,CAAC,KAAK,OACnC,CACF,CClCA,MAAMC,EAAmB,IACnBC,EAAe,IACfC,EAAiB,EAEhB,MAAMC,CAAmB,CAS9B,YAAYC,EAAK,CAAE,UAAAC,EAAW,UAAAC,EAAW,SAAAC,EAAU,M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WlB,CACzC,EAAQ,CACR,CACE,CACF"}
@@ -0,0 +1,2 @@
1
+ import{createLogger as T,PLAYER_API as $}from"./index-Cv2QuVar.js";const B=T("Cache");class R{constructor(){this.dependants=new Map}addDependant(e,s){const t=String(e);this.dependants.has(t)||this.dependants.set(t,new Set),this.dependants.get(t).add(String(s))}removeLayoutDependants(e){const s=String(e),t=[];for(const[n,r]of this.dependants)r.delete(s),r.size===0&&(this.dependants.delete(n),t.push(n));return t.length>0&&B.info(`${t.length} media files orphaned after layout ${e} removed:`,t),t}isMediaReferenced(e){const s=this.dependants.get(String(e));return s?s.size>0:!1}async clearAll(){this.dependants.clear()}}const O=new R,_=T("StoreClient");class N{async has(e,s){try{const t=await fetch(`/store/${e}/${s}`,{method:"HEAD"});if(t.ok)return!0;if(t.status===404)return!1;const n=new Error(`Store error: ${t.status}`);throw n.status=t.status,_.warn(`has(${e}/${s}): unexpected status ${t.status}`),n}catch(t){throw t.status||t.name==="AbortError"||t.name==="TimeoutError"||_.warn(`has(${e}/${s}): network error — ${t.message}`),t}}async get(e,s){var t;try{const n=await fetch(`/store/${e}/${s}`);if(!n.ok){if((t=n.body)==null||t.cancel(),n.status===404)return null;throw new Error(`Failed to get file: ${n.status}`)}return await n.blob()}catch(n){return _.error("get error:",n.message),null}}async put(e,s,t,n="application/octet-stream"){var r;try{const i=await fetch(`/store/${e}/${s}`,{method:"PUT",headers:{"Content-Type":n},body:t});return(r=i.body)==null||r.cancel(),i.ok}catch(i){return _.error("put error:",i.message),!1}}async remove(e){try{const t=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(s){return _.error("remove error:",s.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return _.error("list error:",e.message),[]}}}const b={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 v(d){return b[d]||b.media}const l=T("Download"),P=6,S=50*1024*1024,A=3,M=100*1024*1024,Q=2,D=6e5,z=15e3;function U(d){var n,r;const s=(r=(n=(d.path||d.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:r.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"}[s]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},m=Symbol("BARRIER");function C(d){try{const e=d.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function F(d,e=30){const s=C(d);return s===1/0?!1:Date.now()/1e3>=s-e}class x{constructor(e,s={}){this.fileInfo=e,this.chunkIndex=s.chunkIndex??null,this.rangeStart=s.rangeStart??null,this.rangeEnd=s.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal,this._typeConfig=v(e.type)}getUrl(){const e=this.fileInfo.path;if(F(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 t;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)),this.fileInfo.cmsDownloadUrl&&(e["X-Cms-Download-Url"]=this.fileInfo.cmsDownloadUrl);const s=this._typeConfig.maxRetries;for(let n=1;n<=s;n++){const r=new AbortController,i=setTimeout(()=>r.abort(),D);try{const a=this.getUrl(),h={signal:r.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=r.signal.aborted?`Timeout after ${D/1e3}s`:a.message;if(n<s){const o=((t=this._typeConfig.retryDelays)==null?void 0:t[n-1])??this._typeConfig.retryDelayMs*n,u=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${u} attempt ${n}/${s} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(p=>setTimeout(p,o))}else throw this.state="failed",r.signal.aborted?new Error(h):a}finally{clearTimeout(i)}}}}class E{constructor(e,s={}){this.fileInfo=e,this.options=s,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((t,n)=>{this._resolve=t,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(F(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:s,type:t,size:n}=this.fileInfo;l.info("[FileDownload] Starting:",`${t}/${s}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=U(this.fileInfo);const r=v(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!r){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),z);try{const u=await fetch(a,{method:"HEAD",signal:h.signal});u.ok&&(this.totalBytes=parseInt(u.headers.get("Content-Length")||"0"),this._contentType=u.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const i=this.options.chunkSize||S;if(this.totalBytes>M){const a=[];for(let c=0;c<this.totalBytes;c+=i)a.push({start:c,end:Math.min(c+i-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(c=>!this.skipChunks.has(c.index)),o=a.length-h.length;for(const c of a)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(h.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&l.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const u=o>0;if(u){const c=h.sort((g,k)=>g.index-k.index);for(const g of c){const k=new x(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});k._parentFile=this,k._priority=f.normal,this.tasks.push(k)}}else for(const c of h){const g=new x(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===a.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(c=>c._priority>=f.high).length;l.info(`[FileDownload] ${t}/${s}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(u?" (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(s){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}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(s){l.warn("[FileDownload] onChunkDownloaded callback error:",s)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:s,id:t}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${s}/${t}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${s}/${t}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let i=0;i<this.totalChunks;i++){const a=this._chunkBlobs.get(i);a&&n.push(a)}const r=new Blob(n,{type:this._contentType});l.info("[FileDownload] Complete:",`${s}/${t}`,`(${r.size} bytes, reassembled)`),this._resolve(r)}this._chunkBlobs.clear()}}onTaskFailed(e,s){var t;if(!(this.state==="complete"||this.state==="failed")){if((t=s.message)!=null&&t.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(r=>r!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}l.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}}class L{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const s=q.stableKey(e);if(this.queue.active.has(s)){const n=this.queue.active.get(s);if(e.path&&e.path!==n.fileInfo.path){const r=C(n.fileInfo.path);C(e.path)>r&&(n.fileInfo.path=e.path)}return n}const t=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(s,t),this._filesToPrepare.push(t),t}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let s=0,t=0;const n=()=>{for(;s<this._maxPreparing&&t<this._filesToPrepare.length;){const r=this._filesToPrepare[t++];s++,r.prepare(this).finally(()=>{s--,t>=this._filesToPrepare.length&&s===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var i;const e=[],s=[],t=[],n=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)s.push(a);else{const h=((i=a._parentFile)==null?void 0:i.totalChunks)||0;h>1&&a.chunkIndex===h-1?t.push(a):n.push(a)}e.sort((a,h)=>{var o,u;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((u=h._parentFile)==null?void 0:u.totalBytes)||0)}),n.sort((a,h)=>a.chunkIndex-h.chunkIndex);const r=[...e,...s,...t];return n.length>0&&r.push(m,...n),r}}class q{constructor(e={}){this.concurrency=e.concurrency||P,this.chunkSize=e.chunkSize||S,this.maxChunksPerFile=e.chunksPerFile||A,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 s=q.stableKey(e);if(this.active.has(s)){const n=this.active.get(s);if(e.path&&e.path!==n.fileInfo.path){const r=C(n.fileInfo.path);C(e.path)>r&&(l.info("[DownloadQueue] Refreshing URL for",s),n.fileInfo.path=e.path)}return n}const t=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(s,t),l.info("[DownloadQueue] Enqueued:",s),this._schedulePrepare(t),t}_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 s of e)this.queue.push(s);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let s=0,t=0;for(const n of e)n===m?(this.queue.push(m),t++):(this.queue.push(n),s++);l.info(`[DownloadQueue] Ordered queue: ${s} tasks, ${t} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,s)=>s._priority-e._priority)}prioritizeLayoutFiles(e,s=f.high){var r,i,a,h;const t=new Set(e.map(String));let n=0;for(const o of this.queue){const u=((r=o._parentFile)==null?void 0:r.fileInfo.saveAs)||String((i=o._parentFile)==null?void 0:i.fileInfo.id);t.has(u)&&o._priority<s&&(o._priority=s,n++)}for(const o of this._activeTasks){const u=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);t.has(u)&&o._priority<s&&(o._priority=s)}this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",t.size,"files,",n,"tasks boosted to",s)}urgentChunk(e,s,t){const n=`${e}/${s}`,r=this.active.get(n);if(!r)return l.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",t),!1;if(this._activeTasks.some(o=>o._parentFile===r&&o.chunkIndex===t&&o.state==="downloading")){const o=this._activeTasks.find(u=>u._parentFile===r&&u.chunkIndex===t);return o&&o._priority<f.urgent?(o._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${n} chunk ${t} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",t),!1)}const a=this.queue.findIndex(o=>o!==m&&o._parentFile===r&&o.chunkIndex===t);if(a===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",t),!1;const h=this.queue.splice(a,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${n} chunk ${t} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(r=>r!==m&&r._priority>=f.urgent)||((n=this._activeTasks)==null?void 0:n.some(r=>r._priority>=f.urgent&&r.state==="downloading")),s=e?Q:this.concurrency,t=e?f.urgent:0;for(;this.running<s&&this.queue.length>0;){const r=this.queue[0];if(r===m){if(this.running>0)break;this.queue.shift();continue}if(r._priority<t||!this._canStartTask(r)){let i=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==m;a++){const h=this.queue[a];if(h._priority>=t&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),i=!0;break}}if(!i)break;continue}this.queue.shift(),this._startTask(r)}this.queue.length===0&&this.running===0&&l.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 s=`${e.fileInfo.type}/${e.fileInfo.id}`,t=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${s}${t} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),l.info(`[DownloadQueue] Fetched: ${s}${t} (${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:r,reenqueueDelayMs:i}=e._typeConfig;if(r>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>r){l.error(`[DownloadQueue] ${s} exceeded ${r} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}l.warn(`[DownloadQueue] ${s} failed all retries (attempt ${e._reenqueueCount}/${r}), scheduling re-enqueue in ${i/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),l.info(`[DownloadQueue] ${s} re-enqueued for retry`),this.processQueue()},i);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}removeCompleted(e){const s=this.active.get(e);s&&(s.state==="complete"||s.state==="failed")&&(this.queue=this.queue.filter(t=>t===m||t._parentFile!==s),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[s,t]of this.active.entries())t.state==="complete"||t.state==="failed"||(e[s]={downloaded:t.downloadedBytes,total:t.totalBytes,percent:t.totalBytes>0?(t.downloadedBytes/t.totalBytes*100).toFixed(1):0,state:t.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 K{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,s){this.queue.prioritizeLayoutFiles(e,s),this.queue.processQueue()}urgentChunk(e,s,t){return this.queue.urgentChunk(e,s,t)}createTaskBuilder(){return new L(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}}const y=T("CacheAnalyzer");function w(d){if(d===0)return"0 B";if(!Number.isFinite(d))return"∞";const e=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(d)/Math.log(1024));return`${(d/Math.pow(1024,s)).toFixed(s>0?1:0)} ${e[s]}`}class X{constructor(e,{threshold:s=80}={}){this.cache=e,this.threshold=s}async analyze(e){const s=await this.cache.list(),t=await this._getStorageEstimate(),n=new Set(e.map(o=>String(o.id))),r=[],i=[];for(const o of s)if(n.has(String(o.id)))r.push(o);else if(o.type==="widget"){const u=String(o.id).split("/")[0];n.has(u)?r.push(o):i.push(o)}else o.type==="static"?r.push(o):i.push(o);i.sort((o,u)=>(o.cachedAt||0)-(u.cachedAt||0));const a=i.reduce((o,u)=>o+(u.size||0),0),h={timestamp:Date.now(),storage:{usage:t.usage,quota:t.quota,percent:t.quota>0?Math.round(t.usage/t.quota*100):0},files:{required:r.length,orphaned:i.length,total:s.length},orphaned:i.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(t.usage)} / ${w(t.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${r.length} required, ${i.length} orphaned (${w(a)} reclaimable)`),i.length>0)for(const o of i){const u=Date.now()-(o.cachedAt||0),p=Math.floor(u/864e5),c=Math.floor(u%864e5/36e5),g=p>0?`${p}d ago`:`${c}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${w(o.size||0)}, cached ${g})`)}if(h.storage.percent>this.threshold&&i.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=t.usage-t.quota*this.threshold/100;h.evicted=await this._evict(i,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:s,quota:t}=await navigator.storage.estimate();return{usage:s||0,quota:t||1/0}}}catch(s){y.warn("Storage estimate unavailable:",s.message)}return{usage:0,quota:1/0}}async _evict(e,s){const t=[];let n=0;for(const r of e){if(n>=s)break;t.push(r),n+=r.size||0}if(t.length===0)return[];try{const r=t.map(i=>({type:i.type,id:i.id}));await this.cache.remove(r);for(const i of t)y.info(` Evicted: ${i.type}/${i.id} (${w(i.size||0)})`);y.info(`Evicted ${t.length} files, freed ${w(n)}`)}catch(r){return y.warn("Eviction failed:",r.message),[]}return t.map(r=>({id:r.id,type:r.type,size:r.size||0,cachedAt:r.cachedAt||0}))}}const I=T("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function Y(d,e,s,t){var u;const n=`${$}/widgets/${d}/${e}/${s}`,r=`<base href="${$}/media/file/">`;let i=t;t.includes("<base ")||(t.includes("<head>")?i=t.replace("<head>","<head>"+r):t.includes("<HEAD>")?i=t.replace("<HEAD>","<HEAD>"+r):i=r+t);const a="<style>img,video{object-position:center center}</style>";i.includes("object-position:center center")||(i.includes("</head>")?i=i.replace("</head>",a+"</head>"):i.includes("</HEAD>")&&(i=i.replace("</HEAD>",a+"</HEAD>"))),i=i.replace(/\[\[ViewPortWidth]]/g,"device-width"),i=i.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,p=>"/stream-proxy?url="+encodeURIComponent(p));const h=new RegExp(`https?://[^"'\\s)]+?(${$.replace(/\//g,"\\/")}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,"g");if(i=i.replace(h,(p,c)=>c),i=i.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${$}/dependencies/$2$3`),!i.includes("xiboICTargetId")){const p=`<script>var xiboICTargetId = '${s}';<\/script>`;i.includes(r)?i=i.replace(r,r+p):i.includes("<head>")?i=i.replace("<head>","<head>"+p):i=p+i}return i=i.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),I.info("Injected base tag in widget HTML"),(u=(await fetch(`/store${$}/widgets/${d}/${e}/${s}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:i})).body)==null||u.cancel(),I.info(`Stored widget HTML at ${n} (${i.length} bytes)`),{cacheKey:n,html:i}}export{m as B,X as C,K as D,b as F,L,N as S,R as a,E as b,Y as c,O as d,v as g,F as i};
2
+ //# sourceMappingURL=widget-html-D7RpRI2G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget-html-D7RpRI2G.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":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\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\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 * 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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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 if (response.ok) return true;\n if (response.status === 404) return false;\n // Non-404 HTTP errors (500, 502, etc.) indicate proxy/store problems\n const err = new Error(`Store error: ${response.status}`);\n err.status = response.status;\n log.warn(`has(${type}/${id}): unexpected status ${response.status}`);\n throw err;\n } catch (error) {\n // Re-throw errors that are not simple network failures swallowed above\n // (includes HTTP errors we threw, AbortError, TypeError from fetch)\n if (error.status || error.name === 'AbortError' || error.name === 'TimeoutError') {\n throw error;\n }\n // Network errors (proxy unreachable) — log and re-throw so callers\n // can distinguish from \"not cached\" (which returns false)\n log.warn(`has(${type}/${id}): network error — ${error.message}`);\n throw error;\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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 if (this.fileInfo.cmsDownloadUrl) {\n headers['X-Cms-Download-Url'] = this.fileInfo.cmsDownloadUrl;\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 /**\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 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 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 createTaskBuilder() {\n return new LayoutTaskBuilder(this.queue);\n }\n\n enqueueOrderedTasks(tasks) {\n this.queue.enqueueOrderedTasks(tasks);\n }\n\n removeCompleted(key) {\n this.queue.removeCompleted(key);\n }\n\n get running() {\n return this.queue.running;\n }\n\n get queued() {\n return this.queue.queue.length;\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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 * (${PLAYER_API}/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 ${PLAYER_API}/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 // Replace CMS placeholders left for \"client-side SDK handling\"\n modifiedHtml = modifiedHtml.replace(/\\[\\[ViewPortWidth]]/g, 'device-width');\n\n // Route HLS streams through local proxy (adds CORS headers, rewrites segments)\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\\s\"')<]+\\.m3u8\\b/gi,\n (url) => '/stream-proxy?url=' + encodeURIComponent(url)\n );\n\n // Rewrite dependency URLs to absolute local paths. CMS SOAP GetResource sends\n // bare filenames (e.g. src=\"bundle.min.js\") which resolve against <base> to the\n // wrong /media/file/ path. Normalize all dependency references to absolute paths.\n const depsPattern = new RegExp(\n `https?://[^\"'\\\\s)]+?(${PLAYER_API.replace(/\\//g, '\\\\/')}/dependencies/[^\"'\\\\s?)]+)(\\\\?[^\"'\\\\s)]*)?`,\n 'g'\n );\n modifiedHtml = modifiedHtml.replace(depsPattern, (_, path) => path);\n modifiedHtml = modifiedHtml.replace(\n /(<(?:script|link)\\b[^>]*(?:src|href)=\")(?!\\/|https?:\\/\\/)(bundle\\.min\\.js|fonts\\.css)(\")/g,\n `$1${PLAYER_API}/dependencies/$2$3`\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, html: modifiedHtml };\n}\n"],"names":["log","createLogger","CacheManager","mediaId","layoutId","key","lid","orphaned","layouts","cacheManager","StoreClient","type","id","response","err","error","_a","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","blob","assembled","LayoutTaskBuilder","DownloadQueue","existing","oldExpiry","file","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","total","items","taskCount","barrierCount","item","fileIds","priority","idSet","boosted","matchValue","_c","_d","fileType","fileId","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","i","maxReenqueues","reenqueueDelayMs","timerId","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","BASE","cacheWidgetHtml","regionId","html","cacheKey","PLAYER_API","baseTag","modifiedHtml","cssFixTag","depsPattern","_","path","targetIdScript"],"mappings":"mEAaA,MAAMA,EAAMC,EAAa,OAAO,EAEzB,MAAMC,CAAa,CACxB,aAAc,CAEZ,KAAK,WAAa,IAAI,GACxB,CAOA,aAAaC,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,KAAK,WAAW,OAAOL,CAAO,EAC9BI,EAAS,KAAKJ,CAAO,GAIzB,OAAII,EAAS,OAAS,GACpBP,EAAI,KAAK,GAAGO,EAAS,MAAM,sCAAsCH,CAAQ,YAAaG,CAAQ,EAEzFA,CACT,CAOA,kBAAkBJ,EAAS,CACzB,MAAMK,EAAU,KAAK,WAAW,IAAI,OAAOL,CAAO,CAAC,EACnD,OAAOK,EAAUA,EAAQ,KAAO,EAAI,EACtC,CAKA,MAAM,UAAW,CACf,K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J,EASE,GARAE,EAAeA,EAAa,QAAQE,EAAa,CAACC,EAAGC,IAASA,CAAI,EAClEJ,EAAeA,EAAa,QAC1B,4FACA,KAAKF,CAAU,oBACnB,EAIM,CAACE,EAAa,SAAS,gBAAgB,EAAG,CAC5C,MAAMK,EAAiB,iCAAiCzJ,CAAO,eAC3DoJ,EAAa,SAASD,CAAO,EAC/BC,EAAeA,EAAa,QAAQD,EAASA,EAAUM,CAAc,EAC5DL,EAAa,SAAS,QAAQ,EACvCA,EAAeA,EAAa,QAAQ,SAAU,SAAWK,CAAc,EAEvEL,EAAeK,EAAiBL,CAEpC,CAGA,OAAAA,EAAeA,EAAa,QAC1B,+CACA,iBAAiBP,CAAI,MACzB,EAEEhJ,EAAI,KAAK,kCAAkC,GAQ3CgB,GALgB,MAAM,MAAM,SAASqI,CAAU,YAAYjJ,CAAQ,IAAI8I,CAAQ,IAAI/I,CAAO,GAAI,CAC5F,OAAQ,MACR,QAAS,CAAE,eAAgB,0BAA0B,EACrD,KAAMoJ,CACV,CAAG,GACO,OAAR,MAAAvI,EAAc,SACdhB,EAAI,KAAK,yBAAyBoJ,CAAQ,KAAKG,EAAa,MAAM,SAAS,EAEpE,CAAE,SAAAH,EAAU,KAAMG,CAAY,CACvC"}
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-Ddgs1h5h.js"></script>
97
+ <script type="module" crossorigin src="./assets/main-DmDlxZTo.js"></script>
98
98
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
99
- <link rel="modulepreload" crossorigin href="./assets/index-BmnGgxhy.js">
100
- <link rel="modulepreload" crossorigin href="./assets/widget-html-p3dC5HGH.js">
99
+ <link rel="modulepreload" crossorigin href="./assets/index-Cv2QuVar.js">
100
+ <link rel="modulepreload" crossorigin href="./assets/widget-html-D7RpRI2G.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-DcthBcbI.js"></script>
290
+ <script type="module" crossorigin src="./assets/setup-Du8FebQP.js"></script>
291
291
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
292
- <link rel="modulepreload" crossorigin href="./assets/index-BmnGgxhy.js">
293
- <link rel="modulepreload" crossorigin href="./assets/protocol-detector-UOvkmuFn.js">
292
+ <link rel="modulepreload" crossorigin href="./assets/index-Cv2QuVar.js">
293
+ <link rel="modulepreload" crossorigin href="./assets/protocol-detector-BEOLJeK0.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-p3dC5HGH.js";import{VERSION as S}from"./assets/index-DPUPuUO8.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-BqpCSJ87.js";import{createLogger as E}from"./assets/index-BmnGgxhy.js";const o="2026-03-20T19:48:56.043Z",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");
1
+ import{D as C}from"./assets/widget-html-D7RpRI2G.js";import{VERSION as S}from"./assets/index-CeqXK1Dq.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-CzWpgWbQ.js";import{createLogger as E}from"./assets/index-Cv2QuVar.js";const o="2026-03-21T20:47:51.343Z",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.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "Lightweight PWA Xibo Player with RendererLite",
5
5
  "type": "module",
6
6
  "files": [
@@ -10,25 +10,25 @@
10
10
  "html2canvas": "^1.4.1",
11
11
  "nanoevents": "^9.1.0",
12
12
  "xml2js": "^0.6.2",
13
- "@xiboplayer/crypto": "0.7.2",
14
- "@xiboplayer/cache": "0.7.2",
15
- "@xiboplayer/schedule": "0.7.2",
16
- "@xiboplayer/settings": "0.7.2",
17
- "@xiboplayer/renderer": "0.7.2",
18
- "@xiboplayer/sw": "0.7.2",
19
- "@xiboplayer/stats": "0.7.2",
20
- "@xiboplayer/sync": "0.7.2",
21
- "@xiboplayer/utils": "0.7.2",
22
- "@xiboplayer/xmr": "0.7.2",
23
- "@xiboplayer/core": "0.7.2",
24
- "@xiboplayer/xmds": "0.7.2"
13
+ "@xiboplayer/cache": "0.7.3",
14
+ "@xiboplayer/renderer": "0.7.3",
15
+ "@xiboplayer/core": "0.7.3",
16
+ "@xiboplayer/crypto": "0.7.3",
17
+ "@xiboplayer/settings": "0.7.3",
18
+ "@xiboplayer/schedule": "0.7.3",
19
+ "@xiboplayer/sw": "0.7.3",
20
+ "@xiboplayer/stats": "0.7.3",
21
+ "@xiboplayer/sync": "0.7.3",
22
+ "@xiboplayer/utils": "0.7.3",
23
+ "@xiboplayer/xmds": "0.7.3",
24
+ "@xiboplayer/xmr": "0.7.3"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@playwright/test": "^1.58.2",
28
- "@types/node": "^22.10.5",
28
+ "@types/node": "^22.19.15",
29
29
  "@types/xml2js": "^0.4.14",
30
- "typescript": "^5.6.3",
31
- "vite": "^5.4.11"
30
+ "typescript": "^5.9.3",
31
+ "vite": "^5.4.21"
32
32
  },
33
33
  "author": "Pau Aliagas <linuxnow@gmail.com>",
34
34
  "license": "AGPL-3.0-or-later",