Socket
Socket
Sign inDemoInstall

listr2

Package Overview
Dependencies
Maintainers
1
Versions
232
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

listr2 - npm Package Compare versions

Comparing version 1.0.3 to 1.1.0

dist/interfaces/listr.interface.d.ts

22

dist/index.d.ts

@@ -1,18 +0,4 @@

import { ListrError } from './interfaces/listr-error';
import { ListrClass, ListrContext, ListrOptions, ListrRendererClass, ListrTask } from './interfaces/listr-task.interface';
export declare class Listr<Ctx = ListrContext> implements ListrClass {
task: ListrTask<Ctx>[];
options?: ListrOptions;
tasks: ListrClass['tasks'];
err: ListrError[];
exitOnError: ListrOptions['exitOnError'];
rendererClass: ListrRendererClass<Ctx>;
context: Ctx;
private concurrency;
private renderer;
constructor(task: ListrTask<Ctx>[], options?: ListrOptions);
add(task: ListrTask | ListrTask[]): void;
run(context?: Ctx): Promise<Ctx>;
private checkAll;
private runTask;
}
export * from './listr';
export * from './manager';
export * from './interfaces/listr.interface';
export * from './interfaces/manager.interface';
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const pMap = require("p-map");
const listr_error_1 = require("./interfaces/listr-error");
const task_1 = require("./lib/task");
const task_wrapper_1 = require("./lib/task-wrapper");
const renderer_1 = require("./utils/renderer");
class Listr {
constructor(task, options) {
var _a;
this.task = task;
this.options = options;
this.tasks = [];
this.err = [];
this.options = Object.assign({
showSubtasks: true,
concurrent: false,
renderer: 'default',
nonTTYRenderer: 'verbose',
exitOnError: true,
collapse: true
}, options);
this.concurrency = 1;
if (this.options.concurrent === true) {
this.concurrency = Infinity;
}
else if (typeof this.options.concurrent === 'number') {
this.concurrency = this.options.concurrent;
}
this.rendererClass = renderer_1.getRenderer(this.options.renderer, this.options.nonTTYRenderer);
this.exitOnError = this.options.exitOnError;
this.context = (_a = this.options) === null || _a === void 0 ? void 0 : _a.ctx;
this.add(task || []);
}
add(task) {
const tasks = Array.isArray(task) ? task : [task];
tasks.forEach((task) => {
this.tasks.push(new task_1.Task(this, task, this.options));
});
}
async run(context) {
if (!this.renderer) {
this.renderer = new this.rendererClass(this.tasks, this.options);
}
this.renderer.render();
context = context || this.context || Object.create({});
const errors = [];
await this.checkAll(context);
try {
await pMap(this.tasks, async (task) => {
await this.checkAll(context);
return this.runTask(task, context, errors);
}, { concurrency: this.concurrency });
if (errors.length > 0) {
const err = new listr_error_1.ListrError('Something went wrong');
err.errors = errors;
throw err;
}
this.renderer.end();
return context;
}
catch (error) {
error.context = context;
this.renderer.end(error);
if (this.exitOnError !== false) {
throw error;
}
}
}
checkAll(context) {
return Promise.all(this.tasks.map((task) => {
task.check(context);
}));
}
runTask(task, context, errors) {
if (!task.isEnabled()) {
return Promise.resolve();
}
return new task_wrapper_1.TaskWrapper(task, errors).run(context);
}
}
exports.Listr = Listr;
__export(require("./listr"));
__export(require("./manager"));
__export(require("./interfaces/listr.interface"));
__export(require("./interfaces/manager.interface"));
//# sourceMappingURL=index.js.map

@@ -1,3 +0,5 @@

import { ListrError } from '../interfaces/listr-error';
import { ListrTaskWrapper, StateConstants } from './../interfaces/listr-task.interface';
import { ListrTaskWrapper, StateConstants, ListrTask, ListrOptions, ListrError } from '../interfaces/listr.interface';
import { Listr } from '../listr';
import { PromptOptions } from '../utils/prompt.interface';
import { PromptTypes } from './../utils/prompt.interface';
import { Task } from './task';

@@ -12,5 +14,7 @@ export declare class TaskWrapper<Ctx> implements ListrTaskWrapper {

set state(data: StateConstants);
newListr<Ctx>(task: ListrTask<Ctx>[], options?: ListrOptions): Listr<Ctx>;
report(error: Error | ListrError): void;
skip(message: string): void;
prompt(type: PromptTypes, prompt: PromptOptions): Promise<any>;
run(ctx: Ctx): Promise<void>;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const through_1 = __importDefault(require("through"));
const state_constants_1 = require("../constants/state.constants");
const listr_error_1 = require("../interfaces/listr-error");
const listr_interface_1 = require("../interfaces/listr.interface");
const listr_1 = require("../listr");
const prompt_1 = require("../utils/prompt");
class TaskWrapper {

@@ -34,5 +40,8 @@ constructor(task, errors) {

}
newListr(task, options) {
return new listr_1.Listr(task, options);
}
report(error) {
var _a, _b;
if (error instanceof listr_error_1.ListrError) {
if (error instanceof listr_interface_1.ListrError) {
for (const err of error.errors) {

@@ -55,2 +64,18 @@ this.errors.push(err);

}
prompt(type, prompt) {
this.task.prompt = true;
let buffer = Buffer.alloc(64);
const outputStream = through_1.default((data) => {
buffer += data;
const deleteMultiLineRegexp = new RegExp(/.*\u001b\[.*G.*/);
if (deleteMultiLineRegexp.test(buffer.toString())) {
buffer = Buffer.alloc(64);
}
else {
this.output = buffer;
}
});
Object.assign(prompt, { stdout: outputStream });
return prompt_1.createPrompt(type, prompt);
}
run(ctx) {

@@ -57,0 +82,0 @@ return this.task.run(ctx, this);

import { Subject } from 'rxjs';
import { ListrContext, ListrOptions, ListrTask, ListrTaskObject, ListrTaskWrapper, ListrEvent, StateConstants } from '../interfaces/listr-task.interface';
import { Listr } from './../index';
import { ListrContext, ListrEvent, ListrOptions, ListrTask, ListrTaskObject, ListrTaskWrapper, StateConstants } from '../interfaces/listr.interface';
import { Listr } from './../listr';
export declare class Task<Ctx> extends Subject<ListrEvent> implements ListrTaskObject<ListrContext> {

@@ -17,2 +17,3 @@ listr: Listr<Ctx>;

enabledFn: ListrTask['enabled'];
prompt: ListrTaskObject<Ctx>['prompt'];
constructor(listr: Listr<Ctx>, tasks: ListrTask, options: ListrOptions);

@@ -29,3 +30,4 @@ set state$(state: StateConstants);

hasTitle(): boolean;
isPrompt(): boolean;
run(context: Ctx, wrapper: ListrTaskWrapper<Ctx>): Promise<void>;
}
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const sttoob = require("@samverschueren/stream-to-observable");
const sttoob = __importStar(require("@samverschueren/stream-to-observable"));
const rxjs_1 = require("rxjs");
const stream_1 = require("stream");
const state_constants_1 = require("../constants/state.constants");
const listr_error_1 = require("../interfaces/listr-error");
const listr_interface_1 = require("../interfaces/listr.interface");
const renderer_1 = require("../utils/renderer");
const index_1 = require("./../index");
const listr_1 = require("./../listr");
class Task extends rxjs_1.Subject {

@@ -69,6 +76,9 @@ constructor(listr, tasks, options) {

}
isPrompt() {
return this.prompt;
}
async run(context, wrapper) {
const handleResult = (result) => {
var _a;
if (result instanceof index_1.Listr) {
if (result instanceof listr_1.Listr) {
result.options = Object.assign(this.options, result.options);

@@ -83,2 +93,4 @@ result.exitOnError = (_a = result.options) === null || _a === void 0 ? void 0 : _a.exitOnError;

}
else if (this.isPrompt()) {
}
else if (result instanceof Promise) {

@@ -127,3 +139,6 @@ result = result.then(handleResult);

this.state$ = state_constants_1.stateConstants.FAILED;
if (error instanceof listr_error_1.ListrError) {
if (this.isPrompt()) {
error = new Error('Cancelled the prompt.');
}
if (error instanceof listr_interface_1.ListrError) {
wrapper.report(error);

@@ -130,0 +145,0 @@ return;

@@ -1,2 +0,2 @@

import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr-task.interface';
import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr.interface';
export declare class MultiLineRenderer implements ListrRenderer {

@@ -10,2 +10,3 @@ tasks: ListrTaskObject<any>[];

private bottomBar;
private promptBar;
constructor(tasks: ListrTaskObject<any>[], options: ListrOptions);

@@ -16,2 +17,3 @@ render(): void;

private renderBottomBar;
private renderPrompt;
private dumpData;

@@ -18,0 +20,0 @@ private formatString;

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const cliCursor = require("cli-cursor");
const cliTruncate = require("cli-truncate");
const elegantSpinner = require("elegant-spinner");
const figures = require("figures");
const indentString = require("indent-string");
const logUpdate = require("log-update");
const chalk_1 = __importDefault(require("chalk"));
const cli_cursor_1 = __importDefault(require("cli-cursor"));
const cli_truncate_1 = __importDefault(require("cli-truncate"));
const elegant_spinner_1 = __importDefault(require("elegant-spinner"));
const figures_1 = __importDefault(require("figures"));
const indent_string_1 = __importDefault(require("indent-string"));
const log_update_1 = __importDefault(require("log-update"));
class MultiLineRenderer {

@@ -19,3 +22,3 @@ constructor(tasks, options) {

render() {
cliCursor.hide();
cli_cursor_1.default.hide();
if (this.id) {

@@ -25,3 +28,3 @@ return;

this.id = setInterval(() => {
logUpdate(this.multiLineRenderer(this.tasks), this.renderBottomBar());
log_update_1.default(this.multiLineRenderer(this.tasks), this.renderBottomBar(), this.renderPrompt());
}, 100);

@@ -34,5 +37,5 @@ }

}
logUpdate(this.multiLineRenderer(this.tasks));
logUpdate.done();
cliCursor.show();
log_update_1.default(this.multiLineRenderer(this.tasks));
log_update_1.default.done();
cli_cursor_1.default.show();
}

@@ -44,7 +47,10 @@ multiLineRenderer(tasks, level = 0) {

if (task.hasTitle()) {
const taskTitle = !task.isSkipped() ? task === null || task === void 0 ? void 0 : task.title : `${task === null || task === void 0 ? void 0 : task.output} ${chalk.dim('[SKIPPED]')}`;
const taskTitle = !task.isSkipped() ? task === null || task === void 0 ? void 0 : task.title : `${task === null || task === void 0 ? void 0 : task.output} ${chalk_1.default.dim('[SKIPPED]')}`;
output.push(this.formatString(taskTitle, this.getSymbol(task, this.options), level));
}
if (task.isPending() && (task === null || task === void 0 ? void 0 : task.output)) {
if (task.isBottomBar() || !task.hasTitle()) {
if (task.isPrompt()) {
this.promptBar = task.output;
}
else if (task.isBottomBar() || !task.hasTitle()) {
const data = this.dumpData(task.output, -1);

@@ -65,2 +71,6 @@ if (!(data === null || data === void 0 ? void 0 : data.some((element) => this.bottomBar.includes(element)))) {

}
if (task.isCompleted()) {
this.promptBar = null;
this.bottomBar = [];
}
}

@@ -76,2 +86,7 @@ }

}
renderPrompt() {
if (this.promptBar) {
return `\n\n${this.promptBar}`;
}
}
dumpData(taskOutput, level) {

@@ -81,3 +96,3 @@ const output = [];

taskOutput.split('\n').filter(Boolean).forEach((line, i) => {
const icon = i === 0 ? figures.pointerSmall : ' ';
const icon = i === 0 ? figures_1.default.pointerSmall : ' ';
output.push(this.formatString(line, icon, level + 1));

@@ -89,21 +104,24 @@ });

formatString(string, icon, level) {
return `${cliTruncate(indentString(`${icon} ${string}`, (level) * this.indentation), process.stdout.columns - 3)}`;
return `${cli_truncate_1.default(indent_string_1.default(`${icon} ${string}`, (level) * this.indentation), process.stdout.columns - 3)}`;
}
getSymbol(task, options) {
if (!task.spinner) {
task.spinner = elegantSpinner();
task.spinner = elegant_spinner_1.default();
}
if (task.isPending()) {
return options.showSubtasks !== false && task.hasSubtasks() ? chalk.yellow(figures.pointer) : chalk.yellowBright(task.spinner());
return options.showSubtasks !== false && task.hasSubtasks() ? chalk_1.default.yellow(figures_1.default.pointer) : chalk_1.default.yellowBright(task.spinner());
}
if (task.isCompleted()) {
return chalk.green(figures.tick);
return chalk_1.default.green(figures_1.default.tick);
}
if (task.hasFailed()) {
return task.hasSubtasks() ? chalk.red(figures.play) : chalk.red(figures.cross);
return task.hasSubtasks() ? chalk_1.default.red(figures_1.default.play) : chalk_1.default.red(figures_1.default.cross);
}
if (task.isSkipped()) {
return chalk.yellow(figures.arrowDown);
return chalk_1.default.yellow(figures_1.default.arrowDown);
}
return chalk.dim(figures.squareSmallFilled);
if (task.isPrompt()) {
return chalk_1.default.cyan(figures_1.default.questionMarkPrefix);
}
return chalk_1.default.dim(figures_1.default.squareSmallFilled);
}

@@ -110,0 +128,0 @@ }

@@ -1,2 +0,2 @@

import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr-task.interface';
import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr.interface';
export declare class SilentRenderer implements ListrRenderer {

@@ -3,0 +3,0 @@ tasks: ListrTaskObject<any>[];

@@ -1,2 +0,2 @@

import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr-task.interface';
import { ListrOptions, ListrRenderer, ListrTaskObject } from '../interfaces/listr.interface';
export declare class VerboseRenderer implements ListrRenderer {

@@ -3,0 +3,0 @@ tasks: ListrTaskObject<any>[];

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const figures = require("figures");
const pad = require("pad");
const chalk_1 = __importDefault(require("chalk"));
const figures_1 = __importDefault(require("figures"));
const winston_1 = require("winston");

@@ -32,3 +34,2 @@ const logger_constants_1 = require("./logger.constants");

let icon;
const context = level;
let coloring = (input) => {

@@ -39,24 +40,24 @@ return input;

case logger_constants_1.logLevels.fail:
coloring = chalk.red;
icon = figures.cross;
coloring = chalk_1.default.red;
icon = figures_1.default.cross;
break;
case logger_constants_1.logLevels.skip:
coloring = chalk.yellow;
icon = figures.arrowDown;
coloring = chalk_1.default.yellow;
icon = figures_1.default.arrowDown;
break;
case logger_constants_1.logLevels.success:
coloring = chalk.green;
icon = figures.tick;
coloring = chalk_1.default.green;
icon = figures_1.default.tick;
break;
case logger_constants_1.logLevels.data:
icon = figures.arrowRight;
icon = figures_1.default.arrowRight;
break;
case logger_constants_1.logLevels.start:
icon = figures.pointer;
icon = figures_1.default.pointer;
break;
default:
icon = figures.pointer;
icon = figures_1.default.pointer;
break;
}
return coloring(`${icon} ${pad(context.toUpperCase(), 7)} | ${message}`);
return coloring(`${icon} ${message}`);
}

@@ -63,0 +64,0 @@ }

@@ -1,2 +0,2 @@

import { ListrContext, ListrRendererClass, ListrRendererValue } from '../interfaces/listr-task.interface';
import { ListrContext, ListrRendererClass, ListrRendererValue } from '../interfaces/listr.interface';
export declare function getRenderer(renderer: ListrRendererValue<ListrContext>, fallbackRenderer?: ListrRendererValue<ListrContext>): ListrRendererClass<ListrContext>;
{
"name": "listr2",
"version": "1.0.3",
"version": "1.1.0",
"description": "Terminal task list reborn!",

@@ -56,2 +56,3 @@ "license": "MIT",

"elegant-spinner": "^2.0.0",
"enquirer": "^2.3.4",
"figures": "^3.2.0",

@@ -63,2 +64,3 @@ "indent-string": "^4.0.0",

"rxjs": "^6.3.3",
"through": "^2.3.8",
"winston": "^3.2.1"

@@ -65,0 +67,0 @@ },

@@ -1,2 +0,3 @@

# Listr2
Listr2
====

@@ -11,2 +12,7 @@ [![Version](https://img.shields.io/npm/v/init-cli.svg)](https://npmjs.org/package/listr2)

# Navigation
* [Changelog](./CHANGELOG.md)
* [How to use](#how-to-use)
* [Features](#extra-features)
# How to use

@@ -17,3 +23,3 @@

```typescript
import { Listr } from 'Listr2'
import { Listr } from 'listr2'

@@ -49,6 +55,73 @@ interface ListrCtx {

## Task Manager
I have added a task manager kind of thing that is utilizing the Listr to the mix since I usually use it this kind of way. This task manager consists of three execution steps as described below.
```typescript
import { Manager } from 'listr2'
```
This enables user to push the tasks in a queue and execute them when needed. In my opinion this provides a more clean code interface, just to add everything to queue and execute at the end of the script, thats why I included it.
### Create A New Task Manager
* You can inject your type through the initial generation.
* The only option for manager is the show run time, which shows the run time off only the middle async part.
```typescript
private manager: Manager<Ctx> = new Manager<Ctx>()
```
### Initial Tasks
* Initial tasks will be executed in order at the beginning.
* You can also inject your type through add initial interface if initiating it via defining a type is not possible. ```manager.addInitial<Ctx>([])```
```typescript
manager.addInitial([])
```
### Parallel Tasks
* This tasks will be run as async.
* If showRuntime option enabled while generating manager, it will show the run time of async part.
* You can also inject your type through add initial interface if initiating it via defining a type is not possible. ```manager.add<Ctx>([])```
```typescript
manager.add([])
```
### Final Tasks
* Final tasks will be executed in order at the end.
* You can also inject your type through add initial interface if initiating it via defining a type is not possible. ```manager.addFinal<Ctx>([])```
```typescript
manager.addFinal([])
```
### Run Tasks that are in Queue
* This will also return the context object back.
```typescript
const ctx = await manager.runAll()
```
## Input Module
Todo ATM.
Input module uses the beautiful [enquirer](https://www.npmjs.com/package/enquirer). So with running a `task.prompt` function, you first select which kind of prompt that you will use and second one is the enquirer object which you can see more in detail in the designated npm page.
To get a input you can assign the task a new prompt in an async function and write the response to the context. It is not advisable to run prompts in a concurrent task because they will class and overwrite each others console output and when you do keyboard movements it will apply to the both.
Prompts can either have a title or not but they will always be rendered at the end of the current console while using the default renderer.
```typescript
new Listr<ListrCtx>([
{
task: async (ctx, task): Promise<any> => ctx.testInput = await task.prompt('Input', { message: 'test' })
},
{
title: 'Dump prompt.',
task: (ctx,task): void => {
task.output = ctx.testInput
}
}
])
```
## Inject Context

@@ -55,0 +128,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc