Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/preview/preview-server.ts
6433 views
1
/*
2
* preview-server.ts
3
*
4
* Copyright (C) 2020-2022 Posit Software, PBC
5
*/
6
7
import { MuxAsyncIterator } from "async";
8
import { isWindows } from "../deno_ral/platform.ts";
9
10
export interface PreviewServer {
11
// returns path to browse to
12
start: () => Promise<string | undefined>;
13
serve: () => Promise<void>;
14
stop: () => Promise<void>;
15
}
16
17
export function noPreviewServer(): Promise<PreviewServer> {
18
return Promise.resolve({
19
start: () => Promise.resolve(undefined),
20
serve: () => {
21
return new Promise(() => {
22
});
23
},
24
stop: () => {
25
return Promise.resolve();
26
},
27
});
28
}
29
30
export function runExternalPreviewServer(options: {
31
cmd: string[];
32
readyPattern: RegExp;
33
env?: { [key: string]: string };
34
cwd?: string;
35
}): PreviewServer {
36
const { cmd } = options;
37
// start the process
38
const denoCommand = new Deno.Command(cmd[0], {
39
args: cmd.slice(1),
40
...options,
41
stdout: "piped",
42
stderr: "piped",
43
});
44
45
const process = denoCommand.spawn();
46
47
// merge and stream stdout and stderr
48
const multiplexIterator = new MuxAsyncIterator<
49
Uint8Array
50
>();
51
multiplexIterator.add(process.stdout);
52
multiplexIterator.add(process.stderr);
53
54
// wait for ready and then return from 'start'
55
const decoder = new TextDecoder();
56
return {
57
start: async () => {
58
for await (const chunk of multiplexIterator) {
59
const text = decoder.decode(chunk);
60
if (options.readyPattern.test(text)) {
61
break;
62
}
63
Deno.stderr.writeSync(chunk);
64
}
65
return "";
66
},
67
serve: async () => {
68
for await (const chunk of multiplexIterator) {
69
Deno.stderr.writeSync(chunk);
70
}
71
await process.output();
72
},
73
stop: () => {
74
if (!isWindows) {
75
Deno.kill(-process.pid, "SIGTERM");
76
} else {
77
process.kill();
78
}
79
return Promise.resolve();
80
},
81
};
82
}
83
84