feat(esm): migrate this package to a pure ESM

BREAKING CHANGE: Please run node 12.20 or higher
BREAKING CHANGE: This package is now a pure esm, please [read this](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c)
This commit is contained in:
Nico Jansen 2022-12-05 23:06:22 +01:00 committed by Antonin Stefanutti
parent 866daced5e
commit 056002fcdc
20 changed files with 513 additions and 519 deletions

View File

@ -2,22 +2,22 @@
'use strict';
const chalk = require('chalk'),
crypto = require('crypto'),
Font = require('fonteditor-core').Font,
fs = require('fs'),
os = require('os'),
parser = require('./libs/nomnom'),
path = require('path'),
puppeteer = require('puppeteer'),
URI = require('urijs'),
util = require('util');
import chalk from 'chalk';
import chalkTemplate from 'chalk-template';
import crypto from 'crypto';
import { Font } from 'fonteditor-core';
import fs from 'fs';
import os from 'os';
import parser from './libs/nomnom.js';
import path from 'path';
import puppeteer from 'puppeteer';
import URI from 'urijs';
import util from 'util';
import { fileURLToPath } from 'url';
const { PDFDocument, PDFName, ParseSpeeds, decodePDFRawStream } = require('pdf-lib');
import { PDFDocument, PDFName, ParseSpeeds, decodePDFRawStream } from 'pdf-lib';
const { delay, pause } = require('./libs/util');
const plugins = loadAvailablePlugins(path.join(path.dirname(__filename), 'plugins'));
import { delay, pause } from './libs/util.js';
parser.script('decktape').options({
url : {
@ -184,7 +184,8 @@ parser.command('version')
.root(true)
.help('Display decktape package version')
.callback(_ => {
console.log(require('./package.json').version);
const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url)));
console.log(pkg.version);
process.exit();
});
parser.nocommand()
@ -198,19 +199,10 @@ parser.command('automatic')
`Iterates over the available plugins, picks the compatible one for presentation at the
specified <url> and uses it to export and write the PDF into the specified <filename>.`
);
Object.entries(plugins).forEach(([id, plugin]) => {
const command = parser.command(id);
if (typeof plugin.options === 'object') {
command.options(plugin.options);
}
if (typeof plugin.help === 'string') {
command.help(plugin.help);
}
});
// TODO: should be deactivated as well when it does not execute in a TTY context
if (os.name === 'windows') parser.nocolors();
const options = parser.parse(process.argv.slice(2));
const color = type => {
switch (type) {
@ -226,6 +218,18 @@ process.on('unhandledRejection', error => {
});
(async () => {
const plugins = await loadAvailablePlugins(path.join(path.dirname(fileURLToPath(import.meta.url)), 'plugins'));
Object.entries(plugins).forEach(([id, plugin]) => {
const command = parser.command(id);
if (typeof plugin.options === 'object') {
command.options(plugin.options);
}
if (typeof plugin.help === 'string') {
command.help(plugin.help);
}
});
const options = parser.parse(process.argv.slice(2));
const browser = await puppeteer.launch({
headless : true,
@ -255,9 +259,9 @@ process.on('unhandledRejection', error => {
.on('requestfailed', request => {
// do not output warning for cancelled requests
if (request.failure() && request.failure().errorText === 'net::ERR_ABORTED') return;
console.log(chalk`\n{keyword('orange') Unable to load resource from URL: ${request.url()}}`);
console.log(chalkTemplate`\n{keyword('orange') Unable to load resource from URL: ${request.url()}}`);
})
.on('pageerror', error => console.log(chalk`\n{red Page error: ${error.message}}`));
.on('pageerror', error => console.log(chalkTemplate`\n{red Page error: ${error.message}}`));
console.log('Loading page', options.url, '...');
const load = page.waitForNavigation({ waitUntil: 'load', timeout: options.urlLoadTimeout });
@ -275,17 +279,16 @@ process.on('unhandledRejection', error => {
.then(_ => exportSlides(plugin, page, pdf))
.then(async context => {
await writePdf(options.filename, pdf);
console.log(chalk`{green \nPrinted {bold ${context.exportedSlides}} slides}`);
console.log(chalkTemplate`{green \nPrinted {bold ${context.exportedSlides}} slides}`);
browser.close();
process.exit();
}))
.catch(error => {
console.log(chalk`{red \n${error}}`);
console.log(chalkTemplate`{red \n${error}}`);
browser.close();
process.exit(1);
});
})();
async function writePdf(filename, pdf) {
const pdfDir = path.dirname(filename);
@ -297,14 +300,15 @@ async function writePdf(filename, pdf) {
fs.writeFileSync(filename, await pdf.save({ addDefaultPage: false }));
}
function loadAvailablePlugins(pluginsPath) {
return fs.readdirSync(pluginsPath).reduce((plugins, pluginPath) => {
async function loadAvailablePlugins(pluginsPath) {
const plugins = await fs.promises.readdir(pluginsPath);
const entries = await Promise.all(plugins.map(async pluginPath => {
const [, plugin] = pluginPath.match(/^(.*)\.js$/);
if (plugin && fs.statSync(path.join(pluginsPath, pluginPath)).isFile()) {
plugins[plugin] = require('./plugins/' + plugin);
if (plugin && (await fs.promises.stat(path.join(pluginsPath, pluginPath))).isFile()) {
return [plugin, await import (`./plugins/${pluginPath}`)];
}
return plugins;
}, {});
}));
return Object.fromEntries(entries.filter(Boolean));
}
async function createPlugin(page) {
@ -321,7 +325,7 @@ async function createPlugin(page) {
throw Error(`Unable to activate the ${plugin.getName()} DeckTape plugin for the address: ${options.url}`);
}
}
console.log(chalk`{cyan {bold ${plugin.getName()}} plugin activated}`);
console.log(chalkTemplate`{cyan {bold ${plugin.getName()}} plugin activated}`);
return plugin;
}
@ -546,3 +550,4 @@ async function progressBar(plugin, context, { skip } = { skip : false }) {
context.progressBarOverflow = Math.max(index.length + 1 - 8, 0);
return cols.join('');
}
})();

View File

@ -1,13 +1,12 @@
var chalk = require('chalk');
import chalk from 'chalk';
function ArgParser() {
class ArgParser {
constructor() {
this.commands = {}; // expected commands
this.specs = {}; // option specifications
}
ArgParser.prototype = {
/* Add a command to the expected commands */
command : function(name) {
command(name) {
var command;
if (name) {
command = this.commands[name] = {
@ -53,77 +52,62 @@ ArgParser.prototype = {
}
};
return chain;
},
nocommand : function() {
}
nocommand() {
return this.command();
},
options : function(specs) {
}
options(specs) {
this.specs = specs;
return this;
},
opts : function(specs) {
}
opts(specs) {
// old API
return this.options(specs);
},
globalOpts : function(specs) {
}
globalOpts(specs) {
// old API
return this.options(specs);
},
option : function(name, spec) {
}
option(name, spec) {
this.specs[name] = spec;
return this;
},
usage : function(usage) {
}
usage(usage) {
this._usage = usage;
return this;
},
printer : function(print) {
}
printer(print) {
this.print = print;
return this;
},
script : function(script) {
}
script(script) {
this._script = script;
return this;
},
scriptName : function(script) {
}
scriptName(script) {
// old API
return this.script(script);
},
help : function(help) {
}
help(help) {
this._help = help;
return this;
},
colors: function() {
}
colors() {
// deprecated - colors are on by default now
return this;
},
nocolors : function() {
}
nocolors() {
this._nocolors = true;
return this;
},
parseArgs : function(argv) {
}
parseArgs(argv) {
// old API
return this.parse(argv);
},
nom : function(argv) {
}
nom(argv) {
return this.parse(argv);
},
parse : function(argv) {
}
parse(argv) {
this.print = this.print || function (str, code) {
console.log(str);
process.exit(code || 0);
@ -321,9 +305,8 @@ ArgParser.prototype = {
}
return options;
},
getUsage : function() {
}
getUsage() {
if (this.command && this.command._usage) {
return this.command._usage;
}
@ -400,10 +383,10 @@ ArgParser.prototype = {
var posStr = pos.string || pos.name;
str += posStr + spaces(longest - posStr.length) + " ";
if (!this._nocolors) {
str += chalk.grey(pos.help || "")
str += chalk.grey(pos.help || "");
}
else {
str += (pos.help || "")
str += (pos.help || "");
}
str += "\n";
}, this);
@ -440,9 +423,7 @@ ArgParser.prototype = {
}
return str;
}
};
ArgParser.prototype.opt = function(arg) {
opt(arg) {
// get the specified opt for this parsed arg
var match = Opt({});
this.specs.forEach(function (opt) {
@ -451,9 +432,8 @@ ArgParser.prototype.opt = function(arg) {
}
});
return match;
};
ArgParser.prototype.setOption = function(options, arg, value) {
}
setOption(options, arg, value) {
var option = this.opt(arg);
if (option.callback) {
var message = option.callback(value);
@ -466,7 +446,7 @@ ArgParser.prototype.setOption = function(options, arg, value) {
if (option.type != "string") {
try {
// infer type by JSON parsing the string
value = JSON.parse(value)
value = JSON.parse(value);
}
catch (e) { }
}
@ -491,7 +471,11 @@ ArgParser.prototype.setOption = function(options, arg, value) {
else {
options[name] = value;
}
};
}
}
/* an arg is an item that's actually parsed from the command line
@ -585,4 +569,4 @@ var createParser = function() {
return new ArgParser();
}
module.exports = createParser();
export default createParser();

View File

@ -1,45 +1,7 @@
'use strict';
module.exports.delay = delay => value => new Promise(resolve => setTimeout(resolve, delay, value));
export const delay = delay => value => new Promise(resolve => setTimeout(resolve, delay, value));
module.exports.pause = ms => module.exports.delay(ms)();
export const pause = ms => delay(ms)();
module.exports.wait = ms => () => module.exports.delay(ms);
// Can be removed when Node 8 becomes a requirement
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String(padString || ' ');
if (this.length > targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length);
}
return padString.slice(0, targetLength) + String(this);
}
};
}
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
if (!String.prototype.padEnd) {
String.prototype.padEnd = function padEnd(targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String(padString || ' ');
if (this.length > targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length);
}
return String(this) + padString.slice(0, targetLength);
}
};
}
export const wait = ms => () => delay(ms);

43
npm-shrinkwrap.json generated
View File

@ -9,7 +9,8 @@
"version": "3.5.0",
"license": "MIT",
"dependencies": {
"chalk": "^4.1.2",
"chalk": "~5.1.2",
"chalk-template": "^0.4.0",
"fonteditor-core": "2.1.10",
"pdf-lib": "1.17.1",
"puppeteer": "18.2.1",
@ -162,6 +163,31 @@
}
},
"node_modules/chalk": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.1.2.tgz",
"integrity": "sha512-E5CkT4jWURs1Vy5qGJye+XwCkNj7Od3Af7CP6SujMetSMkLs8Do2RWJK5yx1wamHV/op8Rz+9rltjaTQWDnEFQ==",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk-template": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz",
"integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==",
"dependencies": {
"chalk": "^4.1.2"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/chalk-template?sponsor=1"
}
},
"node_modules/chalk-template/node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
@ -774,6 +800,19 @@
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
"integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="
},
"chalk": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.1.2.tgz",
"integrity": "sha512-E5CkT4jWURs1Vy5qGJye+XwCkNj7Od3Af7CP6SujMetSMkLs8Do2RWJK5yx1wamHV/op8Rz+9rltjaTQWDnEFQ=="
},
"chalk-template": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz",
"integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==",
"requires": {
"chalk": "^4.1.2"
},
"dependencies": {
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@ -782,6 +821,8 @@
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
}
}
}
},
"chownr": {
"version": "1.1.4",

View File

@ -6,6 +6,7 @@
"homepage": "https://github.com/astefanutti/decktape",
"license": "MIT",
"main": "decktape.js",
"type": "module",
"bin": {
"decktape": "decktape.js"
},
@ -20,7 +21,8 @@
"url": "https://github.com/astefanutti/decktape/issues"
},
"dependencies": {
"chalk": "^4.1.2",
"chalk": "~5.1.2",
"chalk-template": "^0.4.0",
"fonteditor-core": "2.1.10",
"pdf-lib": "1.17.1",
"puppeteer": "18.2.1",
@ -28,6 +30,6 @@
"urijs": "1.19.11"
},
"engines": {
"node": ">=12.0.0"
"node": ">=12.20"
}
}

View File

@ -1,9 +1,9 @@
exports.help =
export const help =
`Requires the bespoke-extern module to expose the Bespoke.js API to a global variable named
'bespoke' and provides access to the collection of deck instances via 'bespoke.decks
and the most recent deck via 'bespoke.deck'.`;
exports.create = page => new Bespoke(page);
export const create = page => new Bespoke(page);
class Bespoke {

View File

@ -1,4 +1,4 @@
exports.create = page => new Deck(page);
export const create = page => new Deck(page);
class Deck {

View File

@ -1,4 +1,4 @@
exports.create = page => new DZSlides(page);
export const create = page => new DZSlides(page);
class DZSlides {

View File

@ -1,4 +1,4 @@
exports.create = page => new Flowtime(page);
export const create = page => new Flowtime(page);
class Flowtime {

View File

@ -2,9 +2,9 @@
// and detects changes to the DOM. The deck is considered over when no change
// is detected afterward.
const { pause } = require('../libs/util');
import { pause } from '../libs/util.js';
exports.options = {
export const options = {
key : {
default : 'ArrowRight',
metavar : '<key>',
@ -23,15 +23,15 @@ exports.options = {
},
};
exports.help =
export const help =
`Emulates the end-user interaction by pressing the key with the specified --key option
and iterates over the presentation as long as:
- Any change to the DOM is detected by observing mutation events targeting the body element
and its subtree,
- Nor the number of slides exported has reached the specified --max-slides option.
The --key option must be one of the 'KeyboardEvent' keys and defaults to [${exports.options.key.default}].`;
The --key option must be one of the 'KeyboardEvent' keys and defaults to [${options.key.default}].`;
exports.create = (page, options) => new Generic(page, options);
export const create = (page, options) => new Generic(page, options);
class Generic {
constructor(page, options) {
@ -39,8 +39,8 @@ class Generic {
this.options = options;
this.currentSlide = 1;
this.isNextSlideDetected = false;
this.key = this.options.key || exports.options.key.default;
this.media = this.options.media || exports.options.media.default;
this.key = this.options.key || options.key.default;
this.media = this.options.media || options.media.default;
}
getName() {

View File

@ -1,4 +1,4 @@
exports.create = page => new Impress(page);
export const create = page => new Impress(page);
class Impress {

View File

@ -1,4 +1,4 @@
exports.create = page => new Inspire(page);
export const create = page => new Inspire(page);
class Inspire {

View File

@ -1,4 +1,4 @@
exports.create = page => new NueDeck(page);
export const create = page => new NueDeck(page);
class NueDeck {

View File

@ -1,4 +1,4 @@
exports.create = page => new Remark(page);
export const create = page => new Remark(page);
class Remark {

View File

@ -1,6 +1,6 @@
const URI = require('urijs');
import URI from 'urijs';
exports.create = page => new Reveal(page);
export const create = page => new Reveal(page);
class Reveal {

View File

@ -1,4 +1,4 @@
exports.create = page => new RISE(page);
export const create = page => new RISE(page);
class RISE {

View File

@ -1,4 +1,4 @@
exports.create = page => new Shower(page);
export const create = page => new Shower(page);
class Shower {

View File

@ -1,4 +1,4 @@
exports.create = page => new Shower(page);
export const create = page => new Shower(page);
class Shower {

View File

@ -1,4 +1,4 @@
exports.create = page => new Slidy(page);
export const create = page => new Slidy(page);
class Slidy {

View File

@ -1,4 +1,4 @@
exports.create = page => new WebSlides(page);
export const create = page => new WebSlides(page);
class WebSlides {