-
Notifications
You must be signed in to change notification settings - Fork 340
/
dev.ts
348 lines (309 loc) · 11.5 KB
/
dev.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
347
348
import process from 'process'
import { OptionValues, Option } from 'commander'
// @ts-expect-error TS(7016) FIXME: Could not find a declaration file for module '@net... Remove this comment to see the full error message
import { applyMutations } from '@netlify/config'
import { BLOBS_CONTEXT_VARIABLE, encodeBlobsContext, getBlobsContext } from '../../lib/blobs/blobs.js'
import { promptEditorHelper } from '../../lib/edge-functions/editor-helper.js'
import { startFunctionsServer } from '../../lib/functions/server.js'
import { printBanner } from '../../utils/banner.js'
import {
BANG,
chalk,
log,
NETLIFYDEV,
NETLIFYDEVERR,
NETLIFYDEVLOG,
NETLIFYDEVWARN,
normalizeConfig,
} from '../../utils/command-helpers.js'
import detectServerSettings, { getConfigWithPlugins } from '../../utils/detect-server-settings.js'
import { getDotEnvVariables, getSiteInformation, injectEnvVariables, UNLINKED_SITE_MOCK_ID } from '../../utils/dev.js'
import { getEnvelopeEnv, normalizeContext } from '../../utils/env/index.js'
import { ensureNetlifyIgnore } from '../../utils/gitignore.js'
import { getLiveTunnelSlug, startLiveTunnel } from '../../utils/live-tunnel.js'
import openBrowser from '../../utils/open-browser.js'
import { generateInspectSettings, startProxyServer } from '../../utils/proxy-server.js'
import { getProxyUrl } from '../../utils/proxy.js'
import { runDevTimeline } from '../../utils/run-build.js'
import { getGeoCountryArgParser } from '../../utils/validation.js'
import BaseCommand from '../base-command.js'
import { createDevExecCommand } from './dev-exec.js'
import { type DevConfig } from './types.js'
/**
*
* @param {object} config
* @param {*} config.api
* @param {import('commander').OptionValues} config.options
* @param {import('../../utils/types.js').ServerSettings} config.settings
* @param {*} config.site
* @param {*} config.state
* @returns
*/
// @ts-expect-error TS(7031) FIXME: Binding element 'api' implicitly has an 'any' type... Remove this comment to see the full error message
const handleLiveTunnel = async ({ api, options, settings, site, state }) => {
const { live } = options
if (live) {
const customSlug = typeof live === 'string' && live.length !== 0 ? live : undefined
const slug = getLiveTunnelSlug(state, customSlug)
let message = `${NETLIFYDEVWARN} Creating live URL with ID ${chalk.yellow(slug)}`
if (!customSlug) {
message += ` (to generate a custom URL, use ${chalk.magenta('--live=<subdomain>')})`
}
log(message)
const sessionUrl = await startLiveTunnel({
siteId: site.id,
netlifyApiToken: api.accessToken,
localPort: settings.port,
slug,
})
process.env.BASE_URL = sessionUrl
return sessionUrl
}
}
const validateShortFlagArgs = (args: string) => {
if (args.startsWith('=')) {
throw new Error(
`Short flag options like -e or -E don't support the '=' sign
${chalk.red(BANG)} Supported formats:
netlify dev -e
netlify dev -e 127.0.0.1:9229
netlify dev -e127.0.0.1:9229
netlify dev -E
netlify dev -E 127.0.0.1:9229
netlify dev -E127.0.0.1:9229`,
)
}
return args
}
export const dev = async (options: OptionValues, command: BaseCommand) => {
log(`${NETLIFYDEV}`)
const { api, cachedConfig, config, repositoryRoot, site, siteInfo, state } = command.netlify
config.dev = { ...config.dev }
config.build = { ...config.build }
const devConfig = {
framework: '#auto',
autoLaunch: Boolean(options.open),
...(config.functionsDirectory && { functions: config.functionsDirectory }),
...(config.build.publish && { publish: config.build.publish }),
...(config.build.base && { base: config.build.base }),
...config.dev,
...options,
} as DevConfig
let { env } = cachedConfig
env.NETLIFY_DEV = { sources: ['internal'], value: 'true' }
const blobsContext = await getBlobsContext({
debug: options.debug,
projectRoot: command.workingDir,
siteID: site.id ?? UNLINKED_SITE_MOCK_ID,
})
env[BLOBS_CONTEXT_VARIABLE] = { sources: ['internal'], value: encodeBlobsContext(blobsContext) }
if (!options.offline && siteInfo.use_envelope) {
env = await getEnvelopeEnv({ api, context: options.context, env, siteInfo })
log(`${NETLIFYDEVLOG} Injecting environment variable values for ${chalk.yellow('all scopes')}`)
}
env = await getDotEnvVariables({ devConfig, env, site })
injectEnvVariables(env)
await promptEditorHelper({ chalk, config, log, NETLIFYDEVLOG, repositoryRoot, state })
const { accountId, addonsUrls, capabilities, siteUrl, timeouts } = await getSiteInformation({
// inherited from base command --offline
offline: options.offline,
api,
site,
siteInfo,
})
/** @type {import('../../utils/types.js').ServerSettings} */
let settings
try {
settings = await detectServerSettings(devConfig, options, command)
if (process.env.NETLIFY_INCLUDE_DEV_SERVER_PLUGIN) {
if (options.debug) {
log(`${NETLIFYDEVLOG} Including dev server plugin`)
}
settings.plugins = [...(settings.plugins || []), '@netlify/plugin-dev-server']
}
cachedConfig.config = getConfigWithPlugins(cachedConfig.config, settings)
} catch (error_) {
if (error_ && typeof error_ === 'object' && 'message' in error_) {
log(NETLIFYDEVERR, error_.message)
}
process.exit(1)
}
command.setAnalyticsPayload({ live: options.live })
const liveTunnelUrl = await handleLiveTunnel({ options, site, api, settings, state })
const url = liveTunnelUrl || getProxyUrl(settings)
process.env.URL = url
process.env.DEPLOY_URL = url
log(`${NETLIFYDEVWARN} Setting up local development server`)
const { configMutations, configPath: configPathOverride } = await runDevTimeline({
command,
options,
settings,
env: {
URL: url,
DEPLOY_URL: url,
},
})
const mutatedConfig = applyMutations(config, configMutations)
const functionsRegistry = await startFunctionsServer({
blobsContext,
command,
config: mutatedConfig,
debug: options.debug,
settings,
site,
siteInfo,
siteUrl,
capabilities,
timeouts,
geolocationMode: options.geo,
geoCountry: options.country,
offline: options.offline,
state,
accountId,
})
// Try to add `.netlify` to `.gitignore`.
try {
await ensureNetlifyIgnore(repositoryRoot)
} catch {
// no-op
}
// TODO: We should consolidate this with the existing config watcher.
const getUpdatedConfig = async () => {
const { config: newConfig } = await command.getConfig({
cwd: command.workingDir,
offline: true,
state,
})
const normalizedNewConfig = normalizeConfig(newConfig)
return normalizedNewConfig
}
const inspectSettings = generateInspectSettings(options.edgeInspect, options.edgeInspectBrk)
await startProxyServer({
addonsUrls,
blobsContext,
config: mutatedConfig,
configPath: configPathOverride,
debug: options.debug,
projectDir: command.workingDir,
env,
getUpdatedConfig,
inspectSettings,
offline: options.offline,
settings,
site,
siteInfo,
state,
geolocationMode: options.geo,
geoCountry: options.country,
accountId,
functionsRegistry,
repositoryRoot,
})
if (devConfig.autoLaunch !== false) {
await openBrowser({ url, silentBrowserNoneError: true })
}
printBanner({ url })
}
export const createDevCommand = (program: BaseCommand) => {
createDevExecCommand(program)
return program
.command('dev')
.alias('develop')
.description(
`Local dev server\nThe dev command will run a local dev server with Netlify's proxy and redirect rules`,
)
.option('-c ,--command <command>', 'command to run')
.option(
'--context <context>',
'Specify a deploy context or branch for environment variables (contexts: "production", "deploy-preview", "branch-deploy", "dev")',
normalizeContext,
)
.option('-p ,--port <port>', 'port of netlify dev', (value) => Number.parseInt(value))
.addOption(
new Option('--targetPort <port>', 'Old, prefer --target-port. Port of target app server')
.argParser((value) => Number.parseInt(value))
.hideHelp(true),
)
.addOption(new Option('--no-open', 'disables the automatic opening of a browser window'))
.option('--target-port <port>', 'port of target app server', (value) => Number.parseInt(value))
.option('--framework <name>', 'framework to use. Defaults to #auto which automatically detects a framework')
.option('-d ,--dir <path>', 'dir with static files')
.option('-f ,--functions <folder>', 'specify a functions folder to serve')
.option('-o ,--offline', 'disables any features that require network access')
.option(
'-l, --live [subdomain]',
'start a public live session; optionally, supply a subdomain to generate a custom URL',
false,
)
.addOption(
new Option('--functionsPort <port>', 'Old, prefer --functions-port. Port of functions server')
.argParser((value) => Number.parseInt(value))
.hideHelp(true),
)
.option('--functions-port <port>', 'port of functions server', (value) => Number.parseInt(value))
.addOption(
new Option(
'--geo <mode>',
'force geolocation data to be updated, use cached data from the last 24h if found, or use a mock location',
)
.choices(['cache', 'mock', 'update'])
.default('cache'),
)
.addOption(
new Option(
'--country <geoCountry>',
'Two-letter country code (https://ntl.fyi/country-codes) to use as mock geolocation (enables --geo=mock automatically)',
).argParser(getGeoCountryArgParser('netlify dev --geo=mock --country=FR')),
)
.addOption(
new Option('--staticServerPort <port>', 'port of the static app server used when no framework is detected')
.argParser((value) => Number.parseInt(value))
.hideHelp(),
)
.addOption(
new Option(
'-e, --edgeInspect [address]',
'Old, prefer --edge-inspect. Enable the V8 Inspector Protocol for Edge Functions, with an optional address in the host:port format',
)
.conflicts('edgeInspectBrk')
.argParser(validateShortFlagArgs)
.hideHelp(true),
)
.addOption(
new Option(
'-e, --edge-inspect [address]',
'enable the V8 Inspector Protocol for Edge Functions, with an optional address in the host:port format',
)
.conflicts('edgeInspectBrk')
.argParser(validateShortFlagArgs),
)
.addOption(
new Option(
'-E, --edgeInspectBrk [address]',
'Old, prefer --edge-inspect-brk. Enable the V8 Inspector Protocol for Edge Functions and pause execution on the first line of code, with an optional address in the host:port format',
)
.conflicts('edgeInspect')
.hideHelp(true)
.argParser(validateShortFlagArgs),
)
.addOption(
new Option(
'-E, --edge-inspect-brk [address]',
'enable the V8 Inspector Protocol for Edge Functions and pause execution on the first line of code, with an optional address in the host:port format',
)
.conflicts('edgeInspect')
.argParser(validateShortFlagArgs),
)
.addExamples([
'netlify dev',
'netlify dev -d public',
'netlify dev -c "hugo server -w" --target-port 1313',
'netlify dev --context production',
'netlify dev --edge-inspect',
'netlify dev --edge-inspect=127.0.0.1:9229',
'netlify dev --edge-inspect-brk',
'netlify dev --edge-inspect-brk=127.0.0.1:9229',
'BROWSER=none netlify dev # disable browser auto opening',
])
.action(dev)
}