-
Notifications
You must be signed in to change notification settings - Fork 655
/
serve.ts
225 lines (191 loc) · 8.05 KB
/
serve.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { LOGGER_LEVELS, OptionGroup, ParsedArgs, createPrefixedFormatter, unparseArgs } from '@ionic/cli-framework';
import { isHostConnectable } from '@ionic/cli-framework/utils/network';
import { onBeforeExit } from '@ionic/cli-framework/utils/process';
import { str2num } from '@ionic/cli-framework/utils/string';
import chalk from 'chalk';
import * as Debug from 'debug';
import * as split2 from 'split2';
import * as through2 from 'through2';
import { prettyProjectName } from '../';
import { CommandLineInputs, CommandLineOptions, CommandMetadata, IonicAngularServeOptions, ServeDetails } from '../../../definitions';
import { FatalException, ServeCommandNotFoundException } from '../../errors';
import { BIND_ALL_ADDRESS, DEFAULT_DEV_LOGGER_PORT, DEFAULT_LIVERELOAD_PORT, LOCAL_ADDRESSES, SERVE_SCRIPT, ServeRunner as BaseServeRunner } from '../../serve';
import { findOpenIonicPorts } from '../common';
import { APP_SCRIPTS_OPTIONS } from './app-scripts';
const debug = Debug('ionic:cli-utils:lib:project:ionic-angular:serve');
const DEFAULT_PROGRAM = 'ionic-app-scripts';
export const DEFAULT_SERVE_SCRIPT_VALUE = `${DEFAULT_PROGRAM} serve`;
interface ServeCmdDetails {
program: string;
}
export class ServeRunner extends BaseServeRunner<IonicAngularServeOptions> {
async getCommandMetadata(): Promise<Partial<CommandMetadata>> {
return {
options: [
{
name: 'consolelogs',
summary: 'Print app console logs to Ionic CLI',
type: Boolean,
aliases: ['c'],
},
{
name: 'serverlogs',
summary: 'Print dev server logs to Ionic CLI',
type: Boolean,
aliases: ['s'],
groups: [OptionGroup.Hidden],
},
{
name: 'livereload-port',
summary: 'Use specific port for live-reload',
default: DEFAULT_LIVERELOAD_PORT.toString(),
aliases: ['r'],
groups: [OptionGroup.Advanced],
},
{
name: 'dev-logger-port',
summary: 'Use specific port for dev server communication',
default: DEFAULT_DEV_LOGGER_PORT.toString(),
groups: [OptionGroup.Advanced],
},
{
name: 'proxy',
summary: 'Do not add proxies',
type: Boolean,
default: true,
groups: [OptionGroup.Advanced],
// TODO: Adding 'x' to aliases here has some weird behavior with minimist.
},
...APP_SCRIPTS_OPTIONS,
],
};
}
createOptionsFromCommandLine(inputs: CommandLineInputs, options: CommandLineOptions): IonicAngularServeOptions {
const baseOptions = super.createOptionsFromCommandLine(inputs, options);
const livereloadPort = str2num(options['livereload-port'], DEFAULT_LIVERELOAD_PORT);
const notificationPort = str2num(options['dev-logger-port'], DEFAULT_DEV_LOGGER_PORT);
return {
...baseOptions,
consolelogs: options['consolelogs'] ? true : false,
serverlogs: options['serverlogs'] ? true : false,
livereloadPort,
notificationPort,
env: options['env'] ? String(options['env']) : undefined,
};
}
modifyOpenURL(url: string, options: IonicAngularServeOptions): string {
return `${url}${options.browserOption ? options.browserOption : ''}${options.platform ? `?ionicplatform=${options.platform}` : ''}`;
}
async serveProject(options: IonicAngularServeOptions): Promise<ServeDetails> {
const [ externalIP, availableInterfaces ] = await this.selectExternalIP(options);
const { port, livereloadPort, notificationPort } = await findOpenIonicPorts(options.address, options);
options.port = port;
options.livereloadPort = livereloadPort;
options.notificationPort = notificationPort;
const { program } = await this.serveCommandWrapper(options);
const interval = setInterval(() => {
this.log.info(`Waiting for connectivity with ${chalk.green(program)}...`);
}, 5000);
await isHostConnectable('localhost', port);
clearInterval(interval);
return {
custom: program !== DEFAULT_PROGRAM,
protocol: 'http',
localAddress: 'localhost',
externalAddress: externalIP,
externalNetworkInterfaces: availableInterfaces,
port,
externallyAccessible: ![BIND_ALL_ADDRESS, ...LOCAL_ADDRESSES].includes(externalIP),
};
}
private async serveCommandWrapper(options: IonicAngularServeOptions): Promise<ServeCmdDetails> {
try {
return await this.servecmd(options);
} catch (e) {
if (!(e instanceof ServeCommandNotFoundException)) {
throw e;
}
const pkg = '@ionic/app-scripts';
this.log.nl();
throw new FatalException(
`${chalk.green(pkg)} is required for ${chalk.green('ionic serve')} to work properly.\n` +
`Looks like ${chalk.green(pkg)} isn't installed in this project.\n\n` +
`This package is required for ${chalk.green('ionic serve')} in ${prettyProjectName('angular')} projects.`
);
}
}
private async servecmd(options: IonicAngularServeOptions): Promise<ServeCmdDetails> {
const { pkgManagerArgs } = await import('../../utils/npm');
const config = await this.config.load();
const pkg = await this.project.requirePackageJson();
const { npmClient } = config;
let program = DEFAULT_PROGRAM;
let args = await this.serveOptionsToAppScriptsArgs(options);
const shellOptions = { cwd: this.project.directory };
debug(`Looking for ${chalk.cyan(SERVE_SCRIPT)} npm script.`);
if (pkg.scripts && pkg.scripts[SERVE_SCRIPT]) {
if (pkg.scripts[SERVE_SCRIPT] === DEFAULT_SERVE_SCRIPT_VALUE) {
debug(`Found ${chalk.cyan(SERVE_SCRIPT)}, but it is the default. Not running.`);
args = ['serve', ...args];
} else {
debug(`Invoking ${chalk.cyan(SERVE_SCRIPT)} npm script.`);
const [ pkgManager, ...pkgArgs ] = await pkgManagerArgs(npmClient, { command: 'run', script: SERVE_SCRIPT, scriptArgs: [...args] });
program = pkgManager;
args = pkgArgs;
}
} else {
args = ['serve', ...args];
}
const p = this.shell.spawn(program, args, shellOptions);
this.emit('cli-utility-spawn', p);
return new Promise<ServeCmdDetails>((resolve, reject) => {
p.on('error', (err: NodeJS.ErrnoException) => {
if (program === DEFAULT_PROGRAM && err.code === 'ENOENT') {
reject(new ServeCommandNotFoundException(`${chalk.bold(DEFAULT_PROGRAM)} command not found.`));
} else {
reject(err);
}
});
onBeforeExit(async () => p.kill());
const log = this.log.clone();
log.setFormatter(createPrefixedFormatter(chalk.dim(`[${program === DEFAULT_PROGRAM ? 'app-scripts' : program}]`)));
const ws = log.createWriteStream(LOGGER_LEVELS.INFO);
if (program === DEFAULT_PROGRAM) {
const stdoutFilter = through2(function(chunk, enc, callback) {
const str = chunk.toString();
if (str.includes('server running')) {
resolve({ program }); // TODO: https://github.com/ionic-team/ionic-app-scripts/pull/1372
} else {
this.push(chunk);
}
callback();
});
p.stdout.pipe(split2()).pipe(stdoutFilter).pipe(ws);
p.stderr.pipe(split2()).pipe(ws);
} else {
p.stdout.pipe(split2()).pipe(ws);
p.stderr.pipe(split2()).pipe(ws);
resolve({ program });
}
});
}
async serveOptionsToAppScriptsArgs(options: IonicAngularServeOptions): Promise<string[]> {
const args: ParsedArgs = {
_: [],
address: options.address,
port: String(options.port),
livereloadPort: String(options.livereloadPort),
devLoggerPort: String(options.notificationPort),
consolelogs: options.consolelogs,
serverlogs: options.serverlogs,
nobrowser: true,
nolivereload: !options.livereload,
noproxy: !options.proxy,
iscordovaserve: options.engine === 'cordova',
platform: options.platform,
target: options.engine === 'cordova' ? 'cordova' : undefined,
env: options.env,
};
return [...unparseArgs(args, { useEquals: false }), ...options['--']];
}
}