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

Mjs plugins #535

Merged
merged 4 commits into from
Jul 7, 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Released: TBD

### New features

- [#530](https://github.com/peggyjs/peggy/issues/531) Allow es6 plugins from CLI

### Bug fixes

- [#531](https://github.com/peggyjs/peggy/issues/531) Clean up rollup hacks
Expand Down
61 changes: 52 additions & 9 deletions bin/peggy-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class PeggyCLI extends Command {
"-c, --extra-options-file <file>",
"File with additional options (in JSON as an object or commonjs module format) to pass to peggy.generate",
val => {
if (/\.c?js$/.test(val)) {
if (/\.[cm]?js$/.test(val)) {
return this.addExtraOptions(require(path.resolve(val)), "extra-options-file");
} else {
return this.addExtraOptionsJSON(readFile(val), "extra-options-file");
Expand Down Expand Up @@ -229,7 +229,7 @@ class PeggyCLI extends Command {
.hideHelp()
.default(false)
)
.action((inputFiles, opts) => { // On parse()
.action(async(inputFiles, opts) => { // On parse()
this.inputFiles = inputFiles;
this.argv = opts;

Expand All @@ -252,10 +252,10 @@ class PeggyCLI extends Command {
// Combine plugin/plugins
if ((this.argv.plugin && (this.argv.plugin.length > 0))
|| (this.argv.plugins && (this.argv.plugins.length > 0))) {
this.argv.plugins = [
this.argv.plugins = await Promise.all([
...(this.argv.plugins || []),
...(this.argv.plugin || []),
].map(val => {
].map(async val => {
if (typeof val !== "string") {
return val;
}
Expand All @@ -265,16 +265,23 @@ class PeggyCLI extends Command {
: val;
let mod = null;
try {
mod = require(id);
mod = await import(id);
if (typeof mod.use !== "function") {
mod = mod.default;
}
if (typeof mod.use !== "function") {
this.error(`Invalid plugin "${id}", no \`use()\` function`);
}
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND") {
this.error(`requiring:\n${e.stack}`);
if ((e.code === "ERR_MODULE_NOT_FOUND")
|| (e.code === "MODULE_NOT_FOUND")) {
this.error(`importing: ${e.message}`);
} else {
this.error(`requiring "${id}": ${e.message}`);
this.error(`importing "${id}":\n${e.stack}`);
}
}
return mod;
});
}));
}
delete this.argv.plugin;

Expand Down Expand Up @@ -422,6 +429,12 @@ class PeggyCLI extends Command {
}
}

/**
* Print text and a newline to stdout, using util.format.
*
* @param {NodeJS.WriteStream} stream Stream to write to.
* @param {...any} args Format arguments.
*/
static print(stream, ...args) {
stream.write(util.formatWithOptions({
colors: stream.isTTY,
Expand All @@ -432,6 +445,12 @@ class PeggyCLI extends Command {
stream.write("\n");
}

/**
* If we are in verbose mode, print to stderr with a newline.
*
* @param {...any} args Format arguments.
* @returns {boolean} On write, true. Otherwise false.
*/
verbose(...args) {
if (!this.progOptions.verbose) {
return false;
Expand All @@ -440,6 +459,13 @@ class PeggyCLI extends Command {
return true;
}

/**
* Get options from a JSON string.
*
* @param {string} json JSON as text
* @param {string} source Name of option that was the source of the JSON.
* @returns {peggy.BuildOptionsBase}
*/
addExtraOptionsJSON(json, source) {
let extraOptions = undefined;

Expand All @@ -452,6 +478,12 @@ class PeggyCLI extends Command {
return this.addExtraOptions(extraOptions, source);
}

/**
* Add
* @param {peggy.BuildOptionsBase|peggy.BuildOptionsBase[]|null} extraOptions
* @param {string} source
* @returns {peggy.BuildOptionsBase}
*/
addExtraOptions(extraOptions, source) {
if ((extraOptions === null)
|| (typeof extraOptions !== "object")
Expand Down Expand Up @@ -698,6 +730,17 @@ class PeggyCLI extends Command {
this.watcher = null;
}

/**
* @deprecated Use parseAsync instead
* @param {string[]} args Arguments
*/
// eslint-disable-next-line class-methods-use-this
parse(args) {
// Put this here in case anyone was calling PeggyCLI by hand.
// Remove in peggy@v5
throw new Error(`Must call parseAsync: ${args}`);
}

/**
* Entry point. If in watch mode, does `run` in a loop, catching errors,
* otherwise does `run` once.
Expand Down
14 changes: 8 additions & 6 deletions bin/peggy.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ exports.PeggyCLI = PeggyCLI;
// See: https://github.com/facebook/jest/issues/5274
/* istanbul ignore if */
if (require.main === module) {
const cli = new PeggyCLI().parse();
cli.main().then(
code => process.exit(code),
er => {
(async() => {
let code = 1;
try {
const cli = await (new PeggyCLI().parseAsync());
code = await cli.main();
} catch (er) {
console.error("Uncaught Error\n", er);
process.exit(1);
}
);
process.exit(code);
})();
}
20 changes: 19 additions & 1 deletion docs/documentation.html
Original file line number Diff line number Diff line change
Expand Up @@ -1697,6 +1697,20 @@ <h2 id="plugins-api">Plugins API</h2>
That method will be called for all plugins in the <code>options.plugins</code>
array, supplied to the <code>generate()</code> method.</p>

<p>Plugins suitable for use on the command line can be written either as CJS
or MJS modules that export a "use" function. The CLI loads plugins with
<code class="language-js">await(plugin_name)</code>, which should
correctly load from node_modules, a local file starting with "/" or "./",
etc. For example:</p>

<pre><code class="language-js">// CJS
exports.use = (config, options) => {
}</code></pre>

<pre><code class="language-js">// MJS
export function use(config, options) => {
}</code></pre>

<p><code>use</code> accepts these parameters:</p>

<h3><code>config</code></h3>
Expand Down Expand Up @@ -1754,8 +1768,12 @@ <h3><code>options</code></h3>

<p>Build options passed to the <code>generate()</code> method. A best practice
for a plugin would look for its own options under a
<code>&lt;plugin_name&gt;</code> key.</p>
<code>&lt;plugin_name&gt;</code> key:</p>

<pre><code class="language-js">// File: foo.mjs
export function use(config, options) => {
const mine = options['foo_mine'] ?? 'my default';
}</code></pre>

<h3 id="session-api">Session API</h3>

Expand Down
2 changes: 1 addition & 1 deletion docs/js/test-bundle.min.js

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"@rollup/plugin-typescript": "^11.1.6",
"@types/chai": "^4.3.11",
"@types/jest": "^29.5.12",
"@types/node": "^20.14.9",
"@types/node": "^20.14.10",
"@typescript-eslint/eslint-plugin": "^7.15.0",
"@typescript-eslint/parser": "^7.15.0",
"chai": "^4.3.11",
Expand All @@ -71,9 +71,9 @@
"eslint-plugin-compat": "5.0.0",
"eslint-plugin-mocha": "10.4.3",
"express": "4.19.2",
"glob": "^10.4.2",
"glob": "^10.4.3",
"jest": "^29.7.0",
"rimraf": "^5.0.7",
"rimraf": "^5.0.8",
"rollup": "^4.18.0",
"rollup-plugin-ignore": "1.0.10",
"source-map": "^0.8.0-beta.0",
Expand Down
Loading