-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathsite-builder.ts
346 lines (291 loc) · 9.02 KB
/
site-builder.ts
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { copyFile, mkdir, rm, unlink, writeFile } from 'fs/promises'
import os from 'os'
import path from 'path'
import process from 'process'
import { inspect } from 'util'
import type { OnPreBuild, OnBuild, OnPostBuild, OnSuccess } from '@netlify/build'
import type { Context, Handler } from '@netlify/functions'
import type { EdgeFunction } from '@netlify/edge-functions'
import slugify from '@sindresorhus/slugify'
import execa from 'execa'
import serializeJS from 'serialize-javascript'
import tempDirectory from 'temp-dir'
import tomlify from 'tomlify-j0.4'
import { v4 as uuidv4 } from 'uuid'
import type { TestContext } from 'vitest'
const ensureDir = (directory: string) => mkdir(directory, { recursive: true })
type Task = () => Promise<unknown>
export class SiteBuilder {
tasks: Task[] = []
constructor(public readonly directory: string) {}
ensureDirectoryExists(directory: string) {
this.tasks.push(async () => ensureDir(directory))
return this
}
withNetlifyToml({ config, pathPrefix = '' }: { config: unknown; pathPrefix?: string | undefined }) {
const dest = path.join(this.directory, pathPrefix, 'netlify.toml')
const content = tomlify.toToml(config, {
replace: (_, val) => {
if (typeof val === 'number' && Number.isInteger(val)) {
// Strip off `.0` from integers that tomlify normally generates
return String(Math.round(val))
}
// Output normal value
return false
},
space: 2,
})
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withStateFile({ siteId = '' }: { siteId?: string }) {
const dest = path.join(this.directory, '.netlify', 'state.json')
this.tasks.push(async () => {
const content = `{ "siteId" : "${siteId}" }`
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withPackageJson({ packageJson, pathPrefix = '' }: { packageJson: any; pathPrefix?: string }) {
const dest = path.join(this.directory, pathPrefix, 'package.json')
this.tasks.push(async () => {
const content = JSON.stringify(packageJson, null, 2)
await ensureDir(path.dirname(dest))
await writeFile(dest, `${content}\n`)
})
return this
}
withFunction({
config,
esm = false,
handler,
path: filePath,
pathPrefix = 'functions',
runtimeAPIVersion,
}: {
config?: object
esm?: boolean
handler: Handler | ((req: Request, context: Context) => Response | Promise<Response>) | string
path: string
pathPrefix?: string
runtimeAPIVersion?: number
}) {
const dest = path.join(this.directory, pathPrefix, filePath)
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
let file = ''
if (runtimeAPIVersion === 2) {
file = `const handler = ${handler.toString()}; export default handler;`
if (config) {
file += `export const config = ${inspect(config)};`
}
} else {
file = esm ? `export const handler = ${handler.toString()}` : `exports.handler = ${handler.toString()}`
}
await writeFile(dest, file)
})
return this
}
withEdgeFunction({
config,
handler,
imports = '',
name = 'function',
path: edgeFunctionsDirectory = 'netlify/edge-functions',
pathPrefix = '',
}: {
config?: any
handler: EdgeFunction | string
imports?: string
name?: string
path?: string
pathPrefix?: string
}) {
const dest = path.join(this.directory, pathPrefix, edgeFunctionsDirectory, `${name}.js`)
this.tasks.push(async () => {
let content = `${imports};`
content += typeof handler === 'string' ? handler : `export default ${handler.toString()}`
if (config) {
content += `;export const config = ${JSON.stringify(config)}`
}
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withRedirectsFile({ pathPrefix = '', redirects = [] }: { pathPrefix?: string; redirects?: any[] }) {
const dest = path.join(this.directory, pathPrefix, '_redirects')
this.tasks.push(async () => {
const content = redirects
.map(({ condition = '', from, status, to }) => [from, to, status, condition].filter(Boolean).join(' '))
.join(os.EOL)
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withHeadersFile({
headers = [],
pathPrefix = '',
}: {
headers?: { headers: string[]; path: string }[]
pathPrefix?: string
}) {
const dest = path.join(this.directory, pathPrefix, '_headers')
this.tasks.push(async () => {
const content = headers
.map(
({ headers: headersValues, path: headerPath }) =>
`${headerPath}${os.EOL}${headersValues.map((header) => ` ${header}`).join(os.EOL)}`,
)
.join(os.EOL)
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withContentFile({ content, path: filePath }: { content: string; path: string }) {
const dest = path.join(this.directory, filePath)
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
await writeFile(dest, content)
})
return this
}
withMockPackage({ content, name }: { name: string; content: string }) {
const dir = path.join(this.directory, 'node_modules', name)
this.tasks.push(async () => {
await ensureDir(dir)
await writeFile(path.join(dir, 'index.js'), content)
await writeFile(path.join(dir, 'package.json'), '{}')
await writeFile(path.join(dir, 'manifest.yml'), `name: '${name}'`)
})
return this
}
withCopiedFile({ path: filePath, src }: { path: string; src: string }) {
const dest = path.join(this.directory, filePath)
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
await copyFile(src, dest)
})
return this
}
withContentFiles(files: { content: string; path: string }[]) {
files.forEach((file) => {
this.withContentFile(file)
})
return this
}
withEnvFile({
env = {},
path: filePath = '.env',
pathPrefix = '',
}: {
env?: any
path?: string
pathPrefix?: string
}) {
const dest = path.join(this.directory, pathPrefix, filePath)
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
await writeFile(
dest,
Object.entries(env)
.map(([key, value]) => `${key}=${value}`)
.join(os.EOL),
)
})
return this
}
withGit({ repoUrl = '[email protected]:owner/repo.git' }: { repoUrl?: string } = {}) {
this.tasks.push(async () => {
await execa('git', ['init', '--initial-branch', 'main'], { cwd: this.directory })
await execa('git', ['remote', 'add', 'origin', repoUrl], { cwd: this.directory })
})
return this
}
withoutFile({ path: filePath }: { path: string }) {
const dest = path.join(this.directory, filePath)
this.tasks.push(async () => {
await unlink(dest)
})
return this
}
withBuildPlugin({
name,
pathPrefix = 'plugins',
plugin,
}: {
name: string
pathPrefix?: string
plugin: {
onBuild?: OnBuild | undefined
onDev?: OnBuild | undefined
onPostBuild?: OnPostBuild | undefined
onPreBuild?: OnPreBuild | undefined
onPreDev?: OnPreBuild | undefined
onSuccess?: OnSuccess | undefined
}
}) {
const dest = path.join(this.directory, pathPrefix, `${name}.js`)
this.tasks.push(async () => {
await ensureDir(path.dirname(dest))
await Promise.all([
writeFile(path.join(this.directory, pathPrefix, 'manifest.yml'), `name: ${name}`),
writeFile(dest, `module.exports = ${serializeJS(plugin)}`),
])
})
return this
}
withCommand({ command }: { command: string[] }) {
this.tasks.push(async () => {
const [mainCommand, ...args] = command
await execa(mainCommand, args, { cwd: this.directory })
})
return this
}
async build() {
for (const task of this.tasks) {
await task()
}
this.tasks = []
return this
}
async cleanup() {
try {
await rm(this.directory, { force: true, recursive: true })
} catch (error) {
console.warn(error)
}
return this
}
}
export const createSiteBuilder = ({ siteName }: { siteName: string }) => {
const directory = path.join(
tempDirectory,
`netlify-cli-tests-${process.version}`,
`${process.pid}`,
uuidv4(),
siteName,
)
return new SiteBuilder(directory).ensureDirectoryExists(directory)
}
/**
* @param taskContext used to infer directory name from test name
*/
export async function withSiteBuilder<T>(
taskContext: TestContext,
testHandler: (builder: SiteBuilder) => Promise<T>,
): Promise<T> {
let builder: SiteBuilder | undefined
try {
builder = createSiteBuilder({ siteName: slugify(taskContext.task.name) })
return await testHandler(builder)
} finally {
if (builder) await builder.cleanup()
}
}