-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathdeploy.ts
More file actions
1190 lines (1063 loc) · 36.9 KB
/
deploy.ts
File metadata and controls
1190 lines (1063 loc) · 36.9 KB
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { type Stats } from 'fs'
import { stat } from 'fs/promises'
import { basename, resolve } from 'path'
import { stdin, stdout } from 'process'
import type { NetlifyAPI } from '@netlify/api'
import { type NetlifyConfig, type OnPostBuild, runCoreSteps } from '@netlify/build'
import inquirer from 'inquirer'
import isEmpty from 'lodash/isEmpty.js'
import isObject from 'lodash/isObject.js'
import { parseAllHeaders } from '@netlify/headers-parser'
import { parseAllRedirects } from '@netlify/redirect-parser'
import prettyjson from 'prettyjson'
import { cancelDeploy } from '../../lib/api.js'
import {
type CachedConfig,
type DefaultConfig,
type PatchedHandlerType,
getRunBuildOptions,
runBuild,
} from '../../lib/build.js'
import { getBootstrapURL } from '../../lib/edge-functions/bootstrap.js'
import { featureFlags as edgeFunctionsFeatureFlags } from '../../lib/edge-functions/consts.js'
import { normalizeFunctionsConfig } from '../../lib/functions/config.js'
import { BACKGROUND_FUNCTIONS_WARNING } from '../../lib/log.js'
import { type Spinner, startSpinner, stopSpinner } from '../../lib/spinner.js'
import { detectFrameworkSettings, getDefaultConfig } from '../../utils/build-info.js'
import {
NETLIFY_CYAN_HEX,
NETLIFYDEVERR,
NETLIFYDEVLOG,
chalk,
logAndThrowError,
exit,
getToken,
log,
logJson,
warn,
type APIError,
} from '../../utils/command-helpers.js'
import { DEFAULT_DEPLOY_TIMEOUT } from '../../utils/deploy/constants.js'
import { getDeployUrls } from '../../utils/deploy/deploy-output.js'
import { type DeployEvent, deploySite } from '../../utils/deploy/deploy-site.js'
import { uploadSourceZip } from '../../utils/deploy/upload-source-zip.js'
import { getEnvelopeEnv } from '../../utils/env/index.js'
import { getFunctionsManifestPath, getInternalFunctionsDir } from '../../utils/functions/index.js'
import openBrowser from '../../utils/open-browser.js'
import type BaseCommand from '../base-command.js'
import { link } from '../link/link.js'
import { sitesCreate } from '../sites/sites-create.js'
import type { $TSFixMe } from '../types.js'
import { SiteInfo } from '../../utils/types.js'
import type { DeployOptionValues } from './option_values.js'
import boxen from 'boxen'
import terminalLink from 'terminal-link'
import { anyEdgeFunctionsDirectoryExists } from '../../lib/edge-functions/get-directories.js'
const triggerDeploy = async ({
api,
options,
siteData,
siteId,
}: {
api: NetlifyAPI
options: DeployOptionValues
siteData: { name: string }
siteId: string
}) => {
try {
const siteBuild = await api.createSiteBuild({ siteId })
if (options.json) {
logJson({
site_id: siteId,
site_name: siteData.name,
deploy_id: `${siteBuild.deploy_id}`,
logs: `https://app.netlify.com/projects/${siteData.name}/deploys/${siteBuild.deploy_id}`,
})
} else {
log(
`${NETLIFYDEVLOG} A new deployment was triggered successfully. Visit https://app.netlify.com/projects/${siteData.name}/deploys/${siteBuild.deploy_id} to see the logs.`,
)
}
} catch (error_) {
if ((error_ as APIError).status === 404) {
return logAndThrowError(
'Project not found. Please rerun "netlify link" and make sure that your project has CI configured.',
)
} else {
return logAndThrowError((error_ as APIError).message)
}
}
}
/** Retrieves the folder containing the static files that need to be deployed */
const getDeployFolder = async ({
command,
config,
options,
site,
siteData,
}: {
command: BaseCommand
config: $TSFixMe
options: DeployOptionValues
site: $TSFixMe
siteData: $TSFixMe
}): Promise<string> => {
let deployFolder: string | undefined
// if the `--dir .` flag is provided we should resolve it to the working directory.
// - in regular sites this is the `process.cwd`
// - in mono repositories this will be the root of the jsWorkspace
if (options.dir) {
deployFolder = command.workspacePackage
? resolve(command.jsWorkspaceRoot || site.root, options.dir)
: resolve(command.workingDir, options.dir)
} else if (config?.build?.publish) {
deployFolder = resolve(site.root, config.build.publish)
} else if (siteData?.build_settings?.dir) {
deployFolder = resolve(site.root, siteData.build_settings.dir)
}
if (!deployFolder) {
if (!stdin.isTTY || !stdout.isTTY) {
// non interactive - can't get the value, resolve to the cwd
if (command.workspacePackage) {
return command.jsWorkspaceRoot || site.root
}
return command.workingDir
}
log('Please provide a publish directory (e.g. "public" or "dist" or "."):')
// Generate copy-pasteable command with current options
const copyableCommand = generateDeployCommand({ ...options, dir: '<PATH>' }, [], command)
log(`\nTo specify directory non-interactively, use: ${copyableCommand}\n`)
const { promptPath } = await inquirer.prompt([
{
type: 'input',
name: 'promptPath',
message: 'Publish directory',
default: '.',
filter: (input) => resolve(command.workingDir, input),
},
])
deployFolder = promptPath as string
}
return deployFolder
}
const validateDeployFolder = async (deployFolder: string) => {
let stats: Stats
try {
stats = await stat(deployFolder)
} catch (error_) {
if (error_ && typeof error_ === 'object' && 'code' in error_) {
if (error_.code === 'ENOENT') {
return logAndThrowError(
`The deploy directory "${deployFolder}" has not been found. Did you forget to run 'netlify build'?`,
)
}
// Improve the message of permission errors
if (error_.code === 'EACCES') {
return logAndThrowError('Permission error when trying to access deploy folder')
}
}
throw error_
}
if (!stats.isDirectory()) {
return logAndThrowError('Deploy target must be a path to a directory')
}
return stats
}
/** get the functions directory */
const getFunctionsFolder = ({
config,
options,
site,
siteData,
workingDir,
}: {
config: $TSFixMe
options: DeployOptionValues
site: $TSFixMe
siteData: $TSFixMe
/** The process working directory where the build command is executed */
workingDir: string
}): string | undefined => {
let functionsFolder: string | undefined
// Support "functions" and "Functions"
const funcConfig = config.functionsDirectory
if (options.functions) {
functionsFolder = resolve(workingDir, options.functions)
} else if (funcConfig) {
functionsFolder = resolve(site.root, funcConfig)
} else if (siteData?.build_settings?.functions_dir) {
functionsFolder = resolve(site.root, siteData.build_settings.functions_dir)
}
return functionsFolder
}
const validateFunctionsFolder = async (functionsFolder: string | undefined) => {
let stats: Stats | undefined
if (functionsFolder) {
// we used to hard error if functions folder is specified but doesn't exist
// but this was too strict for onboarding. we can just log a warning.
try {
stats = await stat(functionsFolder)
} catch (error_) {
if (error_ && typeof error_ === 'object' && 'code' in error_) {
if (error_.code === 'ENOENT') {
log(
`Functions folder "${functionsFolder}" specified but it doesn't exist! Will proceed without deploying functions`,
)
}
// Improve the message of permission errors
if (error_.code === 'EACCES') {
return logAndThrowError('Permission error when trying to access functions folder')
}
}
}
}
if (stats && !stats.isDirectory()) {
return logAndThrowError('Functions folder must be a path to a directory')
}
return stats
}
const validateFolders = async ({
deployFolder,
functionsFolder,
}: {
deployFolder: string
functionsFolder?: string
}) => {
const deployFolderStat = await validateDeployFolder(deployFolder)
const functionsFolderStat = await validateFunctionsFolder(functionsFolder)
return { deployFolderStat, functionsFolderStat }
}
/**
* @param {object} config
* @param {string} config.deployFolder
* @param {*} config.site
* @returns
*/
// @ts-expect-error TS(7031) FIXME: Binding element 'deployFolder' implicitly has an '... Remove this comment to see the full error message
const getDeployFilesFilter = ({ deployFolder, site }) => {
// site.root === deployFolder can happen when users run `netlify deploy --dir .`
// in that specific case we don't want to publish the repo node_modules
// when site.root !== deployFolder the behaviour matches our buildbot
const skipNodeModules = site.root === deployFolder
return (filename: string) => {
if (filename == null) {
return false
}
if (filename === deployFolder) {
return true
}
const base = basename(filename)
const skipFile =
(skipNodeModules && base === 'node_modules') ||
(base.startsWith('.') && base !== '.well-known') ||
base.startsWith('__MACOSX') ||
base.includes('/.') ||
// headers and redirects are bundled in the config
base === '_redirects' ||
base === '_headers'
return !skipFile
}
}
const SEC_TO_MILLISEC = 1e3
// 100 bytes
const SYNC_FILE_LIMIT = 1e2
// Helper function to generate copy-pasteable deploy command
const generateDeployCommand = (
options: DeployOptionValues,
availableTeams: { name: string; slug: string }[],
command?: BaseCommand,
): string => {
const parts = ['netlify deploy']
// Handle site selection/creation first
if (options.createSite) {
const siteName = typeof options.createSite === 'string' ? options.createSite : '<SITE_NAME>'
parts.push(`--create-site ${siteName}`)
if (availableTeams.length > 1) {
parts.push('--team <TEAM_SLUG>')
}
} else if (options.site) {
parts.push(`--site ${options.site}`)
} else {
parts.push('--create-site <SITE_NAME>')
if (availableTeams.length > 1) {
parts.push('--team <TEAM_SLUG>')
}
}
if (command?.options) {
for (const option of command.options) {
if (['createSite', 'site', 'team'].includes(option.attributeName())) {
continue
}
const optionName = option.attributeName() as keyof DeployOptionValues
const value = options[optionName]
if (option.long?.startsWith('--no-')) {
if (value === false) {
parts.push(option.long)
}
continue
}
if (optionName === 'build') {
continue
}
if (value && option.long) {
const flag = option.long
const hasValue = option.required || option.optional
if (hasValue && typeof value === 'string') {
const quotedValue = optionName === 'message' ? `"${value}"` : value
parts.push(`${flag} ${quotedValue}`)
} else if (hasValue && typeof value === 'number') {
parts.push(`${flag} ${value}`)
} else if (!hasValue && value === true) {
parts.push(flag)
}
}
}
}
return parts.join(' ')
}
// @ts-expect-error TS(7031) FIXME: Binding element 'api' implicitly has an 'any' type... Remove this comment to see the full error message
const prepareProductionDeploy = async ({ api, siteData, options, command }) => {
if (isObject(siteData.published_deploy) && siteData.published_deploy.locked) {
log(`\n${NETLIFYDEVERR} Deployments are "locked" for production context of this project\n`)
// Generate copy-pasteable command with current options
const overrideCommand = generateDeployCommand({ ...options, prodIfUnlocked: true, prod: false }, [], command)
log('\nTo override deployment lock (USE WITH CAUTION), use:')
log(` ${overrideCommand}`)
log('\nWarning: Only use --prod-if-unlocked if you are absolutely sure you want to override the deployment lock.\n')
const { unlockChoice } = await inquirer.prompt([
{
type: 'confirm',
name: 'unlockChoice',
message: 'Would you like to "unlock" deployments for production context to proceed?',
default: false,
},
])
if (!unlockChoice) exit(0)
await api.unlockDeploy({ deploy_id: siteData.published_deploy.id })
log(`\n${NETLIFYDEVLOG} "Auto publishing" has been enabled for production context\n`)
}
}
const hasErrorMessage = (actual: unknown, expected: string): boolean => {
if (typeof actual === 'string') {
return actual.includes(expected)
}
return false
}
interface DeployError extends Error {
json?: { message?: string }
status?: unknown
}
const reportDeployError = ({
error,
failAndExit,
}: {
error: DeployError
failAndExit: (err: unknown) => never
}): never => {
switch (true) {
case error.name === 'JSONHTTPError': {
const message = error.json?.message ?? ''
if (hasErrorMessage(message, 'Background Functions not allowed by team plan')) {
return failAndExit(`\n${BACKGROUND_FUNCTIONS_WARNING}`)
}
warn(`JSONHTTPError: ${message} ${error.status}`)
warn(`\n${JSON.stringify(error, null, ' ')}\n`)
return failAndExit(error)
}
case error.name === 'TextHTTPError': {
warn(`TextHTTPError: ${error.status}`)
warn(`\n${error}\n`)
return failAndExit(error)
}
case hasErrorMessage(error.message, 'Invalid filename'): {
warn(error.message)
return failAndExit(error)
}
default: {
warn(`\n${JSON.stringify(error, null, ' ')}\n`)
return failAndExit(error)
}
}
}
const deployProgressCb = function () {
const spinnersByType: Record<DeployEvent['type'], Spinner> = {}
return (event: DeployEvent) => {
switch (event.phase) {
case 'start': {
spinnersByType[event.type] = startSpinner({
text: event.msg,
})
return
}
case 'progress': {
const spinner = spinnersByType[event.type]
if (spinner) {
spinner.update({ text: event.msg })
}
return
}
case 'error':
stopSpinner({ error: true, spinner: spinnersByType[event.type], text: event.msg })
delete spinnersByType[event.type]
return
case 'stop':
default: {
spinnersByType[event.type].success(event.msg)
delete spinnersByType[event.type]
}
}
}
}
const uploadDeployBlobs = async ({
cachedConfig,
deployId,
options,
packagePath,
silent,
siteId,
}: {
cachedConfig: CachedConfig
deployId: string
options: DeployOptionValues
packagePath?: string
silent: boolean
siteId: string
}) => {
const statusCb = silent ? () => {} : deployProgressCb()
statusCb({
type: 'blobs-uploading',
msg: 'Uploading blobs to deploy store...\n',
phase: 'start',
})
const [token] = await getToken()
const blobsToken = token || undefined
const { success } = await runCoreSteps(['blobs_upload'], {
...options,
// We log our own progress so we don't want this as well. Plus, this logs much of the same
// information as the build that (likely) came before this as part of the deploy build.
quiet: options.debug ?? true,
// @ts-expect-error(serhalp) -- Untyped in `@netlify/build`
cachedConfig,
packagePath,
deployId,
siteId,
token: blobsToken,
})
if (!success) {
statusCb({
type: 'blobs-uploading',
msg: 'Deploy aborted due to error while uploading blobs to deploy store',
phase: 'error',
})
return logAndThrowError('Error while uploading blobs to deploy store')
}
statusCb({
type: 'blobs-uploading',
msg: 'Finished uploading blobs to deploy store',
phase: 'stop',
})
}
const runDeploy = async ({
// @ts-expect-error TS(7031) FIXME: Binding element 'alias' implicitly has an 'any' ty... Remove this comment to see the full error message
alias,
// @ts-expect-error TS(7031) FIXME: Binding element 'api' implicitly has an 'any' type... Remove this comment to see the full error message
api,
command,
// @ts-expect-error TS(7031) FIXME: Binding element 'config' implicitly has an 'any' t... Remove this comment to see the full error message
config,
// @ts-expect-error TS(7031) FIXME: Binding element 'deployFolder' implicitly has an '... Remove this comment to see the full error message
deployFolder,
// @ts-expect-error TS(7031) FIXME: Binding element 'deployTimeout' implicitly has an ... Remove this comment to see the full error message
deployTimeout,
// @ts-expect-error TS(7031) FIXME: Binding element 'deployToProduction' implicitly ha... Remove this comment to see the full error message
deployToProduction,
// @ts-expect-error TS(7031) FIXME: Binding element 'functionsConfig' implicitly has a... Remove this comment to see the full error message
functionsConfig,
functionsFolder,
// @ts-expect-error TS(7031) FIXME: Binding element 'options' implicitly has an 'a... Remove this comment to see the full error message
options,
// @ts-expect-error TS(7031) FIXME: Binding element 'packagePath' implicitly has an 'a... Remove this comment to see the full error message
packagePath,
// @ts-expect-error TS(7031) FIXME: Binding element 'silent' implicitly has an 'any' t... Remove this comment to see the full error message
silent,
// @ts-expect-error TS(7031) FIXME: Binding element 'site' implicitly has an 'any' typ... Remove this comment to see the full error message
site,
// @ts-expect-error TS(7031) FIXME: Binding element 'siteData' implicitly has an 'any'... Remove this comment to see the full error message
siteData,
// @ts-expect-error TS(7031) FIXME: Binding element 'siteId' implicitly has an 'any' t... Remove this comment to see the full error message
siteId,
// @ts-expect-error TS(7031) FIXME: Binding element 'skipFunctionsCache' implicitly ha... Remove this comment to see the full error message
skipFunctionsCache,
// @ts-expect-error TS(7031) FIXME: Binding element 'title' implicitly has an 'any' ty... Remove this comment to see the full error message
title,
deployId: existingDeployId,
}: {
functionsFolder?: string
command: BaseCommand
deployId?: string
}): Promise<{
siteId: string
siteName: string
deployId: string
siteUrl: string
deployUrl: string
logsUrl: string
functionLogsUrl: string
edgeFunctionLogsUrl: string
sourceZipFileName?: string
}> => {
let results
let deployId = existingDeployId
let uploadSourceZipResult
try {
// We won't have a deploy ID if we run the command with `--no-build`.
// In this case, we must create the deploy.
if (!deployId) {
if (deployToProduction) {
await prepareProductionDeploy({ siteData, api, options, command })
}
const draft = options.draft || (!deployToProduction && !alias)
const createDeployBody = { draft, branch: alias, include_upload_url: options.uploadSourceZip }
const createDeployResponse = await api.createSiteDeploy({ siteId, title, body: createDeployBody })
deployId = createDeployResponse.id as string
if (
options.uploadSourceZip &&
createDeployResponse.source_zip_upload_url &&
createDeployResponse.source_zip_filename
) {
uploadSourceZipResult = await uploadSourceZip({
sourceDir: site.root,
uploadUrl: createDeployResponse.source_zip_upload_url,
filename: createDeployResponse.source_zip_filename,
statusCb: silent ? () => {} : deployProgressCb(),
})
}
}
const internalFunctionsFolder = await getInternalFunctionsDir({ base: site.root, packagePath, ensureExists: true })
await command.netlify.frameworksAPIPaths.functions.ensureExists()
// The order of the directories matter: zip-it-and-ship-it will prioritize
// functions from the rightmost directories. In this case, we want user
// functions to take precedence over internal functions.
const functionDirectories = [
internalFunctionsFolder,
command.netlify.frameworksAPIPaths.functions.path,
functionsFolder,
].filter((folder): folder is string => Boolean(folder))
const manifestPath = skipFunctionsCache ? null : await getFunctionsManifestPath({ base: site.root, packagePath })
const redirectsPath = `${deployFolder}/_redirects`
const headersPath = `${deployFolder}/_headers`
const { redirects } = await parseAllRedirects({
configRedirects: config.redirects,
redirectsFiles: [redirectsPath],
minimal: true,
})
config.redirects = redirects
const { headers } = await parseAllHeaders({
configHeaders: config.headers,
headersFiles: [headersPath],
minimal: true,
})
config.headers = headers
await uploadDeployBlobs({
deployId,
siteId,
silent,
options,
cachedConfig: command.netlify.cachedConfig,
packagePath: command.workspacePackage,
})
results = await deploySite(command, api, siteId, deployFolder, {
// @ts-expect-error FIXME
config,
fnDir: functionDirectories,
functionsConfig,
statusCb: silent ? () => {} : deployProgressCb(),
deployTimeout,
syncFileLimit: SYNC_FILE_LIMIT,
// pass an existing deployId to update
deployId,
filter: getDeployFilesFilter({ site, deployFolder }),
workingDir: command.workingDir,
manifestPath,
skipFunctionsCache,
siteRoot: site.root,
})
} catch (error) {
if (deployId) {
await cancelDeploy({ api, deployId })
}
return reportDeployError({ error: error as DeployError, failAndExit: logAndThrowError })
}
const urls = getDeployUrls(results.deploy, { deployToProduction })
return {
siteId: results.deploy.site_id,
siteName: results.deploy.name,
deployId: results.deployId,
...urls,
sourceZipFileName: uploadSourceZipResult?.sourceZipFileName,
}
}
const handleBuild = async ({
cachedConfig,
currentDir,
defaultConfig,
deployHandler,
deployId,
options,
packagePath,
skewProtectionToken,
}: {
cachedConfig: CachedConfig
currentDir: string
defaultConfig?: DefaultConfig | undefined
deployHandler?: PatchedHandlerType<OnPostBuild> | undefined
deployId?: string
options: DeployOptionValues
packagePath: string | undefined
skewProtectionToken?: string
}) => {
if (!options.build) {
return {}
}
const [token] = await getToken()
const resolvedOptions = await getRunBuildOptions({
cachedConfig,
currentDir,
defaultConfig,
deployHandler,
deployId,
options,
packagePath,
skewProtectionToken,
token,
})
const { configMutations, exitCode, newConfig, logs } = await runBuild(resolvedOptions)
// Without this, the deploy command fails silently
if (exitCode !== 0) {
let message = ''
if (options.verbose && logs?.stdout.length) {
message += `\n\n${logs.stdout.join('')}\n\n`
}
if (logs?.stderr.length) {
message += logs.stderr.join('')
}
logAndThrowError(`Error while running build${message}`)
}
return { newConfig, configMutations }
}
const bundleEdgeFunctions = async (options: DeployOptionValues, command: BaseCommand): Promise<void> => {
const argv = process.argv.slice(2)
const statusCb =
options.silent || argv.includes('--json') || argv.includes('--silent') ? () => {} : deployProgressCb()
statusCb({
type: 'edge-functions-bundling',
msg: 'Bundling edge functions...\n',
phase: 'start',
})
const { severityCode, success } = await runCoreSteps(['edge_functions_bundling'], {
...options,
packagePath: command.workspacePackage,
buffer: true,
featureFlags: edgeFunctionsFeatureFlags,
// We log our own progress so we don't want this as well. Plus, this logs much of the same
// information as the build that (likely) came before this as part of the deploy build.
quiet: options.debug ?? true,
// (cachedConfig type error hides this one, but it still is valid) @ts-expect-error FIXME(serhalp): This is missing from the `runCoreSteps` type in @netlify/build
edgeFunctionsBootstrapURL: await getBootstrapURL(),
// @ts-expect-error 'CachedConfig' is not assignable to type 'Record<string, unknown>'.
// Index signature for type 'string' is missing in type 'CachedConfig'.
cachedConfig: command.netlify.cachedConfig,
})
if (!success) {
statusCb({
type: 'edge-functions-bundling',
msg: 'Deploy aborted due to error while bundling edge functions',
phase: 'error',
})
exit(severityCode)
}
statusCb({
type: 'edge-functions-bundling',
msg: 'Finished bundling edge functions',
phase: 'stop',
})
}
interface JsonData {
site_id: string
site_name: string
deploy_id: string
deploy_url: string
logs: string
function_logs: string
edge_function_logs: string
url?: string
source_zip_filename?: string
}
const printResults = ({
deployToProduction,
uploadSourceZip,
json,
results,
runBuildCommand,
}: {
deployToProduction: boolean
uploadSourceZip: boolean
json: boolean
results: Awaited<ReturnType<typeof prepAndRunDeploy>>
runBuildCommand: boolean
}): void => {
const msgData: Record<string, string> = {
'Build logs': terminalLink(results.logsUrl, results.logsUrl, { fallback: false }),
'Function logs': terminalLink(results.functionLogsUrl, results.functionLogsUrl, { fallback: false }),
'Edge function Logs': terminalLink(results.edgeFunctionLogsUrl, results.edgeFunctionLogsUrl, { fallback: false }),
}
log('')
// Note: this is leakily mimicking the @netlify/build heading style
log(chalk.cyanBright.bold(`🚀 Deploy complete\n${'─'.repeat(64)}`))
// Json response for piping commands
if (json) {
const jsonData: JsonData = {
site_id: results.siteId,
site_name: results.siteName,
deploy_id: results.deployId,
deploy_url: results.deployUrl,
logs: results.logsUrl,
function_logs: results.functionLogsUrl,
edge_function_logs: results.edgeFunctionLogsUrl,
}
if (deployToProduction) {
jsonData.url = results.siteUrl
}
if (uploadSourceZip) {
jsonData.source_zip_filename = results.sourceZipFileName
}
logJson(jsonData)
exit(0)
} else {
const message = deployToProduction
? `Deployed to production URL: ${terminalLink(results.siteUrl, results.siteUrl, { fallback: false })}\n
Unique deploy URL: ${terminalLink(results.deployUrl, results.deployUrl, { fallback: false })}`
: `Deployed draft to ${terminalLink(results.deployUrl, results.deployUrl, { fallback: false })}`
log(
boxen(message, {
padding: 1,
margin: 1,
textAlignment: 'center',
borderStyle: 'round',
borderColor: NETLIFY_CYAN_HEX,
// This is an intentional half-width space to work around a unicode padding math bug in boxen
// eslint-disable-next-line no-irregular-whitespace
title: `⬥ ${deployToProduction ? 'Production deploy' : 'Draft deploy'} is live ⬥ `,
titleAlignment: 'center',
}),
)
log(prettyjson.render(msgData))
if (!deployToProduction) {
log()
log('If everything looks good on your draft URL, deploy it to your main project URL with the --prod flag:')
log(chalk.cyanBright.bold(`netlify deploy${runBuildCommand ? '' : ' --no-build'} --prod`))
log()
}
}
}
const prepAndRunDeploy = async ({
api,
command,
config,
deployToProduction,
options,
site,
siteData,
siteId,
workingDir,
deployId,
}: {
options: DeployOptionValues
command: BaseCommand
workingDir: string
deployId?: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- FIXME(serhalp)
[key: string]: any
}) => {
const alias = options.alias || options.branch
// if a context is passed besides dev, we need to pull env vars from that specific context
if (options.context && options.context !== 'dev') {
command.netlify.cachedConfig.env = await getEnvelopeEnv({
api,
context: options.context,
env: command.netlify.cachedConfig.env,
siteInfo: siteData,
})
}
const deployFolder = await getDeployFolder({ command, options, config, site, siteData })
const functionsFolder = getFunctionsFolder({ workingDir, options, config, site, siteData })
const { configPath } = site
// build flag wasn't used and edge functions directories exist
if (!options.build && (await anyEdgeFunctionsDirectoryExists(command))) {
// for the case of directories existing but not containing any edge functions,
// there is early bail in edge functions bundling after scanning for edge functions
// for this case and to avoid replicating scanning logic here, we defer to the bundling step
await bundleEdgeFunctions(options, command)
}
log('')
// Note: this is leakily mimicking the @netlify/build heading style
log(chalk.cyanBright.bold(`Deploying to Netlify\n${'─'.repeat(64)}`))
log('')
log(
prettyjson.render({
'Deploy path': deployFolder,
'Functions path': functionsFolder,
'Configuration path': configPath,
}),
)
log()
const { functionsFolderStat } = await validateFolders({
deployFolder,
functionsFolder,
})
const siteEnv = await getEnvelopeEnv({
api,
context: options.context,
env: command.netlify.cachedConfig.env,
raw: true,
scope: 'functions',
siteInfo: siteData,
})
const functionsConfig = normalizeFunctionsConfig({
functionsConfig: config.functions,
projectRoot: site.root,
siteEnv,
})
const results = await runDeploy({
// @ts-expect-error FIXME
alias,
api,
command,
config,
deployFolder,
deployTimeout: options.timeout ? options.timeout * SEC_TO_MILLISEC : DEFAULT_DEPLOY_TIMEOUT,
deployToProduction,
functionsConfig,
// pass undefined functionsFolder if doesn't exist
functionsFolder: functionsFolderStat && functionsFolder,
options,
packagePath: command.workspacePackage,
silent: options.json || options.silent,
site,
siteData,
siteId,
skipFunctionsCache: options.skipFunctionsCache,
title: options.message,
deployId,
})
return results
}
const validateTeamForSiteCreation = (
accounts: { slug: string; name: string }[],
options: DeployOptionValues,
siteName?: string,
) => {
if (accounts.length === 0) {
return logAndThrowError('No teams available. Please ensure you have access to at least one team.')
}
if (accounts.length === 1) {
options.team = accounts[0].slug
const message = siteName ? `Creating new site: ${siteName}` : 'Creating new site with random name'
log(`${message} (using team: ${accounts[0].name})`)
return
}
const availableTeams = accounts.map((team) => team.slug).join(', ')
return logAndThrowError(
`Multiple teams available. Please specify which team to use with --team flag.\n` +
`Available teams: ${availableTeams}\n\n` +
`Example: netlify deploy --create-site${siteName ? ` ${siteName}` : ''} --team <TEAM_SLUG>`,
)
}
const createSiteWithFlags = async (options: DeployOptionValues, command: BaseCommand, site: $TSFixMe) => {
const { accounts } = command.netlify
const siteName = typeof options.createSite === 'string' ? options.createSite : undefined
if (!options.team) {
validateTeamForSiteCreation(accounts, options, siteName)
} else {
const message = siteName ? `Creating new site: ${siteName}` : 'Creating new site with random name'
log(message)
}
// Create site directly via API to bypass interactive prompts
const { api } = command.netlify
const body: { name?: string } = {}
if (siteName) {
body.name = siteName.trim()
}
if (!options.team) {
throw new Error('Team must be specified to create a site')
}
try {
const siteData = await api.createSiteInTeam({
accountSlug: options.team,
body,
})