Full Code of unjs/consola for AI

main c47faac1738b cached
64 files
143.3 KB
44.2k tokens
123 symbols
1 requests
Download .txt
Repository: unjs/consola
Branch: main
Commit: c47faac1738b
Files: 64
Total size: 143.3 KB

Directory structure:
gitextract_mvamdj0q/

├── .editorconfig
├── .github/
│   ├── codecov.yml
│   └── workflows/
│       ├── autofix.yml
│       └── ci.yml
├── .gitignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── basic.d.ts
├── browser.d.ts
├── build.config.ts
├── core.d.ts
├── eslint.config.mjs
├── examples/
│   ├── basic.ts
│   ├── box.ts
│   ├── error.ts
│   ├── fancy.ts
│   ├── index.html
│   ├── index.legacy.html
│   ├── json.ts
│   ├── mock.ts
│   ├── no-width.ts
│   ├── pause.ts
│   ├── prompt.mjs
│   ├── prompt.ts
│   ├── raw.ts
│   ├── sample.ts
│   ├── spam.ts
│   ├── special.ts
│   ├── spinner.ts
│   ├── tree.ts
│   ├── utils/
│   │   ├── index.ts
│   │   └── sentence.ts
│   ├── wrap-all.ts
│   ├── wrap-console.ts
│   └── wrap-std.ts
├── lib/
│   └── index.cjs
├── package.json
├── renovate.json
├── src/
│   ├── basic.ts
│   ├── browser.ts
│   ├── consola.ts
│   ├── constants.ts
│   ├── core.ts
│   ├── index.ts
│   ├── prompt.ts
│   ├── reporters/
│   │   ├── basic.ts
│   │   ├── browser.ts
│   │   └── fancy.ts
│   ├── shared.ts
│   ├── types.ts
│   ├── utils/
│   │   ├── box.ts
│   │   ├── color.ts
│   │   ├── error.ts
│   │   ├── format.ts
│   │   ├── log.ts
│   │   ├── stream.ts
│   │   ├── string.ts
│   │   └── tree.ts
│   └── utils.ts
├── test/
│   └── consola.test.ts
├── tsconfig.json
└── utils.d.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# editorconfig.org
root = true

[*]
indent_size = 2
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false


================================================
FILE: .github/codecov.yml
================================================
coverage:
  status:
    project:
      default:
        threshold: 5%


================================================
FILE: .github/workflows/autofix.yml
================================================
name: autofix.ci # needed to securely identify the workflow

on:
  pull_request:
  push:
    branches: ["main"]

permissions:
  contents: read

jobs:
  autofix:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm i -fg corepack && corepack enable
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "pnpm"
      - run: pnpm install
      - name: Fix lint issues
        run: pnpm run lint:fix
      - uses: autofix-ci/action@7a166d7532b277f34e16238930461bf77f9d7ed8
        with:
          commit-message: "chore: apply automated updates"


================================================
FILE: .github/workflows/ci.yml
================================================
name: ci

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm i -fg corepack && corepack enable
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "pnpm"
      - run: pnpm install
      - run: pnpm lint
      - run: pnpm build
      - run: pnpm vitest --coverage
      - uses: codecov/codecov-action@v5


================================================
FILE: .gitignore
================================================
node_modules
*.log*
dist
coverage


================================================
FILE: .prettierrc
================================================
{}


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## v3.4.2

[compare changes](https://github.com/unjs/consola/compare/v3.4.1...v3.4.2)

### 🩹 Fixes

- Export tree utils ([#349](https://github.com/unjs/consola/pull/349))
- Calculate box width with the title width ([#362](https://github.com/unjs/consola/pull/362))

### 🏡 Chore

- Cleanup unused deps ([#361](https://github.com/unjs/consola/pull/361))
- Update deps ([1e5f846](https://github.com/unjs/consola/commit/1e5f846))

### ❤️ Contributors

- Kricsleo ([@kricsleo](https://github.com/kricsleo))
- Scott Humphries ([@sscotth](https://github.com/sscotth))
- Pooya Parsa ([@pi0](https://github.com/pi0))

## v3.4.1

[compare changes](https://github.com/unjs/consola/compare/v3.4.0...v3.4.1)

### 🩹 Fixes

- Remove all message lines from stack ([#356](https://github.com/unjs/consola/pull/356))

### 🏡 Chore

- Update ci ([#353](https://github.com/unjs/consola/pull/353))
- Update deps ([da26f10](https://github.com/unjs/consola/commit/da26f10))

### ❤️ Contributors

- Pooya Parsa ([@pi0](https://github.com/pi0))
- Nozomu Ikuta ([@nozomuikuta](https://github.com/nozomuikuta))

## v3.4.0

[compare changes](https://github.com/unjs/consola/compare/v3.3.3...v3.4.0)

### 🚀 Enhancements

- Use upstream `@clack/prompts` ([#332](https://github.com/unjs/consola/pull/332))

### 🩹 Fixes

- Calculate box width without escape sequence chars ([#336](https://github.com/unjs/consola/pull/336))

### 💅 Refactors

- Keep prompt styles (cont. #332) ([#332](https://github.com/unjs/consola/issues/332))

### 📦 Build

- Update exports for node16 typescript resolution ([#331](https://github.com/unjs/consola/pull/331))

### 🏡 Chore

- Update deps ([9193d63](https://github.com/unjs/consola/commit/9193d63))
- Apply automated updates ([fc8b9b9](https://github.com/unjs/consola/commit/fc8b9b9))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Yongqi <yongqi14@qq.com>

## v3.3.3

[compare changes](https://github.com/unjs/consola/compare/v3.3.2...v3.3.3)

### 📦 Build

- Revert "build: update exports for `node16` typescript resolution" ([2065136](https://github.com/unjs/consola/commit/2065136))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.3.2

[compare changes](https://github.com/unjs/consola/compare/v3.3.1...v3.3.2)

### 📦 Build

- Patch `string-width` for node 14 support ([421c663](https://github.com/unjs/consola/commit/421c663))
- Update exports for `node16` typescript resolution ([18bc852](https://github.com/unjs/consola/commit/18bc852))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.3.1

[compare changes](https://github.com/unjs/consola/compare/v3.3.0...v3.3.1)

### 🩹 Fixes

- **fancy:** Fallback when`Intl` is unavailable ([#326](https://github.com/unjs/consola/pull/326))

### ❤️ Contributors

- Red Huang <redhuang@synology.com>

## v3.3.0

[compare changes](https://github.com/unjs/consola/compare/v3.2.3...v3.3.0)

### 🚀 Enhancements

- **utils:** `formatTree` utility ([#223](https://github.com/unjs/consola/pull/223))
- Export prompt option types ([#301](https://github.com/unjs/consola/pull/301))
- Support report error `cause` ([#308](https://github.com/unjs/consola/pull/308))
- **prompt:** Configurable cancel strategy ([#325](https://github.com/unjs/consola/pull/325))
- **formatTree:** Support max depth ([#267](https://github.com/unjs/consola/pull/267))

### 🩹 Fixes

- Use `initial` in `select` and `multiselect` prompts ([#232](https://github.com/unjs/consola/pull/232))
- Make box title color same as border ([#236](https://github.com/unjs/consola/pull/236))

### 📖 Documentation

- Update screenshot ([205d9c8](https://github.com/unjs/consola/commit/205d9c8))
- Add vitest ([#182](https://github.com/unjs/consola/pull/182))
- Add note about raw method ([#271](https://github.com/unjs/consola/pull/271))
- Add jsdocs for utils functions ([#286](https://github.com/unjs/consola/pull/286))
- Add jsdocs for top-level functions ([#288](https://github.com/unjs/consola/pull/288))

### 📦 Build

- Fix subpath types ([#265](https://github.com/unjs/consola/pull/265))
- Add `require` condition for browser builds ([#243](https://github.com/unjs/consola/pull/243))

### 🌊 Types

- Fix prompt with `select` type return value type ([#238](https://github.com/unjs/consola/pull/238))

### 🏡 Chore

- Update dependencies ([68b36c7](https://github.com/unjs/consola/commit/68b36c7))
- Update dependencies ([dff1ef8](https://github.com/unjs/consola/commit/dff1ef8))
- Update eslint to v9 ([238d677](https://github.com/unjs/consola/commit/238d677))
- Lint ([985a786](https://github.com/unjs/consola/commit/985a786))
- Update pnpm to v9 ([61adfbe](https://github.com/unjs/consola/commit/61adfbe))
- Update ci scripts ([9545b65](https://github.com/unjs/consola/commit/9545b65))
- Apply automated updates ([df0e555](https://github.com/unjs/consola/commit/df0e555))
- Update dependencies ([e851525](https://github.com/unjs/consola/commit/e851525))
- Fix lint issues ([8238844](https://github.com/unjs/consola/commit/8238844))
- Update deps ([093d966](https://github.com/unjs/consola/commit/093d966))
- Lint ([64cd547](https://github.com/unjs/consola/commit/64cd547))
- Update clack/core ([e2aa5c9](https://github.com/unjs/consola/commit/e2aa5c9))

### 🎨 Styles

- Format repo ([899173f](https://github.com/unjs/consola/commit/899173f))

### 🤖 CI

- Use conventional commit for autofix ([#217](https://github.com/unjs/consola/pull/217))

### ❤️ Contributors

- Guo ([@Plumbiu](http://github.com/Plumbiu))
- Pooya Parsa ([@pi0](http://github.com/pi0))
- Kongmoumou ([@kongmoumou](http://github.com/kongmoumou))
- Max ([@onmax](http://github.com/onmax))
- Michel EDIGHOFFER <edimitchel@gmail.com>
- Sébastien Chopin ([@atinux](http://github.com/atinux))
- Estéban <e.soubiran25@gmail.com>
- Nozomu Ikuta ([@nozomuikuta](http://github.com/nozomuikuta))
- Maxim Molochkov ([@klaseca](http://github.com/klaseca))
- Xjccc ([@xjccc](http://github.com/xjccc))
- Gangan ([@shinGangan](http://github.com/shinGangan))
- Daniel Roe ([@danielroe](http://github.com/danielroe))

## v3.2.3

[compare changes](https://github.com/unjs/consola/compare/v3.2.2...v3.2.3)


### 🩹 Fixes

  - **types:** Partial style options for `box` ([#210](https://github.com/unjs/consola/pull/210))
  - **types:** Add backward compatible declarations ([e46733b](https://github.com/unjs/consola/commit/e46733b))

### 🏡 Chore

  - Remove extra `await` in `spinner` example ([#211](https://github.com/unjs/consola/pull/211))
  - Add autofix ci ([b3aa049](https://github.com/unjs/consola/commit/b3aa049))
  - Update prettier ([9a4b67e](https://github.com/unjs/consola/commit/9a4b67e))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Alexander Topalo <topaloalexander@gmail.com>
- Estéban ([@Barbapapazes](http://github.com/Barbapapazes))

## v3.2.2

[compare changes](https://github.com/unjs/consola/compare/v3.2.1...v3.2.2)


### 🩹 Fixes

  - **fancy:** Add node 14 compatibility ([#204](https://github.com/unjs/consola/pull/204))

### 📦 Build

  - **pkg:** Add supported engines field ([#179](https://github.com/unjs/consola/pull/179))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.2.1

[compare changes](https://github.com/unjs/consola/compare/v3.2.0...v3.2.1)


### 🩹 Fixes

  - **box:** Fix preset naming for `singleThick` ([#201](https://github.com/unjs/consola/pull/201))
  - **fancy:** Style underscore with surrounding spaces ([#203](https://github.com/unjs/consola/pull/203))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Christian Preston ([@cpreston321](http://github.com/cpreston321))

## v3.2.0

[compare changes](https://github.com/unjs/consola/compare/v3.1.0...v3.2.0)


### 🚀 Enhancements

  - **fancy:** Support underlining ([#191](https://github.com/unjs/consola/pull/191))
  - `consola.box` ([#193](https://github.com/unjs/consola/pull/193))
  - `consola/utils` subpath export ([#199](https://github.com/unjs/consola/pull/199))
  - Color utils ([#200](https://github.com/unjs/consola/pull/200))

### 🩹 Fixes

  - Inherit mocks ([#183](https://github.com/unjs/consola/pull/183))
  - Correct and improve return types for single and multi select prompts ([#197](https://github.com/unjs/consola/pull/197))
  - Preserve tag casing ([#190](https://github.com/unjs/consola/pull/190))

### 🏡 Chore

  - Update prompt example ([#196](https://github.com/unjs/consola/pull/196))
  - Lint code ([d424218](https://github.com/unjs/consola/commit/d424218))
  - Update dependencies ([dabb705](https://github.com/unjs/consola/commit/dabb705))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Christian Preston ([@cpreston321](http://github.com/cpreston321))
- Leex ([@jsonleex](http://github.com/jsonleex))
- Inesh Bose 
- Damian Głowala

## v3.1.0

[compare changes](https://github.com/unjs/consola/compare/v3.0.2...v3.1.0)


### 🚀 Enhancements

  - Support `fancy` option for `createConsola` and improve docs ([#177](https://github.com/unjs/consola/pull/177))
  - `/basic`, `/core` and `/browser` subpath exports ([#178](https://github.com/unjs/consola/pull/178))

### 🏡 Chore

  - Add json example ([943992d](https://github.com/unjs/consola/commit/943992d))
  - Update the docs ([a952bc2](https://github.com/unjs/consola/commit/a952bc2))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.2

[compare changes](https://github.com/unjs/consola/compare/v3.0.1...v3.0.2)


### 🩹 Fixes

  - **`mockTypes`:** Mock on `options.typs` ([f9d86b6](https://github.com/unjs/consola/commit/f9d86b6))
  - Type `.raw` for types ([dfb976f](https://github.com/unjs/consola/commit/dfb976f))

### 💅 Refactors

  - Use individual named exports of reporters ([57bb579](https://github.com/unjs/consola/commit/57bb579))

### 🏡 Chore

  - Add `codecov.yml` ([1f50123](https://github.com/unjs/consola/commit/1f50123))
  - Update readme ([5a4708d](https://github.com/unjs/consola/commit/5a4708d))
  - Fix mock example ([4dadfb3](https://github.com/unjs/consola/commit/4dadfb3))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.1

[compare changes](https://github.com/unjs/consola/compare/v3.0.0...v3.0.1)


### 🩹 Fixes

  - **utils:** Use default `stream.write` for workers support ([#173](https://github.com/unjs/consola/pull/173))
  - Wrap `options.stdout` and `options.stderr` for wrapStd ([ab59db6](https://github.com/unjs/consola/commit/ab59db6))

### 💅 Refactors

  - **fancy:** More minimal badges when width cannot be determined ([ad24029](https://github.com/unjs/consola/commit/ad24029))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.0

[compare changes](https://github.com/unjs/consola/compare/v2.15.2...v3.0.0)


### 🚀 Enhancements

  - Default `logLevel` to 1 in test environments ([#134](https://github.com/unjs/consola/pull/134))
  - Support literal for logLevels ([#133](https://github.com/unjs/consola/pull/133))
  - Expose `createConsola` and named exports ([ef6e5e5](https://github.com/unjs/consola/commit/ef6e5e5))
  - `consola.prompt` util ([#170](https://github.com/unjs/consola/pull/170))
  - `consola.fail` log level ([#153](https://github.com/unjs/consola/pull/153))
  - Pass `formatOptions` and other options to reporters ([d77286a](https://github.com/unjs/consola/commit/d77286a))
  - Show stack trace with `consola.trace` ([#151](https://github.com/unjs/consola/pull/151))

### 🔥 Performance

  - Switch from chalk to colorette ([271b4db](https://github.com/unjs/consola/commit/271b4db))
  - Remove `dayjs` dependency ([d6a3776](https://github.com/unjs/consola/commit/d6a3776))

### 🩹 Fixes

  - Add `.raw` to mocked functions ([987dadc](https://github.com/unjs/consola/commit/987dadc))
  - Type consola instance with built-in type functions ([1a4b893](https://github.com/unjs/consola/commit/1a4b893))
  - Default value for color format utils ([ec9be78](https://github.com/unjs/consola/commit/ec9be78))
  - **fancy:** Show time and tag on right when width cannot be determined ([#128](https://github.com/unjs/consola/pull/128))
  - Pass level from `CONSOLA_LEVEL` to the `defaults` ([#129](https://github.com/unjs/consola/pull/129))
  - **consola:** Type defaults overrides generic defaults ([d3d3c05](https://github.com/unjs/consola/commit/d3d3c05))
  - **fancy:** Improve colors ([99c2a4f](https://github.com/unjs/consola/commit/99c2a4f))
  - **promp:** Options is optional ([817626f](https://github.com/unjs/consola/commit/817626f))

### 💅 Refactors

  - ⚠️  Rewrite consola with typescript ([4479d2f](https://github.com/unjs/consola/commit/4479d2f))
  - Rename `global` to `globalThis` ([bd03098](https://github.com/unjs/consola/commit/bd03098))
  - **utils:** Rename `global` to `globalThis` ([8c3ef77](https://github.com/unjs/consola/commit/8c3ef77))
  - Strict typechecks ([63bbd56](https://github.com/unjs/consola/commit/63bbd56))
  - Remove `globalThis` caching ([4e7b909](https://github.com/unjs/consola/commit/4e7b909))
  - Drop `json` and `winston` reporters ([5af0e99](https://github.com/unjs/consola/commit/5af0e99))
  - Move all options to `consola.options` without duplication ([2d31ef4](https://github.com/unjs/consola/commit/2d31ef4))
  - Move spam logic into `_lastLog` object ([cabd04f](https://github.com/unjs/consola/commit/cabd04f))
  - Remove global `async` option ([edd1bb9](https://github.com/unjs/consola/commit/edd1bb9))
  - **types:** Merge `LogTypeLiteral` and `logtype` types to `LogType` ([da1bc73](https://github.com/unjs/consola/commit/da1bc73))
  - ⚠️  Move log levels and types to constants ([514f5b3](https://github.com/unjs/consola/commit/514f5b3))
  - Use `index.node.ts` for main build ([b92d23b](https://github.com/unjs/consola/commit/b92d23b))
  - Improve types  and exports ([b380d21](https://github.com/unjs/consola/commit/b380d21))
  - Improve fancy reporter ([bc90db8](https://github.com/unjs/consola/commit/bc90db8))
  - Revert back to `dist/index.*` for bw compatibility ([98e300f](https://github.com/unjs/consola/commit/98e300f))
  - **fancy:** Better start color and icon ([5a01d53](https://github.com/unjs/consola/commit/5a01d53))

### 📖 Documentation

  - Fix links to the source files ([#172](https://github.com/unjs/consola/pull/172))

### 📦 Build

  - Use backward compatible cjs wrapper for default export ([e2e6aa6](https://github.com/unjs/consola/commit/e2e6aa6))

### 🏡 Chore

  - **release:** 2.15.3 ([c99ff6c](https://github.com/unjs/consola/commit/c99ff6c))
  - Make example/index.js working ([#110](https://github.com/unjs/consola/pull/110))
  - Add LICENSE ([#121](https://github.com/unjs/consola/pull/121))
  - **npm:** Update repository to unjs orgnization ([#125](https://github.com/unjs/consola/pull/125))
  - Add prerelease script ([cfaba5e](https://github.com/unjs/consola/commit/cfaba5e))
  - Hide rollup warn ([5c3b7f1](https://github.com/unjs/consola/commit/5c3b7f1))
  - Ignore coverage ([da557ac](https://github.com/unjs/consola/commit/da557ac))
  - Update examples ([e07e3ab](https://github.com/unjs/consola/commit/e07e3ab))
  - **release:** V3.0.0-1 ([c24ae27](https://github.com/unjs/consola/commit/c24ae27))
  - Rename dist-tag to 3.x ([3e8f1e0](https://github.com/unjs/consola/commit/3e8f1e0))
  - Update readme ([85bbe3a](https://github.com/unjs/consola/commit/85bbe3a))
  - Update badges ([cf7c6e5](https://github.com/unjs/consola/commit/cf7c6e5))
  - Update badges ([566ff68](https://github.com/unjs/consola/commit/566ff68))
  - **release:** V3.0.0-2 ([4a01304](https://github.com/unjs/consola/commit/4a01304))
  - Update shared exports ([8fc0fdd](https://github.com/unjs/consola/commit/8fc0fdd))
  - **release:** V3.0.0-3 ([6253fb0](https://github.com/unjs/consola/commit/6253fb0))
  - Fix import in examples ([c4fff18](https://github.com/unjs/consola/commit/c4fff18))
  - **release:** V3.0.0-4 ([474f82f](https://github.com/unjs/consola/commit/474f82f))
  - **release:** V3.0.0-5 ([ad20f89](https://github.com/unjs/consola/commit/ad20f89))
  - Add example for readme ([2bb5813](https://github.com/unjs/consola/commit/2bb5813))
  - Update readme ([0568e61](https://github.com/unjs/consola/commit/0568e61))
  - Update readme ([6a5fb0c](https://github.com/unjs/consola/commit/6a5fb0c))
  - Lint changelog ([11ba5be](https://github.com/unjs/consola/commit/11ba5be))
  - Update package.json ([f698f88](https://github.com/unjs/consola/commit/f698f88))
  - Remove browser cjs ([a5db8db](https://github.com/unjs/consola/commit/a5db8db))
  - Update release script to normal ([2634c71](https://github.com/unjs/consola/commit/2634c71))

### ✅ Tests

  - Update test ([64fa81d](https://github.com/unjs/consola/commit/64fa81d))

### 🎨 Styles

  - Prefer object spread instead of `Object.assign` ([c03268a](https://github.com/unjs/consola/commit/c03268a))

#### ⚠️  Breaking Changes

  - ⚠️  Rewrite consola with typescript ([4479d2f](https://github.com/unjs/consola/commit/4479d2f))
  - ⚠️  Move log levels and types to constants ([514f5b3](https://github.com/unjs/consola/commit/514f5b3))

### ❤️  Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- With-heart ([@with-heart](http://github.com/with-heart))
- Anthony Fu <anthonyfu117@hotmail.com>
- Xin Du (Clark) <clark.duxin@gmail.com>
- Sébastien Chopin <seb@nuxtjs.com>
- Thomas K ([@ThomasKoscheck](http://github.com/ThomasKoscheck))

## v3.0.0-5

[compare changes](https://github.com/unjs/consola/compare/v3.0.0-4...v3.0.0-5)

### 🩹 Fixes

- **fancy:** Improve colors ([99c2a4f](https://github.com/unjs/consola/commit/99c2a4f))

### 💅 Refactors

- **fancy:** Better start color and icon ([5a01d53](https://github.com/unjs/consola/commit/5a01d53))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.0-4

[compare changes](https://github.com/unjs/consola/compare/v3.0.0-3...v3.0.0-4)

### 🚀 Enhancements

- `consola.fail` log level ([#153](https://github.com/unjs/consola/pull/153))
- Pass `formatOptions` and other options to reporters ([d77286a](https://github.com/unjs/consola/commit/d77286a))
- Show stack trace with `consola.trace` ([#151](https://github.com/unjs/consola/pull/151))

### 🩹 Fixes

- Type consola instance with built-in type functions ([1a4b893](https://github.com/unjs/consola/commit/1a4b893))
- Default value for color format utils ([ec9be78](https://github.com/unjs/consola/commit/ec9be78))
- **fancy:** Show time and tag on right when width cannot be determined ([#128](https://github.com/unjs/consola/pull/128))
- Pass level from `CONSOLA_LEVEL` to the `defaults` ([#129](https://github.com/unjs/consola/pull/129))
- **consola:** Type defaults overrides generic defaults ([d3d3c05](https://github.com/unjs/consola/commit/d3d3c05))

### 💅 Refactors

- Drop `json` and `winston` reporters ([5af0e99](https://github.com/unjs/consola/commit/5af0e99))
- Move all options to `consola.options` without duplication ([2d31ef4](https://github.com/unjs/consola/commit/2d31ef4))
- Move spam logic into `_lastLog` object ([cabd04f](https://github.com/unjs/consola/commit/cabd04f))
- Remove global `async` option ([edd1bb9](https://github.com/unjs/consola/commit/edd1bb9))
- **types:** Merge `LogTypeLiteral` and `logtype` types to `LogType` ([da1bc73](https://github.com/unjs/consola/commit/da1bc73))
- ⚠️ Move log levels and types to constants ([514f5b3](https://github.com/unjs/consola/commit/514f5b3))
- Use `index.node.ts` for main build ([b92d23b](https://github.com/unjs/consola/commit/b92d23b))
- Improve types and exports ([b380d21](https://github.com/unjs/consola/commit/b380d21))
- Improve fancy reporter ([bc90db8](https://github.com/unjs/consola/commit/bc90db8))
- Revert back to `dist/index.*` for bw compatibility ([98e300f](https://github.com/unjs/consola/commit/98e300f))

### 📖 Documentation

- Fix links to the source files ([#172](https://github.com/unjs/consola/pull/172))

### 🏡 Chore

- Fix import in examples ([c4fff18](https://github.com/unjs/consola/commit/c4fff18))

### ✅ Tests

- Update test ([64fa81d](https://github.com/unjs/consola/commit/64fa81d))

### 🎨 Styles

- Prefer object spread instead of `Object.assign` ([c03268a](https://github.com/unjs/consola/commit/c03268a))

#### ⚠️ Breaking Changes

- ⚠️ Move log levels and types to constants ([514f5b3](https://github.com/unjs/consola/commit/514f5b3))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- With-heart ([@with-heart](http://github.com/with-heart))

## v3.0.0-3

[compare changes](https://github.com/unjs/consola/compare/v3.0.0-2...v3.0.0-3)

### 💅 Refactors

- Remove `globalThis` caching ([4e7b909](https://github.com/unjs/consola/commit/4e7b909))

### 📦 Build

- Use backward compatible cjs wrapper for default export ([e2e6aa6](https://github.com/unjs/consola/commit/e2e6aa6))

### 🏡 Chore

- Update shared exports ([8fc0fdd](https://github.com/unjs/consola/commit/8fc0fdd))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.0-2

[compare changes](https://github.com/unjs/consola/compare/v3.0.0-1...v3.0.0-2)

### 🚀 Enhancements

- `consola.prompt` util ([#170](https://github.com/unjs/consola/pull/170))

### 🏡 Chore

- Rename dist-tag to 3.x ([3e8f1e0](https://github.com/unjs/consola/commit/3e8f1e0))
- Update readme ([85bbe3a](https://github.com/unjs/consola/commit/85bbe3a))
- Update badges ([cf7c6e5](https://github.com/unjs/consola/commit/cf7c6e5))
- Update badges ([566ff68](https://github.com/unjs/consola/commit/566ff68))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))

## v3.0.0-1

[compare changes](https://github.com/unjs/consola/compare/v2.15.3...v3.0.0-1)

>

### 🚀 Enhancements

- Default `logLevel` to 1 in test environments ([#134](https://github.com/unjs/consola/pull/134))
- Support literal for logLevels ([#133](https://github.com/unjs/consola/pull/133))
- Expose `createConsola` and named exports ([ef6e5e5](https://github.com/unjs/consola/commit/ef6e5e5))

### 🔥 Performance

- Switch from chalk to colorette ([271b4db](https://github.com/unjs/consola/commit/271b4db))
- Remove `dayjs` dependency ([d6a3776](https://github.com/unjs/consola/commit/d6a3776))

### 💅 Refactors

- ⚠️ Rewrite consola with typescript ([4479d2f](https://github.com/unjs/consola/commit/4479d2f))
- Rename `global` to `globalThis` ([bd03098](https://github.com/unjs/consola/commit/bd03098))
- **utils:** Rename `global` to `globalThis` ([8c3ef77](https://github.com/unjs/consola/commit/8c3ef77))
- Strict typechecks ([63bbd56](https://github.com/unjs/consola/commit/63bbd56))

### 🏡 Chore

- Make example/index.js working ([#110](https://github.com/unjs/consola/pull/110))
- Add LICENSE ([#121](https://github.com/unjs/consola/pull/121))
- **npm:** Update repository to unjs orgnization ([#125](https://github.com/unjs/consola/pull/125))
- Add prerelease script ([cfaba5e](https://github.com/unjs/consola/commit/cfaba5e))
- Hide rollup warn ([5c3b7f1](https://github.com/unjs/consola/commit/5c3b7f1))
- Ignore coverage ([da557ac](https://github.com/unjs/consola/commit/da557ac))
- Update examples ([e07e3ab](https://github.com/unjs/consola/commit/e07e3ab))

#### ⚠️ Breaking Changes

- ⚠️ Rewrite consola with typescript ([4479d2f](https://github.com/unjs/consola/commit/4479d2f))

### ❤️ Contributors

- Pooya Parsa ([@pi0](http://github.com/pi0))
- Anthony Fu <anthonyfu117@hotmail.com>
- Xin Du (Clark) <clark.duxin@gmail.com>
- Sébastien Chopin <seb@nuxtjs.com>
- Thomas K ([@ThomasKoscheck](http://github.com/ThomasKoscheck))

### [2.15.3](https://github.com/unjs/consola/compare/v2.15.2...v2.15.3) (2021-02-07)

### Bug Fixes

- add `.raw` to mocked functions ([987dadc](https://github.com/unjs/consola/commit/987dadcc81a82698051ade2384ae2f0fc12d8aef))

### [2.15.2](https://github.com/unjs/consola/compare/v2.15.1...v2.15.2) (2021-02-03)

### Bug Fixes

- add isRaw flag only for wrapped calls ([23b1184](https://github.com/unjs/consola/commit/23b1184e2897f5d33943bec7180fb2427402d400)), closes [unjs/unjs.js#8752](https://github.com/unjs/unjs.js/issues/8752)

### [2.15.1](https://github.com/unjs/consola/compare/v2.15.0...v2.15.1) (2021-02-02)

### Bug Fixes

- skip logObj check for wrapped calls (fixes [#109](https://github.com/unjs/consola/issues/109)) ([091a244](https://github.com/unjs/consola/commit/091a24423bb9c28b7371e7af849b15c7e39747fa))

## [2.15.0](https://github.com/unjs/consola/compare/v2.14.0...v2.15.0) (2020-08-05)

### Features

- **types:** use union type for `ConsolaLogObject.type` ([#100](https://github.com/unjs/consola/issues/100)) ([a6eba53](https://github.com/unjs/consola/commit/a6eba532381bcec9c84ac5600ac668aca87c8487))
- support `formatOptions.date` to optionally hide date ([#101](https://github.com/unjs/consola/issues/101)) ([6bf733f](https://github.com/unjs/consola/commit/6bf733f2b9a5320584bdd0de7de08f4341c74335))

## [2.14.0](https://github.com/unjs/consola/compare/v2.13.0...v2.14.0) (2020-06-26)

### Features

- improve spam throttle ([5314eee](https://github.com/unjs/consola/commit/5314eeebb4b564408a4ab14cb457bdbd426f6124))

## [2.13.0](https://github.com/unjs/consola/compare/v2.12.2...v2.13.0) (2020-06-12)

### Features

- remove level boundary check ([8972d47](https://github.com/unjs/consola/commit/8972d478c93690fafb909f49d9d0edbcb67bddae))

### Bug Fixes

- **types:** fix silent/verbose levels ([7ab0a65](https://github.com/unjs/consola/commit/7ab0a65f383d9dd1b68a18ee439bf19468a57885))

### [2.12.2](https://github.com/unjs/consola/compare/v2.12.1...v2.12.2) (2020-05-26)

### Bug Fixes

- silent log level does not work ([#98](https://github.com/unjs/consola/issues/98)) ([6a4a79c](https://github.com/unjs/consola/commit/6a4a79c24b8db902b078ad92a6ee7a33880ed26c))

### [2.12.1](https://github.com/unjs/consola/compare/v2.12.0...v2.12.1) (2020-05-07)

### Bug Fixes

- new LogLevel enum is not exported properly [#95](https://github.com/unjs/consola/issues/95) ([#96](https://github.com/unjs/consola/issues/96)) ([fafbec2](https://github.com/unjs/consola/commit/fafbec2b1bc75912eea5d0618a27b982738d6cda))

## [2.12.0](https://github.com/unjs/consola/compare/v2.11.3...v2.12.0) (2020-05-07)

### Features

- **types:** add missing typescript definitions for reporters ([#94](https://github.com/unjs/consola/issues/94)) ([4a08ef0](https://github.com/unjs/consola/commit/4a08ef02bc48ddc887f2b91713520eda50793a27))

### [2.11.3](https://github.com/unjs/consola/compare/v2.11.2...v2.11.3) (2019-12-31)

### Bug Fixes

- **typescript:** remove cjs export (fixes [#88](https://github.com/unjs/consola/issues/88)) ([0d9ab1b](https://github.com/unjs/consola/commit/0d9ab1bba8645853c721069c57527764ed708869))

### [2.11.2](https://github.com/unjs/consola/compare/v2.11.1...v2.11.2) (2019-12-27)

### Bug Fixes

- **types:** `const consola = require('consola')` type is wrong ([#80](https://github.com/unjs/consola/issues/80)) ([5c22d8c](https://github.com/unjs/consola/commit/5c22d8cd4624e3bbd7294b9eba09f131ed786332))
- throttle expiration ([#81](https://github.com/unjs/consola/issues/81)) ([940474d](https://github.com/unjs/consola/commit/940474d3b64a4969acdec04290734e700920c19f)), closes [#68](https://github.com/unjs/consola/issues/68)

### [2.11.1](https://github.com/unjs/consola/compare/v2.11.0...v2.11.1) (2019-12-17)

### Bug Fixes

- **consola:** use `options.stderr` ([#77](https://github.com/unjs/consola/issues/77)) ([774c673](https://github.com/unjs/consola/commit/774c6739e794665bc5e2c40aa84921b7f2a26387))

## [2.11.0](https://github.com/unjs/consola/compare/v2.10.0...v2.11.0) (2019-11-10)

### Features

- **browser:** add support of formatted strings ([#66](https://github.com/unjs/consola/issues/66)) ([920f313](https://github.com/unjs/consola/commit/920f313dba322c34ccd1b2f08afba59122c3b8e7))

### Bug Fixes

- typecheck type and tag before normalize ([1984deb](https://github.com/unjs/consola/commit/1984deb0a5214a3aa82dab972ec76af20ba14d1b))
- **types:** reporter in remove methods are optional ([#70](https://github.com/unjs/consola/issues/70)) ([a17cdb1](https://github.com/unjs/consola/commit/a17cdb1a423e41076c58692130955d5a9f5e36ba))

### [2.10.1](https://github.com/unjs/consola/compare/v2.10.0...v2.10.1) (2019-08-05)

## [2.10.0](https://github.com/unjs/consola/compare/v2.9.0...v2.10.0) (2019-08-05)

### Bug Fixes

- add missing typescript declaration for level, stdout and stderr ([#58](https://github.com/unjs/consola/issues/58)) ([a149dbb](https://github.com/unjs/consola/commit/a149dbb))

### Features

- improve typescript type definitions ([#57](https://github.com/unjs/consola/issues/57)) ([80eefd8](https://github.com/unjs/consola/commit/80eefd8))

## [2.9.0](https://github.com/unjs/consola/compare/v2.8.0...v2.9.0) (2019-06-18)

### Features

- count spam log ([197a6b3](https://github.com/unjs/consola/commit/197a6b3))

## [2.8.0](https://github.com/unjs/consola/compare/v2.7.1...v2.8.0) (2019-06-18)

### Features

- spam preventation ([7da806b](https://github.com/unjs/consola/commit/7da806b))

### [2.7.1](https://github.com/unjs/consola/compare/v2.7.0...v2.7.1) (2019-05-26)

### Bug Fixes

- **browser:** hide `:` with tag and normal log ([8250d5a](https://github.com/unjs/consola/commit/8250d5a))

## [2.7.0](https://github.com/unjs/consola/compare/v2.6.2...v2.7.0) (2019-05-26)

### Bug Fixes

- correctly calculate line width when using grave accent ([bad52bd](https://github.com/unjs/consola/commit/bad52bd))

### Features

- always hide right side on width < 80 ([07d8246](https://github.com/unjs/consola/commit/07d8246))
- improve basic logs ([ea6ce59](https://github.com/unjs/consola/commit/ea6ce59))
- **browser:** fancier logs ([b64f337](https://github.com/unjs/consola/commit/b64f337))
- hide time from basic logger as it is commonly used in CI environments ([68c3bae](https://github.com/unjs/consola/commit/68c3bae))
- smart hide time and tag when there is no space ([00a375f](https://github.com/unjs/consola/commit/00a375f))

### [2.6.2](https://github.com/unjs/consola/compare/v2.6.1...v2.6.2) (2019-05-15)

### Bug Fixes

- transpile browser dist to ES5 ([1f81eea](https://github.com/unjs/consola/commit/1f81eea)), closes [unjs/unjs.js#5743](https://github.com/unjs/consola/issues/5743)

### [2.6.1](https://github.com/unjs/consola/compare/v2.6.0...v2.6.1) (2019-05-08)

### Bug Fixes

- **browser:** use `console.warn` when possible ([#49](https://github.com/unjs/consola/issues/49)) ([e386ede](https://github.com/unjs/consola/commit/e386ede))

# [2.6.0](https://github.com/unjs/consola/compare/v2.5.8...v2.6.0) (2019-04-12)

### Features

- expose constructor and reporters ([3a8f662](https://github.com/unjs/consola/commit/3a8f662))

## [2.5.8](https://github.com/unjs/consola/compare/v2.5.7...v2.5.8) (2019-03-29)

### Bug Fixes

- **types:** allow passing extra arguments ([#46](https://github.com/unjs/consola/issues/46)) ([d29fc46](https://github.com/unjs/consola/commit/d29fc46))

## [2.5.7](https://github.com/unjs/consola/compare/v2.5.6...v2.5.7) (2019-03-19)

### Bug Fixes

- **formatting:** fix formatting when multiple back-quotes ([#44](https://github.com/unjs/consola/issues/44)) ([669a12e](https://github.com/unjs/consola/commit/669a12e))

## [2.5.6](https://github.com/unjs/consola/compare/v2.5.5...v2.5.6) (2019-02-25)

### Bug Fixes

- **ts:** revert export consola ts declarations ([#43](https://github.com/unjs/consola/issues/43)) ([6bd4f85](https://github.com/unjs/consola/commit/6bd4f85))

<a name="2.4.1"></a>

## [2.4.1](https://github.com/unjs/consola/compare/v2.4.0...v2.4.1) (2019-02-12)

### Bug Fixes

- **ts:** set type "any" ([#40](https://github.com/unjs/consola/issues/40)) ([ea9d551](https://github.com/unjs/consola/commit/ea9d551))

<a name="2.4.0"></a>

# [2.4.0](https://github.com/unjs/consola/compare/v2.3.2...v2.4.0) (2019-02-05)

### Bug Fixes

- **esm:** fix esm compatibility ([8ddecc3](https://github.com/unjs/consola/commit/8ddecc3))
- **consola:** return `this` in setReporters ([544a887](https://github.com/unjs/consola/commit/544a887))
- **types:** set message type to "any" ([#39](https://github.com/unjs/consola/issues/39)) ([ff97b09](https://github.com/unjs/consola/commit/ff97b09)), closes [#38](https://github.com/unjs/consola/issues/38)

### Features

- **types:** update types ([d0d7455](https://github.com/unjs/consola/commit/d0d7455))

<a name="2.3.2"></a>

## [2.3.2](https://github.com/unjs/consola/compare/v2.3.1...v2.3.2) (2019-01-06)

### Bug Fixes

- **types:** add some of the missing types ([#35](https://github.com/unjs/consola/issues/35)) ([5e3e69b](https://github.com/unjs/consola/commit/5e3e69b))
- ignore winston dep in webpack ([#37](https://github.com/unjs/consola/issues/37)) ([e534a28](https://github.com/unjs/consola/commit/e534a28))

<a name="2.3.1"></a>

## [2.3.1](https://github.com/unjs/consola/compare/v2.3.0...v2.3.1) (2019-01-02)

### Bug Fixes

- bypass webpack for lazy required version of winston ([500b509](https://github.com/unjs/consola/commit/500b509))

<a name="2.3.0"></a>

# [2.3.0](https://github.com/unjs/consola/compare/v2.2.6...v2.3.0) (2018-11-19)

### Bug Fixes

- **isLogObj:** handle non-standard error objects ([8748c81](https://github.com/unjs/consola/commit/8748c81))

### Features

- browser reporter improvements ([591d0b4](https://github.com/unjs/consola/commit/591d0b4)), closes [#31](https://github.com/unjs/consola/issues/31)
- **fancy:** look like jest traces ([ecae238](https://github.com/unjs/consola/commit/ecae238))

<a name="2.2.6"></a>

## [2.2.6](https://github.com/unjs/consola/compare/v2.2.5...v2.2.6) (2018-11-14)

### Bug Fixes

- **json-reporter:** add a default value to the constructor ([#33](https://github.com/unjs/consola/issues/33)) ([c59db36](https://github.com/unjs/consola/commit/c59db36))

<a name="2.2.5"></a>

## [2.2.5](https://github.com/unjs/consola/compare/v2.2.4...v2.2.5) (2018-11-14)

### Bug Fixes

- expose typescript typings ([f0398ed](https://github.com/unjs/consola/commit/f0398ed))

<a name="2.2.4"></a>

## [2.2.4](https://github.com/unjs/consola/compare/v2.2.3...v2.2.4) (2018-11-08)

### Bug Fixes

- use basic reporter only for ci and test environments ([33220e4](https://github.com/unjs/consola/commit/33220e4))

<a name="2.2.3"></a>

## [2.2.3](https://github.com/unjs/consola/compare/v2.2.2...v2.2.3) (2018-11-07)

### Bug Fixes

- **fancy:** honor logObj.icon ([d56fa38](https://github.com/unjs/consola/commit/d56fa38))

<a name="2.2.2"></a>

## [2.2.2](https://github.com/unjs/consola/compare/v2.2.1...v2.2.2) (2018-11-04)

### Bug Fixes

- update std-env to 2.1.1 ([32a9c67](https://github.com/unjs/consola/commit/32a9c67))

<a name="2.2.1"></a>

## [2.2.1](https://github.com/unjs/consola/compare/v2.2.0...v2.2.1) (2018-11-04)

### Bug Fixes

- remove file:// from error stack traces ([ff24b69](https://github.com/unjs/consola/commit/ff24b69))

<a name="2.2.0"></a>

# [2.2.0](https://github.com/unjs/consola/compare/v2.1.1...v2.2.0) (2018-11-04)

### Bug Fixes

- correctly handle falsy values ([367fb19](https://github.com/unjs/consola/commit/367fb19))

### Features

- support formatOptions. resolves [#29](https://github.com/unjs/consola/issues/29). ([7ed640f](https://github.com/unjs/consola/commit/7ed640f))

<a name="2.1.1"></a>

## [2.1.1](https://github.com/unjs/consola/compare/v2.1.0...v2.1.1) (2018-11-03)

### Bug Fixes

- add legacy ready and start levels for more backward compatibility ([f54b5c2](https://github.com/unjs/consola/commit/f54b5c2))

<a name="2.1.0"></a>

# [2.1.0](https://github.com/unjs/consola/compare/v2.0.9...v2.1.0) (2018-11-03)

### Features

- add aliases ([cbea7bd](https://github.com/unjs/consola/commit/cbea7bd))
- mockTypes for easy mocking ([a332890](https://github.com/unjs/consola/commit/a332890))

<a name="2.0.9"></a>

## [2.0.9](https://github.com/unjs/consola/compare/v2.0.8...v2.0.9) (2018-11-03)

<a name="2.0.8"></a>

## [2.0.8](https://github.com/unjs/consola/compare/v2.0.7...v2.0.8) (2018-11-03)

<a name="2.0.7"></a>

## [2.0.7](https://github.com/unjs/consola/compare/v2.0.6...v2.0.7) (2018-11-02)

### Bug Fixes

- always use computed values for stdout/stderr ([f91abc0](https://github.com/unjs/consola/commit/f91abc0))

<a name="2.0.6"></a>

## [2.0.6](https://github.com/unjs/consola/compare/v2.0.5...v2.0.6) (2018-11-02)

<a name="2.0.5"></a>

## [2.0.5](https://github.com/unjs/consola/compare/v2.0.4...v2.0.5) (2018-11-02)

<a name="2.0.4"></a>

## [2.0.4](https://github.com/unjs/consola/compare/v2.0.3...v2.0.4) (2018-11-02)

### Bug Fixes

- **fancy:** remove extra icons ([b66fde0](https://github.com/unjs/consola/commit/b66fde0))

<a name="2.0.3"></a>

## [2.0.3](https://github.com/unjs/consola/compare/v2.0.2...v2.0.3) (2018-11-02)

### Bug Fixes

- **pkg:** exclude src from package ([4b1fb7d](https://github.com/unjs/consola/commit/4b1fb7d))
- use live console.\_stdout bindings for default stream ([d9573c3](https://github.com/unjs/consola/commit/d9573c3))

<a name="2.0.2"></a>

## [2.0.2](https://github.com/unjs/consola/compare/v2.0.1...v2.0.2) (2018-11-02)

### Bug Fixes

- **error:** always strip first line from stack ([3afa9aa](https://github.com/unjs/consola/commit/3afa9aa))

<a name="2.0.1"></a>

## [2.0.1](https://github.com/unjs/consola/compare/v2.0.0...v2.0.1) (2018-11-02)

### Bug Fixes

- **fancy:** use proper color for log paths ([7c75283](https://github.com/unjs/consola/commit/7c75283))

<a name="2.0.0"></a>

# [2.0.0](https://github.com/unjs/consola/compare/v2.0.0-2...v2.0.0) (2018-11-02)

<a name="2.0.0-2"></a>

# [2.0.0-2](https://github.com/unjs/consola/compare/v2.0.0-1...v2.0.0-2) (2018-11-02)

### Bug Fixes

- add methods for legacy support ([4bdd034](https://github.com/unjs/consola/commit/4bdd034))
- preserve additional new lines ([340a001](https://github.com/unjs/consola/commit/340a001))
- update std-env to 2.1.0 ([2dc2a50](https://github.com/unjs/consola/commit/2dc2a50))

### Features

- support badge with fancy ([38600fe](https://github.com/unjs/consola/commit/38600fe))

<a name="2.0.0-1"></a>

# [2.0.0-1](https://github.com/unjs/consola/compare/v2.0.0-0...v2.0.0-1) (2018-10-31)

<a name="2.0.0-0"></a>

# [2.0.0-0](https://github.com/unjs/consola/compare/v1.4.4...v2.0.0-0) (2018-10-31)

### Bug Fixes

- add schmance.js ([2929648](https://github.com/unjs/consola/commit/2929648))
- **docs:** update readme ([#22](https://github.com/unjs/consola/issues/22)) ([e75f2a0](https://github.com/unjs/consola/commit/e75f2a0))
- add default/undefined color for browser ([39584d2](https://github.com/unjs/consola/commit/39584d2))
- add missing parseStack import ([da53dee](https://github.com/unjs/consola/commit/da53dee))
- also copy symbols in assignGlobalReference ([b0eefb5](https://github.com/unjs/consola/commit/b0eefb5))
- don't return this when calling log functions ([f07e056](https://github.com/unjs/consola/commit/f07e056))
- fix badge display ([e036eed](https://github.com/unjs/consola/commit/e036eed))
- fix main field ([4b56e48](https://github.com/unjs/consola/commit/4b56e48))
- fix typos ([45e2f99](https://github.com/unjs/consola/commit/45e2f99))
- handle null value of obj for assignToLogObj ([d2402af](https://github.com/unjs/consola/commit/d2402af))
- improve browser packaging ([4d8c8d0](https://github.com/unjs/consola/commit/4d8c8d0))
- lint ([f909761](https://github.com/unjs/consola/commit/f909761))
- lint ([d976620](https://github.com/unjs/consola/commit/d976620))
- only one color ending parameter is enough ([d213634](https://github.com/unjs/consola/commit/d213634))
- readme: icon string length is digit ([31f1894](https://github.com/unjs/consola/commit/31f1894))
- remove name assignment ([8d59075](https://github.com/unjs/consola/commit/8d59075))
- remove pushes for better readability ([418d84a](https://github.com/unjs/consola/commit/418d84a))
- rename private fields ([244fe5c](https://github.com/unjs/consola/commit/244fe5c))
- rename require test file ([cfc8f9e](https://github.com/unjs/consola/commit/cfc8f9e))
- return earlier on not displaying levels ([cfdcf04](https://github.com/unjs/consola/commit/cfdcf04))
- support Error as logObject ([134ff54](https://github.com/unjs/consola/commit/134ff54))
- text color comment ([9336fbc](https://github.com/unjs/consola/commit/9336fbc))
- update demo ([3842e0e](https://github.com/unjs/consola/commit/3842e0e))
- use symbols for private property access ([8e6343c](https://github.com/unjs/consola/commit/8e6343c))

### Code Refactoring

- additionalStyle ~> additionalColor ([3f808e9](https://github.com/unjs/consola/commit/3f808e9))

### Features

- add **VERSION** to consola prototype ([982c8ca](https://github.com/unjs/consola/commit/982c8ca))
- add assignGlobalConsola helper ([1af28f7](https://github.com/unjs/consola/commit/1af28f7))
- add getter/setter for level ([7af5ed5](https://github.com/unjs/consola/commit/7af5ed5))
- add global.consola ([4da784d](https://github.com/unjs/consola/commit/4da784d))
- add shmancy reporter ([dc6121a](https://github.com/unjs/consola/commit/dc6121a))
- add symbols to browser ([30cd4f0](https://github.com/unjs/consola/commit/30cd4f0))
- add sync/async write ([8525525](https://github.com/unjs/consola/commit/8525525))
- add typescript typings ([#24](https://github.com/unjs/consola/issues/24)) ([0853a6f](https://github.com/unjs/consola/commit/0853a6f))
- align basic and fancy reporter tags ([38a4729](https://github.com/unjs/consola/commit/38a4729))
- better stack formater ([f5acb3c](https://github.com/unjs/consola/commit/f5acb3c))
- detect version changes and throw a warning ([73bdd1a](https://github.com/unjs/consola/commit/73bdd1a))
- improve packaging and exports ([90da862](https://github.com/unjs/consola/commit/90da862))
- improve packaging for browser support ([47af1df](https://github.com/unjs/consola/commit/47af1df))
- initial works for v2.0.0 ([455b6f9](https://github.com/unjs/consola/commit/455b6f9))
- log formatting using printf ([2afb025](https://github.com/unjs/consola/commit/2afb025))
- no more side effects ([c015c31](https://github.com/unjs/consola/commit/c015c31))
- pause/resume ([f217cc1](https://github.com/unjs/consola/commit/f217cc1))
- return new consola instance with consola.create ([4ae3614](https://github.com/unjs/consola/commit/4ae3614))
- rework \_createLogFn with better argument handling ([2d4af39](https://github.com/unjs/consola/commit/2d4af39))
- scope inheritance support ([#23](https://github.com/unjs/consola/issues/23)) ([0070c54](https://github.com/unjs/consola/commit/0070c54))
- **fancy/basic:** support logObj.stack field ([aa2216f](https://github.com/unjs/consola/commit/aa2216f))
- setReporters, withDefaults and withTag ([912446f](https://github.com/unjs/consola/commit/912446f))
- showType option ([ed294e4](https://github.com/unjs/consola/commit/ed294e4))
- style browser reporter ([d39684d](https://github.com/unjs/consola/commit/d39684d))
- support all chalk colors ([2cec678](https://github.com/unjs/consola/commit/2cec678)), closes [#20](https://github.com/unjs/consola/issues/20)
- wrapConsole ([3962a1f](https://github.com/unjs/consola/commit/3962a1f))
- wrapStd ([f8bfbeb](https://github.com/unjs/consola/commit/f8bfbeb))
- write error and warns to process.stderr by default ([6565254](https://github.com/unjs/consola/commit/6565254))

### Performance Improvements

- **basic:** refactor getWriteMethod ([c52db69](https://github.com/unjs/consola/commit/c52db69))
- remove all DEPRECATED helpers for less bundle size ([fe39d37](https://github.com/unjs/consola/commit/fe39d37))

### BREAKING CHANGES

- Use new additionalColor prop
- lot's of internals had been changed.
- Behavior may be changed in some conditions

<a name="1.4.4"></a>

## [1.4.4](https://github.com/unjs/consola/compare/v1.4.3...v1.4.4) (2018-10-13)

### Bug Fixes

- add global.consola ([558cae5](https://github.com/unjs/consola/commit/558cae5))

<a name="1.4.3"></a>

## [1.4.3](https://github.com/unjs/consola/compare/v1.4.2...v1.4.3) (2018-08-18)

### Bug Fixes

- use more compatible string to clear the console ([82ce410](https://github.com/unjs/consola/commit/82ce410))

<a name="1.4.2"></a>

## [1.4.2](https://github.com/unjs/consola/compare/v1.4.1...v1.4.2) (2018-08-12)

### Bug Fixes

- cannot set level as 0 in options ([4c1ecce](https://github.com/unjs/consola/commit/4c1ecce))

<a name="1.4.1"></a>

## [1.4.1](https://github.com/unjs/consola/compare/v1.4.0...v1.4.1) (2018-05-27)

### Bug Fixes

- **fancy:** logObj.type ([418be28](https://github.com/unjs/consola/commit/418be28))

<a name="1.4.0"></a>

# [1.4.0](https://github.com/unjs/consola/compare/v1.3.0...v1.4.0) (2018-05-27)

### Features

- support custom additional style ([#18](https://github.com/unjs/consola/issues/18)) ([7a750bf](https://github.com/unjs/consola/commit/7a750bf))
- **fancy:** support icon field ([0123bed](https://github.com/unjs/consola/commit/0123bed))

<a name="1.3.0"></a>

# [1.3.0](https://github.com/unjs/consola/compare/v1.2.0...v1.3.0) (2018-04-15)

### Bug Fixes

- **reporters/fancy:** extra space for additional ([efeab44](https://github.com/unjs/consola/commit/efeab44))
- prevent duplicate consola instances when different versions used by packages ([0bce262](https://github.com/unjs/consola/commit/0bce262))

### Features

- support extra log arguments ([8b6d3d2](https://github.com/unjs/consola/commit/8b6d3d2))

<a name="1.2.0"></a>

# [1.2.0](https://github.com/unjs/consola/compare/v1.1.4...v1.2.0) (2018-04-02)

### Features

- **basic:** support additional field ([b50cad8](https://github.com/unjs/consola/commit/b50cad8))
- improve packaging ([158e8ef](https://github.com/unjs/consola/commit/158e8ef))

### Performance Improvements

- require needed lodash methods only ([91065e4](https://github.com/unjs/consola/commit/91065e4))

<a name="1.1.4"></a>

## [1.1.4](https://github.com/unjs/consola/compare/v1.1.3...v1.1.4) (2018-03-31)

### Bug Fixes

- **package:** add chalk to dependencies ([3f738e9](https://github.com/unjs/consola/commit/3f738e9))

<a name="1.1.3"></a>

## [1.1.3](https://github.com/unjs/consola/compare/v1.1.2...v1.1.3) (2018-03-31)

### Bug Fixes

- only include dist and src in package ([8b477ec](https://github.com/unjs/consola/commit/8b477ec))

<a name="1.1.2"></a>

## [1.1.2](https://github.com/unjs/consola/compare/v1.1.1...v1.1.2) (2018-03-31)

### Bug Fixes

- handle null and undefined calls ([1f98bb1](https://github.com/unjs/consola/commit/1f98bb1))

<a name="1.1.1"></a>

## [1.1.1](https://github.com/unjs/consola/compare/v1.1.0...v1.1.1) (2018-03-31)

### Bug Fixes

- add prepublish script ([8dd8700](https://github.com/unjs/consola/commit/8dd8700))

<a name="1.1.0"></a>

# [1.1.0](https://github.com/unjs/consola/compare/v1.0.0...v1.1.0) (2018-03-31)

### Features

- rewrite FancyReporter without ora ([73c1ddc](https://github.com/unjs/consola/commit/73c1ddc))

<a name="1.0.0"></a>

# [1.0.0](https://github.com/unjs/consola/compare/v0.1.0...v1.0.0) (2018-03-31)

<a name="0.1.0"></a>

# 0.1.0 (2018-03-31)

### Features

- add log type for console compability ([96a8162](https://github.com/unjs/consola/commit/96a8162))


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) Pooya Parsa <pooya@pi0.io>

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.

---

Prompt support is based on https://github.com/bombshell-dev/clack

MIT License

Copyright (c) Nate Moore

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.

---

Color support is based on https://github.com/jorgebucaran/colorette

Copyright © Jorge Bucaran <https://jorgebucaran.com>

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.


================================================
FILE: README.md
================================================
# 🐨 Consola

> Elegant Console Wrapper

[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]

<!-- [![Codecov][codecov-src]][codecov-href] -->

## Why Consola?

👌&nbsp; Easy to use<br>
💅&nbsp; Fancy output with fallback for minimal environments<br>
🔌&nbsp; Pluggable reporters<br>
💻&nbsp; Consistent command line interface (CLI) experience<br>
🏷&nbsp; Tag support<br>
🚏&nbsp; Redirect `console` and `stdout/stderr` to consola and easily restore redirect.<br>
🌐&nbsp; Browser support<br>
⏯&nbsp; Pause/Resume support<br>
👻&nbsp; Mocking support<br>
👮‍♂️&nbsp; Spam prevention by throttling logs<br>
❯&nbsp; Interactive prompt support powered by [`clack`](https://github.com/natemoo-re/clack)<br>

## Installation

Using npm:

```bash
npm i consola
```

Using yarn:

```bash
yarn add consola
```

Using pnpm:

```bash
pnpm i consola
```

## Getting Started

```js
// ESM
import { consola, createConsola } from "consola";

// CommonJS
const { consola, createConsola } = require("consola");

consola.info("Using consola 3.0.0");
consola.start("Building project...");
consola.warn("A new version of consola is available: 3.0.1");
consola.success("Project built!");
consola.error(new Error("This is an example error. Everything is fine!"));
consola.box("I am a simple box");
await consola.prompt("Deploy to the production?", {
  type: "confirm",
});
```

Will display in the terminal:

![consola-screenshot](https://github.com/unjs/consola/assets/904724/0e511ee6-2543-43ab-9eda-152f07134d94)

You can use smaller core builds without fancy reporter to save 80% of the bundle size:

```ts
import { consola, createConsola } from "consola/basic";
import { consola, createConsola } from "consola/browser";
import { createConsola } from "consola/core";
```

## Consola Methods

#### `<type>(logObject)` `<type>(args...)`

Log to all reporters.

Example: `consola.info('Message')`

#### `await prompt(message, { type, cancel })`

Show an input prompt. Type can either of `text`, `confirm`, `select` or `multiselect`.

If prompt is canceled by user (with Ctrol+C), default value will be resolved by default. This strategy can be configured by setting `{ cancel: "..." }` option:

- `"default"` - Resolve the promise with the `default` value or `initial` value.
- `"undefined`" - Resolve the promise with `undefined`.
- `"null"` - Resolve the promise with `null`.
- `"symbol"` - Resolve the promise with a symbol `Symbol.for("cancel")`.
- `"reject"` - Reject the promise with an error.

See [examples/prompt.ts](./examples/prompt.ts) for usage examples.

#### `addReporter(reporter)`

- Aliases: `add`

Register a custom reporter instance.

#### `removeReporter(reporter?)`

- Aliases: `remove`, `clear`

Remove a registered reporter.

If no arguments are passed all reporters will be removed.

#### `setReporters(reporter|reporter[])`

Replace all reporters.

#### `create(options)`

Create a new `Consola` instance and inherit all parent options for defaults.

#### `withDefaults(defaults)`

Create a new `Consola` instance with provided defaults

#### `withTag(tag)`

- Aliases: `withScope`

Create a new `Consola` instance with that tag.

#### `wrapConsole()` `restoreConsole()`

Globally redirect all `console.log`, etc calls to consola handlers.

#### `wrapStd()` `restoreStd()`

Globally redirect all stdout/stderr outputs to consola.

#### `wrapAll()` `restoreAll()`

Wrap both, std and console.

console uses std in the underlying so calling `wrapStd` redirects console too.
Benefit of this function is that things like `console.info` will be correctly redirected to the corresponding type.

#### `pauseLogs()` `resumeLogs()`

- Aliases: `pause`/`resume`

**Globally** pause and resume logs.

Consola will enqueue all logs when paused and then sends them to the reported when resumed.

#### `mockTypes`

- Aliases: `mock`

Mock all types. Useful for using with tests.

The first argument passed to `mockTypes` should be a callback function accepting `(typeName, type)` and returning the mocked value:

```js
// Jest
consola.mockTypes((typeName, type) => jest.fn());
// Vitest
consola.mockTypes((typeName, type) => vi.fn());
```

Please note that with the example above, everything is mocked independently for each type. If you need one mocked fn create it outside:

```js
// Jest
const fn = jest.fn();
// Vitest
const fn = vi.fn();
consola.mockTypes(() => fn);
```

If callback function returns a _falsy_ value, that type won't be mocked.

For example if you just need to mock `consola.fatal`:

```js
// Jest
consola.mockTypes((typeName) => typeName === "fatal" && jest.fn());
// Vitest
consola.mockTypes((typeName) => typeName === "fatal" && vi.fn());
```

**NOTE:** Any instance of consola that inherits the mocked instance, will apply provided callback again.
This way, mocking works for `withTag` scoped loggers without need to extra efforts.

## Custom Reporters

Consola ships with 3 built-in reporters out of the box. A fancy colored reporter by default and fallsback to a basic reporter if running in a testing or CI environment detected using [unjs/std-env](https://github.com/unjs/std-env) and a basic browser reporter.

You can create a new reporter object that implements `{ log(logObject): () => { } }` interface.

**Example:** Simple JSON reporter

```ts
import { createConsola } from "consola";

const consola = createConsola({
  reporters: [
    {
      log: (logObj) => {
        console.log(JSON.stringify(logObj));
      },
    },
  ],
});

// Prints {"date":"2023-04-18T12:43:38.693Z","args":["foo bar"],"type":"log","level":2,"tag":""}
consola.log("foo bar");
```

**Example:** Exit on fatal errors

```ts
import { consola } from 'consola';

consola.addReporter({
  log(logObj) {
    if(logObj.type === 'fatal') {
      process.exit(1)
    }
  }
})

// Will exit on this line.
consola.fatal("fatal error");
```

## Log Level

Consola only shows logs with configured log level or below. (Default is `3`)

Available log levels:

- `0`: Fatal and Error
- `1`: Warnings
- `2`: Normal logs
- `3`: Informational logs, success, fail, ready, start, ...
- `4`: Debug logs
- `5`: Trace logs
- `-999`: Silent
- `+999`: Verbose logs

You can set the log level by either:

- Passing `level` option to `createConsola`
- Setting `consola.level` on instance
- Using the `CONSOLA_LEVEL` environment variable (not supported for browser and core builds).

## Log Types

Log types are exposed as `consola.[type](...)` and each is a preset of styles and log level.

A list of all available built-in types is [available here](./src/constants.ts).

## Creating a new instance

Consola has a global instance and is recommended to use everywhere.
In case more control is needed, create a new instance.

```js
import { createConsola } from "consola";

const logger = createConsola({
  // level: 4,
  // fancy: true | false
  // formatOptions: {
  //     columns: 80,
  //     colors: false,
  //     compact: false,
  //     date: false,
  // },
});
```

## Integrations

### With jest or vitest

```js
describe("your-consola-mock-test", () => {
  beforeAll(() => {
    // Redirect std and console to consola too
    // Calling this once is sufficient
    consola.wrapAll();
  });

  beforeEach(() => {
    // Re-mock consola before each test call to remove
    // calls from before
    // Jest
    consola.mockTypes(() => jest.fn());
    // Vitest
    consola.mockTypes(() => vi.fn());
  });

  test("your test", async () => {
    // Some code here

    // Let's retrieve all messages of `consola.log`
    // Get the mock and map all calls to their first argument
    const consolaMessages = consola.log.mock.calls.map((c) => c[0]);
    expect(consolaMessages).toContain("your message");
  });
});
```

### With jsdom

```js
{
  new jsdom.VirtualConsole().sendTo(consola);
}
```

## Console Utils

```ts
// ESM
import {
  stripAnsi,
  centerAlign,
  rightAlign,
  leftAlign,
  align,
  box,
  colors,
  getColor,
  colorize,
} from "consola/utils";

// CommonJS
const { stripAnsi } = require("consola/utils");
```

## Raw logging methods

Objects sent to the reporter could lead to unexpected output when object is close to internal object structure containing either `message` or `args` props. To enforce the object to be interpreted as pure object, you can use the `raw` method chained to any log type.

**Example:**

```js
// Prints "hello"
consola.log({ message: "hello" });

// Prints "{ message: 'hello' }"
consola.log.raw({ message: "hello" });
```

## License

MIT

<!-- Badges -->

[npm-version-src]: https://img.shields.io/npm/v/consola?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/consola
[npm-downloads-src]: https://img.shields.io/npm/dm/consola?style=flat&colorA=18181B&colorB=F0DB4F
[npm-downloads-href]: https://npmjs.com/package/consola
[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/consola/main?style=flat&colorA=18181B&colorB=F0DB4F
[codecov-href]: https://codecov.io/gh/unjs/consola
[bundle-src]: https://img.shields.io/bundlephobia/min/consola?style=flat&colorA=18181B&colorB=F0DB4F
[bundle-href]: https://bundlephobia.com/result?p=consola


================================================
FILE: basic.d.ts
================================================
export * from "./dist/basic";


================================================
FILE: browser.d.ts
================================================
export * from "./dist/browser";


================================================
FILE: build.config.ts
================================================
import { defineBuildConfig } from "unbuild";

export default defineBuildConfig({
  rollup: {
    inlineDependencies: true,
  },
  hooks: {
    "rollup:options"(_, options) {
      for (const output of options.output as any[]) {
        // @ts-ignore
        output.exports = "named";
      }

      // Prompts theme
      // https://github.com/bombshell-dev/clack/issues/36
      options.plugins.push({
        name: "@clack/prompts",
        transform(code, id) {
          if (id.endsWith("@clack/prompts/dist/index.mjs")) {
            const replaces = [
              ["}  $", "} $"],
              [String.raw`"\u25C6","*"`, '"❯", ">"'],
              [String.raw`"\u25A0","x"`, '"■", "x"'],
              [String.raw`"\u25B2","x"`, '"▲", "x"'],
              [String.raw`"\u25C7","o"`, '"✔", "√"'],
              [String.raw`"\u250C","T"`, '""'],
              [String.raw`"\u2502","|"`, '""'],
              [String.raw`"\u2514","\u2014"`, '""'],
            ] as const;
            for (const [from, to] of replaces) {
              code = code.replaceAll(from, to);
            }
            return code;
          }
        },
      });

      // Node.js 14 support
      // https://github.com/unjs/consola/issues/204
      options.plugins.push({
        name: "icu-compat",
        transform(code, id) {
          if (id.endsWith("string-width/index.js")) {
            return code.replace(
              "const segmenter = new Intl.Segmenter();",
              "const segmenter = globalThis.Intl?.Segmenter ? new Intl.Segmenter() : { segment: (str) => str.split('') };",
            );
          }
        },
      });
    },
  },
});


================================================
FILE: core.d.ts
================================================
export * from "./dist/core";


================================================
FILE: eslint.config.mjs
================================================
import unjs from "eslint-config-unjs";

// https://github.com/unjs/eslint-config
export default unjs({
  ignores: [],
  rules: {
    "no-undef": 0,
    "unicorn/prefer-module": 0,
    "unicorn/prefer-top-level-await": 0,
    "unicorn/no-null": 0,
    "@typescript-eslint/no-unused-vars": 0,
    "unicorn/expiring-todo-comments": 0,
  },
  markdown: {
    rules: {
      'unicorn/no-process-exit': 0,
    }
  }
});


================================================
FILE: examples/basic.ts
================================================
import { reporterDemo } from "./utils";

reporterDemo({
  fancy: false,
});


================================================
FILE: examples/box.ts
================================================
import { consola } from "./utils";
import { colors } from "../src/utils";

function main() {
  consola.box(`I am the default banner`);

  consola.box(
    `${colors.red("I")} ${colors.yellowBright("am")} ${colors.yellow("the")} ${colors.green("rainbow")} ${colors.blue("banner")}`,
  );

  consola.box({
    title: "longer title",
    message: "short msg",
  });

  consola.box({
    title: "Box with options",
    message: `I am a banner with different options`,
    style: {
      padding: 1,
      borderColor: "magenta",
      borderStyle: "double-single-rounded",
    },
  });

  consola.box({
    title: "Update available for `consola`",
    message: `\`v1.0.2\` → \`v2.0.0\`\n\nRun \`npm install -g consola\` to update`,
    style: {
      padding: 2,
      borderColor: "yellow",
      borderStyle: "rounded",
    },
  });
}

main();


================================================
FILE: examples/error.ts
================================================
import { consola } from "./utils";

const error = new Error("This is an error\nWith second line\nAnd another", {
  cause: new Error("This is the cause", {
    cause: new Error("This is the cause of the cause"),
  }),
});

console.error(error);

console.log("\n");

consola.error(error);


================================================
FILE: examples/fancy.ts
================================================
import { reporterDemo } from "./utils";

reporterDemo({
  fancy: true,
});


================================================
FILE: examples/index.html
================================================
<!doctype html>
<html>
  <head>
    <title>Consola</title>
  </head>
  <body>
    Open developer tools to see the magic!
    <script type="module">
      import consola from "../src/browser.js";
      consola.level = 5;

      consola.wrapAll();

      for (let type of Object.keys(consola.options.types).sort()) {
        consola[type]("Open developer tools to see the magic!");
      }

      consola.withTag("customTag").info("Im from custom world!");
      consola.withTag("customTag").log("Im from custom world!");

      consola.error(new Error("Whoo Haha"));
    </script>
  </body>
</html>


================================================
FILE: examples/index.legacy.html
================================================
<!doctype html>
<html>
  <head>
    <title>Consola</title>
  </head>
  <body>
    Open developer tools to see the magic!
    <script src="../dist/consola.browser.js"></script>
    <script>
      consola.level = 5;

      consola.wrapAll();

      for (let type of Object.keys(consola.options.types).sort()) {
        consola[type]("Open developer tools to see the magic!");
      }

      consola.withTag("customTag").info("Im from custom world!");

      consola.error(new Error("Whoo Haha"));
    </script>
  </body>
</html>


================================================
FILE: examples/json.ts
================================================
import { createConsola } from "consola";

const consola = createConsola({
  reporters: [
    {
      log: (logObj) => {
        console.log(JSON.stringify(logObj));
      },
    },
  ],
});

consola.log("foo bar");


================================================
FILE: examples/mock.ts
================================================
import { consola } from "./utils";

function mockFn(type) {
  if (type === "info") {
    return function () {
      this.log("(mocked fn with info tag)");
    };
  }
}

consola.info("before");

consola.mockTypes(mockFn);

const tagged = consola.withTag("newTag");

consola.log("log is not mocked!");

consola.info("Dont see me");
tagged.info("Dont see me too");


================================================
FILE: examples/no-width.ts
================================================
import { createConsola } from "../src";

function main() {
  const consola = createConsola({
    formatOptions: { columns: 0 },
  });
  consola.info("Foobar");
  const scoped = consola.withTag("test");
  scoped.success("Foobar");
}

main();


================================================
FILE: examples/pause.ts
================================================
import { consola } from "./utils";

const c1 = consola.withTag("foo");
const c2 = consola.withTag("bar");

consola.log("before pause");

c2.pause();

c1.log("C1 is ready");
c2.log("C2 is ready");

setTimeout(() => {
  consola.resume();
  consola.log("Yo!");
}, 1000);


================================================
FILE: examples/prompt.mjs
================================================
#!/usr/bin/env node

import { consola } from "../dist/index.mjs";

const name = await consola.prompt("What is your name?", {
  placeholder: "Not sure",
  initial: "java",
  cancel: "undefined",
});

if (!name) {
  process.exit(1);
}

const confirmed = await consola.prompt("Do you want to continue?", {
  type: "confirm",
  cancel: "undefined",
});

if (!confirmed) {
  process.exit(1);
}

const projectType = await consola.prompt("Pick a project type.", {
  type: "select",
  options: [
    "JavaScript",
    "TypeScript",
    { label: "CoffeeScript", value: "CoffeeScript", hint: "oh no" },
  ],
  cancel: "undefined",
  initial: "TypeScript",
});

if (!projectType) {
  process.exit(1);
}

const tools = await consola.prompt("Select additional tools.", {
  type: "multiselect",
  required: false,
  options: [
    { value: "eslint", label: "ESLint", hint: "recommended" },
    { value: "prettier", label: "Prettier" },
    { value: "gh-action", label: "GitHub Action" },
  ],
  cancel: "undefined",
  initial: ["eslint", "prettier"],
});

if (!tools) {
  process.exit(1);
}

consola.start("Creating project...");
await new Promise((resolve) => setTimeout(resolve, 1000));
consola.success("Project created!");


================================================
FILE: examples/prompt.ts
================================================
import { consola } from "./utils";

async function main() {
  const name = await consola.prompt("What is your name?", {
    placeholder: "Not sure",
    initial: "java",
  });

  const confirmed = await consola.prompt("Do you want to continue?", {
    type: "confirm",
  });

  const projectType = await consola.prompt("Pick a project type.", {
    type: "select",
    options: [
      "JavaScript",
      "TypeScript",
      { label: "CoffeeScript", value: "CoffeeScript", hint: "oh no" },
    ],
    initial: "TypeScript",
  });

  const tools = await consola.prompt("Select additional tools.", {
    type: "multiselect",
    required: false,
    options: [
      { value: "eslint", label: "ESLint", hint: "recommended" },
      { value: "prettier", label: "Prettier" },
      { value: "gh-action", label: "GitHub Action" },
    ],
    initial: ["eslint", "prettier"],
  });

  consola.start("Creating project...");
  await new Promise((resolve) => setTimeout(resolve, 1000));
  consola.success("Project created!");
}

main();


================================================
FILE: examples/raw.ts
================================================
import { consola } from "./utils";

consola.log('consola.log({ message: "hello" })');
// Prints "hello"
consola.log({ message: "hello" });

consola.log('consola.log.raw({ message: "hello" })');
// Prints "{ message: 'hello' }"
consola.log.raw({ message: "hello" });


================================================
FILE: examples/sample.ts
================================================
import { consola } from "../src";

async function main() {
  consola.warn("A new version of consola is available: 3.0.1");
  consola.error(new Error("This is an example error. Everything is fine!"));
  consola.info("Using consola 3.0.0");
  consola.start("Building project...");
  consola.success("Project built!");
  await consola.prompt("Deploy to the production?", {
    type: "confirm",
  });
}

main();


================================================
FILE: examples/spam.ts
================================================
import { consola } from "./utils";

function waitFor(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function spam({ count, delay }) {
  for (let i = 0; i < count; i++) {
    await waitFor(delay);
    consola.log(`Spam (Count: ${count} Delay: ${delay} ms)`);
  }
}

(async () => {
  await spam({ count: 2, delay: 10 });
  await spam({ count: 20, delay: 10 });
  await spam({ count: 20, delay: 0 });
  await spam({ count: 80, delay: 10 });
})();


================================================
FILE: examples/special.ts
================================================
import { consola } from "./utils";

consola.error({
  message: "Foobar",
});

consola.log({
  AAA: "BBB",
});

// consola.log(consola)

consola.log("%d", 12);

consola.error({ type: "CSSError", message: "Use scss" });

consola.error(undefined, null, false, true, Number.NaN);

consola.log("We can `monospace` keyword using grave accent charachter!");

consola.log(
  "We can also _underline_ words but not_this or this should_not_be_underlined!",
);

// Nonstandard error
const { message, stack } = new Error("Custom Error!");
consola.error({ message, stack });

// Circular object
const a = { foo: 1, bar: undefined as any };
a.bar = a;
consola.log(a);

// Multiline
consola.log("`Hello` the `JS`\n`World` and `Beyond`!");


================================================
FILE: examples/spinner.ts
================================================
import { consola } from "./utils";

async function main() {
  consola.start("Creating project...");
  await new Promise((resolve) => setTimeout(resolve, 1000));
  consola.success("Project created!");
}

main();


================================================
FILE: examples/tree.ts
================================================
import { TreeItem, formatTree } from "../src/utils/tree";
import { consola } from "./utils";

function main() {
  const keywords = [
    "console",
    "logger",
    "reporter",
    "elegant",
    "cli",
    "universal",
    "unified",
    "prompt",
    "clack",
    "format",
    "error",
    "stacktrace",
  ];

  consola.log(formatTree(keywords));

  consola.log(
    formatTree(keywords, {
      color: "cyan",
      prefix: "  |  ",
    }),
  );

  consola.log(
    formatTree(
      [
        {
          text: "consola",
          color: "green",
        },
        {
          text: "logger",
        },
      ].map(
        (item) =>
          ({
            text: ` ${item.text}`,
            color: item.color,
          }) as TreeItem,
      ),
      {
        color: "gray",
      },
    ),
  );

  // Deep tree
  consola.log(
    formatTree([
      {
        text: "format",
        color: "red",
      },
      {
        text: "consola",
        color: "yellow",
        children: [
          {
            text: "logger",
            color: "green",
            children: [
              {
                text: "reporter",
                color: "cyan",
              },
              {
                text: "test",
                color: "magenta",
                children: ["nice tree"],
              },
            ],
          },
          {
            text: "reporter",
            color: "bold",
          },
          "test",
        ],
      },
    ]),
  );

  // Deep tree with max depth
  consola.log(
    formatTree(
      [
        {
          text: "format",
          color: "red",
        },
        {
          text: "consola",
          color: "yellow",
          children: [
            {
              text: "logger",
              color: "green",
              children: [
                {
                  text: "reporter",
                  color: "cyan",
                },
                {
                  text: "test",
                  color: "magenta",
                  children: ["nice tree"],
                },
              ],
            },
            {
              text: "reporter",
              color: "bold",
            },
            "test",
          ],
        },
      ],
      {
        maxDepth: 2,
      },
    ),
  );

  // Indicate the ellipsis
  consola.log(
    formatTree(
      [
        {
          text: "format",
          color: "red",
        },
        {
          text: "consola",
          color: "yellow",
          children: [
            {
              text: "logger",
              color: "green",
              children: [
                {
                  text: "reporter",
                  color: "cyan",
                },
                {
                  text: "test",
                  color: "magenta",
                  children: ["nice tree"],
                },
              ],
            },
            {
              text: "reporter",
              color: "bold",
            },
            "test",
          ],
        },
      ],
      {
        maxDepth: 2,
        ellipsis: "---",
      },
    ),
  );
}

main();


================================================
FILE: examples/utils/index.ts
================================================
import { ConsolaOptions, createConsola } from "../../src";
import { randomSentence } from "./sentence";

export function reporterDemo(
  opts: Partial<ConsolaOptions & { fancy: boolean }>,
) {
  const consola = createConsola({
    ...opts,
  });

  for (const type of Object.keys(consola.options.types).sort()) {
    consola[type](randomSentence());
  }

  consola.info("JSON", {
    name: "Cat",
    color: "#454545",
  });

  consola.error(new Error(randomSentence()));

  const tagged = consola.withTag("unjs").withTag("router");

  for (const type of Object.keys(consola.options.types).sort()) {
    tagged[type](randomSentence());
  }
}

export const consola = createConsola();


================================================
FILE: examples/utils/sentence.ts
================================================
import Sentencer from "sentencer";

const sentenceTemplates = [
  "the {{ noun }} is {{ a_noun }}",
  "{{ a_noun }} is {{ an_adjective }} {{ noun }}",
  "the first {{ adjective }} {{ noun }} is, in its own way, {{ a_noun }}",
  "their {{ noun }} was, in this moment, {{ an_adjective }} {{ noun }}",
  "{{ a_noun }} is {{ a_noun }} from the right perspective",
  "the literature would have us believe that {{ an_adjective }} {{ noun }} is not but {{ a_noun }}",
  "{{ an_adjective }} {{ noun }} is {{ a_noun }} of the mind",
  "the {{ adjective }} {{ noun }} reveals itself as {{ an_adjective }} {{ noun }} to those who look",
  "authors often misinterpret the {{ noun }} as {{ an_adjective }} {{ noun }}, when in actuality it feels more like {{ an_adjective}} {{ noun }}",
  "we can assume that any instance of {{ a_noun }} can be construed as {{ an_adjective }} {{ noun }}",
  "they were lost without the {{ adjective }} {{ noun }} that composed their {{ noun }}",
  "the {{ adjective }} {{ noun }} comes from {{ an_adjective }} {{ noun }}",
  "{{ a_noun }} can hardly be considered {{ an_adjective }} {{ noun }} without also being {{ a_noun }}",
  "few can name {{ an_adjective }} {{ noun }} that isn't {{ an_adjective }} {{ noun }}",
  "some posit the {{ adjective }} {{ noun }} to be less than {{ adjective }}",
  "{{ a_noun }} of the {{ noun }} is assumed to be {{ an_adjective }} {{ noun }}",
  "{{ a_noun }} sees {{ a_noun }} as {{ an_adjective }} {{ noun }}",
  "the {{ noun }} of {{ a_noun }} becomes {{ an_adjective }} {{ noun }}",
  "{{ a_noun }} is {{ a_noun }}'s {{ noun }}",
  "{{ a_noun }} is the {{ noun }} of {{ a_noun }}",
  "{{ an_adjective }} {{ noun }}'s {{ noun }} comes with it the thought that the {{ adjective }} {{ noun }} is {{ a_noun }}",
  "{{ nouns }} are {{ adjective }} {{ nouns }}",
  "{{ adjective }} {{ nouns }} show us how {{ nouns }} can be {{ nouns }}",
  "before {{ nouns }}, {{ nouns }} were only {{ nouns }}",
  "those {{ nouns }} are nothing more than {{ nouns }}",
  "some {{ adjective }} {{ nouns }} are thought of simply as {{ nouns }}",
  "one cannot separate {{ nouns }} from {{ adjective }} {{ nouns }}",
  "the {{ nouns }} could be said to resemble {{ adjective }} {{ nouns }}",
  "{{ an_adjective }} {{ noun }} without {{ nouns }} is truly a {{ noun }} of {{ adjective }} {{ nouns }}",
];

export function randomSentence() {
  const t =
    sentenceTemplates[
      Math.round(Math.random() * (sentenceTemplates.length - 1))
    ];
  return Sentencer.make(t);
}


================================================
FILE: examples/wrap-all.ts
================================================
import { consola } from "./utils";

function foo() {
  console.info("console foo");
  process.stderr.write("called from stderr\n");
}

consola.wrapAll();
foo();
consola.restoreAll();
foo();


================================================
FILE: examples/wrap-console.ts
================================================
import { consola } from "./utils";

function foo() {
  console.info("foo");
  console.warn("foo warn");
}

function _trace() {
  console.trace("foobar");
}
function trace() {
  _trace();
}

foo();
consola.wrapConsole();
foo();
trace();
consola.restoreConsole();
foo();
trace();


================================================
FILE: examples/wrap-std.ts
================================================
import { consola } from "./utils";

function foo() {
  console.info("console foo");
  process.stdout.write("called from stdout foo\n");
  process.stderr.write("called from stderr foo\n");
}

consola.wrapStd();
foo();
consola.restoreStd();
foo();


================================================
FILE: lib/index.cjs
================================================
// eslint-disable-next-line @typescript-eslint/no-require-imports
const lib = require("../dist/index.cjs");

module.exports = lib.consola;

for (const key in lib) {
  if (!(key in module.exports)) {
    module.exports[key] = lib[key];
  }
}


================================================
FILE: package.json
================================================
{
  "name": "consola",
  "version": "3.4.2",
  "description": "Elegant Console Wrapper",
  "keywords": [
    "console",
    "logger",
    "reporter",
    "elegant",
    "cli",
    "universal",
    "unified",
    "prompt",
    "clack",
    "format",
    "error",
    "stacktrace"
  ],
  "repository": "unjs/consola",
  "license": "MIT",
  "type": "module",
  "exports": {
    ".": {
      "node": {
        "import": {
          "types": "./dist/index.d.mts",
          "default": "./dist/index.mjs"
        },
        "require": {
          "types": "./dist/index.d.cts",
          "default": "./lib/index.cjs"
        }
      },
      "default": {
        "import": {
          "types": "./dist/browser.d.mts",
          "default": "./dist/browser.mjs"
        },
        "require": {
          "types": "./dist/browser.d.cts",
          "default": "./dist/browser.cjs"
        }
      }
    },
    "./browser": {
      "import": {
        "types": "./dist/browser.d.mts",
        "default": "./dist/browser.mjs"
      },
      "require": {
        "types": "./dist/browser.d.cts",
        "default": "./dist/browser.cjs"
      }
    },
    "./basic": {
      "node": {
        "import": {
          "types": "./dist/basic.d.mts",
          "default": "./dist/basic.mjs"
        },
        "require": {
          "types": "./dist/basic.d.cts",
          "default": "./dist/basic.cjs"
        }
      },
      "default": {
        "import": {
          "types": "./dist/browser.d.mts",
          "default": "./dist/browser.mjs"
        },
        "require": {
          "types": "./dist/browser.d.cts",
          "default": "./dist/browser.cjs"
        }
      }
    },
    "./core": {
      "import": {
        "types": "./dist/core.d.mts",
        "default": "./dist/core.mjs"
      },
      "require": {
        "types": "./dist/core.d.cts",
        "default": "./dist/core.cjs"
      }
    },
    "./utils": {
      "import": {
        "types": "./dist/utils.d.mts",
        "default": "./dist/utils.mjs"
      },
      "require": {
        "types": "./dist/utils.d.cts",
        "default": "./dist/utils.cjs"
      }
    }
  },
  "main": "./lib/index.cjs",
  "module": "./dist/index.mjs",
  "browser": "./dist/browser.mjs",
  "types": "./dist/index.d.ts",
  "files": [
    "dist",
    "lib",
    "*.d.ts"
  ],
  "scripts": {
    "build": "unbuild",
    "dev": "vitest",
    "lint": "eslint . && prettier -c src examples test",
    "lint:fix": "eslint . --fix && prettier -w src examples test",
    "release": "pnpm test && pnpm build && changelogen --release --push && npm publish",
    "test": "pnpm lint && pnpm vitest run --coverage"
  },
  "devDependencies": {
    "@clack/prompts": "^0.10.0",
    "@types/node": "^22.13.10",
    "@vitest/coverage-v8": "^3.0.9",
    "changelogen": "^0.6.1",
    "defu": "^6.1.4",
    "eslint": "^9.22.0",
    "eslint-config-unjs": "^0.4.2",
    "is-unicode-supported": "^2.1.0",
    "prettier": "^3.5.3",
    "sentencer": "^0.2.1",
    "std-env": "^3.8.1",
    "string-width": "^7.2.0",
    "typescript": "^5.8.2",
    "unbuild": "^3.5.0",
    "vitest": "^3.0.9"
  },
  "engines": {
    "node": "^14.18.0 || >=16.10.0"
  },
  "packageManager": "pnpm@10.6.3"
}


================================================
FILE: renovate.json
================================================
{
  "extends": ["github>unjs/renovate-config"]
}


================================================
FILE: src/basic.ts
================================================
import { LogLevels, LogLevel } from "./constants";
import type { ConsolaOptions } from "./types";
import { BasicReporter } from "./reporters/basic";
import { ConsolaInstance, createConsola as _createConsola } from "./consola";

export * from "./shared";

/**
 * Factory function to create a new Consola instance
 *
 * @param {Partial<ConsolaOptions & { fancy: boolean }>} [options={}] - Optional configuration options. See {@link ConsolaOptions}.
 * @returns {ConsolaInstance} A new Consola instance configured with the given options.
 */
export function createConsola(
  options: Partial<ConsolaOptions & { fancy: boolean }> = {},
): ConsolaInstance {
  // Log level
  let level: LogLevel = LogLevels.info;
  if (process.env.CONSOLA_LEVEL) {
    level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
  }

  // Create new consola instance
  const consola = _createConsola({
    level,
    defaults: { level },
    stdout: process.stdout,
    stderr: process.stderr,
    reporters: options.reporters || [new BasicReporter()],
    ...options,
  });

  return consola;
}

/**
 * Creates and exports a standard instance of Consola with the default configuration.
 * This instance can be used directly for logging throughout the application.
 *
 * @type {ConsolaInstance} consola - The default instance of Consola.
 */
export const consola = createConsola();

export default consola;


================================================
FILE: src/browser.ts
================================================
import { BrowserReporter } from "./reporters/browser";
import { createConsola as _createConsola } from "./consola";
import type { ConsolaOptions } from "./types";

export * from "./shared";

/**
 * Creates a new Consola instance configured specifically for browser environments.
 * This function sets up default reporters and a prompt method tailored to the browser's dialogue APIs.
 *
 * @param {Partial<ConsolaOptions>} [options={}] - Optional configuration options.
 * The options can override the default reporter and prompt behaviour. See {@link ConsolaOptions}.
 * @returns {ConsolaInstance} A new Consola instance optimised for use in browser environments.
 */
export function createConsola(options: Partial<ConsolaOptions> = {}) {
  const consola = _createConsola({
    reporters: options.reporters || [new BrowserReporter({})],
    prompt(message, options = {}) {
      if (options.type === "confirm") {
        return Promise.resolve(confirm(message) as any);
      }
      return Promise.resolve(prompt(message));
    },
    ...options,
  });
  return consola;
}

/**
 * A standard Consola instance created with browser-specific configurations.
 * This instance can be used throughout a browser-based project.
 *
 * @type {ConsolaInstance} consola - The default browser-configured Consola instance.
 */
export const consola = createConsola();

export default consola;


================================================
FILE: src/consola.ts
================================================
import { defu } from "defu";
import { LogTypes, LogType, LogLevel } from "./constants";
import { isLogObj } from "./utils/log";
import type {
  ConsolaReporter,
  InputLogObject,
  LogObject,
  ConsolaOptions,
} from "./types";
import type { PromptOptions } from "./prompt";

let paused = false;
const queue: any[] = [];

/**
 * Consola class for logging management with support for pause/resume, mocking and customisable reporting.
 * Provides flexible logging capabilities including level-based logging, custom reporters and integration options.
 *
 * @class Consola
 */
export class Consola {
  options: ConsolaOptions;

  _lastLog: {
    serialized?: string;
    object?: LogObject;
    count?: number;
    time?: Date;
    timeout?: ReturnType<typeof setTimeout>;
  };

  _mockFn?: ConsolaOptions["mockFn"];

  /**
   * Creates an instance of Consola with specified options or defaults.
   *
   * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
   */
  constructor(options: Partial<ConsolaOptions> = {}) {
    // Options
    const types = options.types || LogTypes;
    this.options = defu(
      <ConsolaOptions>{
        ...options,
        defaults: { ...options.defaults },
        level: _normalizeLogLevel(options.level, types),
        reporters: [...(options.reporters || [])],
      },
      <Partial<ConsolaOptions>>{
        types: LogTypes,
        throttle: 1000,
        throttleMin: 5,
        formatOptions: {
          date: true,
          colors: false,
          compact: true,
        },
      },
    );

    // Create logger functions for current instance
    for (const type in types) {
      const defaults: InputLogObject = {
        type: type as LogType,
        ...this.options.defaults,
        ...types[type as LogType],
      };
      // @ts-expect-error
      (this as unknown as ConsolaInstance)[type as LogType] =
        this._wrapLogFn(defaults);
      // @ts-expect-error
      (this as unknown as ConsolaInstance)[type].raw = this._wrapLogFn(
        defaults,
        true,
      );
    }

    // Use _mockFn if is set
    if (this.options.mockFn) {
      this.mockTypes();
    }

    // Track of last log
    this._lastLog = {};
  }

  /**
   * Gets the current log level of the Consola instance.
   *
   * @returns {number} The current log level.
   */
  get level() {
    return this.options.level;
  }

  /**
   * Sets the minimum log level that will be output by the instance.
   *
   * @param {number} level - The new log level to set.
   */
  set level(level) {
    this.options.level = _normalizeLogLevel(
      level,
      this.options.types,
      this.options.level,
    );
  }

  /**
   * Displays a prompt to the user and returns the response.
   * Throw an error if `prompt` is not supported by the current configuration.
   *
   * @template T
   * @param {string} message - The message to display in the prompt.
   * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
   * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
   */
  prompt<T extends PromptOptions>(message: string, opts?: T) {
    if (!this.options.prompt) {
      throw new Error("prompt is not supported!");
    }
    return this.options.prompt<any, any, T>(message, opts);
  }

  /**
   * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
   *
   * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  create(options: Partial<ConsolaOptions>): ConsolaInstance {
    const instance = new Consola({
      ...this.options,
      ...options,
    }) as ConsolaInstance;

    if (this._mockFn) {
      instance.mockTypes(this._mockFn);
    }

    return instance;
  }

  /**
   * Creates a new Consola instance with the specified default log object properties.
   *
   * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  withDefaults(defaults: InputLogObject): ConsolaInstance {
    return this.create({
      ...this.options,
      defaults: {
        ...this.options.defaults,
        ...defaults,
      },
    });
  }

  /**
   * Creates a new Consola instance with a specified tag, which will be included in every log.
   *
   * @param {string} tag - The tag to include in each log of the new instance.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  withTag(tag: string): ConsolaInstance {
    return this.withDefaults({
      tag: this.options.defaults.tag
        ? this.options.defaults.tag + ":" + tag
        : tag,
    });
  }

  /**
   * Adds a custom reporter to the Consola instance.
   * Reporters will be called for each log message, depending on their implementation and log level.
   *
   * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  addReporter(reporter: ConsolaReporter) {
    this.options.reporters.push(reporter);
    return this;
  }

  /**
   * Removes a custom reporter from the Consola instance.
   * If no reporter is specified, all reporters will be removed.
   *
   * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  removeReporter(reporter: ConsolaReporter) {
    if (reporter) {
      const i = this.options.reporters.indexOf(reporter);
      if (i !== -1) {
        return this.options.reporters.splice(i, 1);
      }
    } else {
      this.options.reporters.splice(0);
    }
    return this;
  }

  /**
   * Replaces all reporters of the Consola instance with the specified array of reporters.
   *
   * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  setReporters(reporters: ConsolaReporter[]) {
    this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
    return this;
  }

  wrapAll() {
    this.wrapConsole();
    this.wrapStd();
  }

  restoreAll() {
    this.restoreConsole();
    this.restoreStd();
  }

  /**
   * Overrides console methods with Consola logging methods for consistent logging.
   */
  wrapConsole() {
    for (const type in this.options.types) {
      // Backup original value
      if (!(console as any)["__" + type]) {
        (console as any)["__" + type] = (console as any)[type];
      }
      // Override
      (console as any)[type] = (this as unknown as ConsolaInstance)[
        type as LogType
      ].raw;
    }
  }

  /**
   * Restores the original console methods, removing Consola overrides.
   */
  restoreConsole() {
    for (const type in this.options.types) {
      // Restore if backup is available
      if ((console as any)["__" + type]) {
        (console as any)[type] = (console as any)["__" + type];
        delete (console as any)["__" + type];
      }
    }
  }

  /**
   * Overrides standard output and error streams to redirect them through Consola.
   */
  wrapStd() {
    this._wrapStream(this.options.stdout, "log");
    this._wrapStream(this.options.stderr, "log");
  }

  _wrapStream(stream: NodeJS.WriteStream | undefined, type: LogType) {
    if (!stream) {
      return;
    }

    // Backup original value
    if (!(stream as any).__write) {
      (stream as any).__write = stream.write;
    }

    // Override
    (stream as any).write = (data: any) => {
      (this as unknown as ConsolaInstance)[type].raw(String(data).trim());
    };
  }

  /**
   * Restores the original standard output and error streams, removing the Consola redirection.
   */
  restoreStd() {
    this._restoreStream(this.options.stdout);
    this._restoreStream(this.options.stderr);
  }

  _restoreStream(stream?: NodeJS.WriteStream) {
    if (!stream) {
      return;
    }

    if ((stream as any).__write) {
      stream.write = (stream as any).__write;
      delete (stream as any).__write;
    }
  }

  /**
   * Pauses logging, queues incoming logs until resumed.
   */
  pauseLogs() {
    paused = true;
  }

  /**
   * Resumes logging, processing any queued logs.
   */
  resumeLogs() {
    paused = false;

    // Process queue
    const _queue = queue.splice(0);
    for (const item of _queue) {
      item[0]._logFn(item[1], item[2]);
    }
  }

  /**
   * Replaces logging methods with mocks if a mock function is provided.
   *
   * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
   */
  mockTypes(mockFn?: ConsolaOptions["mockFn"]) {
    const _mockFn = mockFn || this.options.mockFn;

    this._mockFn = _mockFn;

    if (typeof _mockFn !== "function") {
      return;
    }

    for (const type in this.options.types) {
      // @ts-expect-error
      (this as unknown as ConsolaInstance)[type as LogType] =
        _mockFn(type as LogType, this.options.types[type as LogType]) ||
        (this as unknown as ConsolaInstance)[type as LogType];
      (this as unknown as ConsolaInstance)[type as LogType].raw = (
        this as unknown as ConsolaInstance
      )[type as LogType];
    }
  }

  _wrapLogFn(defaults: InputLogObject, isRaw?: boolean) {
    return (...args: any[]) => {
      if (paused) {
        queue.push([this, defaults, args, isRaw]);
        return;
      }
      return this._logFn(defaults, args, isRaw);
    };
  }

  _logFn(defaults: InputLogObject, args: any[], isRaw?: boolean) {
    if (((defaults.level as number) || 0) > this.level) {
      return false;
    }

    // Construct a new log object
    const logObj: Partial<LogObject> = {
      date: new Date(),
      args: [],
      ...defaults,
      level: _normalizeLogLevel(defaults.level, this.options.types),
    };

    // Consume arguments
    if (!isRaw && args.length === 1 && isLogObj(args[0])) {
      Object.assign(logObj, args[0]);
    } else {
      logObj.args = [...args];
    }

    // Aliases
    if (logObj.message) {
      logObj.args!.unshift(logObj.message);
      delete logObj.message;
    }
    if (logObj.additional) {
      if (!Array.isArray(logObj.additional)) {
        logObj.additional = logObj.additional.split("\n");
      }

      logObj.args!.push("\n" + logObj.additional.join("\n"));
      delete logObj.additional;
    }

    // Normalize type to lowercase
    logObj.type = (
      typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log"
    ) as LogType;
    logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";

    // Resolve log
    /**
     * @param newLog false if the throttle expired and
     *  we don't want to log a duplicate
     */
    const resolveLog = (newLog = false) => {
      const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
      if (this._lastLog.object && repeated > 0) {
        const args = [...this._lastLog.object.args];
        if (repeated > 1) {
          args.push(`(repeated ${repeated} times)`);
        }
        this._log({ ...this._lastLog.object, args });
        this._lastLog.count = 1;
      }

      // Log
      if (newLog) {
        this._lastLog.object = logObj as LogObject;
        this._log(logObj as LogObject);
      }
    };

    // Throttle
    clearTimeout(this._lastLog.timeout);
    const diffTime =
      this._lastLog.time && logObj.date
        ? logObj.date.getTime() - this._lastLog.time.getTime()
        : 0;
    this._lastLog.time = logObj.date;
    if (diffTime < this.options.throttle) {
      try {
        const serializedLog = JSON.stringify([
          logObj.type,
          logObj.tag,
          logObj.args,
        ]);
        const isSameLog = this._lastLog.serialized === serializedLog;
        this._lastLog.serialized = serializedLog;
        if (isSameLog) {
          this._lastLog.count = (this._lastLog.count || 0) + 1;
          if (this._lastLog.count > this.options.throttleMin) {
            // Auto-resolve when throttle is timed out
            this._lastLog.timeout = setTimeout(
              resolveLog,
              this.options.throttle,
            );
            return; // SPAM!
          }
        }
      } catch {
        // Circular References
      }
    }

    resolveLog(true);
  }

  _log(logObj: LogObject) {
    for (const reporter of this.options.reporters) {
      reporter.log(logObj, {
        options: this.options,
      });
    }
  }
}

function _normalizeLogLevel(
  input: LogLevel | LogType | undefined,
  types: any = {},
  defaultLevel = 3,
) {
  if (input === undefined) {
    return defaultLevel;
  }
  if (typeof input === "number") {
    return input;
  }
  if (types[input] && types[input].level !== undefined) {
    return types[input].level;
  }
  return defaultLevel;
}

export interface LogFn {
  (message: InputLogObject | any, ...args: any[]): void;
  raw: (...args: any[]) => void;
}
export type ConsolaInstance = Consola & Record<LogType, LogFn>;

// Legacy support
// @ts-expect-error
Consola.prototype.add = Consola.prototype.addReporter;
// @ts-expect-error
Consola.prototype.remove = Consola.prototype.removeReporter;
// @ts-expect-error
Consola.prototype.clear = Consola.prototype.removeReporter;
// @ts-expect-error
Consola.prototype.withScope = Consola.prototype.withTag;
// @ts-expect-error
Consola.prototype.mock = Consola.prototype.mockTypes;
// @ts-expect-error
Consola.prototype.pause = Consola.prototype.pauseLogs;
// @ts-expect-error
Consola.prototype.resume = Consola.prototype.resumeLogs;

/**
 * Utility for creating a new Consola instance with optional configuration.
 *
 * @param {Partial<ConsolaOptions>} [options={}] - Optional configuration options for the new Consola instance. See {@link ConsolaOptions}.
 * @returns {ConsolaInstance} A new instance of Consola. See {@link ConsolaInstance}.
 */
export function createConsola(
  options: Partial<ConsolaOptions> = {},
): ConsolaInstance {
  return new Consola(options) as ConsolaInstance;
}


================================================
FILE: src/constants.ts
================================================
import { LogObject } from "./types";

/**
 * Defines the level of logs as specific numbers or special number types.
 *
 * @type {0 | 1 | 2 | 3 | 4 | 5 | (number & {})} LogLevel - Represents the log level.
 * @default 0 - Represents the default log level.
 */
export type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | (number & {});

/**
 * A mapping of `LogType` to its corresponding numeric log level.
 *
 * @type {Record<LogType, number>} LogLevels - key-value pairs of log types to their numeric levels. See {@link LogType}.
 */
export const LogLevels: Record<LogType, number> = {
  silent: Number.NEGATIVE_INFINITY,

  fatal: 0,
  error: 0,

  warn: 1,

  log: 2,
  info: 3,

  success: 3,
  fail: 3,
  ready: 3,
  start: 3,
  box: 3,

  debug: 4,

  trace: 5,

  verbose: Number.POSITIVE_INFINITY,
};

/**
 * Lists the types of log messages supported by the system.
 *
 * @type {"silent" | "fatal" | "error" | "warn" | "log" | "info" | "success" | "fail" | "ready" | "start" | "box" | "debug" | "trace" | "verbose"} LogType - Represents the specific type of log message.
 */
export type LogType =
  // 0
  | "silent"
  | "fatal"
  | "error"
  // 1
  | "warn"
  // 2
  | "log"
  // 3
  | "info"
  | "success"
  | "fail"
  | "ready"
  | "start"
  | "box"
  // Verbose
  | "debug"
  | "trace"
  | "verbose";

/**
 * Maps `LogType` to a `Partial<LogObject>`, primarily defining the log level.
 *
 * @type {Record<LogType, Partial<LogObject>>} LogTypes - key-value pairs of log types to partial log objects, specifying log levels. See {@link LogType} and {@link LogObject}.
 */
export const LogTypes: Record<LogType, Partial<LogObject>> = {
  // Silent
  silent: {
    level: -1,
  },

  // Level 0
  fatal: {
    level: LogLevels.fatal,
  },
  error: {
    level: LogLevels.error,
  },

  // Level 1
  warn: {
    level: LogLevels.warn,
  },

  // Level 2
  log: {
    level: LogLevels.log,
  },

  // Level 3
  info: {
    level: LogLevels.info,
  },
  success: {
    level: LogLevels.success,
  },
  fail: {
    level: LogLevels.fail,
  },
  ready: {
    level: LogLevels.info,
  },
  start: {
    level: LogLevels.info,
  },
  box: {
    level: LogLevels.info,
  },

  // Level 4
  debug: {
    level: LogLevels.debug,
  },

  // Level 5
  trace: {
    level: LogLevels.trace,
  },

  // Verbose
  verbose: {
    level: LogLevels.verbose,
  },
};


================================================
FILE: src/core.ts
================================================
export { createConsola } from "./consola";
export * from "./shared";


================================================
FILE: src/index.ts
================================================
import { isDebug, isTest, isCI } from "std-env";
import { LogLevels, LogLevel } from "./constants";
import type { ConsolaOptions } from "./types";
import { BasicReporter } from "./reporters/basic";
import { FancyReporter } from "./reporters/fancy";
import { ConsolaInstance, createConsola as _createConsola } from "./consola";

export * from "./shared";

/**
 * Factory function to create a new Consola instance tailored for use in different environments.
 * It automatically adjusts logging levels based on environment variables and execution context.
 *
 * @param {Partial<ConsolaOptions & { fancy: boolean }>} [options={}] - Optional configuration options. See {@link ConsolaOptions}.
 * @returns {ConsolaInstance} A new Consola instance with configurations based on the given options and the execution environment.
 */
export function createConsola(
  options: Partial<ConsolaOptions & { fancy: boolean }> = {},
): ConsolaInstance {
  // Log level
  let level = _getDefaultLogLevel();
  if (process.env.CONSOLA_LEVEL) {
    level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
  }

  // Create new consola instance
  const consola = _createConsola({
    level: level as LogLevel,
    defaults: { level },
    stdout: process.stdout,
    stderr: process.stderr,
    prompt: (...args) => import("./prompt").then((m) => m.prompt(...args)),
    reporters: options.reporters || [
      (options.fancy ?? !(isCI || isTest))
        ? new FancyReporter()
        : new BasicReporter(),
    ],
    ...options,
  });

  return consola;
}

function _getDefaultLogLevel() {
  if (isDebug) {
    return LogLevels.debug;
  }
  if (isTest) {
    return LogLevels.warn;
  }
  return LogLevels.info;
}

/**
 * A default instance of Consola, created and configured for immediate use.
 * This instance is configured based on the execution environment and the options provided.
 *
 * @type {ConsolaInstance} consola - The default Consola instance, ready to use.
 */
export const consola = createConsola();

export default consola;


================================================
FILE: src/prompt.ts
================================================
import { text, confirm, select, multiselect } from "@clack/prompts";

type SelectOption = {
  label: string;
  value: string;
  hint?: string;
};

export const kCancel = Symbol.for("cancel");

export type PromptCommonOptions = {
  /**
   * Specify how to handle a cancelled prompt (e.g. by pressing Ctrl+C).
   *
   * Default strategy is `"default"`.
   *
   * - `"default"` - Resolve the promise with the `default` value or `initial` value.
   * - `"undefined`" - Resolve the promise with `undefined`.
   * - `"null"` - Resolve the promise with `null`.
   * - `"symbol"` - Resolve the promise with a symbol `Symbol.for("cancel")`.
   * - `"reject"`  - Reject the promise with an error.
   */
  cancel?: "reject" | "default" | "undefined" | "null" | "symbol";
};

export type TextPromptOptions = PromptCommonOptions & {
  /**
   * Specifies the prompt type as text.
   * @optional
   * @default "text"
   */
  type?: "text";

  /**
   * The default text value.
   * @optional
   */
  default?: string;

  /**
   * A placeholder text displayed in the prompt.
   * @optional
   */
  placeholder?: string;

  /**
   * The initial text value.
   * @optional
   */
  initial?: string;
};

export type ConfirmPromptOptions = PromptCommonOptions & {
  /**
   * Specifies the prompt type as confirm.
   */
  type: "confirm";

  /**
   * The initial value for the confirm prompt.
   * @optional
   */
  initial?: boolean;
};

export type SelectPromptOptions = PromptCommonOptions & {
  /**
   * Specifies the prompt type as select.
   */
  type: "select";

  /**
   * The initial value for the select prompt.
   * @optional
   */
  initial?: string;

  /**
   * The options to select from. See {@link SelectOption}.
   */
  options: (string | SelectOption)[];
};

export type MultiSelectOptions = PromptCommonOptions & {
  /**
   * Specifies the prompt type as multiselect.
   */
  type: "multiselect";

  /**
   * The options to select from. See {@link SelectOption}.
   */
  initial?: string[];

  /**
   * The options to select from. See {@link SelectOption}.
   */
  options: (string | SelectOption)[];

  /**
   * Whether the prompt requires at least one selection.
   */
  required?: boolean;
};

/**
 * Defines a combined type for all prompt options.
 */
export type PromptOptions =
  | TextPromptOptions
  | ConfirmPromptOptions
  | SelectPromptOptions
  | MultiSelectOptions;

type inferPromptReturnType<T extends PromptOptions> =
  T extends TextPromptOptions
    ? string
    : T extends ConfirmPromptOptions
      ? boolean
      : T extends SelectPromptOptions
        ? T["options"][number] extends SelectOption
          ? T["options"][number]["value"]
          : T["options"][number]
        : T extends MultiSelectOptions
          ? T["options"]
          : unknown;

type inferPromptCancalReturnType<T extends PromptOptions> = T extends {
  cancel: "reject";
}
  ? never
  : T extends { cancel: "default" }
    ? inferPromptReturnType<T>
    : T extends { cancel: "undefined" }
      ? undefined
      : T extends { cancel: "null" }
        ? null
        : T extends { cancel: "symbol" }
          ? typeof kCancel
          : inferPromptReturnType<T> /* default */;

/**
 * Asynchronously prompts the user for input based on specified options.
 * Supports text, confirm, select and multi-select prompts.
 *
 * @param {string} message - The message to display in the prompt.
 * @param {PromptOptions} [opts={}] - The prompt options. See {@link PromptOptions}.
 * @returns {Promise<inferPromptReturnType<T>>} - A promise that resolves with the user's response, the type of which is inferred from the options. See {@link inferPromptReturnType}.
 */
export async function prompt<
  _ = any,
  __ = any,
  T extends PromptOptions = TextPromptOptions,
>(
  message: string,
  opts: PromptOptions = {},
): Promise<inferPromptReturnType<T> | inferPromptCancalReturnType<T>> {
  const handleCancel = (value: unknown) => {
    if (
      typeof value !== "symbol" ||
      value.toString() !== "Symbol(clack:cancel)"
    ) {
      return value;
    }

    switch (opts.cancel) {
      case "reject": {
        const error = new Error("Prompt cancelled.");
        error.name = "ConsolaPromptCancelledError";
        if (Error.captureStackTrace) {
          Error.captureStackTrace(error, prompt);
        }
        throw error;
      }
      case "undefined": {
        return undefined;
      }
      case "null": {
        return null;
      }
      case "symbol": {
        return kCancel;
      }
      default:
      case "default": {
        return (opts as TextPromptOptions).default ?? opts.initial;
      }
    }
  };

  if (!opts.type || opts.type === "text") {
    return (await text({
      message,
      defaultValue: opts.default,
      placeholder: opts.placeholder,
      initialValue: opts.initial as string,
    }).then(handleCancel)) as any;
  }

  if (opts.type === "confirm") {
    return (await confirm({
      message,
      initialValue: opts.initial,
    }).then(handleCancel)) as any;
  }

  if (opts.type === "select") {
    return (await select({
      message,
      options: opts.options.map((o) =>
        typeof o === "string" ? { value: o, label: o } : o,
      ),
      initialValue: opts.initial,
    }).then(handleCancel)) as any;
  }

  if (opts.type === "multiselect") {
    return (await multiselect({
      message,
      options: opts.options.map((o) =>
        typeof o === "string" ? { value: o, label: o } : o,
      ),
      required: opts.required,
      initialValues: opts.initial,
    }).then(handleCancel)) as any;
  }

  throw new Error(`Unknown prompt type: ${opts.type}`);
}


================================================
FILE: src/reporters/basic.ts
================================================
import { formatWithOptions } from "node:util";
import type {
  LogObject,
  ConsolaReporter,
  FormatOptions,
  ConsolaOptions,
} from "../types";
import { parseStack } from "../utils/error";
import { writeStream } from "../utils/stream";

const bracket = (x: string) => (x ? `[${x}]` : "");

export class BasicReporter implements ConsolaReporter {
  formatStack(stack: string, message: string, opts: FormatOptions) {
    const indent = "  ".repeat((opts?.errorLevel || 0) + 1);
    return indent + parseStack(stack, message).join(`\n${indent}`);
  }

  formatError(err: any, opts: FormatOptions): string {
    const message = err.message ?? formatWithOptions(opts, err);
    const stack = err.stack ? this.formatStack(err.stack, message, opts) : "";

    const level = opts?.errorLevel || 0;
    const causedPrefix = level > 0 ? `${"  ".repeat(level)}[cause]: ` : "";
    const causedError = err.cause
      ? "\n\n" + this.formatError(err.cause, { ...opts, errorLevel: level + 1 })
      : "";

    return causedPrefix + message + "\n" + stack + causedError;
  }

  formatArgs(args: any[], opts: FormatOptions) {
    const _args = args.map((arg) => {
      if (arg && typeof arg.stack === "string") {
        return this.formatError(arg, opts);
      }
      return arg;
    });

    // Only supported with Node >= 10
    // https://nodejs.org/api/util.html#util_util_inspect_object_options
    return formatWithOptions(opts, ..._args);
  }

  formatDate(date: Date, opts: FormatOptions) {
    return opts.date ? date.toLocaleTimeString() : "";
  }

  filterAndJoin(arr: any[]) {
    return arr.filter(Boolean).join(" ");
  }

  formatLogObj(logObj: LogObject, opts: FormatOptions) {
    const message = this.formatArgs(logObj.args, opts);

    if (logObj.type === "box") {
      return (
        "\n" +
        [
          bracket(logObj.tag),
          logObj.title && logObj.title,
          ...message.split("\n"),
        ]
          .filter(Boolean)
          .map((l) => " > " + l)
          .join("\n") +
        "\n"
      );
    }

    return this.filterAndJoin([
      bracket(logObj.type),
      bracket(logObj.tag),
      message,
    ]);
  }

  log(logObj: LogObject, ctx: { options: ConsolaOptions }) {
    const line = this.formatLogObj(logObj, {
      columns: (ctx.options.stdout as any).columns || 0,
      ...ctx.options.formatOptions,
    });

    return writeStream(
      line + "\n",
      logObj.level < 2
        ? ctx.options.stderr || process.stderr
        : ctx.options.stdout || process.stdout,
    );
  }
}


================================================
FILE: src/reporters/browser.ts
================================================
import { LogObject } from "../types";

export class BrowserReporter {
  options: any;
  defaultColor: string;
  levelColorMap: Record<number, string>;
  typeColorMap: Record<string, string>;

  constructor(options: any) {
    this.options = { ...options };

    this.defaultColor = "#7f8c8d"; // Gray
    this.levelColorMap = {
      0: "#c0392b", // Red
      1: "#f39c12", // Yellow
      3: "#00BCD4", // Cyan
    };
    this.typeColorMap = {
      success: "#2ecc71", // Green
    };
  }

  _getLogFn(level: number) {
    if (level < 1) {
      return (console as any).__error || console.error;
    }
    if (level === 1) {
      return (console as any).__warn || console.warn;
    }
    return (console as any).__log || console.log;
  }

  log(logObj: LogObject) {
    const consoleLogFn = this._getLogFn(logObj.level);

    // Type
    const type = logObj.type === "log" ? "" : logObj.type;

    // Tag
    const tag = logObj.tag || "";

    // Styles
    const color =
      this.typeColorMap[logObj.type] ||
      this.levelColorMap[logObj.level] ||
      this.defaultColor;
    const style = `
      background: ${color};
      border-radius: 0.5em;
      color: white;
      font-weight: bold;
      padding: 2px 0.5em;
    `;

    const badge = `%c${[tag, type].filter(Boolean).join(":")}`;

    // Log to the console
    if (typeof logObj.args[0] === "string") {
      consoleLogFn(
        `${badge}%c ${logObj.args[0]}`,
        style,
        // Empty string as style resets to default console style
        "",
        ...logObj.args.slice(1),
      );
    } else {
      consoleLogFn(badge, style, ...logObj.args);
    }
  }
}


================================================
FILE: src/reporters/fancy.ts
================================================
import _stringWidth from "string-width";
import isUnicodeSupported from "is-unicode-supported";
import { colors } from "../utils/color";
import { parseStack } from "../utils/error";
import { FormatOptions, LogObject } from "../types";
import { LogLevel, LogType } from "../constants";
import { BoxOpts, box } from "../utils/box";
import { stripAnsi } from "../utils";
import { BasicReporter } from "./basic";

export const TYPE_COLOR_MAP: { [k in LogType]?: string } = {
  info: "cyan",
  fail: "red",
  success: "green",
  ready: "green",
  start: "magenta",
};

export const LEVEL_COLOR_MAP: { [k in LogLevel]?: string } = {
  0: "red",
  1: "yellow",
};

const unicode = isUnicodeSupported();
const s = (c: string, fallback: string) => (unicode ? c : fallback);
const TYPE_ICONS: { [k in LogType]?: string } = {
  error: s("✖", "×"),
  fatal: s("✖", "×"),
  ready: s("✔", "√"),
  warn: s("⚠", "‼"),
  info: s("ℹ", "i"),
  success: s("✔", "√"),
  debug: s("⚙", "D"),
  trace: s("→", "→"),
  fail: s("✖", "×"),
  start: s("◐", "o"),
  log: "",
};

function stringWidth(str: string) {
  // https://github.com/unjs/consola/issues/204
  const hasICU = typeof Intl === "object";
  if (!hasICU || !Intl.Segmenter) {
    return stripAnsi(str).length;
  }
  return _stringWidth(str);
}

export class FancyReporter extends BasicReporter {
  formatStack(stack: string, message: string, opts?: FormatOptions) {
    const indent = "  ".repeat((opts?.errorLevel || 0) + 1);
    return (
      `\n${indent}` +
      parseStack(stack, message)
        .map(
          (line) =>
            "  " +
            line
              .replace(/^at +/, (m) => colors.gray(m))
              .replace(/\((.+)\)/, (_, m) => `(${colors.cyan(m)})`),
        )
        .join(`\n${indent}`)
    );
  }

  formatType(logObj: LogObject, isBadge: boolean, opts: FormatOptions) {
    const typeColor =
      (TYPE_COLOR_MAP as any)[logObj.type] ||
      (LEVEL_COLOR_MAP as any)[logObj.level] ||
      "gray";

    if (isBadge) {
      return getBgColor(typeColor)(
        colors.black(` ${logObj.type.toUpperCase()} `),
      );
    }

    const _type =
      typeof (TYPE_ICONS as any)[logObj.type] === "string"
        ? (TYPE_ICONS as any)[logObj.type]
        : (logObj as any).icon || logObj.type;

    return _type ? getColor(typeColor)(_type) : "";
  }

  formatLogObj(logObj: LogObject, opts: FormatOptions) {
    const [message, ...additional] = this.formatArgs(logObj.args, opts).split(
      "\n",
    );

    if (logObj.type === "box") {
      return box(
        characterFormat(
          message + (additional.length > 0 ? "\n" + additional.join("\n") : ""),
        ),
        {
          title: logObj.title
            ? characterFormat(logObj.title as string)
            : undefined,
          style: logObj.style as BoxOpts["style"],
        },
      );
    }

    const date = this.formatDate(logObj.date, opts);
    const coloredDate = date && colors.gray(date);

    const isBadge = (logObj.badge as boolean) ?? logObj.level < 2;
    const type = this.formatType(logObj, isBadge, opts);

    const tag = logObj.tag ? colors.gray(logObj.tag) : "";

    let line;
    const left = this.filterAndJoin([type, characterFormat(message)]);
    const right = this.filterAndJoin(opts.columns ? [tag, coloredDate] : [tag]);
    const space =
      (opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;

    line =
      space > 0 && (opts.columns || 0) >= 80
        ? left + " ".repeat(space) + right
        : (right ? `${colors.gray(`[${right}]`)} ` : "") + left;

    line += characterFormat(
      additional.length > 0 ? "\n" + additional.join("\n") : "",
    );

    if (logObj.type === "trace") {
      const _err = new Error("Trace: " + logObj.message);
      line += this.formatStack(_err.stack || "", _err.message);
    }

    return isBadge ? "\n" + line + "\n" : line;
  }
}

function characterFormat(str: string) {
  return (
    str
      // highlight backticks
      .replace(/`([^`]+)`/gm, (_, m) => colors.cyan(m))
      // underline underscores
      .replace(/\s+_([^_]+)_\s+/gm, (_, m) => ` ${colors.underline(m)} `)
  );
}

function getColor(color = "white") {
  return (colors as any)[color] || colors.white;
}

function getBgColor(color = "bgWhite") {
  return (
    (colors as any)[`bg${color[0].toUpperCase()}${color.slice(1)}`] ||
    colors.bgWhite
  );
}


================================================
FILE: src/shared.ts
================================================
export { LogLevels, LogTypes } from "./constants";
export { Consola } from "./consola";

export type * from "./types";
export type { ConsolaInstance } from "./consola";
export type { LogLevel, LogType } from "./constants";
export type {
  PromptOptions,
  ConfirmPromptOptions,
  MultiSelectOptions,
  SelectPromptOptions,
  TextPromptOptions,
} from "./prompt";


================================================
FILE: src/types.ts
================================================
import type { LogLevel, LogType } from "./constants";

export interface ConsolaOptions {
  /**
   * An array of ConsolaReporter instances used to handle and output log messages.
   */
  reporters: ConsolaReporter[];

  /**
   * A record mapping LogType to InputLogObject, defining the log configuration for each log type.
   * See {@link LogType} and {@link InputLogObject}.
   */
  types: Record<LogType, InputLogObject>;

  /**
   * The minimum log level to output. See {@link LogLevel}.
   */
  level: LogLevel;

  /**
   * Default properties applied to all log messages unless overridden. See {@link InputLogObject}.
   */
  defaults: InputLogObject;

  /**
   * The maximum number of times a log message can be repeated within a given timeframe.
   */
  throttle: number;

  /**
   * The minimum time in milliseconds that must elapse before a throttled log message can be logged again.
   */
  throttleMin: number;

  /**
   * The Node.js writable stream for standard output. See {@link NodeJS.WriteStream}.
   * @optional
   */
  stdout?: NodeJS.WriteStream;

  /**
   * The Node.js writeable stream for standard error output. See {@link NodeJS.WriteStream}.
   * @optional
   */
  stderr?: NodeJS.WriteStream;

  /**
   * A function that allows you to mock log messages for testing purposes.
   * @optional
   */
  mockFn?: (type: LogType, defaults: InputLogObject) => (...args: any) => void;

  /**
   * Custom prompt function to use. It can be undefined.
   * @optional
   */
  prompt?: typeof import("./prompt").prompt | undefined;

  /**
   * Configuration options for formatting log messages. See {@link FormatOptions}.
   */
  formatOptions: FormatOptions;
}

/**
 * @see https://nodejs.org/api/util.html#util_util_inspect_object_showhidden_depth_colors
 */
export interface FormatOptions {
  /**
   * The maximum number of columns to output, affects formatting.
   * @optional
   */
  columns?: number;

  /**
   * Whether to include timestamp information in log messages.
   * @optional
   */
  date?: boolean;

  /**
   * Whether to use colors in the output.
   * @optional
   */
  colors?: boolean;

  /**
   * Specifies whether or not the output should be compact. Accepts a boolean or numeric level of compactness.
   * @optional
   */
  compact?: boolean | number;

  /**
   * Error cause level.
   */
  errorLevel?: number;

  /**
   * Allows additional custom formatting options.
   */
  [key: string]: unknown;
}

export interface InputLogObject {
  /**
   * The logging level of the message. See {@link LogLevel}.
   * @optional
   */
  level?: LogLevel;

  /**
   * A string tag to categorise or identify the log message.
   * @optional
   */
  tag?: string;

  /**
   * The type of log message, which affects how it's processed and displayed. See {@link LogType}.
   * @optional
   */
  type?: LogType;

  /**
   * The main log message text.
   * @optional
   */
  message?: string;

  /**
   * Additional text or texts to be logged with the message.
   * @optional
   */
  additional?: string | string[];

  /**
   * Additional arguments to be logged with the message.
   * @optional
   */
  args?: any[];

  /**
   * The date and time when the log message was created.
   * @optional
   */
  date?: Date;
}

export interface LogObject extends InputLogObject {
  /**
   * The logging level of the message, overridden if required. See {@link LogLevel}.
   */
  level: LogLevel;

  /**
   * The type of log message, overridden if required. See {@link LogType}.
   */
  type: LogType;

  /**
   * A string tag to categorise or identify the log message, overridden if necessary.
   */
  tag: string;

  /**
   * Additional arguments to be logged with the message, overridden if necessary.
   */
  args: any[];

  /**
   * The date and time the log message was created, overridden if necessary.
   */
  date: Date;

  /**
   * Allows additional custom properties to be set on the log object.
   */
  [key: string]: unknown;
}

export interface ConsolaReporter {
  /**
   * Defines how a log message is processed and displayed by this reporter.
   * @param logObj The LogObject containing the log information to process. See {@link LogObject}.
   * @param ctx An object containing context information such as options. See {@link ConsolaOptions}.
   */
  log: (
    logObj: LogObject,
    ctx: {
      options: ConsolaOptions;
    },
  ) => void;
}


================================================
FILE: src/utils/box.ts
================================================
import { getColor } from "./color";
import { stripAnsi } from "./string";

export type BoxBorderStyle = {
  /**
   * Top left corner
   * @example `┌`
   * @example `╔`
   * @example `╓`
   */
  tl: string;
  /**
   * Top right corner
   * @example `┐`
   * @example `╗`
   * @example `╖`
   */
  tr: string;
  /**
   * Bottom left corner
   * @example `└`
   * @example `╚`
   * @example `╙`
   */
  bl: string;
  /**
   * Bottom right corner
   * @example `┘`
   * @example `╝`
   * @example `╜`
   */
  br: string;
  /**
   * Horizontal line
   * @example `─`
   * @example `═`
   * @example `─`
   */
  h: string;
  /**
   * Vertical line
   * @example `│`
   * @example `║`
   * @example `║`
   */
  v: string;
};

const boxStylePresets: Record<string, BoxBorderStyle> = {
  solid: {
    tl: "┌",
    tr: "┐",
    bl: "└",
    br: "┘",
    h: "─",
    v: "│",
  },
  double: {
    tl: "╔",
    tr: "╗",
    bl: "╚",
    br: "╝",
    h: "═",
    v: "║",
  },
  doubleSingle: {
    tl: "╓",
    tr: "╖",
    bl: "╙",
    br: "╜",
    h: "─",
    v: "║",
  },
  doubleSingleRounded: {
    tl: "╭",
    tr: "╮",
    bl: "╰",
    br: "╯",
    h: "─",
    v: "║",
  },
  singleThick: {
    tl: "┏",
    tr: "┓",
    bl: "┗",
    br: "┛",
    h: "━",
    v: "┃",
  },
  singleDouble: {
    tl: "╒",
    tr: "╕",
    bl: "╘",
    br: "╛",
    h: "═",
    v: "│",
  },
  singleDoubleRounded: {
    tl: "╭",
    tr: "╮",
    bl: "╰",
    br: "╯",
    h: "═",
    v: "│",
  },
  rounded: {
    tl: "╭",
    tr: "╮",
    bl: "╰",
    br: "╯",
    h: "─",
    v: "│",
  },
};

export type BoxStyle = {
  /**
   * The border color
   * @default 'white'
   */
  borderColor:
    | "black"
    | "red"
    | "green"
    | "yellow"
    | "blue"
    | "magenta"
    | "cyan"
    | "white"
    | "gray"
    | "blackBright"
    | "redBright"
    | "greenBright"
    | "yellowBright"
    | "blueBright"
    | "magentaBright"
    | "cyanBright"
    | "whiteBright";

  /**
   * The border style
   * @default 'solid'
   * @example 'single-double-rounded'
   * @example
   * ```ts
   * {
   *   tl: '┌',
   *   tr: '┐',
   *   bl: '└',
   *   br: '┘',
   *   h: '─',
   *   v: '│',
   * }
   * ```
   */
  borderStyle: BoxBorderStyle | keyof typeof boxStylePresets;

  /**
   * The vertical alignment of the text
   * @default 'center'
   */
  valign: "top" | "center" | "bottom";

  /**
   * The padding of the box
   * @default 2
   */
  padding: number;

  /**
   * The left margin of the box
   * @default 1
   */
  marginLeft: number;

  /**
   * The top margin of the box
   * @default 1
   */
  marginTop: number;

  /**
   * The top margin of the box
   * @default 1
   */
  marginBottom: number;
};

/**
 * The border options of the box
 */
export type BoxOpts = {
  /**
   * Title that will be displayed on top of the box
   * @example 'Hello World'
   * @example 'Hello {name}'
   */
  title?: string;

  style?: Partial<BoxStyle>;
};

/**
 * The default style applied to a box if no custom style is specified. See {@link BoxStyle}.
 */
const defaultStyle: BoxStyle = {
  borderColor: "white",
  borderStyle: "rounded",
  valign: "center",
  padding: 2,
  marginLeft: 1,
  marginTop: 1,
  marginBottom: 1,
};

/**
 * Creates a styled box with text content, customisable via options.
 * @param {string} text - The text to display in the box.
 * @param {BoxOpts} [_opts={}] - Optional settings for the appearance and behaviour of the box. See {@link BoxOpts}.
 * @returns {string} The formatted box as a string, ready for printing or logging.
 */
export function box(text: string, _opts: BoxOpts = {}) {
  const opts = {
    ..._opts,
    style: {
      ...defaultStyle,
      ..._opts.style,
    },
  };

  // Split the text into lines
  const textLines = text.split("\n");

  // Create the box
  const boxLines = [];

  // Get the characters for the box and colorize
  const _color = getColor(opts.style.borderColor);
  const borderStyle = {
    ...(typeof opts.style.borderStyle === "string"
      ? boxStylePresets[
          opts.style.borderStyle as keyof typeof boxStylePresets
        ] || boxStylePresets.solid
      : opts.style.borderStyle),
  };
  if (_color) {
    for (const key in borderStyle) {
      borderStyle[key as keyof typeof borderStyle] = _color(
        borderStyle[key as keyof typeof borderStyle],
      );
    }
  }

  // Calculate the width and height of the box
  const paddingOffset =
    opts.style.padding % 2 === 0 ? opts.style.padding : opts.style.padding + 1;
  const height = textLines.length + paddingOffset;
  const width =
    Math.max(
      ...textLines.map((line) => stripAnsi(line).length),
      opts.title ? stripAnsi(opts.title).length : 0,
    ) + paddingOffset;
  const widthOffset = width + paddingOffset;

  const leftSpace =
    opts.style.marginLeft > 0 ? " ".repeat(opts.style.marginLeft) : "";

  // Top line
  if (opts.style.marginTop > 0) {
    boxLines.push("".repeat(opts.style.marginTop));
  }
  // Include the title if it exists with borders
  if (opts.title) {
    const title = _color ? _color(opts.title) : opts.title;
    const left = borderStyle.h.repeat(
      Math.floor((width - stripAnsi(opts.title).length) / 2),
    );
    const right = borderStyle.h.repeat(
      width -
        stripAnsi(opts.title).length -
        stripAnsi(left).length +
        paddingOffset,
    );
    boxLines.push(
      `${leftSpace}${borderStyle.tl}${left}${title}${right}${borderStyle.tr}`,
    );
  } else {
    boxLines.push(
      `${leftSpace}${borderStyle.tl}${borderStyle.h.repeat(widthOffset)}${
        borderStyle.tr
      }`,
    );
  }

  // Middle lines
  const valignOffset =
    opts.style.valign === "center"
      ? Math.floor((height - textLines.length) / 2)
      : opts.style.valign === "top" // eslint-disable-line unicorn/no-nested-ternary
        ? height - textLines.length - paddingOffset
        : height - textLines.length;

  for (let i = 0; i < height; i++) {
    if (i < valignOffset || i >= valignOffset + textLines.length) {
      // Empty line
      boxLines.push(
        `${leftSpace}${borderStyle.v}${" ".repeat(widthOffset)}${
          borderStyle.v
        }`,
      );
    } else {
      // Text line
      const line = textLines[i - valignOffset];
      const left = " ".repeat(paddingOffset);
      const right = " ".repeat(width - stripAnsi(line).length);
      boxLines.push(
        `${leftSpace}${borderStyle.v}${left}${line}${right}${borderStyle.v}`,
      );
    }
  }

  // Bottom line
  boxLines.push(
    `${leftSpace}${borderStyle.bl}${borderStyle.h.repeat(widthOffset)}${
      borderStyle.br
    }`,
  );
  if (opts.style.marginBottom > 0) {
    boxLines.push("".repeat(opts.style.marginBottom));
  }

  return boxLines.join("\n");
}


================================================
FILE: src/utils/color.ts
================================================
/**
 * Based on https://github.com/jorgebucaran/colorette
 * Read LICENSE file for more information
 * https://github.com/jorgebucaran/colorette/blob/20fc196d07d0f87c61e0256eadd7831c79b24108/index.js
 */

import * as tty from "node:tty";

// TODO: Migrate to std-env
const {
  env = {},
  argv = [],
  platform = "",
} = typeof process === "undefined" ? {} : process;
const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
const isForced = "FORCE_COLOR" in env || argv.includes("--color");
const isWindows = platform === "win32";
const isDumbTerminal = env.TERM === "dumb";
const isCompatibleTerminal =
  tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
const isCI =
  "CI" in env &&
  ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);

/**
 * Determines support for terminal colours based on the environment and capabilities of the terminal.
 * @type {boolean} isColorSupported - Indicates whether colour support is enabled in the terminal.
 */
const isColorSupported =
  !isDisabled &&
  (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);

function replaceClose(
  index: number,
  string: string,
  close: string,
  replace: string,
  head = string.slice(0, Math.max(0, index)) + replace,
  tail = string.slice(Math.max(0, index + close.length)),
  next = tail.indexOf(close),
): string {
  return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
}

function clearBleed(
  index: number,
  string: string,
  open: string,
  close: string,
  replace: string,
) {
  return index < 0
    ? open + string + close
    : open + replaceClose(index, string, close, replace) + close;
}

function filterEmpty(
  open: string,
  close: string,
  replace = open,
  at = open.length + 1,
) {
  return (string: string) =>
    string || !(string === "" || string === undefined)
      ? clearBleed(
          ("" + string).indexOf(close, at),
          string,
          open,
          close,
          replace,
        )
      : "";
}

function init(open: number, close: number, replace?: string) {
  return filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
}

const colorDefs = {
  reset: init(0, 0),
  bold: init(1, 22, "\u001B[22m\u001B[1m"),
  dim: init(2, 22, "\u001B[22m\u001B[2m"),
  italic: init(3, 23),
  underline: init(4, 24),
  inverse: init(7, 27),
  hidden: init(8, 28),
  strikethrough: init(9, 29),
  black: init(30, 39),
  red: init(31, 39),
  green: init(32, 39),
  yellow: init(33, 39),
  blue: init(34, 39),
  magenta: init(35, 39),
  cyan: init(36, 39),
  white: init(37, 39),
  gray: init(90, 39),
  bgBlack: init(40, 49),
  bgRed: init(41, 49),
  bgGreen: init(42, 49),
  bgYellow: init(43, 49),
  bgBlue: init(44, 49),
  bgMagenta: init(45, 49),
  bgCyan: init(46, 49),
  bgWhite: init(47, 49),
  blackBright: init(90, 39),
  redBright: init(91, 39),
  greenBright: init(92, 39),
  yellowBright: init(93, 39),
  blueBright: init(94, 39),
  magentaBright: init(95, 39),
  cyanBright: init(96, 39),
  whiteBright: init(97, 39),
  bgBlackBright: init(100, 49),
  bgRedBright: init(101, 49),
  bgGreenBright: init(102, 49),
  bgYellowBright: init(103, 49),
  bgBlueBright: init(104, 49),
  bgMagentaBright: init(105, 49),
  bgCyanBright: init(106, 49),
  bgWhiteBright: init(107, 49),
};

export type ColorName = keyof typeof colorDefs;
export type ColorFunction = (text: string | number) => string;

/**
 * Creates an object that maps colour names to their respective colour functions,
 * based on whether or not colour support is enabled.
 * @param {boolean} [useColor=isColorSupported] - Specifies whether to use colour functions or fallback to plain strings.
 * @returns {Record<ColorName, ColorFunction>} An object where keys are colour names and values are functions to apply those colours. See {@link ColorFunction}.
 */
function createColors(useColor = isColorSupported) {
  return useColor
    ? colorDefs
    : Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));
}

/**
 * An object containing functions for colouring text. Each function corresponds to a terminal colour. See {@link ColorName} for available colours.
 */
export const colors = createColors() as Record<ColorName, ColorFunction>;

/**
 * Gets a colour function by name, with an option for a fallback colour if the requested colour is not found.
 * @param {ColorName} color - The name of the colour function to get. See {@link ColorName}.
 * @param {ColorName} [fallback="reset"] - The name of the fallback colour function if the requested colour is not found. See {@link ColorName}.
 * @returns {ColorFunction} The colour function that corresponds to the requested colour, or the fallback colour function. See {@link ColorFunction}.
 */
export function getColor(
  color: ColorName,
  fallback: ColorName = "reset",
): ColorFunction {
  return colors[color] || colors[fallback];
}

/**
 * Applies a specified colour to a given text string or number.
 * @param {ColorName} color - The colour to apply. See {@link ColorName}.
 * @param {string | number} text - The text to colour.
 * @returns {string} The coloured text.
 */
export function colorize(color: ColorName, text: string | number): string {
  return getColor(color)(text);
}


================================================
FILE: src/utils/error.ts
================================================
import { sep } from "node:path";

/**
 * Parses a stack trace string and normalises its paths by removing the current working directory and the "file://" protocol.
 * @param {string} stack - The stack trace string.
 * @returns {string[]} An array of stack trace lines with normalised paths.
 */
export function parseStack(stack: string, message: string) {
  const cwd = process.cwd() + sep;

  const lines = stack
    .split("\n")
    .splice(message.split("\n").length)
    .map((l) => l.trim().replace("file://", "").replace(cwd, ""));

  return lines;
}


================================================
FILE: src/utils/format.ts
================================================
import { vsprintf } from "printj";

// Predefined rules for replacing format arguments
const FORMAT_ARGS = [
  ["additional", 5],
  ["message", 4],
  ["type", 2],
  ["date", 1],
  ["tag", 3],
]; // .sort((a, b) => b[0].length - a[0].length)

// Caches compiled format strings for reuse
const _compileCache: any = {};
// process.on('beforeExit', () => { console.log(_compileCache) })

/**
 * Compiles a format string by replacing placeholders with appropriate position indices.
 * Caches compiled formats for efficiency.
 * @param {string} format - The format string containing the placeholders to replace.
 * @returns {string} The compiled format string with placeholders replaced by positional indices.
 */
export function compileFormat(format: string) {
  if (_compileCache[format]) {
    return _compileCache[format];
  }

  let _format = format;
  for (const arg of FORMAT_ARGS) {
    _format = _format.replace(
      new RegExp("([%-])" + arg[0], "g"),
      "$1" + arg[1],
    );
  }

  _compileCache[format] = _format;
  return _format;
}

/**
 * Formats a string according to a custom format, using vsprintf for string formatting.
 * @param {string} format - The custom format string.
 * @param {any[]} argv - The arguments to format into the string.
 * @returns {string} The formatted string.
 */
export function formatString(format: string, argv: any) {
  return vsprintf(compileFormat(format), argv);
}


================================================
FILE: src/utils/log.ts
================================================
/**
 * Checks if the given argument is a simple JavaScript object.
 * @param {any} obj - The object to test.
 * @returns {boolean} `true` if the argument is a plain object, otherwise `false`.
 */
export function isPlainObject(obj: any) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

/**
 * Determines whether the given argument is a protocol object. A log object must be a simple object and
 * must contain either a 'message' or 'args' field, but not a 'stack' field.
 * @param {any} arg - The argument to check.
 * @returns {boolean} `true` if the argument is a log object according to the specified criteria, otherwise `false`.
 */
export function isLogObj(arg: any) {
  // Should be plain object
  if (!isPlainObject(arg)) {
    return false;
  }

  // Should contains either 'message' or 'args' field
  if (!arg.message && !arg.args) {
    return false;
  }

  // Handle non-standard error objects
  if (arg.stack) {
    return false;
  }

  return true;
}


================================================
FILE: src/utils/stream.ts
================================================
/**
 * Writes data to a specified NodeJS writable stream. This function supports streams that have a custom
 * `__write' method, and will fall back to the default `write' method if `__write' is not present.
 *
 * @param {any} data - The data to write to the stream. This can be a string, a buffer, or any data type
 * supported by the stream's `write' or `__write' method.
 * @param {NodeJS.WriteStream} stream - The writable stream to write the data to. This stream
 * must implement the `write' method, and can optionally implement a custom `__write' method.
 * @returns {boolean} `true` if the data has been completely processed by the write operation,
 * indicating that further writes can be performed immediately. Returns `false` if the data is
 * buffered by the stream, indicating that the `drain` event should be waited for before writing
 * more data.
 */
export function writeStream(data: any, stream: NodeJS.WriteStream) {
  const write = (stream as any).__write || stream.write;
  return write.call(stream, data);
}


================================================
FILE: src/utils/string.ts
================================================
const ansiRegex = [
  String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`,
  String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`,
].join("|");

/**
 * Removes ANSI escape codes from a given string. This is particularly useful for
 * processing text that contains formatting codes, such as colours or styles, so that the
 * the raw text without any visual formatting.
 *
 * @param {string} text - The text string from which to strip the ANSI escape codes.
 * @returns {string} The text without ANSI escape codes.
 */
export function stripAnsi(text: string) {
  return text.replace(new RegExp(ansiRegex, "g"), "");
}

/**
 * Centers a string within a specified total width, padding it with spaces or another specified character.
 * If the string is longer than the total width, it is returned as is.
 *
 * @param {string} str - The string to centre.
 * @param {number} len - The total width in which to centre the string.
 * @param {string} [space=" "] - The character to use for padding. Defaults to a space.
 * @returns {string} The centred string.
 */
export function centerAlign(str: string, len: number, space = " ") {
  const free = len - str.length;
  if (free <= 0) {
    return str;
  }
  const freeLeft = Math.floor(free / 2);
  let _str = "";
  for (let i = 0; i < len; i++) {
    _str +=
      i < freeLeft || i >= freeLeft + str.length ? space : str[i - freeLeft];
  }
  return _str;
}

/**
 * Right-justifies a string within a given total width, padding it with whitespace or another specified character.
 * If the string is longer than the total width, it is returned as is.
 *
 * @param {string} str - The string to right-justify.
 * @param {number} len - The total width to align the string.
 * @param {string} [space=" "] - The character to use for padding. Defaults to a space.
 * @returns {string} The right-justified string.
 */
export function rightAlign(str: string, len: number, space = " ") {
  const free = len - str.length;
  if (free <= 0) {
    return str;
  }
  let _str = "";
  for (let i = 0; i < len; i++) {
    _str += i < free ? space : str[i - free];
  }
  return _str;
}

/**
 * Left-aligns a string within a given total width, padding it with whitespace or another specified character on the right.
 * If the string is longer than the total width, it is returned as is.
 *
 * @param {string} str - The string to align left.
 * @param {number} len - The total width to align the string.
 * @param {string} [space=" "] - The character to use for padding. Defaults to a space.
 * @returns {string} The left-justified string.
 */
export function leftAlign(str: string, len: number, space = " ") {
  let _str = "";
  for (let i = 0; i < len; i++) {
    _str += i < str.length ? str[i] : space;
  }
  return _str;
}

/**
 * Aligns a string (left, right, or centre) within a given total width, padding it with spaces or another specified character.
 * If the string is longer than the total width, it is returned as is. This function acts as a wrapper for individual alignment functions.
 *
 * @param {"left" | "right" | "centre"} alignment - The desired alignment of the string.
 * @param {string} str - The string to align.
 * @param {number} len - The total width in which to align the string.
 * @param {string} [space=" "] - The character to use for padding. Defaults to a space.
 * @returns {string} The aligned string, according to the given alignment.
 */
export function align(
  alignment: "left" | "right" | "center",
  str: string,
  len: number,
  space = " ",
) {
  switch (alignment) {
    case "left": {
      return leftAlign(str, len, space);
    }
    case "right": {
      return rightAlign(str, len, space);
    }
    case "center": {
      return centerAlign(str, len, space);
    }
    default: {
      return str;
    }
  }
}


================================================
FILE: src/utils/tree.ts
================================================
import { type ColorName, colorize } from "./color";

export type TreeItemObject = {
  /**
   * Text of the item
   */
  text: string;

  /**
   * Children of the item
   */
  children?: TreeItem[];

  /**
   * Color of the item
   */
  color?: ColorName;
};

export type TreeItem = string | TreeItemObject;

export type TreeOptions = {
  /**
   * Color of the tree
   */
  color?: ColorName;

  /**
   * Prefix of the tree
   *
   * @default "  "
   */
  prefix?: string;

  /**
   * The max depth of tree
   */
  maxDepth?: number;

  /**
   * Ellipsis of the tree
   *
   * @default "..."
   */
  ellipsis?: string;
};

/**
 * Formats a hierarchical list of items into a string representing a tree structure.
 * Each item in the tree can be a simple string or an object defining the text of the item,
 * optional children, and colour. The tree structure can be customised with options
 * Specify the overall colour and the prefix used for indentation and tree lines.
 *
 * @param {TreeItem[]} items - An array of items to include in the tree. Each item can be
 * either a string or an object with `text', `children' and `colour' properties.
 * @param {TreeOptions} [options] - Optional settings to customise the appearance of the tree, including
 * the colour of the tree text and the prefix for branches. See {@link TreeOptions}.
 * @returns {string} The formatted tree as a string, ready for printing to the console or elsewhere.
 */
export function formatTree(items: TreeItem[], options?: TreeOptions): string {
  options = {
    prefix: "  ",
    ellipsis: "...",
    ...options,
  };

  const tree = _buildTree(items, options).join("");
  if (options && options.color) {
    return colorize(options.color, tree);
  }

  return tree;
}

function _buildTree(items: TreeItem[], options?: TreeOptions): string[] {
  const chunks: string[] = [];
  const total = items.length - 1;
  for (let i = 0; i <= total; i++) {
    const item = items[i];
    const isItemString = typeof item === "string";
    const isLimit = options?.maxDepth != null && options.maxDepth <= 0;
    if (isLimit) {
      const ellipsis = `${options.prefix}${options.ellipsis}\n`;
      return [
        isItemString
          ? ellipsis
          :
            (item.color
            ? colorize(item.color, ellipsis)
            : ellipsis), // prettier-ignore
      ];
    }
    const isLast = i === total;
    const prefix = isLast ? `${options?.prefix}└─` : `${options?.prefix}├─`;
    if (isItemString) {
      chunks.push(`${prefix}${item}\n`);
    } else {
      const log = `${prefix}${item.text}\n`;
      chunks.push(item.color ? colorize(item.color, log) : log);

      if (item.children) {
        const _tree = _buildTree(item.children, {
          ...options,
          maxDepth:
            options?.maxDepth == null ? undefined : options.maxDepth - 1,
          prefix: `${options?.prefix}${isLast ? "  " : "│  "}`,
        });
        chunks.push(..._tree);
      }
    }
  }

  return chunks;
}


================================================
FILE: src/utils.ts
================================================
export * from "./utils/box";
export * from "./utils/color";
export {
  stripAnsi,
  centerAlign,
  rightAlign,
  leftAlign,
  align,
} from "./utils/string";
export {
  type TreeItemObject,
  type TreeItem,
  type TreeOptions,
  formatTree,
} from "./utils/tree";


================================================
FILE: test/consola.test.ts
================================================
import { describe, test, expect } from "vitest";
import { ConsolaReporter, LogLevels, LogObject, createConsola } from "../src";

describe("consola", () => {
  test("can set level", () => {
    const consola = createConsola();
    expect(consola.level).toBe(1);

    for (let i = 0; i <= 5; i++) {
      consola.level = i;
      expect(consola.level).toBe(i);
    }
  });

  test("silent log level does't print logs", async () => {
    const logs: LogObject[] = [];
    const TestReporter: ConsolaReporter = {
      log(logObj) {
        logs.push(logObj);
      },
    };

    const consola = createConsola({
      throttle: 100,
      level: LogLevels.silent,
      reporters: [TestReporter],
    });

    for (let i = 0; i < 10; i++) {
      consola.log("SPAM");
    }

    await wait(200);
    expect(logs.length).toBe(0);
  });

  test("can see spams without ending log", async () => {
    const logs: LogObject[] = [];
    const TestReporter: ConsolaReporter = {
      log(logObj) {
        logs.push(logObj);
      },
    };

    const consola = createConsola({
      throttle: 100,
      level: LogLevels.info,
      reporters: [TestReporter],
    });
    for (let i = 0; i < 10; i++) {
      consola.log("SPAM");
    }
    await wait(300);
    expect(logs.length).toBe(7);
    // 6 + Last one indicating it repeated 4

    expect(logs.at(-1)!.args).toEqual(["SPAM", "(repeated 4 times)"]);
  });
});

function wait(delay) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
}


================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "strict": true,
    "types": ["vitest/globals", "node"]
  },
  "include": ["src"]
}


================================================
FILE: utils.d.ts
================================================
export * from "./dist/utils";
Download .txt
gitextract_mvamdj0q/

├── .editorconfig
├── .github/
│   ├── codecov.yml
│   └── workflows/
│       ├── autofix.yml
│       └── ci.yml
├── .gitignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── basic.d.ts
├── browser.d.ts
├── build.config.ts
├── core.d.ts
├── eslint.config.mjs
├── examples/
│   ├── basic.ts
│   ├── box.ts
│   ├── error.ts
│   ├── fancy.ts
│   ├── index.html
│   ├── index.legacy.html
│   ├── json.ts
│   ├── mock.ts
│   ├── no-width.ts
│   ├── pause.ts
│   ├── prompt.mjs
│   ├── prompt.ts
│   ├── raw.ts
│   ├── sample.ts
│   ├── spam.ts
│   ├── special.ts
│   ├── spinner.ts
│   ├── tree.ts
│   ├── utils/
│   │   ├── index.ts
│   │   └── sentence.ts
│   ├── wrap-all.ts
│   ├── wrap-console.ts
│   └── wrap-std.ts
├── lib/
│   └── index.cjs
├── package.json
├── renovate.json
├── src/
│   ├── basic.ts
│   ├── browser.ts
│   ├── consola.ts
│   ├── constants.ts
│   ├── core.ts
│   ├── index.ts
│   ├── prompt.ts
│   ├── reporters/
│   │   ├── basic.ts
│   │   ├── browser.ts
│   │   └── fancy.ts
│   ├── shared.ts
│   ├── types.ts
│   ├── utils/
│   │   ├── box.ts
│   │   ├── color.ts
│   │   ├── error.ts
│   │   ├── format.ts
│   │   ├── log.ts
│   │   ├── stream.ts
│   │   ├── string.ts
│   │   └── tree.ts
│   └── utils.ts
├── test/
│   └── consola.test.ts
├── tsconfig.json
└── utils.d.ts
Download .txt
SYMBOL INDEX (123 symbols across 33 files)

FILE: build.config.ts
  method "rollup:options" (line 8) | "rollup:options"(_, options) {

FILE: examples/box.ts
  function main (line 4) | function main() {

FILE: examples/mock.ts
  function mockFn (line 3) | function mockFn(type) {

FILE: examples/no-width.ts
  function main (line 3) | function main() {

FILE: examples/prompt.ts
  function main (line 3) | async function main() {

FILE: examples/sample.ts
  function main (line 3) | async function main() {

FILE: examples/spam.ts
  function waitFor (line 3) | function waitFor(ms) {
  function spam (line 7) | async function spam({ count, delay }) {

FILE: examples/spinner.ts
  function main (line 3) | async function main() {

FILE: examples/tree.ts
  function main (line 4) | function main() {

FILE: examples/utils/index.ts
  function reporterDemo (line 4) | function reporterDemo(

FILE: examples/utils/sentence.ts
  function randomSentence (line 35) | function randomSentence() {

FILE: examples/wrap-all.ts
  function foo (line 3) | function foo() {

FILE: examples/wrap-console.ts
  function foo (line 3) | function foo() {
  function _trace (line 8) | function _trace() {
  function trace (line 11) | function trace() {

FILE: examples/wrap-std.ts
  function foo (line 3) | function foo() {

FILE: src/basic.ts
  function createConsola (line 14) | function createConsola(

FILE: src/browser.ts
  function createConsola (line 15) | function createConsola(options: Partial<ConsolaOptions> = {}) {

FILE: src/consola.ts
  class Consola (line 21) | class Consola {
    method constructor (line 39) | constructor(options: Partial<ConsolaOptions> = {}) {
    method level (line 92) | get level() {
    method level (line 101) | set level(level) {
    method prompt (line 118) | prompt<T extends PromptOptions>(message: string, opts?: T) {
    method create (line 131) | create(options: Partial<ConsolaOptions>): ConsolaInstance {
    method withDefaults (line 150) | withDefaults(defaults: InputLogObject): ConsolaInstance {
    method withTag (line 166) | withTag(tag: string): ConsolaInstance {
    method addReporter (line 181) | addReporter(reporter: ConsolaReporter) {
    method removeReporter (line 193) | removeReporter(reporter: ConsolaReporter) {
    method setReporters (line 211) | setReporters(reporters: ConsolaReporter[]) {
    method wrapAll (line 216) | wrapAll() {
    method restoreAll (line 221) | restoreAll() {
    method wrapConsole (line 229) | wrapConsole() {
    method restoreConsole (line 245) | restoreConsole() {
    method wrapStd (line 258) | wrapStd() {
    method _wrapStream (line 263) | _wrapStream(stream: NodeJS.WriteStream | undefined, type: LogType) {
    method restoreStd (line 282) | restoreStd() {
    method _restoreStream (line 287) | _restoreStream(stream?: NodeJS.WriteStream) {
    method pauseLogs (line 301) | pauseLogs() {
    method resumeLogs (line 308) | resumeLogs() {
    method mockTypes (line 323) | mockTypes(mockFn?: ConsolaOptions["mockFn"]) {
    method _wrapLogFn (line 343) | _wrapLogFn(defaults: InputLogObject, isRaw?: boolean) {
    method _logFn (line 353) | _logFn(defaults: InputLogObject, args: any[], isRaw?: boolean) {
    method _log (line 451) | _log(logObj: LogObject) {
  function _normalizeLogLevel (line 460) | function _normalizeLogLevel(
  type LogFn (line 477) | interface LogFn {
  type ConsolaInstance (line 481) | type ConsolaInstance = Consola & Record<LogType, LogFn>;
  function createConsola (line 505) | function createConsola(

FILE: src/constants.ts
  type LogLevel (line 9) | type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | (number & {});
  type LogType (line 45) | type LogType =

FILE: src/index.ts
  function createConsola (line 17) | function createConsola(
  function _getDefaultLogLevel (line 44) | function _getDefaultLogLevel() {

FILE: src/prompt.ts
  type SelectOption (line 3) | type SelectOption = {
  type PromptCommonOptions (line 11) | type PromptCommonOptions = {
  type TextPromptOptions (line 26) | type TextPromptOptions = PromptCommonOptions & {
  type ConfirmPromptOptions (line 53) | type ConfirmPromptOptions = PromptCommonOptions & {
  type SelectPromptOptions (line 66) | type SelectPromptOptions = PromptCommonOptions & {
  type MultiSelectOptions (line 84) | type MultiSelectOptions = PromptCommonOptions & {
  type PromptOptions (line 109) | type PromptOptions =
  type inferPromptReturnType (line 115) | type inferPromptReturnType<T extends PromptOptions> =
  type inferPromptCancalReturnType (line 128) | type inferPromptCancalReturnType<T extends PromptOptions> = T extends {
  function prompt (line 150) | async function prompt<

FILE: src/reporters/basic.ts
  class BasicReporter (line 13) | class BasicReporter implements ConsolaReporter {
    method formatStack (line 14) | formatStack(stack: string, message: string, opts: FormatOptions) {
    method formatError (line 19) | formatError(err: any, opts: FormatOptions): string {
    method formatArgs (line 32) | formatArgs(args: any[], opts: FormatOptions) {
    method formatDate (line 45) | formatDate(date: Date, opts: FormatOptions) {
    method filterAndJoin (line 49) | filterAndJoin(arr: any[]) {
    method formatLogObj (line 53) | formatLogObj(logObj: LogObject, opts: FormatOptions) {
    method log (line 78) | log(logObj: LogObject, ctx: { options: ConsolaOptions }) {

FILE: src/reporters/browser.ts
  class BrowserReporter (line 3) | class BrowserReporter {
    method constructor (line 9) | constructor(options: any) {
    method _getLogFn (line 23) | _getLogFn(level: number) {
    method log (line 33) | log(logObj: LogObject) {

FILE: src/reporters/fancy.ts
  constant TYPE_COLOR_MAP (line 11) | const TYPE_COLOR_MAP: { [k in LogType]?: string } = {
  constant LEVEL_COLOR_MAP (line 19) | const LEVEL_COLOR_MAP: { [k in LogLevel]?: string } = {
  constant TYPE_ICONS (line 26) | const TYPE_ICONS: { [k in LogType]?: string } = {
  function stringWidth (line 40) | function stringWidth(str: string) {
  class FancyReporter (line 49) | class FancyReporter extends BasicReporter {
    method formatStack (line 50) | formatStack(stack: string, message: string, opts?: FormatOptions) {
    method formatType (line 66) | formatType(logObj: LogObject, isBadge: boolean, opts: FormatOptions) {
    method formatLogObj (line 86) | formatLogObj(logObj: LogObject, opts: FormatOptions) {
  function characterFormat (line 137) | function characterFormat(str: string) {
  function getColor (line 147) | function getColor(color = "white") {
  function getBgColor (line 151) | function getBgColor(color = "bgWhite") {

FILE: src/types.ts
  type ConsolaOptions (line 3) | interface ConsolaOptions {
  type FormatOptions (line 68) | interface FormatOptions {
  type InputLogObject (line 104) | interface InputLogObject {
  type LogObject (line 148) | interface LogObject extends InputLogObject {
  type ConsolaReporter (line 180) | interface ConsolaReporter {

FILE: src/utils/box.ts
  type BoxBorderStyle (line 4) | type BoxBorderStyle = {
  type BoxStyle (line 116) | type BoxStyle = {
  type BoxOpts (line 192) | type BoxOpts = {
  function box (line 222) | function box(text: string, _opts: BoxOpts = {}) {

FILE: src/utils/color.ts
  function replaceClose (line 33) | function replaceClose(
  function clearBleed (line 45) | function clearBleed(
  function filterEmpty (line 57) | function filterEmpty(
  function init (line 75) | function init(open: number, close: number, replace?: string) {
  type ColorName (line 123) | type ColorName = keyof typeof colorDefs;
  type ColorFunction (line 124) | type ColorFunction = (text: string | number) => string;
  function createColors (line 132) | function createColors(useColor = isColorSupported) {
  function getColor (line 149) | function getColor(
  function colorize (line 162) | function colorize(color: ColorName, text: string | number): string {

FILE: src/utils/error.ts
  function parseStack (line 8) | function parseStack(stack: string, message: string) {

FILE: src/utils/format.ts
  constant FORMAT_ARGS (line 4) | const FORMAT_ARGS = [
  function compileFormat (line 22) | function compileFormat(format: string) {
  function formatString (line 45) | function formatString(format: string, argv: any) {

FILE: src/utils/log.ts
  function isPlainObject (line 6) | function isPlainObject(obj: any) {
  function isLogObj (line 16) | function isLogObj(arg: any) {

FILE: src/utils/stream.ts
  function writeStream (line 14) | function writeStream(data: any, stream: NodeJS.WriteStream) {

FILE: src/utils/string.ts
  function stripAnsi (line 14) | function stripAnsi(text: string) {
  function centerAlign (line 27) | function centerAlign(str: string, len: number, space = " ") {
  function rightAlign (line 50) | function rightAlign(str: string, len: number, space = " ") {
  function leftAlign (line 71) | function leftAlign(str: string, len: number, space = " ") {
  function align (line 89) | function align(

FILE: src/utils/tree.ts
  type TreeItemObject (line 3) | type TreeItemObject = {
  type TreeItem (line 20) | type TreeItem = string | TreeItemObject;
  type TreeOptions (line 22) | type TreeOptions = {
  function formatTree (line 60) | function formatTree(items: TreeItem[], options?: TreeOptions): string {
  function _buildTree (line 75) | function _buildTree(items: TreeItem[], options?: TreeOptions): string[] {

FILE: test/consola.test.ts
  method log (line 18) | log(logObj) {
  method log (line 40) | log(logObj) {
  function wait (line 61) | function wait(delay) {
Condensed preview — 64 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (157K chars).
[
  {
    "path": ".editorconfig",
    "chars": 207,
    "preview": "# editorconfig.org\nroot = true\n\n[*]\nindent_size = 2\nindent_style = space\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_"
  },
  {
    "path": ".github/codecov.yml",
    "chars": 70,
    "preview": "coverage:\n  status:\n    project:\n      default:\n        threshold: 5%\n"
  },
  {
    "path": ".github/workflows/autofix.yml",
    "chars": 618,
    "preview": "name: autofix.ci # needed to securely identify the workflow\n\non:\n  pull_request:\n  push:\n    branches: [\"main\"]\n\npermiss"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 478,
    "preview": "name: ci\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n    branches:\n      - main\n\njobs:\n  ci:\n    runs-on: ub"
  },
  {
    "path": ".gitignore",
    "chars": 34,
    "preview": "node_modules\n*.log*\ndist\ncoverage\n"
  },
  {
    "path": ".prettierrc",
    "chars": 3,
    "preview": "{}\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 47097,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file. See [standard-version](https://github."
  },
  {
    "path": "LICENSE",
    "chars": 3365,
    "preview": "MIT License\n\nCopyright (c) Pooya Parsa <pooya@pi0.io>\n\nPermission is hereby granted, free of charge, to any person obtai"
  },
  {
    "path": "README.md",
    "chars": 9195,
    "preview": "# 🐨 Consola\n\n> Elegant Console Wrapper\n\n[![npm version][npm-version-src]][npm-version-href]\n[![npm downloads][npm-downlo"
  },
  {
    "path": "basic.d.ts",
    "chars": 30,
    "preview": "export * from \"./dist/basic\";\n"
  },
  {
    "path": "browser.d.ts",
    "chars": 32,
    "preview": "export * from \"./dist/browser\";\n"
  },
  {
    "path": "build.config.ts",
    "chars": 1647,
    "preview": "import { defineBuildConfig } from \"unbuild\";\n\nexport default defineBuildConfig({\n  rollup: {\n    inlineDependencies: tru"
  },
  {
    "path": "core.d.ts",
    "chars": 29,
    "preview": "export * from \"./dist/core\";\n"
  },
  {
    "path": "eslint.config.mjs",
    "chars": 414,
    "preview": "import unjs from \"eslint-config-unjs\";\n\n// https://github.com/unjs/eslint-config\nexport default unjs({\n  ignores: [],\n  "
  },
  {
    "path": "examples/basic.ts",
    "chars": 76,
    "preview": "import { reporterDemo } from \"./utils\";\n\nreporterDemo({\n  fancy: false,\n});\n"
  },
  {
    "path": "examples/box.ts",
    "chars": 842,
    "preview": "import { consola } from \"./utils\";\nimport { colors } from \"../src/utils\";\n\nfunction main() {\n  consola.box(`I am the def"
  },
  {
    "path": "examples/error.ts",
    "chars": 287,
    "preview": "import { consola } from \"./utils\";\n\nconst error = new Error(\"This is an error\\nWith second line\\nAnd another\", {\n  cause"
  },
  {
    "path": "examples/fancy.ts",
    "chars": 75,
    "preview": "import { reporterDemo } from \"./utils\";\n\nreporterDemo({\n  fancy: true,\n});\n"
  },
  {
    "path": "examples/index.html",
    "chars": 598,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <title>Consola</title>\n  </head>\n  <body>\n    Open developer tools to see the magic!"
  },
  {
    "path": "examples/index.legacy.html",
    "chars": 527,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <title>Consola</title>\n  </head>\n  <body>\n    Open developer tools to see the magic!"
  },
  {
    "path": "examples/json.ts",
    "chars": 215,
    "preview": "import { createConsola } from \"consola\";\n\nconst consola = createConsola({\n  reporters: [\n    {\n      log: (logObj) => {\n"
  },
  {
    "path": "examples/mock.ts",
    "chars": 362,
    "preview": "import { consola } from \"./utils\";\n\nfunction mockFn(type) {\n  if (type === \"info\") {\n    return function () {\n      this"
  },
  {
    "path": "examples/no-width.ts",
    "chars": 241,
    "preview": "import { createConsola } from \"../src\";\n\nfunction main() {\n  const consola = createConsola({\n    formatOptions: { column"
  },
  {
    "path": "examples/pause.ts",
    "chars": 268,
    "preview": "import { consola } from \"./utils\";\n\nconst c1 = consola.withTag(\"foo\");\nconst c2 = consola.withTag(\"bar\");\n\nconsola.log(\""
  },
  {
    "path": "examples/prompt.mjs",
    "chars": 1212,
    "preview": "#!/usr/bin/env node\n\nimport { consola } from \"../dist/index.mjs\";\n\nconst name = await consola.prompt(\"What is your name?"
  },
  {
    "path": "examples/prompt.ts",
    "chars": 1029,
    "preview": "import { consola } from \"./utils\";\n\nasync function main() {\n  const name = await consola.prompt(\"What is your name?\", {\n"
  },
  {
    "path": "examples/raw.ts",
    "chars": 266,
    "preview": "import { consola } from \"./utils\";\n\nconsola.log('consola.log({ message: \"hello\" })');\n// Prints \"hello\"\nconsola.log({ me"
  },
  {
    "path": "examples/sample.ts",
    "chars": 408,
    "preview": "import { consola } from \"../src\";\n\nasync function main() {\n  consola.warn(\"A new version of consola is available: 3.0.1\""
  },
  {
    "path": "examples/spam.ts",
    "chars": 472,
    "preview": "import { consola } from \"./utils\";\n\nfunction waitFor(ms) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}"
  },
  {
    "path": "examples/special.ts",
    "chars": 724,
    "preview": "import { consola } from \"./utils\";\n\nconsola.error({\n  message: \"Foobar\",\n});\n\nconsola.log({\n  AAA: \"BBB\",\n});\n\n// consol"
  },
  {
    "path": "examples/spinner.ts",
    "chars": 211,
    "preview": "import { consola } from \"./utils\";\n\nasync function main() {\n  consola.start(\"Creating project...\");\n  await new Promise("
  },
  {
    "path": "examples/tree.ts",
    "chars": 3132,
    "preview": "import { TreeItem, formatTree } from \"../src/utils/tree\";\nimport { consola } from \"./utils\";\n\nfunction main() {\n  const "
  },
  {
    "path": "examples/utils/index.ts",
    "chars": 683,
    "preview": "import { ConsolaOptions, createConsola } from \"../../src\";\nimport { randomSentence } from \"./sentence\";\n\nexport function"
  },
  {
    "path": "examples/utils/sentence.ts",
    "chars": 2512,
    "preview": "import Sentencer from \"sentencer\";\n\nconst sentenceTemplates = [\n  \"the {{ noun }} is {{ a_noun }}\",\n  \"{{ a_noun }} is {"
  },
  {
    "path": "examples/wrap-all.ts",
    "chars": 190,
    "preview": "import { consola } from \"./utils\";\n\nfunction foo() {\n  console.info(\"console foo\");\n  process.stderr.write(\"called from "
  },
  {
    "path": "examples/wrap-console.ts",
    "chars": 278,
    "preview": "import { consola } from \"./utils\";\n\nfunction foo() {\n  console.info(\"foo\");\n  console.warn(\"foo warn\");\n}\n\nfunction _tra"
  },
  {
    "path": "examples/wrap-std.ts",
    "chars": 246,
    "preview": "import { consola } from \"./utils\";\n\nfunction foo() {\n  console.info(\"console foo\");\n  process.stdout.write(\"called from "
  },
  {
    "path": "lib/index.cjs",
    "chars": 241,
    "preview": "// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst lib = require(\"../dist/index.cjs\");\n\nmodule.expo"
  },
  {
    "path": "package.json",
    "chars": 3203,
    "preview": "{\n  \"name\": \"consola\",\n  \"version\": \"3.4.2\",\n  \"description\": \"Elegant Console Wrapper\",\n  \"keywords\": [\n    \"console\",\n"
  },
  {
    "path": "renovate.json",
    "chars": 49,
    "preview": "{\n  \"extends\": [\"github>unjs/renovate-config\"]\n}\n"
  },
  {
    "path": "src/basic.ts",
    "chars": 1386,
    "preview": "import { LogLevels, LogLevel } from \"./constants\";\nimport type { ConsolaOptions } from \"./types\";\nimport { BasicReporter"
  },
  {
    "path": "src/browser.ts",
    "chars": 1379,
    "preview": "import { BrowserReporter } from \"./reporters/browser\";\nimport { createConsola as _createConsola } from \"./consola\";\nimpo"
  },
  {
    "path": "src/consola.ts",
    "chars": 14236,
    "preview": "import { defu } from \"defu\";\nimport { LogTypes, LogType, LogLevel } from \"./constants\";\nimport { isLogObj } from \"./util"
  },
  {
    "path": "src/constants.ts",
    "chars": 2340,
    "preview": "import { LogObject } from \"./types\";\n\n/**\n * Defines the level of logs as specific numbers or special number types.\n *\n "
  },
  {
    "path": "src/core.ts",
    "chars": 69,
    "preview": "export { createConsola } from \"./consola\";\nexport * from \"./shared\";\n"
  },
  {
    "path": "src/index.ts",
    "chars": 2024,
    "preview": "import { isDebug, isTest, isCI } from \"std-env\";\nimport { LogLevels, LogLevel } from \"./constants\";\nimport type { Consol"
  },
  {
    "path": "src/prompt.ts",
    "chars": 5632,
    "preview": "import { text, confirm, select, multiselect } from \"@clack/prompts\";\n\ntype SelectOption = {\n  label: string;\n  value: st"
  },
  {
    "path": "src/reporters/basic.ts",
    "chars": 2541,
    "preview": "import { formatWithOptions } from \"node:util\";\nimport type {\n  LogObject,\n  ConsolaReporter,\n  FormatOptions,\n  ConsolaO"
  },
  {
    "path": "src/reporters/browser.ts",
    "chars": 1644,
    "preview": "import { LogObject } from \"../types\";\n\nexport class BrowserReporter {\n  options: any;\n  defaultColor: string;\n  levelCol"
  },
  {
    "path": "src/reporters/fancy.ts",
    "chars": 4381,
    "preview": "import _stringWidth from \"string-width\";\nimport isUnicodeSupported from \"is-unicode-supported\";\nimport { colors } from \""
  },
  {
    "path": "src/shared.ts",
    "chars": 363,
    "preview": "export { LogLevels, LogTypes } from \"./constants\";\nexport { Consola } from \"./consola\";\n\nexport type * from \"./types\";\ne"
  },
  {
    "path": "src/types.ts",
    "chars": 4369,
    "preview": "import type { LogLevel, LogType } from \"./constants\";\n\nexport interface ConsolaOptions {\n  /**\n   * An array of ConsolaR"
  },
  {
    "path": "src/utils/box.ts",
    "chars": 6733,
    "preview": "import { getColor } from \"./color\";\nimport { stripAnsi } from \"./string\";\n\nexport type BoxBorderStyle = {\n  /**\n   * Top"
  },
  {
    "path": "src/utils/color.ts",
    "chars": 5247,
    "preview": "/**\n * Based on https://github.com/jorgebucaran/colorette\n * Read LICENSE file for more information\n * https://github.co"
  },
  {
    "path": "src/utils/error.ts",
    "chars": 557,
    "preview": "import { sep } from \"node:path\";\n\n/**\n * Parses a stack trace string and normalises its paths by removing the current wo"
  },
  {
    "path": "src/utils/format.ts",
    "chars": 1414,
    "preview": "import { vsprintf } from \"printj\";\n\n// Predefined rules for replacing format arguments\nconst FORMAT_ARGS = [\n  [\"additio"
  },
  {
    "path": "src/utils/log.ts",
    "chars": 987,
    "preview": "/**\n * Checks if the given argument is a simple JavaScript object.\n * @param {any} obj - The object to test.\n * @returns"
  },
  {
    "path": "src/utils/stream.ts",
    "chars": 1029,
    "preview": "/**\n * Writes data to a specified NodeJS writable stream. This function supports streams that have a custom\n * `__write'"
  },
  {
    "path": "src/utils/string.ts",
    "chars": 3869,
    "preview": "const ansiRegex = [\n  String.raw`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-"
  },
  {
    "path": "src/utils/tree.ts",
    "chars": 2986,
    "preview": "import { type ColorName, colorize } from \"./color\";\n\nexport type TreeItemObject = {\n  /**\n   * Text of the item\n   */\n  "
  },
  {
    "path": "src/utils.ts",
    "chars": 264,
    "preview": "export * from \"./utils/box\";\nexport * from \"./utils/color\";\nexport {\n  stripAnsi,\n  centerAlign,\n  rightAlign,\n  leftAli"
  },
  {
    "path": "test/consola.test.ts",
    "chars": 1508,
    "preview": "import { describe, test, expect } from \"vitest\";\nimport { ConsolaReporter, LogLevels, LogObject, createConsola } from \"."
  },
  {
    "path": "tsconfig.json",
    "chars": 222,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"esModuleIn"
  },
  {
    "path": "utils.d.ts",
    "chars": 30,
    "preview": "export * from \"./dist/utils\";\n"
  }
]

About this extraction

This page contains the full source code of the unjs/consola GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 64 files (143.3 KB), approximately 44.2k tokens, and a symbol index with 123 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!