Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 🎸 initial commit @merkur/cli #182

Merged
merged 19 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,18 @@ module.exports = {
},
plugins: ['prettier', 'jest', 'react', 'jasmine'],
settings: {
ecmascript: 2020,
ecmascript: 2022,
jsx: true,
react: {
version: '18',
},
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 11,
ecmaVersion: 13,
},
env: {
[`es2022`]: true,
browser: true,
node: true,
es6: true,
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
preview: ['preact', 'uhtml', 'svelte', 'vanilla']
preview: ['preact', 'vanilla']

steps:
- uses: actions/checkout@v3
Expand Down
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
/packages/*/dist
/packages/*/lib
/packages/*/coverage
/packages/*/node_modules
/packages/*/node_modules
/packages/cli/bin/merkur.mjs
4,940 changes: 2,478 additions & 2,462 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions packages/cli/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/coverage
.babelrc
.eslintrc.js
.gitignore
.npmignore
.npmrc
.prettierignore
.travis.yml
.DS_Store
README.md
CHANGELOG.md
commitlint.config.js
rollup.config.js
babel.config.js
jest.config.js
setupJest.js
1 change: 1 addition & 0 deletions packages/cli/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
registry = "https://registry.npmjs.org/"
5 changes: 5 additions & 0 deletions packages/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Change Log

All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

8 changes: 8 additions & 0 deletions packages/cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Copyright 2024 Miroslav Jancarik [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
git s
5 changes: 5 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Merkur - CLI

## About Merkur

The [Merkur](https://merkur.js.org/) is tiny extensible javascript library for front-end microservices. It allows by default server side rendering for loading performance boost. You can connect it with other frameworks or languages because merkur defines easy API. You can use one of four predefined template's library [Preact](https://preactjs.com/), [µhtml](https://github.com/WebReflection/uhtml#readme), [Svelte](https://svelte.dev/) and [vanilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) but you can easily extend for others.
61 changes: 61 additions & 0 deletions packages/cli/bin/merkur.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/usr/bin/env node
import { Command } from 'commander';
import { dev } from '../src/commands/dev.mjs';
import { build } from '../src/commands/build.mjs';
import { start } from '../src/commands/start.mjs';
import { test } from '../src/commands/test.mjs';
import { COMMAND_NAME } from '../src/commands/constant.mjs';

// eslint-disable-next-line
import packageFile from '../package.json' with { type: 'json' };

const program = new Command();

program
.name('merkur')
.description('CLI for Merkur framework.')
.option('--writeToDisk', 'Write built files to disk.')
.option('--runTask [runTask...]', 'Run only defined task.')
.option('--outFile <string>', 'Server out file configuration to es-build.')
.option('--port <number>', 'Widget server port.')
.option('--devServerPort <number>', 'Dev server port.')
.option('--projectFolder <string>', 'Project folder.')
.option('--buildFolder <string>', 'Build folder.')
.option('--staticFolder <string>', 'Static folder.')
.option('--staticPath <string>', 'The static path for dev server and widget server.')
.option('--inspect', 'Debugging widget server')
.option('--verbose', 'Verbose mode which show debug information.')
.version(packageFile.version);

program.command(COMMAND_NAME.DEV).description('Dev command').action(async (options, cmd) => {
const args = { ...{ writeToDisk: false, watch: true, runTask: ['node', 'es13'] }, ...cmd.optsWithGlobals(), ...options };
process.env.NODE_ENV = process.env.NODE_ENV ?? 'development';

dev({ args, command: COMMAND_NAME.DEV });
});

program.command(COMMAND_NAME.BUILD).action(async (options, cmd) => {
const args = {
...{ writeToDisk: true, watch: false, forceLegacy: true }, ...cmd.optsWithGlobals(), ...options
};
process.env.NODE_ENV = process.env.NODE_ENV ?? 'production';

await build({ args, command: COMMAND_NAME.BUILD });
});

program.command(COMMAND_NAME.START).action(async (options, cmd) => {
const args = {
...{ watch: false }, ...cmd.optsWithGlobals(), ...options
};
process.env.NODE_ENV = process.env.NODE_ENV ?? 'production';

await start({ args, command: COMMAND_NAME.START});
});

program.command(COMMAND_NAME.TEST).allowUnknownOption().action(async (options, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV ?? 'test';

await test({ args: cmd.args, command: COMMAND_NAME.TEST });
});

program.parse(process.argv);
Empty file added packages/cli/index.d.ts
Empty file.
57 changes: 57 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@merkur/cli",
"version": "0.34.0",
"description": "Merkur is tiny and extensible library for creating front-end microservices.",
"bin": {
"merkur": "./bin/merkur.mjs"
},
"exports": {
"./server": {
"import": "./lib/index.mjs",
"require": "./lib/index.cjs"
}
},
"scripts": {
"build": "node ./scripts/build.mjs",
"dev": "node ./scripts/build.mjs --watch"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mjancarik/merkur.git"
},
"keywords": [
"merkur",
"plugin",
"microservices",
"microfrontends",
"cli",
"esbuild"
],
"author": "Miroslav Jancarik",
"license": "ISC",
"bugs": {
"url": "https://github.com/mjancarik/merkur/issues"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"homepage": "https://merkur.js.org/",
"dependencies": {
"@esmj/emitter": "^0.4.1",
"@esmj/observable": "^0.1.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"compression": "^1.7.4",
"esbuild": "^0.20.1",
"esbuild-plugin-manifest": "^1.0.3",
"express": "^4.18.2",
"ws": "^8.16.0"
},
"peerDependencies": {
"@merkur/tools": "*"
},
"engines": {
"node": ">=20"
}
}
53 changes: 53 additions & 0 deletions packages/cli/scripts/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { argv } from 'node:process';
import * as esbuild from 'esbuild';

(async () => {
const watch = argv.some((key) => key.includes('--watch'));
const command = watch ? esbuild.context : esbuild.build;

const devClient = await command({
entryPoints: ['./src/devClient/index.mjs'],
sourcemap: false,
bundle: true,
minify: true,
write: true,
target: 'es2022',
outfile: './lib/devClient.mjs',
});

if (watch) {
await devClient.watch();
}

const moduleMJS = await command({
entryPoints: ['./src/index.mjs'],
sourcemap: false,
bundle: true,
minify: true,
write: true,
format: 'esm',
target: 'es2022',
platform: 'node',
outfile: './lib/index.mjs',
});

if (watch) {
await moduleMJS.watch();
}

const moduleCJS = await command({
entryPoints: ['./src/index.mjs'],
sourcemap: false,
bundle: true,
minify: true,
write: true,
format: 'cjs',
target: 'es2022',
platform: 'node',
outfile: './lib/index.cjs',
});

if (watch) {
await moduleCJS.watch();
}
})();
34 changes: 34 additions & 0 deletions packages/cli/src/CLIConfig.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { EMITTER_EVENTS, emitter, RESULT_KEY } from './emitter.mjs';

export async function createCLIConfig({ args, context, command } = {}) {
const environment = process.env.NODE_ENV;
const isProduction = environment === 'production';

let event = {
cliConfig: {
environment,
isProduction,
command: command ?? 'unknown',
watch: args?.watch ?? !isProduction,
writeToDisk: args?.writeToDisk ?? isProduction,
outFile: args?.outFile ?? './build/widget.cjs',
port: args?.port ?? 4444,
runTask: args?.runTask ?? [],
devServerPort: args?.devServerPort ?? 4445,
projectFolder: args?.projectFolder ?? process.cwd(),
cliFolder: import.meta.dirname,
buildFolder: args?.buildFolder ?? './build',
staticFolder: args?.staticFolder ?? './build/static',
staticPath: args?.staticPath ?? '/static',
inspect: args.inspect ?? false,
verbose: args.verbose ?? false,
},
context,
args,
[RESULT_KEY]: 'cliConfig',
};

event = await emitter.emit(EMITTER_EVENTS.CLI_CONFIG, event);

return event.cliConfig;
}
108 changes: 108 additions & 0 deletions packages/cli/src/buildConfig.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { readdir } from 'node:fs/promises';

import manifestPlugin from 'esbuild-plugin-manifest';

import { EMITTER_EVENTS, emitter, RESULT_KEY } from './emitter.mjs';
import { memoryStaticPlugin } from './plugins/memoryStaticPlugin.mjs';
import { metaPlugin } from './plugins/metaPlugin.mjs';

export async function createBuildConfig({
definition,
config,
merkurConfig,
cliConfig,
context,
}) {
const { isServer, writeToDisk } = config;
const { isProduction, outFile, staticFolder, projectFolder } = cliConfig;

const entries = await getEntries({ merkurConfig, cliConfig });

let event = {
build: {
entryPoints: isServer ? entries.server : entries.client,
bundle: true,
treeShaking: isProduction,
sourcemap: true,
minify: isProduction,
target: 'es2022',
write: writeToDisk,
entryNames: isServer || !isProduction ? 'widget' : 'widget.[hash]',
format: isServer ? 'cjs' : 'iife',
mainFields: isServer ? ['module', 'main'] : ['browser', 'module', 'main'],

//@TODO map right versions
//es6 === es2015, es9 === es2018, es11 === es2020 es13 ===es2022
...(isServer ? { outfile: outFile } : { outdir: `${staticFolder}/es13` }),
...definition.build,

// Alias
alias: {
'@widget': `${projectFolder}/src/widget.js`,
...definition.build.alias,
},

// Plugins
plugins: [
!isServer &&
manifestPlugin({
shortNames: true,
generate: (manifest) => {
return Object.keys(manifest).reduce((result, originalKey) => {
const key = originalKey
.replace('client', 'widget')
.replace('server', 'widget');

result[key] = manifest[originalKey];

return result;
}, {});
},
}),
!writeToDisk && memoryStaticPlugin,
metaPlugin,
...(definition.build?.plugins ?? []),
]
.map((plugin) => {
return typeof plugin === 'function'
? plugin({ definition, config, merkurConfig, cliConfig, context })
: plugin;
})
.filter(Boolean),
},
definition,
config,
cliConfig,
context,
[RESULT_KEY]: 'build',
};

event = await emitter.emit(EMITTER_EVENTS.TASK_BUILD, event);

return event.build;
}

async function getEntries({ merkurConfig, cliConfig }) {
const entries = {
...merkurConfig.defaultEntries,
};

try {
const files = await readdir(`${cliConfig.projectFolder}/src/entries/`);
const FILENAMES = ['client', 'server'];

files.forEach((file) => {
FILENAMES.forEach((filename) => {
if (file.startsWith(filename)) {
entries[filename] = [
`${cliConfig.projectFolder}/src/entries/${file}`,
];
}
});
});
} catch (_) {
/* empty */
}

return entries;
}
Loading
Loading