@fgiova/cjs-esm-ts-builder 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Francesco Giovannini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # Typescript CommonJS and ESM Builder for Node.js
2
+
3
+ ![GitHub license](https://img.shields.io/github/license/fgiova/cjs-esm-ts-builder.svg)
4
+ [![NPM version](https://img.shields.io/npm/v/@fgiova/cjs-esm-ts-builder.svg?style=flat)](https://www.npmjs.com/package/@fgiova/cjs-esm-ts-builder)
5
+ ![CI workflow](https://github.com/fgiova/cjs-esm-ts-builder/actions/workflows/node.js.yml/badge.svg)
6
+ [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
7
+
8
+
9
+ ## Description
10
+ This module is a Typescript CommonJS and ESM Builder for Node.js.
11
+ It provides a simple way to build your Typescript projects as CommonJS and ESM modules.
12
+ It uses `tsc` and default tsconfig.json to build the project then rewrote import and export of esm files adding .mjs extension and indexes.
13
+
14
+ ## Install
15
+ ```bash
16
+ npm i @fgiova/cjs-esm-ts-builder
17
+ ```
18
+ ## CLI usage
19
+ ```bash
20
+ npx @fgiova/cjs-esm-ts-builder
21
+ ```
22
+ or
23
+ ```bash
24
+ npm install --save-dev @fgiova/cjs-esm-ts-builder
25
+ esmBuilder
26
+ ```
27
+ ### Cli options
28
+ - `--target`: The target version of ECMAScript to compile to. Default is `es2020`.
29
+ - `--esmFolder`: The folder where the ESM files will be generated. Default is `esm`.
30
+ - `--cjsFolder`: The folder where the CommonJS files will be generated. Default is `cjs`.
31
+ - `--buildFolder`: The folder where the build files will be generated. Default is `dist`.
32
+ - `--help`: Show help message.
33
+
34
+
35
+
36
+ ## Programmatic usage
37
+ ```js
38
+ const { build } = require("@fgiova/cjs-esm-ts-builder");
39
+
40
+ const options = {
41
+ target: "es2020",
42
+ esmFolder: "esm",
43
+ cjsFolder: "cjs",
44
+ buildFolder: "dist"
45
+ };
46
+
47
+ build(options)
48
+ .then(() => {
49
+ console.log("Build completed");
50
+ })
51
+ .catch((err) => {
52
+ console.error(err);
53
+ });
54
+ ```
55
+
56
+ ## Configure package.json
57
+ ```json
58
+ {
59
+ ...
60
+ "main": "./dist/cjs/index.js",
61
+ "types": "./dist/cjs/index.d.ts",
62
+ "exports": {
63
+ ".": {
64
+ "import": {
65
+ "types": "./dist/esm/index.d.mts",
66
+ "default": "./dist/esm/index.mjs"
67
+ },
68
+ "require": {
69
+ "types": "./dist/cjs/index.d.ts",
70
+ "default": "./dist/cjs/index.js"
71
+ }
72
+ }
73
+ },
74
+ "files": [
75
+ "dist"
76
+ ],
77
+ ...
78
+ }
79
+ ```
80
+
81
+ ## Options
82
+ - `target`: The target version of ECMAScript to compile to. Default is `es2020`.
83
+ - `esmFolder`: The folder where the ESM files will be generated. Default is `esm`.
84
+ - `cjsFolder`: The folder where the CommonJS files will be generated. Default is `cjs`.
85
+ - `buildFolder`: The folder where the build files will be generated. Default is `dist`.
86
+
87
+
88
+ ## Notes
89
+ - Tested with Node.js >= 20
90
+ - Work only on *nix systems (Linux, MacOS, etc.)
91
+
92
+ ## License
93
+ Licensed under [MIT](./LICENSE).
package/builder.mjs ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import {build} from "./dist/esm/index.mjs";
3
+ import arg from "arg";
4
+
5
+ const args = arg({
6
+ "--target": String,
7
+ "--buildFolder": String,
8
+ "--esmFolder": String,
9
+ "--cjsFolder": String,
10
+ "--help": Boolean,
11
+ "-h": "--help",
12
+ "-t": "--target",
13
+ "-e": "--esmFolder",
14
+ "-c": "--cjsFolder"
15
+ });
16
+
17
+ const target = args["--target"] ?? "es2020";
18
+ const buildFolder = args["--buildFolder"] ?? "dist";
19
+ const esmFolder = args["--esmFolder"] ?? "esm";
20
+ const cjsFolder = args["--cjsFolder"] ?? "cjs";
21
+
22
+ if (args["--help"]) {
23
+ console.log(`
24
+ Usage: build [options]
25
+
26
+ Options:
27
+ --buildFolder Specify the target directory for the build (default: dist)
28
+ --esmFolder Specify the target directory for the ESM build (default: esm)
29
+ --cjsFolder Specify the target directory for the CJS build (default: cjs)
30
+ --target Specify the target ECMAScript version (default: es2020)
31
+ --help Show this help message
32
+ `);
33
+ process.exit(0);
34
+ }
35
+
36
+ build({
37
+ target,
38
+ buildFolder,
39
+ esmFolder,
40
+ cjsFolder
41
+ }).then(() => {
42
+ console.log("Build completed successfully.");
43
+ }).catch((error) => {
44
+ console.error("Build failed:", error);
45
+ process.exit(1);
46
+ });
@@ -0,0 +1 @@
1
+ export declare const compile: (outDir: string, target: string) => Promise<void>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compile = void 0;
4
+ const index_1 = require("../command/index");
5
+ const compile = async (outDir, target) => {
6
+ const options = [
7
+ `--outDir ${outDir}`,
8
+ `--target ${target}`,
9
+ "--module CommonJS",
10
+ "--moduleResolution Node",
11
+ "--declaration",
12
+ ].join(" ");
13
+ const commandLine = `npx tsc ${options}`;
14
+ const command = new index_1.Command(commandLine);
15
+ await command.getPromise();
16
+ console.log("Compiling to CJS completed.");
17
+ };
18
+ exports.compile = compile;
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile";
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Builder = void 0;
37
+ exports.Builder = __importStar(require("./compile"));
@@ -0,0 +1,14 @@
1
+ export declare class Command {
2
+ private readonly command;
3
+ private readonly debug?;
4
+ private readonly process;
5
+ private readonly promise;
6
+ private resolve;
7
+ private terminated;
8
+ private outputBuffers;
9
+ constructor(command: string, debug?: boolean | undefined);
10
+ getPromise(): Promise<number | null>;
11
+ private onExit;
12
+ private onClose;
13
+ private kill;
14
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Command = void 0;
4
+ const node_child_process_1 = require("node:child_process");
5
+ class Command {
6
+ constructor(command, debug) {
7
+ this.command = command;
8
+ this.debug = debug;
9
+ this.terminated = false;
10
+ this.outputBuffers = [];
11
+ this.promise = new Promise((resolve) => {
12
+ this.resolve = resolve;
13
+ });
14
+ this.process = (0, node_child_process_1.spawn)("sh", ["-c", this.command]);
15
+ if (this.debug) {
16
+ this.process.stdout?.on("data", (data) => {
17
+ this.outputBuffers.push(data);
18
+ });
19
+ this.process.stderr?.on("data", (data) => {
20
+ this.outputBuffers.push(data);
21
+ });
22
+ }
23
+ this.process.on("close", (exitCode) => this.onClose(exitCode));
24
+ this.process.on("exit", (exitCode) => this.onExit(exitCode));
25
+ this.terminated = false;
26
+ }
27
+ getPromise() {
28
+ return this.promise;
29
+ }
30
+ onExit(exitCode) {
31
+ this.resolve(exitCode);
32
+ if (this.debug) {
33
+ console.log(this.outputBuffers.join(""));
34
+ }
35
+ this.terminated = true;
36
+ }
37
+ onClose(exitCode) {
38
+ this.resolve(exitCode);
39
+ if (!this.terminated)
40
+ this.kill();
41
+ }
42
+ kill() {
43
+ try {
44
+ const processPid = (0, node_child_process_1.spawnSync)("ps", [
45
+ "-o",
46
+ "pid",
47
+ "--no-headers",
48
+ "--ppid",
49
+ this.process.pid.toString()
50
+ ], {
51
+ encoding: "utf8"
52
+ });
53
+ const pid = parseInt(processPid.output[1]);
54
+ process.kill(pid, "SIGTERM");
55
+ this.process.kill();
56
+ }
57
+ catch (error) {
58
+ if (error instanceof Error) {
59
+ console.warn(error.message);
60
+ }
61
+ else {
62
+ console.warn(error);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ exports.Command = Command;
@@ -0,0 +1 @@
1
+ export declare const toEsm: (sourceDirectory: string) => Promise<void>;
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.toEsm = void 0;
37
+ /* eslint-disable @typescript-eslint/no-unused-vars */
38
+ const path = __importStar(require("node:path"));
39
+ const fs = __importStar(require("node:fs/promises"));
40
+ const relativePath = async (sourceFile, targetFile) => {
41
+ targetFile = targetFile.trim().slice(1, targetFile.length - 1).replace(".js", "");
42
+ const sourceDir = path.dirname(sourceFile);
43
+ const targetElement = path.resolve(sourceDir, `${targetFile}`);
44
+ try {
45
+ const stat = await fs.stat(targetElement);
46
+ if (stat.isDirectory()) {
47
+ return `${targetFile}/index`;
48
+ }
49
+ return null;
50
+ }
51
+ catch (e) { }
52
+ try {
53
+ const stat = await fs.stat(`${targetElement}.js`);
54
+ if (stat.isFile()) {
55
+ return targetFile;
56
+ }
57
+ return null;
58
+ }
59
+ catch (e) { }
60
+ try {
61
+ const stat = await fs.stat(`${targetElement}.mjs`);
62
+ if (stat.isFile()) {
63
+ return targetFile;
64
+ }
65
+ return null;
66
+ }
67
+ catch (e) {
68
+ return null;
69
+ }
70
+ };
71
+ const replaceInlineImports = async (content, sourceFile) => {
72
+ const pattern = /import\((.*?)\)/g;
73
+ while (true) {
74
+ const match = pattern.exec(content);
75
+ if (match === null) {
76
+ return content;
77
+ }
78
+ const importDeclaration = match[1];
79
+ const importModule = await relativePath(sourceFile, importDeclaration);
80
+ if (!importModule) {
81
+ continue;
82
+ }
83
+ content = content.replace(importDeclaration, `"${importModule}.mjs"`);
84
+ }
85
+ };
86
+ const replaceExportImportDeclarations = async (content, sourceFile) => {
87
+ const pattern = /(export|import)(.*) from ("(.*)");/g;
88
+ while (true) {
89
+ const match = pattern.exec(content);
90
+ if (match === null) {
91
+ return content;
92
+ }
93
+ const declaration = match[3];
94
+ const importModule = await relativePath(sourceFile, declaration);
95
+ if (!importModule) {
96
+ continue;
97
+ }
98
+ content = content.replace(declaration, `"${importModule}.mjs"`);
99
+ }
100
+ };
101
+ const replaceDeclarations = async (content, sourceFile) => {
102
+ return await replaceInlineImports(await replaceExportImportDeclarations(content, sourceFile), sourceFile);
103
+ };
104
+ const fileIsProcessable = (sourcepath) => {
105
+ const extname = path.extname(sourcepath);
106
+ return [".js", ".ts"].includes(extname);
107
+ };
108
+ const esmExtension = (extension) => {
109
+ return (extension === ".js" ? ".mjs" :
110
+ extension === ".ts" ? ".mts" :
111
+ extension);
112
+ };
113
+ const processFile = async (sourceFile) => {
114
+ if (!fileIsProcessable(sourceFile)) {
115
+ return;
116
+ }
117
+ const extname = path.extname(sourceFile);
118
+ const dirname = path.dirname(sourceFile);
119
+ const basename = path.basename(sourceFile, extname);
120
+ const newExtname = esmExtension(extname);
121
+ const sourceContent = await fs.readFile(sourceFile, "utf-8");
122
+ const newContent = replaceDeclarations(sourceContent, sourceFile);
123
+ const newFile = `${path.join(dirname, basename)}${newExtname}`;
124
+ await fs.writeFile(newFile, await newContent);
125
+ await fs.unlink(sourceFile);
126
+ };
127
+ const processDirectory = async (directory) => {
128
+ const files = await fs.readdir(directory);
129
+ for (const file of files) {
130
+ const elementPath = path.join(directory, file);
131
+ await processElement(elementPath);
132
+ }
133
+ };
134
+ const processElement = async (sourcePath) => {
135
+ const element = await fs.stat(sourcePath);
136
+ if (element.isDirectory()) {
137
+ return await processDirectory(sourcePath);
138
+ }
139
+ if (element.isFile()) {
140
+ return await processFile(sourcePath);
141
+ }
142
+ };
143
+ const toEsm = async (sourceDirectory) => {
144
+ await processElement(sourceDirectory);
145
+ };
146
+ exports.toEsm = toEsm;
@@ -0,0 +1 @@
1
+ export declare const compile: (outDir: string, target: string) => Promise<void>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compile = void 0;
4
+ const command_1 = require("../command");
5
+ const cjs_to_esm_1 = require("./cjs-to-esm");
6
+ const compile = async (outDir, target) => {
7
+ const options = [
8
+ `--outDir ${outDir}`,
9
+ `--target ${target}`,
10
+ "--module esnext",
11
+ "--declaration",
12
+ "--moduleResolution node"
13
+ ].join(" ");
14
+ const commandLine = `npx tsc ${options}`;
15
+ const command = new command_1.Command(commandLine);
16
+ await command.getPromise();
17
+ console.log("Compiling to ESM completed.");
18
+ await (0, cjs_to_esm_1.toEsm)(outDir);
19
+ console.log("Converting to ESM completed.");
20
+ };
21
+ exports.compile = compile;
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile";
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Builder = void 0;
37
+ exports.Builder = __importStar(require("./compile"));
@@ -0,0 +1,8 @@
1
+ type BuildOptions = {
2
+ target: string;
3
+ esmFolder: string;
4
+ cjsFolder: string;
5
+ buildFolder: string;
6
+ };
7
+ export declare const build: (options?: BuildOptions) => Promise<void>;
8
+ export {};
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.build = void 0;
37
+ const esm = __importStar(require("./esm"));
38
+ const cjs = __importStar(require("./cjs"));
39
+ const path = __importStar(require("node:path"));
40
+ const build = async (options) => {
41
+ const defaultOptions = {
42
+ target: "es2020",
43
+ esmFolder: "esm",
44
+ cjsFolder: "cjs",
45
+ buildFolder: "dist"
46
+ };
47
+ const { target, esmFolder, cjsFolder, buildFolder } = {
48
+ ...defaultOptions,
49
+ ...options
50
+ };
51
+ console.log("Building...");
52
+ await Promise.all([
53
+ esm.Builder.compile(path.resolve(buildFolder, esmFolder), target),
54
+ cjs.Builder.compile(path.resolve(buildFolder, cjsFolder), target)
55
+ ]);
56
+ console.log(`Build completed. Output directory: ${buildFolder}`);
57
+ };
58
+ exports.build = build;
@@ -0,0 +1 @@
1
+ export declare const compile: (outDir: string, target: string) => Promise<void>;
@@ -0,0 +1,14 @@
1
+ import { Command } from "../command/index.mjs";
2
+ export const compile = async (outDir, target) => {
3
+ const options = [
4
+ `--outDir ${outDir}`,
5
+ `--target ${target}`,
6
+ "--module CommonJS",
7
+ "--moduleResolution Node",
8
+ "--declaration",
9
+ ].join(" ");
10
+ const commandLine = `npx tsc ${options}`;
11
+ const command = new Command(commandLine);
12
+ await command.getPromise();
13
+ console.log("Compiling to CJS completed.");
14
+ };
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile.mjs";
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile.mjs";
@@ -0,0 +1,14 @@
1
+ export declare class Command {
2
+ private readonly command;
3
+ private readonly debug?;
4
+ private readonly process;
5
+ private readonly promise;
6
+ private resolve;
7
+ private terminated;
8
+ private outputBuffers;
9
+ constructor(command: string, debug?: boolean | undefined);
10
+ getPromise(): Promise<number | null>;
11
+ private onExit;
12
+ private onClose;
13
+ private kill;
14
+ }
@@ -0,0 +1,63 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ export class Command {
3
+ constructor(command, debug) {
4
+ this.command = command;
5
+ this.debug = debug;
6
+ this.terminated = false;
7
+ this.outputBuffers = [];
8
+ this.promise = new Promise((resolve) => {
9
+ this.resolve = resolve;
10
+ });
11
+ this.process = spawn("sh", ["-c", this.command]);
12
+ if (this.debug) {
13
+ this.process.stdout?.on("data", (data) => {
14
+ this.outputBuffers.push(data);
15
+ });
16
+ this.process.stderr?.on("data", (data) => {
17
+ this.outputBuffers.push(data);
18
+ });
19
+ }
20
+ this.process.on("close", (exitCode) => this.onClose(exitCode));
21
+ this.process.on("exit", (exitCode) => this.onExit(exitCode));
22
+ this.terminated = false;
23
+ }
24
+ getPromise() {
25
+ return this.promise;
26
+ }
27
+ onExit(exitCode) {
28
+ this.resolve(exitCode);
29
+ if (this.debug) {
30
+ console.log(this.outputBuffers.join(""));
31
+ }
32
+ this.terminated = true;
33
+ }
34
+ onClose(exitCode) {
35
+ this.resolve(exitCode);
36
+ if (!this.terminated)
37
+ this.kill();
38
+ }
39
+ kill() {
40
+ try {
41
+ const processPid = spawnSync("ps", [
42
+ "-o",
43
+ "pid",
44
+ "--no-headers",
45
+ "--ppid",
46
+ this.process.pid.toString()
47
+ ], {
48
+ encoding: "utf8"
49
+ });
50
+ const pid = parseInt(processPid.output[1]);
51
+ process.kill(pid, "SIGTERM");
52
+ this.process.kill();
53
+ }
54
+ catch (error) {
55
+ if (error instanceof Error) {
56
+ console.warn(error.message);
57
+ }
58
+ else {
59
+ console.warn(error);
60
+ }
61
+ }
62
+ }
63
+ }
@@ -0,0 +1 @@
1
+ export declare const toEsm: (sourceDirectory: string) => Promise<void>;
@@ -0,0 +1,109 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import * as path from "node:path";
3
+ import * as fs from "node:fs/promises";
4
+ const relativePath = async (sourceFile, targetFile) => {
5
+ targetFile = targetFile.trim().slice(1, targetFile.length - 1).replace(".js", "");
6
+ const sourceDir = path.dirname(sourceFile);
7
+ const targetElement = path.resolve(sourceDir, `${targetFile}`);
8
+ try {
9
+ const stat = await fs.stat(targetElement);
10
+ if (stat.isDirectory()) {
11
+ return `${targetFile}/index`;
12
+ }
13
+ return null;
14
+ }
15
+ catch (e) { }
16
+ try {
17
+ const stat = await fs.stat(`${targetElement}.js`);
18
+ if (stat.isFile()) {
19
+ return targetFile;
20
+ }
21
+ return null;
22
+ }
23
+ catch (e) { }
24
+ try {
25
+ const stat = await fs.stat(`${targetElement}.mjs`);
26
+ if (stat.isFile()) {
27
+ return targetFile;
28
+ }
29
+ return null;
30
+ }
31
+ catch (e) {
32
+ return null;
33
+ }
34
+ };
35
+ const replaceInlineImports = async (content, sourceFile) => {
36
+ const pattern = /import\((.*?)\)/g;
37
+ while (true) {
38
+ const match = pattern.exec(content);
39
+ if (match === null) {
40
+ return content;
41
+ }
42
+ const importDeclaration = match[1];
43
+ const importModule = await relativePath(sourceFile, importDeclaration);
44
+ if (!importModule) {
45
+ continue;
46
+ }
47
+ content = content.replace(importDeclaration, `"${importModule}.mjs"`);
48
+ }
49
+ };
50
+ const replaceExportImportDeclarations = async (content, sourceFile) => {
51
+ const pattern = /(export|import)(.*) from ("(.*)");/g;
52
+ while (true) {
53
+ const match = pattern.exec(content);
54
+ if (match === null) {
55
+ return content;
56
+ }
57
+ const declaration = match[3];
58
+ const importModule = await relativePath(sourceFile, declaration);
59
+ if (!importModule) {
60
+ continue;
61
+ }
62
+ content = content.replace(declaration, `"${importModule}.mjs"`);
63
+ }
64
+ };
65
+ const replaceDeclarations = async (content, sourceFile) => {
66
+ return await replaceInlineImports(await replaceExportImportDeclarations(content, sourceFile), sourceFile);
67
+ };
68
+ const fileIsProcessable = (sourcepath) => {
69
+ const extname = path.extname(sourcepath);
70
+ return [".js", ".ts"].includes(extname);
71
+ };
72
+ const esmExtension = (extension) => {
73
+ return (extension === ".js" ? ".mjs" :
74
+ extension === ".ts" ? ".mts" :
75
+ extension);
76
+ };
77
+ const processFile = async (sourceFile) => {
78
+ if (!fileIsProcessable(sourceFile)) {
79
+ return;
80
+ }
81
+ const extname = path.extname(sourceFile);
82
+ const dirname = path.dirname(sourceFile);
83
+ const basename = path.basename(sourceFile, extname);
84
+ const newExtname = esmExtension(extname);
85
+ const sourceContent = await fs.readFile(sourceFile, "utf-8");
86
+ const newContent = replaceDeclarations(sourceContent, sourceFile);
87
+ const newFile = `${path.join(dirname, basename)}${newExtname}`;
88
+ await fs.writeFile(newFile, await newContent);
89
+ await fs.unlink(sourceFile);
90
+ };
91
+ const processDirectory = async (directory) => {
92
+ const files = await fs.readdir(directory);
93
+ for (const file of files) {
94
+ const elementPath = path.join(directory, file);
95
+ await processElement(elementPath);
96
+ }
97
+ };
98
+ const processElement = async (sourcePath) => {
99
+ const element = await fs.stat(sourcePath);
100
+ if (element.isDirectory()) {
101
+ return await processDirectory(sourcePath);
102
+ }
103
+ if (element.isFile()) {
104
+ return await processFile(sourcePath);
105
+ }
106
+ };
107
+ export const toEsm = async (sourceDirectory) => {
108
+ await processElement(sourceDirectory);
109
+ };
@@ -0,0 +1 @@
1
+ export declare const compile: (outDir: string, target: string) => Promise<void>;
@@ -0,0 +1,17 @@
1
+ import { Command } from "../command/index.mjs";
2
+ import { toEsm } from "./cjs-to-esm.mjs";
3
+ export const compile = async (outDir, target) => {
4
+ const options = [
5
+ `--outDir ${outDir}`,
6
+ `--target ${target}`,
7
+ "--module esnext",
8
+ "--declaration",
9
+ "--moduleResolution node"
10
+ ].join(" ");
11
+ const commandLine = `npx tsc ${options}`;
12
+ const command = new Command(commandLine);
13
+ await command.getPromise();
14
+ console.log("Compiling to ESM completed.");
15
+ await toEsm(outDir);
16
+ console.log("Converting to ESM completed.");
17
+ };
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile.mjs";
@@ -0,0 +1 @@
1
+ export * as Builder from "./compile.mjs";
@@ -0,0 +1,8 @@
1
+ type BuildOptions = {
2
+ target: string;
3
+ esmFolder: string;
4
+ cjsFolder: string;
5
+ buildFolder: string;
6
+ };
7
+ export declare const build: (options?: BuildOptions) => Promise<void>;
8
+ export {};
@@ -0,0 +1,21 @@
1
+ import * as esm from "./esm/index.mjs";
2
+ import * as cjs from "./cjs/index.mjs";
3
+ import * as path from "node:path";
4
+ export const build = async (options) => {
5
+ const defaultOptions = {
6
+ target: "es2020",
7
+ esmFolder: "esm",
8
+ cjsFolder: "cjs",
9
+ buildFolder: "dist"
10
+ };
11
+ const { target, esmFolder, cjsFolder, buildFolder } = {
12
+ ...defaultOptions,
13
+ ...options
14
+ };
15
+ console.log("Building...");
16
+ await Promise.all([
17
+ esm.Builder.compile(path.resolve(buildFolder, esmFolder), target),
18
+ cjs.Builder.compile(path.resolve(buildFolder, cjsFolder), target)
19
+ ]);
20
+ console.log(`Build completed. Output directory: ${buildFolder}`);
21
+ };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@fgiova/cjs-esm-ts-builder",
3
+ "version": "1.0.0",
4
+ "description": "Build tool for CJS and ESM modules in TypeScript",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/fgiova/cjs-esm-ts-builder.git"
8
+ },
9
+ "author": "Francesco Giovannini <fgiova@fgiova.com>",
10
+ "license": "MIT",
11
+ "keywords": [
12
+ "nodejs",
13
+ "build",
14
+ "typescript",
15
+ "build-tool",
16
+ "esmodules",
17
+ "esm",
18
+ "cjs",
19
+ "commonjs"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./dist/esm/index.d.mts",
30
+ "default": "./dist/esm/index.mjs"
31
+ },
32
+ "require": {
33
+ "types": "./dist/cjs/index.d.ts",
34
+ "default": "./dist/cjs/index.js"
35
+ }
36
+ }
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "builder.mjs"
41
+ ],
42
+ "bin": {
43
+ "esmBuilder": "./builder.mjs"
44
+ },
45
+ "scripts": {
46
+ "build": "ts-node build.ts",
47
+ "lint": "eslint"
48
+ },
49
+ "dependencies": {
50
+ "arg": "^5.0.2"
51
+ },
52
+ "devDependencies": {
53
+ "@eslint/compat": "^1.2.7",
54
+ "@eslint/eslintrc": "^3.3.0",
55
+ "@eslint/js": "^9.21.0",
56
+ "@semantic-release/changelog": "^6.0.3",
57
+ "@semantic-release/git": "^10.0.1",
58
+ "@tsconfig/node22": "^22.0.0",
59
+ "@types/node": "^22.13.10",
60
+ "conventional-changelog-conventionalcommits": "^8.0.0",
61
+ "eslint": "^9.21.0",
62
+ "eslint-config-prettier": "^10.1.0",
63
+ "eslint-plugin-import": "^2.31.0",
64
+ "eslint-plugin-prefer-arrow": "^1.2.3",
65
+ "eslint-plugin-prettier": "^5.2.3",
66
+ "prettier": "^3.5.3",
67
+ "semantic-release": "^24.2.3",
68
+ "ts-node": "^10.9.2",
69
+ "typescript": "^5.8.2",
70
+ "typescript-eslint": "^8.27.0"
71
+ }
72
+ }