UNPKG

1.5 kBPlain TextView Raw
1import openBrowserWindow from 'open';
2import path from 'path';
3import { DevServerConfig } from './config/DevServerConfig.js';
4
5function isValidURL(str: string) {
6 try {
7 return !!new URL(str);
8 } catch (error) {
9 return false;
10 }
11}
12
13function getBasePath(basePath?: string) {
14 if (!basePath) {
15 return '';
16 }
17 if (basePath.endsWith('/')) {
18 return basePath.substring(0, basePath.length - 1);
19 }
20 return basePath;
21}
22
23export async function openBrowser(config: DevServerConfig) {
24 const basePath = getBasePath(config.basePath);
25 let openPath: string;
26 if (typeof config.open === 'string') {
27 // user-provided open path
28 openPath = (config.open as string) === '' ? '/' : config.open;
29 } else if (config.appIndex) {
30 const resolvedAppIndex = path.resolve(config.appIndex);
31 const relativeAppIndex = path.relative(config.rootDir, resolvedAppIndex);
32 const appIndexBrowserPath = `/${relativeAppIndex.split(path.sep).join('/')}`;
33 const appIndexDir = path.dirname(appIndexBrowserPath);
34 // if an appIndex was provided, use it's directory as open path
35 openPath = `${basePath}${appIndexDir.endsWith('/') ? appIndexDir : `${appIndexDir}/`}`;
36 } else {
37 openPath = `${basePath}/`;
38 }
39
40 if (!isValidURL(openPath)) {
41 // construct a full URL to open if the user didn't provide a full URL
42 openPath = new URL(
43 openPath,
44 `http${config.http2 ? 's' : ''}://${config.hostname}:${config.port}`,
45 ).href;
46 }
47
48 await openBrowserWindow(openPath);
49}