-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive.js
235 lines (197 loc) · 5.57 KB
/
interactive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const interactive = require("inquirer")
const safeEval = require('safe-eval')
const { Options, getOption } = require("./options")
const { CUSTOM_ARR_METHODS_NAMES, CUSTOM_OBJ_METHODS_NAMES } = require("./custom")
const grayCode = ' \x1b[90m'; //keep space at the beginning
const yellowCode = '\x1b[33m';
const resetCode = '\x1b[0m';
const funcPrefix = `[func] .`
const funcPostfix = `()`
const indexPrefix = `[idx] `
const propertyPrefix = `[prop] `
// array methods that are not available in interactive mode
const UNAVAILABLE_ARRAY_METHODS = [
"entries", // returns an iterator
"toString", // useless
"copyWithin", // adds a "costructor" to the array
"fill", // adds a "costructor" to the array
"pop", // useless
"shift", // useless
"unshift", // useless
"push", // useless
"forEach", // useless
"values", // returns an iterator
"keys", // returns an iterator
"toLocaleString", // useless
"toReversed", // useless
"toSpliced", // useless
"toSorted", // useless
]
// objects and arrays methods that don't require arguments
const NO_ARGS_METHODS = [
"listEntries",
"listValues",
"listKeys",
"compact",
"reverse",
]
const REQUIRED_ARGS_METHODS = [
"every",
"filter",
"find",
"findIndex",
"findLast",
"findLastIndex",
"flatMap",
"map",
"reduce",
"reduceRight",
"some",
]
module.exports = runInteractive
async function runInteractive(OBJECT) {
let current = OBJECT
let path = ""
let type
do {
const question = {
name: "jsjq",
type: "list",
prefix: ""
}
switch (typeof current) {
case "bigint":
case "number":
case "boolean":
case "string":
return current
case "object":
question.choices = ["!exit", "!print"]
if (Array.isArray(current)) {
if (current.length === 0) {
return current
}
type = "array"
question.choices.push(...Object.entries(current).map(([idx, v]) => `${indexPrefix}${idx}${formatKeyContent(v)}`))
question.choices.push(...Object.getOwnPropertyNames(Array.prototype)
.filter(p => !UNAVAILABLE_ARRAY_METHODS.includes(p))
.filter(p => p !== "length")
.map(p => `${funcPrefix}${p}${funcPostfix}`))
question.choices.push("[prop] .length")
for (const n of CUSTOM_ARR_METHODS_NAMES) {
question.choices.push(`${funcPrefix}${n}${funcPostfix}`)
}
} else {
if (current === null) {
return null
}
//prune custom properties
if (Object.keys(current).length === 0) {
return current
}
type = "object"
question.choices.push(...Object.entries(current).map(([k, v]) => `${propertyPrefix}${k}${formatKeyContent(v)}`))
for (const n of CUSTOM_OBJ_METHODS_NAMES) {
if (!question.choices.find(x => x.startsWith(`${propertyPrefix}${n}`))) {
question.choices.push(`${funcPrefix}${n}${funcPostfix}`)
}
}
}
question.message = `${yellowCode}[${type}]${resetCode} ` + path
removeFromArray(question.choices, `${funcPrefix}constructor${funcPostfix}`)
question.choices.sort()
break
case "undefined":
return undefined
default:
throw Error("unexpected type: " + typeof current)
}
// select property/index/function
let resp = (await interactive.prompt([question]))["jsjq"]
// check macros
if (resp == "[prop] .length") return current.length
if (resp == "!print") return current
if (resp == "!exit") process.exit(0)
// process choice
if (type == "array") {
if (resp.startsWith(funcPrefix)) { // is an array method
const funcName = pruneChoiceText(resp, funcPrefix, funcPostfix)
const { result, fnCall } = await runFunction(current, funcName)
transformed = true
current = result
path += fnCall
} else { // is an array index
const idx = pruneChoiceText(resp, indexPrefix)
path += `[${idx}]`
current = current.at(idx)
}
} else { // object
if (resp.startsWith(funcPrefix)) { //object method
const funcName = pruneChoiceText(resp, funcPrefix, funcPostfix)
const { result, fnCall } = await runFunction(current, funcName)
transformed = true
current = result
path += fnCall
} else { // is an object property
const prop = pruneChoiceText(resp, propertyPrefix)
path += `.${prop}`
current = current[prop]
}
}
} while (true)
};
async function runFunction(object, name) {
let body = ""
if (!NO_ARGS_METHODS.includes(name)) {
body = (await interactive.prompt([{
name: "jsjq",
message: `${yellowCode}[func]${resetCode} ${name}():`,
prefix: ""
}]))["jsjq"]
}
if (body == "" && REQUIRED_ARGS_METHODS.includes(name)) {
throw Error(`method .${name}() requires arguments`)
}
let fnCall = `.${name}(${body})`
const code = `OBJECT${fnCall}`
return {
result: safeEval(code, { OBJECT: object }),
fnCall
}
}
function removeFromArray(arr, value) {
const index = arr.indexOf(value);
if (index !== -1) {
arr.splice(index, 1);
}
}
function pruneChoiceText(choice, prefix, postFix = undefined) {
const pIdx = choice.indexOf(`${grayCode}`)
if (postFix !== undefined) {
choice = choice.slice(undefined, -postFix.length)
}
if (pIdx == -1) {
return choice.slice(prefix.length)
}
return choice.slice(undefined, pIdx).slice(prefix.length)
}
function formatKeyContent(content) {
let c
const maxLen = 30
if (typeof content == "object") {
const stringified = JSON.stringify(content)
c = stringified.slice(0, maxLen)
if (stringified.length > maxLen) {
c += "…"
}
} else if (typeof content == "string") {
c = '"' + content.slice(0, maxLen) + '"'
if (content.length > maxLen) {
c.slice(undefined, -1)
c += "…\""
}
} else {
c = content
}
return `${grayCode}${c}${resetCode}`
}