Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/core/esbuild.ts
3562 views
1
/*
2
* esbuild.ts
3
*
4
* Copyright (C) 2021-2022 Posit Software, PBC
5
*/
6
7
import { assert } from "testing/asserts";
8
import { execProcess } from "./process.ts";
9
import { architectureToolsPath } from "./resources.ts";
10
import { TempContext } from "./temp-types.ts";
11
import { createTempContext } from "./temp.ts";
12
import { nullDevice } from "./platform.ts";
13
14
type ESBuildAnalysisImport = {
15
path: string;
16
kind: string;
17
external: boolean;
18
};
19
20
type ESBuildOutputValue = {
21
imports: ESBuildAnalysisImport[];
22
entryPoint: string;
23
inputs: Record<string, { bytesInOutput: number }>;
24
bytes: number;
25
};
26
27
export type ESBuildAnalysis = {
28
inputs: Record<string, { bytes: number; format: string }>;
29
outputs: Record<string, ESBuildOutputValue>;
30
};
31
32
export async function esbuildAnalyze(
33
input: string,
34
workingDir: string,
35
tempContext?: TempContext,
36
): Promise<ESBuildAnalysis> {
37
let mustCleanup = false;
38
if (!tempContext) {
39
tempContext = createTempContext();
40
mustCleanup = true;
41
}
42
43
try {
44
const tempName = tempContext.createFile({ suffix: ".json" });
45
await esbuildCommand(
46
[
47
"--analyze=verbose",
48
`--metafile=${tempName}`,
49
`--outfile=${nullDevice()}`,
50
input,
51
],
52
"",
53
workingDir,
54
);
55
const result = JSON.parse(
56
Deno.readTextFileSync(tempName),
57
) as ESBuildAnalysis;
58
assert(Object.entries(result.outputs).length === 1);
59
result.outputs = {
60
"<output>": Object.values(result.outputs)[0],
61
};
62
return result;
63
} finally {
64
if (mustCleanup) {
65
tempContext.cleanup();
66
}
67
}
68
}
69
70
export async function esbuildCompile(
71
input: string,
72
workingDir: string,
73
args?: string[],
74
format?: "esm" | "cjs" | "iife",
75
): Promise<string | undefined> {
76
format = format ?? "esm";
77
const fullArgs = [
78
"--bundle",
79
`--format=${format}`,
80
...(args || []),
81
];
82
83
return await esbuildCommand(fullArgs, input, workingDir);
84
}
85
86
export async function esbuildCommand(
87
args: string[],
88
input: string,
89
workingDir: string,
90
) {
91
const cmd = Deno.env.get("QUARTO_ESBUILD") ||
92
architectureToolsPath("esbuild");
93
const result = await execProcess(
94
{
95
cmd,
96
args,
97
cwd: workingDir,
98
stdout: "piped",
99
stderr: "piped",
100
},
101
input,
102
);
103
104
if (result.success) {
105
return result.stdout;
106
} else {
107
console.error(result.stderr);
108
109
throw new Error("esbuild command failed");
110
}
111
}
112
113