Skip to content

Commit

Permalink
📦 Minifying the npm package
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Sep 21, 2024
1 parent 863bcce commit 23833b2
Show file tree
Hide file tree
Showing 13 changed files with 197 additions and 178 deletions.
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@ eslint.config.js
tsconfig.json
tsconfig.cjs.json
tsconfig.dts.json
tsconfig.mjs.json
tsconfig.mjs.json

bun.lockb
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,8 @@ Usage: tjss [options]
```

### 👨‍💻 | Code:
##### ⚠️ | Warning: Currently only use this package in projects that support ESM natively, it won't work with commonjs (CJS)!

```ts
// build.ts
import 'js-to-sh/loader' // this should be in the main file of your project
// build.ts - Esm
import { Transpiler } from 'js-to-sh'

const AST = await new Transpiler({ path: 'src/test.js' }).loader()
Expand All @@ -70,10 +67,32 @@ const code = Transpiler.parser(AST)
console.log(code)
```

```ts
// build.ts - Communjs
const { Transpiler } = require('js-to-sh'); // <-- yes, you need that here ”;”

(async () => {
const ast = await (new Transpiler({ path: 'src/test.js', cwd: process.cwd() })).loader()
const code = Transpiler.parser(ast)

console.log(code)
})()
```

## 🌎 | Global variables

These global variables are associated with static functions, which are imported during the build process of the file. You should use these functions if you need to leverage shellscript behaviors.

```ts
// To use these functions in JavaScript, without the conversion, for backward compatibility (work in JavaScript and ShellScript), you should use:

// Communjs
require('js-to-sh/loader')

// Esm
import 'js-to-sh/globals'
```

```ts
// Checks if a specific command exists in the operating system where the script is running.
isCommand(command)
Expand Down
28 changes: 25 additions & 3 deletions build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import { build } from 'tsup'
await build({
platform: 'node',
format: 'cjs',
entry: ['src/**/*.ts'],
entry: ['src/index.ts'],
outDir: 'dist/cjs',
tsconfig: './tsconfig.cjs.json',
bundle: false,
bundle: true,
shims: true,
minify: true,
minifyIdentifiers: true,
minifySyntax: true,
minifyWhitespace: true,
skipNodeModulesBundle: true,
splitting: false,
clean: true,
Expand All @@ -20,4 +25,21 @@ const files = await glob('dist/**/*.cjs', { cwd: process.cwd() })
for (const filename of files) {
const newName = filename.replace('.cjs', '.js')
await rename(filename, newName)
}
}

await build({
platform: 'node',
format: 'esm',
entry: ['src/index.ts'],
outDir: 'dist/mjs',
tsconfig: './tsconfig.mjs.json',
bundle: true,
minify: true,
minifyIdentifiers: true,
minifySyntax: true,
minifyWhitespace: true,
skipNodeModulesBundle: true,
splitting: true,
clean: true,
dts: false
})
Binary file added bun.lockb
Binary file not shown.
16 changes: 15 additions & 1 deletion fixup.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/bin/bash

cat >dist/cjs/package.json <<!EOF
{
"type": "commonjs"
Expand All @@ -8,4 +10,16 @@ cat >dist/mjs/package.json <<!EOF
{
"type": "module"
}
!EOF
!EOF

arquivos_js=("dist/cjs/index.js" "dist/mjs/index.js")

for arquivo in "${arquivos_js[@]}"; do
if ! grep -q "^#!/usr/bin/env node" "$arquivo"; then
sed -i '1i#!/usr/bin/env node' "$arquivo"
chmod 777 $arquivo
echo "Linha adicionada no início do arquivo $arquivo"
else
echo "Linha já está presente no arquivo $arquivo"
fi
done
29 changes: 15 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"name": "js-to-sh",
"description": "Turn javascript code into shellscript",
"version": "1.1.7",
"main": "dist/cjs/index.cjs",
"version": "1.1.8",
"main": "dist/cjs/index.js",
"module": "dist/mjs/index.js",
"types": "dist/types/index.d.ts",
"typings": "dist/types/index.d.ts",
"type": "module",
"bin": {
Expand All @@ -23,19 +24,19 @@
},
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"import": "./dist/mjs/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/types/index.d.ts"
"require": "./dist/cjs/index.js"
},
"./globals": {
"import": "./dist/types/types/globals.d.ts",
"require": "./dist/cjs/types/global.js",
"types": "./dist/types/types/globals.d.ts"
"types": "./dist/types/types/index.d.ts",
"import": "./dist/types/types/index.d.ts",
"require": "./dist/types/types/index.d.js"
},
"./loader": {
"import": "./dist/mjs/loader/index.js",
"require": "./dist/cjs/loader/index.js",
"types": "./dist/types/loader/index.d.ts"
"types": "./dist/types/index.d.ts",
"import": "./dist/mjs/index.js",
"require": "./dist/cjs/index.js"
}
},
"engines": {
Expand All @@ -44,10 +45,9 @@
"scripts": {
"cli": "tsx src/cli.ts",
"test": "tsx test/app.ts && chmod 777 output/*",
"build": "rimraf dist && npm run build:mjs && npm run build:dts && npm run build:cjs && cp -R src/transformers/shellscript dist/mjs/transformers/shellscript && cp -R src/transformers/shellscript dist/cjs/transformers/shellscript && ./fixup.sh && npm run lint -- --fix",
"build:mjs": "tsc -p tsconfig.mjs.json && tsc-alias -p tsconfig.mjs.json",
"build:cjs": "npx tsx build.ts",
"build:dts": "tsc -p tsconfig.dts.json && tsc-alias -p tsconfig.dts.json",
"build": "rimraf dist && npm run build:tsup && npm run build:dts && ./fixup.sh && cp -R src/transformers/shellscript dist/transformers",
"build:tsup": "npx tsx build.ts",
"build:dts": "mkdir dist/types && ./node_modules/.bin/dts-bundle-generator -o dist/types/index.d.ts --verbose --no-check --sort --external-imports=meriyah --external-types=meriyah --external-inlines=meriyah -- src/index.ts",
"lint": "eslint -c eslint.config.js"
},
"keywords": [
Expand Down Expand Up @@ -79,6 +79,7 @@
"devDependencies": {
"@eslint/js": "^9.9.0",
"@types/node": "^22.2.0",
"dts-bundle-generator": "^9.5.1",
"eslint": "^9.9.0",
"globals": "^15.9.0",
"meriyah": "^5.0.0",
Expand Down
45 changes: 0 additions & 45 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 12 additions & 15 deletions src/class/transpiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ import { ParseFetch } from '../modules/fetch.js'
import { ParserClass } from '../transpilers/class.js'
import { ParseFunction } from '../transpilers/funtion.js'
import { ParseIFs } from '../transpilers/ifElse.js'
import { ParserSwitch } from '../transpilers/switch.js'
import { ParseLoops } from '../transpilers/loops.js'
import { ParserSwitch } from '../transpilers/switch.js'
import { Colors, Rgb } from '@loggings/beta'
// @ts-ignore
import AbstractSyntaxTree from 'abstract-syntax-tree'
import { existsSync, readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { ArrowFunctionExpression, AwaitExpression, ClassDeclaration, NewExpression, ObjectExpression, ObjectLiteralElementLike, Property } from '../../node_modules/meriyah/dist/src/estree.js'
import { basename, dirname, join, resolve } from 'path'
import { ArrowFunctionExpression, AwaitExpression, ClassDeclaration, NewExpression, ObjectExpression, ObjectLiteralElementLike, Property } from '../../node_modules/meriyah/dist/src/estree.js'
import { ArrayExpression, BinaryExpression, BlockStatement, BlockStatementBase, BreakStatement, CallExpression, DeclarationStatement, Expression, ExpressionStatement, ForOfStatement, FunctionDeclaration, FunctionExpression, Identifier, IfStatement, ImportDeclaration, Literal, MemberExpression, MetaProperty, Parameter, PrivateIdentifier, ReturnStatement, SpreadElement, Statement, SwitchStatement, TemplateLiteral, VariableDeclaration } from '../../node_modules/meriyah/src/estree.js'
import { Colors, Rgb } from '@loggings/beta'
import { getTransformers } from '../loader.js'

interface TransformOptions {
path: string
Expand All @@ -33,15 +34,10 @@ export class Transpiler {
path: join(options.cwd ?? '', options.path)
}

global.console = {
...global.console,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
debug(message?: any, ...optionalParams: any[]) {
if (Transpiler.options.debug) process.stdout.write(`${message} ${optionalParams.join('\n')}\n`)
},
}
// @ts-ignore
global.loggings.config({ format: '{message}', level: Transpiler.options?.debug ? 'debug' : 'info' })

console.debug(Rgb(249, 248, 113) +'Debug Mode!')
console.debug(Rgb(249, 248, 113) + 'Debug Mode!')
console.debug(Rgb(132, 94, 194) + 'Compiling:', Rgb(255, 199, 95) + basename(Transpiler.options.path), Transpiler.options.path)
}

Expand Down Expand Up @@ -296,23 +292,24 @@ export class Transpiler {
return this.parseMemberExpression(callee, args.map((arg) => this.parseReturnString(arg.type, this.parseExpression(arg) as string)).join(' '))
} else {
const functionName = expression.callee.name
const rootPath = join(import.meta.dirname, '..')
const transformers: Record<string, string> = {}
getTransformers().map((transformer) => Object.assign(transformers, { [basename(transformer)]: transformer }))

/**
* Aqui é definido o transformers de certas funções, como o fetch, onde é puxado a função que trata o fetch entre curl e wget, e o isCommand para validar se existe as dependencias
*/
switch (functionName) {
case 'fetch': {
const fetchCode = readFileSync(join(rootPath, 'transformers/shellscript/fetch.sh'), { encoding: 'utf-8' })
const isCommandCode = readFileSync(join(rootPath, 'transformers/shellscript/isCommand.sh'), { encoding: 'utf-8' })
const fetchCode = readFileSync(transformers['fetch.sh'], { encoding: 'utf-8' })
const isCommandCode = readFileSync(transformers['isCommand.sh'], { encoding: 'utf-8' })
Transpiler.globalDeclarations = Object.assign({ 'isCommand': isCommandCode, 'fetch': fetchCode }, Transpiler.globalDeclarations)
break
}
}

const args = expression.arguments.map((arg) => this.parseReturnString(arg.type, this.parseExpression(arg) as string)) as (string)[]

const transformer = join(rootPath, 'transformers/shellscript', `${functionName}.sh`)
const transformer = transformers[`${functionName}.sh`]

if (existsSync(transformer)) {
const transformerCode = readFileSync(transformer, { encoding: 'utf-8' })
Expand Down
Loading

0 comments on commit 23833b2

Please sign in to comment.