-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathcreate-mobify-app.js
More file actions
executable file
·1259 lines (1141 loc) · 44 KB
/
create-mobify-app.js
File metadata and controls
executable file
·1259 lines (1141 loc) · 44 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
#!/usr/bin/env node
/*
* Copyright (c) 2023, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable @typescript-eslint/no-var-requires */
/**
* This is a generator for PWA Kit projects that run on the Managed Runtime.
*
* The output of this script is a copy of a project template with the following changes:
*
* 1) We update any monorepo-local dependencies to be installed through NPM.
*
* 2) We rename the template and configure the generated project based on answers to
* questions that we ask the user on the CLI.
*
* ## Basic usage
*
* We expect end-users to generate projects by running `npx @salesforce/pwa-kit-create-app` on
* the CLI and following the prompts. Users must be able to run that command without
* installing any dependencies first.
*
* ## Advanced usage and integration testing:
*
* For testing on CI we need to be able to generate projects without running
* the interactive prompts on the CLI. To support these cases, we have
* a few presets that are "private" and only usable through the GENERATOR_PRESET
* env var – this keeps them out of the --help docs.
*
* If both the GENERATOR_PRESET env var and --preset arguments are passed, the
* option set in --preset is used.
*/
const p = require('path')
const fs = require('fs')
const os = require('os')
const child_proc = require('child_process')
const {Command} = require('commander')
const inquirer = require('inquirer')
const {URL} = require('url')
const deepmerge = require('deepmerge')
const sh = require('shelljs')
const tar = require('tar')
const semver = require('semver')
const slugify = require('slugify')
const generatorPkg = require('../package.json')
const Handlebars = require('handlebars')
const program = new Command()
sh.set('-e')
// Handlebars helpers
// Our eslint script uses exscaped double quotes to have windows compatibility. This helper
// will ensure those escaped double quotes are still escaped after processing the template.
Handlebars.registerHelper('script', (object) => object.replaceAll('"', '\\"'))
// Validations
const validPreset = (preset) => {
return ALL_PRESET_NAMES.includes(preset)
}
const validProjectName = (s) => {
if (s.length > PROJECT_ID_MAX_LENGTH) {
return `Maximum length is ${PROJECT_ID_MAX_LENGTH} characters.`
}
const regex = new RegExp(`^[a-zA-Z0-9-\\s]{1,${PROJECT_ID_MAX_LENGTH}}$`)
return regex.test(s) || 'Value can only contain letters, numbers, space and hyphens.'
}
const validAppExtensionNameRegex = /^(@[a-zA-Z0-9-_]+\/)?extension-[a-zA-Z0-9-_]+$/
const validProjectAppExtensionName = (input) => {
if (!validAppExtensionNameRegex.test(input)) {
return 'The Application Extension name must follow the format @{namespace}/extension-{package-name} (namespace is optional).'
}
return true
}
const validUrl = (s) => {
try {
new URL(s)
return true
} catch (err) {
return 'Value must be an absolute URL'
}
}
const validSiteId = (s) =>
/^[a-z0-9_-]+$/i.test(s) || 'Valid characters are alphanumeric, hyphen, or underscore'
// To see definitions for Commerce API configuration values, go to
// https://developer.salesforce.com/docs/commerce/commerce-api/guide/commerce-api-configuration-values.
const defaultCommerceAPIError =
'Invalid format. Use docs to find more information about valid configurations: https://developer.salesforce.com/docs/commerce/commerce-api/guide/commerce-api-configuration-values'
const validShortCode = (s) => /(^[0-9A-Z]{8}$)/i.test(s) || defaultCommerceAPIError
const validClientId = (s) =>
/(^[0-9A-Z]{8}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{12}$)/i.test(s) ||
s === 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ||
defaultCommerceAPIError
const validOrganizationId = (s) =>
/^(f_ecom)_([A-Z]{4})_(prd|stg|dev|[0-9]{3}|s[0-9]{2})$/i.test(s) || defaultCommerceAPIError
// Globals
const GENERATED_PROJECT_VERSION = '0.0.1'
const INITIAL_CONTEXT = {
preset: undefined,
answers: {
general: {},
project: {}
}
}
const TEMPLATE_SOURCE_NPM = 'npm'
const TEMPLATE_SOURCE_BUNDLE = 'bundle'
const DEFAULT_TEMPLATE_VERSION = 'latest'
const LOCAL_DEV_PROJECT_DIR = 'sample-app'
const INITIAL_QUESTION = [
{
name: 'project.type',
message: 'What type of PWA Kit project would you like to create?',
type: 'list',
choices: [
{name: 'PWA Kit Application', value: 'PWAKitAppProject'},
{
name: 'PWA Kit Application Extension',
value: 'PWAKitAppExtensionProject'
}
],
default: 'PWAKitAppProject'
}
]
const askApplicationExtensibilityQuestions = (availableAppExtensions) => {
return [
{
name: 'project.useAppExtensibility',
message: 'Do you want to use Application Extensibility?',
type: 'confirm',
default: true
},
{
name: 'project.selectedAppExtensions',
message: 'Which Application Extensions do you want to install?',
type: 'checkbox',
choices: availableAppExtensions,
when: (answers) => answers.project.useAppExtensibility === true
},
{
name: 'project.extractAppExtensions',
message:
'⚠️ WARNING: If you choose to extract the Application Extension code,\n' +
'you will NO LONGER be able to consume upgrades from NPM. All changes\n' +
'made to the extracted code will be YOUR RESPONSIBILITY.\n' +
'\n' +
'Do you want to proceed with extracting the Application Extensions code?',
type: 'confirm',
default: false,
when: (answers) => answers.project.useAppExtensibility === true
}
]
}
const APPLICATION_EXTENSION_QUESTIONS = [
{
name: 'project.extensionName',
message:
'What is the name of your Application Extension? \n' +
'The name must follow the pattern "@{namespace}/extension-{package-name}", where namespace is optional.',
validate: validProjectAppExtensionName
}
]
const EXTENSIBILITY_QUESTIONS = [
{
name: 'project.extend',
message: 'Do you wish to use template extensibility?',
type: 'list',
choices: [
{
name: 'No',
value: false
},
{
name: 'Yes',
value: true
}
]
}
]
const HYBRID_QUESTIONS = [
{
name: 'project.hybrid',
message: 'Do you wish to set up a phased headless rollout?',
type: 'list',
choices: [
{
name: 'No',
value: false
},
{
name: 'Yes',
value: true
}
]
}
]
const MRT_REFERENCE_QUESTIONS = [
{
name: 'project.name',
validate: validProjectName,
message: 'What is the name of your Project?'
}
]
const EXPRESS_MINIMAL_QUESTIONS = [
{
name: 'project.name',
validate: validProjectName,
message: 'What is the name of your Project?'
}
]
const TYPESCRIPT_MINIMAL_QUESTIONS = [
{
name: 'project.name',
validate: validProjectName,
message: 'What is the name of your Project?'
}
]
const RETAIL_REACT_APP_QUESTIONS = [
{
name: 'project.name',
validate: validProjectName,
message: 'What is the name of your Project?'
},
{
name: 'project.commerce.instanceUrl',
message: 'What is the URL for your Commerce Cloud instance?',
validate: validUrl
},
{
name: 'project.commerce.clientId',
message: 'What is your SLAS Client ID?',
validate: validClientId
},
{
name: 'project.commerce.isSlasPrivate',
message: 'Is your SLAS client private?',
type: 'list',
choices: [
{
name: 'Yes',
value: true
},
{
name: 'No',
value: false
}
]
},
{
name: 'project.commerce.siteId',
message: 'What is your Site ID in Business Manager?',
validate: validSiteId
},
{
name: 'project.commerce.organizationId',
message: 'What is your Commerce API organization ID in Business Manager?',
validate: validOrganizationId
},
{
name: 'project.commerce.shortCode',
message: 'What is your Commerce API short code in Business Manager?',
validate: validShortCode
}
]
// Project dictionary describing details and how the gerator should ask questions etc.
const PRESETS = [
{
id: 'retail-react-app',
name: 'Retail React App',
description: `
Generate a project using custom settings by answering questions about a
B2C Commerce instance.
Use this preset to connect to an existing instance, such as a sandbox.
`,
shortDescription: 'The Retail app using your own Commerce Cloud instance',
templateSource: {
type: TEMPLATE_SOURCE_NPM,
id: '@salesforce/retail-react-app'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
assets: ['translations'],
private: false
},
{
id: 'retail-react-app-demo',
name: 'Retail React App Demo',
description: `
Generate a project using the settings for a special B2C Commerce
instance that is used for demo purposes. No questions are asked.
Use this preset to try out PWA Kit.
`,
shortDescription: 'The Retail app with demo Commerce Cloud instance',
templateSource: {
type: TEMPLATE_SOURCE_NPM,
id: '@salesforce/retail-react-app'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
answers: {
['project.extend']: true,
['project.hybrid']: false,
['project.name']: 'demo-storefront',
['project.commerce.instanceUrl']: 'https://zzte-053.dx.commercecloud.salesforce.com',
['project.commerce.clientId']: '1d763261-6522-4913-9d52-5d947d3b94c4',
['project.commerce.siteId']: 'RefArch',
['project.commerce.organizationId']: 'f_ecom_zzte_053',
['project.commerce.shortCode']: 'kv7kzm78',
['project.commerce.isSlasPrivate']: false,
['project.einstein.clientId']: '1ea06c6e-c936-4324-bcf0-fada93f83bb1',
['project.einstein.siteId']: 'aaij-MobileFirst'
},
assets: ['translations'],
private: false
},
{
id: 'retail-react-app-test-project',
name: 'Retail React App Test Project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'typescript-minimal'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
answers: {
['project.extend']: false,
['project.hybrid']: false,
['project.extractAppExtensions']: true,
['project.type']: 'PWAKitAppProject',
['project.useApplicationExtensibility']: true,
['project.selectedAppExtensions']: [
'@salesforce/extension-chakra-storefront',
'@salesforce/extension-chakra-store-locator'
],
['project.name']: 'retail-react-app',
['project.commerce.instanceUrl']: 'https://zzrf-001.dx.commercecloud.salesforce.com',
['project.commerce.clientId']: 'c9c45bfd-0ed3-4aa2-9971-40f88962b836',
['project.commerce.siteId']: 'RefArch',
['project.commerce.organizationId']: 'f_ecom_zzrf_001',
['project.commerce.shortCode']: 'kv7kzm78',
['project.commerce.isSlasPrivate']: false,
['project.einstein.clientId']: '1ea06c6e-c936-4324-bcf0-fada93f83bb1',
['project.einstein.siteId']: 'aaij-MobileFirst'
},
assets: ['translations'],
private: true
},
{
id: 'retail-react-app-private-slas-client',
name: 'Retail React App Private SLAS client project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_NPM,
id: '@salesforce/retail-react-app'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
answers: {
['project.extend']: true,
['project.hybrid']: false,
['project.name']: 'retail-react-app',
['project.commerce.instanceUrl']: 'https://zzrf-002.dx.commercecloud.salesforce.com',
['project.commerce.clientId']: '89655706-9a0d-49ba-a1e5-18bb2d616374',
['project.commerce.siteId']: 'RefArch',
['project.commerce.organizationId']: 'f_ecom_zzrf_002',
['project.commerce.shortCode']: 'kv7kzm78',
['project.commerce.isSlasPrivate']: true,
['project.einstein.clientId']: '1ea06c6e-c936-4324-bcf0-fada93f83bb1',
['project.einstein.siteId']: 'aaij-MobileFirst'
},
assets: ['translations'],
private: true
},
{
id: 'retail-react-app-hybrid-test-project',
name: 'Retail React App Hybrid Test Private SLAS Project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_NPM,
id: '@salesforce/retail-react-app'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...HYBRID_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
answers: {
['project.extend']: true,
['project.hybrid']: true,
['project.name']: 'retail-react-app',
['project.commerce.instanceUrl']: 'https://test.phased-launch-testing.com/',
['project.commerce.clientId']: '99b4e081-00cf-454a-95b0-26ac2b824931',
['project.commerce.siteId']: 'RefArch',
['project.commerce.organizationId']: 'f_ecom_bdpx_dev',
['project.commerce.shortCode']: 'xitgmcd3',
['project.einstein.clientId']: '1ea06c6e-c936-4324-bcf0-fada93f83bb1',
['project.einstein.siteId']: 'aaij-MobileFirst',
['project.commerce.isSlasPrivate']: true
},
assets: ['translations'],
private: true
},
{
id: 'retail-react-app-hybrid-public-client-test-project',
name: 'Retail React App Hybrid Test Public SLAS client project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_NPM,
id: '@salesforce/retail-react-app'
},
questions: [...EXTENSIBILITY_QUESTIONS, ...HYBRID_QUESTIONS, ...RETAIL_REACT_APP_QUESTIONS],
answers: {
['project.extend']: true,
['project.hybrid']: true,
['project.name']: 'retail-react-app',
['project.commerce.instanceUrl']: 'https://www.phased-launch-testing.com/',
['project.commerce.clientId']: 'e7e22b7f-a904-4f3a-8022-49dbee696485',
['project.commerce.siteId']: 'RefArch',
['project.commerce.organizationId']: 'f_ecom_bjnl_prd',
['project.commerce.shortCode']: 'performance-001',
['project.einstein.clientId']: '1ea06c6e-c936-4324-bcf0-fada93f83bb1',
['project.einstein.siteId']: 'aaij-MobileFirst',
['project.commerce.isSlasPrivate']: false
},
assets: ['translations'],
private: true
},
{
id: 'typescript-minimal-test-project',
name: 'Template Minimal Test Project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'typescript-minimal'
},
private: true
},
{
id: 'typescript-minimal',
name: 'Template Minimal Project',
description: `
Generate a project using a bare-bones TypeScript app template.
Use this as a TypeScript starting point or as a base on top of
which to build new TypeScript project templates for Managed Runtime.
`,
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'typescript-minimal'
},
questions: TYPESCRIPT_MINIMAL_QUESTIONS,
private: true
},
{
id: 'express-minimal-test-project',
name: 'Express Minimal Test Project',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'express-minimal'
},
questions: EXPRESS_MINIMAL_QUESTIONS,
answers: {
['project.name']: 'express-minimal'
},
private: true
},
{
id: 'express-minimal',
name: 'Express Minimal Project',
description: `
Generate a project using a bare-bones express app template.
Use this as a starting point for APIs or as a base on top of
which to build new project templates for Managed Runtime.
`,
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'express-minimal'
},
questions: EXPRESS_MINIMAL_QUESTIONS,
private: true
},
{
id: 'mrt-reference-app',
name: 'Managed Runtime Reference App',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'mrt-reference-app'
},
questions: MRT_REFERENCE_QUESTIONS,
answers: {
['project.name']: 'mrt-reference-app'
},
private: true
},
{
id: 'extension-base',
name: 'Template base Application Extension',
description: '',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'extension-base'
},
private: true
},
{
id: 'app-extension-sample-extract',
name: 'Application Extension sample project (Extract Application Extensions code)',
description:
'Generate an Application Extension using typescript-minimal template with the Application Extensions code extracted.',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'typescript-minimal'
},
questions: TYPESCRIPT_MINIMAL_QUESTIONS,
answers: {
['project.name']: 'app-extension-sample-extract',
['project.selectedAppExtensions']: ['extension-sample'],
['project.extractAppExtensions']: true
},
private: true
},
{
id: 'app-extension-sample-no-extract',
name: 'Application Extension sample project (Without extracting Application Extensions code)',
description:
'Generate an Application Extension using typescript-minimal template without the Applications Extensions code extracted.',
templateSource: {
type: TEMPLATE_SOURCE_BUNDLE,
id: 'typescript-minimal'
},
questions: TYPESCRIPT_MINIMAL_QUESTIONS,
answers: {
['project.name']: 'app-extension-sample-no-extract',
['project.selectedAppExtensions']: ['extension-sample'],
['project.extractAppExtensions']: false
},
private: true
}
]
const PRESET_QUESTIONS = [
{
name: 'general.presetId',
message: 'Choose a project preset to get started:',
type: 'list',
choices: PRESETS.filter(({private}) => !private).map(({shortDescription, id}) => ({
name: shortDescription,
value: id
}))
}
]
const BOOTSTRAP_DIR = p.join(__dirname, '..', 'assets', 'bootstrap', 'js')
const ASSETS_TEMPLATES_DIR = p.join(__dirname, '..', 'assets', 'templates')
const PRIVATE_PRESET_NAMES = PRESETS.filter(({private}) => !!private).map(({id}) => id)
const PUBLIC_PRESET_NAMES = PRESETS.filter(({private}) => !private).map(({id}) => id)
const ALL_PRESET_NAMES = PRIVATE_PRESET_NAMES.concat(PUBLIC_PRESET_NAMES)
const PROJECT_ID_MAX_LENGTH = 20
// Utilities
const readJson = (path) => JSON.parse(sh.cat(path))
const writeJson = (path, data) => new sh.ShellString(JSON.stringify(data, null, 2)).to(path)
/**
* Updates the `package.json` file in place by merging new updates with the existing content.
*
* @param {string} pkgJsonPath - The file path to the `package.json` file that needs to be updated.
* @param {Object} updates - An object containing the updates to be merged into the existing `package.json`.
*/
const updatePackageJson = (pkgJsonPath, updates) => {
const pkgJSON = readJson(pkgJsonPath)
const finalPkgData = merge(pkgJSON, updates)
writeJson(pkgJsonPath, finalPkgData)
}
const slugifyName = (name) =>
slugify(name, {
lower: true,
strict: true
}).slice(0, PROJECT_ID_MAX_LENGTH)
const getSlugifiedProjectName = (projectName) => {
// Split the project name into namespace and name if it's in the format @namespace/name
const [slugifiedNamespace, slugifiedName] = projectName.includes('/')
? projectName.split('/').map(slugifyName)
: ['', slugifyName(projectName)]
return slugifiedNamespace ? `@${slugifiedNamespace}/${slugifiedName}` : slugifiedName
}
/**
* Check if the provided path is an empty directory.
* @param {*} path
* @returns
*/
const isDirEmpty = (path) => fs.readdirSync(path).length === 0
/**
* Logs an error and exits the process if the provided path points at a
* non-empty directory.
*
* @param {*} path
*/
const checkOutputDir = (path) => {
if (sh.test('-e', path) && !isDirEmpty(path)) {
console.error(
`The output directory "${path}" already exists. Try, for example, ` +
`"~/Desktop/my-project" instead of "~/Desktop"`
)
process.exit(1)
}
}
/**
* Returns a list of absolute file paths for a given folder. This will recursively
* list files in child folders.
*
* @param {*} dirPath
* @param {*} arrayOfFiles
* @returns
*/
const getFiles = (dirPath, arrayOfFiles = []) => {
const files = fs.readdirSync(dirPath)
files.forEach((file) => {
if (fs.statSync(p.join(dirPath, file)).isDirectory()) {
arrayOfFiles = getFiles(p.join(dirPath, file), arrayOfFiles)
} else {
arrayOfFiles.push(p.join(dirPath, file))
}
})
return arrayOfFiles
}
/**
* Deeply merge two objects in such a way that all array entries in b replace array
* entries in a, eg:
*
* merge(
* {foo: 'foo', items: [{thing: 'a'}]},
* {bar: 'bar', items: [{thing: 'b'}]}
* )
* > {foo: 'foo', bar: 'bar', items: [{thing: 'b'}]}
*
* @param a
* @param b
* @return {*}
*/
const merge = (a, b) => deepmerge(a, b, {arrayMerge: (orignal, replacement) => replacement})
/**
* Provided a dot notation key, and a value, return an expanded object splitting
* the key.
*
* @example
* const expandedObj = expand('parent.child.grandchild': { name: 'Preseley' })
* console.log(expandedObj) // {parent: { child: {grandchild: {name: 'Presley}}}}
*
* @param {string} key
* @param {Object} value
* @returns
*
*/
const expandKey = (key, value) =>
key
.split('.')
.reverse()
.reduce(
(acc, curr) =>
acc
? {
[curr]: acc
}
: {
[curr]: value
},
undefined
)
/**
* Creates an .npmignore file at the root of the generated project.
* Ensures the specified directories and files are excluded from being published to npm.
*
* @param {string} outputDir - The path to the root of the generated project.
* @param {string[]} ignorePaths - An array of directory or file paths to ignore in the npm package.
*/
const createNpmIgnoreFile = (outputDir, ignorePaths = []) => {
const npmIgnoreContent = ignorePaths.join('\n') + '\n'
fs.writeFileSync(p.join(outputDir, '.npmignore'), npmIgnoreContent)
}
/**
* Provided an object there the keys use "dot notation", expand each individual key.
* NOTE: This only expands keys at the root level, and not those nested.
*
* @example
* const expandedObj = expand({'coolthings.babynames': 'Preseley', 'coolthings.cars': 'bmws'})
* console.log(expandedObj) // {coolthings: { babynames: 'Presley', cars: 'bmws'}}
*
* @param {Object} answers
* @returns {Object} The expanded object.
*
*/
const expandObject = (obj = {}) =>
Object.keys(obj).reduce((acc, curr) => merge(acc, expandKey(curr, obj[curr])), {})
/**
* Envoke the "npm install" command for the provided project directory.
*
* @param {*} outputDir
* @param {*} param1
*/
const npmInstall = (outputDir, {verbose, projectName}) => {
console.log(`Installing dependencies${
projectName ? ` for ${projectName}` : ''
}... This may take a few minutes.
`)
const npmLogLevel = verbose ? 'notice' : 'error'
const disableStdOut = ['inherit', 'ignore', 'inherit']
const stdio = verbose ? 'inherit' : disableStdOut
try {
child_proc.execSync(`npm install --color always --loglevel ${npmLogLevel}`, {
cwd: outputDir,
stdio,
env: {
...process.env,
OPENCOLLECTIVE_HIDE: 'true',
DISABLE_OPENCOLLECTIVE: 'true',
OPEN_SOURCE_CONTRIBUTOR: 'true'
}
})
} catch {
// error is already displayed on the console by child process.
// exit the program
process.exit(1)
}
}
/**
* Execute and copy the handlebars template to the output directory using
* the provided context object. If the file isn't a template, simply copy
* it to the destination.
*
* @param {string} inputFile
* @param {string} outputDir
* @param {Object} context
*/
const processTemplate = (relFile, inputDir, outputDir, context) => {
const inputFile = p.join(inputDir, relFile)
const outputFile = p.join(outputDir, relFile)
const destDir = p.join(outputFile, '..')
// Create folder if we are doing a deep copy
if (destDir) {
fs.mkdirSync(destDir, {recursive: true})
}
if (inputFile.endsWith('.hbs')) {
const template = sh.cat(inputFile).stdout
fs.writeFileSync(outputFile.replace('.hbs', ''), Handlebars.compile(template)(context))
} else {
fs.copyFileSync(inputFile, outputFile)
}
}
/**
* Process the Application Extensions into the application-extensions directory.
*
* @param appExtensions - An array of the Application Extension names.
* @param extractAppExtensions - A boolean indicating whether to extract the Application Extensions code from the npm package
* @param appExtensionsDir - The path to the application-extensions directory.
*/
const processAppExtensions = (
appExtensions = [],
extractAppExtensions = false,
appExtensionsDir
) => {
if (appExtensions.length > 0 && extractAppExtensions) {
appExtensions.forEach((appExtensionName) => {
// Create the full path for the temporary directory, preserving the namespace
const appExtensionTmp = p.join(os.tmpdir(), `extract-${appExtensionName}`)
fs.mkdirSync(appExtensionTmp, {recursive: true})
const appExtensionTarFile = sh
.exec(`npm pack ${appExtensionName} --pack-destination="${appExtensionTmp}"`, {
silent: true
})
.stdout.trim()
const appExtensionTarPath = p.join(appExtensionTmp, appExtensionTarFile)
// Extract the Application Extension
tar.x({
file: appExtensionTarPath,
cwd: appExtensionTmp,
sync: true
})
// Copy the Application Extension into the appropriate folder inside application-extensions
const appExtensionTmpPath = p.join(appExtensionTmp, 'package')
const appExtensionDestDir = p.join(appExtensionsDir, appExtensionName)
sh.mkdir('-p', appExtensionDestDir)
sh.cp('-rf', p.join(appExtensionTmpPath, '*'), appExtensionDestDir)
// Clean up the temporary Application Extension directory
sh.rm('-rf', appExtensionTmp)
})
}
}
/**
* Fetch available Application Extensions using npm search command.
* The command searches for packages starting with '@salesforce/extension-'.
*
* Currently, the npm search command is not returning the expected results for known extension packages.
* Therefore, we are using a static value to ensure the correct extensions are available.
*
* @returns {Array} A list of available Application Extension names and their versions.
*/
const fetchAvailableAppExtensions = () => {
const filePath = p.join(__dirname, '..', 'assets', 'available-app-extensions.json')
try {
const data = fs.readFileSync(filePath)
const staticResult = JSON.parse(data)
// Use the static result for names but always use the npm label "latest" for versions
return staticResult.map((pkg) => {
return {
name: pkg.name,
value: pkg.name,
version: 'latest'
}
})
} catch (error) {
console.error('Failed to fetch Application Extensions:', error.message)
return []
}
}
/**
* This function does the bulk of the project generation given the project config
* object and the answers returned from the survey process.
*
* @param {*} preset
* @param {*} answers
* @param {*} param2
*/
const runGenerator = async (
context,
{outputDir, templateVersion, verbose, installDependencies = true}
) => {
const {answers, preset} = context
const {templateSource} = preset
const {
extend = false,
selectedAppExtensions = [],
extractAppExtensions = false
} = answers.project
// Check if the output directory doesn't already exist.
checkOutputDir(outputDir)
// Ensure the output directory exists
fs.mkdirSync(outputDir, {recursive: true})
// We need to get some assets from the base template. So extract it after
// downloading from NPM or copying from the template bundle folder.
const tmp = fs.mkdtempSync(p.resolve(os.tmpdir(), 'extract-template'))
const packagePath = p.join(tmp, 'package')
const appExtensionsDir = p.join(outputDir, 'app', 'application-extensions')
const {id, type} = templateSource
let tarPath
switch (type) {
case TEMPLATE_SOURCE_NPM: {
const tarFile = sh
.exec(`npm pack ${id}@${templateVersion} --pack-destination="${tmp}"`, {
silent: true
})
.stdout.trim()
tarPath = p.join(tmp, tarFile)
break
}
case TEMPLATE_SOURCE_BUNDLE:
tarPath = p.join(__dirname, '..', 'templates', `${id}.tar.gz`)
break
default: {
const msg = `Error: Cannot handle template source type ${type}.`
console.error(msg)
process.exit(1)
}
}
// Extract the main template
tar.x({
file: tarPath,
cwd: tmp,
sync: true
})
// Copy the base template either from the package or npm.
sh.cp('-rf', p.join(packagePath, '{*,.*}'), outputDir)
// Copy template specific assets over.
const assetsDir = p.join(ASSETS_TEMPLATES_DIR, id)
if (sh.test('-e', assetsDir)) {
getFiles(assetsDir)
.map((file) => {
const relFilePath = file.replace(assetsDir, '')
return relFilePath
})
.forEach((relFilePath) => {
processTemplate(relFilePath, assetsDir, outputDir, context)
})
}
// Check project type and handle appropriately
if (answers.project.type === 'PWAKitAppExtensionProject') {
const devOutputDir = p.join(outputDir, LOCAL_DEV_PROJECT_DIR)
// Update the root package.json to add a start script
updatePackageJson(p.resolve(outputDir, 'package.json'), {
scripts: {
start: `npm --prefix ./${LOCAL_DEV_PROJECT_DIR} start`,
'start:inspect': `npm --prefix ./${LOCAL_DEV_PROJECT_DIR} run start:inspect`
}
})
// Recursively call runGenerator for the 'typescript-minimal' local dev project
const localDevProjectContext = {
...context,
preset: {
id: 'typescript-minimal',
templateSource: {type: TEMPLATE_SOURCE_BUNDLE, id: 'typescript-minimal'},
private: true
},
answers: {project: {type: 'PWAKitAppProject', name: 'sample-app'}}
}
await runGenerator(localDevProjectContext, {
outputDir: devOutputDir,
templateVersion,
verbose,
installDependencies: false
})
// Update the typescript-minimal dev package.json with dependencies
updatePackageJson(p.resolve(devOutputDir, 'package.json'), {
devDependencies: {[answers.project.name]: 'file:../'},
mobify: {app: {extensions: [answers.project.name]}}
})
// TODO: The generator is growing, we should refactor this to be more maintainable.
const processGeneratedExtension = () => {
// do a file content replacement for extension-meta.json in the outputDir
// find all instances of "@salesforce/extension-base" and replace with answers.project.name
const extensionMetaJsonPath = p.join(outputDir, 'extension-meta.json')
if (fs.existsSync(extensionMetaJsonPath)) {
let extensionMetaJsonContent = fs.readFileSync(extensionMetaJsonPath, 'utf8')
extensionMetaJsonContent = extensionMetaJsonContent.replace(
/@salesforce\/extension-base/g,
answers.project.name
)
fs.writeFileSync(extensionMetaJsonPath, extensionMetaJsonContent)
}
}
processGeneratedExtension()
// Create the .npmignore file, excluding the typescript-minimal local dev project folder