UNPKG

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