-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathbuild.ts
More file actions
323 lines (251 loc) · 8.99 KB
/
build.ts
File metadata and controls
323 lines (251 loc) · 8.99 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
import { BaseError, MetadataGroup } from '@ionic/cli-framework';
import { PromptModule } from '@ionic/cli-framework-prompts';
import { createProcessEnv } from '@ionic/utils-process';
import { ERROR_COMMAND_NOT_FOUND, SubprocessError } from '@ionic/utils-subprocess';
import { debug as Debug } from 'debug';
import { BaseBuildOptions, BuildOptions, CommandLineInputs, CommandLineOptions, CommandMetadata, CommandMetadataOption, IConfig, ILogger, IProject, IShell, NpmClient, Runner } from '../definitions';
import { ancillary, input, strong } from './color';
import { BuildCLIProgramNotFoundException, FatalException } from './errors';
import { Hook } from './hooks';
const debug = Debug('ionic:lib:build');
export const BUILD_SCRIPT = 'ionic:build';
export const COMMON_BUILD_COMMAND_OPTIONS: readonly CommandMetadataOption[] = [
{
name: 'engine',
summary: `Target engine (e.g. ${['browser', 'cordova'].map(e => input(e)).join(', ')})`,
groups: [MetadataGroup.ADVANCED],
},
{
name: 'platform',
summary: `Target platform on chosen engine (e.g. ${['ios', 'android'].map(e => input(e)).join(', ')})`,
groups: [MetadataGroup.ADVANCED],
},
];
export interface BuildRunnerDeps {
readonly config: IConfig;
readonly log: ILogger;
readonly project: IProject;
readonly prompt: PromptModule;
readonly shell: IShell;
}
export abstract class BuildRunner<T extends BuildOptions<any>> implements Runner<T, void> {
protected abstract readonly e: BuildRunnerDeps;
abstract getCommandMetadata(): Promise<Partial<CommandMetadata>>;
abstract createOptionsFromCommandLine(inputs: CommandLineInputs, options: CommandLineOptions): T;
abstract buildProject(options: T): Promise<void>;
getPkgManagerBuildCLI(): PkgManagerBuildCLI {
const pkgManagerCLIs = {
npm: NpmBuildCLI,
pnpm: PnpmBuildCLI,
yarn: YarnBuildCLI,
bun: BunBuildCLI,
};
const client = this.e.config.get('npmClient');
const CLI = pkgManagerCLIs[client];
if (CLI) {
return new CLI(this.e);
}
throw new BuildCLIProgramNotFoundException('Unknown CLI client: ' + client);
}
createBaseOptionsFromCommandLine(inputs: CommandLineInputs, options: CommandLineOptions): BaseBuildOptions {
const separatedArgs = options['--'];
const [platform] = options['platform'] ? [String(options['platform'])] : inputs;
const engine = this.determineEngineFromCommandLine(options);
const project = options['project'] ? String(options['project']) : undefined;
const verbose = !!options['verbose'];
return { '--': separatedArgs ? separatedArgs : [], engine, platform, project, verbose };
}
determineEngineFromCommandLine(options: CommandLineOptions): string {
if (options['engine']) {
return String(options['engine']);
}
if (options['cordova']) {
return 'cordova';
}
return 'browser';
}
async beforeBuild(options: T): Promise<void> {
const hook = new BuildBeforeHook(this.e);
try {
await hook.run({ name: hook.name, build: options });
} catch (e: any) {
if (e instanceof BaseError) {
throw new FatalException(e.message);
}
throw e;
}
}
async run(options: T): Promise<void> {
debug('build options: %O', options);
if (options.engine === 'cordova' && !options.platform) {
this.e.log.warn(`Cordova engine chosen without a target platform. This could cause issues. Please use the ${input('--platform')} option.`);
}
await this.beforeBuild(options);
await this.buildProject(options);
await this.afterBuild(options);
}
async afterBuild(options: T): Promise<void> {
const hook = new BuildAfterHook(this.e);
try {
await hook.run({ name: hook.name, build: options });
} catch (e: any) {
if (e instanceof BaseError) {
throw new FatalException(e.message);
}
throw e;
}
}
}
export abstract class BuildCLI<T extends object> {
/**
* The pretty name of this Build CLI.
*/
abstract readonly name: string;
/**
* The npm package of this Build CLI.
*/
abstract readonly pkg: string;
/**
* The bin program to use for this Build CLI.
*/
abstract readonly program: string;
/**
* If specified, `package.json` is inspected for this script to use instead
* of `program`.
*/
abstract readonly script?: string;
/**
* If true, the Build CLI will not prompt to be installed.
*/
readonly global: boolean = false;
private _resolvedProgram?: string;
constructor(protected readonly e: BuildRunnerDeps) { }
get resolvedProgram() {
if (this._resolvedProgram) {
return this._resolvedProgram;
}
return this.program;
}
/**
* Build the arguments for starting this Build CLI. Called by `this.run()`.
*/
protected abstract buildArgs(options: T): Promise<string[]>;
/**
* Build the environment variables for this Build CLI. Called by `this.run()`.
*/
protected async buildEnvVars(options: T): Promise<NodeJS.ProcessEnv> {
return process.env;
}
async resolveScript(): Promise<string | undefined> {
if (typeof this.script === 'undefined') {
return;
}
const pkg = await this.e.project.requirePackageJson();
return pkg.scripts && pkg.scripts[this.script];
}
async build(options: T): Promise<void> {
this._resolvedProgram = await this.resolveProgram();
await this.runWrapper(options);
}
protected async runWrapper(options: T): Promise<void> {
try {
return await this.run(options);
} catch (e: any) {
if (!(e instanceof BuildCLIProgramNotFoundException)) {
throw e;
}
if (this.global) {
this.e.log.nl();
throw new FatalException(`${input(this.pkg)} is required for this command to work properly.`);
}
this.e.log.nl();
this.e.log.info(
`Looks like ${input(this.pkg)} isn't installed in this project.\n` +
`This package is required for this command to work properly.`
);
const installed = await this.promptToInstall();
if (!installed) {
this.e.log.nl();
throw new FatalException(`${input(this.pkg)} is required for this command to work properly.`);
}
return this.run(options);
}
}
protected async run(options: T): Promise<void> {
const args = await this.buildArgs(options);
const env = await this.buildEnvVars(options);
try {
await this.e.shell.run(this.resolvedProgram, args, { stdio: 'inherit', cwd: this.e.project.directory, fatalOnNotFound: false, env: createProcessEnv(env) });
} catch (e: any) {
if (e instanceof SubprocessError && e.code === ERROR_COMMAND_NOT_FOUND) {
throw new BuildCLIProgramNotFoundException(`${strong(this.resolvedProgram)} command not found.`);
}
throw e;
}
}
protected async resolveProgram(): Promise<string> {
if (typeof this.script !== 'undefined') {
debug(`Looking for ${ancillary(this.script)} npm script.`);
if (await this.resolveScript()) {
debug(`Using ${ancillary(this.script)} npm script.`);
return this.e.config.get('npmClient');
}
}
return this.program;
}
protected async promptToInstall(): Promise<boolean> {
const { pkgManagerArgs } = await import('./utils/npm');
const [manager, ...managerArgs] = await pkgManagerArgs(this.e.config.get('npmClient'), { command: 'install', pkg: this.pkg, saveDev: true, saveExact: true });
this.e.log.nl();
const confirm = await this.e.prompt({
name: 'confirm',
message: `Install ${input(this.pkg)}?`,
type: 'confirm',
});
if (!confirm) {
this.e.log.warn(`Not installing--here's how to install manually: ${input(`${manager} ${managerArgs.join(' ')}`)}`);
return false;
}
await this.e.shell.run(manager, managerArgs, { cwd: this.e.project.directory });
return true;
}
}
abstract class PkgManagerBuildCLI extends BuildCLI<BaseBuildOptions> {
readonly abstract program: NpmClient;
readonly global = true;
readonly script = BUILD_SCRIPT;
protected async resolveProgram(): Promise<string> {
return this.program;
}
protected async buildArgs(options: BaseBuildOptions): Promise<string[]> {
const { pkgManagerArgs } = await import('./utils/npm');
const [, ...pkgArgs] = await pkgManagerArgs(this.program, { command: 'run', script: this.script, scriptArgs: [...options['--'] || []] });
return pkgArgs;
}
}
export class NpmBuildCLI extends PkgManagerBuildCLI {
readonly name = 'npm CLI';
readonly pkg = 'npm';
readonly program = 'npm';
}
export class PnpmBuildCLI extends PkgManagerBuildCLI {
readonly name = 'pnpm CLI';
readonly pkg = 'pnpm';
readonly program = 'pnpm';
}
export class YarnBuildCLI extends PkgManagerBuildCLI {
readonly name = 'Yarn';
readonly pkg = 'yarn';
readonly program = 'yarn';
}
export class BunBuildCLI extends PkgManagerBuildCLI {
readonly name = 'Bun';
readonly pkg = 'bun';
readonly program = 'bun';
}
class BuildBeforeHook extends Hook {
readonly name = 'build:before';
}
class BuildAfterHook extends Hook {
readonly name = 'build:after';
}