-
Notifications
You must be signed in to change notification settings - Fork 55
/
browser.ts
93 lines (80 loc) · 2.29 KB
/
browser.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
import { fs, open } from 'flex-dev-utils';
import { FlexPluginError } from 'flex-dev-utils/dist/errors';
import { join } from 'path';
import run from '../../utils/run';
import pluginServer, { Plugin } from '../start/pluginServer';
/**
* Extracts port from a localhost url
*
* @param url the localhost url
* @private
*/
export const _getPort = (url: string) => {
const matches = url.match(/localhost:(\d*)/);
if (!matches) {
throw new FlexPluginError(`Could not find a local port on url ${url}`);
}
return matches[1];
};
/**
* Finds the port and localhost url from the argv
*
* @param argv
* @private
*/
export const _getPortAndUrl = (...argv: string[]) => {
const url = argv.find((a) => a.indexOf('localhost:') !== -1);
if (!url) {
throw new FlexPluginError('No localhost server was found running.');
}
return {
url,
port: _getPort(url),
};
};
/**
* requires packages
*
* @param pluginsPath the plugins path
* @param pkgPath the package path
* @private
*/
/* istanbul ignore next */
export const _requirePackages = (pluginsPath: string, pkgPath: string) => {
const plugins = require(pluginsPath) as Plugin[];
const pkg = require(pkgPath);
return {
plugins,
pkg,
};
};
/**
* Replaces the port in plugins.json and re-writes ito the file
*
* @param port the port to update to
* @private
*/
export const _replacePlugins = (port: string) => {
const pluginsPath = join(process.cwd(), 'public', 'plugins.json');
const pkgPath = join(process.cwd(), 'package.json');
const { plugins, pkg } = _requirePackages(pluginsPath, pkgPath);
const pluginIndex = plugins.findIndex((p) => p.src.indexOf(pkg.name) !== -1);
const existingPort = _getPort(plugins[pluginIndex].src);
// Replace port and re-write to file
plugins[pluginIndex].src = plugins[pluginIndex].src.replace(existingPort, port);
fs.writeFileSync(pluginsPath, JSON.stringify(plugins, null, 2));
};
/**
* Dynamically updates the plugins.json file, and then opens the browser
* @param argv
*/
const browser = async (...argv: string[]) => {
const { url, port } = _getPortAndUrl(...argv);
_replacePlugins(port);
// Now open browser
await open(url);
// Run a dev-server plugin service to talk with Flex plugin service
pluginServer(port);
};
run(browser);
export default browser;