-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathesbuild.config.js
149 lines (129 loc) · 4.75 KB
/
esbuild.config.js
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
const fs = require("fs");
const path = require("path");
const esbuild = require("esbuild");
const glob = require("glob");
// automatically find all files in the src/lit-actions/src directory
const ENTRY_POINTS = glob.sync("./src/lit-actions/**/*.ts");
const configs = ENTRY_POINTS.map((entryPoint) => {
// Read the content and extract the comment block
const content = fs.readFileSync(entryPoint, "utf8");
const commentBlock = content.match(/\/\*\*([\s\S]*?)\*\//)?.[1];
if (!commentBlock) return { entryPoint };
// Find all lines containing 'inject' or 'inject:'
const injectLines = commentBlock
.split("\n")
.filter((line) => line.includes("inject"));
// Extract the injected values
const injectedValues = injectLines.map((line) => {
const match = line.match(/inject:?\s*([^\s]+)/);
return match ? match[1] : null;
});
// for each injected value, check if the file exist
injectedValues.forEach((injectedValue) => {
if (injectedValue && !fs.existsSync(injectedValue)) {
throw new Error(`❌ File ${injectedValue} does not exist`);
}
});
return {
entryPoint,
...(injectedValues.length > 0 && { injectedValues }),
};
});
const ensureDirectoryExistence = (filePath) => {
const dirname = path.dirname(filePath);
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, { recursive: true });
}
};
const wrapIIFEInStringPlugin = {
name: "wrap-iife-in-string",
setup(build) {
// Ensure write is set to false so our plugin will always receive outputFiles
build.initialOptions.write = false;
build.onEnd((result) => {
if (result.errors.length > 0) {
console.error("Build failed with errors:", result.errors);
return;
}
result.outputFiles.forEach((outputFile) => {
let content = outputFile.text;
// Leaving this in for now, but not needed if we find a better
// solution for the global ethers object.
// // IMPORTANT: if minify is disabled, we need to:
// // 1. remove var import_ethers = __require("ethers");
// // 2. remove import_ethers.
// content = content
// .replace(/var import_ethers = __require\("ethers"\);/g, "")
// .replace(/import_ethers\./g, "");
// // IMPORTANT: if minify is enabled, we need to:
// // 1. remove var t=o(\"ethers\");
// // 2. replace t.ethers to ethers
// content = content
// .replace(/var\s+\w+=\w+\("ethers"\);/g, '')
// .replace(/[a-zA-Z]\.ethers/g, "ethers");
// Use JSON.stringify to safely encode the content
const wrappedContent = `/**
* DO NOT EDIT THIS FILE. IT IS GENERATED ON BUILD. RUN \`yarn generate-lit-actions\` IN THE ROOT DIRECTORY TO UPDATE THIS FILE.
*
* @type { string } code - Lit Action code. You want to use the content in the "code" constant and NOT the content of this file.
*
*/
export const code = ${JSON.stringify(content, null, 2)};
`;
// Ensure the output directory exists
const outputPath = path.resolve(outputFile.path);
ensureDirectoryExistence(outputPath);
// Write the modified content back to the output file
fs.writeFileSync(outputPath, wrappedContent);
});
});
},
};
const promises = configs.map((config) => {
return esbuild.build({
entryPoints: [config.entryPoint],
bundle: true,
minify: false, // Up to user to turn it on/off. Default off.
treeShaking: true,
outdir: "./src/lit-actions/dist",
external: ["ethers"],
plugins: [wrapIIFEInStringPlugin],
...(config?.injectedValues && { inject: config?.injectedValues }),
});
});
// resolve all promises
const startTime = Date.now();
Promise.all(promises)
.then((results) => {
results.forEach((result) => {
// Check if outputFiles is defined and is an array
if (result.outputFiles && Array.isArray(result.outputFiles)) {
result.outputFiles.forEach((file) => {
const bytes = file.contents.length;
const mbInBinary = (bytes / (1024 * 1024)).toFixed(4);
const mbInDecimal = (bytes / 1_000_000).toFixed(4);
const fileName = path.relative(process.cwd(), file.path);
console.log(`🗂️ File: ${fileName}`);
console.log(
` Size: ${mbInDecimal} MB (decimal) | ${mbInBinary} MB (binary)`
);
});
}
});
const endTime = Date.now();
const buildTime = (endTime - startTime) / 1000; // Convert to seconds
const msg = `✅ Lit actions built successfully in ${buildTime.toFixed(
2
)} seconds`;
console.log(
msg
.split("")
.map((char) => "=")
.join("")
);
console.log(msg);
})
.catch((error) => {
console.error("❌ Error building lit actions: ", error);
process.exit(1);
});