Files
tlsn-plugin-boilerplate/esbuild.js
2024-06-25 15:08:43 +02:00

85 lines
2.9 KiB
JavaScript

const esbuild = require('esbuild');
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const { name } = require('./package.json');
const { execSync } = require('child_process');
// Promisify fs.readFile and fs.stat for convenience
const readFileAsync = promisify(fs.readFile);
const statAsync = promisify(fs.stat);
const mkdirAsync = promisify(fs.mkdir);
/**
* Generates a Base64 encoded icon file.
* It checks if the output file already exists and is up-to-date before generating a new one.
*/
async function generateBase64Icon() {
const iconPath = path.join(__dirname, 'assets', "icon.png");
const outputDir = path.join(__dirname, 'dist', 'assets');
const outputPath = path.join(outputDir, 'icon.ts');
try {
// Ensure the output directory exists
await mkdirAsync(outputDir, { recursive: true });
const [iconStat, outputStat] = await Promise.all([
statAsync(iconPath).catch(() => null),
statAsync(outputPath).catch(() => null)
]);
// Check if output file exists and is newer than the icon file
if (outputStat && iconStat && outputStat.mtime > iconStat.mtime) {
console.log('Base64 icon file is up-to-date.');
return;
}
const fileBuffer = await readFileAsync(iconPath);
const base64Icon = `data:image/png;base64,${fileBuffer.toString('base64')}`;
const outputContent = `// This is a generated file. Do not edit directly.
// This is a Base64 encoded version of the plugin's icon ('icon.png') used in the plugin's config.
// This file is automatically generated by esBuild.js whenever the icon is changed.
// There is no need to add it to version control.
export const icon = "${base64Icon}";\n`;
fs.writeFileSync(outputPath, outputContent);
console.log('Base64 icon file generated successfully.');
} catch (error) {
console.error(`Failed to generate base64 icon: ${error.message}`);
process.exit(1);
}
}
const outputDir = 'dist';
const entryFile = 'src/index.ts';
const outputFile = path.join(outputDir, 'index.js');
const outputWasm = path.join(outputDir, `${name}.tlsn.wasm`);
async function build() {
await generateBase64Icon();
try {
await esbuild.build({
entryPoints: [entryFile],
bundle: true,
outdir: outputDir, // Use outdir for directory output
sourcemap: true,
minify: false, // might want to use true for production build
format: 'cjs', // needs to be CJS for now
target: ['es2020'], // don't go over es2020 because quickjs doesn't support it
});
console.log('esbuild completed successfully.');
// Run extism-js to generate the wasm file
const extismCommand = `extism-js ${outputFile} -i src/index.d.ts -o ${outputWasm}`;
execSync(extismCommand, { stdio: 'inherit' });
console.log('extism-js completed successfully.');
} catch (error) {
console.error('Build process failed:', error);
process.exit(1);
}
}
build();