{"name":"@inquirer/core","version":"9.0.3","keywords":["answer","answers","ask","base","cli","command","command-line","confirm","enquirer","generate","generator","hyper","input","inquire","inquirer","interface","iterm","javascript","menu","node","nodejs","prompt","promptly","prompts","question","readline","scaffold","scaffolder","scaffolding","stdin","stdout","terminal","tty","ui","yeoman","yo","zsh"],"author":"Simon Boudrias <admin@simonboudrias.com>","license":"MIT","_id":"@inquirer/core@9.0.3","homepage":"https://github.com/SBoudrias/Inquirer.js/blob/master/packages/core/README.md","dist":{"shasum":"40564a501f77410752b0a5dda652d6340e30dfa1","tarball":"http://registry-npm.ywwl.com/@inquirer/core/download/@inquirer/core-9.0.3.tgz","fileCount":99,"integrity":"sha512-p2BRZv/vMmpwlU4ZR966vKQzGVCi4VhLjVofwnFLziTQia541T7i1Ar8/LPh+LzjkXzocme+g5Io6MRtzlCcNA==","signatures":[{"sig":"MEQCIHV4OZTFotlmfV8H9bW35qqNGdk/GvK4aE6ukRk7+mL5AiA3du8/OZnlXw1j2IYOn4MLezedI2xEkZFshlzUaqhl8g==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":90399,"size":22795,"noattachment":false,"key":"/@inquirer/core/-/@inquirer/core-9.0.3.tgz"},"main":"./dist/cjs/index.js","engines":{"node":">=18"},"exports":{".":{"import":{"types":"./dist/esm/types/index.d.mts","default":"./dist/esm/index.mjs"},"require":{"types":"./dist/cjs/types/index.d.ts","default":"./dist/cjs/index.js"}}},"gitHead":"eb7a658ca58d8cc5863efb9289ae1b42e818bdd0","scripts":{"tsc":"yarn run tsc:esm && yarn run tsc:cjs","attw":"attw --pack","tsc:cjs":"rm -rf dist/cjs && tsc -p ./tsconfig.cjs.json && node ../../tools/fix-ext.mjs","tsc:esm":"rm -rf dist/esm && tsc -p ./tsconfig.json","tsc:watch":"tsc -p ./tsconfig.json --watch"},"typings":"./dist/cjs/types/index.d.ts","_npmUser":{"name":"sboudrias","email":"admin@simonboudrias.com"},"repository":{"url":"https://github.com/SBoudrias/Inquirer.js.git","type":"git"},"_npmVersion":"lerna/8.1.6/node@v20.11.1+arm64 (darwin)","description":"Core Inquirer prompt API","directories":{},"sideEffects":false,"_nodeVersion":"20.11.1","dependencies":{"cli-width":"^4.1.0","wrap-ansi":"^6.2.0","strip-ansi":"^6.0.1","@types/node":"^20.14.11","mute-stream":"^1.0.0","signal-exit":"^4.1.0","ansi-escapes":"^4.3.2","cli-spinners":"^2.9.2","@inquirer/type":"^1.5.0","yoctocolors-cjs":"^2.1.2","@types/wrap-ansi":"^3.0.0","@inquirer/figures":"^1.0.4","@types/mute-stream":"^0.0.4"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"@inquirer/testing":"^2.1.26"},"_npmOperationalInternal":{"tmp":"tmp/core_9.0.3_1721162815043_0.1351283258709699","host":"s3://npm-registry-packages"},"readme":"# `@inquirer/core`\n\nThe `@inquirer/core` package is the library enabling the creation of Inquirer prompts.\n\nIt aims to implements a lightweight API similar to React hooks - but without JSX.\n\n# Installation\n\n<table>\n<tr>\n  <th>npm</th>\n  <th>yarn</th>\n</tr>\n<tr>\n<td>\n\n```sh\nnpm install @inquirer/core\n```\n\n</td>\n<td>\n\n```sh\nyarn add @inquirer/core\n```\n\n</td>\n</tr>\n</table>\n\n# Usage\n\n## Basic concept\n\nVisual terminal apps are at their core strings rendered onto the terminal.\n\nThe most basic prompt is a function returning a string that'll be rendered in the terminal. This function will run every time the prompt state change, and the new returned string will replace the previously rendered one. The prompt cursor appears after the string.\n\nWrapping the rendering function with `createPrompt()` will setup the rendering layer, inject the state management utilities, and wait until the `done` callback is called.\n\n```ts\nimport { createPrompt } from '@inquirer/core';\n\nconst input = createPrompt((config, done) => {\n  // Implement logic\n\n  return '? My question';\n});\n\n// And it is then called as\nconst answer = await input({\n  /* config */\n});\n```\n\n## Hooks\n\nState management and user interactions are handled through hooks. Hooks are common [within the React ecosystem](https://react.dev/reference/react/hooks), and Inquirer reimplement the common ones.\n\n### State hook\n\nState lets a component “remember” information like user input. For example, an input prompt can use state to store the input value, while a list prompt can use state to track the cursor index.\n\n`useState` declares a state variable that you can update directly.\n\n```ts\nimport { createPrompt, useState } from '@inquirer/core';\n\nconst input = createPrompt((config, done) => {\n  const [index, setIndex] = useState(0);\n\n  // ...\n```\n\n### Keypress hook\n\nAlmost all prompts need to react to user actions. In a terminal, this is done through typing.\n\n`useKeypress` allows you to react to keypress events, and access the prompt line.\n\n```ts\nconst input = createPrompt((config, done) => {\n  useKeypress((key) => {\n    if (key.name === 'enter') {\n      done(answer);\n    }\n  });\n\n  // ...\n```\n\nBehind the scenes, Inquirer prompts are wrappers around [readlines](https://nodejs.org/api/readline.html). Aside the keypress event object, the hook also pass the active readline instance to the event handler.\n\n```ts\nconst input = createPrompt((config, done) => {\n  useKeypress((key, readline) => {\n    setValue(readline.line);\n  });\n\n  // ...\n```\n\n### Ref hook\n\nRefs let a prompt hold some information that isn’t used for rendering, like a class instance or a timeout ID. Unlike with state, updating a ref does not re-render your prompt. Refs are an “escape hatch” from the rendering paradigm.\n\n`useRef` declares a ref. You can hold any value in it, but most often it’s used to hold a timeout ID.\n\n```ts\nconst input = createPrompt((config, done) => {\n  const timeout = useRef(null);\n\n  // ...\n```\n\n### Effect Hook\n\nEffects let a prompt connect to and synchronize with external systems. This includes dealing with network or animations.\n\n`useEffect` connects a component to an external system.\n\n```ts\nconst chat = createPrompt((config, done) => {\n  useEffect(() => {\n    const connection = createConnection(roomId);\n    connection.connect();\n    return () => connection.disconnect();\n  }, [roomId]);\n\n  // ...\n```\n\n### Performance hook\n\nA common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell Inquirer to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.\n\n`useMemo` lets you cache the result of an expensive calculation.\n\n```ts\nconst todoSelect = createPrompt((config, done) => {\n  const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);\n\n  // ...\n```\n\n### Rendering hooks\n\n#### Prefix / loading\n\nAll default prompts, and most custom ones, uses a prefix at the beginning of the prompt line. This helps visually delineate different questions, and provides a convenient area to render a loading spinner.\n\n`usePrefix` is a built-in hook to do this.\n\n```ts\nconst input = createPrompt((config, done) => {\n  const prefix = usePrefix({ status });\n\n  return `${prefix} My question`;\n});\n```\n\n#### Pagination\n\nWhen looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompts to cycle through the list of options.\n\nPagination works by taking in the list of options and returning a subset of the rendered items that fit within the page. The hook takes in a few options. It needs a list of options (`items`), and a `pageSize` which is the number of lines to be rendered. The `active` index is the index of the currently selected/selectable item. The `loop` option is a boolean that indicates if the list should loop around when reaching the end: this is the default behavior. The pagination hook renders items only as necessary, so it takes a function that can render an item at an index, including an `active` state, called `renderItem`.\n\n```js\nexport default createPrompt((config, done) => {\n  const [active, setActive] = useState(0);\n\n  const allChoices = config.choices.map((choice) => choice.name);\n\n  const page = usePagination({\n    items: allChoices,\n    active: active,\n    renderItem: ({ item, index, isActive }) => `${isActive ? \">\" : \" \"}${index}. ${item.toString()}`\n    pageSize: config.pageSize,\n    loop: config.loop,\n  });\n\n  return `... ${page}`;\n});\n```\n\n## `createPrompt()` API\n\nAs we saw earlier, the rendering function should return a string, and eventually call `done` to close the prompt and return the answer.\n\n```ts\nconst input = createPrompt((config, done) => {\n  const [value, setValue] = useState();\n\n  useKeypress((key, readline) => {\n    if (key.name === 'enter') {\n      done(answer);\n    } else {\n      setValue(readline.line);\n    }\n  });\n\n  return `? ${config.message} ${value}`;\n});\n```\n\nThe rendering function can also return a tuple of 2 string (`[string, string]`.) The first string represents the prompt. The second one is content to render under the prompt, like an error message. The text input cursor will appear after the first string.\n\n```ts\nconst number = createPrompt((config, done) => {\n  // Add some logic here\n\n  return [`? My question ${input}`, `! The input must be a number`];\n});\n```\n\n### Typescript\n\nIf using typescript, `createPrompt` takes 2 generic arguments.\n\n```ts\n// createPrompt<Value, Config>\nconst input = createPrompt<string, { message: string }>(// ...\n```\n\nThe first one is the type of the resolved value\n\n```ts\nconst answer: string = await input();\n```\n\nThe second one is the type of the prompt config; in other words the interface the created prompt will provide to users.\n\n```ts\nconst answer = await input({\n  message: 'My question',\n});\n```\n\n## Key utilities\n\nListening for keypress events inside an inquirer prompt is a very common pattern. To ease this, we export a few utility functions taking in the keypress event object and return a boolean:\n\n- `isEnterKey()`\n- `isBackspaceKey()`\n- `isSpaceKey()`\n- `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`)\n- `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`)\n- `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0\n\nSet `INQUIRER_KEYBINDINGS=vim`, `INQUIRER_KEYBINDINGS=emacs`, or `INQUIRER_KEYBINDINGS=vim,emacs` to enable alternative navigation keybindings globally. Prompt-level `theme.keybindings` values override the environment variable.\n\n## Theming\n\nTheming utilities will allow you to expose customization of the prompt style. Inquirer also has a few standard theme values shared across all the official prompts.\n\nTo allow standard customization:\n\n```ts\nimport { createPrompt, usePrefix, makeTheme, type Theme } from '@inquirer/core';\nimport type { PartialDeep } from '@inquirer/type';\n\ntype PromptConfig = {\n  theme?: PartialDeep<Theme>;\n};\n\nexport default createPrompt<string, PromptConfig>((config, done) => {\n  const theme = makeTheme(config.theme);\n\n  const prefix = usePrefix({ status, theme });\n\n  return `${prefix} ${theme.style.highlight('hello')}`;\n});\n```\n\nTo setup a custom theme:\n\n```ts\nimport { createPrompt, makeTheme, type Theme } from '@inquirer/core';\nimport type { PartialDeep } from '@inquirer/type';\n\ntype PromptTheme = {};\n\nconst promptTheme: PromptTheme = {\n  icon: '!',\n};\n\ntype PromptConfig = {\n  theme?: PartialDeep<Theme<PromptTheme>>;\n};\n\nexport default createPrompt<string, PromptConfig>((config, done) => {\n  const theme = makeTheme(promptTheme, config.theme);\n\n  const prefix = usePrefix({ status, theme });\n\n  return `${prefix} ${theme.icon}`;\n});\n```\n\nThe [default theme keys cover](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/src/lib/theme.ts):\n\n```ts\ntype DefaultTheme = {\n  prefix: string | { idle: string; done: string };\n  spinner: {\n    interval: number;\n    frames: string[];\n  };\n  keybindings: readonly ('emacs' | 'vim')[];\n  style: {\n    answer: (text: string) => string;\n    message: (text: string, status: 'idle' | 'done' | 'loading') => string;\n    error: (text: string) => string;\n    defaultAnswer: (text: string) => string;\n    help: (text: string) => string;\n    highlight: (text: string) => string;\n    key: (text: string) => string;\n  };\n};\n```\n\n# Examples\n\nYou can refer to any `@inquirer/prompts` prompts for real examples:\n\n- [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/confirm/src/index.ts)\n- [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/input/src/index.ts)\n- [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/password/src/index.ts)\n- [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/editor/src/index.ts)\n- [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/select/src/index.ts)\n- [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/checkbox/src/index.ts)\n- [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/rawlist/src/index.ts)\n- [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/expand/src/index.ts)\n\n```ts\nimport { styleText } from 'node:util';\nimport {\n  createPrompt,\n  useState,\n  useKeypress,\n  isEnterKey,\n  usePrefix,\n  type Status,\n} from '@inquirer/core';\n\nconst confirm = createPrompt<boolean, { message: string; default?: boolean }>(\n  (config, done) => {\n    const [status, setStatus] = useState<Status>('idle');\n    const [value, setValue] = useState('');\n    const prefix = usePrefix({});\n\n    useKeypress((key, rl) => {\n      if (isEnterKey(key)) {\n        const answer = value ? /^y(es)?/i.test(value) : config.default !== false;\n        setValue(answer ? 'yes' : 'no');\n        setStatus('done');\n        done(answer);\n      } else {\n        setValue(rl.line);\n      }\n    });\n\n    let formattedValue = value;\n    let defaultValue = '';\n    if (status === 'done') {\n      formattedValue = styleText('cyan', value);\n    } else {\n      defaultValue = styleText('dim', config.default === false ? ' (y/N)' : ' (Y/n)');\n    }\n\n    const message = styleText('bold', config.message);\n    return `${prefix} ${message}${defaultValue} ${formattedValue}`;\n  },\n);\n\n/**\n *  Which then can be used like this:\n */\nconst answer = await confirm({ message: 'Do you want to continue?' });\n```\n\n# License\n\nCopyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>\nLicensed under the MIT license.\n","publish_time":1721162815220,"maintainers":[{"name":"sboudrias","email":"admin@simonboudrias.com"},{"name":"danielchatfield","email":"chatfielddaniel@gmail.com"},{"name":"mischah","email":"mail@michael-kuehnel.de"}],"_cnpm_publish_time":1721162815220,"dist-tags":{"latest":"12.1.0"}}