@xiboplayer/pwa 0.6.11 → 0.6.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/chunk-config-C9U90T6u.js +2 -0
- package/dist/assets/chunk-config-C9U90T6u.js.map +1 -0
- package/dist/assets/{index-DMq935D7.js → index-B2dyKYhW.js} +2 -2
- package/dist/assets/{index-DMq935D7.js.map → index-B2dyKYhW.js.map} +1 -1
- package/dist/assets/{index-Dllq0Rxc.js → index-B57dvLVB.js} +2 -2
- package/dist/assets/{index-Dllq0Rxc.js.map → index-B57dvLVB.js.map} +1 -1
- package/dist/assets/{index-DuYioXxs.js → index-B_ADwXGQ.js} +2 -2
- package/dist/assets/{index-DuYioXxs.js.map → index-B_ADwXGQ.js.map} +1 -1
- package/dist/assets/{index-D3ONc-uh.js → index-BpwloMHc.js} +2 -2
- package/dist/assets/{index-D3ONc-uh.js.map → index-BpwloMHc.js.map} +1 -1
- package/dist/assets/{index-DpUJWDra.js → index-CLgKYdBJ.js} +2 -2
- package/dist/assets/{index-DpUJWDra.js.map → index-CLgKYdBJ.js.map} +1 -1
- package/dist/assets/index-ClTQ0ldA.js +2 -0
- package/dist/assets/{index-B2q-aBh8.js.map → index-ClTQ0ldA.js.map} +1 -1
- package/dist/assets/index-D39gYDMZ.js +2 -0
- package/dist/assets/{index-I6Jt7iN-.js.map → index-D39gYDMZ.js.map} +1 -1
- package/dist/assets/{index-DLnEjxEP.js → index-D9_3Ns4E.js} +2 -2
- package/dist/assets/{index-DLnEjxEP.js.map → index-D9_3Ns4E.js.map} +1 -1
- package/dist/assets/{index-DhU2Fgj5.js → index-GPOkOOlx.js} +2 -2
- package/dist/assets/{index-DhU2Fgj5.js.map → index-GPOkOOlx.js.map} +1 -1
- package/dist/assets/{index-DaK61i9Z.js → index-dBd5BTjH.js} +2 -2
- package/dist/assets/{index-DaK61i9Z.js.map → index-dBd5BTjH.js.map} +1 -1
- package/dist/assets/{main-D251kcoe.js → main-GlNtH9kX.js} +6 -6
- package/dist/assets/main-GlNtH9kX.js.map +1 -0
- package/dist/assets/{protocol-detector-BEdREUxU.js → protocol-detector-CpRVVofI.js} +3 -3
- package/dist/assets/protocol-detector-CpRVVofI.js.map +1 -0
- package/dist/assets/{setup-DbE9wDXy.js → setup-CInkLEZK.js} +2 -2
- package/dist/assets/{setup-DbE9wDXy.js.map → setup-CInkLEZK.js.map} +1 -1
- package/dist/assets/{sync-manager-CNULCESw.js → sync-manager-C0UDCBzv.js} +2 -2
- package/dist/assets/{sync-manager-CNULCESw.js.map → sync-manager-C0UDCBzv.js.map} +1 -1
- package/dist/assets/widget-html-BSjCib6e.js +2 -0
- package/dist/assets/widget-html-BSjCib6e.js.map +1 -0
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +13 -13
- package/dist/assets/chunk-config-C86koBXE.js +0 -2
- package/dist/assets/chunk-config-C86koBXE.js.map +0 -1
- package/dist/assets/index-B2q-aBh8.js +0 -2
- package/dist/assets/index-I6Jt7iN-.js +0 -2
- package/dist/assets/main-D251kcoe.js.map +0 -1
- package/dist/assets/protocol-detector-BEdREUxU.js.map +0 -1
- package/dist/assets/widget-html-CRNarPfj.js +0 -2
- package/dist/assets/widget-html-CRNarPfj.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-detector-BEdREUxU.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js","../../../xmds/src/cms-client.js","../../../xmds/src/protocol-detector.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * REST transport client for Xibo CMS Player API.\n *\n * Uses the Player API REST endpoints with JWT auth, resource-oriented URLs,\n * and native JSON responses (no XML parsing required).\n *\n * - JWT bearer token auth (single POST /auth → token for all requests)\n * - Resource-oriented URLs (/displays/{id}/schedule vs /schedule)\n * - Native JSON schedule (no client-side XML parsing)\n * - Categorized required files (media/layouts/widgets)\n * - CDN/reverse proxy compatible (GET with cache headers)\n *\n * Same public API as XmdsClient — drop-in replacement.\n */\nimport { createLogger, fetchWithRetry, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('REST');\n\nexport class RestClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 7;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n\n // JWT auth state\n this._token = null;\n this._tokenExpiresAt = 0;\n this._displayId = null;\n\n // ETag-based HTTP caching\n this._etags = new Map();\n this._responseCache = new Map();\n\n log.info('Using REST transport');\n }\n\n // ─── Transport helpers ──────────────────────────────────────────\n\n /**\n * Get the REST API base URL.\n * In proxy mode (Electron/Chromium), returns the local relative path so\n * requests go through the Express proxy's mirror routes.\n * In direct mode (standalone PWA), returns the full CMS URL.\n */\n getRestBaseUrl() {\n if (this._isProxyMode()) {\n return `${window.location.origin}${PLAYER_API}`;\n }\n const base = this.config.restApiUrl || `${this.config.cmsUrl}${PLAYER_API}`;\n return base.replace(/\\/+$/, '');\n }\n\n /**\n * Check if running behind the local proxy (Electron or Chromium kiosk).\n */\n _isProxyMode() {\n return typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost');\n }\n\n // ─── JWT auth ─────────────────────────────────────────────────\n\n /**\n * Authenticate with the CMS and obtain a JWT token.\n * Called automatically before the first authenticated request.\n */\n async _authenticate() {\n const url = `${this.getRestBaseUrl()}/auth`;\n\n log.debug('Authenticating...');\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n }),\n }, this.retryOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`Auth failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const data = await response.json();\n this._token = data.token;\n this._displayId = data.displayId;\n // Refresh 60s before expiry to avoid edge-case rejections\n this._tokenExpiresAt = Date.now() + (data.expiresIn - 60) * 1000;\n\n log.info(`Authenticated as display ${this._displayId}`);\n }\n\n /**\n * Get a valid JWT token, refreshing if expired or missing.\n */\n async _getToken() {\n if (!this._token || Date.now() >= this._tokenExpiresAt) {\n await this._authenticate();\n }\n return this._token;\n }\n\n /**\n * Make an authenticated GET request with ETag caching.\n */\n async restGet(path, queryParams = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, String(value));\n }\n\n const cacheKey = path;\n const headers = { 'Authorization': `Bearer ${token}` };\n const cachedEtag = this._etags.get(cacheKey);\n if (cachedEtag) {\n headers['If-None-Match'] = cachedEtag;\n }\n\n log.debug(`GET ${path}`, queryParams);\n\n const response = await fetchWithRetry(url.toString(), {\n method: 'GET',\n headers,\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restGet(path, queryParams);\n }\n\n if (response.status === 304) {\n const cached = this._responseCache.get(cacheKey);\n if (cached) {\n log.debug(`${path} → 304 (using cache)`);\n return cached;\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST GET ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const etag = response.headers.get('ETag');\n if (etag) {\n this._etags.set(cacheKey, etag);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n let data;\n if (contentType.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n this._responseCache.set(cacheKey, data);\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n\n log.debug(`${method} ${path}`);\n\n const response = await fetchWithRetry(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restSend(method, path, body);\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST ${method} ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return await response.json();\n }\n return await response.text();\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings.\n * POST /displays → JSON with display settings\n */\n async registerDisplay() {\n // Auth first to get displayId\n await this._getToken();\n\n const os = typeof navigator !== 'undefined'\n ? `${navigator.platform} ${navigator.userAgent}`\n : 'unknown';\n\n const json = await this.restSend('POST', '/displays', {\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || 400,\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel,\n xmrPubKey: this.config.xmrPubKey || '',\n });\n\n return this._parseRegisterDisplayJson(json);\n }\n\n /**\n * Parse register display JSON response.\n * Same output format as XmdsClient.\n */\n _parseRegisterDisplayJson(json) {\n const display = json.display || json;\n const attrs = display['@attributes'] || {};\n const code = attrs.code || display.code;\n const message = attrs.message || display.message || '';\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n let tags = [];\n let commands = [];\n for (const [key, value] of Object.entries(display)) {\n if (key === '@attributes' || key === 'file') continue;\n if (key === 'commands') {\n if (Array.isArray(value)) {\n commands = value.map(c => ({\n commandCode: c.code || c.commandCode || '',\n commandString: c.commandString || ''\n }));\n }\n continue;\n }\n if (key === 'tags') {\n const extractTag = (t) => typeof t === 'object' ? (t.tag || t.value || '') : String(t);\n if (Array.isArray(value)) {\n tags = value.map(extractTag).filter(Boolean);\n } else if (value && typeof value === 'object') {\n const t = extractTag(value);\n if (t) tags = [t];\n } else if (typeof value === 'string' && value) {\n tags = [value];\n }\n continue;\n }\n settings[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n const checkRf = attrs.checkRf || '';\n const checkSchedule = attrs.checkSchedule || '';\n\n const displayAttrs = {\n date: attrs.date || display.date || null,\n timezone: attrs.timezone || display.timezone || null,\n status: attrs.status || display.status || null,\n localDate: attrs.localDate || display.localDate || null,\n version_instructions: attrs.version_instructions || display.version_instructions || null,\n };\n\n const syncConfig = display.syncGroup ? {\n syncGroup: String(display.syncGroup),\n syncPublisherPort: parseInt(display.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(display.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(display.syncVideoPauseDelay || '100', 10),\n isLead: String(display.syncGroup) === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download.\n * GET /displays/{id}/media → categorized JSON (no XML parsing)\n */\n async requiredFiles() {\n const json = await this.restGet(`/displays/${this._displayId}/media`);\n return this._parseRequiredFilesV2(json);\n }\n\n /**\n * Parse v2 categorized required files into the same flat format\n * that the download pipeline expects.\n *\n * v2 server returns: { media: [...], layouts: [...], widgets: [...] }\n * We flatten back to: { files: [...], purge: [] }\n */\n _parseRequiredFilesV2(json) {\n const files = [];\n\n // Media files (images, videos)\n for (const m of json.media || []) {\n files.push({\n type: m.type || 'media',\n id: m.id != null ? String(m.id) : null,\n size: m.fileSize || 0,\n md5: m.md5 || null,\n download: 'http',\n path: m.url || null,\n saveAs: m.saveAs || null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Layout files\n for (const l of json.layouts || []) {\n files.push({\n type: 'layout',\n id: l.id != null ? String(l.id) : null,\n size: l.fileSize || 0,\n md5: l.md5 || null,\n download: 'http',\n path: l.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Widget data files (datasets — dynamic API, not static media)\n for (const w of json.widgets || []) {\n files.push({\n type: 'dataset',\n id: w.id != null ? String(w.id) : null,\n size: 0,\n md5: w.md5 || null,\n download: 'http',\n path: w.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n updateInterval: w.updateInterval || 0,\n });\n }\n\n // Dependencies (fonts, CSS, JS bundles) — pre-classified as 'static'\n for (const d of json.dependencies || []) {\n files.push({\n type: 'static',\n id: d.id != null ? String(d.id) : null,\n size: d.fileSize || 0,\n md5: d.md5 || null,\n download: 'http',\n path: d.url || null,\n saveAs: null,\n fileType: d.type || null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n return { files, purge: [] };\n }\n\n /**\n * Schedule - get layout schedule.\n * GET /displays/{id}/schedule → native JSON (no XML parsing needed!)\n *\n * The v2 server returns the same structure as parseScheduleResponse(),\n * so we return it directly.\n */\n async schedule() {\n return this.restGet(`/displays/${this._displayId}/schedule`);\n }\n\n /**\n * GetResource - get rendered widget HTML.\n * GET /widgets/{layoutId}/{regionId}/{mediaId} → HTML string\n */\n async getResource(layoutId, regionId, mediaId) {\n return this.restGet(`/widgets/${layoutId}/${regionId}/${mediaId}`);\n }\n\n /**\n * NotifyStatus - report current status.\n * PUT /displays/{id}/status → JSON acknowledgement\n */\n async notifyStatus(status) {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return this.restSend('PUT', `/displays/${this._displayId}/status`, {\n statusData: status,\n });\n }\n\n /**\n * MediaInventory - report downloaded files.\n * PUT /displays/{id}/inventory → JSON acknowledgement\n */\n async mediaInventory(inventoryXml) {\n const body = Array.isArray(inventoryXml)\n ? { inventoryItems: inventoryXml }\n : { inventory: inventoryXml };\n return this.restSend('PUT', `/displays/${this._displayId}/inventory`, body);\n }\n\n /**\n * BlackList - report broken media to CMS.\n * Not in v2 API — falls back to v1 behavior (no-op with warning).\n */\n async blackList(mediaId, type, reason) {\n log.warn(`BlackList not available in v2 API (${type}/${mediaId}: ${reason})`);\n return false;\n }\n\n /**\n * SubmitLog - submit player logs to CMS.\n * POST /displays/{id}/logs → JSON acknowledgement\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const body = Array.isArray(logXml) ? { logs: logXml } : { logXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/logs`, body);\n return result?.success === true;\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS.\n * POST /displays/{id}/screenshot → JSON acknowledgement\n */\n async submitScreenShot(base64Image) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/screenshot`, {\n screenshot: base64Image,\n });\n return result?.success === true;\n }\n\n /**\n * SubmitStats - submit proof of play statistics.\n * POST /displays/{id}/stats → JSON acknowledgement\n */\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const body = Array.isArray(statsXml) ? { stats: statsXml } : { statXml: statsXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/stats`, body);\n const success = result?.success === true;\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts.\n * POST /displays/{id}/faults → JSON acknowledgement\n */\n async reportFaults(faultJson) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/faults`, {\n fault: faultJson,\n });\n return result?.success === true;\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria.\n * GET /displays/{id}/weather → JSON weather data\n */\n async getWeather() {\n return this.restGet(`/displays/${this._displayId}/weather`);\n }\n\n // ─── Static helpers ───────────────────────────────────────────\n\n /**\n * Probe whether the CMS supports API v2.\n * GET ${PLAYER_API}/health → { version: 2, status: \"ok\" }\n *\n * @param {string} cmsUrl - CMS base URL\n * @param {Object} [retryOptions] - Retry options for fetch\n * @returns {Promise<boolean>} true if v2 is available\n */\n static async isAvailable(cmsUrl, retryOptions) {\n try {\n // In proxy mode, probe the local proxy's forward route instead of the CMS directly (avoids CORS)\n const isProxy = typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron || window.location.hostname === 'localhost');\n const base = isProxy ? '' : cmsUrl.replace(/\\/+$/, '');\n const url = `${base}${PLAYER_API}/health`;\n const timeoutMs = retryOptions?.timeoutMs || 3000;\n const fetchOptions = { method: 'GET' };\n // Apply timeout via AbortSignal (short timeout avoids delaying startup)\n if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) {\n fetchOptions.signal = AbortSignal.timeout(timeoutMs);\n }\n const response = await fetchWithRetry(url, fetchOptions, retryOptions || { maxRetries: 0 });\n if (!response.ok) return false;\n const data = await response.json();\n return data.version === 2 && data.status === 'ok';\n } catch {\n return false;\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Shared schedule XML parser used by both RestClient and XmdsClient.\n *\n * Both transports return the same XML structure for the Schedule endpoint,\n * so the parsing logic lives here to avoid duplication.\n */\n\n/**\n * Parse criteria child elements from a layout/overlay element.\n * Criteria are conditions that must be met for the item to display.\n *\n * XML format: <criteria metric=\"dayOfWeek\" condition=\"equals\" type=\"string\">Monday</criteria>\n *\n * @param {Element} parentEl - Parent XML element containing <criteria> children\n * @returns {Array<{metric: string, condition: string, type: string, value: string}>}\n */\nfunction parseCriteria(parentEl) {\n const criteria = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'criteria') continue;\n criteria.push({\n metric: child.getAttribute('metric') || '',\n condition: child.getAttribute('condition') || '',\n type: child.getAttribute('type') || 'string',\n value: child.textContent || ''\n });\n }\n return criteria;\n}\n\n/**\n * Parse Schedule XML response into a normalized schedule object.\n *\n * @param {string} xml - Raw XML string from CMS schedule endpoint\n * @returns {Object} Parsed schedule with default, layouts, campaigns, overlays, actions, commands, dataConnectors\n */\nexport function parseScheduleResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const schedule = {\n default: null,\n defaultDependants: [],\n dependants: [], // Global dependants that gate ALL layouts\n layouts: [],\n campaigns: [],\n overlays: [],\n actions: [],\n commands: [],\n dataConnectors: []\n };\n\n // Parse global dependants (root-level <dependants> — must be cached before any layout plays)\n const scheduleEl = doc.querySelector('schedule');\n if (scheduleEl) {\n const globalDeps = Array.from(scheduleEl.children).filter(\n el => el.tagName === 'dependants'\n );\n for (const depContainer of globalDeps) {\n // Skip if this is nested inside <default>, <layout>, etc.\n if (depContainer.parentElement !== scheduleEl) continue;\n for (const fileEl of depContainer.querySelectorAll('file')) {\n if (fileEl.textContent) schedule.dependants.push(fileEl.textContent);\n }\n }\n }\n\n const defaultEl = doc.querySelector('default');\n if (defaultEl) {\n schedule.default = defaultEl.getAttribute('file');\n // Parse dependants — files that must be cached before this layout plays\n const defaultDeps = defaultEl.querySelectorAll('dependants > file');\n if (defaultDeps.length > 0) {\n schedule.defaultDependants = [...defaultDeps].map(el => el.textContent);\n }\n }\n\n // Parse campaigns (groups of layouts with shared priority)\n for (const campaignEl of doc.querySelectorAll('campaign')) {\n const campaign = {\n id: campaignEl.getAttribute('id'),\n priority: parseInt(campaignEl.getAttribute('priority') || '0'),\n fromdt: campaignEl.getAttribute('fromdt'),\n todt: campaignEl.getAttribute('todt'),\n scheduleid: campaignEl.getAttribute('scheduleid'),\n maxPlaysPerHour: parseInt(campaignEl.getAttribute('maxPlaysPerHour') || '0'),\n shareOfVoice: parseInt(campaignEl.getAttribute('shareOfVoice') || '0'),\n isGeoAware: campaignEl.getAttribute('isGeoAware') === '1',\n geoLocation: campaignEl.getAttribute('geoLocation') || '',\n syncEvent: campaignEl.getAttribute('syncEvent') === '1',\n recurrenceType: campaignEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(campaignEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: campaignEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: campaignEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(campaignEl),\n layouts: []\n };\n\n // Parse layouts within this campaign\n for (const layoutEl of campaignEl.querySelectorAll('layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n campaign.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n // Layouts in campaigns inherit timing from campaign level\n fromdt: layoutEl.getAttribute('fromdt') || campaign.fromdt,\n todt: layoutEl.getAttribute('todt') || campaign.todt,\n scheduleid: campaign.scheduleid,\n priority: campaign.priority, // Priority at campaign level\n campaignId: campaign.id,\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n schedule.campaigns.push(campaign);\n }\n\n // Parse standalone layouts (not in campaigns)\n for (const layoutEl of doc.querySelectorAll('schedule > layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n schedule.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n fromdt: layoutEl.getAttribute('fromdt'),\n todt: layoutEl.getAttribute('todt'),\n scheduleid: layoutEl.getAttribute('scheduleid'),\n priority: parseInt(layoutEl.getAttribute('priority') || '0'),\n campaignId: null, // Standalone layout\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n recurrenceType: layoutEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(layoutEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: layoutEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: layoutEl.getAttribute('recurrenceRange') || null,\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n // Parse overlay layouts (appear on top of main layouts)\n const overlaysContainer = doc.querySelector('overlays');\n if (overlaysContainer) {\n for (const overlayEl of overlaysContainer.querySelectorAll('overlay')) {\n const fileId = overlayEl.getAttribute('file');\n schedule.overlays.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n duration: parseInt(overlayEl.getAttribute('duration') || '60'),\n file: fileId,\n fromdt: overlayEl.getAttribute('fromdt'),\n todt: overlayEl.getAttribute('todt'),\n priority: parseInt(overlayEl.getAttribute('priority') || '0'),\n scheduleid: overlayEl.getAttribute('scheduleid'),\n isGeoAware: overlayEl.getAttribute('isGeoAware') === '1',\n geoLocation: overlayEl.getAttribute('geoLocation') || '',\n syncEvent: overlayEl.getAttribute('syncEvent') === '1',\n maxPlaysPerHour: parseInt(overlayEl.getAttribute('maxPlaysPerHour') || '0'),\n recurrenceType: overlayEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(overlayEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: overlayEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: overlayEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(overlayEl)\n });\n }\n }\n\n // Parse action events (scheduled triggers)\n const actionsContainer = doc.querySelector('actions');\n if (actionsContainer) {\n for (const actionEl of actionsContainer.querySelectorAll('action')) {\n schedule.actions.push({\n actionType: actionEl.getAttribute('actionType') || '',\n triggerCode: actionEl.getAttribute('triggerCode') || '',\n layoutCode: actionEl.getAttribute('layoutCode') || '',\n commandCode: actionEl.getAttribute('commandCode') || '',\n duration: parseInt(actionEl.getAttribute('duration') || '0'),\n fromdt: actionEl.getAttribute('fromdt'),\n todt: actionEl.getAttribute('todt'),\n priority: parseInt(actionEl.getAttribute('priority') || '0'),\n scheduleid: actionEl.getAttribute('scheduleid'),\n isGeoAware: actionEl.getAttribute('isGeoAware') === '1',\n geoLocation: actionEl.getAttribute('geoLocation') || ''\n });\n }\n }\n\n // Parse server commands (remote control)\n for (const cmdEl of doc.querySelectorAll('schedule > command')) {\n schedule.commands.push({\n code: cmdEl.getAttribute('code') || '',\n date: cmdEl.getAttribute('date') || ''\n });\n }\n\n // Parse data connectors (real-time data sources for widgets)\n // Spec: <dataConnectors><connector dataSetId=\"\" dataParams=\"\" js=\"\"/></dataConnectors>\n const dataConnectorsContainer = doc.querySelector('dataConnectors');\n if (dataConnectorsContainer) {\n for (const dcEl of dataConnectorsContainer.querySelectorAll('connector')) {\n schedule.dataConnectors.push({\n id: dcEl.getAttribute('id') || '',\n dataConnectorId: dcEl.getAttribute('dataConnectorId') || '',\n dataSetId: dcEl.getAttribute('dataSetId') || '',\n dataKey: dcEl.getAttribute('dataKey') || '',\n dataParams: dcEl.getAttribute('dataParams') || '',\n js: dcEl.getAttribute('js') || '',\n url: dcEl.getAttribute('url') || '',\n updateInterval: parseInt(dcEl.getAttribute('updateInterval') || '300', 10)\n });\n }\n }\n\n return schedule;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * XMDS SOAP transport client for Xibo CMS.\n *\n * Uses the traditional SOAP/XML endpoint (xmds.php) for full protocol\n * compatibility with all Xibo CMS versions.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry } from '@xiboplayer/utils';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('XMDS');\n\nexport class XmdsClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 5;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n }\n\n // ─── SOAP transport helpers ─────────────────────────────────────\n\n /**\n * Build SOAP envelope for a given method and parameters\n */\n buildEnvelope(method, params) {\n const paramElements = Object.entries(params)\n .map(([key, value]) => {\n const escaped = String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n return `<${key} xsi:type=\"xsd:string\">${escaped}</${key}>`;\n })\n .join('\\n ');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soap:Envelope\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:tns=\"urn:xmds\"\n xmlns:types=\"urn:xmds/encodedTypes\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <tns:${method}>\n ${paramElements}\n </tns:${method}>\n </soap:Body>\n</soap:Envelope>`;\n }\n\n /**\n * Rewrite XMDS URL for local proxy.\n * If running inside a local wrapper (Electron, Chromium kiosk), use the\n * local proxy to avoid CORS.\n * Detection: preload.js exposes window.electronAPI.isElectron = true,\n * or fallback to checking localhost (any local wrapper port).\n */\n rewriteXmdsUrl(cmsUrl) {\n if (typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost')) {\n const encodedCmsUrl = encodeURIComponent(cmsUrl);\n return `/xmds-proxy?cms=${encodedCmsUrl}`;\n }\n\n return `${cmsUrl}/xmds.php`;\n }\n\n /**\n * Call XMDS SOAP method\n */\n async call(method, params = {}) {\n const xmdsUrl = this.rewriteXmdsUrl(this.config.cmsUrl);\n const url = `${xmdsUrl}${xmdsUrl.includes('?') ? '&' : '?'}v=${this.schemaVersion}&method=${method}`;\n const body = this.buildEnvelope(method, params);\n\n log.debug(`${method}`, params);\n log.debug(`URL: ${url}`);\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n body\n }, this.retryOptions);\n\n if (!response.ok) {\n throw new Error(`XMDS ${method} failed: ${response.status} ${response.statusText}`);\n }\n\n const xml = await response.text();\n return this.parseResponse(xml, method);\n }\n\n /**\n * Parse SOAP response\n */\n parseResponse(xml, method) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n // Check for SOAP fault (handle namespace prefix like soap:Fault)\n let fault = doc.querySelector('Fault');\n if (!fault) {\n fault = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === 'Fault' || el.tagName.endsWith(':Fault')\n );\n }\n if (fault) {\n const faultString = fault.querySelector('faultstring')?.textContent\n || Array.from(fault.querySelectorAll('*')).find(el => el.localName === 'faultstring')?.textContent\n || 'Unknown SOAP fault';\n throw new Error(`SOAP Fault: ${faultString}`);\n }\n\n // Extract response element (handle namespace prefixes like ns1:MethodResponse)\n const responseTag = `${method}Response`;\n let responseEl = doc.querySelector(responseTag);\n if (!responseEl) {\n responseEl = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === responseTag || el.tagName.endsWith(':' + responseTag)\n );\n }\n\n if (!responseEl) {\n throw new Error(`No ${responseTag} element in SOAP response`);\n }\n\n const returnEl = responseEl.firstElementChild;\n if (!returnEl) {\n return null;\n }\n\n return returnEl.textContent;\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n */\n async registerDisplay() {\n const os = `${navigator.platform} ${navigator.userAgent}`;\n\n const xml = await this.call('RegisterDisplay', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || '400',\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed'\n });\n\n return this.parseRegisterDisplayResponse(xml);\n }\n\n /**\n * Parse RegisterDisplay XML response\n */\n parseRegisterDisplayResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const display = doc.querySelector('display');\n if (!display) {\n throw new Error('Invalid RegisterDisplay response: no <display> element');\n }\n\n const code = display.getAttribute('code');\n const message = display.getAttribute('message');\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n const tags = [];\n const commands = [];\n for (const child of display.children) {\n const name = child.tagName.toLowerCase();\n if (name === 'file') continue;\n if (name === 'commands') {\n // Parse <commands><command code=\"xyz\" commandString=\"args\"/></commands>\n for (const cmdEl of child.querySelectorAll('command')) {\n commands.push({\n commandCode: cmdEl.getAttribute('code') || cmdEl.getAttribute('commandCode') || '',\n commandString: cmdEl.getAttribute('commandString') || ''\n });\n }\n continue;\n }\n if (name === 'tags') {\n // Parse <tags><tag>value</tag>...</tags> into array\n for (const tagEl of child.querySelectorAll('tag')) {\n if (tagEl.textContent) tags.push(tagEl.textContent);\n }\n continue;\n }\n settings[child.tagName] = child.textContent;\n }\n\n const checkRf = display.getAttribute('checkRf') || '';\n const checkSchedule = display.getAttribute('checkSchedule') || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: display.getAttribute('date') || null,\n timezone: display.getAttribute('timezone') || null,\n status: display.getAttribute('status') || null,\n localDate: display.getAttribute('localDate') || null,\n version_instructions: display.getAttribute('version_instructions') || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n const syncGroupVal = settings.syncGroup || null;\n const syncConfig = syncGroupVal ? {\n syncGroup: syncGroupVal,\n syncPublisherPort: parseInt(settings.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(settings.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(settings.syncVideoPauseDelay || '100', 10),\n isLead: syncGroupVal === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n */\n async requiredFiles() {\n const xml = await this.call('RequiredFiles', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return this.parseRequiredFilesResponse(xml);\n }\n\n /**\n * Parse RequiredFiles XML response\n */\n parseRequiredFilesResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const files = [];\n for (const fileEl of doc.querySelectorAll('file')) {\n files.push({\n type: fileEl.getAttribute('type'),\n id: fileEl.getAttribute('id'),\n size: parseInt(fileEl.getAttribute('size') || '0'),\n md5: fileEl.getAttribute('md5'),\n download: fileEl.getAttribute('download'),\n path: fileEl.getAttribute('path'),\n saveAs: fileEl.getAttribute('saveAs') || null,\n fileType: fileEl.getAttribute('fileType') || null,\n code: fileEl.getAttribute('code'),\n layoutid: fileEl.getAttribute('layoutid'),\n regionid: fileEl.getAttribute('regionid'),\n mediaid: fileEl.getAttribute('mediaid')\n });\n }\n\n // Parse purge block — files CMS wants the player to delete\n const purgeItems = [];\n const purgeEl = doc.querySelector('purge');\n if (purgeEl) {\n for (const itemEl of purgeEl.querySelectorAll('item')) {\n purgeItems.push({\n id: itemEl.getAttribute('id'),\n storedAs: itemEl.getAttribute('storedAs')\n });\n }\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n */\n async schedule() {\n const xml = await this.call('Schedule', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n */\n async getResource(layoutId, regionId, mediaId) {\n const xml = await this.call('GetResource', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId)\n });\n\n return xml;\n }\n\n /**\n * NotifyStatus - report current status\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n // Enrich with storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return await this.call('NotifyStatus', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n status: JSON.stringify(status)\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n */\n async mediaInventory(inventoryXml) {\n return await this.call('MediaInventory', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaInventory: inventoryXml\n });\n }\n\n /**\n * BlackList - report broken media to CMS\n * @param {string} mediaId - The media file ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const xml = await this.call('BlackList', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render'\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return xml === 'true';\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS for remote debugging\n * @param {string} logXml - XML string containing log entries\n * @returns {Promise<boolean>} - true if logs were successfully submitted\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const xml = await this.call('SubmitLog', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n logXml: logXml\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS for display verification\n * @param {string} base64Image - Base64-encoded PNG image data\n * @returns {Promise<boolean>} - true if screenshot was successfully submitted\n */\n async submitScreenShot(base64Image) {\n const xml = await this.call('SubmitScreenShot', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n screenShot: base64Image\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * @param {string} statsXml - XML-encoded stats string\n * @returns {Promise<boolean>} - true if stats were successfully submitted\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n return this.call('ReportFaults', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n fault: faultJson\n });\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * @returns {Promise<string>} Weather data XML from CMS\n */\n async getWeather() {\n return this.call('GetWeather', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const xml = await this.call('SubmitStats', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n statXml: statsXml\n });\n\n const success = xml === 'true';\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CmsClient interface definition — the unified contract for CMS communication.\n *\n * Both RestClient and XmdsClient implement this interface identically.\n * PlayerCore calls these methods without knowing which transport is underneath.\n * ProtocolDetector selects the implementation at startup.\n *\n * This file provides:\n * 1. JSDoc type definitions for the interface\n * 2. CMS_CLIENT_METHODS — canonical list of required methods\n * 3. assertCmsClient() — runtime conformance check\n *\n * @example\n * import { ProtocolDetector, RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(cmsUrl, RestClient, XmdsClient);\n * const { client } = await detector.detect(config);\n * // client implements CmsClient — PlayerCore doesn't care which one\n */\n\n/**\n * @typedef {Object} RegisterDisplayResult\n * @property {string} code - 'READY' or error code\n * @property {string} message - Human-readable status message\n * @property {Object|null} settings - Display settings (null if not READY)\n * @property {string[]} tags - Display tags\n * @property {Array<{commandCode: string, commandString: string}>} commands - Scheduled commands\n * @property {Object} displayAttrs - Server-provided attributes (date, timezone, status)\n * @property {string} checkRf - CRC checksum for RequiredFiles (skip if unchanged)\n * @property {string} checkSchedule - CRC checksum for Schedule (skip if unchanged)\n * @property {Object|null} syncConfig - Multi-display sync configuration\n */\n\n/**\n * @typedef {Object} RequiredFilesResult\n * @property {Array<{type: string, id: string, size: number, md5: string, download: string, path: string, saveAs: string|null}>} files\n * @property {Array<{id: string, storedAs: string}>} purge - Files to delete\n */\n\n/**\n * @typedef {Object} CmsClient\n * @property {() => Promise<RegisterDisplayResult>} registerDisplay\n * @property {() => Promise<RequiredFilesResult>} requiredFiles\n * @property {() => Promise<Object>} schedule\n * @property {(layoutId: string, regionId: string, mediaId: string) => Promise<string>} getResource\n * @property {(status: Object) => Promise<any>} notifyStatus\n * @property {(inventoryXml: string|Array) => Promise<any>} mediaInventory\n * @property {(mediaId: string, type: string, reason: string) => Promise<boolean>} blackList\n * @property {(logXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitLog\n * @property {(base64Image: string) => Promise<boolean>} submitScreenShot\n * @property {(statsXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitStats\n * @property {(faultJson: string|Object) => Promise<boolean>} reportFaults\n * @property {() => Promise<Object>} getWeather\n */\n\n/**\n * Canonical list of methods that every CmsClient implementation must provide.\n * Used for runtime conformance checks and test assertions.\n */\nexport const CMS_CLIENT_METHODS = [\n 'registerDisplay',\n 'requiredFiles',\n 'schedule',\n 'getResource',\n 'notifyStatus',\n 'mediaInventory',\n 'blackList',\n 'submitLog',\n 'submitScreenShot',\n 'submitStats',\n 'reportFaults',\n 'getWeather',\n];\n\n/**\n * Verify that an object implements the CmsClient interface.\n * Throws if any required method is missing or not a function.\n *\n * @param {any} client - Object to check\n * @param {string} [label] - Label for error messages (e.g. 'RestClient')\n * @throws {Error} If the client doesn't conform\n */\nexport function assertCmsClient(client, label = 'client') {\n for (const method of CMS_CLIENT_METHODS) {\n if (typeof client[method] !== 'function') {\n throw new Error(`${label} missing CmsClient method: ${method}()`);\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS Protocol Auto-Detector\n *\n * Probes the CMS to determine which communication protocol to use:\n * - REST/PlayerRestApi — optimized JSON protocol (custom CMS image)\n * - SOAP/XMDS — universal XML protocol (any vanilla Xibo CMS)\n *\n * Detection logic:\n * 1. GET {cmsUrl}${PLAYER_API}/health with a 3-second timeout\n * 2. If 200 + valid JSON → REST\n * 3. If 404/error/timeout → SOAP (fallback)\n *\n * The detected protocol is cached and can be re-probed on connection errors.\n *\n * @example\n * import { ProtocolDetector } from '@xiboplayer/xmds';\n * import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(config.cmsUrl, RestClient, XmdsClient);\n * const xmds = await detector.detect(config);\n * // xmds is either a RestClient or XmdsClient instance\n *\n * // On connection errors, re-probe:\n * const newXmds = await detector.reprobe(config);\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { assertCmsClient } from './cms-client.js';\n\nconst log = createLogger('Protocol');\n\n/** Default probe timeout in milliseconds */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport class ProtocolDetector {\n /**\n * @param {string} cmsUrl - CMS base URL\n * @param {typeof import('./rest-client.js').RestClient} RestClientClass - RestClient constructor\n * @param {typeof import('./xmds-client.js').XmdsClient} XmdsClientClass - XmdsClient constructor\n * @param {Object} [options]\n * @param {number} [options.probeTimeoutMs=3000] - Timeout for health probe\n */\n constructor(cmsUrl, RestClientClass, XmdsClientClass, options = {}) {\n this.cmsUrl = cmsUrl;\n this.RestClient = RestClientClass;\n this.XmdsClient = XmdsClientClass;\n this.probeTimeoutMs = options.probeTimeoutMs || PROBE_TIMEOUT_MS;\n\n /** @type {'rest'|'xmds'|null} Detected protocol (null = not yet probed) */\n this.protocol = null;\n\n /** @type {number} Timestamp of last successful probe */\n this.lastProbeTime = 0;\n }\n\n /**\n * Probe the CMS health endpoint to determine protocol availability.\n * @returns {Promise<boolean>} true if REST/PlayerRestApi is available\n */\n async probe() {\n const available = await this.RestClient.isAvailable(this.cmsUrl, {\n maxRetries: 0,\n timeoutMs: this.probeTimeoutMs,\n });\n this.lastProbeTime = Date.now();\n return available;\n }\n\n /**\n * Detect the best protocol and create the appropriate client.\n * On first call, probes the CMS. On subsequent calls, returns the cached\n * protocol unless reprobe() is called.\n *\n * @param {Object} config - Player configuration (passed to client constructor)\n * @param {string} [forceProtocol] - 'rest'|'xmds' to skip detection\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds'}>}\n */\n async detect(config, forceProtocol) {\n if (forceProtocol === 'rest') {\n this.protocol = 'rest';\n log.info('Using REST transport (forced)');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n if (forceProtocol === 'xmds') {\n this.protocol = 'xmds';\n log.info('Using XMDS/SOAP transport (forced)');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n // Auto-detect\n log.info('Probing CMS for REST API availability...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('REST probe failed:', e?.message || e);\n }\n\n if (isRest) {\n this.protocol = 'rest';\n log.info('REST transport detected — using PlayerRestApi');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n this.protocol = 'xmds';\n log.info('REST unavailable — using XMDS/SOAP transport');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n /**\n * Re-probe the CMS and potentially switch protocols.\n * Called on connection errors to check if the CMS was upgraded/downgraded.\n *\n * @param {Object} config - Player configuration\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds', changed: boolean}>}\n */\n async reprobe(config) {\n const previousProtocol = this.protocol;\n\n log.info('Re-probing CMS protocol...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('Re-probe failed:', e?.message || e);\n }\n\n const newProtocol = isRest ? 'rest' : 'xmds';\n const changed = newProtocol !== previousProtocol;\n\n if (changed) {\n log.info(`Protocol changed: ${previousProtocol} → ${newProtocol}`);\n this.protocol = newProtocol;\n const client = isRest ? new this.RestClient(config) : new this.XmdsClient(config);\n assertCmsClient(client, isRest ? 'RestClient' : 'XmdsClient');\n return { client, protocol: newProtocol, changed: true };\n }\n\n log.info(`Protocol unchanged: ${newProtocol}`);\n return { client: null, protocol: newProtocol, changed: false };\n }\n\n /**\n * Get the currently detected protocol.\n * @returns {'rest'|'xmds'|null}\n */\n getProtocol() {\n return this.protocol;\n }\n}\n"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","url","response","fetchWithRetry","errorBody","data","path","queryParams","token","key","value","cacheKey","headers","cachedEtag","cached","etag","contentType","method","body","os","json","display","attrs","code","message","settings","tags","commands","c","extractTag","t","checkRf","checkSchedule","displayAttrs","syncConfig","files","m","l","w","d","layoutId","regionId","mediaId","status","estimate","inventoryXml","type","reason","logXml","hardwareKeyOverride","result","base64Image","statsXml","success","error","faultJson","cmsUrl","retryOptions","timeoutMs","fetchOptions","parseCriteria","parentEl","criteria","child","parseScheduleResponse","xml","doc","schedule","scheduleEl","globalDeps","el","depContainer","fileEl","defaultEl","defaultDeps","campaignEl","campaign","layoutEl","fileId","depEls","overlaysContainer","overlayEl","actionsContainer","actionEl","cmdEl","dataConnectorsContainer","dcEl","XmdsClient","params","paramElements","escaped","xmdsUrl","fault","faultString","_b","responseTag","responseEl","returnEl","name","tagEl","syncGroupVal","purgeItems","purgeEl","itemEl","CMS_CLIENT_METHODS","assertCmsClient","client","label","PROBE_TIMEOUT_MS","ProtocolDetector","RestClientClass","XmdsClientClass","options","available","forceProtocol","isRest","e","previousProtocol","newProtocol"],"mappings":"uFAkBA,MAAMA,EAAMC,EAAa,MAAM,EAExB,MAAMC,CAAW,CACtB,YAAYC,EAAQ,CAClB,KAAK,OAASA,EACd,KAAK,cAAgB,EACrB,KAAK,aAAeA,EAAO,cAAgB,CAAE,WAAY,EAAG,YAAa,GAAI,EAG7E,KAAK,OAAS,KACd,KAAK,gBAAkB,EACvB,KAAK,WAAa,KAGlB,KAAK,OAAS,IAAI,IAClB,KAAK,eAAiB,IAAI,IAE1BH,EAAI,KAAK,sBAAsB,CACjC,CAUA,gBAAiB,CACf,OAAI,KAAK,eACA,GAAG,OAAO,SAAS,MAAM,GAAGI,CAAU,IAElC,KAAK,OAAO,YAAc,GAAG,KAAK,OAAO,MAAM,GAAGA,CAA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A,EAAG,UAAWA,CAAC,CAC9C,CAEA,MAAME,EAAcH,EAAS,OAAS,OAGtC,GAFgBG,IAAgBD,EAEnB,CACX1H,EAAI,KAAK,qBAAqB0H,CAAgB,MAAMC,CAAW,EAAE,EACjE,KAAK,SAAWA,EAChB,MAAMZ,EAASS,EAAS,IAAI,KAAK,WAAWrH,CAAM,EAAI,IAAI,KAAK,WAAWA,CAAM,EAChF,OAAA2G,EAAgBC,EAAQS,EAAS,aAAe,YAAY,EACrD,CAAE,OAAAT,EAAQ,SAAUY,EAAa,QAAS,EAAI,CACvD,CAEA,OAAA3H,EAAI,KAAK,uBAAuB2H,CAAW,EAAE,EACtC,CAAE,OAAQ,KAAM,SAAUA,EAAa,QAAS,EAAK,CAC9D,CAMA,aAAc,CACZ,OAAO,KAAK,QACd,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createLogger as $,PLAYER_API as C}from"./index-Dllq0Rxc.js";const P=$("Cache"),B=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class R{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${B}/cache/${e}/${s||t}`}addDependant(e,t){const s=String(e);this.dependants.has(s)||this.dependants.set(s,new Set),this.dependants.get(s).add(String(t))}removeLayoutDependants(e){const t=String(e),s=[];for(const[n,i]of this.dependants)i.delete(t),i.size===0&&(this.dependants.delete(n),s.push(n));return s.length>0&&P.info(`${s.length} media files orphaned after layout ${e} removed:`,s),s}isMediaReferenced(e){const t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){this.dependants.clear()}}const N=new R,T=$("StoreClient");class O{async has(e,t){try{return(await fetch(`/store/${e}/${t}`,{method:"HEAD"})).ok}catch{return!1}}async get(e,t){var s;try{const n=await fetch(`/store/${e}/${t}`);if(!n.ok){if((s=n.body)==null||s.cancel(),n.status===404)return null;throw new Error(`Failed to get file: ${n.status}`)}return await n.blob()}catch(n){return T.error("get error:",n.message),null}}async put(e,t,s,n="application/octet-stream"){var i;try{const r=await fetch(`/store/${e}/${t}`,{method:"PUT",headers:{"Content-Type":n},body:s});return(i=r.body)==null||i.cancel(),r.ok}catch(r){return T.error("put error:",r.message),!1}}async remove(e){try{const s=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:s.deleted||0,total:s.total||e.length}}catch(t){return T.error("remove error:",t.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return T.error("list error:",e.message),[]}}}const b={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function I(d){return b[d]||b.media}const l=$("Download"),A=6,F=50*1024*1024,M=3,Q=100*1024*1024,z=2,D=6e5,L=15e3;function U(d){var n,i;const t=(i=(n=(d.path||d.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:i.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},_=Symbol("BARRIER");function k(d){try{const e=d.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function S(d,e=30){const t=k(d);return t===1/0?!1:Date.now()/1e3>=t-e}class x{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal,this._typeConfig=I(e.type)}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){var s;this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e["X-Store-Chunk-Index"]=String(this.chunkIndex),this._parentFile&&(e["X-Store-Num-Chunks"]=String(this._parentFile.totalChunks),e["X-Store-Chunk-Size"]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e["X-Store-MD5"]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e["X-Cache-TTL"]=String(this.fileInfo.updateInterval));const t=this._typeConfig.maxRetries;for(let n=1;n<=t;n++){const i=new AbortController,r=setTimeout(()=>i.abort(),D);try{const a=this.getUrl(),h={signal:i.signal};Object.keys(e).length>0&&(h.headers=e);const o=await fetch(a,h);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(a){const h=i.signal.aborted?`Timeout after ${D/1e3}s`:a.message;if(n<t){const o=((s=this._typeConfig.retryDelays)==null?void 0:s[n-1])??this._typeConfig.retryDelayMs*n,u=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${u} attempt ${n}/${t} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(p=>setTimeout(p,o))}else throw this.state="failed",i.signal.aborted?new Error(h):a}finally{clearTimeout(r)}}}}class E{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,n)=>{this._resolve=s,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:n}=this.fileInfo;l.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=U(this.fileInfo);const i=I(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!i){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),L);try{const u=await fetch(a,{method:"HEAD",signal:h.signal});u.ok&&(this.totalBytes=parseInt(u.headers.get("Content-Length")||"0"),this._contentType=u.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const r=this.options.chunkSize||F;if(this.totalBytes>Q){const a=[];for(let c=0;c<this.totalBytes;c+=r)a.push({start:c,end:Math.min(c+r-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(c=>!this.skipChunks.has(c.index)),o=a.length-h.length;for(const c of a)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(h.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&l.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const u=o>0;if(u){const c=h.sort((g,m)=>g.index-m.index);for(const g of c){const m=new x(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});m._parentFile=this,m._priority=f.normal,this.tasks.push(m)}}else for(const c of h){const g=new x(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===a.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(c=>c._priority>=f.high).length;l.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(u?" (resume)":""))}else{this.totalChunks=1;const a=new x(this.fileInfo,{});a._parentFile=this,this.tasks.push(a)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){l.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let r=0;r<this.totalChunks;r++){const a=this._chunkBlobs.get(r);a&&n.push(a)}const i=new Blob(n,{type:this._contentType});l.info("[FileDownload] Complete:",`${t}/${s}`,`(${i.size} bytes, reassembled)`),this._resolve(i)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(i=>i!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}l.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class K{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=q.stableKey(e);if(this.queue.active.has(t)){const n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=k(n.fileInfo.path);k(e.path)>i&&(n.fileInfo.path=e.path)}return n}const s=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const n=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const i=this._filesToPrepare[s++];t++,i.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var r;const e=[],t=[],s=[],n=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)t.push(a);else{const h=((r=a._parentFile)==null?void 0:r.totalChunks)||0;h>1&&a.chunkIndex===h-1?s.push(a):n.push(a)}e.sort((a,h)=>{var o,u;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((u=h._parentFile)==null?void 0:u.totalBytes)||0)}),n.sort((a,h)=>a.chunkIndex-h.chunkIndex);const i=[...e,...t,...s];return n.length>0&&i.push(_,...n),i}}class q{constructor(e={}){this.concurrency=e.concurrency||A,this.chunkSize=e.chunkSize||F,this.maxChunksPerFile=e.chunksPerFile||M,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=q.stableKey(e);if(this.active.has(t)){const n=this.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=k(n.fileInfo.path);k(e.path)>i&&(l.info("[DownloadQueue] Refreshing URL for",t),n.fileInfo.path=e.path)}return n}const s=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),l.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const n of e)n===_?(this.queue.push(_),s++):(this.queue.push(n),t++);l.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,n=this.active.get(s);if(!n)return l.info("[DownloadQueue] Not found:",s),!1;let i=0;for(const r of this.queue)r._parentFile===n&&r._priority<f.high&&(r._priority=f.high,i++);return this._sortQueue(),l.info("[DownloadQueue] Prioritized:",s,`(${i} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=f.high){var i,r,a,h;const s=new Set(e.map(String));let n=0;for(const o of this.queue){const u=((i=o._parentFile)==null?void 0:i.fileInfo.saveAs)||String((r=o._parentFile)==null?void 0:r.fileInfo.id);s.has(u)&&o._priority<t&&(o._priority=t,n++)}for(const o of this._activeTasks){const u=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);s.has(u)&&o._priority<t&&(o._priority=t)}this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",n,"tasks boosted to",t)}urgentChunk(e,t,s){const n=`${e}/${t}`,i=this.active.get(n);if(!i)return l.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",s),!1;if(this._activeTasks.some(o=>o._parentFile===i&&o.chunkIndex===s&&o.state==="downloading")){const o=this._activeTasks.find(u=>u._parentFile===i&&u.chunkIndex===s);return o&&o._priority<f.urgent?(o._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",s),!1)}const a=this.queue.findIndex(o=>o!==_&&o._parentFile===i&&o.chunkIndex===s);if(a===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",s),!1;const h=this.queue.splice(a,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(i=>i!==_&&i._priority>=f.urgent)||((n=this._activeTasks)==null?void 0:n.some(i=>i._priority>=f.urgent&&i.state==="downloading")),t=e?z:this.concurrency,s=e?f.urgent:0;for(;this.running<t&&this.queue.length>0;){const i=this.queue[0];if(i===_){if(this.running>0)break;this.queue.shift();continue}if(i._priority<s||!this._canStartTask(i)){let r=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==_;a++){const h=this.queue[a];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(i)}this.queue.length===0&&this.running===0&&l.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),l.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(a=>a!==e);const{maxReenqueues:i,reenqueueDelayMs:r}=e._typeConfig;if(i>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>i){l.error(`[DownloadQueue] ${t} exceeded ${i} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}l.warn(`[DownloadQueue] ${t} failed all retries (attempt ${e._reenqueueCount}/${i}), scheduling re-enqueue in ${r/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),l.info(`[DownloadQueue] ${t} re-enqueued for retry`),this.processQueue()},r);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===_||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())s.state==="complete"||s.state==="failed"||(e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(const e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}}class X{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}enqueueForLayout(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,s){return this.queue.urgentChunk(e,t,s)}clear(){this.queue.clear()}}const y=$("CacheAnalyzer");function w(d){if(d===0)return"0 B";if(!Number.isFinite(d))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(d)/Math.log(1024));return`${(d/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class Y{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.list(),s=await this._getStorageEstimate(),n=new Set(e.map(o=>String(o.id))),i=[],r=[];for(const o of t)if(n.has(String(o.id)))i.push(o);else if(o.type==="widget"){const u=String(o.id).split("/")[0];n.has(u)?i.push(o):r.push(o)}else o.type==="static"?i.push(o):r.push(o);r.sort((o,u)=>(o.cachedAt||0)-(u.cachedAt||0));const a=r.reduce((o,u)=>o+(u.size||0),0),h={timestamp:Date.now(),storage:{usage:s.usage,quota:s.quota,percent:s.quota>0?Math.round(s.usage/s.quota*100):0},files:{required:i.length,orphaned:r.length,total:t.length},orphaned:r.map(o=>({id:o.id,type:o.type,size:o.size||0,cachedAt:o.cachedAt||0})),orphanedSize:a,evicted:[],threshold:this.threshold};if(y.info(`Storage: ${w(s.usage)} / ${w(s.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${i.length} required, ${r.length} orphaned (${w(a)} reclaimable)`),r.length>0)for(const o of r){const u=Date.now()-(o.cachedAt||0),p=Math.floor(u/864e5),c=Math.floor(u%864e5/36e5),g=p>0?`${p}d ago`:`${c}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${w(o.size||0)}, cached ${g})`)}if(h.storage.percent>this.threshold&&r.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(r,o)}else y.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:t,quota:s}=await navigator.storage.estimate();return{usage:t||0,quota:s||1/0}}}catch(t){y.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let n=0;for(const i of e){if(n>=t)break;s.push(i),n+=i.size||0}if(s.length===0)return[];try{const i=s.map(r=>({type:r.type,id:r.id}));await this.cache.remove(i);for(const r of s)y.info(` Evicted: ${r.type}/${r.id} (${w(r.size||0)})`);y.info(`Evicted ${s.length} files, freed ${w(n)}`)}catch(i){return y.warn("Eviction failed:",i.message),[]}return s.map(i=>({id:i.id,type:i.type,size:i.size||0,cachedAt:i.cachedAt||0}))}}const v=$("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function G(d,e,t,s){var u;const n=`${C}/widgets/${d}/${e}/${t}`,i=`<base href="${C}/media/file/">`;let r=s;s.includes("<base ")||(s.includes("<head>")?r=s.replace("<head>","<head>"+i):s.includes("<HEAD>")?r=s.replace("<HEAD>","<HEAD>"+i):r=i+s);const a="<style>img,video{object-position:center center}</style>";r.includes("object-position:center center")||(r.includes("</head>")?r=r.replace("</head>",a+"</head>"):r.includes("</HEAD>")&&(r=r.replace("</HEAD>",a+"</HEAD>"))),r=r.replace(/\[\[ViewPortWidth]]/g,"device-width"),r=r.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,p=>"/stream-proxy?url="+encodeURIComponent(p));const h=new RegExp(`https?://[^"'\\s)]+?(${C.replace(/\//g,"\\/")}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,"g");if(r=r.replace(h,(p,c)=>c),!r.includes("xiboICTargetId")){const p=`<script>var xiboICTargetId = '${t}';<\/script>`;r.includes(i)?r=r.replace(i,i+p):r.includes("<head>")?r=r.replace("<head>","<head>"+p):r=p+r}return r=r.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),v.info("Injected base tag in widget HTML"),(u=(await fetch(`/store${C}/widgets/${d}/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:r})).body)==null||u.cancel(),v.info(`Stored widget HTML at ${n} (${r.length} bytes)`),n}export{_ as B,Y as C,X as D,b as F,K as L,O as S,R as a,E as b,G as c,N as d,I as g,S as i};
|
|
2
|
-
//# sourceMappingURL=widget-html-CRNarPfj.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"widget-html-CRNarPfj.js","sources":["../../../cache/src/cache.js","../../../cache/src/store-client.js","../../../cache/src/file-types.js","../../../cache/src/download-manager.js","../../../cache/src/cache-analyzer.js","../../../cache/src/widget-html.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the storage unification, all downloads and file retrieval go through\n * the proxy's ContentStore (via StoreClient/DownloadClient). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Get cache key for a file\n * For media, uses the actual filename; for layouts, uses the ID\n */\n getCacheKey(type, id, filename = null) {\n const key = filename || id;\n return `${BASE}/cache/${type}/${key}`;\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files via proxy\n */\n async clearAll() {\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * StoreClient — Pure REST client for ContentStore\n *\n * Communicates with the proxy's /store/* endpoints via fetch().\n * No Service Worker dependency — works immediately after construction.\n *\n * Usage:\n * const store = new StoreClient();\n * const exists = await store.has('media', '123');\n * const blob = await store.get('media', '123');\n * await store.put('widget', 'layout/1/region/2/media/3', htmlBlob, 'text/html');\n * await store.remove([{ type: 'media', id: '456' }]);\n * const files = await store.list();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('StoreClient');\n\nexport class StoreClient {\n /**\n * Check if a file exists in the store.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<boolean>}\n */\n async has(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`, { method: 'HEAD' });\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Get a file from the store as a Blob.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<Blob|null>}\n */\n async get(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`);\n if (!response.ok) {\n response.body?.cancel();\n if (response.status === 404) return null;\n throw new Error(`Failed to get file: ${response.status}`);\n }\n return await response.blob();\n } catch (error) {\n log.error('get error:', error.message);\n return null;\n }\n }\n\n /**\n * Store a file in the ContentStore.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @param {Blob|ArrayBuffer|string} body - Content to store\n * @param {string} [contentType='application/octet-stream'] - MIME type\n * @returns {Promise<boolean>} true if stored successfully\n */\n async put(type, id, body, contentType = 'application/octet-stream') {\n try {\n const response = await fetch(`/store/${type}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body,\n });\n response.body?.cancel();\n return response.ok;\n } catch (error) {\n log.error('put error:', error.message);\n return false;\n }\n }\n\n /**\n * Delete files from the store.\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async remove(files) {\n try {\n const response = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n const result = await response.json();\n return { deleted: result.deleted || 0, total: result.total || files.length };\n } catch (error) {\n log.error('remove error:', error.message);\n return { deleted: 0, total: files.length };\n }\n }\n\n /**\n * List all files in the store.\n * @returns {Promise<Array<{id: string, type: string, size: number}>>}\n */\n async list() {\n try {\n const response = await fetch('/store/list');\n const data = await response.json();\n return data.files || [];\n } catch (error) {\n log.error('list error:', error.message);\n return [];\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * FILE_TYPES — centralized download behavior per file type.\n *\n * Each type declares retry strategy, HEAD skip, and cache TTL.\n * Used by DownloadTask/FileDownload instead of ad-hoc isGetData checks.\n */\n\nexport const FILE_TYPES = {\n media: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n layout: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n dataset: { maxRetries: 4, retryDelayMs: 0,\n retryDelays: [15_000, 30_000, 60_000, 120_000],\n maxReenqueues: 5, reenqueueDelayMs: 60_000,\n skipHead: true, cacheTtl: 300 },\n static: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n};\n\nexport function getFileTypeConfig(type) {\n return FILE_TYPES[type] || FILE_TYPES.media;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { getFileTypeConfig } from './file-types.js';\n\nconst log = createLogger('Download');\nconst DEFAULT_CONCURRENCY = 6; // Max concurrent HTTP connections (matches Chromium per-host limit)\nconst DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB chunks\nconst DEFAULT_MAX_CHUNKS_PER_FILE = 3; // Max parallel chunk downloads per file\nconst CHUNK_THRESHOLD = 100 * 1024 * 1024; // Files > 100MB get chunked\nconst URGENT_CONCURRENCY = 2; // Slots when urgent chunk is active (bandwidth focus)\nconst FETCH_TIMEOUT_MS = 600_000; // 10 minutes — 100MB chunk at ~2 Mbps\nconst HEAD_TIMEOUT_MS = 15_000; // 15 seconds for HEAD requests\n\n/**\n * Infer Content-Type from file path extension.\n * Used when we skip HEAD (size already known from RequiredFiles).\n */\nfunction inferContentType(fileInfo) {\n const path = fileInfo.path || fileInfo.code || '';\n const ext = path.split('.').pop()?.split('?')[0]?.toLowerCase();\n const types = {\n mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',\n gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',\n css: 'text/css', js: 'application/javascript',\n ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2',\n xml: 'application/xml', xlf: 'application/xml',\n };\n return types[ext] || 'application/octet-stream';\n}\n\n// Priority levels — higher number = starts first\nexport const PRIORITY = { normal: 0, layout: 1, high: 2, urgent: 3 };\n\n/**\n * BARRIER sentinel — hard gate in the download queue.\n *\n * When processQueue() encounters a BARRIER:\n * - If tasks are still in-flight above it → STOP (slots stay empty)\n * - If running === 0 → remove barrier, continue with tasks below\n *\n * Used by LayoutQueueBuilder to separate critical chunks (chunk-0, chunk-last)\n * from remaining bulk chunks. Ensures video playback can start before all\n * chunks finish downloading.\n */\nexport const BARRIER = Symbol('BARRIER');\n\n/**\n * Parse the X-Amz-Expires absolute timestamp from a signed URL.\n * Returns the expiry as a Unix timestamp (seconds), or Infinity if not found.\n */\nfunction getUrlExpiry(url) {\n try {\n const match = url.match(/X-Amz-Expires=(\\d+)/);\n return match ? parseInt(match[1], 10) : Infinity;\n } catch {\n return Infinity;\n }\n}\n\n/**\n * Check if a signed URL has expired (or will expire within a grace period).\n * @param {string} url - Signed URL with X-Amz-Expires parameter\n * @param {number} graceSeconds - Seconds before actual expiry to consider it expired (default: 30)\n * @returns {boolean}\n */\nexport function isUrlExpired(url, graceSeconds = 30) {\n const expiry = getUrlExpiry(url);\n if (expiry === Infinity) return false;\n return (Date.now() / 1000) >= (expiry - graceSeconds);\n}\n\n\n/**\n * DownloadTask - Single HTTP fetch unit\n *\n * Handles exactly one HTTP request: either a full small file GET or a single Range GET\n * for one chunk of a larger file. Includes retry logic with exponential backoff.\n */\nexport class DownloadTask {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.chunkIndex = options.chunkIndex ?? null;\n this.rangeStart = options.rangeStart ?? null;\n this.rangeEnd = options.rangeEnd ?? null;\n this.state = 'pending';\n this.blob = null;\n this._parentFile = null;\n this._priority = PRIORITY.normal;\n this._typeConfig = getFileTypeConfig(fileInfo.type);\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n async start() {\n this.state = 'downloading';\n const headers = {};\n if (this.rangeStart != null) {\n headers['Range'] = `bytes=${this.rangeStart}-${this.rangeEnd}`;\n }\n // Pass chunk metadata and MD5 via custom headers for cache-through proxy\n if (this.chunkIndex != null) {\n headers['X-Store-Chunk-Index'] = String(this.chunkIndex);\n if (this._parentFile) {\n headers['X-Store-Num-Chunks'] = String(this._parentFile.totalChunks);\n headers['X-Store-Chunk-Size'] = String(this._parentFile.options.chunkSize || 104857600);\n }\n }\n if (this.fileInfo.md5) {\n headers['X-Store-MD5'] = this.fileInfo.md5;\n }\n if (this.fileInfo.updateInterval) {\n headers['X-Cache-TTL'] = String(this.fileInfo.updateInterval);\n }\n\n const maxRetries = this._typeConfig.maxRetries;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);\n try {\n const url = this.getUrl();\n const fetchOpts = { signal: ac.signal };\n if (Object.keys(headers).length > 0) fetchOpts.headers = headers;\n const response = await fetch(url, fetchOpts);\n\n if (!response.ok && response.status !== 206) {\n throw new Error(`Fetch failed: ${response.status}`);\n }\n\n this.blob = await response.blob();\n this.state = 'complete';\n return this.blob;\n\n } catch (error) {\n const msg = ac.signal.aborted ? `Timeout after ${FETCH_TIMEOUT_MS / 1000}s` : error.message;\n if (attempt < maxRetries) {\n const delay = this._typeConfig.retryDelays?.[attempt - 1]\n ?? this._typeConfig.retryDelayMs * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${maxRetries} failed: ${msg}. Retrying in ${delay / 1000}s...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n this.state = 'failed';\n throw ac.signal.aborted ? new Error(msg) : error;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n }\n}\n\n/**\n * FileDownload - Orchestrates downloading a single file\n *\n * Does the HEAD request to determine file size, then:\n * - Small file (≤ 100MB): creates 1 DownloadTask for the full file\n * - Large file (> 100MB): creates N DownloadTasks, one per chunk\n *\n * All tasks are enqueued into the flat DownloadQueue where they compete\n * equally for HTTP connection slots with tasks from other files.\n *\n * Provides wait() that resolves when ALL tasks for this file complete.\n * Supports progressive caching via onChunkDownloaded callback.\n */\nexport class FileDownload {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.options = options;\n this.state = 'pending';\n this.tasks = [];\n this.completedChunks = 0;\n this.totalChunks = 0;\n this.totalBytes = 0;\n this.downloadedBytes = 0;\n this.onChunkDownloaded = null;\n this.skipChunks = fileInfo.skipChunks || new Set();\n this._contentType = 'application/octet-stream';\n this._chunkBlobs = new Map();\n this._runningCount = 0; // Currently running tasks for this file\n this._resolve = null;\n this._reject = null;\n this._promise = new Promise((res, rej) => {\n this._resolve = res;\n this._reject = rej;\n });\n this._promise.catch(() => {});\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n wait() {\n return this._promise;\n }\n\n /**\n * Determine file size and create DownloadTasks.\n * Uses RequiredFiles size when available (instant, no network).\n * Falls back to HEAD request only when size is unknown.\n */\n async prepare(queue) {\n try {\n this.state = 'preparing';\n const { id, type, size } = this.fileInfo;\n log.info('[FileDownload] Starting:', `${type}/${id}`);\n\n // Use declared size from RequiredFiles — no HEAD needed for queue building\n this.totalBytes = (size && size > 0) ? parseInt(size) : 0;\n this._contentType = inferContentType(this.fileInfo);\n\n // Skip HEAD for types that declare skipHead (e.g. datasets — dynamic API endpoints).\n // These generate responses server-side; HEAD triggers the full handler for nothing\n // and may fail if the CMS cache isn't warm yet. They're always small, never chunked.\n const skipHead = getFileTypeConfig(this.fileInfo.type).skipHead;\n\n if (this.totalBytes === 0 && !skipHead) {\n // No size declared — HEAD fallback (rare: only for files without CMS size)\n const url = this.getUrl();\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), HEAD_TIMEOUT_MS);\n try {\n const head = await fetch(url, { method: 'HEAD', signal: ac.signal });\n if (head.ok) {\n this.totalBytes = parseInt(head.headers.get('Content-Length') || '0');\n this._contentType = head.headers.get('Content-Type') || this._contentType;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n log.info('[FileDownload] File size:', (this.totalBytes / 1024 / 1024).toFixed(1), 'MB');\n\n const chunkSize = this.options.chunkSize || DEFAULT_CHUNK_SIZE;\n\n if (this.totalBytes > CHUNK_THRESHOLD) {\n const ranges = [];\n for (let start = 0; start < this.totalBytes; start += chunkSize) {\n ranges.push({\n start,\n end: Math.min(start + chunkSize - 1, this.totalBytes - 1),\n index: ranges.length\n });\n }\n this.totalChunks = ranges.length;\n\n const needed = ranges.filter(r => !this.skipChunks.has(r.index));\n const skippedCount = ranges.length - needed.length;\n\n for (const r of ranges) {\n if (this.skipChunks.has(r.index)) {\n this.downloadedBytes += (r.end - r.start + 1);\n }\n }\n\n if (needed.length === 0) {\n log.info('[FileDownload] All chunks already cached, nothing to download');\n this.state = 'complete';\n this._resolve(new Blob([], { type: this._contentType }));\n return;\n }\n\n if (skippedCount > 0) {\n log.info(`[FileDownload] Resuming: ${skippedCount} chunks cached, ${needed.length} to download`);\n }\n\n const isResume = skippedCount > 0;\n\n if (isResume) {\n const sorted = needed.sort((a, b) => a.index - b.index);\n for (const r of sorted) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = PRIORITY.normal;\n this.tasks.push(task);\n }\n } else {\n for (const r of needed) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = (r.index === 0 || r.index === ranges.length - 1) ? PRIORITY.high : PRIORITY.normal;\n this.tasks.push(task);\n }\n }\n\n const highCount = this.tasks.filter(t => t._priority >= PRIORITY.high).length;\n log.info(`[FileDownload] ${type}/${id}: ${this.tasks.length} chunks` +\n (highCount > 0 ? ` (${highCount} priority)` : '') +\n (isResume ? ' (resume)' : ''));\n\n } else {\n this.totalChunks = 1;\n const task = new DownloadTask(this.fileInfo, {});\n task._parentFile = this;\n this.tasks.push(task);\n }\n\n queue.enqueueChunkTasks(this.tasks);\n this.state = 'downloading';\n\n } catch (error) {\n log.error('[FileDownload] Prepare failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n }\n\n async onTaskComplete(task) {\n this.completedChunks++;\n this.downloadedBytes += task.blob.size;\n\n if (task.chunkIndex != null) {\n this._chunkBlobs.set(task.chunkIndex, task.blob);\n }\n\n if (this.options.onProgress) {\n this.options.onProgress(this.downloadedBytes, this.totalBytes);\n }\n\n // Fire progressive chunk callback\n if (this.onChunkDownloaded && task.chunkIndex != null) {\n try {\n await this.onChunkDownloaded(task.chunkIndex, task.blob, this.totalChunks);\n } catch (e) {\n log.warn('[FileDownload] onChunkDownloaded callback error:', e);\n }\n }\n\n if (this.completedChunks === this.tasks.length && this.state !== 'complete') {\n this.state = 'complete';\n const { type, id } = this.fileInfo;\n\n if (task.chunkIndex == null) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${task.blob.size} bytes)`);\n this._resolve(task.blob);\n } else if (this.onChunkDownloaded) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(progressive, ${this.totalChunks} chunks)`);\n this._resolve(new Blob([], { type: this._contentType }));\n } else {\n const ordered = [];\n for (let i = 0; i < this.totalChunks; i++) {\n const blob = this._chunkBlobs.get(i);\n if (blob) ordered.push(blob);\n }\n const assembled = new Blob(ordered, { type: this._contentType });\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${assembled.size} bytes, reassembled)`);\n this._resolve(assembled);\n }\n\n this._chunkBlobs.clear();\n }\n }\n\n onTaskFailed(task, error) {\n if (this.state === 'complete' || this.state === 'failed') return;\n\n // URL expiration is transient — drop this task, don't fail the file.\n // Already-downloaded chunks are safe in cache. Next collection cycle\n // provides fresh URLs and the resume logic (skipChunks) fills the gaps.\n if (error.message?.includes('URL expired')) {\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.warn(`[FileDownload] URL expired, dropping${chunkLabel}:`, `${this.fileInfo.type}/${this.fileInfo.id}`);\n this.tasks = this.tasks.filter(t => t !== task);\n // If all remaining tasks completed, resolve as partial\n if (this.tasks.length === 0 || this.completedChunks >= this.tasks.length) {\n this.state = 'complete';\n this._urlExpired = true;\n this._resolve(new Blob([], { type: this._contentType }));\n }\n return;\n }\n\n log.error('[FileDownload] Failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n}\n\n/**\n * LayoutTaskBuilder — Smart builder that produces a sorted, barrier-embedded\n * task list for a single layout.\n *\n * Usage:\n * const builder = new LayoutTaskBuilder(queue);\n * builder.addFile(fileInfo);\n * const orderedTasks = await builder.build();\n * queue.enqueueOrderedTasks(orderedTasks);\n *\n * The builder runs HEAD requests (throttled), collects the resulting\n * DownloadTasks, sorts them optimally, and embeds BARRIERs between\n * critical chunks (chunk-0, chunk-last) and bulk chunks.\n *\n * Duck-typing: implements enqueueChunkTasks() so FileDownload.prepare()\n * works unchanged — it just collects tasks instead of processing them.\n */\nexport class LayoutTaskBuilder {\n constructor(queue) {\n this.queue = queue; // Main DownloadQueue (for dedup via active map)\n this._filesToPrepare = []; // FileDownloads needing HEAD requests\n this._tasks = []; // Collected DownloadTasks (from prepare callbacks)\n this._maxPreparing = 2; // HEAD request throttle\n }\n\n /**\n * Register a file. Uses queue.active for dedup/URL refresh.\n * Does NOT trigger prepare — that happens in build().\n */\n addFile(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.queue.active.has(key)) {\n const existing = this.queue.active.get(key);\n // URL refresh (same logic as queue.enqueue)\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.queue.chunkSize,\n calculateMD5: this.queue.calculateMD5,\n onProgress: this.queue.onProgress\n });\n\n this.queue.active.set(key, file);\n this._filesToPrepare.push(file);\n return file;\n }\n\n /**\n * Duck-type interface for FileDownload.prepare().\n * Collects tasks instead of processing them.\n */\n enqueueChunkTasks(tasks) {\n this._tasks.push(...tasks);\n }\n\n /**\n * Run all HEAD requests (throttled) and return sorted tasks with barriers.\n */\n async build() {\n await this._prepareAll();\n return this._sortWithBarriers();\n }\n\n async _prepareAll() {\n await new Promise((resolve) => {\n let running = 0;\n let idx = 0;\n const next = () => {\n while (running < this._maxPreparing && idx < this._filesToPrepare.length) {\n const file = this._filesToPrepare[idx++];\n running++;\n file.prepare(this).finally(() => {\n running--;\n if (idx >= this._filesToPrepare.length && running === 0) {\n resolve();\n } else {\n next();\n }\n });\n }\n };\n if (this._filesToPrepare.length === 0) resolve();\n else next();\n });\n }\n\n _sortWithBarriers() {\n const nonChunked = [];\n const chunk0s = [];\n const chunkLasts = [];\n const remaining = [];\n\n for (const t of this._tasks) {\n if (t.chunkIndex == null) {\n nonChunked.push(t);\n } else if (t.chunkIndex === 0) {\n chunk0s.push(t);\n } else {\n const total = t._parentFile?.totalChunks || 0;\n if (total > 1 && t.chunkIndex === total - 1) {\n chunkLasts.push(t);\n } else {\n remaining.push(t);\n }\n }\n }\n\n nonChunked.sort((a, b) => (a._parentFile?.totalBytes || 0) - (b._parentFile?.totalBytes || 0));\n remaining.sort((a, b) => a.chunkIndex - b.chunkIndex);\n\n // Build: small files + critical chunks → BARRIER → bulk chunks\n const result = [...nonChunked, ...chunk0s, ...chunkLasts];\n if (remaining.length > 0) {\n result.push(BARRIER, ...remaining);\n }\n return result;\n }\n}\n\n/**\n * DownloadQueue - Flat queue with per-file and global concurrency limits\n *\n * Global concurrency limit (e.g., 6) controls total HTTP connections.\n * Per-file chunk limit (e.g., 2) prevents one large file from hogging all\n * connections, ensuring bandwidth per chunk is high and chunk 0 arrives fast.\n * HEAD requests are throttled to avoid flooding browser connection pool.\n */\nexport class DownloadQueue {\n constructor(options = {}) {\n this.concurrency = options.concurrency || DEFAULT_CONCURRENCY;\n this.chunkSize = options.chunkSize || DEFAULT_CHUNK_SIZE;\n this.maxChunksPerFile = options.chunksPerFile || DEFAULT_MAX_CHUNKS_PER_FILE;\n this.calculateMD5 = options.calculateMD5;\n this.onProgress = options.onProgress;\n\n this.queue = []; // DownloadTask[] — flat queue of chunk/file tasks\n this.active = new Map(); // stableKey → FileDownload\n this._activeTasks = []; // DownloadTask[] — currently in-flight tasks\n this.running = 0;\n\n // HEAD request throttling: prevents prepare() from flooding browser connections\n this._prepareQueue = [];\n this._preparingCount = 0;\n this._maxPreparing = 2; // Max concurrent HEAD requests\n\n // When paused, processQueue() is a no-op (used during barrier setup)\n this.paused = false;\n\n // Track getData re-enqueue timers so clear() can cancel them\n this._reenqueueTimers = new Set();\n }\n\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n prioritize(fileType, fileId) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] Not found:', key);\n return false;\n }\n\n let boosted = 0;\n for (const t of this.queue) {\n if (t._parentFile === file && t._priority < PRIORITY.high) {\n t._priority = PRIORITY.high;\n boosted++;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Prioritized:', key, `(${boosted} tasks boosted)`);\n return true;\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Layout files prioritized:', idSet.size, 'files,', boosted, 'tasks boosted to', priority);\n }\n\n /**\n * Emergency priority for a specific streaming chunk.\n * Called by the Service Worker when a video is stalled waiting for chunk N.\n * Sets urgent priority → queue re-sorts → processQueue() limits concurrency.\n */\n urgentChunk(fileType, fileId, chunkIndex) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] urgentChunk: file not active:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Already in-flight — nothing to do\n const isActive = this._activeTasks.some(\n t => t._parentFile === file && t.chunkIndex === chunkIndex && t.state === 'downloading'\n );\n if (isActive) {\n // Mark the in-flight task as urgent so processQueue() limits concurrency\n const activeTask = this._activeTasks.find(\n t => t._parentFile === file && t.chunkIndex === chunkIndex\n );\n if (activeTask && activeTask._priority < PRIORITY.urgent) {\n activeTask._priority = PRIORITY.urgent;\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (already in-flight, limiting slots)`);\n // Don't call processQueue() — can't stop in-flight tasks, but next\n // processQueue() call (when any task completes) will see hasUrgent\n // and limit new starts to URGENT_CONCURRENCY.\n return true;\n }\n log.info('[DownloadQueue] urgentChunk: already urgent:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Find task in queue (may be past a barrier)\n const idx = this.queue.findIndex(\n t => t !== BARRIER && t._parentFile === file && t.chunkIndex === chunkIndex\n );\n\n if (idx === -1) {\n log.info('[DownloadQueue] urgentChunk: chunk not in queue:', key, 'chunk', chunkIndex);\n return false;\n }\n\n const task = this.queue.splice(idx, 1)[0];\n task._priority = PRIORITY.urgent;\n // Move to front of queue (past any barriers)\n this.queue.unshift(task);\n\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (moved to front)`);\n this.processQueue();\n return true;\n }\n\n /**\n * Process queue — barrier-aware loop.\n *\n * Supports two modes:\n * 1. Priority-sorted (legacy): queue sorted by priority, urgent reduces concurrency\n * 2. Barrier-ordered: queue contains BARRIER sentinels that act as hard gates\n *\n * BARRIER behavior:\n * - When processQueue() hits a BARRIER and running > 0 → STOP (slots stay empty)\n * - When running === 0 → remove barrier, continue with tasks below\n * - Tasks are never reordered past a BARRIER (except urgentChunk which bypasses)\n *\n * Urgent mode: when any task has PRIORITY.urgent, concurrency drops to\n * URGENT_CONCURRENCY so the stalled chunk gets maximum bandwidth.\n */\n processQueue() {\n if (this.paused) return;\n\n // Determine effective concurrency and minimum priority to start\n const hasUrgent = this.queue.some(t => t !== BARRIER && t._priority >= PRIORITY.urgent) ||\n this._activeTasks?.some(t => t._priority >= PRIORITY.urgent && t.state === 'downloading');\n const maxSlots = hasUrgent ? URGENT_CONCURRENCY : this.concurrency;\n const minPriority = hasUrgent ? PRIORITY.urgent : 0; // Urgent = only urgent tasks run\n\n // Fill slots from front of queue\n while (this.running < maxSlots && this.queue.length > 0) {\n const next = this.queue[0];\n\n // Hit a BARRIER — hard gate\n if (next === BARRIER) {\n if (this.running > 0) {\n break; // In-flight tasks still running — slots stay empty\n }\n // All above-barrier tasks done → raise barrier, continue\n this.queue.shift();\n continue;\n }\n\n // Per-file limit: skip to next eligible task (but don't cross barrier)\n if (next._priority < minPriority || !this._canStartTask(next)) {\n let found = false;\n for (let i = 1; i < this.queue.length; i++) {\n if (this.queue[i] === BARRIER) break; // Don't look past barrier\n const task = this.queue[i];\n if (task._priority >= minPriority && this._canStartTask(task)) {\n this.queue.splice(i, 1);\n this._startTask(task);\n found = true;\n break;\n }\n }\n if (!found) break;\n continue;\n }\n\n this.queue.shift();\n this._startTask(next);\n }\n\n if (this.queue.length === 0 && this.running === 0) {\n log.info('[DownloadQueue] All downloads complete');\n }\n }\n\n /**\n * Per-file concurrency check. Priority sorting decides order,\n * this just prevents one file from hogging all connections.\n */\n _canStartTask(task) {\n return task._parentFile._runningCount < this.maxChunksPerFile;\n }\n\n _startTask(task) {\n this.running++;\n task._parentFile._runningCount++;\n this._activeTasks.push(task);\n const key = `${task.fileInfo.type}/${task.fileInfo.id}`;\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.info(`[DownloadQueue] Starting: ${key}${chunkLabel} (${this.running}/${this.concurrency} active)`);\n\n task.start()\n .then(() => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n log.info(`[DownloadQueue] Fetched: ${key}${chunkLabel} (${this.running} active, ${this.queue.length} pending)`);\n this.processQueue();\n return task._parentFile.onTaskComplete(task);\n })\n .catch(err => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n\n // Re-enqueueable types (e.g. datasets): defer re-enqueue instead of permanent failure.\n // CMS \"cache not ready\" resolves when the XTR task runs (30-120s).\n const { maxReenqueues, reenqueueDelayMs } = task._typeConfig;\n if (maxReenqueues > 0) {\n task._reenqueueCount = (task._reenqueueCount || 0) + 1;\n if (task._reenqueueCount > maxReenqueues) {\n log.error(`[DownloadQueue] ${key} exceeded ${maxReenqueues} re-enqueues, failing permanently`);\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n return;\n }\n log.warn(`[DownloadQueue] ${key} failed all retries (attempt ${task._reenqueueCount}/${maxReenqueues}), scheduling re-enqueue in ${reenqueueDelayMs / 1000}s`);\n const timerId = setTimeout(() => {\n this._reenqueueTimers.delete(timerId);\n task.state = 'pending';\n task._parentFile.state = 'downloading';\n this.queue.push(task);\n log.info(`[DownloadQueue] ${key} re-enqueued for retry`);\n this.processQueue();\n }, reenqueueDelayMs);\n this._reenqueueTimers.add(timerId);\n this.processQueue();\n return;\n }\n\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n /**\n * Wait for all queued prepare (HEAD) operations to finish.\n * Returns when the prepare queue is drained and all FileDownloads have\n * either created their tasks or failed.\n */\n awaitAllPrepared() {\n return new Promise((resolve) => {\n const check = () => {\n if (this._preparingCount === 0 && this._prepareQueue.length === 0) {\n resolve();\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n // Skip completed/failed — they stay in active until removeCompleted() runs\n if (file.state === 'complete' || file.state === 'failed') continue;\n progress[key] = {\n downloaded: file.downloadedBytes,\n total: file.totalBytes,\n percent: file.totalBytes > 0 ? (file.downloadedBytes / file.totalBytes * 100).toFixed(1) : 0,\n state: file.state\n };\n }\n return progress;\n }\n\n clear() {\n this.queue = [];\n this.active.clear();\n this.running = 0;\n this._prepareQueue = [];\n this._preparingCount = 0;\n // Cancel any pending getData re-enqueue timers\n for (const id of this._reenqueueTimers) clearTimeout(id);\n this._reenqueueTimers.clear();\n }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n /**\n * Enqueue a file for layout-grouped downloading.\n * Layout grouping is now handled externally by LayoutTaskBuilder.\n * @param {Object} fileInfo - File info\n * @returns {FileDownload}\n */\n enqueueForLayout(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through StoreClient (REST to proxy) — no IndexedDB,\n * no direct Cache API access.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheAnalyzer');\n\n/**\n * Format bytes into human-readable string (e.g. 1.2 GB, 350 MB)\n */\nfunction formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n if (!Number.isFinite(bytes)) return '∞';\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n const value = bytes / Math.pow(1024, i);\n return `${value.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;\n}\n\nexport class CacheAnalyzer {\n /**\n * @param {import('./store-client.js').StoreClient} cache - StoreClient instance\n * @param {object} [options]\n * @param {number} [options.threshold=80] - Storage usage % above which eviction triggers\n */\n constructor(cache, { threshold = 80 } = {}) {\n this.cache = cache;\n this.threshold = threshold;\n }\n\n /**\n * Analyze cache health by comparing cached files against required files.\n *\n * @param {Array<{id: string, type: string}>} requiredFiles - Current RequiredFiles from CMS\n * @returns {Promise<object>} Analysis report\n */\n async analyze(requiredFiles) {\n const cachedFiles = await this.cache.list();\n const storage = await this._getStorageEstimate();\n\n // Build set of required file IDs (as strings for consistent comparison)\n const requiredIds = new Set(requiredFiles.map(f => String(f.id)));\n\n // Categorize cached files\n const required = [];\n const orphaned = [];\n\n for (const file of cachedFiles) {\n if (requiredIds.has(String(file.id))) {\n required.push(file);\n } else if (file.type === 'widget') {\n // Widget HTML IDs are \"layoutId/regionId/widgetId\" — check parent layout\n const parentLayoutId = String(file.id).split('/')[0];\n if (requiredIds.has(parentLayoutId)) {\n required.push(file);\n } else {\n orphaned.push(file);\n }\n } else if (file.type === 'static') {\n // Static files (bundle.min.js, fonts.css, fonts, images) are shared widget\n // dependencies — never orphan them, they're referenced from widget HTML\n required.push(file);\n } else {\n orphaned.push(file);\n }\n }\n\n // Sort orphaned by cachedAt ascending (oldest first — evict these first)\n orphaned.sort((a, b) => (a.cachedAt || 0) - (b.cachedAt || 0));\n\n const orphanedSize = orphaned.reduce((sum, f) => sum + (f.size || 0), 0);\n\n const report = {\n timestamp: Date.now(),\n storage: {\n usage: storage.usage,\n quota: storage.quota,\n percent: storage.quota > 0 ? Math.round((storage.usage / storage.quota) * 100) : 0,\n },\n files: {\n required: required.length,\n orphaned: orphaned.length,\n total: cachedFiles.length,\n },\n orphaned: orphaned.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n })),\n orphanedSize,\n evicted: [],\n threshold: this.threshold,\n };\n\n // Log summary\n log.info(`Storage: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)} (${report.storage.percent}%)`);\n log.info(`Cache: ${required.length} required, ${orphaned.length} orphaned (${formatBytes(orphanedSize)} reclaimable)`);\n\n if (orphaned.length > 0) {\n for (const f of orphaned) {\n const age = Date.now() - (f.cachedAt || 0);\n const days = Math.floor(age / 86400000);\n const hours = Math.floor((age % 86400000) / 3600000);\n const ageStr = days > 0 ? `${days}d ago` : `${hours}h ago`;\n log.info(` Orphaned: ${f.type}/${f.id} (${formatBytes(f.size || 0)}, cached ${ageStr})`);\n }\n }\n\n // Evict only when storage exceeds threshold\n if (report.storage.percent > this.threshold && orphaned.length > 0) {\n log.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);\n const targetBytes = storage.usage - (storage.quota * this.threshold / 100);\n report.evicted = await this._evict(orphaned, targetBytes);\n } else {\n log.info(`No eviction needed (threshold: ${this.threshold}%)`);\n }\n\n return report;\n }\n\n /**\n * Get storage estimate from the browser.\n * Falls back to { usage: 0, quota: Infinity } in environments without the API.\n */\n async _getStorageEstimate() {\n try {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n const { usage, quota } = await navigator.storage.estimate();\n return { usage: usage || 0, quota: quota || Infinity };\n }\n } catch (e) {\n log.warn('Storage estimate unavailable:', e.message);\n }\n return { usage: 0, quota: Infinity };\n }\n\n /**\n * Evict orphaned files (oldest first) until targetBytes are freed.\n * Delegates deletion to StoreClient.remove() which routes to proxy.\n *\n * @param {Array} orphanedFiles - Files to evict, sorted oldest-first\n * @param {number} targetBytes - Bytes to free\n * @returns {Promise<Array>} Evicted file records\n */\n async _evict(orphanedFiles, targetBytes) {\n const toEvict = [];\n let plannedBytes = 0;\n\n for (const file of orphanedFiles) {\n if (plannedBytes >= targetBytes) break;\n toEvict.push(file);\n plannedBytes += file.size || 0;\n }\n\n if (toEvict.length === 0) return [];\n\n try {\n const filesToDelete = toEvict.map(f => ({ type: f.type, id: f.id }));\n await this.cache.remove(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Widget HTML processing — preprocesses widget HTML and stores via REST\n *\n * Handles:\n * - <base> tag injection for relative path resolution (CMS mirror paths)\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * URL rewriting is no longer needed — the CMS serves CSS with relative paths\n * (${PLAYER_API}/dependencies/font.otf), and the <base> tag resolves widget\n * media references via mirror routes. Zero translation, zero regex.\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Stores content via PUT /store/... — no Cache API needed.\n */\n\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\n/**\n * Store widget HTML in ContentStore for iframe loading.\n * Stored at mirror path ${PLAYER_API}/widgets/{L}/{R}/{M} — same URL the\n * CMS serves from, so iframes load directly from Express mirror routes.\n *\n * @param {string} layoutId - Layout ID\n * @param {string} regionId - Region ID\n * @param {string} mediaId - Media ID\n * @param {string} html - Widget HTML content\n * @returns {Promise<string>} Cache key URL (absolute path for iframe src)\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`;\n\n // Inject <base> tag — resolves relative media refs (e.g. \"42\") to mirror route\n const baseTag = `<base href=\"${PLAYER_API}/media/file/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag (skip if already present)\n if (!html.includes('<base ')) {\n if (html.includes('<head>')) {\n modifiedHtml = html.replace('<head>', '<head>' + baseTag);\n } else if (html.includes('<HEAD>')) {\n modifiedHtml = html.replace('<HEAD>', '<HEAD>' + baseTag);\n } else {\n modifiedHtml = baseTag + html;\n }\n }\n\n // Inject CSS default for object-position to suppress CMS template warning\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Replace CMS placeholders left for \"client-side SDK handling\"\n modifiedHtml = modifiedHtml.replace(/\\[\\[ViewPortWidth]]/g, 'device-width');\n\n // Route HLS streams through local proxy (adds CORS headers, rewrites segments)\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\\s\"')<]+\\.m3u8\\b/gi,\n (url) => '/stream-proxy?url=' + encodeURIComponent(url)\n );\n\n // Rewrite dependency URLs to local mirror paths. CMS sends absolute URLs\n // like https://cms.example.com${PLAYER_API}/dependencies/bundle.min.js\n // which fail due to CORS/auth. Replace with local PLAYER_API/dependencies/...\n const depsPattern = new RegExp(\n `https?://[^\"'\\\\s)]+?(${PLAYER_API.replace(/\\//g, '\\\\/')}/dependencies/[^\"'\\\\s?)]+)(\\\\?[^\"'\\\\s)]*)?`,\n 'g'\n );\n modifiedHtml = modifiedHtml.replace(depsPattern, (_, path) => path);\n\n // Inject xiboICTargetId — XIC library reads this global before its IIFE runs\n // to set _lib.targetId, which is included in every IC HTTP request as {id: ...}\n if (!modifiedHtml.includes('xiboICTargetId')) {\n const targetIdScript = `<script>var xiboICTargetId = '${mediaId}';</script>`;\n if (modifiedHtml.includes(baseTag)) {\n modifiedHtml = modifiedHtml.replace(baseTag, baseTag + targetIdScript);\n } else if (modifiedHtml.includes('<head>')) {\n modifiedHtml = modifiedHtml.replace('<head>', '<head>' + targetIdScript);\n } else {\n modifiedHtml = targetIdScript + modifiedHtml;\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag in widget HTML');\n\n // Store widget HTML — deps are already downloaded by the pipeline\n const putResp = await fetch(`/store${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n body: modifiedHtml,\n });\n putResp.body?.cancel();\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n return cacheKey;\n}\n"],"names":["log","createLogger","BASE","CacheManager","type","id","filename","mediaId","layoutId","key","lid","orphaned","layouts","cacheManager","StoreClient","response","_a","error","body","contentType","files","result","FILE_TYPES","getFileTypeConfig","DEFAULT_CONCURRENCY","DEFAULT_CHUNK_SIZE","DEFAULT_MAX_CHUNKS_PER_FILE","CHUNK_THRESHOLD","URGENT_CONCURRENCY","FETCH_TIMEOUT_MS","HEAD_TIMEOUT_MS","inferContentType","fileInfo","ext","_b","PRIORITY","BARRIER","getUrlExpiry","url","match","isUrlExpired","graceSeconds","expiry","DownloadTask","options","headers","maxRetries","attempt","ac","timer","fetchOpts","msg","delay","chunkLabel","resolve","FileDownload","res","rej","queue","size","skipHead","head","chunkSize","ranges","start","needed","r","skippedCount","isResume","sorted","a","b","task","highCount","t","e","ordered","i","blob","assembled","LayoutTaskBuilder","DownloadQueue","existing","oldExpiry","file","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","total","items","taskCount","barrierCount","item","fileType","fileId","boosted","fileIds","priority","idSet","matchValue","_c","_d","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","err","maxReenqueues","reenqueueDelayMs","timerId","check","progress","DownloadManager","formatBytes","bytes","units","CacheAnalyzer","cache","threshold","requiredFiles","cachedFiles","storage","requiredIds","f","required","parentLayoutId","orphanedSize","sum","report","age","days","hours","ageStr","targetBytes","usage","quota","orphanedFiles","toEvict","plannedBytes","filesToDelete","cacheWidgetHtml","regionId","html","cacheKey","PLAYER_API","baseTag","modifiedHtml","cssFixTag","depsPattern","_","path","targetIdScript"],"mappings":"mEAaA,MAAMA,EAAMC,EAAa,OAAO,EAG1BC,EAAQ,OAAO,OAAW,KAC5B,OAAO,SAAS,SAAS,QAAQ,WAAY,EAAE,EAAE,QAAQ,MAAO,EAAE,GAAK,cAGpE,MAAMC,CAAa,CACxB,aAAc,CAEZ,KAAK,WAAa,IAAI,GACxB,CAMA,YAAYC,EAAMC,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