Skip to content

Commit 0abb3c3

Browse files
committed
refactor: create constructOpenOptions
1 parent c1ef7ed commit 0abb3c3

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

src/node/util.ts

+35-8
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,40 @@ export const isWsl = async (
404404
}
405405
}
406406

407+
interface OpenOptions {
408+
args: string[]
409+
options: cp.SpawnOptions
410+
command: string
411+
urlSearch: string
412+
}
413+
414+
/**
415+
* A helper function to construct options for `open` function.
416+
*
417+
* Extract to make it easier to test.
418+
*
419+
* @param platform - platform on machine
420+
* @param urlSearch - url.search
421+
* @returns an object with args, command, options and urlSearch
422+
*/
423+
export function constructOpenOptions(platform: NodeJS.Platform | "wsl", urlSearch: string): OpenOptions {
424+
const args: string[] = []
425+
const options: cp.SpawnOptions = {}
426+
let command = platform === "darwin" ? "open" : "xdg-open"
427+
if (platform === "win32" || platform === "wsl") {
428+
command = platform === "wsl" ? "cmd.exe" : "cmd"
429+
args.push("/c", "start", '""', "/b")
430+
urlSearch = urlSearch.replace(/&/g, "^&")
431+
}
432+
433+
return {
434+
args,
435+
command,
436+
options,
437+
urlSearch,
438+
}
439+
}
440+
407441
/**
408442
* Try opening an address using whatever the system has set for opening URLs.
409443
*/
@@ -416,15 +450,8 @@ export const open = async (address: URL | string): Promise<void> => {
416450
if (url.hostname === "0.0.0.0") {
417451
url.hostname = "localhost"
418452
}
419-
const args: string[] = []
420-
const options: cp.SpawnOptions = {}
421453
const platform = (await isWsl(process.platform, os.release(), "/proc/version")) ? "wsl" : process.platform
422-
let command = platform === "darwin" ? "open" : "xdg-open"
423-
if (platform === "win32" || platform === "wsl") {
424-
command = platform === "wsl" ? "cmd.exe" : "cmd"
425-
args.push("/c", "start", '""', "/b")
426-
url.search = url.search.replace(/&/g, "^&")
427-
}
454+
const { command, args, options } = constructOpenOptions(platform, url.search)
428455
const proc = cp.spawn(command, [...args, url.toString()], options)
429456
await new Promise<void>((resolve, reject) => {
430457
proc.on("error", reject)

0 commit comments

Comments
 (0)