@backan/builder
Version:
Backan library for building executables, client libraries, JSON schema files, TypeScript definitions, and Markdown documentation.
109 lines (108 loc) • 2.98 kB
JavaScript
import { BINARIUM_CONSTS } from "binarium";
import { build, buildAuto, buildDeno, buildNode, defineConfig } from "binarium";
import openapiTS, { astToString } from "openapi-typescript";
import { spawn } from "node:child_process";
import { mkdir, writeFile as writeFile$1, stat, rm, unlink } from "node:fs/promises";
import { dirname, join } from "node:path";
import * as url from "node:url";
const bin = { "backan-builder": "dist/bin.js" };
url.fileURLToPath(new URL("..", import.meta.url));
const joinPath = join;
const getDirname = dirname;
const writeFile = async (path, data) => {
const dir = getDirname(path);
await mkdir(dir, { recursive: true });
await writeFile$1(path, data, "utf8");
};
const exec = async (cmd) => {
await new Promise((resolve2, reject) => {
const childProcess = spawn(cmd, {
shell: true,
stdio: "inherit"
});
childProcess.on("close", (code) => {
if (code === 0) resolve2();
else {
const error = new Error(`Command failed with code ${code}`);
console.error(error);
reject(error);
}
});
});
};
const removePathIfExist = async (path) => {
try {
const stats = await stat(path);
if (stats.isDirectory()) {
await rm(path, {
recursive: true,
force: true
});
} else if (stats.isFile()) {
await unlink(path);
}
} catch (error) {
if (error.code === "ENOENT") return;
else console.error(`Error deleting ${path}:`, error);
}
};
const buildSchema = async ({
app,
output,
dts = true
}) => {
try {
const jsonOutput = output.endsWith(".json") ? output : output + ".json";
const openApi = app.getOpenApiObject();
await writeFile(
jsonOutput,
JSON.stringify(openApi, null, 2)
);
if (dts === false) return;
const dtsOutput = jsonOutput.replace(".json", ".d.ts");
const ast = await openapiTS(openApi);
const contents = astToString(ast);
await writeFile(
dtsOutput,
contents
);
} catch (e) {
throw new Error(`Schema build failed: ${e instanceof Error ? e.message : "Unknown error"}`);
}
};
const buildMD = async ({
app,
output
}) => {
try {
output = output.endsWith(".md") ? output : output + ".md";
const outputDir = getDirname(output);
const outputSchema = joinPath(outputDir, "schema.json");
const binPath = joinPath(
new URL(".", import.meta.url).pathname,
"..",
"node_modules",
".bin",
"openapi-to-md"
);
await buildSchema({
app,
output: outputSchema
});
await exec(`${binPath} ${outputSchema} ${output}`);
await removePathIfExist(outputSchema);
} catch (e) {
throw new Error(`Markdown build failed: ${e instanceof Error ? e.message : "Unknown error"}`);
}
};
BINARIUM_CONSTS.icon = "🔥";
BINARIUM_CONSTS.name = Object.keys(bin)[0].toUpperCase();
export {
build,
buildAuto,
buildDeno,
buildMD,
buildNode,
buildSchema,
defineConfig
};