UNPKG

1.24 kBJavaScriptView Raw
1const { readFile } = require('fs')
2const { promisify } = require('util')
3
4const pathExists = require('path-exists')
5const { parse: loadToml } = require('toml')
6
7const { splitResults } = require('./results')
8
9const pReadFile = promisify(readFile)
10
11// Parse `redirects` field in "netlify.toml" to an array of objects.
12// This field is already an array of objects so it only validates and
13// normalizes it.
14const parseConfigRedirects = async function (netlifyConfigPath) {
15 if (!(await pathExists(netlifyConfigPath))) {
16 return splitResults([])
17 }
18
19 const results = await parseConfig(netlifyConfigPath)
20 return splitResults(results)
21}
22
23// Load the configuration file and parse it (TOML)
24const parseConfig = async function (configPath) {
25 try {
26 const configString = await pReadFile(configPath, 'utf8')
27 const config = loadToml(configString)
28 // Convert `null` prototype objects to normal plain objects
29 const { redirects = [] } = JSON.parse(JSON.stringify(config))
30 if (!Array.isArray(redirects)) {
31 throw new TypeError(`"redirects" must be an array`)
32 }
33 return redirects
34 } catch (error) {
35 return [new Error(`Could not parse configuration file: ${error}`)]
36 }
37}
38
39module.exports = { parseConfigRedirects }