/
to-disk.js
214 lines (181 loc) · 7.26 KB
/
to-disk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
const path = require('path')
const fs = require('fs-extra')
const glob = require('glob-promise')
const {get, isEmpty, merge} = require('lodash')
const {asyncForEach} = require('../../utils/helpers')
const Config = require('../config')
const Tailwind = require('../tailwindcss')
const Plaintext = require('../plaintext')
const render = require('./to-string')
module.exports = async (env, spinner, config) => {
process.env.NODE_ENV = env || 'local'
if (isEmpty(config)) {
config = await Config.getMerged(env).catch(error => {
spinner.fail('Build failed')
throw error
})
}
const buildTemplates = get(config, 'build.templates')
const templatesConfig = Array.isArray(buildTemplates) ? buildTemplates : [buildTemplates]
const parsed = []
let files = []
const css = (typeof get(config, 'build.tailwind.compiled') === 'string')
? config.build.tailwind.compiled
: await Tailwind.compile('', '', {}, config)
// Parse each template config object
await asyncForEach(templatesConfig, async templateConfig => {
const outputDir = get(templateConfig, 'destination.path', `build_${env}`)
await fs.remove(outputDir)
/**
* Get all files in the template config's source directory
* Supports `source` defined as:
* - string
* - array of strings
* - function that returns either of the above
*
* */
const templateSource = []
const templateTypeErrorMessage = 'Invalid template source: expected string or array of strings, got '
if (typeof templateConfig.source === 'function') {
const sources = templateConfig.source(config)
if (Array.isArray(sources)) {
templateSource.push(...sources)
} else if (typeof sources === 'string') {
templateSource.push(sources)
} else {
throw new TypeError(templateTypeErrorMessage + typeof sources)
}
} else {
if (Array.isArray(templateConfig.source)) {
templateSource.push(...templateConfig.source)
} else if (typeof templateConfig.source === 'string') {
templateSource.push(templateConfig.source)
} else {
throw new TypeError(templateTypeErrorMessage + typeof templateConfig.source)
}
}
// Parse each template source
await asyncForEach(templateSource, async source => {
/**
* Copy single-file sources correctly
* If `src` is a file, `dest` cannot be a directory
* https://github.com/jprichardson/node-fs-extra/issues/323
*/
const out = fs.lstatSync(source).isFile() ? `${outputDir}/${path.basename(source)}` : outputDir
await fs
.copy(source, out)
.then(async () => {
const extensions = Array.isArray(templateConfig.filetypes)
? templateConfig.filetypes.join('|')
: templateConfig.filetypes || get(templateConfig, 'filetypes', 'html')
const templates = await glob(`${outputDir}/**/*.+(${extensions})`)
if (templates.length === 0) {
spinner.warn(`Error: no files with the .${extensions} extension found in ${templateConfig.source}`)
return
}
if (config.events && typeof config.events.beforeCreate === 'function') {
await config.events.beforeCreate(config)
}
await asyncForEach(templates, async file => {
config.build.current = {
path: path.parse(file)
}
const html = await fs.readFile(file, 'utf8')
try {
const compiled = await render(html, {
useFileConfig: true,
maizzle: {
...config,
env
},
tailwind: {
compiled: css
},
...config.events
})
const destination = config.permalink || file
/**
* Generate plaintext
*
* We do this first so that we can remove the <plaintext>
* tags from the markup before outputting the file.
*/
// Check if plaintext: true globally, fallback to template's front matter
const plaintextConfig = get(templateConfig, 'plaintext', get(compiled.config, 'plaintext', false))
const plaintextPath = get(plaintextConfig, 'destination.path', config.permalink || file)
if (Boolean(plaintextConfig) || !isEmpty(plaintextConfig)) {
await Plaintext
.generate(
compiled.html,
plaintextPath,
merge(plaintextConfig, {filepath: file})
)
.then(async ({html, plaintext, destination}) => {
compiled.html = html
await fs.outputFile(destination, plaintext)
})
}
/**
* Output file
*/
const parts = path.parse(destination)
const extension = get(templateConfig, 'destination.extension', 'html')
const finalDestination = `${parts.dir}/${parts.name}.${extension}`
await fs.outputFile(finalDestination, compiled.html)
/**
* Remove original file if its path is different
* from the final destination path.
*
* This ensures non-HTML files do not pollute
* the build destination folder.
*/
if (finalDestination !== file) {
await fs.remove(file)
}
// Keep track of handled files
files.push(file)
parsed.push(file)
} catch (error) {
switch (config.build.fail) {
case 'silent':
spinner.warn(`Failed to compile template: ${path.basename(file)}`)
break
case 'verbose':
spinner.warn(`Failed to compile template: ${path.basename(file)}`)
console.error(error)
break
default:
spinner.fail(`Failed to compile template: ${path.basename(file)}`)
throw error
}
}
})
const assets = {source: '', destination: 'assets', ...get(templateConfig, 'assets')}
if (Array.isArray(assets.source)) {
await asyncForEach(assets.source, async source => {
if (fs.existsSync(source)) {
await fs.copy(source, path.join(templateConfig.destination.path, assets.destination)).catch(error => spinner.warn(error.message))
}
})
} else {
if (fs.existsSync(assets.source)) {
await fs.copy(assets.source, path.join(templateConfig.destination.path, assets.destination)).catch(error => spinner.warn(error.message))
}
}
await glob(path.join(templateConfig.destination.path, '/**/*.*'))
.then(contents => {
files = [...new Set([...files, ...contents])]
})
})
.catch(error => spinner.warn(error.message))
})
})
if (config.events && typeof config.events.afterBuild === 'function') {
await config.events.afterBuild(files)
}
return {
files,
parsed,
css
}
}