{"name":"listr2","version":"2.3.0-beta.2","description":"Terminal task list reborn! Create beautiful CLI interfaces via easy and logical to implement task lists that feel alive and interactive.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/cenk1cenk2/listr2.git"},"main":"./dist/index.js","types":"./dist/index.d.ts","author":{"name":"Cenk Kilic","email":"cenk@kilic.dev","url":"https://srcs.kilic.dev"},"engines":{"node":">=10.0.0"},"scripts":{"prebuild":"rimraf tsconfig*.tsbuildinfo && rimraf dist/","build":"tsc -P tsconfig.build.json && tscpaths -p tsconfig.paths.json -s ./dist -o ./dist","lint":"prettier --write src/ && eslint --ext .ts,.js,.tsx,.jsx --fix src/","lint:check":"eslint --ext .ts,.js,.tsx,.jsx src/","test":"NODE_ENV=test ts-node -P tests/tsconfig.json -r tsconfig-paths/register node_modules/jest/bin/jest.js --config ./tests/jest.js","test:cov":"NODE_ENV=test ts-node -P tests/tsconfig.json -r tsconfig-paths/register node_modules/jest/bin/jest.js --coverage --config ./tests/jest.js","dev:test":"NODE_ENV=test ts-node -P tests/tsconfig.json -r tsconfig-paths/register node_modules/jest/bin/jest.js --verbose --watchAll --config ./tests/jest.js"},"husky":{"hooks":{"pre-commit":"lint-staged","prepare-commit-msg":"exec < /dev/tty && git cz --hook || true"}},"lint-staged":{"./*.{ts,js,tsx,jsx}":["prettier --write","eslint --fix"],"./*.{json,md}":["prettier --write"]},"keywords":["listr","cli","task","list","tasklist","terminal","term","console","ascii","unicode","loading","indicator","progress","busy","wait","idle"],"dependencies":{"chalk":"^4.0.0","cli-truncate":"^2.1.0","figures":"^3.2.0","indent-string":"^4.0.0","log-update":"^4.0.0","p-map":"^4.0.0","rxjs":"^6.5.5","through":"^2.3.8"},"devDependencies":{"@cenk1cenk2/eslint-config":"^0.3.2","@types/jest":"^26.0.0","@types/node":"^14.0.9","@types/rewire":"^2.5.28","cz-conventional-changelog":"3.2.0","delay":"^4.3.0","enquirer":"^2.3.5","eslint":"^7.1.0","husky":"^4.2.5","jest":"^26.0.1","lint-staged":"^10.2.8","prettier":"^2.0.5","rewire":"^5.0.0","rimraf":"^3.0.2","ts-jest":"^26.1.0","ts-node":"^8.10.2","tsconfig-paths":"^3.9.0","tscpaths":"^0.0.9","typescript":"^3.9.3"},"peerDependencies":{"enquirer":">= 2.3.0 < 3"},"config":{"commitizen":{"path":"./node_modules/cz-conventional-changelog"}},"readme":"# Listr2\n\n[![Build Status](https://drone.kilic.dev/api/badges/cenk1cenk2/listr2/status.svg)](https://drone.kilic.dev/cenk1cenk2/listr2) [![Version](https://img.shields.io/npm/v/listr2.svg)](https://npmjs.org/package/listr2) [![Downloads/week](https://img.shields.io/npm/dw/listr2.svg)](https://npmjs.org/package/listr2) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\n**Create beautiful CLI interfaces via easy and logical to implement task lists that feel alive and interactive.**\n\nThis is the expanded and re-written in Typescript version of the beautiful plugin by [Sam Verschueren](https://github.com/SamVerschueren) called [Listr](https://github.com/SamVerschueren/listr).\n\n![Demo](./demo/demo.gif)\n\n> **It breaks backward compatibility with [Listr](https://github.com/SamVerschueren/listr) after v1.3.12, albeit refactoring requires only moving renderer options to their own key, concerning the [conversation on the original repository](https://github.com/SamVerschueren/listr/issues/143#issuecomment-623094930).** You can find the README of compatible version [here](https://github.com/cenk1cenk2/listr2/tree/84ff9c70ba4aab16106d1e7114453ac5e0351ec0). Keep in mind that it will not get further bug fixes.\n\n- [Changelog](./CHANGELOG.md)\n\n<!-- toc -->\n\n- [How to Use](#how-to-use)\n  - [Install](#install)\n  - [Create A New Listr](#create-a-new-listr)\n    - [Tasks](#tasks)\n    - [Options](#options)\n  - [The Concept of Context](#the-concept-of-context)\n  - [General Usage](#general-usage)\n    - [Subtasks](#subtasks)\n    - [Get User Input](#get-user-input)\n      - [Create A Prompt](#create-a-prompt)\n        - [Single Prompt](#single-prompt)\n        - [Multiple Prompts](#multiple-prompts)\n      - [Use an Custom Prompt](#use-an-custom-prompt)\n    - [Enable a Task](#enable-a-task)\n    - [Skip a Task](#skip-a-task)\n    - [Show Output](#show-output)\n      - [Utilizing the Task Itself](#utilizing-the-task-itself)\n      - [Utilizing the Bottom Bar](#utilizing-the-bottom-bar)\n      - [Utilizing an Observable or Stream](#utilizing-an-observable-or-stream)\n      - [Passing the Output Through as a Stream](#passing-the-output-through-as-a-stream)\n    - [Throw Errors](#throw-errors)\n  - [Task Manager](#task-manager)\n    - [Basic Use-Case Scenerio](#basic-use-case-scenerio)\n    - [More Functionality](#more-functionality)\n  - [Generic Features](#generic-features)\n    - [Tasks Without Titles](#tasks-without-titles)\n    - [Signal Interrupt](#signal-interrupt)\n  - [Testing](#testing)\n  - [Default Renderers](#default-renderers)\n  - [Renderer Fallback](#renderer-fallback)\n  - [Custom Renderers](#custom-renderers)\n  - [Render Hooks](#render-hooks)\n  - [Log To A File](#log-to-a-file)\n  - [Migration from Version v1](#migration-from-version-v1)\n  - [Types](#types)\n\n<!-- tocstop -->\n\n# How to Use\n\nCheck out `examples/` folder in the root of the repository for the code in demo or follow through with this README.\n\n## Install\n\n```bash\n# Install the latest supported version\nnpm install listr2\n\nyarn add listr2\n\n# Install listr compatabile version\nnpm install listr2@1.3.12\n\nyarn add listr2@1.3.12\n```\n\n## Create A New Listr\n\nCreate a new task list. It will returns a Listr class.\n\n```typescript\nimport { Listr } from 'listr2'\n\ninterface Ctx {\n  /* some variables for internal use */\n}\n\nconst tasks = new Listr<Ctx>(\n  [\n    /* tasks */\n  ],\n  {\n    /* options */\n  }\n)\n```\n\nThen you can run this task lists as a async function and it will return the context that is used.\n\n```typescript\ntry {\n  await tasks.run()\n} catch (e) {\n  // it will collect all the errors encountered if { exitOnError: false } is set as an option\n  // elsewise it will throw the first error encountered as expected\n  console.error(e)\n}\n```\n\n### Tasks\n\n```typescript\nexport interface ListrTask<Ctx, Renderer extends ListrRendererFactory> {\n  // A title can be given or omitted. For default renderer if the title is omitted,\n  title?: string\n  // A task can be a sync or async function that returns a string, readable stream or an observable or plain old void\n  // if it does actually return string, readable stream or an observable, task output will be refreshed with each data push\n  task: (ctx: Ctx, task: ListrTaskWrapper<Ctx, Renderer>) => void | ListrTaskResult<Ctx>\n  // to skip the task programmatically, skip can be a sync or async function that returns a boolean or string\n  // if string is returned it will be showed as the skip message, else the task title will be used\n  skip?: boolean | string | ((ctx: Ctx) => boolean | string | Promise<boolean> | Promise<string>)\n  // to enable the task programmatically, this will show no messages comparing to skip and it will hide the tasks enabled depending on the context\n  // enabled can be external boolean, a sync or async function that returns a boolean\n  // pay in mind that context enabled functionallity might depend on other functions to finish first, therefore the list shall be treated as a async function\n  enabled?: boolean | ((ctx: Ctx) => boolean | Promise<boolean>)\n  // this will change depending on the available options on the renderer\n  // these renderer options are per task basis and does not affect global options\n  options?: ListrGetRendererTaskOptions<Renderer>\n}\n```\n\n### Options\n\n```typescript\nexport interface ListrOptions<Ctx = ListrContext> {\n  // how many tasks can be run at the same time.\n  // false or 1 for synhronous task list, true or Infinity for compelete parallel operation, a number for limitting tasks that can run at the same time\n  // defaults to false\n  concurrent?: boolean | number\n  // it will silently fail or throw out an error\n  // defaults to false\n  exitOnError?: boolean\n  // inject a context from another operation\n  // defaults to any\n  ctx?: Ctx\n  // to have graceful exit on signal terminate and to inform the renderer all the tasks awaiting or processing are failed\n  // defaults to true\n  registerSignalListeners?: boolean\n  // select the renderer or inject a class yourself\n  // defaults to 'default' which is a updating renderer\n  renderer?: 'default' | 'verbose' | 'silent' | ListrRendererFactory\n  // renderer options depends on the selected renderer\n  rendererOptions?: ListrGetRendererOptions<T>\n  // renderer will fallback to the nonTTYRenderer on non-tty environments as the name suggest\n  // defaults to verbose\n  nonTTYRenderer?: 'default' | 'verbose' | 'silent' | ListrRendererFactory\n  // options for the non-tty renderer\n  nonTTYrendererOptions?: ListrGetRendererOptions<T>\n  // instead of creating a custom method and overwriting the renderer value, you can create a function or pass in a boolean to evaluate when to fallback to nonTTYRenderer\n  rendererFallback?: boolean | (() => boolean)\n  // inject items to wrapper level\n  injectWrapper?: {\n    // pass in enquirer for testing purposes mostly, see: https://github.com/cenk1cenk2/listr2/issues/66\n    enquirer?: Enquirer\n  }\n}\n```\n\n## The Concept of Context\n\nContext is the variables that are shared across the task list. Even though external variables can be used to do the same operation, context gives a self-contained way to process internal tasks.\n\nA successful task will return the context back for further operation.\n\nYou can also manually inject a context variable preset depending on the prior operations through the task options.\n\n**If all tasks are in one big Listr list you do not have to inject context manually to the child tasks since it is automatically injected as in the original.**\n\nIf an outside variable wants to be injected inside the Listr itself it can be done in two ways.\n\n- Injecting it as an option.\n\n```typescript\nconst ctx: Ctx = {}\n\nconst tasks = new Listr<Ctx>(\n  [\n    /* tasks */\n  ],\n  { ctx }\n)\n```\n\n- Injecting it at runtime.\n\n```typescript\ntry {\n  await tasks.run({ ctx })\n} catch (e) {\n  console.error(e)\n}\n```\n\n## General Usage\n\n### Subtasks\n\nAny task can return a new Listr. But rather than calling it as `new Listr` to get the full autocompeletion features depending on the parent task's selected renderer, it is a better idea to call it through the `Task` itself by `task.newListr()`.\n\n_Please refer to [examples section](examples/subtasks.example.ts) for more detailed and further examples._\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): Listr =>\n        task.newListr([\n          {\n            title: 'This is a subtask.',\n            task: async (): Promise<void> => {\n              await delay(3000)\n            }\n          }\n        ])\n    }\n  ],\n  { concurrent: false }\n)\n```\n\nYou can change indivudual settings of the renderer on per-subtask basis.\n\nThis includes renderer options as well as Listr options like `exitOnError`, `concurrent` to be set on a per subtask basis independent of the parent task, while it will always use the most adjacent setting.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): Listr =>\n        task.newListr(\n          [\n            {\n              title: 'This is a subtask.',\n              task: async (): Promise<void> => {\n                await delay(3000)\n              }\n            },\n            {\n              title: 'This is an another subtask.',\n              task: async (): Promise<void> => {\n                await delay(2000)\n              }\n            }\n          ],\n          { concurrent: true, rendererOptions: { collapse: true } }\n        )\n    },\n\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): Listr =>\n        task.newListr(\n          [\n            {\n              title: 'This is a subtask.',\n              task: async (): Promise<void> => {\n                await delay(3000)\n              }\n            },\n            {\n              title: 'This is an another subtask.',\n              task: async (): Promise<void> => {\n                await delay(2000)\n              }\n            }\n          ],\n          { concurrent: true, rendererOptions: { collapse: false } }\n        )\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n_Please refer to [Throw Errors Section](#Throw-Errors) for more detailed and further examples on how to handle silently failing errors._\n\n### Get User Input\n\nThe input module uses the beautiful [enquirer](https://www.npmjs.com/package/enquirer).\n\n> **Attention: Enquirer is a optional dependency. Please install it first.**\n\nSo with running a `task.prompt` function, you can get access to any [enquirer](https://www.npmjs.com/package/enquirer) default prompts as well as using a custom enquirer prompt.\n\nTo get an input you can assign the task a new prompt in an async function and write the response to the context.\n\n**It is not advisable to run prompts in a concurrent task because multiple prompts will clash and overwrite each other's console output and when you do keyboard movements it will apply to them both.**\n\nPrompts, since their rendering is getting passed as a data output will render multiple times in verbose renderer since verbose renderer is not terminal-updating intended to be used in nonTTY environments. It will work anyhow albeit it might not look great.\n\nPrompts 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.\n\n_Please refer to [examples section](examples/get-user-input.example.ts) for more detailed and further examples._\n\n#### Create A Prompt\n\nTo access the prompts just utilize the `task.prompt` jumper function. The first argument takes in one of the default [enquirer](https://www.npmjs.com/package/enquirer) prompts as a string or you can also pass in a custom [enquirer](https://www.npmjs.com/package/enquirer) prompt class as well, while the second argument is the options for the given prompt.\n\nPrompts always rendered at the bottom of the tasks when using the default renderer with one line return in between it and the tasks.\n\n_Please note that I rewrote the types for enquirer, since some of them was failing for me. So it may have a chance of having some mistakes in it since I usually do not use all of them._\n\n**>v2.1.0, defining the prompt style has been changed a little. It know requires type to be integrated inside the prompt itself, instead of passing two variables. Custom prompts still work the same way.**\n\n##### Single Prompt\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      task: async (ctx, task): Promise<boolean> => (ctx.input = await task.prompt<boolean>({ type: 'Toggle', message: 'Do you love me?' }))\n    },\n    {\n      title: 'This task will get your input.',\n      task: async (ctx, task): Promise<void> => {\n        ctx.input = await task.prompt<boolean>({ type: 'Toggle', message: 'Do you love me?' })\n        // do something\n        if (ctx.input === false) {\n          throw new Error(':/')\n        }\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n##### Multiple Prompts\n\n**Important: If you want to pass in an array of prompts, becareful that you should name them, this is also enforced by Typescript as well. This is not true for single prompts, since they only return a single value, it will be directly gets passed to the assigned variable.**\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will get your input.',\n      task: async (ctx, task): Promise<void> => {\n        ctx.input = await task.prompt<{ first: boolean; second: boolean }>([\n          { type: 'Toggle', name: 'first', message: 'Do you love me?' },\n          { type: 'Toggle', name: 'second', message: 'Do you love me?' }\n        ])\n        // do something\n        if (ctx.input.first === false) {\n          logger.log('oh okay')\n        }\n        if (ctx.input.second === false) {\n          throw new Error('You did not had to tell me for the second time')\n        }\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n#### Use an Custom Prompt\n\nYou can either use a custom prompt out of the npm registry or custom-created one as long as it works with [enquirer](https://www.npmjs.com/package/enquirer), it will work expectedly. Instead of passing in the prompt name use the not-generated class.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'Custom prompt',\n      task: async (ctx, task): Promise<void> => {\n        ctx.testInput = await task.prompt({\n          type: EditorPrompt,\n          message: 'Write something in this enquirer custom prompt.',\n          initial: 'Start writing!',\n          validate: (response): boolean | string => {\n            //  i do declare you valid!\n            return true\n          }\n        })\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n### Enable a Task\n\nTasks can be enabled depending on the variables programmatically. This enables to skip them depending on the context. Not enabled tasks will never show up in the default renderer, but when or if they get enabled they will magically appear.\n\n_Please pay attention to asynchronous operation while designing a context enabled task list since it does not await for any variable in the context._\n\n_Please refer to [examples section](examples/task-enable.example.ts) for more detailed and further examples._\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: (ctx): void => {\n        ctx.skip = true\n      }\n    },\n\n    {\n      title: 'This task will never execute.',\n      enabled: (ctx): boolean => !ctx.skip,\n      task: (): void => {}\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n### Skip a Task\n\nSkip is more or less the same with enable when used at `Task` level. But the main difference is it will always render the given task. If it is skipped it renders it as skipped.\n\nThere are to main ways to skip a task. One is utilizing the `Task` so that instead of enabled it will show a visual output while the other one is inside the task.\n\n_Please pay attention to asynchronous operation while designing a context skipped task list since it does not await for any variable in the context._\n\n_Please refer to [examples section](examples/task-skip.example.ts) for more detailed and further examples._\n\nInside the task itself after some logic is done.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): void => {\n        task.skip('I am skipping this tasks for reasons.')\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\nThrough the task wrapper.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: (ctx): void => {\n        ctx.skip = true\n      }\n    },\n\n    {\n      title: 'This task will never execute.',\n      skip: (ctx): boolean => ctx.skip,\n      task: (): void => {}\n    }\n  ],\n  { concurrent: false }\n)\n```\n\nThere are two rendering methods for the default renderer for skipping the task. The default behavior is to replace the task title with skip message if the skip function returns a string. You can select the other way around with `rendererOptions: { collapseSkips: false }` for the default renderer to show the skip message under the task title.\n\n### Show Output\n\nShowing output from a task can be done in various ways.\n\nTo keep the output when the task finishes while using default renderer, you can set `{ persistentOutput: true }` in the `Task`.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: async (ctx, task): Promise<void> => {\n        task.output = 'I will push an output. [0]'\n      },\n      options: { persistentOutput: true }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n_Please refer to [examples section](examples/show-output.example.ts) for more detailed and further examples._\n\n#### Utilizing the Task Itself\n\nThis will show the output in a small bar that can only show the last output from the task.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: async (ctx, task): Promise<void> => {\n        task.output = 'I will push an output. [0]'\n        await delay(500)\n\n        task.output = 'I will push an output. [1]'\n        await delay(500)\n\n        task.output = 'I will push an output. [2]'\n        await delay(500)\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n#### Utilizing the Bottom Bar\n\nIf task output to the bottom bar is selected, it will create a bar at the end of the tasks leaving one line return space in between. The bottom bar can only be used in the default renderer.\n\nItems count that is desired to be showed in the bottom bar can be set through `Task` option `bottomBar`.\n\n- If set to `true` it will only show the last output from the task.\n- If it is set to a number it will limit the output to that number.\n- If set to `Infinity`, it will keep all the output.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: async (ctx, task): Promise<void> => {\n        task.output = 'I will push an output. [0]'\n        await delay(500)\n\n        task.output = 'I will push an output. [1]'\n        await delay(500)\n\n        task.output = 'I will push an output. [2]'\n        await delay(500)\n      },\n      options: {\n        bottomBar: Infinity\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n#### Utilizing an Observable or Stream\n\nSince observables and streams are supported they can also be used to generate output.\n\n_Please refer to [examples section](examples/stream.example.ts) for more detailed and further examples._\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      // Task can also handle and observable\n      title: 'Observable test.',\n      task: (): Observable<string> =>\n        new Observable((observer) => {\n          observer.next('test')\n\n          delay(500)\n            .then(() => {\n              observer.next('changed')\n              return delay(500)\n            })\n            .then(() => {\n              observer.complete()\n            })\n        })\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n#### Passing the Output Through as a Stream\n\nSince `process.stdout` method is controlled by `log-update` to create a refreshing interface, for anything else that might need to output data and can use `Writeable` streams, `task.stdout()` will create a new punch-hole to redirect all the write requests to `task.output`. This is esspecially benefical for external libraries like `enquirer`, which is already integrated or something like `ink`.\n\n**Supported for >v2.1.0.**\n\n_This unfortunetly relies on cleaning all ANSI escape charachters, since currently I do not find a good way to sandbox them inside `log-update` which utilizes the cursor position by itself. So use this with caution, because it will only render the last chunk in a stream as well as cleaning up all the ANSI escape charachters except for styles._\n\n```typescript\nimport { Box, Color, render } from 'ink'\nimport React, { Fragment, useEffect, useState } from 'react'\n\nimport { Listr } from 'Listr2'\nimport { Logger } from '@utils/logger'\n\ntype Ctx = {}\n\nconst logger = new Logger({ useIcons: false })\n\nasync function main(): Promise<void> {\n  let task: Listr<Ctx, 'default'>\n\n  task = new Listr<Ctx, 'default'>(\n    [\n      {\n        title: 'This task will show INK as output.',\n        task: async (ctx, task): Promise<any> => {\n          const Counter = () => {\n            const [counter, setCounter] = useState(0)\n\n            useEffect(() => {\n              const timer = setInterval(() => {\n                setCounter((previousCounter) => previousCounter + 1)\n              }, 100)\n\n              return (): void => {\n                clearInterval(timer)\n              }\n            }, [])\n\n            return <Color green>{counter} tests passed</Color>\n          }\n\n          const { unmount, waitUntilExit } = render(<Counter />, task.stdout())\n\n          setTimeout(unmount, 2000)\n\n          return waitUntilExit()\n        }\n      }\n    ],\n    { concurrent: false }\n  )\n\n  try {\n    const context = await task.run()\n    console.log(`Context: ${JSON.stringify(context)}`)\n  } catch (e) {\n    console.error(e)\n  }\n}\n\nmain()\n```\n\n### Throw Errors\n\nYou can throw errors out of the tasks to show they are insuccessful. While this gives a visual output on the terminal, it also handles how to handle tasks that are failed. The default behaviour is any of the tasks have failed, it will deem itself as unsuccessful and exit. This behaviour can be changed with `exitOnError` option.\n\n- Throw out an error in serial execution mode will cause all of the upcoming tasks to be never executed.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will fail.',\n      task: async (): Promise<void> => {\n        await delay(2000)\n        throw new Error('This task failed after 2 seconds.')\n      }\n    },\n    {\n      title: 'This task will never execute.',\n      task: (ctx, task): void => {\n        task.title = 'I will change my title if this executes.'\n      }\n    }\n  ],\n  { concurrent: false }\n)\n```\n\n- Throwing out an error while execution in parallel mode will immediately stop all the actions.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will fail.',\n      task: async (): Promise<void> => {\n        await delay(2000)\n        throw new Error('This task failed after 2 seconds.')\n      }\n    },\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): void => {\n        task.title = 'I will change my title since it is concurrent.'\n      }\n    }\n  ],\n  { concurrent: true }\n)\n```\n\n- Default behavior can be changed with `exitOnError` option.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will fail.',\n      task: async (): Promise<void> => {\n        await delay(2000)\n        throw new Error('This task failed after 2 seconds.')\n      }\n    },\n    {\n      title: 'This task will execute.',\n      task: (ctx, task): void => {\n        task.title = 'I will change my title if this executes.'\n      }\n    }\n  ],\n  { concurrent: false, exitOnError: false }\n)\n```\n\n- `exitOnError` is subtask based so you can change it on the fly for given set of subtasks.\n\n```typescript\nnew Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute and not quit on errors.',\n      task: (ctx, task): Listr =>\n        task.newListr(\n          [\n            {\n              title: 'This is a subtask.',\n              task: async (): Promise<void> => {\n                throw new Error('I have failed [0]')\n              }\n            },\n            {\n              title: 'This is yet an another subtask and it will run.',\n              task: async (ctx, task): Promise<void> => {\n                task.title = 'I have succeeded.'\n              }\n            }\n          ],\n          { exitOnError: false }\n        )\n    },\n    {\n      title: 'This task will execute.',\n      task: (): void => {\n        throw new Error('I will exit on error since I am a direct child of parent task.')\n      }\n    }\n  ],\n  { concurrent: false, exitOnError: true }\n)\n```\n\n- The error that makes the application to quit will be thrown out from the async function.\n\n```typescript\ntry {\n  const context = await task.run()\n} catch (e) {\n  logger.fail(e)\n  // which will show the last error\n}\n```\n\n- Access all of the errors that makes the application quit or not through `task.err` which is an array of all the errors encountered.\n\n```typescript\nconst task = new Listr(...)\nlogger.fail(task.err)\n// will show all of the errors that are encountered through execution\n```\n\n- ListrError which is thrown out of `task.err´ in prior example is in the structure of\n\n```typescript\npublic message: string\npublic errors?: Error[]\npublic context?: any\n```\n\n## Task Manager\n\nTask manager is a great way to create a custom-tailored Listr class once and then utilize it more than once.\n\n_Please refer to [examples section](examples/manager.example.ts) for more detailed and further examples._\n\n### Basic Use-Case Scenerio\n\n- Create something like a manager factory with your own default settings\n\n```typescript\nexport function TaskManagerFactory<T = any>(override?: ListrBaseClassOptions): Manager<T> {\n  const myDefaultOptions: ListrBaseClassOptions = {\n    concurrent: false,\n    exitOnError: false,\n    rendererOptions: {\n      collapse: false,\n      collapseSkips: false\n    }\n  }\n  return new Manager({ ...myDefaultOptions, ...override })\n}\n```\n\n- Create your class that benefits from manager\n\n```typescript\nexport class MyMainClass {\n  private tasks = TaskManagerFactory<Ctx>()\n\n  constructor() {\n    this.run()\n  }\n\n  private async run(): Promise<void> {\n    // CODE WILL GO HERE IN THIS EXAMPLE\n  }\n}\n```\n\n- Add multiple set of subtasks with their own options\n\n```typescript\nthis.tasks.add(\n  [\n    {\n      title: 'A task running manager [0]',\n      task: async (): Promise<void> => {\n        throw new Error('Do not dare to run the second task.')\n      }\n    },\n    {\n      title: 'This will never run first one failed.',\n      task: async (): Promise<void> => {\n        await delay(2000)\n      }\n    }\n  ],\n  { exitOnError: true, concurrent: false }\n)\n```\n\n- Run the tasks. Running the tasks will clear the pending queue so you can go ahead and add more new tasks!\n\n```typescript\ntry {\n  const ctx = await this.tasks.runAll()\n} catch (e) {\n  this.logger.fail(e)\n}\n```\n\n### More Functionality\n\n- Indenting tasks, to change options like `concurrency`, `exitOnError` and so on.\n\n```typescript\nthis.tasks.add(\n  [\n    {\n      title: 'Some task that will run in sequential execution mode. [0]',\n      task: async (): Promise<void> => {\n        await delay(2000)\n      }\n    },\n    {\n      title: 'Some task that will run in sequential execution mode. [1]',\n      task: async (): Promise<void> => {\n        await delay(2000)\n      }\n    },\n    this.tasks.indent([\n      {\n        title: 'This will run in parallel. [0]',\n        task: async (): Promise<void> => {\n          await delay(2000)\n        }\n      },\n      {\n        title: 'This will run in parallel. [1]',\n        task: async (): Promise<void> => {\n          await delay(2000)\n        }\n      }\n    ])\n  ],\n  { concurrent: true }\n)\n```\n\n- Run a Task Directly, which will use the defaults settings you set in the manager.\n\n```typescript\nawait this.tasks.run([\n  {\n    title: 'I will survive, dont worry',\n    task: (): void => {\n      throw new Error('This will not crash since exitOnError is set to false eventhough default setting in Listr is false.')\n    }\n  }\n])\n```\n\n- Access the errors of the last task as in the Listr.\n\n```typescript\nawait this.tasks.run([\n  {\n    title: 'I will survive, dont worry',\n    task: (): void => {\n      throw new Error('This will not crash since exitOnError is set to false eventhough default setting in Listr is false.')\n    }\n  }\n])\nthis.logger.data(this.tasks.err.toString())\n// will yield: ListrError: Task failed without crashing. with the error details in the object\n```\n\n- Access base Listr class directly, this will use the default Listr settings and just a mere jumper function for omiting the need the import the Listr class when using manager.\n\n```typescript\ntry {\n  await this.tasks\n    .newListr([\n      {\n        title: 'I will die now, goodbye my freinds.',\n        task: (): void => {\n          throw new Error('This will not crash since exitOnError is set to false eventhough default setting in Listr is false.')\n        }\n      }\n    ])\n    .run()\n} catch (e) {\n  this.logger.fail(e)\n}\n```\n\n- Get Task Runtime, and tailor it as your own\n\n```typescript\nawait this.tasks.run(\n  [\n    {\n      task: async (ctx): Promise<void> => {\n        // start the clock\n        ctx.runTime = Date.now()\n      }\n    },\n    {\n      title: 'Running',\n      task: async (): Promise<void> => {\n        await delay(1000)\n      }\n    },\n    {\n      task: async (ctx, task): Promise<string> => (task.title = this.tasks.getRuntime(ctx.runTime))\n    }\n  ],\n  { concurrent: false }\n)\n// outputs: \"1.001s\" in seconds\n```\n\n## Generic Features\n\n### Tasks Without Titles\n\nFor default renderer, all tasks that do not have titles will be hidden from the visual task list and executed behind. You can still set `task.title` inside the task wrapper programmatically afterward, if you so desire.\n\nSince tasks can have subtasks as in the form of Listr classes again, if a task without a title does have subtasks with the title it will be rendered one less level indented. So you can use this operation to change the individual options of the set of tasks like `exitOnError` or `concurrency` or even render properties, like while you do want collapse parent's subtasks after completed but do not want this for a given set of subtasks.\n\nFor verbose renderer, since it is not updating, it will show tasks that do not have a title as `Task without title.`\n\n### Signal Interrupt\n\nWhen the interrupt signal is caught Listr will render for one last time therefore you will always have clean exits. This registers event listener `process.on('exit')`, therefore it will use a bit more of CPU cycles depending on the Listr task itself.\n\nYou can disable this default behavior by passing in the options for the root task `{ registerSignalListeners: false }`.\n\n## Testing\n\nFor testing purposes you can use the verbose renderer by passing in the option of `{ renderer: 'verbose' }`. This will generate text-based and linear output which is required for testing.\n\nIf you want to change the logger of the verbose renderer you can do that by passing a class implementing `Logger` class which is exported from the index and passing it through as a renderer option with `{ renderer: 'verbose', rendererOptions: { logger: MyLoggerClass } }`.\n\nVerbose renderer will always output predicted output with no fancy features.\n\n| On              | Output                                                              |\n| --------------- | ------------------------------------------------------------------- |\n| Task Started    | \\[STARTED\\] \\${TASK TITLE ?? 'Task without title.'}                 |\n| Task Failure    | \\[FAILED\\] \\${TASK TITLE ?? 'Task without title.'}                  |\n| Task Skipped    | \\[SKIPPED\\] \\${SKIP MESSAGE ?? TASK TITLE ?? 'Task without title.'} |\n| Task Successful | \\[SUCCESS\\] \\${TASK TITLE ?? 'Task without title.'}                 |\n| Spit Output     | \\[DATA\\] \\${TASK OUTPUT}                                            |\n| Title Change    | \\[TITLE\\] \\${NEW TITLE}                                             |\n\n## Default Renderers\n\nThere are three main renderers which are 'default', 'verbose' and 'silent'. Default renderer is the one that can be seen in the demo, which is an updating renderer. But if the environment advirteses itself as non-tty it will fallback to the verbose renderer automatically. Verbose renderer is a text based renderer. It uses the silent renderer for the subtasks since the parent task already started a renderer. But silent renderer can also be used for processes that wants to have no output but just a task list.\n\nDepending on the selected renderer, `rendererOptions` as well as the `options` in the `Task` will change accordingly. It defaults to default renderer as mentioned with the fallback to verbose renderer on non-tty environments.\n\n- Options for the default renderer.\n  - Global\n  ```typescript\n  public static rendererOptions: {\n    // indentation per level\n    indentation?: number\n    // clear output when task finishes\n    clearOutput?: boolean\n    // show subtasks\n    showSubtasks?: boolean\n    // collapse subtasks after finish\n    collapse?: boolean\n    // collapse skips in to single message\n    collapseSkips?: boolean\n    // only update via renderhook\n    lazy?: boolean\n  } = {\n    indentation: 2,\n    clearOutput: false,\n    showSubtasks: true,\n    collapse: true,\n    collapseSkips: true,\n    lazy: false\n  }\n  ```\n  - Per-Task\n  ```typescript\n  public static rendererTaskOptions: {\n    // write task output to bottom bar\n    bottomBar?: boolean | number\n    // keep output after task finishes\n    persistentOutput?: boolean\n  }\n  ```\n- Options for the verbose renderer.\n  - Global\n  ```typescript\n  public static rendererOptions: {\n    // useIcons instead of text for log level\n    useIcons?: boolean\n    // inject a custom loger\n    logger?: new (...args: any) => Logger\n    // log tasks with empty titles\n    logEmptyTitle?: boolean\n    // log title changes\n    logTitleChange?: boolean\n  } = {\n    useIcons: false,\n    logEmptyTitle: true,\n    logTitleChange: true\n  }\n  ```\n- Options for the silent renderer.\n  - NONE\n\n## Renderer Fallback\n\nThere are times other than nonTTY environments that you want to use a verbose renderer instead of the default renderer.\n\nFor these times you needed to create a `getRenderer` kind of method and return the renderer value to renderer. But with the added complexity of the types, it is a bit more buggy to show it returns `default` for autocompelete purposes.\n\nYou can now pass in a function that returns a boolean, or directly a boolean for automatically stepping down to the `nonTTYRenderer` when the condition is met.\n\n```typescript\ntask = new Listr<Ctx>(\n  [\n    {\n      title: 'This task will execute.',\n      task: async (): Promise<void> => {\n        await delay(500)\n      },\n      options: { persistentOutput: true }\n    }\n  ],\n  { concurrent: false, rendererFallback: (): boolean => 3 < 1 }\n)\n```\n\n_Please refer to [examples section](examples/renderer-fallback.example.ts) for more detailed and further examples._\n\n**Supported for >v2.3.0.**\n\n## Custom Renderers\n\nCreating a custom renderer with a beautiful interface can be done in one of two ways.\n\n- First create a Listr renderer class.\n\n```typescript\n/* eslint-disable @typescript-eslint/no-empty-function */\nimport { ListrRenderer, ListrTaskObject } from 'listr2'\n\nexport class MyAmazingRenderer implements ListrRenderer {\n  // Designate this renderer as tty or nonTTY\n  public static nonTTY = true\n  // designate your renderer options that will be showed inside the `ListrOptions` as rendererOptions\n  public static rendererOptions: never\n  // designate your custom internal task-based options that will show as `options` in the task itself\n  public static rendererTaskOptions: never\n\n  // get tasks to be renderered and options of the renderer from the parent\n  constructor(public tasks: ListrTaskObject<any, typeof MyAmazingRenderer>[], public options: typeof MyAmazingRenderer['rendererOptions']) {}\n\n  // implement custom logic for render functionality\n  render(): void {}\n\n  // implement custom logic for end functionality\n  end(err): void {}\n}\n```\n\n- Then there is a branching here you can either use:\n  - Utilizing the task functions themselves. Take a look at [default renderer](src/renderer/default.renderer.ts) since it is implemented this way.\n  ```typescript\n  id: taskUUID\n  hasSubtasks(): boolean\n  isPending(): boolean\n  isSkipped(): boolean\n  isCompleted(): boolean\n  isEnabled(): boolean\n  isPrompt(): boolean\n  hasFailed(): boolean\n  hasTitle(): boolean\n  ```\n  - Observables, where `event` has `event.type` which can either be `SUBTASK`, `STATE`, `DATA` or `TITLE` and `event.data` depending on the `event.type`. Take a look at [verbose renderer](src/renderer/verbose.renderer.ts) since it is implemented this way.\n  ```typescript\n  tasks?.forEach((task) => {\n      task.subscribe((event: ListrEvent) => {\n        ...\n  ```\n  - Or if you so desire both!\n\n## Render Hooks\n\nAdditional to rendering through `task.subscribe` or with a given interval, a renderer can also render on demand via a observable passed through the renderer.\n\nRender hook can be the third optional variable of a given renderer, while using it is always optional.\n\n```typescript\nconstructor (\n    public tasks: ListrTaskObject<any, typeof DefaultRenderer>[],\n    public options: typeof DefaultRenderer['rendererOptions'],\n    public renderHook$?: ListrTaskObject<any, any>['renderHook$']\n  )\n```\n\nRender hook is a void subject, which can be used to trigger re-render dynamically when any changes occur in the underneath.\n\n```typescript\nthis.renderHook$.subscribe(() => {\n  /* DO SOME RENDER MAGIC like render() */\n})\n```\n\n**Supported for >v2.1.0.**\n\n## Log To A File\n\nLogging to a file can be done utilizing a module like [winston](https://www.npmjs.com/package/winston). This can be obtained through using the verbose renderer and creating a custom logger class that implements `Logger` which is exported from the index.\n\nWhile calling a new Listr you can call it with `{ renderer: 'verbose', rendererOptions: { logger: MyLoggerClass } }`.\n\n```typescript\nimport { logLevels, Logger, LoggerOptions } from 'listr2'\n\nexport class MyLoggerClass extends Logger {\n  constructor(private options?: LoggerOptions) {\n    // This is not needed if you don't use these options in your custom logger\n  }\n\n  /* CUSTOM LOGIC */\n  /* CUSTOM LOGIC */\n  /* CUSTOM LOGIC */\n\n  public fail(message: string): void {\n    message = this.parseMessage(logLevels.fail, message)\n    console.error(message)\n  }\n\n  public skip(message: string): void {\n    message = this.parseMessage(logLevels.skip, message)\n    console.warn(message)\n  }\n\n  public success(message: string): void {\n    message = this.parseMessage(logLevels.success, message)\n    console.log(message)\n  }\n\n  public data(message: string): void {\n    message = this.parseMessage(logLevels.data, message)\n    console.info(message)\n  }\n\n  public start(message: string): void {\n    message = this.parseMessage(logLevels.start, message)\n    console.log(message)\n  }\n\n  public title(message: string): void {\n    message = this.parseMessage(logLevels.title, message)\n    console.info(message)\n  }\n}\n```\n\n## Migration from Version v1\n\nTo migrate from prior versions that are older than v1.3.12, which is advisable due to upcoming potential bug fixes:\n\n- rendererOptions has to be moved to their own key\n- some of the types if initiated before assigning a Listr has to be fixed accordingly\n- test renderer also combined with verbose renderer and icons of the verbose renderer is disabled by default which makes them basically same thing, so I think verbose is a better name for it\n\nPlease checkout [the entry in changelog.](./CHANGELOG.md#200-2020-05-06)\n\n## Types\n\nUseful types are exported from the root. It is written with Typescript, so it will work great with any modern IDE/Editor.\n","readmeFilename":"README.md","gitHead":"5e1f2eb0d6db99f80ed1847e1582df480785f8c6","bugs":{"url":"https://github.com/cenk1cenk2/listr2/issues"},"homepage":"https://github.com/cenk1cenk2/listr2#readme","_id":"listr2@2.3.0-beta.2","_nodeVersion":"14.5.0","_npmVersion":"6.14.5","dist":{"integrity":"sha512-W79aC+Br9sfz+vuXHy+yK01vz8RGR6SMW4lqqNtw5X6FPwUsYtYV8votgy2b94DEwN8Dv7RzhzQezYebiy85Dw==","shasum":"64068a9a063cd4ffbf7cd9af3eec3ee882a80eb1","tarball":"http://registry-npm.ywwl.com/listr2/download/listr2-2.3.0-beta.2.tgz","fileCount":56,"unpackedSize":156685,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfGH9jCRA9TVsSAnZWagAAHwUP/Ry02GJof7FyhmXKX06P\n9muHSTPrQbyXfBL/M0mudkfmdvXxN62tyFkKELsmRA1YK57Vtz/ZrLjsa84B\nvhwD4tYiap5mJzCnH8Q+znE/pCXOKBqz99xeI7AJPMU0tT93dO1cdhEnjv2W\nVZ0dudXpI7LXCV67Cb2wgYaidjqQxGGvXkYCzUDaC9wNL9+W/oCGH/aTk3oz\nA0QolE19MaAVXd7byc69nxi8cgwZuBgLWChYYnhkA1CIRLyUpsamz44MgZvW\nxqDie4Z7O1MrlZXDCaDEa1GLcIcW/BelFoLZpjb80k1+X3ImLamvErM+77PB\nozy40axqvUPJ1KOMZ1pnPO2/4otTx9PZTaFQeJh2lP2INxNfWxB1FhSAq3TQ\nUxYqAQtdP3ROgDhKdaci4YwAITEQkYju23m8iiW9i7478g2TN3Z4vSyoEM9T\nij5oAjEn8ZtVuJj00ceiPAXZzj+CjBCA3QeqofJpujgGve4QFNHHEA8qh5/r\n3mbJgtJt/3c/LtpgScAbwHAPYws13FJ40DorYsKh1BHRb+/nx+y4AtStFqzM\nLD47dt10c5MlYN7Bkrd4gQ8coQN7vnzaHIK0vtgGAAz6kI+MbhagAE0+Hh3M\nkLJMzqL6TG7Z3InQMV0aA3kFfMK/dxRIRSkrr6FDywsOh6zmSH6DnS60TXvs\nI0oD\r\n=vc3s\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCcrVybodyGruByvIU5E/3K5t4G7W9sWhmfOFpfp6jDOgIgQB3rTl6E+1RxZZkJrJrAacqmh/hFovRCoxZIGYIsVyI="}],"size":37290,"noattachment":false,"key":"/listr2/-/listr2-2.3.0-beta.2.tgz"},"maintainers":[{"name":"cenk1cenk2","email":"cenk@kilic.dev"}],"_npmUser":{"name":"cenk1cenk2","email":"cenk@kilic.dev"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/listr2_2.3.0-beta.2_1595440995234_0.1524866087481589"},"_hasShrinkwrap":false,"publish_time":1595440995337,"_cnpm_publish_time":1595440995337,"dist-tags":{"beta":"11.0.0-beta.7","latest":"11.4.0"}}