@nan0web/ui-cli 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +20 -0
- package/CONTRIBUTING.md +42 -0
- package/LICENSE +15 -0
- package/README.md +277 -0
- package/docs/uk/README.md +294 -0
- package/package.json +38 -0
- package/playground/forms/addressForm.js +37 -0
- package/playground/forms/ageForm.js +26 -0
- package/playground/forms/profileForm.js +33 -0
- package/playground/forms/userForm.js +36 -0
- package/playground/main.js +81 -0
- package/playground/vocabs/en.js +25 -0
- package/playground/vocabs/index.js +12 -0
- package/playground/vocabs/uk.js +25 -0
- package/src/InputAdapter.js +219 -0
- package/src/InputAdapter.test.js +117 -0
- package/src/README.md.js +459 -0
- package/src/index.js +25 -0
- package/src/ui/index.js +4 -0
- package/src/ui/input.js +63 -0
- package/src/ui/input.test.js +27 -0
- package/src/ui/next.js +70 -0
- package/src/ui/select.js +58 -0
- package/src/ui/select.test.js +34 -0
- package/system.md +99 -0
- package/tsconfig.json +23 -0
- package/types/InputAdapter.d.ts +106 -0
- package/types/README.md.d.ts +1 -0
- package/types/index.d.ts +11 -0
- package/types/test/ReadLine.d.ts +1 -0
- package/types/ui/errors.d.ts +3 -0
- package/types/ui/index.d.ts +4 -0
- package/types/ui/input.d.ts +15 -0
- package/types/ui/next.d.ts +12 -0
- package/types/ui/select.d.ts +30 -0
package/src/README.md.js
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { describe, it, before, beforeEach } from "node:test"
|
|
2
|
+
import assert from "node:assert/strict"
|
|
3
|
+
import FS from "@nan0web/db-fs"
|
|
4
|
+
import { NoConsole } from "@nan0web/log"
|
|
5
|
+
import {
|
|
6
|
+
DatasetParser,
|
|
7
|
+
DocsParser,
|
|
8
|
+
runSpawn,
|
|
9
|
+
} from "@nan0web/test"
|
|
10
|
+
import {
|
|
11
|
+
CLIInputAdapter as BaseCLIInputAdapter,
|
|
12
|
+
CancelError,
|
|
13
|
+
createInput,
|
|
14
|
+
ask as baseAsk,
|
|
15
|
+
Input,
|
|
16
|
+
select as baseSelect,
|
|
17
|
+
next as baseNext,
|
|
18
|
+
pause,
|
|
19
|
+
} from "./index.js"
|
|
20
|
+
import { UIForm } from "@nan0web/ui"
|
|
21
|
+
import Message from "@nan0web/co"
|
|
22
|
+
|
|
23
|
+
async function ask(question) {
|
|
24
|
+
if ("Full Name *: " === question) return "John Doe"
|
|
25
|
+
if ("Email *: " === question) return "John.Doe@example.com"
|
|
26
|
+
if ("What is your name?" === question) return "Alice"
|
|
27
|
+
return ""
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function select(config) {
|
|
31
|
+
if ("Choose Language:" === config.title) return { index: 0, value: "en" }
|
|
32
|
+
if ("Choose an option:" === config.title) return { index: 2, value: "Option B" }
|
|
33
|
+
|
|
34
|
+
return { index: -1, value: null }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function next() {
|
|
38
|
+
return Promise.resolve(" ")
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
class CLIInputAdapter extends BaseCLIInputAdapter {
|
|
42
|
+
async ask(question) {
|
|
43
|
+
return await ask(question)
|
|
44
|
+
}
|
|
45
|
+
async select(config) {
|
|
46
|
+
return await select(config)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const fs = new FS()
|
|
51
|
+
let pkg
|
|
52
|
+
|
|
53
|
+
// Load package.json once before tests
|
|
54
|
+
before(async () => {
|
|
55
|
+
const doc = await fs.loadDocument("package.json", {})
|
|
56
|
+
pkg = doc || {}
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
let console = new NoConsole()
|
|
60
|
+
|
|
61
|
+
beforeEach((info) => {
|
|
62
|
+
console = new NoConsole()
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Core test suite that also serves as the source for README generation.
|
|
67
|
+
*
|
|
68
|
+
* The block comments inside each `it` block are extracted to build
|
|
69
|
+
* the final `README.md`. Keeping the comments here ensures the
|
|
70
|
+
* documentation stays close to the code.
|
|
71
|
+
*/
|
|
72
|
+
function testRender() {
|
|
73
|
+
/**
|
|
74
|
+
* @docs
|
|
75
|
+
* # @nan0web/ui-cli
|
|
76
|
+
*
|
|
77
|
+
* A tiny, zero‑dependency UI input adapter for Java•Script projects.
|
|
78
|
+
* It provides a CLI implementation that can be easily integrated
|
|
79
|
+
* with application logic.
|
|
80
|
+
*
|
|
81
|
+
* <!-- %PACKAGE_STATUS% -->
|
|
82
|
+
*
|
|
83
|
+
* ## Description
|
|
84
|
+
*
|
|
85
|
+
* The `@nan0web/ui-cli` package provides a set of tools for handling
|
|
86
|
+
* CLI user input through structured forms, selections and prompts.
|
|
87
|
+
* It uses an adapter pattern to seamlessly integrate with application data models.
|
|
88
|
+
*
|
|
89
|
+
* Core classes:
|
|
90
|
+
*
|
|
91
|
+
* - `CLIInputAdapter` — handles form, input, and select requests in CLI.
|
|
92
|
+
* - `Input` — wraps user input with value and cancellation status.
|
|
93
|
+
* - `CancelError` — thrown when a user cancels an operation.
|
|
94
|
+
*
|
|
95
|
+
* These classes are perfect for building prompts, wizards, forms,
|
|
96
|
+
* and interactive CLI tools with minimal overhead.
|
|
97
|
+
*
|
|
98
|
+
* ## Installation
|
|
99
|
+
*/
|
|
100
|
+
it("How to install with npm?", () => {
|
|
101
|
+
/**
|
|
102
|
+
* ```bash
|
|
103
|
+
* npm install @nan0web/ui-cli
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
assert.equal(pkg.name, "@nan0web/ui-cli")
|
|
107
|
+
})
|
|
108
|
+
/**
|
|
109
|
+
* @docs
|
|
110
|
+
*/
|
|
111
|
+
it("How to install with pnpm?", () => {
|
|
112
|
+
/**
|
|
113
|
+
* ```bash
|
|
114
|
+
* pnpm add @nan0web/ui-cli
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
assert.equal(pkg.name, "@nan0web/ui-cli")
|
|
118
|
+
})
|
|
119
|
+
/**
|
|
120
|
+
* @docs
|
|
121
|
+
*/
|
|
122
|
+
it("How to install with yarn?", () => {
|
|
123
|
+
/**
|
|
124
|
+
* ```bash
|
|
125
|
+
* yarn add @nan0web/ui-cli
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
assert.equal(pkg.name, "@nan0web/ui-cli")
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @docs
|
|
133
|
+
* ## Usage
|
|
134
|
+
*
|
|
135
|
+
* ### CLIInputAdapter
|
|
136
|
+
*
|
|
137
|
+
* The adapter provides methods to handle form, input, and select requests.
|
|
138
|
+
*
|
|
139
|
+
* #### requestForm(form, options)
|
|
140
|
+
*
|
|
141
|
+
* Displays a form and collects user input field-by-field with validation.
|
|
142
|
+
*/
|
|
143
|
+
it("How to request form input via CLIInputAdapter?", async () => {
|
|
144
|
+
//import { CLIInputAdapter } from '@nan0web/ui-cli'
|
|
145
|
+
const adapter = new CLIInputAdapter()
|
|
146
|
+
const fields = [
|
|
147
|
+
{ name: "name", label: "Full Name", required: true },
|
|
148
|
+
{ name: "email", label: "Email", type: "email", required: true },
|
|
149
|
+
]
|
|
150
|
+
const validateValue = (name, value) => {
|
|
151
|
+
if (name === "email" && !value.includes("@")) {
|
|
152
|
+
return { isValid: false, errors: { email: "Invalid email" } }
|
|
153
|
+
}
|
|
154
|
+
return { isValid: true, errors: {} }
|
|
155
|
+
}
|
|
156
|
+
const setData = (data) => {
|
|
157
|
+
const newForm = { ...form }
|
|
158
|
+
newForm.state = data
|
|
159
|
+
return newForm
|
|
160
|
+
}
|
|
161
|
+
const form = UIForm.from({
|
|
162
|
+
title: "User Profile",
|
|
163
|
+
fields,
|
|
164
|
+
id: "user-profile-form",
|
|
165
|
+
validateValue,
|
|
166
|
+
setData,
|
|
167
|
+
state: {},
|
|
168
|
+
validate: () => ({ isValid: true, errors: {} }),
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
const result = await adapter.requestForm(form, { silent: true })
|
|
172
|
+
|
|
173
|
+
console.info(result.form.state) // ← { name: "John Doe", email: "John.Doe@example.com" }
|
|
174
|
+
assert.deepStrictEqual(console.output()[0][1], { name: "John Doe", email: "John.Doe@example.com" })
|
|
175
|
+
})
|
|
176
|
+
/**
|
|
177
|
+
* @docs
|
|
178
|
+
*/
|
|
179
|
+
it("How to request select input via CLIInputAdapter?", async () => {
|
|
180
|
+
//import { CLIInputAdapter } from '@nan0web/ui-cli'
|
|
181
|
+
const adapter = new CLIInputAdapter()
|
|
182
|
+
const config = {
|
|
183
|
+
title: "Choose Language:",
|
|
184
|
+
prompt: "Language (1-2): ",
|
|
185
|
+
id: "language-select",
|
|
186
|
+
options: new Map([
|
|
187
|
+
["en", "English"],
|
|
188
|
+
["uk", "Ukrainian"],
|
|
189
|
+
]),
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const result = await adapter.requestSelect(config)
|
|
193
|
+
console.info(result.value) // ← Message { body: "en", head: {} }
|
|
194
|
+
assert.deepStrictEqual(console.output()[0][1], Message.from({ body: "en" }))
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* @docs
|
|
199
|
+
* ### Input Utilities
|
|
200
|
+
*
|
|
201
|
+
* #### `Input` class
|
|
202
|
+
*
|
|
203
|
+
* Holds user input and tracks cancelation events.
|
|
204
|
+
*/
|
|
205
|
+
it("How to use the Input class?", () => {
|
|
206
|
+
//import { Input } from '@nan0web/ui-cli'
|
|
207
|
+
const input = new Input({ value: "test", stops: ["quit"] })
|
|
208
|
+
console.info(String(input)) // ← test
|
|
209
|
+
console.info(input.value) // ← test
|
|
210
|
+
console.info(input.cancelled) // ← false
|
|
211
|
+
|
|
212
|
+
input.value = "quit"
|
|
213
|
+
console.info(input.cancelled) // ← true
|
|
214
|
+
assert.equal(console.output()[0][1], "test")
|
|
215
|
+
assert.equal(console.output()[1][1], "test")
|
|
216
|
+
assert.equal(console.output()[2][1], false)
|
|
217
|
+
assert.equal(console.output()[3][1], true)
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* @docs
|
|
222
|
+
* #### `ask(question)`
|
|
223
|
+
*
|
|
224
|
+
* Prompts the user with a question and returns a promise with the answer.
|
|
225
|
+
*/
|
|
226
|
+
it("How to ask a question with ask()?", async () => {
|
|
227
|
+
//import { ask } from "@nan0web/ui-cli"
|
|
228
|
+
|
|
229
|
+
const result = await ask("What is your name?")
|
|
230
|
+
console.info(result)
|
|
231
|
+
assert.equal(console.output()[0][1], "Alice")
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @docs
|
|
236
|
+
* #### `createInput(stops)`
|
|
237
|
+
*
|
|
238
|
+
* Creates a configurable input handler with stop keywords.
|
|
239
|
+
*/
|
|
240
|
+
it("How to use createInput handler?", () => {
|
|
241
|
+
//import { createInput } from '@nan0web/ui-cli'
|
|
242
|
+
const handler = createInput(["cancel"])
|
|
243
|
+
console.info(typeof handler === "function") // ← true
|
|
244
|
+
assert.equal(console.output()[0][1], true)
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* @docs
|
|
249
|
+
* #### `select(config)`
|
|
250
|
+
*
|
|
251
|
+
* Presents options to the user and returns a promise with selection.
|
|
252
|
+
*/
|
|
253
|
+
it("How to prompt user with select()?", async () => {
|
|
254
|
+
//import { select } from '@nan0web/ui-cli'
|
|
255
|
+
const config = {
|
|
256
|
+
title: "Choose an option:",
|
|
257
|
+
prompt: "Selection (1-3): ",
|
|
258
|
+
options: ["Option A", "Option B", "Option C"],
|
|
259
|
+
console: console,
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const result = await select(config)
|
|
263
|
+
console.info(result.value)
|
|
264
|
+
assert.equal(console.output()[0][1], "Option B")
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* @docs
|
|
269
|
+
* #### `next(conf)`
|
|
270
|
+
*
|
|
271
|
+
* Waits for a keypress to continue the process.
|
|
272
|
+
*/
|
|
273
|
+
it("How to pause and wait for keypress with next()?", async () => {
|
|
274
|
+
//import { next } from '@nan0web/ui-cli'
|
|
275
|
+
|
|
276
|
+
const result = await next()
|
|
277
|
+
console.info(typeof result === "string")
|
|
278
|
+
assert.equal(console.output()[0][1], true)
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* @docs
|
|
283
|
+
* #### `pause(ms)`
|
|
284
|
+
*
|
|
285
|
+
* Returns a promise that resolves after a given delay.
|
|
286
|
+
*/
|
|
287
|
+
it("How to delay execution with pause()?", async () => {
|
|
288
|
+
//import { pause } from '@nan0web/ui-cli'
|
|
289
|
+
const before = Date.now()
|
|
290
|
+
await pause(10)
|
|
291
|
+
const after = Date.now()
|
|
292
|
+
console.info(after - before >= 10) // ← true
|
|
293
|
+
assert.equal(console.output()[0][1], true)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* @docs
|
|
298
|
+
* ### Errors
|
|
299
|
+
*
|
|
300
|
+
* #### `CancelError`
|
|
301
|
+
*
|
|
302
|
+
* Thrown when a user interrupts a process.
|
|
303
|
+
*/
|
|
304
|
+
it("How to handle CancelError?", () => {
|
|
305
|
+
//import { CancelError } from '@nan0web/ui-cli'
|
|
306
|
+
const error = new CancelError()
|
|
307
|
+
console.error(error.message) // ← Operation cancelled by user
|
|
308
|
+
assert.equal(console.output()[0][1], "Operation cancelled by user")
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* @docs
|
|
313
|
+
* ## API
|
|
314
|
+
*
|
|
315
|
+
* ### CLIInputAdapter
|
|
316
|
+
*
|
|
317
|
+
* * **Methods**
|
|
318
|
+
* * `requestForm(form, options)` — (async) handles form request
|
|
319
|
+
* * `requestSelect(config)` — (async) handles selection prompt
|
|
320
|
+
* * `requestInput(config)` — (async) handles single input prompt
|
|
321
|
+
*
|
|
322
|
+
* ### Input
|
|
323
|
+
*
|
|
324
|
+
* * **Properties**
|
|
325
|
+
* * `value` – (string) current input value.
|
|
326
|
+
* * `stops` – (array) cancellation keywords.
|
|
327
|
+
* * `cancelled` – (boolean) whether input is cancelled.
|
|
328
|
+
*
|
|
329
|
+
* * **Methods**
|
|
330
|
+
* * `toString()` – returns current value as string.
|
|
331
|
+
* * `static from(input)` – instantiates from input object.
|
|
332
|
+
*
|
|
333
|
+
* ### ask(question)
|
|
334
|
+
*
|
|
335
|
+
* * **Parameters**
|
|
336
|
+
* * `question` (string) – prompt text
|
|
337
|
+
* * **Returns** Promise<string>
|
|
338
|
+
*
|
|
339
|
+
* ### createInput(stops)
|
|
340
|
+
*
|
|
341
|
+
* * **Parameters**
|
|
342
|
+
* * `stops` (array) – stop values
|
|
343
|
+
* * **Returns** function handler
|
|
344
|
+
*
|
|
345
|
+
* ### select(config)
|
|
346
|
+
*
|
|
347
|
+
* * **Parameters**
|
|
348
|
+
* * `config.title` (string) – selection title
|
|
349
|
+
* * `config.prompt` (string) – prompt text
|
|
350
|
+
* * `config.options` (array | Map) – options to choose from
|
|
351
|
+
* * **Returns** Promise<{ index, value }>
|
|
352
|
+
*
|
|
353
|
+
* ### next([conf])
|
|
354
|
+
*
|
|
355
|
+
* * **Parameters**
|
|
356
|
+
* * `conf` (string) – accepted key sequence
|
|
357
|
+
* * **Returns** Promise<string>
|
|
358
|
+
*
|
|
359
|
+
* ### pause(ms)
|
|
360
|
+
*
|
|
361
|
+
* * **Parameters**
|
|
362
|
+
* * `ms` (number) – delay in milliseconds
|
|
363
|
+
* * **Returns** Promise<void>
|
|
364
|
+
*
|
|
365
|
+
* ### CancelError
|
|
366
|
+
*
|
|
367
|
+
* Extends `Error`, thrown when an input is cancelled.
|
|
368
|
+
*/
|
|
369
|
+
it("All exported classes and functions should pass basic tests", () => {
|
|
370
|
+
assert.ok(CLIInputAdapter)
|
|
371
|
+
assert.ok(CancelError)
|
|
372
|
+
assert.ok(createInput)
|
|
373
|
+
assert.ok(baseAsk)
|
|
374
|
+
assert.ok(Input)
|
|
375
|
+
assert.ok(baseSelect)
|
|
376
|
+
assert.ok(baseNext)
|
|
377
|
+
assert.ok(pause)
|
|
378
|
+
})
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* @docs
|
|
382
|
+
* ## Java•Script
|
|
383
|
+
*/
|
|
384
|
+
it("Uses `d.ts` files for autocompletion", () => {
|
|
385
|
+
assert.equal(pkg.types, "types/index.d.ts")
|
|
386
|
+
})
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* @docs
|
|
390
|
+
* ## Playground
|
|
391
|
+
*
|
|
392
|
+
*/
|
|
393
|
+
it("How to run playground script?", async () => {
|
|
394
|
+
/**
|
|
395
|
+
* ```bash
|
|
396
|
+
* # Clone the repository and run the CLI playground
|
|
397
|
+
* git clone https://github.com/nan0web/ui-cli.git
|
|
398
|
+
* cd ui-cli
|
|
399
|
+
* npm install
|
|
400
|
+
* npm run playground
|
|
401
|
+
* ```
|
|
402
|
+
*/
|
|
403
|
+
assert.ok(String(pkg.scripts?.playground))
|
|
404
|
+
const response = await runSpawn("git", ["remote", "get-url", "origin"], { timeout: 2_000 })
|
|
405
|
+
if (response.code === 0) {
|
|
406
|
+
assert.ok(response.text.trim().endsWith(":nan0web/ui-cli.git"))
|
|
407
|
+
} else {
|
|
408
|
+
// git command may fail if not in a repo or no remote, skip assertion
|
|
409
|
+
console.warn("Git command skipped due to non-zero exit code or timeout.")
|
|
410
|
+
}
|
|
411
|
+
})
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* @docs
|
|
415
|
+
* ## Contributing
|
|
416
|
+
*/
|
|
417
|
+
it("How to contribute? - [check here](./CONTRIBUTING.md)", async () => {
|
|
418
|
+
assert.equal(pkg.scripts?.precommit, "npm test")
|
|
419
|
+
assert.equal(pkg.scripts?.prepush, "npm test")
|
|
420
|
+
assert.equal(pkg.scripts?.prepare, "husky")
|
|
421
|
+
try {
|
|
422
|
+
const text = await fs.loadDocument("CONTRIBUTING.md")
|
|
423
|
+
const str = String(text)
|
|
424
|
+
assert.ok(str.includes("# Contributing"))
|
|
425
|
+
} catch (e) {
|
|
426
|
+
console.warn("Contributing file test skipped because CONTRIBUTING.md is not present.")
|
|
427
|
+
}
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* @docs
|
|
432
|
+
* ## License
|
|
433
|
+
*/
|
|
434
|
+
it("How to license ISC? - [check here](./LICENSE)", async () => {
|
|
435
|
+
try {
|
|
436
|
+
const text = await fs.loadDocument("LICENSE")
|
|
437
|
+
assert.ok(String(text).includes("ISC"))
|
|
438
|
+
} catch (e) {
|
|
439
|
+
console.warn("License test skipped because LICENSE is not present.")
|
|
440
|
+
}
|
|
441
|
+
})
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
describe("README.md testing", testRender)
|
|
445
|
+
|
|
446
|
+
describe("Rendering README.md", async () => {
|
|
447
|
+
let text = ""
|
|
448
|
+
const format = new Intl.NumberFormat("en-US").format
|
|
449
|
+
const parser = new DocsParser()
|
|
450
|
+
text = String(parser.decode(testRender))
|
|
451
|
+
await fs.saveDocument("README.md", text)
|
|
452
|
+
const dataset = DatasetParser.parse(text, pkg.name)
|
|
453
|
+
await fs.saveDocument(".datasets/README.dataset.jsonl", dataset)
|
|
454
|
+
|
|
455
|
+
it(`document is rendered in README.md [${format(Buffer.byteLength(text))}b]`, async () => {
|
|
456
|
+
const text = await fs.loadDocument("README.md")
|
|
457
|
+
assert.ok(text.includes("## License"))
|
|
458
|
+
})
|
|
459
|
+
})
|
package/src/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import CLIInputAdapter from './InputAdapter.js'
|
|
2
|
+
import { select, next, pause, createInput, ask, Input } from './ui/index.js'
|
|
3
|
+
import { CancelError } from '@nan0web/ui/core'
|
|
4
|
+
|
|
5
|
+
// Export CLI input adapter
|
|
6
|
+
export {
|
|
7
|
+
CLIInputAdapter,
|
|
8
|
+
CancelError,
|
|
9
|
+
createInput,
|
|
10
|
+
ask,
|
|
11
|
+
Input,
|
|
12
|
+
select,
|
|
13
|
+
next,
|
|
14
|
+
pause,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Export renderers for CLI components
|
|
18
|
+
export const renderers = new Map([
|
|
19
|
+
['UIProcess', (data) => {
|
|
20
|
+
// Render process information in CLI
|
|
21
|
+
return `${data.title || 'Process'}: ${data.status || 'running'}`
|
|
22
|
+
}],
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
export default CLIInputAdapter
|
package/src/ui/index.js
ADDED
package/src/ui/input.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createInterface } from "node:readline"
|
|
2
|
+
import { stdin, stdout } from "node:process"
|
|
3
|
+
|
|
4
|
+
export class Input {
|
|
5
|
+
value = ""
|
|
6
|
+
stops = []
|
|
7
|
+
#cancelled = false
|
|
8
|
+
constructor(input = {}) {
|
|
9
|
+
const {
|
|
10
|
+
value = this.value,
|
|
11
|
+
cancelled = this.#cancelled,
|
|
12
|
+
stops = [],
|
|
13
|
+
} = input
|
|
14
|
+
this.value = String(value)
|
|
15
|
+
this.stops = stops.map(String)
|
|
16
|
+
this.#cancelled = Boolean(cancelled)
|
|
17
|
+
}
|
|
18
|
+
get cancelled() {
|
|
19
|
+
return this.#cancelled || this.stops.includes(this.value)
|
|
20
|
+
}
|
|
21
|
+
toString() {
|
|
22
|
+
return this.value
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Helper to ask a question
|
|
28
|
+
* @param {string} question
|
|
29
|
+
*/
|
|
30
|
+
export function ask(question) {
|
|
31
|
+
return new Promise(resolve => {
|
|
32
|
+
const rl = createInterface({ input: stdin, output: stdout, terminal: true })
|
|
33
|
+
rl.question(question, answer => {
|
|
34
|
+
rl.close()
|
|
35
|
+
resolve(answer.trim())
|
|
36
|
+
})
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function createInput(stops = []) {
|
|
41
|
+
const input = new Input({ stops })
|
|
42
|
+
/**
|
|
43
|
+
* @param {string} question
|
|
44
|
+
* @param {Function | boolean} [loop=false]
|
|
45
|
+
* @param {Function | false} [nextQuestion=false]
|
|
46
|
+
* @returns {Promise<Input>}
|
|
47
|
+
*/
|
|
48
|
+
async function fn(question, loop = false, nextQuestion = false) {
|
|
49
|
+
while (true) {
|
|
50
|
+
input.value = await ask(question)
|
|
51
|
+
if (false === loop || input.cancelled) return input
|
|
52
|
+
if (true === loop && input.value) return input
|
|
53
|
+
if ("function" === typeof loop) {
|
|
54
|
+
if (!loop(input)) return input
|
|
55
|
+
}
|
|
56
|
+
if ("string" === typeof nextQuestion) question = nextQuestion
|
|
57
|
+
if ("function" === typeof nextQuestion) question = nextQuestion(input)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return fn
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export default createInput
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, it } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { Input, ask, createInput } from './input.js'
|
|
4
|
+
|
|
5
|
+
describe('Input utilities', () => {
|
|
6
|
+
it('should create Input instance', () => {
|
|
7
|
+
const input = new Input()
|
|
8
|
+
assert.equal(input.value, '')
|
|
9
|
+
assert.equal(input.cancelled, false)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('should handle cancellation stops', () => {
|
|
13
|
+
const input = new Input({ stops: ['quit'] })
|
|
14
|
+
input.value = 'quit'
|
|
15
|
+
assert.equal(input.cancelled, true)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('should create input handler', () => {
|
|
19
|
+
const handler = createInput()
|
|
20
|
+
assert.equal(typeof handler, 'function')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('should create input handler with stops', () => {
|
|
24
|
+
const handler = createInput(['exit'])
|
|
25
|
+
assert.equal(typeof handler, 'function')
|
|
26
|
+
})
|
|
27
|
+
})
|
package/src/ui/next.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import process from "node:process"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Make a pause.
|
|
5
|
+
* @param {number} ms - Amount in miliseconds
|
|
6
|
+
* @returns {Promise<void>}
|
|
7
|
+
*/
|
|
8
|
+
const pause = async (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Waits for the confirmation message (input) from user
|
|
12
|
+
* @param {string | string[] | undefined} conf - Confirmation message or one of messages if array or any if undefined.
|
|
13
|
+
* @returns {Promise<string>}
|
|
14
|
+
*/
|
|
15
|
+
const next = async (conf = undefined) => {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
if (process.stdin.isRaw) {
|
|
18
|
+
reject(new Error('stdin is already in raw mode'))
|
|
19
|
+
return
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let buffer = ''
|
|
23
|
+
|
|
24
|
+
const onData = (chunk) => {
|
|
25
|
+
const str = chunk.toString()
|
|
26
|
+
buffer += str
|
|
27
|
+
|
|
28
|
+
// Будь-яка клавіша
|
|
29
|
+
if (conf === undefined) {
|
|
30
|
+
cleanup()
|
|
31
|
+
resolve(str)
|
|
32
|
+
}
|
|
33
|
+
else if (typeof conf === 'string') {
|
|
34
|
+
if (buffer === conf || buffer.endsWith(conf)) {
|
|
35
|
+
cleanup()
|
|
36
|
+
resolve(buffer)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (Array.isArray(conf)) {
|
|
40
|
+
for (const seq of conf) {
|
|
41
|
+
if (buffer === seq || buffer.endsWith(seq)) {
|
|
42
|
+
cleanup()
|
|
43
|
+
resolve(seq)
|
|
44
|
+
break
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const errorHandler = (err) => {
|
|
51
|
+
cleanup()
|
|
52
|
+
reject(err)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const cleanup = () => {
|
|
56
|
+
process.stdin.off('data', onData)
|
|
57
|
+
process.stdin.off('error', errorHandler)
|
|
58
|
+
process.stdin.setRawMode(false)
|
|
59
|
+
process.stdin.resume()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
process.stdin.setRawMode(true)
|
|
63
|
+
process.stdin.resume()
|
|
64
|
+
|
|
65
|
+
process.stdin.once('error', errorHandler)
|
|
66
|
+
process.stdin.on('data', onData)
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export { next, pause }
|
package/src/ui/select.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import createInput from "./input.js"
|
|
2
|
+
import { CancelError } from '@nan0web/ui/core'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Generic selection prompt for CLI.
|
|
6
|
+
* Automatically creates its own input handler.
|
|
7
|
+
*
|
|
8
|
+
* @param {Object} config
|
|
9
|
+
* @param {string} config.title - Title shown before the list (e.g. "Select currency:")
|
|
10
|
+
* @param {string} config.prompt - Main prompt text (e.g. "Choose (1-3): ")
|
|
11
|
+
* @param {string} [config.invalidPrompt] - Retry message when input is invalid
|
|
12
|
+
* @param {Array<string> | Map<string, string> | Array<{ label: string, value: string }>} config.options - List of displayable options
|
|
13
|
+
* @param {Object} config.console - Logger (console.info, console.error, etc.)
|
|
14
|
+
* @param {Function} [config.ask] - Input handler
|
|
15
|
+
*
|
|
16
|
+
* @returns {Promise<{ index: number, value: string | null }>} Selected option
|
|
17
|
+
* @throws {CancelError} if the user cancels
|
|
18
|
+
*/
|
|
19
|
+
export async function select({
|
|
20
|
+
title,
|
|
21
|
+
prompt,
|
|
22
|
+
invalidPrompt = "Invalid choice, try again: ",
|
|
23
|
+
options,
|
|
24
|
+
console,
|
|
25
|
+
ask = createInput(["0"]),
|
|
26
|
+
}) {
|
|
27
|
+
if (options instanceof Map) {
|
|
28
|
+
options = Array.from(options.entries()).map(([value, label]) => ({ label, value }))
|
|
29
|
+
}
|
|
30
|
+
if (!Array.isArray(options) || options.length === 0) {
|
|
31
|
+
throw new Error("Options array is required and must not be empty")
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @type {Array<{ label: string, value: string }>} */
|
|
35
|
+
const list = options.map(el => "string" === typeof el ? ({ label: el, value: el }) : el)
|
|
36
|
+
|
|
37
|
+
console.info(title)
|
|
38
|
+
list.forEach(({ label }, i) => {
|
|
39
|
+
console.info(` ${i + 1}) ${label}`)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
const input = await ask(prompt, (input) => {
|
|
43
|
+
const idx = Number(input.value) - 1
|
|
44
|
+
return idx < 0 || idx >= list.length
|
|
45
|
+
}, invalidPrompt)
|
|
46
|
+
|
|
47
|
+
if (input.cancelled) {
|
|
48
|
+
throw new CancelError()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const index = Number(input.value) - 1
|
|
52
|
+
return {
|
|
53
|
+
index,
|
|
54
|
+
value: list[index].value,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export default select
|