materialCache.js 34.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
const md5 = require('../lib/md5.js')

// 基础缓存与图片文件缓存分开版本,图片缓存只在 storage 中保存轻量文件路径。
const SOURCE_PREFIX = 'source_v2_'
const IMAGE_PREFIX = 'material_file_v1_'
const LEGACY_IMAGE_PREFIX = 'material_base64_'
const URL_PREFIX = 'material_file_url_v1_'
const LEGACY_URL_PREFIX = 'material_url_'
const imageGenerations = new Map()
const activeImageTargets = new Map()
const writeQueues = new Map()
// 同一张图片(素材 ID + 位置 + URL 指纹)只下载保存一次,首屏补齐与后台批量缓存共用一个 Promise。
const pendingConversions = new Map()
// 同一 OSS 地址可能同时出现在多个素材位置;下载层再按地址合并,避免为同一文件重复请求。
const pendingUrlDownloads = new Map()
const downloadQueue = []
let activeDownloads = 0
const imageReadQueue = []
const pendingImageReads = new Map()
let activeImageReads = 0
const imageMemory = new Map()

/*
 * 素材来源日志写入规则:
 * 1. 只统计页面实际取得并准备展示的图片;刚下载但尚未展示的图片,等首次展示时再记为 OSS 来源。
 * 2. 同一素材缓存范围内,最后一张图片处理完成后等待 2 秒,再把结果合并成一条来源汇总;
 *    如果两次结果间隔超过 2 秒,则会分别写入日志。
 * 3. 同一批次内,同一张图片只统计一次;同一张图片同时出现 OSS 和文件记录时,以 OSS 为准。
 * 4. 本次运行刚从 OSS 下载成功并首次展示的图片记为 OSS;其余从已保存文件或内存中的本地路径取得的图片记为文件。
 * 5. OSS 下载成功的图片逐行记录开始时间、成功时间、OSS 地址和最终文件读取路径;不记录状态 200 和临时路径。
 * 6. OSS 下载失败的图片逐行记录开始时间、失败时间、失败状态和 OSS 地址;只有失败时才记录下载状态。
 * 7. 接口图片地址在识别、生成缓存标识、比较和下载前,统一清除首尾空格。
 * 8. 每条日志最前面的写入时间由全局日志工具自动添加。
 */
// 记录本次运行中刚从 OSS 保存、但尚未在页面展示的图片;首次展示后即清除。
const pendingImageOrigins = new Map()
const downloadSuccessDetails = new Map()
const downloadFailureDetails = new Map()
const imageSourceLogBatches = new Map()
const IMAGE_SOURCE_LOG_DELAY = 2000
const IMAGE_MEMORY_LIMIT = 16 * 1024 * 1024
let imageMemoryBytes = 0
let imageMemoryEpoch = 0

function formatLogTime(date = new Date()) {
  const pad = (value, length = 2) => String(value).padStart(length, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
    `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
}

function writeMaterialImageSourceLog(logger, message) {
  if (logger && typeof logger.info === 'function') {
    try {
      logger.info(message)
    } catch (error) {
      console.warn('素材来源日志写入失败', error?.message || error)
    }
  } else if (typeof console !== 'undefined' && typeof console.info === 'function') {
    console.info(message)
  }
}

function flushMaterialImageSourceLog(key, batch) {
  if (imageSourceLogBatches.get(key) !== batch) return
  imageSourceLogBatches.delete(key)
  const lines = [`[素材来源汇总] OSS=${batch.oss.size} | 文件=${batch.files.size} | OSS失败=${batch.failures.size}`]
  if (batch.oss.size) {
    lines.push('OSS明细:')
    ;[...batch.oss.values()].forEach((detail, index) => lines.push(
      `素材${index + 1} | 开始下载时间=${detail.downloadStartTime} | 下载成功时间=${detail.downloadSuccessTime} | ` +
      `OSS路径=${detail.ossPath} | 文件读取路径=${detail.filePath}`))
  }
  if (batch.failures.size) {
    lines.push('OSS失败明细:')
    ;[...batch.failures.values()].forEach((detail, index) => lines.push(
      `素材${index + 1} | 开始下载时间=${detail.downloadStartTime} | 下载失败时间=${detail.downloadFailureTime} | ` +
      `下载状态=${detail.status} | OSS路径=${detail.ossPath}`))
  }
  writeMaterialImageSourceLog(batch.logger, lines.join('\n'))
}

// 同一车型短时间内触发的多次读取按图片去重,合并成一条来源日志。
function queueMaterialImageSourceLog(key, targetKey, source, detail) {
  let batch = imageSourceLogBatches.get(key)
  if (!batch) {
    batch = {
      oss: new Map(),
      files: new Set(),
      failures: new Map(),
      logger: typeof uni !== 'undefined' ? uni.$logger : null,
      timer: null
    }
    imageSourceLogBatches.set(key, batch)
  }
  if (source === 'OSS') {
    batch.files.delete(targetKey)
    batch.failures.delete(targetKey)
    batch.oss.set(targetKey, detail)
  } else if (!batch.oss.has(targetKey)) batch.files.add(targetKey)
  if (batch.timer) clearTimeout(batch.timer)
  batch.timer = setTimeout(() => flushMaterialImageSourceLog(key, batch), IMAGE_SOURCE_LOG_DELAY)
}

function queueMaterialImageFailureLog(key, targetKey, detail) {
  let batch = imageSourceLogBatches.get(key)
  if (!batch) {
    batch = {
      oss: new Map(),
      files: new Set(),
      failures: new Map(),
      logger: typeof uni !== 'undefined' ? uni.$logger : null,
      timer: null
    }
    imageSourceLogBatches.set(key, batch)
  }
  if (!batch.oss.has(targetKey)) batch.failures.set(targetKey, detail)
  if (batch.timer) clearTimeout(batch.timer)
  batch.timer = setTimeout(() => flushMaterialImageSourceLog(key, batch), IMAGE_SOURCE_LOG_DELAY)
}

const isRemote = value => typeof value === 'string' && /^https?:\/\//i.test(value)
const isLocalImage = value => typeof value === 'string' && value.trim() !== '' &&
  !isRemote(value) && !/^data:/i.test(value)
const hasId = id => (typeof id === 'string' && id.trim() !== '') || (typeof id === 'number' && Number.isFinite(id))
const isSource = data => data && Array.isArray(data.moduleList) && Array.isArray(data.toolList)

// 只用于判断图片格式,不改变真实下载地址。兼容 OSS 对象名中把 ?V=1 编码成 %3FV%3D1 的情况。
function imageExtensionFromUrl(url) {
  let decodedUrl = url
  try {
    decodedUrl = decodeURIComponent(url)
  } catch (error) {
    // 地址含不完整转义符时继续使用原值,后续按无法识别格式处理。
  }
  return decodedUrl.split(/[?#]/)[0].match(/\.(png|jpe?g|webp|gif|bmp|svg|avif)$/i)?.[1].toLowerCase() || ''
}

function imageTypeFailure(url, declaredType = '') {
  const normalizedType = String(declaredType).split(';')[0].trim().toLowerCase()
  const extension = imageExtensionFromUrl(url)
  const declaredImage = /^image\/[\w.+-]+$/.test(normalizedType)
  const genericType = !normalizedType || normalizedType === 'application/octet-stream' || normalizedType === 'binary/octet-stream'
  return declaredImage || (genericType && extension) ? '' : `type:${normalizedType || 'unknown'}`
}

function getSourceKey(shopMerchantId, sceneType, params = {}) {
  let key = `${SOURCE_PREFIX}${sceneType}_${shopMerchantId}`
  if (hasId(params.brandId) && hasId(params.subBrandId)) key += `_${params.brandId}_${params.subBrandId}`
  return key
}

function imageKey(sourceKey, id, slotKey) {
  // 素材 ID 下按图片位置和 URL 指纹分槽;每条记录的 value 只有本地文件路径。
  // 门店、场景和车型作为命名空间,避免不同配置串图。
  return `${IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}`
}

function legacyImageKey(sourceKey, id, slotKey) {
  return `${LEGACY_IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}`
}

// 位置 => 该位置上次成功转换时使用的 URL,用于判断接口地址是否变化。
function urlKey(sourceKey) {
  return `${URL_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}`
}

function legacyUrlKey(sourceKey) {
  return `${LEGACY_URL_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}`
}

function getNetworkStatus() {
  return new Promise(resolve => {
    uni.getNetworkType({
      success: res => resolve(!!res.networkType && res.networkType !== 'none'),
      fail: () => resolve(false)
    })
  })
}

function read(key) {
  return new Promise(resolve => {
    uni.getStorage({ key, success: res => resolve(res.data), fail: () => resolve(null) })
  })
}

function remove(key) {
  if (key.startsWith(IMAGE_PREFIX)) forgetImage(key)
  return new Promise(resolve => {
    uni.removeStorage({ key, success: resolve, fail: resolve })
  })
}

function removeSavedFile(filePath) {
  if (!isLocalImage(filePath) || typeof uni.removeSavedFile !== 'function') return Promise.resolve()
  return new Promise(resolve => {
    uni.removeSavedFile({ filePath, success: resolve, fail: resolve })
  })
}

// 文件路径记录不等于文件仍存在:App 可能因系统清理而丢失保存的素材文件。
function savedFileExists(filePath) {
  if (!isLocalImage(filePath)) return Promise.resolve(false)
  if (typeof plus !== 'undefined' && plus.io?.resolveLocalFileSystemURL) {
    return new Promise(resolve => {
      try {
        plus.io.resolveLocalFileSystemURL(filePath, () => resolve(true), () => resolve(false))
      } catch (error) {
        resolve(false)
      }
    })
  }
  if (typeof uni.getFileInfo === 'function') {
    return new Promise(resolve => {
      uni.getFileInfo({ filePath, success: () => resolve(true), fail: () => resolve(false) })
    })
  }
  // 不支持文件查询的运行环境沿用路径缓存,避免影响非 App 端原有行为。
  return Promise.resolve(true)
}

function forgetImage(key) {
  const cached = imageMemory.get(key)
  if (cached) imageMemoryBytes -= cached.length * 2
  imageMemory.delete(key)
  pendingImageOrigins.delete(key)
  // 写入与读取重叠时,旧读取结果不能重新放回内存。
  const pending = pendingImageReads.get(key)
  if (pending) {
    pending.invalidated = true
    pendingImageReads.delete(key)
  }
}

function clearImageMemory() {
  imageMemory.clear()
  imageMemoryBytes = 0
  imageMemoryEpoch++
}

function rememberImage(key, image) {
  const bytes = image.length * 2
  if (bytes > IMAGE_MEMORY_LIMIT) return
  const cached = imageMemory.get(key)
  if (cached) imageMemoryBytes -= cached.length * 2
  imageMemory.delete(key)
  while (imageMemoryBytes + bytes > IMAGE_MEMORY_LIMIT && imageMemory.size) {
    const oldest = imageMemory.keys().next().value
    imageMemoryBytes -= imageMemory.get(oldest).length * 2
    imageMemory.delete(oldest)
  }
  imageMemory.set(key, image)
  imageMemoryBytes += bytes
}

function retryInvalidatedRead(job) {
  if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
  // 成功写入已使旧读取失效,仍在显示的素材直接重读同一 key。
  // 复用读取队列以保持并发上限,过期页面不再参与新一轮读取。
  job.subscribers.forEach(subscriber => {
    if (!subscriber.isCurrent()) subscriber.resolve(null)
    else readImage(job.key, subscriber.isCurrent, subscriber.metrics).then(subscriber.resolve)
  })
}

function drainImageReads() {
  while (activeImageReads < 3 && imageReadQueue.length) {
    const job = imageReadQueue.shift()
    const subscribers = job.subscribers.filter(subscriber => subscriber.isCurrent())
    if (!subscribers.length) {
      job.subscribers.forEach(subscriber => subscriber.resolve(null))
      if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
      continue
    }
    if (job.invalidated) { retryInvalidatedRead(job); continue }
    activeImageReads++
    subscribers[0].metrics.storageReads++
    read(job.key).catch(() => null).then(async value => {
      if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
      if (job.invalidated) { retryInvalidatedRead(job); return }
      let image = isLocalImage(value) ? value : null
      if (image && !await savedFileExists(image)) {
        image = null
        // 删除无效路径,后续在线读取和后台缓存都可重新下载。
        await remove(job.key)
      }
      if (image && job.epoch === imageMemoryEpoch && job.subscribers.some(subscriber => subscriber.isCurrent())) {
        rememberImage(job.key, image)
      }
      job.subscribers.forEach(subscriber => subscriber.resolve(subscriber.isCurrent() ? image : null))
    }).finally(() => {
      if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
      activeImageReads--
      drainImageReads()
    })
  }
}

function readImage(key, isCurrent, metrics) {
  if (!isCurrent()) return Promise.resolve(null)
  const image = imageMemory.get(key)
  if (image) {
    return savedFileExists(image).then(exists => {
      if (!exists) {
        forgetImage(key)
        return null
      }
      imageMemory.delete(key)
      imageMemory.set(key, image)
      metrics.memoryHits++
      return image
    })
  }
  return new Promise(resolve => {
    let job = pendingImageReads.get(key)
    if (!job) {
      job = { key, subscribers: [], epoch: imageMemoryEpoch, invalidated: false }
      pendingImageReads.set(key, job)
      imageReadQueue.push(job)
    } else metrics.sharedReads++
    job.subscribers.push({ resolve, isCurrent, metrics })
    drainImageReads()
  })
}

// 同一个 key 的异步写入串行执行,避免较早发起的写入较晚完成。
function write(key, data, shouldWrite = () => true) {
  const previous = writeQueues.get(key) || Promise.resolve()
  const pending = previous.catch(() => { }).then(() => {
    if (!shouldWrite()) return
    return new Promise((resolve, reject) => uni.setStorage({
      key, data,
      success: result => {
        if (key.startsWith(IMAGE_PREFIX)) forgetImage(key)
        resolve(result)
      },
      fail: reject
    }))
  })
  writeQueues.set(key, pending)
  const cleanup = () => { if (writeQueues.get(key) === pending) writeQueues.delete(key) }
  pending.then(cleanup, cleanup)
  return pending
}

function withoutBase64(value) {
  if (typeof value === 'string') return /^data:image\//i.test(value) ? '' : value
  if (Array.isArray(value)) return value.map(withoutBase64)
  if (!value || typeof value !== 'object') return value
  return Object.fromEntries(Object.keys(value).map(key => [key, withoutBase64(value[key])]))
}

async function saveSourceCache(key, data) {
  const base = withoutBase64({ id: data.id, moduleList: data.moduleList || [], toolList: data.toolList || [] })
  // 新基础数据一旦提交,旧图片任务不得继续覆盖该配置。
  const generation = (imageGenerations.get(key) || 0) + 1
  imageGenerations.set(key, generation)
  const targets = [...materialGroups(base)].flatMap(([id, entries]) =>
    entries.flatMap(entry => entry.slots).map(slot => imageKey(key, id, slot.key)))
  activeImageTargets.set(key, { generation, targets: new Set(targets) })
  await write(key, base)
  return base
}

// 只枚举页面使用的图片字段,业务文本、视频、跳转地址不参与图片缓存。
function imageSlots(item, kind, options = {}) {
  const slots = []
  const hasCarKey = Object.prototype.hasOwnProperty.call(options, 'carKey')
  const matchesCar = entry => !hasCarKey || (
    entry && hasId(options.carKey) && (
      String(entry.relVehicleSeriesId) === String(options.carKey) ||
      String(entry.relVehicleModelId) === String(options.carKey)
    )
  )
  function add(path, value) {
    if (Array.isArray(options.fields) && (path.length !== 1 || !options.fields.includes(path[0]))) return
    // 接口偶尔会返回首尾空格,必须在参与缓存和下载前统一清理。
    const normalizedValue = typeof value === 'string' ? value.trim() : value
    if (isRemote(normalizedValue)) slots.push({
      kind, path, url: normalizedValue,
      // key 含 URL 指纹,用于定位图片;name 只标识位置,用于比对接口 URL 与缓存 URL。
      key: md5(JSON.stringify([kind, path, normalizedValue])),
      name: md5(JSON.stringify([kind, path]))
    })
  }
  function fields(value, path, names) {
    if (!value || typeof value !== 'object') return
    names.forEach(name => add([...path, name], value[name]))
  }
  fields(item, [], ['thumbnail', 'homeEntranceCover', 'contentPicUrl', 'shortTitleUrl', 'carIcon', 'productPoster'])
  if (Array.isArray(options.fields)) return slots
  const views = item.receptionSourceDetailList
  // ThreeGuarantees 按 tab 位置取图(views[activeIndex] / views[tabIndex]),
  // 这个位置无法由车系推断,必须枚举全部键;其余组件只取当前车系或 detailUrl / bgUrl。
  const restrictViewKeys = hasCarKey &&
    !/^threeguarantee/i.test(String(item.componentName || '').replace(/[^a-z]/gi, ''))
  if (Array.isArray(views)) {
    views.forEach((view, index) => {
      const path = ['receptionSourceDetailList', index]
      // 位置直接存图片地址时同样要缓存,否则组件读到的仍是在线地址。
      if (isRemote(view)) add(path, view)
      else fields(view, path, ['detailUrl', 'bgUrl'])
    })
  } else if (views && typeof views === 'object') {
    const keys = restrictViewKeys ? [...new Set(['detailUrl', 'bgUrl', String(options.carKey)])] : Object.keys(views)
    keys.forEach(key => add(['receptionSourceDetailList', key], views[key]))
  } else add(['receptionSourceDetailList'], views)
    ;['screenList', 'materialDetailList'].forEach(name => {
      if (Array.isArray(item[name])) item[name].forEach((entry, index) => {
        if (name === 'materialDetailList' && !matchesCar(entry)) return
        fields(entry, [name, index], ['url', 'detailUrl', 'bgUrl', 'contentPicUrl', 'homeEntranceCover', 'thumbnail'])
      })
    })
  function caseImages(value, path) {
    if (!value || typeof value !== 'object') return
    Object.keys(value).forEach(key => {
      if (key === 'imageUrl') add([...path, key], value[key])
      else if (typeof value[key] === 'object') caseImages(value[key], [...path, key])
    })
  }
  caseImages(item.receptionpriproCusCaseList, ['receptionpriproCusCaseList'])
  return slots
}

function materialGroups(data) {
  const groups = new Map()
    ;['moduleList', 'toolList'].forEach(kind => {
      ; (data[kind] || []).forEach(item => {
        if (!item || !hasId(item.id)) return
        const id = String(item.id)
        if (!groups.has(id)) groups.set(id, [])
        groups.get(id).push({ item, slots: imageSlots(item, kind) })
      })
    })
  return groups
}

// 诊断用:枚举补齐后仍是在线图片地址的字段路径,确认还有哪些图片位置没被缓存覆盖。
function remoteImagePaths(items) {
  const found = []
  const walk = (value, path) => {
    if (typeof value === 'string') {
      if (/(^https?:\/\/).+\.(png|jpe?g|webp|gif|bmp|svg|avif)([?#]|$)/i.test(value)) found.push(path.join('.'))
      return
    }
    if (!value || typeof value !== 'object') return
    Object.keys(value).forEach(key => walk(value[key], [...path, key]))
  }
  items.forEach((item, index) => walk(item, [index]))
  return [...new Set(found)]
}

// 直接根据当前素材 ID、图片位置和 URL 算出 key,不枚举 storage 或读取其他素材图片。
async function hydrateSourceImages(key, base, options = {}) {
  const isCurrent = options.isCurrent || (() => true)
  const maxImages = Number.isFinite(options.maxImages) ? Math.max(0, options.maxImages) : Infinity
  let remainingImages = maxImages
  const start = Date.now()
  const metrics = { storageReads: 0, memoryHits: 0, sharedReads: 0, imageHits: 0, missingImages: 0, downloadedImages: 0, requestedImages: 0, pathBytes: 0, leftoverUrls: [] }
  if (!isCurrent() || !isSource(base)) return null
  const display = { ...base }
  const hydrated = []
  const pending = []
    ;['moduleList', 'toolList'].forEach(kind => {
      const ids = options[kind === 'moduleList' ? 'moduleIds' : 'toolIds']
      const selected = Array.isArray(ids) ? new Set(ids.map(String)) : null
      display[kind] = base[kind].map(item => {
        if (!item || !hasId(item.id) || (selected && !selected.has(String(item.id)))) return item
        const allSlots = imageSlots(item, kind, options)
        // 首屏只等待最能代表当前素材的图片;其余图片由后续后台读取补齐。
        const slots = remainingImages === Infinity ? allSlots : allSlots
          .sort((a, b) => {
            const priority = ['detailUrl', 'contentPicUrl', 'bgUrl', 'homeEntranceCover', 'thumbnail', 'shortTitleUrl']
            const getPriority = slot => {
              const index = priority.indexOf(slot.path[slot.path.length - 1])
              return index < 0 ? priority.length : index
            }
            return getPriority(a) - getPriority(b)
          })
          .slice(0, remainingImages)
        remainingImages -= slots.length
        if (!slots.length) return item
        // 只复制本次要展示的素材,其他条目保留轻量基础数据。
        const clone = JSON.parse(JSON.stringify(item))
        // 首屏渐进加载时,未准备好的网络图片不能直接交给组件,避免组件绕过文件缓存自行发起请求。
        if (options.hideUnloadedImages) {
          const selectedKeys = new Set(slots.map(slot => slot.key))
          allSlots.filter(slot => !selectedKeys.has(slot.key)).forEach(slot => {
            let target = clone
            slot.path.slice(0, -1).forEach(part => { target = target[part] })
            target[slot.path[slot.path.length - 1]] = ''
          })
        }
        hydrated.push(clone)
        slots.forEach(slot => {
          metrics.requestedImages++
          const targetKey = imageKey(key, item.id, slot.key)
          pending.push(readImage(targetKey, isCurrent, metrics).then(async image => {
            if (!isCurrent()) return
            // 首屏可能早于后台文件保存完成:缺失的位置按需补齐,优先渲染持久化文件。
            if (!image && options.allowDownload) {
              metrics.downloadedImages++
              image = await convertSlotImage(key, item.id, slot)
              if (!isCurrent()) return
            }
            if (!image) { metrics.missingImages++; return }
            const ossDetail = pendingImageOrigins.get(targetKey)
            const source = ossDetail ? 'OSS' : '文件'
            pendingImageOrigins.delete(targetKey)
            queueMaterialImageSourceLog(key, targetKey, source, ossDetail)
            metrics.imageHits++
            metrics.pathBytes += image.length * 2
            let target = clone
            slot.path.slice(0, -1).forEach(part => { target = target[part] })
            target[slot.path[slot.path.length - 1]] = image
          }))
        })
        return clone
      })
    })
  await Promise.all(pending)
  metrics.leftoverUrls = remoteImagePaths(hydrated).slice(0, 10)
  metrics.durationMs = Date.now() - start
  metrics.cancelled = !isCurrent()
  if (typeof options.onMetrics === 'function') options.onMetrics(metrics)
  return isCurrent() ? display : null
}

async function readSourceCache(key, online = true, options = {}) {
  const isCurrent = options.isCurrent || (() => true)
  if (!isCurrent()) return null
  const base = await read(key)
  if (!isCurrent()) return null
  if (!isSource(base)) {
    if (online) return null
    const legacy = await read(key.replace(SOURCE_PREFIX, 'source_'))
    return isCurrent() && isSource(legacy) ? legacy : null
  }
  if (online || options.baseOnly) return base
  let incomplete = false
  const display = await hydrateSourceImages(key, base, {
    ...options,
    onMetrics: metrics => {
      incomplete = metrics.missingImages > 0
      if (typeof options.onMetrics === 'function') options.onMetrics(metrics)
    }
  })
  if (!isCurrent()) return null
  if (incomplete) {
    // 迁移中途断网时使用完整旧快照,不能把来源不明的旧图拼到新素材上。
    const legacy = await read(key.replace(SOURCE_PREFIX, 'source_'))
    if (!isCurrent()) return null
    if (isSource(legacy)) return legacy
  }
  return display
}

function downloadImageFile(url) {
  return new Promise(resolve => {
    const downloadStartTime = formatLogTime()
    const fail = reason => {
      downloadFailureDetails.set(url, {
        downloadStartTime,
        downloadFailureTime: formatLogTime(),
        status: reason,
        ossPath: url
      })
      console.warn('素材图片下载失败', { url, reason })
      return ''
    }
    // App 原生下载器会把 %3F 解码进临时文件名,uni.saveFile 随后可能把 ? 当成参数而找不到文件。
    // 对这类 OSS 对象直接指定安全的持久化文件名,真实请求 URL 保持不变,也避免二次下载。
    if (/%3f/i.test(url) && typeof plus !== 'undefined' && plus.downloader?.createDownload) {
      const extension = imageExtensionFromUrl(url) || 'img'
      let task = null
      let settled = false
      const finish = value => {
        if (settled) return
        settled = true
        clearTimeout(timer)
        resolve(value)
      }
      const timer = setTimeout(() => {
        try { task?.abort() } catch (error) {}
        finish(fail('timeout'))
      }, 15000)
      try {
        task = plus.downloader.createDownload(url, {
          filename: `_doc/material_${md5(url)}.${extension}`
        }, (download, status) => {
          if (status < 200 || status >= 300) return finish(fail(`status:${status}`))
          const typeFailure = imageTypeFailure(url, download?.getResponseHeader?.('Content-Type') || '')
          if (typeFailure) return finish(fail(typeFailure))
          const filePath = download?.filename || ''
          if (!isLocalImage(filePath)) return finish(fail('empty-saved-path'))
          downloadFailureDetails.delete(url)
          downloadSuccessDetails.set(filePath, {
            downloadStartTime,
            downloadSuccessTime: formatLogTime(),
            ossPath: url,
            filePath
          })
          finish(filePath)
        })
        task.start()
      } catch (error) {
        finish(fail(error?.message || 'native-download'))
      }
      return
    }
    if (typeof uni.downloadFile !== 'function' || typeof uni.saveFile !== 'function') {
      resolve(fail('file-api-unavailable'))
      return
    }
    uni.downloadFile({
      url, timeout: 15000,
      success: res => {
        if (res.statusCode < 200 || res.statusCode >= 300) return resolve(fail(`status:${res.statusCode}`))
        const downloadSuccessTime = formatLogTime()
        downloadFailureDetails.delete(url)
        const header = res.header || {}
        const typeKey = Object.keys(header).find(key => key.toLowerCase() === 'content-type')
        const declaredType = typeKey ? String(header[typeKey]).split(';')[0].trim().toLowerCase() : ''
        const typeFailure = imageTypeFailure(url, declaredType)
        // 明确的图片类型直接通过;通用二进制类型必须能从解码后的地址识别出图片扩展名。
        if (typeFailure) return resolve(fail(typeFailure))
        if (!res.tempFilePath) return resolve(fail('empty-path'))
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: saved => {
            if (!isLocalImage(saved.savedFilePath)) return resolve(fail('empty-saved-path'))
            downloadSuccessDetails.set(saved.savedFilePath, {
              downloadStartTime,
              downloadSuccessTime,
              ossPath: url,
              filePath: saved.savedFilePath
            })
            resolve(saved.savedFilePath)
          },
          fail: error => resolve(fail(error?.errMsg || 'save-file'))
        })
      },
      fail: error => resolve(fail(error?.errMsg || 'request'))
    })
  })
}

function drainDownloads() {
  while (activeDownloads < 3 && downloadQueue.length) {
    const job = downloadQueue.shift()
    if (!job.isCurrent()) { job.resolve(''); continue }
    activeDownloads++
    downloadImageFile(job.url).catch(() => '').then(job.resolve).finally(() => {
      activeDownloads--
      drainDownloads()
    })
  }
}

function enqueueImage(url, isCurrent) {
  const pending = pendingUrlDownloads.get(url)
  if (pending) return pending
  const task = new Promise(resolve => {
    downloadQueue.push({ url, isCurrent, resolve })
    drainDownloads()
  })
  pendingUrlDownloads.set(url, task)
  task.then(image => {
    if (pendingUrlDownloads.get(url) === task) pendingUrlDownloads.delete(url)
    // 等所有共享调用方取走本次结果后,再清理仅属于这次下载的明细。
    setTimeout(() => {
      if (image) downloadSuccessDetails.delete(image)
      downloadFailureDetails.delete(url)
    }, 0)
  }, () => {
    if (pendingUrlDownloads.get(url) === task) pendingUrlDownloads.delete(url)
    downloadFailureDetails.delete(url)
  })
  return task
}

// 下载并持久化单个槽位,storage 只保存文件路径;失败时不写成功标记,确保下次可重试。
// key 由素材 ID、图片位置和 URL 指纹共同决定,同一次下载的调用方共享结果,不会重复请求。
function convertSlotImage(key, id, slot) {
  const target = imageKey(key, id, slot.key)
  const pending = pendingConversions.get(target)
  if (pending) return pending
  const task = enqueueImage(slot.url, () => true).then(async image => {
    if (!isLocalImage(image)) {
      const failure = downloadFailureDetails.get(slot.url)
      if (failure) queueMaterialImageFailureLog(key, target, failure)
      console.warn('素材图片文件保存失败', slot.url)
      return ''
    }
    try {
      await write(target, image, () => true)
    } catch (error) {
      const successDetail = downloadSuccessDetails.get(image)
      queueMaterialImageFailureLog(key, target, {
        downloadStartTime: successDetail?.downloadStartTime || formatLogTime(),
        downloadFailureTime: formatLogTime(),
        status: `cache-write:${error?.message || 'failed'}`,
        ossPath: slot.url
      })
      downloadSuccessDetails.delete(image)
      await removeSavedFile(image)
      console.warn('素材图片路径写入缓存失败,已清理孤立文件', target)
      return ''
    }
    // 同一 URL 的旧 Base64 只在新文件成功后删除,迁移失败时仍保留原缓存。
    remove(legacyImageKey(key, id, slot.key))
    rememberImage(target, image)
    pendingImageOrigins.set(target, downloadSuccessDetails.get(image) || {
      downloadStartTime: formatLogTime(),
      downloadSuccessTime: formatLogTime(),
      ossPath: slot.url,
      filePath: image
    })
    return image
  }).catch(() => '')
  pendingConversions.set(target, task)
  const cleanup = () => { if (pendingConversions.get(target) === task) pendingConversions.delete(target) }
  task.then(cleanup, cleanup)
  return task
}

async function cacheMaterialImages(key, base) {
  const generation = (imageGenerations.get(key) || 0) + 1
  imageGenerations.set(key, generation)
  const isCurrent = () => imageGenerations.get(key) === generation
  const slots = [...materialGroups(base)].flatMap(([id, entries]) =>
    entries.flatMap(entry => entry.slots).map(slot => ({ id, slot })))
  activeImageTargets.set(key, {
    generation,
    targets: new Set(slots.map(({ id, slot }) => imageKey(key, id, slot.key)))
  })
  // 只读取位置、URL 与文件路径的轻量记录,不读取图片内容。
  const cachedUrls = await read(urlKey(key))
  const urls = cachedUrls && typeof cachedUrls === 'object' ? { ...cachedUrls } : {}
  const activeSlotNames = new Set()
  let urlsChanged = false
  const results = await Promise.all(slots.map(async ({ id, slot }) => {
      // 素材 ID + 位置,才是本次要比对 URL 的槽位。
      const slotName = `${id}_${slot.name}`
      activeSlotNames.add(slotName)
      const target = imageKey(key, id, slot.key)
      const previous = urls[slotName]
      const storedPath = await read(target)
      const storedFilePath = isLocalImage(storedPath) && await savedFileExists(storedPath) ? storedPath : ''
      if (isLocalImage(storedPath) && !storedFilePath) await remove(target)
      const recorded = previous && previous.url === slot.url && previous.key === target &&
        isLocalImage(previous.path) && storedFilePath === previous.path
      // 同一素材位置上 URL 与已保存文件一致时,跳过重复下载。
      if (recorded || storedFilePath) {
        // 首屏补齐过的位置补记到 storage,下次冷启动同样能跳过。
        if (!recorded) {
          urls[slotName] = { url: slot.url, path: storedFilePath, key: target }
          urlsChanged = true
        }
        return true
      }
      const image = await convertSlotImage(key, id, slot)
      if (!image) return false
      if (!isCurrent()) {
        // 新一轮缓存或当前页面可能正在复用同一个下载结果。过期调用不能删除共享文件,
        // 当前配置不再使用这个目标时才清理,避免留下旧品牌切换过程中的孤立文件。
        const latest = activeImageTargets.get(key)
        if (!latest?.targets.has(target)) {
          await remove(target)
          await removeSavedFile(image)
        }
        return false
      }
      // 新文件落盘后再清理同一位置的旧文件与旧路径记录。
      if (previous && previous.url && previous.url !== slot.url) {
        const previousSlotKey = md5(JSON.stringify([slot.kind, slot.path, previous.url]))
        await remove(previous.key || imageKey(key, id, previousSlotKey))
        await remove(legacyImageKey(key, id, previousSlotKey))
      }
      if (previous?.path && previous.path !== image) await removeSavedFile(previous.path)
      // 文件保存及路径写入都成功后才记录 URL,失败时下次仍会重试。
      urls[slotName] = { url: slot.url, path: image, key: target }
      urlsChanged = true
      return true
    }))
  // 接口已删除的图片位置不再保留文件,避免长期切换品牌后缓存只增不减。
  await Promise.all(Object.keys(urls).filter(slotName => !activeSlotNames.has(slotName)).map(async slotName => {
    const obsolete = urls[slotName]
    if (obsolete?.key) await remove(obsolete.key)
    if (obsolete?.path) await removeSavedFile(obsolete.path)
    delete urls[slotName]
    urlsChanged = true
  }))
  if (urlsChanged && isCurrent()) {
    try {
      await write(urlKey(key), urls, isCurrent)
    } catch (error) {
      console.warn('素材图片 URL 记录写入失败', key)
    }
  }
  if (isCurrent() && results.every(Boolean)) {
    // 图片全部落盘后才能结束迁移,基础缓存写入成功不代表离线图片已就绪。
    await Promise.all([
      remove(key.replace(SOURCE_PREFIX, 'source_')),
      remove(legacyUrlKey(key))
    ])
  }
}

module.exports = { getSourceKey, getNetworkStatus, readSourceCache, hydrateSourceImages, clearImageMemory, saveSourceCache, cacheMaterialImages }