@xiboplayer/pwa 0.5.4 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/dist/assets/{cms-api-B3gEu-pj.js → cms-api-Df_4fWKB.js} +2 -2
- package/dist/assets/{cms-api-B3gEu-pj.js.map → cms-api-Df_4fWKB.js.map} +1 -1
- package/dist/assets/{index-BJfE9Kwo.js → index-BI2Wgrnr.js} +2 -2
- package/dist/assets/{index-BJfE9Kwo.js.map → index-BI2Wgrnr.js.map} +1 -1
- package/dist/assets/index-BtefBXN1.js +2 -0
- package/dist/assets/{index-CQyGlAYj.js.map → index-BtefBXN1.js.map} +1 -1
- package/dist/assets/index-C6HTCgOh.js +2 -0
- package/dist/assets/{index-CzDf1qpA.js.map → index-C6HTCgOh.js.map} +1 -1
- package/dist/assets/{index-CXNhzvrm.js → index-CO_3HB3b.js} +2 -2
- package/dist/assets/{index-CXNhzvrm.js.map → index-CO_3HB3b.js.map} +1 -1
- package/dist/assets/{index-DxBxL_GE.js → index-CSP8cHo2.js} +2 -2
- package/dist/assets/{index-DxBxL_GE.js.map → index-CSP8cHo2.js.map} +1 -1
- package/dist/assets/index-CXUhpySp.js +2 -0
- package/dist/assets/{index-B0GfHN6H.js.map → index-CXUhpySp.js.map} +1 -1
- package/dist/assets/index-DjVtpboH.js +2 -0
- package/dist/assets/{index-Y1vt-BGr.js.map → index-DjVtpboH.js.map} +1 -1
- package/dist/assets/{index-CUXQMBpU.js → index-DozRpAD9.js} +2 -2
- package/dist/assets/{index-CUXQMBpU.js.map → index-DozRpAD9.js.map} +1 -1
- package/dist/assets/index-O5-FLIor.js +2 -0
- package/dist/assets/{index-CExOPp2u.js.map → index-O5-FLIor.js.map} +1 -1
- package/dist/assets/main-4E7jVmyh.js +715 -0
- package/dist/assets/main-4E7jVmyh.js.map +1 -0
- package/dist/assets/{setup-DgQcE5P_.js → setup-D2LzAr3z.js} +2 -2
- package/dist/assets/{setup-DgQcE5P_.js.map → setup-D2LzAr3z.js.map} +1 -1
- package/dist/assets/{sync-manager-DBfiw5Ey.js → sync-manager-Cibvio-3.js} +2 -2
- package/dist/assets/{sync-manager-DBfiw5Ey.js.map → sync-manager-Cibvio-3.js.map} +1 -1
- package/dist/assets/widget-html-BzYo0-WO.js +5 -0
- package/dist/assets/widget-html-BzYo0-WO.js.map +1 -0
- package/dist/assets/{xmds-client-CX0t7Oes.js → xmds-client-uoul_PDG.js} +2 -2
- package/dist/assets/{xmds-client-CX0t7Oes.js.map → xmds-client-uoul_PDG.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +1 -1
- package/dist/assets/index-B0GfHN6H.js +0 -2
- package/dist/assets/index-CExOPp2u.js +0 -2
- package/dist/assets/index-CQyGlAYj.js +0 -2
- package/dist/assets/index-CzDf1qpA.js +0 -2
- package/dist/assets/index-Y1vt-BGr.js +0 -2
- package/dist/assets/main-ByDZRbW8.js +0 -715
- package/dist/assets/main-ByDZRbW8.js.map +0 -1
- package/dist/assets/widget-html-B_acad6q.js +0 -2
- package/dist/assets/widget-html-B_acad6q.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widget-html-BzYo0-WO.js","sources":["../../node_modules/.pnpm/@xiboplayer+utils@0.5.4/node_modules/@xiboplayer/utils/src/logger.js","../../node_modules/.pnpm/@xiboplayer+crypto@0.5.4/node_modules/@xiboplayer/crypto/src/rsa.js","../../node_modules/.pnpm/@xiboplayer+utils@0.5.4/node_modules/@xiboplayer/utils/src/config.js","../../node_modules/.pnpm/@xiboplayer+utils@0.5.4/node_modules/@xiboplayer/utils/src/fetch-retry.js","../../node_modules/.pnpm/@xiboplayer+utils@0.5.4/node_modules/@xiboplayer/utils/src/cms-api.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.4/node_modules/@xiboplayer/cache/src/download-manager.js","../../node_modules/.pnpm/@xiboplayer+utils@0.5.5/node_modules/@xiboplayer/utils/src/event-emitter.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.5/node_modules/@xiboplayer/cache/src/cache.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.5/node_modules/@xiboplayer/cache/src/cache-proxy.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.5/node_modules/@xiboplayer/cache/src/download-manager.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.5/node_modules/@xiboplayer/cache/src/cache-analyzer.js","../../node_modules/.pnpm/@xiboplayer+cache@0.5.5/node_modules/@xiboplayer/cache/src/widget-html.js"],"sourcesContent":["/**\n * Configurable Logger for Xibo Players\n *\n * Supports log levels: DEBUG, INFO, WARNING, ERROR, NONE\n *\n * Level precedence (highest wins):\n * 1. URL param ?logLevel=DEBUG\n * 2. localStorage xibo_log_level\n * 3. CMS setting via RegisterDisplay (call applyCmsLogLevel())\n * 4. Default: WARNING (production-safe)\n *\n * For development, pass ?logLevel=DEBUG in the URL.\n * Electron's --dev flag does this automatically.\n *\n * Loggers created without an explicit level are REACTIVE — they follow\n * the global level at call time, so setLogLevel() affects all of them.\n */\n\nconst LOG_LEVELS = {\n DEBUG: 0,\n INFO: 1,\n WARNING: 2,\n ERROR: 3,\n NONE: 4\n};\n\n// Log sink system — external consumers (e.g., LogReporter) can intercept all log output\nconst logSinks = [];\n\nclass Logger {\n /**\n * @param {string} name - Logger name (shown in prefix)\n * @param {string|null} level - Explicit level string, or null to follow global\n */\n constructor(name, level = null) {\n this.name = name;\n this.useGlobal = (level === null);\n if (!this.useGlobal) {\n this.setLevel(level);\n }\n }\n\n setLevel(level) {\n this.useGlobal = false;\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n }\n\n /** Effective level: own override or global */\n getEffectiveLevel() {\n return this.useGlobal ? globalConfig.level : this.level;\n }\n\n debug(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.DEBUG) {\n console.log(`[${this.name}] DEBUG:`, ...args);\n }\n _dispatchToSinks('debug', this.name, args);\n }\n\n info(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.INFO) {\n console.log(`[${this.name}]`, ...args);\n }\n _dispatchToSinks('info', this.name, args);\n }\n\n warn(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.WARNING) {\n console.warn(`[${this.name}]`, ...args);\n }\n _dispatchToSinks('warning', this.name, args);\n }\n\n error(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.ERROR) {\n console.error(`[${this.name}]`, ...args);\n }\n _dispatchToSinks('error', this.name, args);\n }\n\n // Convenience method for conditional logging\n log(level, ...args) {\n switch (level.toUpperCase()) {\n case 'DEBUG': return this.debug(...args);\n case 'INFO': return this.info(...args);\n case 'WARNING':\n case 'WARN': return this.warn(...args);\n case 'ERROR': return this.error(...args);\n }\n }\n}\n\n// Global log level configuration\nconst globalConfig = {\n level: LOG_LEVELS.WARNING, // Default: WARNING (production-safe)\n\n setGlobalLevel(level) {\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n\n console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`);\n },\n\n getLevelName(level) {\n return Object.keys(LOG_LEVELS).find(key => LOG_LEVELS[key] === level) || 'UNKNOWN';\n }\n};\n\n// Track whether the level was set by a local override (URL param / localStorage)\nlet hasLocalOverride = false;\n\n// Set global level from environment or localStorage\n// Default: WARNING (production-safe). Use ?logLevel=DEBUG for development,\n// or let the CMS override via applyCmsLogLevel().\nif (typeof window !== 'undefined') {\n const urlParams = new URLSearchParams(window.location.search);\n const urlLevel = urlParams.get('logLevel');\n const storageLevel = localStorage.getItem('xibo_log_level');\n\n if (urlLevel) {\n globalConfig.setGlobalLevel(urlLevel);\n hasLocalOverride = true;\n } else if (storageLevel) {\n globalConfig.setGlobalLevel(storageLevel);\n hasLocalOverride = true;\n } else {\n globalConfig.setGlobalLevel('WARNING');\n }\n}\n\n// Factory function — loggers follow global level by default (reactive)\nexport function createLogger(name, level = null) {\n return new Logger(name, level);\n}\n\n// Set global log level (and persist to localStorage)\nexport function setLogLevel(level) {\n globalConfig.setGlobalLevel(level);\n\n // Save to localStorage\n if (typeof window !== 'undefined') {\n localStorage.setItem('xibo_log_level', level.toUpperCase());\n }\n}\n\n// Get current log level name\nexport function getLogLevel() {\n return globalConfig.getLevelName(globalConfig.level);\n}\n\n/**\n * Returns true when the effective global level is DEBUG.\n * Use this for conditional debug features (video controls, overlays, etc.)\n */\nexport function isDebug() {\n return globalConfig.level <= LOG_LEVELS.DEBUG;\n}\n\n/**\n * Apply CMS logLevel setting — only if no local override (URL/localStorage) exists.\n * @param {string} cmsLevel - CMS level string: 'error', 'audit', 'info', 'debug'\n * @returns {boolean} true if the level was applied\n */\nexport function applyCmsLogLevel(cmsLevel) {\n if (hasLocalOverride) return false;\n if (!cmsLevel) return false;\n\n const mapped = mapCmsLogLevel(cmsLevel);\n globalConfig.setGlobalLevel(mapped);\n return true;\n}\n\n/**\n * Map CMS logLevel strings to internal level names.\n * CMS uses: 'emergency','alert','critical','error','warning','notice','info','debug','audit'\n * We collapse them to our 4 levels.\n */\nexport function mapCmsLogLevel(cmsLevel) {\n switch ((cmsLevel || '').toLowerCase()) {\n case 'debug':\n return 'DEBUG';\n case 'info':\n case 'notice':\n case 'audit':\n return 'INFO';\n case 'warning':\n return 'WARNING';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'ERROR';\n default:\n return 'INFO';\n }\n}\n\n/**\n * Dispatch log entry to all registered sinks.\n * Sinks receive { level, name, args } and should not throw.\n * @private\n */\nfunction _dispatchToSinks(level, name, args) {\n if (logSinks.length === 0) return;\n for (const fn of logSinks) {\n try {\n fn({ level, name, args });\n } catch (_) {\n // Sink errors must never break logging\n }\n }\n}\n\n/**\n * Register a log sink — receives all log output regardless of level filtering.\n * @param {function} fn - Callback: ({ level, name, args }) => void\n */\nexport function registerLogSink(fn) {\n logSinks.push(fn);\n}\n\n/**\n * Unregister a previously registered log sink.\n * @param {function} fn - The same function reference passed to registerLogSink\n */\nexport function unregisterLogSink(fn) {\n const idx = logSinks.indexOf(fn);\n if (idx >= 0) logSinks.splice(idx, 1);\n}\n\nexport { LOG_LEVELS };\n","/**\n * RSA key pair generation via Web Crypto API.\n *\n * Generates RSA-1024 keys compatible with the upstream .NET player.\n * The SPKI PEM public key works with PHP's openssl_get_publickey().\n *\n * No runtime dependencies — uses only the Web Crypto API available\n * in browsers, Electron, and Node.js 16+.\n */\n\n/**\n * Convert an ArrayBuffer (DER-encoded key) to PEM format.\n * @param {ArrayBuffer} buffer - DER-encoded key data\n * @param {string} type - Key type label ('PUBLIC KEY' or 'PRIVATE KEY')\n * @returns {string} PEM-formatted key string\n */\nexport function arrayBufferToPem(buffer, type) {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n const base64 = btoa(binary);\n\n // Split into 64-character lines per PEM spec\n const lines = [];\n for (let i = 0; i < base64.length; i += 64) {\n lines.push(base64.substring(i, i + 64));\n }\n\n return `-----BEGIN ${type}-----\\n${lines.join('\\n')}\\n-----END ${type}-----`;\n}\n\n/**\n * Generate an RSA key pair for XMR registration.\n *\n * Uses RSA-OAEP with SHA-256 and a 1024-bit modulus to match\n * the upstream .NET player's key format.\n *\n * @returns {Promise<{publicKeyPem: string, privateKeyPem: string}>}\n */\nexport async function generateRsaKeyPair() {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 1024,\n publicExponent: new Uint8Array([1, 0, 1]), // 65537\n hash: 'SHA-256',\n },\n true, // extractable\n ['encrypt', 'decrypt']\n );\n\n const publicKeyDer = await crypto.subtle.exportKey('spki', keyPair.publicKey);\n const privateKeyDer = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);\n\n return {\n publicKeyPem: arrayBufferToPem(publicKeyDer, 'PUBLIC KEY'),\n privateKeyPem: arrayBufferToPem(privateKeyDer, 'PRIVATE KEY'),\n };\n}\n\n/**\n * Validate that a string looks like a valid PEM key.\n * Checks for proper BEGIN/END headers and base64 content.\n *\n * @param {string} pem - String to validate\n * @returns {boolean} true if the string appears to be valid PEM\n */\nexport function isValidPemKey(pem) {\n if (!pem || typeof pem !== 'string') return false;\n\n const pemRegex = /^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\\n[A-Za-z0-9+/=\\n]+\\n-----END \\1-----$/;\n return pemRegex.test(pem.trim());\n}\n","/**\n * Configuration management with priority: env vars → localStorage → defaults\n *\n * In Node.js (tests, CLI): environment variables are the only source.\n * In browser (PWA player): localStorage is primary, env vars override if set.\n */\nimport { generateRsaKeyPair, isValidPemKey } from '@xiboplayer/crypto';\n\nconst STORAGE_KEY = 'xibo_config';\nconst HW_DB_NAME = 'xibo-hw-backup';\nconst HW_DB_VERSION = 1;\n\n/**\n * Check for environment variable config (highest priority).\n * Env vars: CMS_URL, CMS_KEY, DISPLAY_NAME, HARDWARE_KEY, XMR_CHANNEL\n * Returns config object if any env vars are set, null otherwise.\n */\nfunction loadFromEnv() {\n // Check if process.env is available (Node.js or bundler injection)\n const env = typeof process !== 'undefined' && process.env ? process.env : {};\n\n const envConfig = {\n cmsUrl: env.CMS_URL || '',\n cmsKey: env.CMS_KEY || '',\n displayName: env.DISPLAY_NAME || '',\n hardwareKey: env.HARDWARE_KEY || '',\n xmrChannel: env.XMR_CHANNEL || '',\n googleGeoApiKey: env.GOOGLE_GEO_API_KEY || '',\n };\n\n // Return env config if any value is set\n const hasEnvValues = Object.values(envConfig).some(v => v !== '');\n return hasEnvValues ? envConfig : null;\n}\n\nexport class Config {\n constructor() {\n this.data = this.load();\n // Async: try to restore hardware key from IndexedDB if localStorage lost it\n // (only when not running from env vars)\n if (!this._fromEnv) {\n this._restoreHardwareKeyFromBackup();\n }\n }\n\n load() {\n // Priority 1: Environment variables (Node.js, tests, CI)\n const envConfig = loadFromEnv();\n if (envConfig) {\n this._fromEnv = true;\n return envConfig;\n }\n\n // Priority 2: localStorage (browser)\n if (typeof localStorage === 'undefined') {\n return { cmsUrl: '', cmsKey: '', displayName: '', hardwareKey: '', xmrChannel: '' };\n }\n\n // Try to load from localStorage\n const json = localStorage.getItem(STORAGE_KEY);\n let config = {};\n\n if (json) {\n try {\n config = JSON.parse(json);\n } catch (e) {\n console.error('[Config] Failed to parse localStorage config:', e);\n }\n }\n\n // ── Single validation gate (same path for fresh + pre-seeded) ──\n let changed = false;\n\n if (!config.hardwareKey || config.hardwareKey.length < 10) {\n console.warn('[Config] Missing/invalid hardwareKey — generating');\n config.hardwareKey = this.generateStableHardwareKey();\n this._backupHardwareKey(config.hardwareKey);\n changed = true;\n } else {\n console.log('[Config] ✓ Loaded existing hardwareKey:', config.hardwareKey);\n }\n\n if (!config.xmrChannel) {\n console.warn('[Config] Missing xmrChannel — generating');\n config.xmrChannel = this.generateXmrChannel();\n changed = true;\n }\n\n // Ensure optional fields have defaults\n config.cmsUrl = config.cmsUrl || '';\n config.cmsKey = config.cmsKey || '';\n config.displayName = config.displayName || '';\n\n if (changed) {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(config));\n }\n\n return config;\n }\n\n /**\n * Backup keys to IndexedDB (more persistent than localStorage).\n * IndexedDB survives \"Clear site data\" in some browsers where localStorage doesn't.\n * @param {Object} keys - Key-value pairs to store (e.g. { hardwareKey: '...', xmrPubKey: '...' })\n */\n _backupKeys(keys) {\n try {\n const req = indexedDB.open(HW_DB_NAME, HW_DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n const store = tx.objectStore('keys');\n for (const [k, v] of Object.entries(keys)) {\n store.put(v, k);\n }\n tx.oncomplete = () => {\n console.log('[Config] Keys backed up to IndexedDB:', Object.keys(keys).join(', '));\n db.close();\n };\n };\n } catch (e) {\n // IndexedDB not available — localStorage-only mode\n }\n }\n\n /**\n * Backup hardware key to IndexedDB (convenience wrapper).\n */\n _backupHardwareKey(key) {\n this._backupKeys({ hardwareKey: key });\n }\n\n /**\n * Restore hardware key from IndexedDB if localStorage was cleared.\n * Runs async after construction — if a backed-up key is found and\n * differs from the current one, it restores the original key.\n */\n async _restoreHardwareKeyFromBackup() {\n if (typeof indexedDB === 'undefined') return;\n try {\n const db = await new Promise((resolve, reject) => {\n const req = indexedDB.open(HW_DB_NAME, HW_DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n\n const tx = db.transaction('keys', 'readonly');\n const store = tx.objectStore('keys');\n const backedUpKey = await new Promise((resolve) => {\n const req = store.get('hardwareKey');\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => resolve(null);\n });\n db.close();\n\n if (backedUpKey && backedUpKey !== this.data.hardwareKey) {\n console.log('[Config] Restoring hardware key from IndexedDB backup:', backedUpKey);\n console.log('[Config] (was:', this.data.hardwareKey, ')');\n this.data.hardwareKey = backedUpKey;\n this.save();\n } else if (!backedUpKey && this.data.hardwareKey) {\n // No backup yet — save current key as backup\n this._backupHardwareKey(this.data.hardwareKey);\n }\n } catch (e) {\n // IndexedDB not available — that's fine\n }\n }\n\n save() {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(this.data));\n }\n }\n\n isConfigured() {\n return !!(this.data.cmsUrl && this.data.cmsKey && this.data.displayName);\n }\n\n generateStableHardwareKey() {\n // Generate a stable UUID-based hardware key\n // CRITICAL: This is generated ONCE and saved to localStorage\n // It NEVER changes unless localStorage is cleared manually\n\n // Use crypto.randomUUID if available (best randomness)\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n const uuid = crypto.randomUUID().replace(/-/g, ''); // Remove dashes\n const hardwareKey = 'pwa-' + uuid.substring(0, 28);\n console.log('[Config] Generated new UUID-based hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n // Fallback: Generate random hex string\n const randomHex = Array.from({ length: 28 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('');\n\n const hardwareKey = 'pwa-' + randomHex;\n console.log('[Config] Generated new random hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n getCanvasFingerprint() {\n // Generate stable canvas fingerprint (same for same GPU/driver)\n try {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) return 'no-canvas';\n\n // Draw test pattern (same rendering = same device)\n ctx.textBaseline = 'top';\n ctx.font = '14px Arial';\n ctx.fillStyle = '#f60';\n ctx.fillRect(125, 1, 62, 20);\n ctx.fillStyle = '#069';\n ctx.fillText('Xibo Player', 2, 15);\n\n return canvas.toDataURL();\n } catch (e) {\n return 'canvas-error';\n }\n }\n\n generateHardwareKey() {\n // For backwards compatibility\n return this.generateStableHardwareKey();\n }\n\n generateXmrChannel() {\n // Generate UUID for XMR channel\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n }\n\n /**\n * Ensure an RSA key pair exists for XMR registration.\n * If keys are missing or invalid, generates a new pair and persists them.\n * Idempotent — safe to call multiple times.\n */\n async ensureXmrKeyPair() {\n if (this.data.xmrPubKey && isValidPemKey(this.data.xmrPubKey)) {\n return;\n }\n\n console.log('[Config] Generating RSA key pair for XMR registration...');\n const { publicKeyPem, privateKeyPem } = await generateRsaKeyPair();\n\n this.data.xmrPubKey = publicKeyPem;\n this.data.xmrPrivKey = privateKeyPem;\n this.save();\n\n // Backup RSA keys to IndexedDB alongside hardware key\n if (typeof indexedDB !== 'undefined') {\n this._backupKeys({ xmrPubKey: publicKeyPem, xmrPrivKey: privateKeyPem });\n }\n\n console.log('[Config] RSA key pair generated and saved');\n }\n\n hash(str) {\n // FNV-1a hash algorithm (better distribution than simple hash)\n // Produces high-entropy 32-character hex string\n let hash = 2166136261; // FNV offset basis\n\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n\n // Convert to unsigned 32-bit integer\n hash = hash >>> 0;\n\n // Extend to 32 characters by hashing multiple times with different seeds\n let result = '';\n for (let round = 0; round < 4; round++) {\n let roundHash = hash + round * 1234567;\n for (let i = 0; i < str.length; i++) {\n roundHash ^= str.charCodeAt(i) + round;\n roundHash += (roundHash << 1) + (roundHash << 4) + (roundHash << 7) + (roundHash << 8) + (roundHash << 24);\n }\n roundHash = roundHash >>> 0;\n result += roundHash.toString(16).padStart(8, '0');\n }\n\n return result.substring(0, 32);\n }\n\n get cmsUrl() { return this.data.cmsUrl; }\n set cmsUrl(val) { this.data.cmsUrl = val; this.save(); }\n\n get cmsKey() { return this.data.cmsKey; }\n set cmsKey(val) { this.data.cmsKey = val; this.save(); }\n\n get displayName() { return this.data.displayName; }\n set displayName(val) { this.data.displayName = val; this.save(); }\n\n get hardwareKey() {\n // CRITICAL: Ensure hardware key never becomes undefined\n if (!this.data.hardwareKey) {\n console.error('[Config] CRITICAL: hardwareKey missing! Generating emergency key.');\n this.data.hardwareKey = this.generateStableHardwareKey();\n this.save();\n }\n return this.data.hardwareKey;\n }\n get xmrChannel() {\n if (!this.data.xmrChannel) {\n console.warn('[Config] xmrChannel missing at access time — generating');\n this.data.xmrChannel = this.generateXmrChannel();\n this.save();\n }\n return this.data.xmrChannel;\n }\n get xmrPubKey() { return this.data.xmrPubKey || ''; }\n get xmrPrivKey() { return this.data.xmrPrivKey || ''; }\n\n get googleGeoApiKey() { return this.data.googleGeoApiKey || ''; }\n set googleGeoApiKey(val) { this.data.googleGeoApiKey = val; this.save(); }\n}\n\nexport const config = new Config();\n","/**\n * Fetch with retry and exponential backoff\n *\n * Wraps native fetch() with configurable retry logic for transient failures.\n * Only retries on network errors and 5xx server errors (not 4xx client errors).\n * On final attempt, returns the response as-is so the caller can handle errors.\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('FetchRetry');\n\nconst DEFAULT_429_DELAY_MS = 30000;\nconst MAX_429_DELAY_MS = 120000;\n\n/**\n * Parse a Retry-After header value into milliseconds.\n * Supports both delta-seconds (\"120\") and HTTP-date (\"Fri, 21 Feb 2026 12:00:00 GMT\").\n * Returns a sensible default if the header is missing or unparseable.\n * The returned delay is NOT capped by maxDelayMs — the server's rate-limit\n * instruction takes priority over our backoff ceiling.\n * @param {string|null} headerValue\n * @returns {number} delay in milliseconds (clamped to MAX_429_DELAY_MS)\n */\nfunction parseRetryAfter(headerValue) {\n if (!headerValue) return DEFAULT_429_DELAY_MS;\n\n // Try delta-seconds first (most common)\n const seconds = Number(headerValue);\n if (!isNaN(seconds) && seconds >= 0) {\n return Math.min(seconds * 1000, MAX_429_DELAY_MS);\n }\n\n // Try HTTP-date format (RFC 7231 §7.1.3)\n const date = new Date(headerValue);\n if (!isNaN(date.getTime())) {\n const delayMs = date.getTime() - Date.now();\n return Math.min(Math.max(delayMs, 0), MAX_429_DELAY_MS);\n }\n\n return DEFAULT_429_DELAY_MS;\n}\n\n/**\n * Fetch with automatic retry on failure\n * @param {string|URL} url - URL to fetch\n * @param {RequestInit} [options] - Fetch options\n * @param {Object} [retryOptions] - Retry configuration\n * @param {number} [retryOptions.maxRetries=3] - Maximum retry attempts\n * @param {number} [retryOptions.baseDelayMs=1000] - Base delay between retries (doubles each time)\n * @param {number} [retryOptions.maxDelayMs=30000] - Maximum delay between retries\n * @returns {Promise<Response>}\n */\nexport async function fetchWithRetry(url, options = {}, retryOptions = {}) {\n const { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 30000 } = retryOptions;\n\n let lastError;\n let lastResponse;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n\n // HTTP 429 Too Many Requests — respect Retry-After header\n if (response.status === 429) {\n const delayMs = parseRetryAfter(response.headers.get('Retry-After'));\n log.debug(`429 Rate limited, waiting ${delayMs}ms (Retry-After: ${response.headers.get('Retry-After')})`);\n lastResponse = response;\n lastError = new Error(`HTTP 429: Too Many Requests`);\n lastError.status = 429;\n if (attempt < maxRetries) {\n await new Promise(resolve => setTimeout(resolve, delayMs));\n continue; // Skip the normal backoff delay below\n }\n break; // Exhausted retries\n }\n\n // Don't retry other client errors (4xx) — they won't change with retries\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n return response;\n }\n\n // Server error (5xx) — retryable, but return on last attempt\n lastResponse = response;\n lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);\n lastError.status = response.status;\n } catch (error) {\n // Network error — retryable\n lastError = error;\n lastResponse = null;\n }\n\n if (attempt < maxRetries) {\n const delay = Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);\n const jitter = delay * (0.5 + Math.random() * 0.5); // 50-100% of delay\n log.debug(`Retry ${attempt + 1}/${maxRetries} in ${Math.round(jitter)}ms:`, String(url).slice(0, 80));\n await new Promise(resolve => setTimeout(resolve, jitter));\n }\n }\n\n // On exhausted retries: return response if we have one (let caller handle),\n // throw if we only have network errors\n if (lastResponse) {\n return lastResponse;\n }\n throw lastError;\n}\n","/**\n * CMS API Client — OAuth2-authenticated REST client for Xibo CMS\n *\n * Full CRUD client for all Xibo CMS REST API entities: displays, layouts,\n * regions, widgets, media, campaigns, schedules, display groups, resolutions,\n * commands, dayparts, playlists, datasets, notifications, folders, and tags.\n * Implements OAuth2 client_credentials flow (machine-to-machine).\n *\n * Usage:\n * const api = new CmsApiClient({ baseUrl: 'https://cms.example.com', clientId, clientSecret });\n * await api.authenticate();\n * const layout = await api.createLayout({ name: 'Test', resolutionId: 9 });\n * const region = await api.addRegion(layout.layoutId, { width: 1920, height: 1080 });\n * await api.addWidget('text', region.playlists[0].playlistId, { text: 'Hello' });\n * await api.publishLayout(layout.layoutId);\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('CmsApi');\n\nexport class CmsApiClient {\n /**\n * @param {Object} options\n * @param {string} options.baseUrl - CMS base URL (e.g. https://cms.example.com)\n * @param {string} [options.clientId] - OAuth2 application client ID\n * @param {string} [options.clientSecret] - OAuth2 application client secret\n * @param {string} [options.apiToken] - Pre-configured bearer token (skips OAuth2 flow)\n */\n constructor({ baseUrl, clientId, clientSecret, apiToken } = {}) {\n this.baseUrl = (baseUrl || '').replace(/\\/+$/, '');\n this.clientId = clientId || null;\n this.clientSecret = clientSecret || null;\n this.accessToken = apiToken || null;\n this.tokenExpiry = apiToken ? Infinity : 0;\n }\n\n // ── OAuth2 Token Management ─────────────────────────────────────\n\n /**\n * Authenticate using client_credentials grant\n * @returns {Promise<string>} Access token\n */\n async authenticate() {\n log.info('Authenticating with CMS API...');\n\n const response = await fetch(`${this.baseUrl}/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret\n })\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`OAuth2 authentication failed (${response.status}): ${text}`);\n }\n\n const data = await response.json();\n this.accessToken = data.access_token;\n this.tokenExpiry = Date.now() + (data.expires_in || 3600) * 1000;\n\n log.info('Authenticated successfully, token expires in', data.expires_in, 's');\n return this.accessToken;\n }\n\n /**\n * Ensure we have a valid token (auto-refresh if expired)\n */\n async ensureToken() {\n if (this.accessToken && Date.now() < this.tokenExpiry - 60000) return;\n if (!this.clientId || !this.clientSecret) {\n if (this.accessToken) return; // apiToken with no expiry\n throw new CmsApiError('AUTH', '/authorize', 0, 'No valid token and no OAuth2 credentials');\n }\n await this.authenticate();\n }\n\n /**\n * Make an authenticated API request\n * @param {string} method - HTTP method\n * @param {string} path - API path (e.g. /display)\n * @param {Object} [params] - Query params (GET) or body params (POST/PUT)\n * @returns {Promise<any>} Response data\n */\n async request(method, path, params = {}) {\n await this.ensureToken();\n\n const url = new URL(`${this.baseUrl}/api${path}`);\n const options = {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n }\n };\n\n if (method === 'GET') {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n } else {\n options.headers['Content-Type'] = 'application/x-www-form-urlencoded';\n options.body = new URLSearchParams(params);\n }\n\n const response = await fetch(url, options);\n\n if (!response.ok) {\n const text = await response.text();\n let errorMsg;\n try {\n const errorData = JSON.parse(text);\n errorMsg = errorData.error?.message || errorData.message || text;\n } catch (_) {\n errorMsg = text;\n }\n throw new CmsApiError(method, path, response.status, errorMsg);\n }\n\n // Some endpoints return empty body (204)\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Convenience methods ────────────────────────────────────────\n\n /** GET request (path relative to /api/) */\n get(path, params) { return this.request('GET', path, params); }\n /** POST request (path relative to /api/) */\n post(path, body) { return this.request('POST', path, body); }\n /** PUT request (path relative to /api/) */\n put(path, body) { return this.request('PUT', path, body); }\n /** DELETE request (path relative to /api/) */\n del(path) { return this.request('DELETE', path); }\n\n // ── Display Management ──────────────────────────────────────────\n\n /**\n * Find a display by hardware key\n * @param {string} hardwareKey\n * @returns {Promise<Object|null>} Display object or null if not found\n */\n async findDisplay(hardwareKey) {\n log.info('Looking up display by hardwareKey:', hardwareKey);\n const data = await this.request('GET', '/display', { hardwareKey });\n\n // API returns array of matching displays\n const displays = Array.isArray(data) ? data : [];\n if (displays.length === 0) {\n log.info('No display found for hardwareKey:', hardwareKey);\n return null;\n }\n\n const display = displays[0];\n log.info(`Found display: ${display.display} (ID: ${display.displayId}, licensed: ${display.licensed})`);\n return display;\n }\n\n /**\n * Authorize (toggle licence) a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async authorizeDisplay(displayId) {\n log.info('Authorizing display:', displayId);\n await this.request('PUT', `/display/authorise/${displayId}`);\n log.info('Display authorized successfully');\n }\n\n /**\n * Edit display properties\n * @param {number} displayId\n * @param {Object} properties - Properties to update (display, description, defaultLayoutId, etc.)\n * @returns {Promise<Object>} Updated display\n */\n async editDisplay(displayId, properties) {\n log.info('Editing display:', displayId, properties);\n return this.request('PUT', `/display/${displayId}`, properties);\n }\n\n /**\n * List all displays (with optional filters)\n * @param {Object} [filters] - Optional filters (displayId, display, macAddress, hardwareKey, clientType)\n * @returns {Promise<Array>} Array of display objects\n */\n async listDisplays(filters = {}) {\n const data = await this.request('GET', '/display', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Request screenshot from a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async requestScreenshot(displayId) {\n await this.request('PUT', `/display/requestscreenshot/${displayId}`);\n }\n\n /**\n * Get display status\n * @param {number} displayId\n * @returns {Promise<Object>}\n */\n async getDisplayStatus(displayId) {\n return this.request('GET', `/display/status/${displayId}`);\n }\n\n // ── Multipart Requests (File Uploads) ─────────────────────────────\n\n /**\n * Make an authenticated multipart/form-data request (for file uploads).\n * Do NOT set Content-Type — fetch adds the multipart boundary automatically.\n * @param {string} method - HTTP method (POST/PUT)\n * @param {string} path - API path\n * @param {FormData} formData - Form data with files\n * @returns {Promise<any>} Response data\n */\n async requestMultipart(method, path, formData) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api${path}`;\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n // No Content-Type — fetch sets multipart boundary automatically\n },\n body: formData\n });\n\n if (!response.ok) {\n const text = await response.text();\n let errorMsg;\n try {\n const errorData = JSON.parse(text);\n errorMsg = errorData.error?.message || errorData.message || text;\n } catch (_) {\n errorMsg = text;\n }\n throw new Error(`CMS API ${method} ${path} failed (${response.status}): ${errorMsg}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Layout Management ─────────────────────────────────────────────\n\n /**\n * Create a new layout\n * @param {Object} params\n * @param {string} params.name - Layout name\n * @param {number} params.resolutionId - Resolution ID\n * @param {string} [params.description] - Description\n * @returns {Promise<Object>} Created layout\n */\n async createLayout({ name, resolutionId, description }) {\n const params = { name, resolutionId };\n if (description) params.description = description;\n return this.request('POST', '/layout', params);\n }\n\n /**\n * List layouts with optional filters\n * @param {Object} [filters] - Filters (layoutId, layout, userId, retired, etc.)\n * @returns {Promise<Array>}\n */\n async listLayouts(filters = {}) {\n const data = await this.request('GET', '/layout', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Get a single layout by ID\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayout(layoutId) {\n return this.request('GET', `/layout/${layoutId}`);\n }\n\n /**\n * Delete a layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async deleteLayout(layoutId) {\n await this.request('DELETE', `/layout/${layoutId}`);\n }\n\n /**\n * Publish a draft layout (makes it available for scheduling)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async publishLayout(layoutId) {\n await this.request('PUT', `/layout/publish/${layoutId}`, { publishNow: 1 });\n }\n\n /**\n * Checkout a published layout (creates editable draft).\n * NOTE: Not needed for newly created layouts — they already have a draft.\n * Use getDraftLayout() to find the auto-created draft instead.\n * @param {number} layoutId\n * @returns {Promise<Object>} Draft layout\n */\n async checkoutLayout(layoutId) {\n return this.request('PUT', `/layout/checkout/${layoutId}`);\n }\n\n /**\n * Get the draft (editable) layout for a given parent layout.\n * In Xibo v4, POST /layout creates a parent + hidden draft automatically.\n * The draft is the one you edit (add regions, widgets) before publishing.\n * @param {number} parentId - The parent layout ID returned by createLayout()\n * @returns {Promise<Object|null>} Draft layout or null if not found\n */\n async getDraftLayout(parentId) {\n const drafts = await this.listLayouts({ parentId });\n return drafts.length > 0 ? drafts[0] : null;\n }\n\n /**\n * Edit layout background\n * @param {number} layoutId\n * @param {Object} params\n * @param {number} [params.backgroundImageId] - Media ID for background image\n * @param {string} [params.backgroundColor] - Hex color (e.g. '#FF0000')\n * @returns {Promise<Object>}\n */\n async editLayoutBackground(layoutId, params) {\n return this.request('PUT', `/layout/background/${layoutId}`, params);\n }\n\n // ── Region Management ─────────────────────────────────────────────\n\n /**\n * Add a region to a layout\n * @param {number} layoutId - Must be the DRAFT layout ID (not the parent)\n * @param {Object} params - { width, height, top, left }\n * @returns {Promise<Object>} Created region with regionPlaylist (singular object, not array)\n */\n async addRegion(layoutId, params) {\n return this.request('POST', `/region/${layoutId}`, params);\n }\n\n /**\n * Edit a region's properties\n * @param {number} regionId\n * @param {Object} params - { width, height, top, left, zIndex }\n * @returns {Promise<Object>}\n */\n async editRegion(regionId, params) {\n return this.request('PUT', `/region/${regionId}`, params);\n }\n\n /**\n * Delete a region\n * @param {number} regionId\n * @returns {Promise<void>}\n */\n async deleteRegion(regionId) {\n await this.request('DELETE', `/region/${regionId}`);\n }\n\n // ── Widget/Playlist Management ────────────────────────────────────\n\n /**\n * Add a widget to a playlist\n *\n * Xibo CMS v4 uses a two-step process:\n * 1. POST creates the widget shell (only templateId and displayOrder are processed)\n * 2. PUT sets all widget properties (uri, duration, mute, etc.)\n *\n * @param {string} type - Widget type (text, image, video, embedded, clock, etc.)\n * @param {number} playlistId - Target playlist ID (from region.playlists[0].playlistId)\n * @param {Object} [properties] - Widget-specific properties\n * @returns {Promise<Object>} Created widget with properties applied\n */\n async addWidget(type, playlistId, properties = {}) {\n // Step 1: Create the widget (only templateId/displayOrder handled by CMS addWidget)\n const { templateId, displayOrder, ...editProps } = properties;\n const createParams = {};\n if (templateId !== undefined) createParams.templateId = templateId;\n if (displayOrder !== undefined) createParams.displayOrder = displayOrder;\n\n const widget = await this.request('POST', `/playlist/widget/${type}/${playlistId}`, createParams);\n\n // Step 2: Set widget properties via editWidget (CMS processes all module properties here)\n if (Object.keys(editProps).length > 0) {\n // useDuration=1 tells CMS to use our custom duration instead of module default\n if (editProps.duration !== undefined && editProps.useDuration === undefined) {\n editProps.useDuration = 1;\n }\n return this.request('PUT', `/playlist/widget/${widget.widgetId}`, editProps);\n }\n\n return widget;\n }\n\n /**\n * Edit a widget's properties\n * @param {number} widgetId\n * @param {Object} properties - Widget-specific properties to update\n * @returns {Promise<Object>}\n */\n async editWidget(widgetId, properties) {\n return this.request('PUT', `/playlist/widget/${widgetId}`, properties);\n }\n\n /**\n * Delete a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async deleteWidget(widgetId) {\n await this.request('DELETE', `/playlist/widget/${widgetId}`);\n }\n\n // ── Media / Library ───────────────────────────────────────────────\n\n /**\n * Upload a media file to the library\n * @param {FormData} formData - Must include 'files' field with the file(s)\n * @returns {Promise<Object>} Upload result with media info\n */\n async uploadMedia(formData) {\n return this.requestMultipart('POST', '/library', formData);\n }\n\n /**\n * List media in the library\n * @param {Object} [filters] - Filters (mediaId, media, type, ownerId, etc.)\n * @returns {Promise<Array>}\n */\n async listMedia(filters = {}) {\n const data = await this.request('GET', '/library', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Get a single media item by ID\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMedia(mediaId) {\n return this.request('GET', `/library/${mediaId}`);\n }\n\n /**\n * Delete a media item from the library\n * @param {number} mediaId\n * @returns {Promise<void>}\n */\n async deleteMedia(mediaId) {\n await this.request('DELETE', `/library/${mediaId}`);\n }\n\n // ── Campaign Management ───────────────────────────────────────────\n\n /**\n * Create a campaign\n * @param {string} name - Campaign name\n * @returns {Promise<Object>} Created campaign\n */\n async createCampaign(name) {\n return this.request('POST', '/campaign', { name });\n }\n\n /**\n * List campaigns\n * @param {Object} [filters] - Filters (campaignId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listCampaigns(filters = {}) {\n const data = await this.request('GET', '/campaign', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Delete a campaign\n * @param {number} campaignId\n * @returns {Promise<void>}\n */\n async deleteCampaign(campaignId) {\n await this.request('DELETE', `/campaign/${campaignId}`);\n }\n\n /**\n * Assign a layout to a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @param {number} [displayOrder] - Position in campaign playlist\n * @returns {Promise<void>}\n */\n async assignLayoutToCampaign(campaignId, layoutId, displayOrder) {\n const params = { layoutId };\n if (displayOrder !== undefined) params.displayOrder = displayOrder;\n await this.request('POST', `/campaign/layout/assign/${campaignId}`, params);\n }\n\n // ── Schedule Management ───────────────────────────────────────────\n\n /**\n * Create a schedule event\n * @param {Object} params\n * @param {number} params.eventTypeId - 1=Campaign, 2=Command, 3=Overlay\n * @param {number} params.campaignId - Campaign to schedule\n * @param {Array<number>} params.displayGroupIds - Target display group IDs\n * @param {string} params.fromDt - Start date (ISO 8601)\n * @param {string} params.toDt - End date (ISO 8601)\n * @param {number} [params.isPriority] - 0 or 1\n * @param {number} [params.displayOrder] - Order within schedule\n * @returns {Promise<Object>} Created schedule event\n */\n async createSchedule(params) {\n // displayGroupIds needs to be sent as displayGroupIds[] for the API\n const body = { ...params };\n if (Array.isArray(body.displayGroupIds)) {\n // Xibo API expects repeated keys: displayGroupIds[]=1&displayGroupIds[]=2\n // URLSearchParams handles this when we pass entries manually\n delete body.displayGroupIds;\n }\n\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/schedule`;\n const urlParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(body)) {\n if (value !== undefined && value !== null) {\n urlParams.set(key, String(value));\n }\n }\n\n // Append array values as repeated keys\n if (Array.isArray(params.displayGroupIds)) {\n for (const id of params.displayGroupIds) {\n urlParams.append('displayGroupIds[]', String(id));\n }\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API POST /schedule failed (${response.status}): ${text}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n /**\n * Delete a schedule event\n * @param {number} eventId\n * @returns {Promise<void>}\n */\n async deleteSchedule(eventId) {\n await this.request('DELETE', `/schedule/${eventId}`);\n }\n\n /**\n * List schedule events\n * @param {Object} [filters] - Filters (displayGroupIds, fromDt, toDt)\n * @returns {Promise<Array>}\n */\n async listSchedules(filters = {}) {\n const data = await this.request('GET', '/schedule/data/events', filters);\n return Array.isArray(data) ? data : (data?.events || []);\n }\n\n // ── Display Group Management ──────────────────────────────────────\n\n /**\n * List display groups\n * @param {Object} [filters] - Filters (displayGroupId, displayGroup)\n * @returns {Promise<Array>}\n */\n async listDisplayGroups(filters = {}) {\n const data = await this.request('GET', '/displaygroup', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a display group\n * @param {string} name - Display group name\n * @param {string} [description]\n * @returns {Promise<Object>} Created display group\n */\n async createDisplayGroup(name, description) {\n const params = { displayGroup: name };\n if (description) params.description = description;\n return this.request('POST', '/displaygroup', params);\n }\n\n /**\n * Delete a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async deleteDisplayGroup(displayGroupId) {\n await this.request('DELETE', `/displaygroup/${displayGroupId}`);\n }\n\n /**\n * Assign a display to a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async assignDisplayToGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/assign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API assign display to group failed (${response.status}): ${text}`);\n }\n }\n\n /**\n * Unassign a display from a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async unassignDisplayFromGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/unassign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API unassign display from group failed (${response.status}): ${text}`);\n }\n }\n\n // ── Resolution Management ─────────────────────────────────────────\n\n /**\n * List available resolutions\n * @returns {Promise<Array>}\n */\n async listResolutions() {\n const data = await this.request('GET', '/resolution');\n return Array.isArray(data) ? data : [];\n }\n\n // ── Template Management ──────────────────────────────────────────\n\n /**\n * List available layout templates\n * @param {Object} [filters] - Filters (layout, tags, etc.)\n * @returns {Promise<Array>}\n */\n async listTemplates(filters = {}) {\n const data = await this.request('GET', '/template', filters);\n return Array.isArray(data) ? data : [];\n }\n\n // ── Playlist Management ──────────────────────────────────────────\n\n /**\n * Assign media library items to a playlist (for file-based widgets: audio, PDF, video)\n * @param {number} playlistId\n * @param {number[]} mediaIds - Array of media IDs to assign\n * @returns {Promise<Object>}\n */\n async assignMediaToPlaylist(playlistId, mediaIds) {\n const ids = Array.isArray(mediaIds) ? mediaIds : [mediaIds];\n // Xibo API expects media[] repeated keys\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/library/assign/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of ids) {\n urlParams.append('media[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/library/assign/${playlistId}`, response.status, text);\n }\n const contentType = response.headers.get('Content-Type') || '';\n return contentType.includes('application/json') ? response.json() : null;\n }\n\n // ── Layout Edit ───────────────────────────────────────────────────\n\n /**\n * Edit layout properties\n * @param {number} layoutId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editLayout(layoutId, params) {\n return this.request('PUT', `/layout/${layoutId}`, params);\n }\n\n // ── Layout Copy / Discard (#25) ────────────────────────────────────\n\n /**\n * Copy a layout\n * @param {number} layoutId\n * @param {Object} [opts] - Options (name, description, copyMediaFiles)\n * @returns {Promise<Object>} Copied layout\n */\n async copyLayout(layoutId, opts = {}) {\n return this.post(`/layout/copy/${layoutId}`, opts);\n }\n\n /**\n * Discard a draft layout (revert to last published version)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async discardLayout(layoutId) {\n await this.put(`/layout/discard/${layoutId}`);\n }\n\n // ── Campaign Edit / Unassign (#26) ─────────────────────────────────\n\n /**\n * Edit campaign properties\n * @param {number} campaignId\n * @param {Object} params - Properties to update (name, etc.)\n * @returns {Promise<Object>} Updated campaign\n */\n async editCampaign(campaignId, params) {\n return this.put(`/campaign/${campaignId}`, params);\n }\n\n /**\n * Get a single campaign by ID\n * @param {number} campaignId\n * @returns {Promise<Object>}\n */\n async getCampaign(campaignId) {\n return this.get(`/campaign/${campaignId}`);\n }\n\n /**\n * Unassign a layout from a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unassignLayoutFromCampaign(campaignId, layoutId) {\n await this.post(`/campaign/layout/unassign/${campaignId}`, { layoutId });\n }\n\n // ── Schedule Edit (#27) ────────────────────────────────────────────\n\n /**\n * Edit a schedule event\n * @param {number} eventId\n * @param {Object} params - Properties to update (fromDt, toDt, isPriority, etc.)\n * @returns {Promise<Object>} Updated schedule event\n */\n async editSchedule(eventId, params) {\n return this.put(`/schedule/${eventId}`, params);\n }\n\n // ── Layout Retire / Status / Tag (#34) ─────────────────────────────\n\n /**\n * Retire a layout (hide from new scheduling but keep existing schedules)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async retireLayout(layoutId) {\n await this.put(`/layout/retire/${layoutId}`);\n }\n\n /**\n * Unretire a previously retired layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unretireLayout(layoutId) {\n await this.put(`/layout/unretire/${layoutId}`);\n }\n\n /**\n * Get layout status (build status, validity)\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayoutStatus(layoutId) {\n return this.get(`/layout/status/${layoutId}`);\n }\n\n /**\n * Tag a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to add\n * @returns {Promise<void>}\n */\n async tagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/untag`, { tag: tags.join(',') });\n }\n\n // ── Command CRUD (#36) ─────────────────────────────────────────────\n\n /**\n * List commands\n * @param {Object} [filters] - Filters (commandId, command)\n * @returns {Promise<Array>}\n */\n async listCommands(filters = {}) {\n const data = await this.get('/command', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a command\n * @param {Object} params - { command, description, code }\n * @returns {Promise<Object>}\n */\n async createCommand(params) {\n return this.post('/command', params);\n }\n\n /**\n * Edit a command\n * @param {number} commandId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editCommand(commandId, params) {\n return this.put(`/command/${commandId}`, params);\n }\n\n /**\n * Delete a command\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async deleteCommand(commandId) {\n await this.del(`/command/${commandId}`);\n }\n\n // ── Display Extras (#41) ───────────────────────────────────────────\n\n /**\n * Delete a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async deleteDisplay(displayId) {\n await this.del(`/display/${displayId}`);\n }\n\n /**\n * Send Wake-on-LAN to a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async wolDisplay(displayId) {\n await this.post(`/display/wol/${displayId}`);\n }\n\n /**\n * Set the default layout for a display\n * @param {number} displayId\n * @param {number} layoutId - Layout to set as default\n * @returns {Promise<Object>}\n */\n async setDefaultLayout(displayId, layoutId) {\n return this.put(`/display/${displayId}`, { defaultLayoutId: layoutId });\n }\n\n /**\n * Purge all content from a display (force re-download)\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async purgeDisplay(displayId) {\n await this.post(`/display/purge/${displayId}`);\n }\n\n // ── DayPart CRUD (#24) ─────────────────────────────────────────────\n\n /**\n * List day parts\n * @param {Object} [filters] - Filters (dayPartId, name)\n * @returns {Promise<Array>}\n */\n async listDayParts(filters = {}) {\n const data = await this.get('/daypart', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a day part\n * @param {Object} params - { name, description, startTime, endTime, exceptionDays, ... }\n * @returns {Promise<Object>}\n */\n async createDayPart(params) {\n return this.post('/daypart', params);\n }\n\n /**\n * Edit a day part\n * @param {number} dayPartId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDayPart(dayPartId, params) {\n return this.put(`/daypart/${dayPartId}`, params);\n }\n\n /**\n * Delete a day part\n * @param {number} dayPartId\n * @returns {Promise<void>}\n */\n async deleteDayPart(dayPartId) {\n await this.del(`/daypart/${dayPartId}`);\n }\n\n // ── Library Extensions (#33) ───────────────────────────────────────\n\n /**\n * Upload media from a URL\n * @param {string} url - Remote URL to download\n * @param {string} name - Name for the media item\n * @returns {Promise<Object>}\n */\n async uploadMediaUrl(url, name) {\n return this.post('/library', { url, name, type: 'uri' });\n }\n\n /**\n * Copy a media item\n * @param {number} mediaId\n * @returns {Promise<Object>} Copied media\n */\n async copyMedia(mediaId) {\n return this.post(`/library/copy/${mediaId}`);\n }\n\n /**\n * Download a media file (returns raw response for streaming)\n * @param {number} mediaId\n * @returns {Promise<Response>} Raw fetch response\n */\n async downloadMedia(mediaId) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/library/download/${mediaId}`;\n const response = await fetch(url, {\n headers: { 'Authorization': `Bearer ${this.accessToken}` }\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('GET', `/library/download/${mediaId}`, response.status, text);\n }\n return response;\n }\n\n /**\n * Edit media properties\n * @param {number} mediaId\n * @param {Object} params - Properties to update (name, duration, retired, etc.)\n * @returns {Promise<Object>}\n */\n async editMedia(mediaId, params) {\n return this.put(`/library/${mediaId}`, params);\n }\n\n /**\n * Get media usage (which layouts/playlists reference this media)\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMediaUsage(mediaId) {\n return this.get(`/library/usage/${mediaId}`);\n }\n\n /**\n * Tidy the library (remove unused/old revisions)\n * @returns {Promise<void>}\n */\n async tidyLibrary() {\n await this.post('/library/tidy');\n }\n\n // ── Playlist CRUD (#35) ────────────────────────────────────────────\n\n /**\n * List playlists\n * @param {Object} [filters] - Filters (playlistId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listPlaylists(filters = {}) {\n const data = await this.get('/playlist', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a playlist\n * @param {string} name\n * @returns {Promise<Object>}\n */\n async createPlaylist(name) {\n return this.post('/playlist', { name });\n }\n\n /**\n * Get a single playlist by ID\n * @param {number} playlistId\n * @returns {Promise<Object>}\n */\n async getPlaylist(playlistId) {\n return this.get(`/playlist/${playlistId}`);\n }\n\n /**\n * Edit playlist properties\n * @param {number} playlistId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editPlaylist(playlistId, params) {\n return this.put(`/playlist/${playlistId}`, params);\n }\n\n /**\n * Delete a playlist\n * @param {number} playlistId\n * @returns {Promise<void>}\n */\n async deletePlaylist(playlistId) {\n await this.del(`/playlist/${playlistId}`);\n }\n\n /**\n * Reorder widgets in a playlist\n * @param {number} playlistId\n * @param {number[]} widgetIds - Ordered widget IDs\n * @returns {Promise<void>}\n */\n async reorderPlaylist(playlistId, widgetIds) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/order/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of widgetIds) {\n urlParams.append('widgets[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/order/${playlistId}`, response.status, text);\n }\n }\n\n /**\n * Copy a playlist\n * @param {number} playlistId\n * @returns {Promise<Object>} Copied playlist\n */\n async copyPlaylist(playlistId) {\n return this.post(`/playlist/copy/${playlistId}`);\n }\n\n // ── Widget Extras (#37) ────────────────────────────────────────────\n\n /**\n * Set transition for a widget\n * @param {number} widgetId\n * @param {string} type - Transition type (e.g. 'fly', 'fade')\n * @param {Object} [config] - Transition config (duration, direction)\n * @returns {Promise<Object>}\n */\n async setWidgetTransition(widgetId, type, config = {}) {\n return this.put(`/playlist/widget/transition/${widgetId}`, { type, ...config });\n }\n\n /**\n * Set audio for a widget\n * @param {number} widgetId\n * @param {Object} params - { mediaId, volume, loop }\n * @returns {Promise<Object>}\n */\n async setWidgetAudio(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/audio`, params);\n }\n\n /**\n * Remove audio from a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async removeWidgetAudio(widgetId) {\n await this.del(`/playlist/widget/${widgetId}/audio`);\n }\n\n /**\n * Set expiry dates for a widget\n * @param {number} widgetId\n * @param {Object} params - { fromDt, toDt, deleteOnExpiry }\n * @returns {Promise<Object>}\n */\n async setWidgetExpiry(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/expiry`, params);\n }\n\n // ── Template Save / Manage (#39) ───────────────────────────────────\n\n /**\n * Save a layout as a template\n * @param {number} layoutId\n * @param {Object} params - { name, description, includeWidgets }\n * @returns {Promise<Object>}\n */\n async saveAsTemplate(layoutId, params) {\n return this.post(`/template/${layoutId}`, params);\n }\n\n /**\n * Get a single template by ID\n * @param {number} templateId\n * @returns {Promise<Object>}\n */\n async getTemplate(templateId) {\n return this.get(`/template/${templateId}`);\n }\n\n /**\n * Delete a template\n * @param {number} templateId\n * @returns {Promise<void>}\n */\n async deleteTemplate(templateId) {\n await this.del(`/template/${templateId}`);\n }\n\n // ── Dataset CRUD (#28) ─────────────────────────────────────────────\n\n /**\n * List datasets\n * @param {Object} [filters] - Filters (dataSetId, dataSet)\n * @returns {Promise<Array>}\n */\n async listDatasets(filters = {}) {\n const data = await this.get('/dataset', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a dataset\n * @param {Object} params - { dataSet, description }\n * @returns {Promise<Object>}\n */\n async createDataset(params) {\n return this.post('/dataset', params);\n }\n\n /**\n * Edit a dataset\n * @param {number} dataSetId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDataset(dataSetId, params) {\n return this.put(`/dataset/${dataSetId}`, params);\n }\n\n /**\n * Delete a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async deleteDataset(dataSetId) {\n await this.del(`/dataset/${dataSetId}`);\n }\n\n /**\n * List columns in a dataset\n * @param {number} dataSetId\n * @returns {Promise<Array>}\n */\n async listDatasetColumns(dataSetId) {\n const data = await this.get(`/dataset/${dataSetId}/column`);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a column in a dataset\n * @param {number} dataSetId\n * @param {Object} params - { heading, dataTypeId, dataSetColumnTypeId, listContent, ... }\n * @returns {Promise<Object>}\n */\n async createDatasetColumn(dataSetId, params) {\n return this.post(`/dataset/${dataSetId}/column`, params);\n }\n\n /**\n * Edit a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDatasetColumn(dataSetId, columnId, params) {\n return this.put(`/dataset/${dataSetId}/column/${columnId}`, params);\n }\n\n /**\n * Delete a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @returns {Promise<void>}\n */\n async deleteDatasetColumn(dataSetId, columnId) {\n await this.del(`/dataset/${dataSetId}/column/${columnId}`);\n }\n\n /**\n * List rows (data) in a dataset\n * @param {number} dataSetId\n * @param {Object} [filters] - Filters (page, length)\n * @returns {Promise<Array>}\n */\n async listDatasetData(dataSetId, filters = {}) {\n const data = await this.get(`/dataset/data/${dataSetId}`, filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Add a row to a dataset\n * @param {number} dataSetId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async addDatasetRow(dataSetId, rowData) {\n return this.post(`/dataset/data/${dataSetId}`, rowData);\n }\n\n /**\n * Edit a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async editDatasetRow(dataSetId, rowId, rowData) {\n return this.put(`/dataset/data/${dataSetId}/${rowId}`, rowData);\n }\n\n /**\n * Delete a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @returns {Promise<void>}\n */\n async deleteDatasetRow(dataSetId, rowId) {\n await this.del(`/dataset/data/${dataSetId}/${rowId}`);\n }\n\n /**\n * Import CSV data into a dataset\n * @param {number} dataSetId\n * @param {FormData} formData - Must include CSV file\n * @returns {Promise<Object>}\n */\n async importDatasetCsv(dataSetId, formData) {\n return this.requestMultipart('POST', `/dataset/import/${dataSetId}`, formData);\n }\n\n /**\n * Clear all data from a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async clearDataset(dataSetId) {\n await this.del(`/dataset/data/${dataSetId}`);\n }\n\n // ── Notification CRUD (#29) ────────────────────────────────────────\n\n /**\n * List notifications\n * @param {Object} [filters] - Filters (notificationId, subject)\n * @returns {Promise<Array>}\n */\n async listNotifications(filters = {}) {\n const data = await this.get('/notification', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a notification\n * @param {Object} params - { subject, body, isEmail, isInterrupt, displayGroupIds, ... }\n * @returns {Promise<Object>}\n */\n async createNotification(params) {\n return this.post('/notification', params);\n }\n\n /**\n * Edit a notification\n * @param {number} notificationId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editNotification(notificationId, params) {\n return this.put(`/notification/${notificationId}`, params);\n }\n\n /**\n * Delete a notification\n * @param {number} notificationId\n * @returns {Promise<void>}\n */\n async deleteNotification(notificationId) {\n await this.del(`/notification/${notificationId}`);\n }\n\n // ── Folder CRUD (#30) ─────────────────────────────────────────────\n\n /**\n * List folders\n * @param {Object} [filters] - Filters (folderId, text)\n * @returns {Promise<Array>}\n */\n async listFolders(filters = {}) {\n const data = await this.get('/folder', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a folder\n * @param {Object} params - { text, parentId }\n * @returns {Promise<Object>}\n */\n async createFolder(params) {\n return this.post('/folder', params);\n }\n\n /**\n * Edit a folder\n * @param {number} folderId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editFolder(folderId, params) {\n return this.put(`/folder/${folderId}`, params);\n }\n\n /**\n * Delete a folder\n * @param {number} folderId\n * @returns {Promise<void>}\n */\n async deleteFolder(folderId) {\n await this.del(`/folder/${folderId}`);\n }\n\n // ── Tag CRUD + Entity Tagging (#31) ────────────────────────────────\n\n /**\n * List tags\n * @param {Object} [filters] - Filters (tagId, tag)\n * @returns {Promise<Array>}\n */\n async listTags(filters = {}) {\n const data = await this.get('/tag', filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Create a tag\n * @param {Object} params - { tag }\n * @returns {Promise<Object>}\n */\n async createTag(params) {\n return this.post('/tag', params);\n }\n\n /**\n * Edit a tag\n * @param {number} tagId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editTag(tagId, params) {\n return this.put(`/tag/${tagId}`, params);\n }\n\n /**\n * Delete a tag\n * @param {number} tagId\n * @returns {Promise<void>}\n */\n async deleteTag(tagId) {\n await this.del(`/tag/${tagId}`);\n }\n\n /**\n * Tag an entity (layout, media, campaign, etc.)\n * @param {string} entity - Entity type (layout, media, campaign, displaygroup, playlist)\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names\n * @returns {Promise<void>}\n */\n async tagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from an entity\n * @param {string} entity - Entity type\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/untag`, { tag: tags.join(',') });\n }\n\n // ── DisplayGroup Actions (#32) ─────────────────────────────────────\n\n /**\n * Change the layout on a display group (immediate override)\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgChangeLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/changeLayout`, { layoutId });\n }\n\n /**\n * Overlay a layout on a display group\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgOverlayLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/overlayLayout`, { layoutId });\n }\n\n /**\n * Revert a display group to its scheduled content\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgRevertToSchedule(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/revertToSchedule`);\n }\n\n /**\n * Trigger immediate content collection on a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgCollectNow(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/collectNow`);\n }\n\n /**\n * Send a command to a display group\n * @param {number} displayGroupId\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async dgSendCommand(displayGroupId, commandId) {\n await this.post(`/displaygroup/${displayGroupId}/action/command`, { commandId });\n }\n\n /**\n * Edit display group properties\n * @param {number} displayGroupId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDisplayGroup(displayGroupId, params) {\n return this.put(`/displaygroup/${displayGroupId}`, params);\n }\n}\n\n/**\n * Structured error for CMS API failures\n */\nexport class CmsApiError extends Error {\n constructor(method, path, status, detail) {\n super(`CMS API ${method} ${path} → ${status}: ${detail}`);\n this.name = 'CmsApiError';\n this.method = method;\n this.path = path;\n this.status = status;\n this.detail = detail;\n }\n}\n","/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\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 MAX_RETRIES = 3;\nconst RETRY_DELAY_MS = 500; // Fast: 500ms, 1s, 1.5s → total ~3s\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 * Rewrite an absolute CMS URL through the local proxy when running behind\n * the proxy server (Chromium kiosk or Electron).\n * Detection: SW/window on localhost:8765 = proxy mode.\n */\nexport function rewriteUrlForProxy(url) {\n if (!url.startsWith('http')) return url;\n const loc = typeof self !== 'undefined' ? self.location : undefined;\n if (!loc || loc.hostname !== 'localhost' || loc.port !== '8765') return url;\n const parsed = new URL(url);\n const cmsOrigin = parsed.origin;\n return `/file-proxy?cms=${encodeURIComponent(cmsOrigin)}&url=${encodeURIComponent(parsed.pathname + parsed.search)}`;\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 }\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 rewriteUrlForProxy(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\n for (let attempt = 1; attempt <= MAX_RETRIES; 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 < MAX_RETRIES) {\n const delay = RETRY_DELAY_MS * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${MAX_RETRIES} 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 rewriteUrlForProxy(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 if (this.totalBytes === 0) {\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\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n prioritize(fileType, fileId) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] Not found:', key);\n return false;\n }\n\n let boosted = 0;\n for (const t of this.queue) {\n if (t._parentFile === file && t._priority < PRIORITY.high) {\n t._priority = PRIORITY.high;\n boosted++;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Prioritized:', key, `(${boosted} tasks boosted)`);\n return true;\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n if (idSet.has(String(t._parentFile?.fileInfo.id)) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n if (idSet.has(String(t._parentFile?.fileInfo.id)) && 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 this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n /**\n * Wait for all queued prepare (HEAD) operations to finish.\n * Returns when the prepare queue is drained and all FileDownloads have\n * either created their tasks or failed.\n */\n awaitAllPrepared() {\n return new Promise((resolve) => {\n const check = () => {\n if (this._preparingCount === 0 && this._prepareQueue.length === 0) {\n resolve();\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n 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 }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n /**\n * Enqueue a file for layout-grouped downloading.\n * Layout grouping is now handled externally by LayoutTaskBuilder.\n * @param {Object} fileInfo - File info\n * @returns {FileDownload}\n */\n enqueueForLayout(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","/**\n * Simple EventEmitter implementation\n * Compatible with both browser and Node.js\n */\n\nexport class EventEmitter {\n constructor() {\n this.events = new Map();\n }\n\n /**\n * Register event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n on(event, callback) {\n if (!this.events.has(event)) {\n this.events.set(event, []);\n }\n this.events.get(event).push(callback);\n }\n\n /**\n * Register one-time event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n once(event, callback) {\n const wrapper = (...args) => {\n callback(...args);\n this.off(event, wrapper);\n };\n this.on(event, wrapper);\n }\n\n /**\n * Remove event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n off(event, callback) {\n if (!this.events.has(event)) return;\n\n const listeners = this.events.get(event);\n const index = listeners.indexOf(callback);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n }\n\n /**\n * Emit event\n * @param {string} event - Event name\n * @param {...any} args - Arguments to pass to listeners\n */\n emit(event, ...args) {\n if (!this.events.has(event)) return;\n\n // Make a copy to handle listeners that remove themselves during emission\n const listeners = this.events.get(event).slice();\n for (const listener of listeners) {\n listener(...args);\n }\n }\n\n /**\n * Remove all listeners for an event\n * @param {string} event - Event name (optional, removes all if not specified)\n */\n removeAllListeners(event) {\n if (event) {\n this.events.delete(event);\n } else {\n this.events.clear();\n }\n }\n}\n","/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the cache unification, all downloads and file retrieval go through\n * the Service Worker (via CacheProxy). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n * - Full cache clearing\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\nconst CACHE_NAME = 'xibo-media-v1';\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Get cache key for a file\n * For media, uses the actual filename; for layouts, uses the ID\n */\n getCacheKey(type, id, filename = null) {\n const key = filename || id;\n return `${BASE}/cache/${type}/${key}`;\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files\n */\n async clearAll() {\n await caches.delete(CACHE_NAME);\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","/**\n * CacheProxy - Service Worker cache interface\n *\n * Provides a proxy to Service Worker for background downloads and caching.\n * Service Worker MUST be available - no fallback (committed to SW architecture).\n *\n * Architecture:\n * ┌─────────────────────────────────────────┐\n * │ CacheProxy (Service Worker Only) │\n * │ - Waits for Service Worker ready │\n * │ - Routes all requests to SW │\n * │ - No fallback to direct cache │\n * └─────────────────────────────────────────┘\n * ↓\n * ┌──────────────────┐\n * │ ServiceWorker │\n * │ Backend │\n * │ - postMessage │\n * │ - Background DL │\n * └──────────────────┘\n *\n * Usage:\n * const proxy = new CacheProxy();\n * await proxy.init(); // Waits for SW to be ready\n *\n * const blob = await proxy.getFile('media', '123');\n * await proxy.requestDownload([{ id, type, path, md5 }]);\n * const isCached = await proxy.isCached('layout', '456');\n */\n\nimport { EventEmitter, createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheProxy');\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 * ServiceWorkerBackend - Uses Service Worker for downloads and caching\n */\nclass ServiceWorkerBackend extends EventEmitter {\n constructor() {\n super();\n this.controller = null;\n this.fetchReady = false;\n this.fetchReadyPromise = null;\n this.fetchReadyResolve = null;\n }\n\n async init() {\n // Create promise for fetch readiness (resolved when SW sends SW_READY)\n this.fetchReadyPromise = new Promise(resolve => {\n this.fetchReadyResolve = resolve;\n });\n\n // Listen for SW_READY message\n navigator.serviceWorker.addEventListener('message', (event) => {\n if (event.data?.type === 'SW_READY') {\n log.info('Received SW_READY signal - fetch handler is ready');\n this.fetchReady = true;\n this.fetchReadyResolve();\n }\n });\n\n // Get the active Service Worker (don't require controller)\n if ('serviceWorker' in navigator) {\n const registration = await navigator.serviceWorker.getRegistration();\n\n // Use active SW if it exists (controller not required!)\n if (registration && registration.active && registration.active.state === 'activated') {\n log.info('Using active Service Worker (controller not required)');\n this.controller = navigator.serviceWorker.controller || registration.active;\n\n // Request readiness signal from SW\n this.controller.postMessage({ type: 'PING' });\n\n log.info('Service Worker backend initialized, waiting for fetch readiness...');\n return;\n }\n\n // Fall back to waiting for ready\n await navigator.serviceWorker.ready;\n this.controller = navigator.serviceWorker.controller;\n\n if (!this.controller) {\n throw new Error('Service Worker not controlling page');\n }\n\n // Request readiness signal from SW\n this.controller.postMessage({ type: 'PING' });\n\n log.info('Service Worker backend initialized, waiting for fetch readiness...');\n } else {\n throw new Error('Service Worker not supported');\n }\n }\n\n /**\n * Get file from cache (via Service Worker)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<Blob|null>}\n */\n async getFile(type, id) {\n // Wait for SW fetch handler to be ready (eliminates race condition)\n if (!this.fetchReady) {\n log.debug(`Waiting for SW fetch handler to be ready before fetching ${type}/${id}...`);\n await this.fetchReadyPromise;\n log.debug(`SW fetch handler ready, proceeding with fetch`);\n }\n\n // Service Worker serves files via fetch interception\n // Construct cache URL and fetch it\n const cacheUrl = `${BASE}/cache/${type}/${id}`;\n\n log.debug(`getFile(${type}, ${id}) → fetching ${cacheUrl}`);\n log.debug(`About to call fetch()...`);\n\n try {\n log.debug(`Calling fetch(${cacheUrl})...`);\n const response = await fetch(cacheUrl);\n log.debug(`fetch returned, status:`, response.status, response.statusText);\n\n if (!response.ok) {\n log.debug(`Response not OK (${response.status}), returning null`);\n if (response.status === 404) {\n return null; // Not cached\n }\n throw new Error(`Failed to get file: ${response.status}`);\n }\n\n log.debug(`Response OK, getting blob...`);\n const blob = await response.blob();\n log.debug(`Got blob, size:`, blob.size);\n return blob;\n } catch (error) {\n log.error('getFile EXCEPTION:', error);\n log.error('Error name:', error.name);\n log.error('Error message:', error.message);\n return null;\n }\n }\n\n /**\n * Check if file exists in cache (supports both whole files and chunked storage)\n * Service Worker's CacheManager.fileExists() handles the logic internally\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async hasFile(type, id) {\n // Wait for SW fetch handler to be ready\n if (!this.fetchReady) {\n await this.fetchReadyPromise;\n }\n\n const cacheUrl = `${BASE}/cache/${type}/${id}`;\n\n try {\n // SW's handleRequest uses CacheManager.fileExists() internally\n // Returns 200 for both whole files and chunked files (via metadata check)\n const response = await fetch(cacheUrl, { method: 'HEAD' });\n return response.ok;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Request downloads from Service Worker (non-blocking)\n * @param {Object|Array} payload - Either { layouts: [{ layoutId, mediaFiles }] } or flat Array of files\n * @returns {Promise<void>}\n */\n async requestDownload(payload) {\n if (!this.controller) {\n throw new Error('Service Worker not available');\n }\n\n // Support both grouped and flat payload (backward compat)\n const data = Array.isArray(payload)\n ? { files: payload }\n : payload;\n\n return new Promise((resolve, reject) => {\n const messageChannel = new MessageChannel();\n\n messageChannel.port1.onmessage = (event) => {\n const { success, error, enqueuedCount, activeCount, queuedCount } = event.data;\n if (success) {\n log.info('Download request acknowledged:', enqueuedCount, 'files');\n log.info('Queue state:', activeCount, 'active,', queuedCount, 'queued');\n resolve();\n } else {\n reject(new Error(error || 'Service Worker download failed'));\n }\n };\n\n this.controller.postMessage(\n {\n type: 'DOWNLOAD_FILES',\n data\n },\n [messageChannel.port2]\n );\n });\n }\n\n /**\n * Tell SW to prioritize downloading a specific file\n * Moves it to the front of the download queue if still queued\n * @param {string} fileType - 'media' or 'layout'\n * @param {string} fileId - File ID\n */\n async prioritizeDownload(fileType, fileId) {\n if (!this.controller) return;\n\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => resolve(event.data);\n this.controller.postMessage(\n { type: 'PRIORITIZE_DOWNLOAD', data: { fileType, fileId } },\n [messageChannel.port2]\n );\n });\n }\n\n /**\n * Check if file is cached (delegates to hasFile for consistent fetchReady handling)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async isCached(type, id) {\n return this.hasFile(type, id);\n }\n\n /**\n * Prioritize layout files — reorder queue and hold other downloads until done.\n * @param {string[]} mediaIds - Media IDs needed by the current layout\n */\n async prioritizeLayoutFiles(mediaIds) {\n if (!this.controller) return;\n this.controller.postMessage({ type: 'PRIORITIZE_LAYOUT_FILES', data: { mediaIds } });\n }\n}\n\n// DirectCacheBackend removed - Service Worker only architecture\n\n/**\n * CacheProxy - Service Worker only interface\n */\nexport class CacheProxy extends EventEmitter {\n constructor() {\n super();\n this.backend = null;\n this.backendType = 'service-worker';\n }\n\n /**\n * Initialize proxy - WAITS for Service Worker to be ready\n */\n async init() {\n if (!('serviceWorker' in navigator)) {\n throw new Error('Service Worker not supported - PWA requires Service Worker');\n }\n\n log.debug('Checking Service Worker state...');\n log.debug('controller =', navigator.serviceWorker.controller);\n\n // Check if SW registration exists (better than checking controller)\n const registration = await navigator.serviceWorker.getRegistration();\n log.debug('registration =', registration);\n log.debug('active =', registration?.active);\n log.debug('installing =', registration?.installing);\n log.debug('waiting =', registration?.waiting);\n\n // FAST PATH: If active SW exists AND no new SW is installing, use it immediately\n if (registration && registration.active && !registration.installing && !registration.waiting) {\n log.info('Active Service Worker found (no updates pending)');\n log.debug('SW state =', registration.active.state);\n\n // If not controlling yet, give it a moment to claim page\n if (!navigator.serviceWorker.controller) {\n log.debug('Not controlling yet, waiting 200ms for claim...');\n await new Promise(resolve => setTimeout(resolve, 200));\n log.debug('After wait, controller =', navigator.serviceWorker.controller);\n }\n\n // Use the active SW (even if controller is still null - it will work)\n this.backend = new ServiceWorkerBackend();\n await this.backend.init();\n log.info('Service Worker backend ready (fast path)');\n return;\n }\n\n // If there's a new SW installing/waiting, wait for it instead of using old one\n if (registration && (registration.installing || registration.waiting)) {\n log.info('New Service Worker detected, waiting for it to activate...');\n log.debug('installing =', registration.installing?.state);\n log.debug('waiting =', registration.waiting?.state);\n }\n\n // SLOW PATH: No active SW, wait for registration (fresh install)\n log.info('No active Service Worker, waiting for registration...');\n\n // Wait with timeout\n const swReady = navigator.serviceWorker.ready;\n const timeout = new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Service Worker ready timeout after 10s')), 10000)\n );\n\n try {\n await Promise.race([swReady, timeout]);\n log.debug('Service Worker ready promise resolved');\n } catch (error) {\n log.error('Service Worker wait failed:', error);\n throw new Error('Service Worker not ready - please reload page');\n }\n\n // Wait for SW to claim page\n await new Promise(resolve => setTimeout(resolve, 100));\n log.debug('After claim wait, controller =', navigator.serviceWorker.controller);\n\n // Controller not required - we can use registration.active instead\n // This handles the case where SW is active but hasn't set controller yet (timing issue)\n this.backend = new ServiceWorkerBackend();\n await this.backend.init();\n log.info('Service Worker backend ready (slow path)');\n }\n\n /**\n * Get file from cache\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<Blob|null>}\n */\n async getFile(type, id) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.getFile(type, id);\n }\n\n /**\n * Check if file exists in cache (for streaming - no blob creation)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async hasFile(type, id) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.hasFile(type, id);\n }\n\n /**\n * Request file downloads\n * Service Worker: Non-blocking (downloads in background)\n * Direct cache: Blocking (downloads sequentially)\n *\n * @param {Array} files - Array of { id, type, path, md5 }\n * @returns {Promise<void>}\n */\n async requestDownload(files) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.requestDownload(files);\n }\n\n /**\n * Prioritize downloading a specific file (move to front of queue)\n * @param {string} fileType - 'media' or 'layout'\n * @param {string} fileId - File ID\n */\n async prioritizeDownload(fileType, fileId) {\n if (!this.backend?.prioritizeDownload) return;\n return await this.backend.prioritizeDownload(fileType, fileId);\n }\n\n /**\n * Check if file is cached (delegates to hasFile for consistent fetchReady handling)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async isCached(type, id) {\n return this.hasFile(type, id);\n }\n\n /**\n * Prioritize layout files — reorder queue and hold other downloads until done.\n * @param {string[]} mediaIds - Media IDs needed by the current layout\n */\n async prioritizeLayoutFiles(mediaIds) {\n if (!this.backend?.prioritizeLayoutFiles) return;\n return await this.backend.prioritizeLayoutFiles(mediaIds);\n }\n\n /**\n * Get backend type for debugging\n * @returns {string} 'service-worker' or 'direct'\n */\n getBackendType() {\n return this.backendType;\n }\n\n /**\n * Check if Service Worker is being used\n * @returns {boolean}\n */\n isUsingServiceWorker() {\n return this.backendType === 'service-worker';\n }\n\n /**\n * Get all cached files from Service Worker\n * @returns {Promise<Array<{id: string, type: string, size: number, cachedAt: number}>>}\n */\n async getAllFiles() {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, files } = event.data;\n resolve(success ? files : []);\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'GET_ALL_FILES' },\n [channel.port2]\n );\n\n setTimeout(() => resolve([]), 5000);\n });\n }\n\n /**\n * Delete files from cache (purge obsolete media)\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async deleteFiles(files) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, error, deleted, total } = event.data;\n if (success) {\n resolve({ deleted, total });\n } else {\n reject(new Error(error || 'Delete failed'));\n }\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'DELETE_FILES', data: { files } },\n [channel.port2]\n );\n\n setTimeout(() => resolve({ deleted: 0, total: files.length }), 5000);\n });\n }\n\n /**\n * Pre-warm video chunks into SW BlobCache for faster playback startup.\n * Loads first and last chunks into memory so moov atom probing is instant.\n * @param {number[]} mediaIds - Media file IDs to pre-warm\n * @returns {Promise<{warmed: number, total: number}>}\n */\n async prewarmVideoChunks(mediaIds) {\n if (!mediaIds || mediaIds.length === 0) return { warmed: 0, total: 0 };\n\n const controller = navigator.serviceWorker?.controller;\n if (!controller) return { warmed: 0, total: mediaIds.length };\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, warmed, total } = event.data;\n resolve(success ? { warmed, total } : { warmed: 0, total: mediaIds.length });\n };\n\n controller.postMessage(\n { type: 'PREWARM_VIDEO_CHUNKS', data: { mediaIds } },\n [channel.port2]\n );\n\n // Don't block layout rendering for more than 2s\n setTimeout(() => resolve({ warmed: 0, total: mediaIds.length }), 2000);\n });\n }\n\n /**\n * Get download progress from Service Worker\n * @returns {Promise<Object>} Progress info for all active downloads\n */\n async getDownloadProgress() {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, progress } = event.data;\n resolve(success ? progress : {});\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'GET_DOWNLOAD_PROGRESS' },\n [channel.port2]\n );\n\n // Timeout after 1 second\n setTimeout(() => resolve({}), 1000);\n });\n }\n}\n","/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\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 MAX_RETRIES = 3;\nconst RETRY_DELAY_MS = 500; // Fast: 500ms, 1s, 1.5s → total ~3s\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 * Rewrite an absolute CMS URL through the local proxy when running behind\n * the proxy server (Chromium kiosk or Electron).\n * Detection: SW/window on localhost (any port) = proxy mode.\n */\nexport function rewriteUrlForProxy(url) {\n if (!url.startsWith('http')) return url;\n const loc = typeof self !== 'undefined' ? self.location : undefined;\n if (!loc || loc.hostname !== 'localhost') return url;\n const parsed = new URL(url);\n const cmsOrigin = parsed.origin;\n return `/file-proxy?cms=${encodeURIComponent(cmsOrigin)}&url=${encodeURIComponent(parsed.pathname + parsed.search)}`;\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 }\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 rewriteUrlForProxy(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\n for (let attempt = 1; attempt <= MAX_RETRIES; 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 < MAX_RETRIES) {\n const delay = RETRY_DELAY_MS * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${MAX_RETRIES} 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 rewriteUrlForProxy(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 if (this.totalBytes === 0) {\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\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n prioritize(fileType, fileId) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] Not found:', key);\n return false;\n }\n\n let boosted = 0;\n for (const t of this.queue) {\n if (t._parentFile === file && t._priority < PRIORITY.high) {\n t._priority = PRIORITY.high;\n boosted++;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Prioritized:', key, `(${boosted} tasks boosted)`);\n return true;\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n if (idSet.has(String(t._parentFile?.fileInfo.id)) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n if (idSet.has(String(t._parentFile?.fileInfo.id)) && 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 this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n /**\n * Wait for all queued prepare (HEAD) operations to finish.\n * Returns when the prepare queue is drained and all FileDownloads have\n * either created their tasks or failed.\n */\n awaitAllPrepared() {\n return new Promise((resolve) => {\n const check = () => {\n if (this._preparingCount === 0 && this._prepareQueue.length === 0) {\n resolve();\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n 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 }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n /**\n * Enqueue a file for layout-grouped downloading.\n * Layout grouping is now handled externally by LayoutTaskBuilder.\n * @param {Object} fileInfo - File info\n * @returns {FileDownload}\n */\n enqueueForLayout(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through CacheProxy (postMessage to SW) — 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('./cache-proxy.js').CacheProxy} cache - CacheProxy 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.getAllFiles();\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 {\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 CacheProxy.deleteFiles() which routes to SW.\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.deleteFiles(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","/**\n * Widget HTML caching — preprocesses widget HTML and stores in Cache API\n *\n * Handles:\n * - <base> tag injection for relative path resolution\n * - CMS signed URL → local cache path rewriting\n * - CSS font URL rewriting and font file caching\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Uses Cache API directly — the SW also serves from the same cache.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\nconst CACHE_NAME = 'xibo-media-v1';\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 cache for iframe loading\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\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${BASE}/cache/widget/${layoutId}/${regionId}/${mediaId}`;\n const cache = await caches.open(CACHE_NAME);\n\n // Inject <base> tag to fix relative paths for widget dependencies\n // Widget HTML has relative paths like \"bundle.min.js\" that should resolve to cache/media/\n const baseTag = `<base href=\"${BASE}/cache/media/\">`;\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 // No head tag, prepend base tag\n modifiedHtml = baseTag + html;\n }\n }\n\n // Rewrite absolute CMS signed URLs to local cache paths\n // Matches: https://cms/xmds.php?file=... or https://cms/pwa/file?file=...\n // These absolute URLs bypass the <base> tag entirely, causing slow CMS fetches\n const cmsUrlRegex = /https?:\\/\\/[^\"'\\s)]+(?:xmds\\.php|pwa\\/file)\\?[^\"'\\s)]*file=([^&\"'\\s)]+)[^\"'\\s)]*/g;\n const staticResources = [];\n modifiedHtml = modifiedHtml.replace(cmsUrlRegex, (match, filename) => {\n const localPath = `${BASE}/cache/static/${filename}`;\n staticResources.push({ filename, originalUrl: match });\n log.info(`Rewrote widget URL: ${filename} → ${localPath}`);\n return localPath;\n });\n\n // Inject CSS default for object-position to suppress CMS template warning\n // CMS global-elements.xml uses {{alignId}} {{valignId}} which produces\n // invalid CSS (empty value) when alignment is not configured\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n // The IC library uses hostAddress + '/info', '/trigger', etc.\n // Original: hostAddress: \"https://cms.example.com\" → XHR to /info goes to CMS (fails)\n // Rewritten: hostAddress: \"/player/pwa/ic\" → XHR to /player/pwa/ic/info (intercepted by SW)\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag and rewrote CMS/data URLs in widget HTML');\n\n // Construct full URL for cache storage\n const cacheUrl = new URL(cacheKey, window.location.origin);\n\n const response = new Response(modifiedHtml, {\n headers: {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Access-Control-Allow-Origin': '*'\n }\n });\n\n await cache.put(cacheUrl, response);\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n // Fetch and cache static resources (shared Cache API - accessible from main thread and SW)\n if (staticResources.length > 0) {\n const STATIC_CACHE_NAME = 'xibo-static-v1';\n const staticCache = await caches.open(STATIC_CACHE_NAME);\n\n await Promise.all(staticResources.map(async ({ filename, originalUrl }) => {\n const staticKey = `${BASE}/cache/static/${filename}`;\n const existing = await staticCache.match(staticKey);\n if (existing) return; // Already cached\n\n try {\n const resp = await fetch(originalUrl);\n if (!resp.ok) {\n log.warn(`Failed to fetch static resource: ${filename} (HTTP ${resp.status})`);\n return;\n }\n\n const ext = filename.split('.').pop().toLowerCase();\n const contentType = {\n 'js': 'application/javascript',\n 'css': 'text/css',\n 'otf': 'font/otf', 'ttf': 'font/ttf',\n 'woff': 'font/woff', 'woff2': 'font/woff2',\n 'eot': 'application/vnd.ms-fontobject',\n 'svg': 'image/svg+xml'\n }[ext] || 'application/octet-stream';\n\n // For CSS files, rewrite font URLs and cache referenced font files\n if (ext === 'css') {\n let cssText = await resp.text();\n const fontResources = [];\n const fontUrlRegex = /url\\((['\"]?)(https?:\\/\\/[^'\")\\s]+\\?[^'\")\\s]*file=([^&'\")\\s]+\\.(?:woff2?|ttf|otf|eot|svg))[^'\")\\s]*)\\1\\)/gi;\n cssText = cssText.replace(fontUrlRegex, (_match, quote, fullUrl, fontFilename) => {\n fontResources.push({ filename: fontFilename, originalUrl: fullUrl });\n log.info(`Rewrote font URL in CSS: ${fontFilename}`);\n return `url(${quote}${BASE}/cache/static/${encodeURIComponent(fontFilename)}${quote})`;\n });\n\n await staticCache.put(staticKey, new Response(cssText, {\n headers: { 'Content-Type': 'text/css' }\n }));\n log.info(`Cached CSS with ${fontResources.length} rewritten font URLs: ${filename}`);\n\n // Fetch and cache referenced font files\n await Promise.all(fontResources.map(async ({ filename: fontFile, originalUrl: fontUrl }) => {\n const fontKey = `${BASE}/cache/static/${encodeURIComponent(fontFile)}`;\n const existingFont = await staticCache.match(fontKey);\n if (existingFont) return; // Already cached (by SW or previous widget)\n\n try {\n const fontResp = await fetch(fontUrl);\n if (!fontResp.ok) {\n log.warn(`Failed to fetch font: ${fontFile} (HTTP ${fontResp.status})`);\n return;\n }\n const fontBlob = await fontResp.blob();\n const fontExt = fontFile.split('.').pop().toLowerCase();\n const fontContentType = {\n 'otf': 'font/otf', 'ttf': 'font/ttf',\n 'woff': 'font/woff', 'woff2': 'font/woff2',\n 'eot': 'application/vnd.ms-fontobject',\n 'svg': 'image/svg+xml'\n }[fontExt] || 'application/octet-stream';\n\n await staticCache.put(fontKey, new Response(fontBlob, {\n headers: { 'Content-Type': fontContentType }\n }));\n log.info(`Cached font: ${fontFile} (${fontContentType}, ${fontBlob.size} bytes)`);\n } catch (fontErr) {\n log.warn(`Failed to cache font: ${fontFile}`, fontErr);\n }\n }));\n } else {\n const blob = await resp.blob();\n await staticCache.put(staticKey, new Response(blob, {\n headers: { 'Content-Type': contentType }\n }));\n log.info(`Cached static resource: ${filename} (${contentType}, ${blob.size} bytes)`);\n }\n } catch (error) {\n log.warn(`Failed to cache static resource: ${filename}`, error);\n }\n }));\n }\n\n return cacheKey;\n}\n"],"names":["LOG_LEVELS","logSinks","Logger","name","level","globalConfig","args","_dispatchToSinks","key","hasLocalOverride","urlLevel","storageLevel","createLogger","applyCmsLogLevel","cmsLevel","mapped","mapCmsLogLevel","fn","arrayBufferToPem","buffer","type","bytes","binary","i","base64","lines","generateRsaKeyPair","keyPair","publicKeyDer","privateKeyDer","isValidPemKey","pem","STORAGE_KEY","HW_DB_NAME","HW_DB_VERSION","loadFromEnv","env","define_process_env_default","envConfig","v","Config","json","config","e","changed","keys","req","db","tx","store","k","resolve","reject","backedUpKey","hardwareKey","canvas","ctx","c","r","publicKeyPem","privateKeyPem","str","hash","result","round","roundHash","val","log","DEFAULT_429_DELAY_MS","MAX_429_DELAY_MS","parseRetryAfter","headerValue","seconds","date","delayMs","fetchWithRetry","url","options","retryOptions","maxRetries","baseDelayMs","maxDelayMs","lastError","lastResponse","attempt","response","error","jitter","DEFAULT_CONCURRENCY","DEFAULT_CHUNK_SIZE","DEFAULT_MAX_CHUNKS_PER_FILE","CHUNK_THRESHOLD","MAX_RETRIES","RETRY_DELAY_MS","URGENT_CONCURRENCY","FETCH_TIMEOUT_MS","HEAD_TIMEOUT_MS","inferContentType","fileInfo","ext","_b","_a","PRIORITY","BARRIER","getUrlExpiry","match","isUrlExpired","graceSeconds","expiry","rewriteUrlForProxy","loc","parsed","cmsOrigin","DownloadTask$1","headers","ac","timer","fetchOpts","msg","delay","chunkLabel","FileDownload$1","res","rej","queue","id","size","head","chunkSize","ranges","start","needed","skippedCount","isResume","sorted","a","b","task","DownloadTask","highCount","t","ordered","blob","assembled","LayoutTaskBuilder$1","DownloadQueue","existing","oldExpiry","file","FileDownload","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","total","DownloadQueue$1","items","taskCount","barrierCount","item","fileType","fileId","boosted","fileIds","priority","idSet","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","err","check","progress","EventEmitter","event","callback","wrapper","listeners","index","listener","CACHE_NAME","BASE","CacheManager","filename","mediaId","layoutId","lid","orphaned","layouts","cacheManager","ServiceWorkerBackend","registration","cacheUrl","payload","data","messageChannel","success","enqueuedCount","activeCount","queuedCount","mediaIds","CacheProxy","swReady","timeout","_","files","channel","deleted","controller","warmed","LayoutTaskBuilder","DownloadManager","formatBytes","units","CacheAnalyzer","cache","threshold","requiredFiles","cachedFiles","storage","requiredIds","f","required","parentLayoutId","orphanedSize","sum","report","age","days","hours","ageStr","targetBytes","usage","quota","orphanedFiles","toEvict","plannedBytes","filesToDelete","cacheWidgetHtml","regionId","html","cacheKey","baseTag","modifiedHtml","cmsUrlRegex","staticResources","localPath","cssFixTag","staticCache","originalUrl","staticKey","resp","contentType","cssText","fontResources","fontUrlRegex","_match","quote","fullUrl","fontFilename","fontFile","fontUrl","fontKey","fontResp","fontBlob","fontExt","fontContentType","fontErr"],"mappings":"0CAkBA,MAAMA,EAAa,CACjB,MAAO,EACP,KAAM,EACN,QAAS,EACT,MAAO,EACP,KAAM,CACR,EAGMC,GAAW,CAAA,EAEjB,MAAMC,EAAO,CAKX,YAAYC,EAAMC,EAAQ,KAAM,CAC9B,KAAK,KAAOD,EACZ,KAAK,UAAaC,IAAU,KACvB,KAAK,WACR,KAAK,SAASA,CAAK,CAEvB,CAEA,SAASA,EAAO,CACd,KAAK,UAAY,GACb,OAAOA,GAAU,SACnB,KAAK,MAAQJ,EAAWI,EAAM,YAAW,CAAE,GAAKJ,EAAW,KAE3D,KAAK,MAAQI,CAEjB,CAGA,mBAAoB,CAClB,OAAO,KAAK,UAAYC,EAAa,MAAQ,KAAK,KACpD,CAEA,SAASC,EAAM,CACT,KAAK,qBAAuBN,EAAW,OACzC,QAAQ,IAAI,IAAI,KAAK,IAAI,WAAY,GAAGM,CAAI,EAE9CC,EAAiB,QAAS,KAAK,KAAMD,CAAI,CAC3C,CAEA,QAAQA,EAAM,CACR,KAAK,qBAAuBN,EAAW,MACzC,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAK,GAAGM,CAAI,EAEvCC,EAAiB,OAAQ,KAAK,KAAMD,CAAI,CAC1C,CAEA,QAAQA,EAAM,CACR,KAAK,qBAAuBN,EAAW,SACzC,QAAQ,KAAK,IAAI,KAAK,IAAI,IAAK,GAAGM,CAAI,EAExCC,EAAiB,UAAW,KAAK,KAAMD,CAAI,CAC7C,CAE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