loadMiniProgramApi.mjs 2.04 KB
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const repositoryRoot = fileURLToPath(new URL('../../../', import.meta.url))
const requestImportPattern =
  /import\s+api\s+from\s+['"]~\/utils\/request\/request\.js['"];?/
const abnormalFlowImportPattern =
  /import\s+\*\s+as\s+abnormalFlowApi\s+from\s+['"]\.\/abnormalFlowDeclaration\.js['"];?/
const exportsPattern = /module\.exports\s*=/

const replaceRequired = (source, pattern, replacement, label) => {
  if (!pattern.test(source)) {
    throw new Error(`Unable to transform mini-program API module: missing ${label}`)
  }
  return source.replace(pattern, replacement)
}

export async function loadMiniProgramApi(relativePath, requestSpy) {
  if (!requestSpy || typeof requestSpy.post !== 'function') {
    throw new TypeError('requestSpy.post must be a function')
  }

  const resolved = path.resolve(repositoryRoot, relativePath)
  const relative = path.relative(repositoryRoot, resolved)
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
    throw new Error(`API source must be inside repository: ${relativePath}`)
  }

  const spyKey = `__orderLifecycleApiSpy_${Date.now()}_${Math.random()
    .toString(36)
    .slice(2)}`
  let source = await readFile(resolved, 'utf8')
  source = replaceRequired(
    source,
    requestImportPattern,
    `const api = globalThis[${JSON.stringify(spyKey)}]`,
    'request import'
  )
  if (abnormalFlowImportPattern.test(source)) {
    source = source.replace(
      abnormalFlowImportPattern,
      'const abnormalFlowApi = Object.create(null)'
    )
  }
  source = replaceRequired(
    source,
    exportsPattern,
    'export default',
    'module.exports assignment'
  )
  source += `\n//# sourceURL=${relativePath.replaceAll('\\', '/')}?spy=${spyKey}\n`

  globalThis[spyKey] = requestSpy
  try {
    const encoded = Buffer.from(source, 'utf8').toString('base64')
    const module = await import(`data:text/javascript;base64,${encoded}`)
    return module.default
  } finally {
    delete globalThis[spyKey]
  }
}