mainPackageSlimming.test.mjs 14.9 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
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import {
  existsSync,
  mkdtempSync,
  mkdirSync,
  readFileSync,
  readdirSync,
  rmSync,
  writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { parse } from '@babel/parser'

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const require = createRequire(import.meta.url)

const COMPONENT_TARGETS = {
  Goods: ['tabWorkOrder'],
  Qrbox: ['tabWorkOrder'],
  SkuGoods: ['tabWorkOrder', 'packageEquity'],
  DateSelect: ['tabWorkOrder', 'packageEquity'],
  'Merchant-Seles': ['tabWorkOrder', 'packageEquity'],
  CustomerInfo: ['tabWorkOrder', 'packageEquity', 'packageUsedCar'],
  CarBrands: ['tabWorkOrder', 'packageEquity'],
  InventoryInfo: ['tabWorkOrder', 'tabRepairOrder'],
  SelectInvoiceModal: ['tabWorkOrder', 'packageEquity'],
  areaOperationsModal: ['tabWorkOrder', 'packageEquity'],
  storePicker: ['packageDynamicForm', 'tabOperating'],
  CustomTabBar: [
    'packageCrowdFunding',
    'packageEquity',
    'packageUsedCar',
    'subvehicleConversion'
  ],
  TabMine: [
    'packageCrowdFunding',
    'packageEquity',
    'packageUsedCar',
    'subvehicleConversion'
  ]
}

const PRODUCTION_ROOTS = [
  'app.json',
  'pages',
  'tabIndex',
  'components',
  'api',
  'store',
  'router',
  'packageCrowdFunding',
  'packageDynamicForm',
  'packageEquity',
  'packageEquityAI',
  'packageStudyCenter',
  'packageUsedCar',
  'subvehicleConversion',
  'tabDate',
  'tabMine',
  'tabOperating',
  'tabRepairOrder',
  'tabWorkOrder',
  'integration'
]

const QR_CONSUMERS = {
  packageCrowdFunding: 'packageCrowdFunding/pages/activityPage/activityPay/activityPay.js',
  packageEquity: 'packageEquity/pages/carQuotation/CarQuotationPay/CarQuotationPay.js',
  subvehicleConversion:
    'subvehicleConversion/pages/orderPage/supplementaryOrderPay/supplementaryOrderPay.js',
  tabWorkOrder: 'tabWorkOrder/components/OrderPopup/OrderPopup.js'
}

const SUBPACKAGE_ONLY_ROOT_UTILS = {
  'orderSubOrderExtras.js': [
    'packageEquity/utils/orderSubOrderExtras.js',
    'tabWorkOrder/utils/orderSubOrderExtras.js'
  ],
  'tabRefreshService.js': [
    'packageCrowdFunding/services/tabRefreshService.js',
    'packageEquity/services/tabRefreshService.js',
    'packageUsedCar/services/tabRefreshService.js',
    'subvehicleConversion/services/tabRefreshService.js'
  ]
}

const ROP_METHODS = [
  'dj.api.smartcarlife.weapp.waitinputorder.union.count',
  'dj.api.smartcarlife.abnormalFlowDeclaration.checkShopLock',
  'dj.api.smartcarlife.weapp.waitinputorder.union.page',
  'dj.api.smartcarlife.abnormalFlowDeclaration.page',
  'dj.api.smartcarlife.abnormalFlowDeclaration.submit',
  'dj.api.smartcarlife.abnormalFlowDeclaration.detail'
]

/**
 * Recursively lists files below a path in deterministic order.
 * @param {string} entryPath Absolute file or directory path.
 * @returns {string[]} Absolute file paths.
 */
function listFiles(entryPath) {
  if (!existsSync(entryPath)) return []
  const stats = require('node:fs').statSync(entryPath)
  if (stats.isFile()) return [entryPath]
  return readdirSync(entryPath, { withFileTypes: true })
    .sort((left, right) => left.name.localeCompare(right.name))
    .flatMap(entry => listFiles(path.join(entryPath, entry.name)))
}

/**
 * Parses a JavaScript module for dependency-boundary assertions.
 * @param {string} relativePath Repository-relative path.
 * @returns {import('@babel/types').File} Babel AST.
 */
function parseModule(relativePath) {
  return parse(readFileSync(path.join(projectRoot, relativePath), 'utf8'), {
    sourceType: 'module',
    plugins: ['optionalChaining', 'nullishCoalescingOperator']
  })
}

/**
 * Returns static import sources from a parsed module.
 * @param {import('@babel/types').File} ast Babel AST.
 * @returns {string[]} Import source values.
 */
function collectImports(ast) {
  return ast.program.body
    .filter(node => node.type === 'ImportDeclaration')
    .map(node => node.source.value)
}

/**
 * Resolves a mini-program component declaration to a repository-relative path.
 * @param {string} jsonPath Absolute JSON path containing the declaration.
 * @param {string} componentPath usingComponents value.
 * @returns {string} Normalized repository-relative path.
 */
function resolveComponentPath(jsonPath, componentPath) {
  const absolute = componentPath.startsWith('/')
    ? path.resolve(projectRoot, componentPath.slice(1))
    : path.resolve(path.dirname(jsonPath), componentPath)
  return path.relative(projectRoot, absolute).replaceAll('\\', '/')
}

test('upload package excludes developer config and canonical generation sources', () => {
  const config = JSON.parse(readFileSync(path.join(projectRoot, 'project.config.json'), 'utf8'))
  const ignored = new Set((config.packOptions?.ignore || []).map(entry => entry.value))

  for (const expected of [
    'project.config.json',
    'shared-subpackage-components',
    'shared-subpackage-assets'
  ]) {
    assert.ok(ignored.has(expected), `${expected} must be excluded from upload`)
  }
})

test('abnormal-flow production API has no mock dependency and preserves all ROP methods', () => {
  const ast = parseModule('api/abnormalFlowDeclaration.js')
  const imports = collectImports(ast)
  assert.equal(
    imports.some(source => source.includes('abnormalFlowDeclaration.mock')),
    false,
    'production API must not statically load abnormal-flow mock data'
  )

  const source = readFileSync(path.join(projectRoot, 'api/abnormalFlowDeclaration.js'), 'utf8')
  for (const method of ROP_METHODS) {
    assert.equal(source.split(method).length - 1, 1, `${method} must remain wired exactly once`)
  }
})

test('root runtime no longer owns the QR implementation', () => {
  const ast = parseModule('utils/utils_wx.js')
  const source = readFileSync(path.join(projectRoot, 'utils/utils_wx.js'), 'utf8')
  assert.equal(
    collectImports(ast).some(source => source.includes('wxqrcode')),
    false,
    'global wx utilities must not pull QR generation into main'
  )
  assert.equal(
    existsSync(path.join(projectRoot, 'utils/lib/wxqrcode.js')),
    false,
    'root QR implementation must move out of the runtime main package'
  )
  assert.doesNotMatch(source, /handleCopy/, 'global wx utilities must not expose QR helpers')
})

test('subpackage-only utilities are generated inside every consuming package', () => {
  for (const [fileName, packageCopies] of Object.entries(SUBPACKAGE_ONLY_ROOT_UTILS)) {
    assert.equal(
      existsSync(path.join(projectRoot, 'utils', fileName)),
      false,
      `${fileName} must not remain in the runtime main package`
    )
    for (const packageCopy of packageCopies) {
      assert.ok(existsSync(path.join(projectRoot, packageCopy)), `${packageCopy} must exist`)
    }
  }
})

test('main-package JS boundary check detects and rejects subpackage-only root imports', async t => {
  const checkerPath = path.join(projectRoot, 'scripts/check-main-package-js-usage.mjs')
  const { findSubpackageOnlyRootJavaScriptImports } = await import(
    pathToFileURL(checkerPath).href
  )
  const fixtureRoot = mkdtempSync(path.join(tmpdir(), 'main-package-js-boundary-'))
  t.after(() => rmSync(fixtureRoot, { recursive: true, force: true }))

  for (const directory of ['pages/home', 'feature/pages/detail', 'utils']) {
    mkdirSync(path.join(fixtureRoot, directory), { recursive: true })
  }
  writeFileSync(
    path.join(fixtureRoot, 'app.json'),
    JSON.stringify({
      pages: ['pages/home/index'],
      subPackages: [{ root: 'feature', pages: ['pages/detail/index'] }]
    })
  )
  writeFileSync(
    path.join(fixtureRoot, 'project.config.json'),
    JSON.stringify({ packOptions: { ignore: [] } })
  )
  writeFileSync(
    path.join(fixtureRoot, 'pages/home/index.js'),
    "import '../../utils/mainShared.js'\n"
  )
  writeFileSync(
    path.join(fixtureRoot, 'feature/pages/detail/index.js'),
    "import '../../../utils/mainShared.js'\nimport '../../../utils/subpackageOnly.js'\n"
  )
  writeFileSync(path.join(fixtureRoot, 'utils/mainShared.js'), 'export const shared = true\n')
  writeFileSync(
    path.join(fixtureRoot, 'utils/subpackageOnly.js'),
    'export const subpackageOnly = true\n'
  )

  const fixtureViolations = findSubpackageOnlyRootJavaScriptImports({
    projectRoot: fixtureRoot
  })
  assert.deepEqual(
    fixtureViolations.map(item => item.target),
    ['utils/subpackageOnly.js']
  )

  const repositoryViolations = findSubpackageOnlyRootJavaScriptImports({ projectRoot })
  assert.deepEqual(
    repositoryViolations,
    [],
    `subpackage-only root JS imports remain:\n${repositoryViolations
      .map(item => `${item.target} <- ${item.importers.join(', ')}`)
      .join('\n')}`
  )
})

test('every direct QR consumer resolves to a file inside its own subpackage', () => {
  for (const [packageRoot, consumerPath] of Object.entries(QR_CONSUMERS)) {
    const imports = collectImports(parseModule(consumerPath))
    const qrImport = imports.find(source => source.includes('wxqrcode'))
    assert.ok(qrImport, `${consumerPath} must import a QR implementation`)

    const absoluteImport = qrImport.startsWith('~/')
      ? path.resolve(projectRoot, qrImport.slice(2))
      : path.resolve(projectRoot, path.dirname(consumerPath), qrImport)
    const relativeImport = path.relative(projectRoot, absoluteImport).replaceAll('\\', '/')
    assert.ok(
      relativeImport.startsWith(`${packageRoot}/`),
      `${consumerPath} must not import QR code from another package`
    )
    assert.ok(
      existsSync(absoluteImport) || existsSync(`${absoluteImport}.js`),
      `${relativeImport} must exist`
    )
  }
})

test('canonical QR implementation preserves the generated image contract', () => {
  const canonicalPath = path.join(
    projectRoot,
    'shared-subpackage-assets/utils/lib/wxqrcode.js'
  )
  assert.ok(existsSync(canonicalPath), 'canonical QR implementation must exist')
  const qrcode = require(canonicalPath)
  const result = qrcode.createQrCodeImg('MAIN_PACKAGE_SLIMMING_QR_TEST', { size: 160 })
  assert.match(result, /^data:image\/png;base64,/)
})

test('quotation QR service uses the package-local implementation', async () => {
  const servicePath = path.join(projectRoot, 'packageEquity/services/qrCode.js')
  const { handleCopy } = await import(pathToFileURL(servicePath).href)
  assert.match(await handleCopy('MAIN_PACKAGE_SLIMMING_SERVICE_TEST'), /^data:image\/png;base64,/)

  const pagePath = 'packageEquity/pages/carQuotation/schemeConfirmation/schemeConfirmation.js'
  const source = readFileSync(path.join(projectRoot, pagePath), 'utf8')
  assert.ok(
    collectImports(parseModule(pagePath)).includes('~/packageEquity/services/qrCode.js'),
    'quotation confirmation page must import the package-local QR service'
  )
  assert.doesNotMatch(source, /wx\.\$util\s*\.\s*handleCopy/)
})

test('subpackage component consumers do not resolve to migrated root components', () => {
  const targetNames = new Set(Object.keys(COMPONENT_TARGETS))
  const violations = []

  for (const productionRoot of PRODUCTION_ROOTS) {
    for (const file of listFiles(path.join(projectRoot, productionRoot))) {
      if (path.extname(file) !== '.json') continue
      const relativeFile = path.relative(projectRoot, file).replaceAll('\\', '/')
      if (/(^|\/)(tests?|docs)\//.test(relativeFile)) continue
      let json
      try {
        json = JSON.parse(readFileSync(file, 'utf8'))
      } catch {
        continue
      }
      for (const componentPath of Object.values(json.usingComponents || {})) {
        if (typeof componentPath !== 'string') continue
        const resolved = resolveComponentPath(file, componentPath)
        const match = /^components\/([^/]+)\//.exec(resolved)
        if (match && targetNames.has(match[1])) {
          violations.push(`${relativeFile} -> ${componentPath}`)
        }
      }
    }
  }

  assert.deepEqual(violations, [], `root component references remain:\n${violations.join('\n')}`)
})

test('used-car evaluation steps register only components rendered by their own templates', () => {
  for (const stepPath of [
    'packageUsedCar/pages/evaluationForm/components/FirstStep/FirstStep.json',
    'packageUsedCar/pages/evaluationForm/components/SecondStep/SecondStep.json'
  ]) {
    const config = JSON.parse(readFileSync(path.join(projectRoot, stepPath), 'utf8'))
    assert.deepEqual(
      Object.keys(config.usingComponents || {}).sort(),
      ['gl-form', 'van-dialog'],
      `${stepPath} must not register page-owned or unused popup components`
    )
  }
})

test('used-car package does not ship the unused CarBrands generated copy', () => {
  assert.equal(
    existsSync(path.join(projectRoot, 'packageUsedCar/components/CarBrands')),
    false,
    'packageUsedCar must not include an unreferenced CarBrands component'
  )
})

test('canonical components and every declared generated target exist', () => {
  for (const [componentName, packageRoots] of Object.entries(COMPONENT_TARGETS)) {
    assert.ok(
      existsSync(path.join(projectRoot, 'shared-subpackage-components', componentName)),
      `${componentName} canonical source must exist`
    )
    assert.equal(
      existsSync(path.join(projectRoot, 'components', componentName)),
      false,
      `${componentName} must not remain in the runtime main package`
    )
    for (const packageRoot of packageRoots) {
      assert.ok(
        existsSync(path.join(projectRoot, packageRoot, 'components', componentName)),
        `${packageRoot}/components/${componentName} must exist`
      )
    }
  }
})

test('subpackage asset synchronizer repairs copies and detects later drift', async t => {
  const synchronizerPath = path.join(projectRoot, 'scripts/sync-subpackage-assets.mjs')
  assert.ok(existsSync(synchronizerPath), 'subpackage asset synchronizer must exist')
  const { syncSubpackageAssets } = await import(pathToFileURL(synchronizerPath).href)

  const fixtureRoot = mkdtempSync(path.join(tmpdir(), 'subpackage-assets-'))
  t.after(() => rmSync(fixtureRoot, { recursive: true, force: true }))
  mkdirSync(path.join(fixtureRoot, 'source/nested'), { recursive: true })
  mkdirSync(path.join(fixtureRoot, 'target'), { recursive: true })
  writeFileSync(path.join(fixtureRoot, 'source/nested/value.txt'), 'canonical')
  writeFileSync(path.join(fixtureRoot, 'target/stale.txt'), 'stale')

  const entries = [{ source: 'source', targets: ['target'] }]
  await assert.rejects(
    syncSubpackageAssets({ projectRoot: fixtureRoot, entries, checkOnly: true }),
    /out of sync/
  )

  await syncSubpackageAssets({ projectRoot: fixtureRoot, entries })
  assert.equal(readFileSync(path.join(fixtureRoot, 'target/nested/value.txt'), 'utf8'), 'canonical')
  assert.equal(existsSync(path.join(fixtureRoot, 'target/stale.txt')), false)
  await syncSubpackageAssets({ projectRoot: fixtureRoot, entries, checkOnly: true })

  writeFileSync(path.join(fixtureRoot, 'target/nested/value.txt'), 'drift')
  await assert.rejects(
    syncSubpackageAssets({ projectRoot: fixtureRoot, entries, checkOnly: true }),
    /out of sync/
  )
})