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
546import { prettyPath } from '@ionic/utils-terminal';
import { readJSON, pathExists } from 'fs-extra';
import { dirname, join } from 'path';
import c from './colors';
import type { Config, PackageJson } from './definitions';
import { fatal } from './errors';
import { output, logger } from './log';
import { getPlugins } from './plugin';
import { findNXMonorepoRoot, isNXMonorepo } from './util/monorepotools';
import { resolveNode } from './util/node';
import { runCommand } from './util/subprocess';
export type CheckFunction = () => Promise<string | null>;
export async function check(checks: CheckFunction[]): Promise<void> {
const results = await Promise.all(checks.map((f) => f()));
const errors = results.filter((r) => r != null) as string[];
if (errors.length > 0) {
throw errors.join('\n');
}
}
export async function checkWebDir(config: Config): Promise<string | null> {
// We can skip checking the web dir if a server URL is set.
if (config.app.extConfig.server?.url) {
return null;
}
const invalidFolders = ['', '.', '..', '../', './'];
if (invalidFolders.includes(config.app.webDir)) {
return `"${config.app.webDir}" is not a valid value for webDir`;
}
if (!(await pathExists(config.app.webDirAbs))) {
return (
`Could not find the web assets directory: ${c.strong(prettyPath(config.app.webDirAbs))}.\n` +
`Please create it and make sure it has an ${c.strong(
'index.html',
)} file. You can change the path of this directory in ${c.strong(config.app.extConfigName)} (${c.input(
'webDir',
)} option). You may need to compile the web assets for your app (typically ${c.input(
'npm run build',
)}). More info: ${c.strong('https://capacitorjs.com/docs/basics/workflow#sync-your-project')}`
);
}
if (!(await pathExists(join(config.app.webDirAbs, 'index.html')))) {
return (
`The web assets directory (${c.strong(
prettyPath(config.app.webDirAbs),
)}) must contain an ${c.strong('index.html')} file.\n` +
`It will be the entry point for the web portion of the Capacitor app.`
);
}
return null;
}
export async function checkPackage(): Promise<string | null> {
if (!(await pathExists('package.json'))) {
if (await pathExists('project.json')) {
return null;
} else {
return (
`The Capacitor CLI needs to run at the root of an npm package or in a valid NX monorepo.\n` +
`Make sure you have a package.json or project.json file in the directory where you run the Capacitor CLI.\n` +
`More info: ${c.strong('https://docs.npmjs.com/cli/init')}`
);
}
}
return null;
}
export async function checkCapacitorPlatform(config: Config, platform: string): Promise<string | null> {
const pkg = await getCapacitorPackage(config, platform);
if (!pkg) {
return (
`Could not find the ${c.input(platform)} platform.\n` +
`You must install it in your project first, e.g. w/ ${c.input(`npm install @capacitor/${platform}`)}`
);
}
return null;
}
export async function checkAppConfig(config: Config): Promise<string | null> {
if (!config.app.appId) {
return (
`Missing ${c.input('appId')} for new platform.\n` +
`Please add it in ${config.app.extConfigName} or run ${c.input('npx cap init')}.`
);
}
if (!config.app.appName) {
return (
`Missing ${c.input('appName')} for new platform.\n` +
`Please add it in ${config.app.extConfigName} or run ${c.input('npx cap init')}.`
);
}
const appIdError = await checkAppId(config, config.app.appId);
if (appIdError) {
return appIdError;
}
const appNameError = await checkAppName(config, config.app.appName);
if (appNameError) {
return appNameError;
}
return null;
}
export async function checkAppDir(config: Config, dir: string): Promise<string | null> {
if (!/^\S*$/.test(dir)) {
return `Your app directory should not contain spaces`;
}
return null;
}
export async function checkAppId(config: Config, id: string): Promise<string | null> {
if (!id) {
return `Invalid App ID. App ID is required and cannot be blank.`;
}
if (/^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)+$/.test(id.toLowerCase())) {
return null;
}
return `
Invalid App ID "${id}". Your App ID must meet the following requirements to be valid on both iOS and Android:
- Must be in Java package form with no dashes (ex: com.example.app)
- It must have at least two segments (one or more dots).
- Each segment must start with a letter.
- All characters must be alphanumeric or an underscore [a-zA-Z][a-zA-Z0-9]+.
If you would like to skip validation, run "cap init" with the "--skip-appid-validation" flag.
`;
}
export async function checkAppName(config: Config, name: string): Promise<string | null> {
// We allow pretty much anything right now, have fun
if (!name?.length) {
return `Must provide an app name. For example: 'Spacebook'`;
}
return null;
}
export async function wait(time: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, time));
}
export async function runHooks(config: Config, platformName: string, dir: string, hook: string): Promise<void> {
await runPlatformHook(config, platformName, dir, hook);
const allPlugins = await getPlugins(config, platformName);
for (const p of allPlugins) {
await runPlatformHook(config, platformName, p.rootPath, hook);
}
}
export async function runPlatformHook(
config: Config,
platformName: string,
platformDir: string,
hook: string,
): Promise<void> {
const { spawn } = await import('child_process');
let pkg;
if (isNXMonorepo(platformDir)) {
pkg = await readJSON(join(findNXMonorepoRoot(platformDir), 'package.json'));
} else {
pkg = await readJSON(join(platformDir, 'package.json'));
}
const cmd = pkg.scripts?.[hook];
if (!cmd) {
return;
}
return new Promise((resolve, reject) => {
const p = spawn(cmd, {
stdio: 'inherit',
shell: true,
cwd: platformDir,
env: {
INIT_CWD: platformDir,
CAPACITOR_ROOT_DIR: config.app.rootDir,
CAPACITOR_WEB_DIR: config.app.webDirAbs,
CAPACITOR_CONFIG: JSON.stringify(config.app.extConfig),
CAPACITOR_PLATFORM_NAME: platformName,
...process.env,
},
});
p.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(
new Error(`${hook} hook on ${platformName} failed with error code: ${code} while running command: ${cmd}`),
);
}
});
p.on('error', (err) => {
reject(err);
});
});
}
export interface RunTaskOptions {
spinner?: boolean;
}
export async function runTask<T>(title: string, fn: () => Promise<T>): Promise<T> {
const chain = output.createTaskChain();
chain.next(title);
try {
const value = await fn();
chain.end();
return value;
} catch (e) {
chain.fail();
throw e;
}
}
export async function getCapacitorPackage(config: Config, name: string): Promise<PackageJson | null> {
const packagePath = resolveNode(config.app.rootDir, `@capacitor/${name}`, 'package.json');
if (!packagePath) {
return null;
}
return readJSON(packagePath);
}
export async function requireCapacitorPackage(config: Config, name: string): Promise<PackageJson> {
const pkg = await getCapacitorPackage(config, name);
if (!pkg) {
fatal(
`Unable to find node_modules/@capacitor/${name}.\n` +
`Are you sure ${c.strong(`@capacitor/${name}`)} is installed?`,
);
}
return pkg;
}
export async function getCapacitorPackageVersion(config: Config, platform: string): Promise<string> {
return (await requireCapacitorPackage(config, platform)).version;
}
export async function getCoreVersion(config: Config): Promise<string> {
return getCapacitorPackageVersion(config, 'core');
}
export async function getCLIVersion(config: Config): Promise<string> {
return getCapacitorPackageVersion(config, 'cli');
}
function getPlatformDirectory(config: Config, platform: string): string | null {
switch (platform) {
case 'android':
return config.android.platformDirAbs;
case 'ios':
return config.ios.platformDirAbs;
case 'web':
return config.web.platformDirAbs;
}
return null;
}
export async function getProjectPlatformDirectory(config: Config, platform: string): Promise<string | null> {
const platformPath = getPlatformDirectory(config, platform);
if (platformPath && (await pathExists(platformPath))) {
return platformPath;
}
return null;
}
export async function selectPlatforms(config: Config, selectedPlatformName?: string): Promise<string[]> {
if (selectedPlatformName) {
// already passed in a platform name
const platformName = selectedPlatformName.toLowerCase().trim();
if (!(await isValidPlatform(platformName))) {
fatal(`Invalid platform: ${c.input(platformName)}`);
} else if (!(await getProjectPlatformDirectory(config, platformName))) {
if (platformName === 'web') {
fatal(`Could not find the web platform directory.\n` + `Make sure ${c.strong(config.app.webDir)} exists.`);
}
fatal(
`${c.strong(platformName)} platform has not been added yet.\n` +
`See the docs for adding the ${c.strong(platformName)} platform: ${c.strong(
`https://capacitorjs.com/docs/${platformName}#adding-the-${platformName}-platform`,
)}`,
);
}
// return the platform in an string array
return [platformName];
}
// wasn't given a platform name, so let's
// get the platforms that have already been created
return getAddedPlatforms(config);
}
export async function getKnownPlatforms(): Promise<string[]> {
return ['web', 'android', 'ios'];
}
export async function isValidPlatform(platform: string): Promise<boolean> {
return (await getKnownPlatforms()).includes(platform);
}
export async function getKnownCommunityPlatforms(): Promise<string[]> {
return ['electron'];
}
export async function isValidCommunityPlatform(platform: string): Promise<boolean> {
return (await getKnownCommunityPlatforms()).includes(platform);
}
export async function getKnownEnterprisePlatforms(): Promise<string[]> {
return ['windows'];
}
export async function isValidEnterprisePlatform(platform: string): Promise<boolean> {
return (await getKnownEnterprisePlatforms()).includes(platform);
}
export async function promptForPlatform(
platforms: string[],
promptMessage: string,
selectedPlatformName?: string,
): Promise<string> {
const { prompt } = await import('prompts');
if (!selectedPlatformName) {
const answers = await prompt(
[
{
type: 'select',
name: 'mode',
message: promptMessage,
choices: platforms.map((p) => ({ title: p, value: p })),
},
],
{ onCancel: () => process.exit(1) },
);
return answers.mode.toLowerCase().trim();
}
const platformName = selectedPlatformName.toLowerCase().trim();
if (!(await isValidPlatform(platformName))) {
const knownPlatforms = await getKnownPlatforms();
fatal(`Invalid platform: ${c.input(platformName)}.\n` + `Valid platforms include: ${knownPlatforms.join(', ')}`);
}
return platformName;
}
export interface PlatformTarget {
id: string;
platform: string;
virtual: boolean;
sdkVersion: string;
name?: string;
model?: string;
}
export async function promptForPlatformTarget(
targets: PlatformTarget[],
selectedTarget?: string,
selectedTargetSdkVersion?: string,
selectByName?: boolean,
): Promise<PlatformTarget> {
const { prompt } = await import('prompts');
const validTargets = targets.filter((t) => t.id !== undefined);
if (!selectedTarget) {
if (validTargets.length === 1) {
return validTargets[0];
} else {
const answers = await prompt(
[
{
type: 'select',
name: 'target',
message: 'Please choose a target device:',
choices: validTargets.map((t) => ({
title: `${getPlatformTargetName(t)} (${t.id})`,
value: t,
})),
},
],
{ onCancel: () => process.exit(1) },
);
return answers.target;
}
}
const targetID = selectedTarget.trim();
const target = targets.find((t) => {
if (selectByName === true) {
let name = t.name ?? t.model;
if (name) {
// Apple device names may have "smart quotes" in the name,
// strip them and replace them with the "straight" versions
name = name.replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"');
}
if (selectedTargetSdkVersion) {
return name === targetID && t.sdkVersion === selectedTargetSdkVersion;
}
return name === targetID;
}
return t.id === targetID;
});
if (!target) {
if (selectByName) {
let invalidTargetName = targetID;
if (selectedTargetSdkVersion) {
invalidTargetName += ` [${selectedTargetSdkVersion}]`;
}
fatal(
`Invalid target name: ${c.input(invalidTargetName)}.\n` +
`Valid targets are:\n ${targets.map((t) => `${t.name ?? t.model} [${t.sdkVersion}]`).join('\n')}`,
);
}
fatal(`Invalid target ID: ${c.input(targetID)}.\n` + `Valid targets are:\n ${targets.map((t) => t.id).join('\n')}`);
}
return target;
}
export function getPlatformTargetName(target: PlatformTarget): string {
return `${target.name ?? target.model ?? target.id ?? '?'}${
target.virtual ? ` (${target.platform === 'ios' ? 'simulator' : 'emulator'})` : ''
}`;
}
export async function getAddedPlatforms(config: Config): Promise<string[]> {
const platforms: string[] = [];
if (await getProjectPlatformDirectory(config, config.android.name)) {
platforms.push(config.android.name);
}
if (await getProjectPlatformDirectory(config, config.ios.name)) {
platforms.push(config.ios.name);
}
platforms.push(config.web.name);
return platforms;
}
export async function checkPlatformVersions(config: Config, platform: string): Promise<void> {
const semver = await import('semver');
const coreVersion = await getCoreVersion(config);
const platformVersion = await getCapacitorPackageVersion(config, platform);
if (semver.diff(coreVersion, platformVersion) === 'minor' || semver.diff(coreVersion, platformVersion) === 'major') {
logger.warn(
`${c.strong('@capacitor/core')}${c.weak(
`@${coreVersion}`,
)} version doesn't match ${c.strong(`@capacitor/${platform}`)}${c.weak(`@${platformVersion}`)} version.\n` +
`Consider updating to a matching version, e.g. w/ ${c.input(`npm install @capacitor/core@${platformVersion}`)}`,
);
}
}
export function resolvePlatform(config: Config, platform: string): string | null {
if (platform[0] !== '@') {
const core = resolveNode(config.app.rootDir, `@capacitor/${platform}`, 'package.json');
if (core) {
return dirname(core);
}
const community = resolveNode(config.app.rootDir, `@capacitor-community/${platform}`, 'package.json');
if (community) {
return dirname(community);
}
const enterprise = resolveNode(config.app.rootDir, `@ionic-enterprise/capacitor-${platform}`, 'package.json');
if (enterprise) {
return dirname(enterprise);
}
}
// third-party
const thirdParty = resolveNode(config.app.rootDir, platform, 'package.json');
if (thirdParty) {
return dirname(thirdParty);
}
return null;
}
export async function checkJDKMajorVersion(): Promise<number> {
try {
const string = await runCommand('java', ['--version']);
const versionRegex = RegExp(/([0-9]+)\.?([0-9]*)\.?([0-9]*)/);
const versionMatch = versionRegex.exec(string);
if (versionMatch === null) {
return -1;
}
const firstVersionNumber = parseInt(versionMatch[1]);
const secondVersionNumber = parseInt(versionMatch[2]);
if (typeof firstVersionNumber === 'number' && firstVersionNumber != 1) {
return firstVersionNumber;
} else if (typeof secondVersionNumber === 'number' && firstVersionNumber == 1 && secondVersionNumber < 9) {
return secondVersionNumber;
} else {
return -1;
}
} catch (e) {
return -1;
}
}
export function parseApkNameFromFlavor(flavor: string): string {
let convertedName = flavor.replace(/([A-Z])/g, '-$1').toLowerCase();
if (convertedName.startsWith('-')) convertedName = convertedName.replace('-', '');
return `app-${convertedName ? `${convertedName}-` : ''}debug.apk`;
}