mainPackageImageCdnMigration.test.mjs 5.02 KB
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const imageExtensions = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.ico'])
const sourceExtensions = new Set(['.js', '.json', '.ts', '.wxml', '.wxs', '.wxss'])
const ignoredRoots = new Set([
  '.cloudbase',
  '.codex-tmp',
  '.cursor',
  '.git',
  'cdn-upload',
  'docs',
  'miniprogram_npm',
  'node_modules',
  'outputs',
  'scripts',
  'tests'
])
const expectedLocalImages = [
  'images/tab-date-active.png',
  'images/tab-date.png',
  'images/tab-home-active.png',
  'images/tab-home.png',
  'images/tab-mine-active.png',
  'images/tab-mine.png',
  'images/tab-order-active.png',
  'images/tab-order.png',
  'images/tab-repair-active.png',
  'images/tab-repair.png'
]

function walkFiles(directory) {
  return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
    const fullPath = path.join(directory, entry.name)
    return entry.isDirectory() ? walkFiles(fullPath) : [fullPath]
  })
}

function listMainPackageImages() {
  const appConfig = JSON.parse(fs.readFileSync(path.join(rootDir, 'app.json'), 'utf8'))
  const subpackageRoots = new Set(appConfig.subpackages.map(item => item.root))

  return walkFiles(rootDir)
    .map(file => path.relative(rootDir, file).split(path.sep).join('/'))
    .filter(relativePath => imageExtensions.has(path.extname(relativePath).toLowerCase()))
    .filter(relativePath => {
      const topLevel = relativePath.split('/')[0]
      return !ignoredRoots.has(topLevel) && !subpackageRoots.has(topLevel)
    })
    .sort()
}

function listDeletedMainPackageImageReferences() {
  const appConfig = JSON.parse(fs.readFileSync(path.join(rootDir, 'app.json'), 'utf8'))
  const subpackageRoots = new Set(appConfig.subpackages.map(item => item.root))
  const uploadedMainPackageImages = new Set(
    walkFiles(path.join(rootDir, 'cdn-upload'))
      .map(file => path.relative(path.join(rootDir, 'cdn-upload'), file).split(path.sep).join('/'))
      .filter(relativePath => imageExtensions.has(path.extname(relativePath).toLowerCase()))
      .filter(relativePath => !subpackageRoots.has(relativePath.split('/')[0]))
  )
  const imageReference = /(?:["'(=]\s*|url\(\s*)(?<asset>(?:\/|\.\.?\/)[^"'()\s{}<>]+?\.(?:png|jpe?g|gif|webp|svg|ico))/gi
  const references = []

  for (const file of walkFiles(rootDir)) {
    const sourceRelativePath = path.relative(rootDir, file).split(path.sep).join('/')
    const sourceTopLevel = sourceRelativePath.split('/')[0]
    if (ignoredRoots.has(sourceTopLevel) || !sourceExtensions.has(path.extname(file).toLowerCase())) {
      continue
    }

    const source = fs.readFileSync(file, 'utf8')
    for (const match of source.matchAll(imageReference)) {
      const asset = match.groups.asset.split(/[?#]/, 1)[0]
      const resolved = asset.startsWith('/')
        ? path.resolve(rootDir, `.${asset}`)
        : path.resolve(path.dirname(file), asset)
      const assetRelativePath = path.relative(rootDir, resolved).split(path.sep).join('/')
      const assetTopLevel = assetRelativePath.split('/')[0]

      if (
        assetRelativePath.startsWith('../') ||
        ignoredRoots.has(assetTopLevel) ||
        subpackageRoots.has(assetTopLevel) ||
        expectedLocalImages.includes(assetRelativePath) ||
        !uploadedMainPackageImages.has(assetRelativePath)
      ) {
        continue
      }

      references.push(`${sourceRelativePath}: ${asset}`)
    }
  }

  return references.sort()
}

function listMissingWxsDependencies(sourceRelativePath) {
  const sourcePath = path.join(rootDir, sourceRelativePath)
  const source = fs.readFileSync(sourcePath, 'utf8')
  const wxsReference = /<wxs\b[^>]*\bsrc=["'](?<dependency>[^"']+)["'][^>]*>/gi

  return [...source.matchAll(wxsReference)]
    .map(match => match.groups.dependency)
    .filter(dependency => {
      const resolved = dependency.startsWith('/')
        ? path.resolve(rootDir, `.${dependency}`)
        : path.resolve(path.dirname(sourcePath), dependency)
      return !fs.existsSync(resolved)
    })
}

describe('main package image CDN migration', () => {
  it('keeps only native TabBar images in the main package', () => {
    assert.deepEqual(listMainPackageImages(), expectedLocalImages)
  })

  it('does not force deleted local images into the upload package', () => {
    const projectConfig = JSON.parse(
      fs.readFileSync(path.join(rootDir, 'project.config.json'), 'utf8')
    )
    const includedPaths = projectConfig.packOptions.include.map(item => item.value)
    assert.ok(!includedPaths.includes('components/images/close.png'))
  })

  it('does not reference deleted main-package images through local paths', () => {
    assert.deepEqual(listDeletedMainPackageImageReferences(), [])
  })

  it('keeps work-order index WXS dependencies resolvable', () => {
    assert.deepEqual(
      listMissingWxsDependencies('pages/tabWorkOrder/pages/index/index.wxml'),
      []
    )
  })
})