-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathindex.js
648 lines (563 loc) · 21.3 KB
/
index.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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
const url = require('url')
const util = require('util')
const { URLSearchParams } = require('url')
const path = require('path')
const fs = require('fs')
const { flags } = require('@oclif/command')
const child_process = require('child_process')
const http = require('http')
const httpProxy = require('http-proxy')
const waitPort = require('wait-port')
const stripAnsiCc = require('strip-ansi-control-characters')
const which = require('which')
const chokidar = require('chokidar')
const debounce = require('lodash.debounce')
const { createProxyMiddleware } = require('http-proxy-middleware')
const cookie = require('cookie')
const get = require('lodash.get')
const isEmpty = require('lodash.isempty')
const { serveFunctions } = require('../../utils/serve-functions')
const { serverSettings } = require('../../utils/detect-server')
const { detectFunctionsBuilder } = require('../../utils/detect-functions-builder')
const Command = require('../../utils/command')
const chalk = require('chalk')
const jwtDecode = require('jwt-decode')
const open = require('open')
const contentType = require('content-type')
const { NETLIFYDEV, NETLIFYDEVLOG, NETLIFYDEVWARN, NETLIFYDEVERR } = require('../../utils/logo')
const boxen = require('boxen')
const { createTunnel, connectTunnel } = require('../../utils/live-tunnel')
const { createRewriter } = require('../../utils/rules-proxy')
const { onChanges } = require('../../utils/rules-proxy')
const { parseHeadersFile, objectForPath } = require('../../utils/headers')
const { getEnvSettings } = require('../../utils/env')
const { createStreamPromise } = require('../../utils/create-stream-promise')
const toReadableStream = require('to-readable-stream')
const stat = util.promisify(fs.stat)
function isInternal(url) {
return url.startsWith('/.netlify/')
}
function isFunction(functionsPort, url) {
return functionsPort && url.match(/^\/.netlify\/functions\/.+/)
}
function addonUrl(addonUrls, req) {
const m = req.url.match(/^\/.netlify\/([^\/]+)(\/.*)/) // eslint-disable-line no-useless-escape
const addonUrl = m && addonUrls[m[1]]
return addonUrl ? `${addonUrl}${m[2]}` : null
}
async function getStatic(pathname, publicFolder) {
const alternatives = [pathname, ...alternativePathsFor(pathname)].map(p => path.resolve(publicFolder, p.substr(1)))
for (const i in alternatives) {
const p = alternatives[i]
try {
const pathStats = await stat(p)
if (pathStats.isFile()) return '/' + path.relative(publicFolder, p)
} catch (err) {
// Ignore
}
}
return false
}
function isExternal(match) {
return match.to && match.to.match(/^https?:\/\//)
}
function isRedirect(match) {
return match.status && match.status >= 300 && match.status <= 400
}
function render404(publicFolder) {
const maybe404Page = path.resolve(publicFolder, '404.html')
if (fs.existsSync(maybe404Page)) return fs.readFileSync(maybe404Page)
return 'Not Found'
}
// Used as an optimization to avoid dual lookups for missing assets
const assetExtensionRegExp = /\.(html?|png|jpg|js|css|svg|gif|ico|woff|woff2)$/
function alternativePathsFor(url) {
const paths = []
if (url[url.length - 1] === '/') {
const end = url.length - 1
if (url !== '/') {
paths.push(url.slice(0, end) + '.html')
paths.push(url.slice(0, end) + '.htm')
}
paths.push(url + 'index.html')
paths.push(url + 'index.htm')
} else if (!url.match(assetExtensionRegExp)) {
paths.push(url + '.html')
paths.push(url + '.htm')
paths.push(url + '/index.html')
paths.push(url + '/index.htm')
}
return paths
}
function initializeProxy(port, distDir, projectDir) {
const proxy = httpProxy.createProxyServer({
selfHandleResponse: true,
target: {
host: 'localhost',
port,
},
})
const headersFiles = Array.from(new Set([path.resolve(projectDir, '_headers'), path.resolve(distDir, '_headers')]))
let headerRules = headersFiles.reduce((prev, curr) => Object.assign(prev, parseHeadersFile(curr)), {})
onChanges(headersFiles, () => {
console.log(
`${NETLIFYDEVLOG} Reloading headers files`,
headersFiles.filter(fs.existsSync).map(p => path.relative(projectDir, p))
)
headerRules = headersFiles.reduce((prev, curr) => Object.assign(prev, parseHeadersFile(curr)), {})
})
proxy.on('error', err => console.error('error while proxying request:', err.message))
proxy.on('proxyReq', (proxyReq, req) => {
if (req.originalBody) {
proxyReq.write(req.originalBody)
}
})
proxy.on('proxyRes', (proxyRes, req, res) => {
if (proxyRes.statusCode === 404 || proxyRes.statusCode === 403) {
if (req.alternativePaths && req.alternativePaths.length > 0) {
req.url = req.alternativePaths.shift()
return proxy.web(req, res, req.proxyOptions)
}
if (req.proxyOptions && req.proxyOptions.match) {
return serveRedirect(req, res, handlers, req.proxyOptions.match, req.proxyOptions)
}
}
const requestURL = new url.URL(req.url, `http://${req.headers.host || 'localhost'}`)
const pathHeaderRules = objectForPath(headerRules, requestURL.pathname)
if (!isEmpty(pathHeaderRules)) {
Object.entries(pathHeaderRules).forEach(([key, val]) => res.setHeader(key, val))
}
res.writeHead(req.proxyOptions.status || proxyRes.statusCode, proxyRes.headers)
proxyRes.on('data', function(data) {
res.write(data)
})
proxyRes.on('end', function() {
res.end()
})
})
const handlers = {
web: (req, res, options) => {
const requestURL = new url.URL(req.url, 'http://localhost')
req.proxyOptions = options
req.alternativePaths = alternativePathsFor(requestURL.pathname).map(p => p + requestURL.search)
// Ref: https://nodejs.org/api/net.html#net_socket_remoteaddress
req.headers['x-forwarded-for'] = req.connection.remoteAddress || ''
return proxy.web(req, res, options)
},
ws: (req, socket, head) => proxy.ws(req, socket, head),
}
return handlers
}
async function startProxy(settings = {}, addonUrls, configPath, projectDir, functionsDir, exit) {
try {
await waitPort({ port: settings.frameworkPort, output: 'silent' })
} catch (err) {
console.error(NETLIFYDEVERR, `Netlify Dev could not connect to localhost:${settings.port}.`)
console.error(NETLIFYDEVERR, `Please make sure your framework server is running on port ${settings.port}`)
exit(1)
}
if (functionsDir && settings.functionsPort) {
await waitPort({ port: settings.functionsPort, output: 'silent' })
}
const functionsServer = settings.functionsPort ? `http://localhost:${settings.functionsPort}` : null
const proxy = initializeProxy(settings.frameworkPort, settings.dist, projectDir)
const rewriter = await createRewriter({
distDir: settings.dist,
jwtRole: settings.jwtRolePath,
configPath,
projectDir,
})
const server = http.createServer(async function(req, res) {
req.originalBody = ['GET', 'OPTIONS', 'HEAD'].includes(req.method) ? null : await createStreamPromise(req, 30)
if (isFunction(settings.functionsPort, req.url)) {
return proxy.web(req, res, { target: functionsServer })
}
const urlForAddons = addonUrl(addonUrls, req)
if (urlForAddons) {
return proxy.web(req, res, { target: urlForAddons })
}
rewriter(req, res, match => {
const options = {
match,
addonUrls,
target: `http://localhost:${settings.frameworkPort}`,
publicFolder: settings.dist,
functionsServer,
functionsPort: settings.functionsPort,
jwtRolePath: settings.jwtRolePath,
framework: settings.framework,
}
if (match) return serveRedirect(req, res, proxy, match, options)
const ct = req.headers['content-type'] ? contentType.parse(req).type : ''
if (
req.method === 'POST' &&
!isInternal(req.url) &&
(ct.endsWith('/x-www-form-urlencoded') || ct === 'multipart/form-data')
) {
return proxy.web(req, res, { target: functionsServer })
}
proxy.web(req, res, options)
})
})
server.on('upgrade', function(req, socket, head) {
proxy.ws(req, socket, head)
})
server.listen(settings.port)
return { url: `http://localhost:${settings.port}`, port: settings.port }
}
async function serveRedirect(req, res, proxy, match, options) {
if (!match) return proxy.web(req, res, options)
options = options || req.proxyOptions || {}
options.match = null
if (!isEmpty(match.proxyHeaders)) {
Object.entries(match.proxyHeaders).forEach(([k, v]) => (req.headers[k] = v))
}
if (isFunction(options.functionsPort, req.url)) {
return proxy.web(req, res, { target: options.functionsServer })
}
const urlForAddons = addonUrl(options.addonUrls, req)
if (urlForAddons) {
return proxy.web(req, res, { target: urlForAddons })
}
if (match.exceptions && match.exceptions.JWT) {
// Some values of JWT can start with :, so, make sure to normalize them
const expectedRoles = match.exceptions.JWT.split(',').map(r => (r.startsWith(':') ? r.slice(1) : r))
const cookieValues = cookie.parse(req.headers.cookie || '')
const token = cookieValues['nf_jwt']
// Serve not found by default
const originalURL = req.url
req.url = '/.netlify/non-existent-path'
if (token) {
let jwtValue = {}
try {
jwtValue = jwtDecode(token) || {}
} catch (err) {
console.warn(NETLIFYDEVWARN, 'Error while decoding JWT provided in request', err.message)
res.writeHead(400)
res.end('Invalid JWT provided. Please see logs for more info.')
return
}
if ((jwtValue.exp || 0) < Math.round(new Date().getTime() / 1000)) {
console.warn(NETLIFYDEVWARN, 'Expired JWT provided in request', req.url)
} else {
const presentedRoles = get(jwtValue, options.jwtRolePath) || []
if (!Array.isArray(presentedRoles)) {
console.warn(NETLIFYDEVWARN, `Invalid roles value provided in JWT ${options.jwtRolePath}`, presentedRoles)
res.writeHead(400)
res.end('Invalid JWT provided. Please see logs for more info.')
return
}
// Restore the URL if everything is correct
if (presentedRoles.some(pr => expectedRoles.includes(pr))) {
req.url = originalURL
}
}
}
}
const reqUrl = new url.URL(
req.url,
`${req.protocol || (req.headers.scheme && req.headers.scheme + ':') || 'http:'}//${req.headers['host'] ||
req.hostname}`
)
const staticFile = await getStatic(reqUrl.pathname, options.publicFolder)
if (staticFile) req.url = staticFile + reqUrl.search
if (match.force404) {
res.writeHead(404)
return render404(options.publicFolder)
}
if (match.force || !staticFile || !options.framework || req.method === 'POST') {
const dest = new url.URL(match.to, `${reqUrl.protocol}//${reqUrl.host}`)
// Use query params of request URL as base, so that, destination query params can supersede
const urlParams = new URLSearchParams(reqUrl.searchParams)
dest.searchParams.forEach((val, key) => urlParams.set(key, val))
urlParams.forEach((val, key) => dest.searchParams.set(key, val))
// Get the URL after http://host:port
const destURL = dest.toString().replace(dest.origin, '')
if (isRedirect(match)) {
res.writeHead(match.status, {
'Location': match.to,
'Cache-Control': 'no-cache',
})
res.end(`Redirecting to ${match.to}`)
return
}
if (isExternal(match)) {
console.log(`${NETLIFYDEVLOG} Proxying to `, dest.toString())
const handler = createProxyMiddleware({
target: `${dest.protocol}//${dest.host}`,
changeOrigin: true,
pathRewrite: (path, req) => destURL.replace(/https?:\/\/[^/]+/, ''),
...(Buffer.isBuffer(req.originalBody) && { buffer: toReadableStream(req.originalBody) }),
})
return handler(req, res, {})
}
const ct = req.headers['content-type'] ? contentType.parse(req).type : ''
if (
req.method === 'POST' &&
!isInternal(req.url) &&
!isInternal(destURL) &&
(ct.endsWith('/x-www-form-urlencoded') || ct === 'multipart/form-data')
) {
return proxy.web(req, res, { target: options.functionsServer })
}
const destStaticFile = await getStatic(dest.pathname, options.publicFolder)
let status
if (match.force || (!staticFile && ((!options.framework && destStaticFile) || isInternal(destURL)))) {
req.url = destStaticFile ? destStaticFile + dest.search : destURL
status = match.status
console.log(`${NETLIFYDEVLOG} Rewrote URL to`, req.url)
}
if (isFunction(options.functionsPort, req.url)) {
req.headers['x-netlify-original-pathname'] = reqUrl.pathname
return proxy.web(req, res, { target: options.functionsServer })
}
const urlForAddons = addonUrl(options.addonUrls, req)
if (urlForAddons) {
return proxy.web(req, res, { target: urlForAddons })
}
return proxy.web(req, res, { ...options, status })
}
return proxy.web(req, res, options)
}
async function startDevServer(settings, log) {
if (settings.noCmd) {
const StaticServer = require('static-server')
const server = new StaticServer({
rootPath: settings.dist,
name: 'netlify-dev',
port: settings.frameworkPort,
templates: {
notFound: path.join(settings.dist, '404.html'),
},
})
server.start(function() {
log(`\n${NETLIFYDEVLOG} Server listening to`, settings.frameworkPort)
})
return
}
log(`${NETLIFYDEVLOG} Starting Netlify Dev with ${settings.framework || 'custom config'}`)
const commandBin = await which(settings.command).catch(err => {
if (err.code === 'ENOENT') {
throw new Error(
`"${settings.command}" could not be found in your PATH. Please make sure that "${settings.command}" is installed and available in your PATH`
)
}
throw err
})
const ps = child_process.spawn(commandBin, settings.args, {
env: { ...process.env, ...settings.env, FORCE_COLOR: 'true' },
stdio: 'pipe',
})
ps.stdout.pipe(stripAnsiCc.stream()).pipe(process.stdout)
ps.stderr.pipe(stripAnsiCc.stream()).pipe(process.stderr)
process.stdin.pipe(process.stdin)
function handleProcessExit(code) {
log(
code > 0 ? NETLIFYDEVERR : NETLIFYDEVWARN,
`"${[settings.command, ...settings.args].join(' ')}" exited with code ${code}. Shutting down Netlify Dev server`
)
process.exit(code)
}
ps.on('close', handleProcessExit)
ps.on('SIGINT', handleProcessExit)
ps.on('SIGTERM', handleProcessExit)
;['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGHUP', 'exit'].forEach(signal =>
process.on(signal, () => {
try {
process.kill(-ps.pid)
} catch (err) {
// Ignore
}
process.exit()
})
)
return ps
}
const getBuildFunction = functionBuilder =>
async function build() {
this.log(
`${NETLIFYDEVLOG} Function builder ${chalk.yellow(functionBuilder.builderName)} ${chalk.magenta(
'building'
)} functions from directory ${chalk.yellow(functionBuilder.src)}`
)
try {
await functionBuilder.build()
this.log(
`${NETLIFYDEVLOG} Function builder ${chalk.yellow(functionBuilder.builderName)} ${chalk.green(
'finished'
)} building functions from directory ${chalk.yellow(functionBuilder.src)}`
)
} catch (error) {
const errorMessage = (error.stderr && error.stderr.toString()) || error.message
this.log(
`${NETLIFYDEVLOG} Function builder ${chalk.yellow(functionBuilder.builderName)} ${chalk.red(
'failed'
)} building functions from directory ${chalk.yellow(functionBuilder.src)}${
errorMessage ? ` with error:\n${errorMessage}` : ''
}`
)
}
}
const getAddonsUrlsAndAddEnvVariablesToProcessEnv = async ({ api, site, flags }) => {
if (site.id && !flags.offline) {
const { addEnvVariables } = require('../../utils/dev')
const addonUrls = await addEnvVariables(api, site)
return addonUrls
} else {
return {}
}
}
const addDotFileEnvs = async ({ site }) => {
const envSettings = await getEnvSettings(site.root)
if (envSettings.file) {
console.log(
`${NETLIFYDEVLOG} Overriding the following env variables with ${chalk.blue(
path.relative(site.root, envSettings.file)
)} file:`,
chalk.yellow(Object.keys(envSettings.vars))
)
Object.entries(envSettings.vars).forEach(([key, val]) => (process.env[key] = val))
}
}
class DevCommand extends Command {
async run() {
this.log(`${NETLIFYDEV}`)
const errorExit = this.error
const log = this.log
const { flags } = this.parse(DevCommand)
const { api, site, config } = this.netlify
config.dev = { ...config.dev }
config.build = { ...config.build }
const devConfig = {
framework: '#auto',
...(config.build.functions && { functions: config.build.functions }),
...(config.build.publish && { publish: config.build.publish }),
...config.dev,
...flags,
}
const addonUrls = await getAddonsUrlsAndAddEnvVariablesToProcessEnv({ api, site, flags })
process.env.NETLIFY_DEV = 'true'
await addDotFileEnvs({ site })
let settings = {}
try {
settings = await serverSettings(devConfig, flags, site.root, this.log)
} catch (err) {
this.log(NETLIFYDEVERR, err.message)
this.exit(1)
}
await startDevServer(settings, this.log)
// serve functions from zip-it-and-ship-it
// env variables relies on `url`, careful moving this code
if (settings.functions) {
const functionBuilder = await detectFunctionsBuilder(site.root)
if (functionBuilder) {
this.log(
`${NETLIFYDEVLOG} Function builder ${chalk.yellow(
functionBuilder.builderName
)} detected: Running npm script ${chalk.yellow(functionBuilder.npmScript)}`
)
this.warn(
`${NETLIFYDEVWARN} This is a beta feature, please give us feedback on how to improve at https://github.com/netlify/cli/`
)
const debouncedBuild = debounce(getBuildFunction(functionBuilder).bind(this), 300, {
leading: true,
trailing: true,
})
await debouncedBuild()
const functionWatcher = chokidar.watch(functionBuilder.src)
functionWatcher.on('ready', () => {
functionWatcher.on('add', debouncedBuild)
functionWatcher.on('change', debouncedBuild)
functionWatcher.on('unlink', debouncedBuild)
})
}
const functionsServer = await serveFunctions(settings.functions, this.netlify.cachedConfig.siteInfo)
functionsServer.listen(settings.functionsPort, function(err) {
if (err) {
errorExit(`${NETLIFYDEVERR} Unable to start lambda server: ${err}`)
}
// add newline because this often appears alongside the client devserver's output
log(`\n${NETLIFYDEVLOG} Functions server is listening on ${settings.functionsPort}`)
})
}
let { url } = await startProxy(settings, addonUrls, site.configPath, site.root, settings.functions, this.exit)
if (!url) {
throw new Error('Unable to start proxy server')
}
if (flags.live) {
const accessToken = api.accessToken
await waitPort({ port: settings.frameworkPort, output: 'silent' })
const liveSession = await createTunnel(site.id, accessToken, this.log)
url = liveSession.session_url
process.env.BASE_URL = url
await connectTunnel(liveSession, accessToken, settings.port, this.log)
}
await this.config.runHook('analytics', {
eventName: 'command',
payload: {
command: 'dev',
projectType: settings.framework || 'custom',
live: flags.live || false,
},
})
if (devConfig.autoLaunch && devConfig.autoLaunch !== false) {
try {
await open(url)
} catch (err) {
console.warn(NETLIFYDEVWARN, 'Error while opening dev server URL in browser', err.message)
}
}
// boxen doesnt support text wrapping yet https://github.com/sindresorhus/boxen/issues/16
const banner = require('wrap-ansi')(chalk.bold(`${NETLIFYDEVLOG} Server now ready on ${url}`), 70)
process.env.URL = url
process.env.DEPLOY_URL = process.env.URL
this.log(
boxen(banner, {
padding: 1,
margin: 1,
align: 'center',
borderColor: '#00c7b7',
})
)
}
}
DevCommand.description = `Local dev server
The dev command will run a local dev server with Netlify's proxy and redirect rules
`
DevCommand.examples = ['$ netlify dev', '$ netlify dev -c "yarn start"', '$ netlify dev -c hugo']
DevCommand.strict = false
DevCommand.flags = {
...DevCommand.flags,
command: flags.string({
char: 'c',
description: 'command to run',
}),
port: flags.integer({
char: 'p',
description: 'port of netlify dev',
}),
targetPort: flags.integer({
description: 'port of target app server',
}),
staticServerPort: flags.integer({
description: 'port of the static app server used when no framework is detected',
hidden: true,
}),
dir: flags.string({
char: 'd',
description: 'dir with static files',
}),
functions: flags.string({
char: 'f',
description: 'Specify a functions folder to serve',
}),
offline: flags.boolean({
char: 'o',
description: 'disables any features that require network access',
}),
live: flags.boolean({
char: 'l',
description: 'Start a public live session',
}),
}
module.exports = DevCommand