Skip to content

Commit

Permalink
fix: Implemented correct default export generation
Browse files Browse the repository at this point in the history
  • Loading branch information
m-t-a97 committed Jan 17, 2025
1 parent d29753e commit 264dea9
Show file tree
Hide file tree
Showing 12 changed files with 241 additions and 121 deletions.
86 changes: 68 additions & 18 deletions javascript/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import tsPlugin from '@rollup/plugin-typescript';
import cjsPlugin from '@rollup/plugin-commonjs';
import terserPlugin from '@rollup/plugin-terser';
import dtsPlugin from 'rollup-plugin-dts';

Expand All @@ -23,13 +24,15 @@ export default () => {
entrypoints,
outDir: 'dist',
minify: true,
sourceMap: false,
}),
createLibBuildConfig({
format: 'cjs',
extension: 'js',
entrypoints,
outDir: 'dist',
minify: true,
sourceMap: false,
}),
createTypeDeclarationConfig({
format: 'esm',
Expand All @@ -46,44 +49,98 @@ export default () => {
];
};

function createLibBuildConfig({ format, extension, entrypoints, outDir, minify }) {
function createLibBuildConfig({ format, extension, entrypoints, outDir, minify, sourceMap }) {
const isEsm = format === 'esm';

return {
input: mapInputFiles(entrypoints),
plugins: [
tsPlugin({
exclude: [...testPatterns],
compilerOptions: {
sourceMap: false,
removeComments: true,
noEmit: true,
emitDeclarationOnly: true,
sourceMap,
inlineSources: sourceMap,
removeComments: !sourceMap,
declaration: false,
},
}),
!isEsm && cjsPlugin(),
minify &&
terserPlugin({
ecma: 2020,
}),
],
transformDefaultExportsPlugin(outDir),
].filter(Boolean),
input: mapInputFiles(entrypoints),
output: {
format,
dir: outDir,
preserveModules: format === 'esm',
preserveModules: isEsm,
sourcemap: sourceMap,
exports: 'default',
...getFilenames(extension),
},
};
}

function createTypeDeclarationConfig({ format, entrypoints, outDir, dtsExtension }) {
const isEsm = format === 'esm';

return {
plugins: [
dtsPlugin({
compilerOptions: {
sourceMap: true,
inlineSources: true,
removeComments: false,
declaration: true,
},
}),
transformDefaultExportsPlugin(outDir),
],
input: mapInputFiles(entrypoints),
plugins: [dtsPlugin()],
output: {
format,
dir: outDir,
preserveModules: isEsm,
preserveModulesRoot: 'src',
generatedCode: 'es2015',
exports: 'default',
...getFilenames(dtsExtension),
preserveModules: true,
preserveModulesRoot: 'src',
},
};
}

function clearDist() {
const distPath = join(directoryName, 'dist');
if (fs.existsSync(distPath)) {
fs.rmSync(distPath, { recursive: true, force: true });
}
}

function transformDefaultExportsPlugin(outDir) {
return {
name: 'fix-default-exports',
writeBundle: (options, bundle) => {
for (const [fileName, file] of Object.entries(bundle)) {
if (file.type !== 'chunk') {
continue;
}

const filePath = join(outDir, fileName);
const code = fs.readFileSync(filePath, 'utf-8');

let transformedCode = '';

if (fileName.endsWith('.mjs') || fileName.endsWith('.js')) {
transformedCode = code.replace(/export\{(\w+) as default\};/g, 'export default $1;');
} else if (fileName.endsWith('.d.mts')) {
transformedCode = code.replace(/export \{ (\w+) as default \};/g, 'export default $1;');
} else if (fileName.endsWith('.d.ts')) {
transformedCode = code.replace(/export \{ (\w+) as default \};/g, 'export = $1;');
}

fs.writeFileSync(filePath, transformedCode, 'utf-8');
}
},
};
}
Expand All @@ -105,10 +162,3 @@ function getFilenames(extension) {
chunkFileNames: `_chunk/[name]-[hash].${extension}`,
};
}

function clearDist() {
const distPath = join(directoryName, 'dist');
if (fs.existsSync(distPath)) {
fs.rmSync(distPath, { recursive: true, force: true });
}
}
3 changes: 2 additions & 1 deletion javascript/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Kestra, Logger } from './kestra';
import Kestra from './kestra/kestra';
import type { Logger } from './types';

type LogMethod = (...message: any) => void;

Expand Down
4 changes: 3 additions & 1 deletion javascript/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { Kestra as default } from './kestra';
import Kestra from './kestra/kestra';

export default Kestra;
82 changes: 0 additions & 82 deletions javascript/src/kestra.ts

This file was deleted.

95 changes: 95 additions & 0 deletions javascript/src/kestra/kestra.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import ConsoleLogger from '../logging/console-logger';
import { KestraFunction, Logger } from '../types';

const Kestra: KestraFunction = function () {} as KestraFunction;

/**
* Formats a map object as a string by converting it to a JSON string
* and surrounding it with "::" delimiters.
*
* @param map - The map object to format.
* @returns The formatted string.
*/
Kestra.format = (map: Record<string, any>): string => {
return '::' + JSON.stringify(map) + '::';
};

/**
* Sends a log message to the standard output.
*
* @param map - The map object containing the log data.
*/
Kestra._send = (map: Record<string, any>) => {
console.log(Kestra.format(map));
};

/**
* Sends a metric to the standard output.
*
* @param name - The name of the metric.
* @param type - The type of the metric.
* @param value - The value of the metric.
* @param tags - The tags of the metric.
*/
Kestra._metrics = (name: string, type: string, value: any, tags: any) => {
Kestra._send({
metrics: [
{
name: name,
type: type,
value: value,
tags: tags || {},
},
],
});
};

Kestra.outputs = (outputs: any) => {
Kestra._send({
outputs: outputs,
});
};

/**
* Sends a counter metric to the standard output.
*
* @param name - The name of the metric.
* @param value - The value of the metric.
* @param tags - The tags of the metric.
*/
Kestra.counter = (name: string, value: any, tags: any) => {
Kestra._metrics(name, 'counter', value, tags);
};

/**
* Measures the duration of a timer and sends the metric.
*
* @param name - The name of the timer.
* @param duration - The duration in seconds or a function to measure the duration.
* @param tags - Additional metadata tags for the timer.
*/
Kestra.timer = (name: string, duration: number | ((func: () => void) => void), tags: any) => {
// Check if duration is a function to execute for measuring time
if (typeof duration === 'function') {
const start = new Date();
// Execute the function and calculate elapsed time
duration(() => {
const elapsedTime = (new Date().getTime() - start.getTime()) / 1000;
Kestra._metrics(name, 'timer', elapsedTime, tags);
});
} else {
// Directly use the provided duration value
Kestra._metrics(name, 'timer', duration, tags);
}
};

/**
* Provides an instance of the Logger.
*
* @returns A Logger instance.
*/
Kestra.logger = (): Logger => {
return new ConsoleLogger(Kestra);
};

export default Kestra;
36 changes: 36 additions & 0 deletions javascript/src/logging/console-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { KestraFunction, Log, Logger } from '../types';

export default class ConsoleLogger implements Logger {
constructor(private readonly Kestra: KestraFunction) {}

trace(...message: any): void {
console.trace(this.Kestra.format(this._log('TRACE', message)));
}

debug(...message: any): void {
console.debug(this.Kestra.format(this._log('DEBUG', message)));
}

info(...message: any): void {
console.info(this.Kestra.format(this._log('INFO', message)));
}

warn(...message: any): void {
console.warn(this.Kestra.format(this._log('WARN', message)));
}

error(...message: any): void {
console.error(this.Kestra.format(this._log('ERROR', message)));
}

_log(level: string, message: string | string[]): { logs: Log[] } {
return {
logs: (Array.isArray(message) ? message : [message]).map((value: string) => {
return {
level: level,
message: value,
};
}),
};
}
}
4 changes: 0 additions & 4 deletions javascript/src/types.ts

This file was deleted.

2 changes: 2 additions & 0 deletions javascript/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './logging';
export * from './kestra';
12 changes: 12 additions & 0 deletions javascript/src/types/kestra.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Logger } from './logging';

export interface KestraFunction {
(): void;
format(map: Record<string, any>): string;
_send(map: Record<string, any>): void;
_metrics(name: string, type: string, value: any, tags: any): void;
outputs(outputs: any): void;
counter(name: string, value: any, tags: any): void;
timer(name: string, duration: number | ((callback: () => void) => void), tags: any): void;
logger(): Logger;
}
Loading

0 comments on commit 264dea9

Please sign in to comment.