-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
197 lines (172 loc) · 6.85 KB
/
Copy pathutils.js
File metadata and controls
197 lines (172 loc) · 6.85 KB
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
import * as p from '@clack/prompts';
import pc from 'picocolors';
import { readFile } from 'fs/promises';
import { join } from 'path';
export const FIELD_TYPES = ['text', 'textarea', 'editor', 'email', 'bool', 'number', 'tel', 'password', 'select', 'color'];
export const TEXT_FIELD_TYPES = ['text', 'textarea', 'editor'];
export const rootDir = process.cwd();
// ── Back-navigation (backspace → ESC in non-text prompts) ────────────────────
let _textActive = false;
/** Drop-in for p.text that tracks when text input is active. */
export async function text(opts) {
_textActive = true;
try {
return await p.text(opts);
} finally {
_textActive = false;
}
}
/**
* Call once at startup. Converts backspace (0x7f) to ESC (0x1b) whenever a
* select/multiselect/confirm is active so the user can press backspace to go
* back one level. Has no effect during p.text prompts (tracked via `text()`).
*/
export function setupBackNavigation() {
process.stdin.prependListener('data', (chunk) => {
if (chunk.length >= 1 && chunk[0] === 0x03) {
p.outro(pc.dim('See you next time! 👋'));
process.exit(0);
}
if (!_textActive && chunk.length >= 1 && chunk[0] === 0x7f) {
chunk[0] = 0x1b;
}
});
}
export function toCamelCase(str) {
return str
.split(/[-_]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
}
export function toLowerCamelCase(str) {
const pascal = toCamelCase(str);
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
export function cancel(msg = 'Cancelled.') {
p.cancel(msg);
process.exit(0);
}
export async function fetchEditorPresets() {
const presets = [];
// From vendor rshop_admin.php — keys of TinyMCE.configs (excluding 'default')
try {
const adminContent = await readFile(
join(rootDir, 'vendor/rshop/admin/config/rshop_admin.php'), 'utf8'
);
const startIdx = adminContent.indexOf("'TinyMCE.configs'");
if (startIdx !== -1) {
const bracketIdx = adminContent.indexOf('[', startIdx);
let depth = 0;
let i = bracketIdx;
while (i < adminContent.length) {
if (adminContent[i] === '[') depth++;
else if (adminContent[i] === ']') {
depth--;
if (depth === 0) break;
} else if (depth === 1 && adminContent[i] === "'") {
const keyMatch = adminContent.slice(i).match(/^'([^']+)'\s*=>\s*\[/);
if (keyMatch && keyMatch[1] !== 'default') presets.push(keyMatch[1]);
}
i++;
}
}
} catch { /* file missing */ }
// From app rshop.php — 'TinyMCE.configs.{name}' => [ (array values, not scalar overrides)
try {
const appContent = await readFile(join(rootDir, 'config/rshop.php'), 'utf8');
const regex = /^'TinyMCE\.configs\.([^.']+)'\s*=>\s*\[/mg;
let match;
while ((match = regex.exec(appContent)) !== null) {
if (!presets.includes(match[1])) presets.push(match[1]);
}
} catch { /* file missing */ }
return presets;
}
export function validatePositiveInt(val) {
if (!val || !val.trim() || isNaN(Number(val)) || Number(val) <= 0)
return 'Enter a valid positive number';
}
function parseEnv(content) {
const result = {};
for (const line of content.split('\n')) {
const match = line.match(/^export\s+(\w+)=["']?([^"'\n#]*)["']?/);
if (match) result[match[1]] = match[2].trim().replace(/["']/g, '');
}
return result;
}
export async function getDbConfig() {
const envContent = await readFile(join(rootDir, 'config/.env'), 'utf8');
const env = parseEnv(envContent);
const { DB_HOST = '127.0.0.1', DB_PORT = '3306', DB_USER = 'root', DB_PASS = 'root', DB_NAME } = env;
return { DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME };
}
export function mysqlArgs({ DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME }, query) {
return [`-h${DB_HOST}`, `-P${DB_PORT}`, `-u${DB_USER}`, `-p${DB_PASS}`, DB_NAME, '-e', query, '--skip-column-names'];
}
export async function promptLimit(presets) {
const limitChoice = await p.select({
message: "What's the limit?",
options: [
...presets.map((n) => ({ value: String(n), label: String(n) })),
{ value: 'custom', label: 'Custom' },
],
});
if (p.isCancel(limitChoice)) cancel();
if (limitChoice === 'custom') {
const customLimit = await p.text({ message: 'Enter limit:', validate: validatePositiveInt });
if (p.isCancel(customLimit)) cancel();
return customLimit.trim();
}
return limitChoice;
}
export async function promptEditorPreset() {
const editorPresets = await fetchEditorPresets();
const presetChoice = await p.select({
message: 'Editor preset:',
options: [
...editorPresets.map((v) => ({ value: v, label: v })),
{ value: 'custom', label: 'Custom...' },
],
});
if (p.isCancel(presetChoice)) cancel();
if (presetChoice === 'custom') {
const customPreset = await p.text({
message: 'Preset name:',
validate: (val) => (!val || !val.trim() ? 'Required' : undefined),
});
if (p.isCancel(customPreset)) cancel();
return customPreset.trim();
}
return presetChoice;
}
export async function promptSelectOptions(initialOptions = []) {
const options = [...initialOptions];
if (options.length > 0) {
p.log.info(pc.cyan(`Current options: ${options.map((o) => `${o.key}=${o.value}`).join(', ')}`));
const keepExisting = await p.confirm({ message: 'Keep existing options?', initialValue: true });
if (p.isCancel(keepExisting)) cancel();
if (!keepExisting) options.length = 0;
}
let addOption = true;
while (addOption) {
const optionNum = options.length + 1;
const optionKey = await p.text({
message: `Select option ${optionNum} — key:`,
validate: (val) => {
if (!val || !val.trim()) return 'Key is required';
if (options.some((o) => o.key === val.trim())) return 'Key already used';
},
});
if (p.isCancel(optionKey)) cancel();
const optionLabel = await p.text({
message: `Select option ${optionNum} — label:`,
validate: (val) => (!val || !val.trim() ? 'Label is required' : undefined),
});
if (p.isCancel(optionLabel)) cancel();
options.push({ key: optionKey.trim(), value: optionLabel.trim() });
const more = await p.confirm({ message: 'Add another option?', initialValue: true });
if (p.isCancel(more)) cancel();
addOption = more;
}
return options;
}