projectRopCredentials.mjs 3.42 KB
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const require = createRequire(import.meta.url)
const repositoryRoot = fileURLToPath(new URL('../../../', import.meta.url))
const TEST_ENV_INDEX = 2
const TEST_DOMAIN = 'https://dj.test.glsx.com.cn'

const asDataModule = (source, label) =>
  `data:text/javascript;base64,${Buffer.from(
    `${source}\n//# sourceURL=${label}\n`,
    'utf8'
  ).toString('base64')}`

const replaceRequired = (source, pattern, replacement, label) => {
  if (!pattern.test(source)) {
    throw new Error(`Unable to load project ROP credentials: missing ${label}`)
  }
  return source.replace(pattern, replacement)
}

async function loadTestEnvironment() {
  const sourcePath = path.join(repositoryRoot, 'utils/request/environment.js')
  let source = await readFile(sourcePath, 'utf8')
  source = replaceRequired(
    source,
    /import\s+\{\s*envIndex\s*\}\s+from\s+['"]~\/config['"];?/,
    `const envIndex = ${TEST_ENV_INDEX}`,
    'environment selector import'
  )
  source = replaceRequired(
    source,
    /module\.exports\s*=/,
    'export default',
    'environment export'
  )
  const module = await import(asDataModule(source, 'order-lifecycle-environment.js'))
  if (module.default?.domain?.dj !== TEST_DOMAIN) {
    throw new Error('Project credential adapter did not select the test environment')
  }
  return module.default
}

async function loadProjectHttpModule(environment) {
  const contextKey = `__orderLifecycleRopContext_${Date.now()}_${Math.random()
    .toString(36)
    .slice(2)}`
  globalThis[contextKey] = {
    environment,
    sha1: require(path.join(repositoryRoot, 'utils/lib/sha1.js')),
    qs: require(path.join(repositoryRoot, 'utils/lib/qs.js'))
  }

  try {
    const sourcePath = path.join(repositoryRoot, 'utils/request/http.js')
    let source = await readFile(sourcePath, 'utf8')
    source = replaceRequired(
      source,
      /import\s+environment\s+from\s+['"]\.\/environment\.js['"];?/,
      `const environment = globalThis[${JSON.stringify(contextKey)}].environment`,
      'environment import'
    )
    source = replaceRequired(
      source,
      /import\s+sha1\s+from\s+['"]~\/utils\/lib\/sha1['"];?/,
      `const sha1 = globalThis[${JSON.stringify(contextKey)}].sha1`,
      'sha1 import'
    )
    source = replaceRequired(
      source,
      /import\s+qs\s+from\s+['"]~\/utils\/lib\/qs['"];?/,
      `const qs = globalThis[${JSON.stringify(contextKey)}].qs`,
      'qs import'
    )
    source = replaceRequired(
      source,
      /module\.exports\s*=/,
      'export default',
      'HTTP module export'
    )
    const module = await import(asDataModule(source, `order-lifecycle-http-${contextKey}.js`))
    return module.default
  } finally {
    delete globalThis[contextKey]
  }
}

let credentialPromise

export async function loadProjectRopCredentials() {
  credentialPromise ??= (async () => {
    const environment = await loadTestEnvironment()
    const http = await loadProjectHttpModule(environment)
    const selected = http?.secretKey?.dj
    if (!selected?.appKey || !selected?.secret || typeof http?.sign !== 'function') {
      throw new Error('Project test ROP credentials are incomplete')
    }
    return {
      appKey: selected.appKey,
      secret: selected.secret,
      sign: http.sign
    }
  })()

  const credentials = await credentialPromise
  return { ...credentials }
}