async function writeReplacements()

in script/build.ts [188:257]


async function writeReplacements(
  inputFilename: string,
  outputDir: string,
  collection: ModeCollection,
  // Function to validate a variable (e.g. deprecated variable or removed variable).
  // Returns an array of error messages. If the returned array is empty, the variable is valid.
  validateVar: (variable: string, collection: ModeCollection, inputFile: string) => any[]
) {
  const inputFile = path.join(dataDir, collection.type, inputFilename)

  // Do nothing if deprecated file doesn't exist
  if (!fs.existsSync(inputFile)) {
    return
  }

  try {
    // Parse input file
    const replacementMap = JSON.parse(fs.readFileSync(inputFile, 'utf8'))

    // Validations
    const errors = []
    for (const [original, replacement] of Object.entries(replacementMap)) {
      errors.push(...validateVar(original, collection, inputFile))

      // We expect `replacement` to be a variable name, an array of variable names, or null
      forEachReplacementVar(replacement, replacementVar => {
        // Assert that replacement variable is a string
        if (typeof replacementVar !== 'string') {
          errors.push(
            chalk`Cannot replace {bold "${original}"} with invalid variable {bold.red ${JSON.stringify(
              replacementVar
            )}} in {bold ${inputFile}}`
          )
          return
        }

        // Assert that replacement variable exists
        if (!existsInCollection(collection, replacementVar)) {
          errors.push(
            chalk`Cannot replace {bold "${original}"} with undefined variable {bold.red ${JSON.stringify(
              replacementVar
            )}} in {bold ${inputFile}}`
          )
          return
        }

        // Assert that replacement variable is not deprecated
        if (Object.keys(replacementMap).includes(replacementVar)) {
          errors.push(
            chalk`Cannot replace {bold "${original}"} with deprecated variable {bold.red ${JSON.stringify(
              replacementVar
            )}} in {bold ${inputFile}}`
          )
          return
        }
      })
    }

    if (errors.length === 0) {
      // Write replacements
      await mkdirp(outputDir)
      fs.writeFileSync(path.join(outputDir, `${collection.type}.json`), JSON.stringify(replacementMap, null, '  '))
    } else {
      throw new Error(errors.join('\n'))
    }
  } catch (error) {
    logError(error.message)
    process.exit(1)
  }
}