-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathask.js
More file actions
executable file
·260 lines (221 loc) · 9.38 KB
/
ask.js
File metadata and controls
executable file
·260 lines (221 loc) · 9.38 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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env bun
const path = require('path');
const { query, startDaemon, stopAndWait, isDaemonDown } = require(path.join(__dirname, 'lib', 'client'));
const { CMD_STOP, CMD_STATUS } = require(path.join(__dirname, 'lib', 'constants'));
// ═══════════════════════════════════════════════════════════════
// COLORS & BOX DRAWING
// ═══════════════════════════════════════════════════════════════
const c = {
reset: '\x1b[0m',
bold: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
gray: '\x1b[90m'
};
const md = s => s
.replace(/\*\*(.+?)\*\*/g, `${c.bold}${c.magenta}$1${c.reset}`) // **bold** → pink
.replace(/\*(.+?)\*/g, `${c.green}$1${c.reset}`) // *italic* → green
.replace(/`(.+?)`/g, `${c.yellow}$1${c.reset}`) // `code` → yellow
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, text, url) => { // [text](url)
const norm = u => u.replace(/^https?:\/\/(www\.)?/, '').replace(/[\/.\s]+$/, '');
return norm(text) === norm(url) ? `${c.cyan}${url}${c.reset}` : `${text} ${c.dim}(${c.cyan}${url}${c.dim})${c.reset}`;
})
.replace(/^(#{1,3})\s+(.+)/gm, `${c.bold}${c.cyan}$2${c.reset}`); // # headers
const B = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│', lc: '├', rc: '┤' };
// ═══════════════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════════════
const strip = s => s.replace(/\x1b\[[0-9;]*m/g, '');
const fmt = ms => ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(2)}s`;
const W = () => Math.min(process.stdout.columns || 80, 100) - 2;
function wrap(text, max) {
const lines = [];
for (const p of text.split('\n')) {
if (!p.trim()) { lines.push(''); continue; }
// Never wrap GFM table rows — splitting them destroys table syntax
if (p.trimStart().startsWith('|')) { lines.push(p); continue; }
if (strip(p).length <= max) { lines.push(p); continue; }
let cur = '';
for (const w of p.split(' ')) {
if (strip(cur + w).length > max) {
if (cur) lines.push(cur.trimEnd());
cur = w + ' ';
} else {
cur += w + ' ';
}
}
if (cur.trim()) lines.push(cur.trimEnd());
}
return lines;
}
function padLine(text, width) {
return text + ' '.repeat(Math.max(0, width - strip(text).length));
}
function renderBox(title, content, meta = {}) {
const w = W();
const inner = w - 2;
const out = [];
out.push(`${c.cyan}${B.tl}${B.h.repeat(w)}${B.tr}${c.reset}`);
// Title
const titleLine = `${c.bold}${c.cyan}Q:${c.reset} ${title}`;
out.push(`${c.cyan}${B.v}${c.reset} ${padLine(titleLine, inner)} ${c.cyan}${B.v}${c.reset}`);
// Meta line
const parts = [];
if (meta.fromCache) parts.push(`${c.yellow}⚡ cached${c.reset}`);
if (meta.timeMs != null) parts.push(`${c.gray}${fmt(meta.timeMs)}${c.reset}`);
if (meta.startup) parts.push(`${c.dim}(+${fmt(meta.startup)} startup)${c.reset}`);
if (parts.length) {
out.push(`${c.cyan}${B.v}${c.reset} ${padLine(parts.join(' '), inner)} ${c.cyan}${B.v}${c.reset}`);
}
// Separator
out.push(`${c.cyan}${B.lc}${B.h.repeat(w)}${B.rc}${c.reset}`);
// Content
for (const line of wrap(md(content) || 'No results found.', inner)) {
out.push(`${c.cyan}${B.v}${c.reset} ${padLine(line, inner)} ${c.cyan}${B.v}${c.reset}`);
}
out.push(`${c.cyan}${B.bl}${B.h.repeat(w)}${B.br}${c.reset}`);
return '\n' + out.join('\n') + '\n';
}
function renderStatus(r) {
const mode = r.headless ? 'headless' : 'headed';
return `
${c.bold}${c.cyan}◆ iSearch Daemon${c.reset}
${c.gray}─────────────────────${c.reset}
Status: ${c.green}●${c.reset} ${r.status}
Mode: ${mode}
Uptime: ${r.uptime}s
Cache: ${r.cacheSize} items
Browser: ${r.browser}
`;
}
function renderHelp() {
return `
${c.bold}${c.cyan}iSearch${c.reset} ${c.dim}v2.0${c.reset} - Lightning-fast Google Search
${c.bold}Usage:${c.reset}
${c.green}ask${c.reset} "your query" Search Google (headless)
${c.green}ask${c.reset} --head "query" Search with visible browser
${c.green}ask${c.reset} --head Switch daemon to headed mode
${c.green}ask${c.reset} --headless Switch daemon to headless mode
${c.green}ask${c.reset} --status Check daemon status
${c.green}ask${c.reset} --stop Stop the daemon
${c.bold}Examples:${c.reset}
${c.dim}$${c.reset} ask "what is rust"
${c.dim}$${c.reset} ask --head "debug this captcha"
${c.dim}$${c.reset} ask --headless
${c.dim}$${c.reset} ask "latest node.js version"
`;
}
// ═══════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════
async function main() {
const rawArgs = process.argv.slice(2);
// Extract mode flags before filtering
const wantHeaded = rawArgs.includes('--head');
const wantHeadless = rawArgs.includes('--headless');
const args = rawArgs.filter(a => !['--head', '--headless'].includes(a));
// Help — show when no args at all
if (!rawArgs.length || args.includes('-h') || args.includes('--help')) {
console.log(renderHelp());
process.exit(0);
}
// Stop
if (args.includes('--stop')) {
try {
await query({ query: CMD_STOP }, 3000);
console.log(`${c.green}✔${c.reset} Daemon stopped.`);
} catch (e) {
if (isDaemonDown(e)) {
console.log(`${c.dim}Daemon was not running.${c.reset}`);
} else {
console.error(`${c.red}Error:${c.reset} ${e.message}`);
}
}
process.exit(0);
}
// Status
if (args.includes('--status')) {
try {
const r = await query({ query: CMD_STATUS }, 3000);
console.log(renderStatus(r));
} catch (e) {
if (isDaemonDown(e)) {
console.log(`\n${c.yellow}◆${c.reset} Daemon is ${c.yellow}not running${c.reset}`);
console.log(` ${c.dim}Start with: ask "your query"${c.reset}\n`);
} else {
console.error(`${c.red}Error:${c.reset} ${e.message}`);
}
}
process.exit(0);
}
// ─── Search / Mode Switch ─────────────────────────────────
// null = no preference (default to headless on fresh start)
const desiredHeadless = wantHeaded ? false : (wantHeadless ? true : null);
const q = args.join(' ');
let startup = 0;
try {
// Probe daemon state
let daemonRunning = false;
let needRestart = false;
try {
const st = await query({ query: CMD_STATUS }, 2000);
daemonRunning = true;
// Restart only if an explicit mode flag was given and it differs
if (desiredHeadless !== null && st.headless !== desiredHeadless) {
needRestart = true;
}
} catch (e) {
if (!isDaemonDown(e)) throw e;
}
// Handle mode switch (stop → restart)
if (needRestart) {
const mode = desiredHeadless ? 'headless' : 'headed';
process.stdout.write(`${c.dim}Restarting in ${mode} mode...${c.reset}`);
await stopAndWait();
const t0 = Date.now();
await startDaemon({ headless: desiredHeadless });
startup = Date.now() - t0;
process.stdout.write(`\r${c.green}✔${c.reset} Engine ready (${mode}) ${c.dim}(${fmt(startup)})${c.reset} \n`);
} else if (!daemonRunning) {
// Fresh start — use explicit flag or default to headless
const headless = desiredHeadless !== null ? desiredHeadless : true;
const mode = headless ? 'headless' : 'headed';
process.stdout.write(`${c.dim}Starting engine...${c.reset}`);
const t0 = Date.now();
await startDaemon({ headless });
startup = Date.now() - t0;
process.stdout.write(`\r${c.green}✔${c.reset} Engine ready (${mode}) ${c.dim}(${fmt(startup)})${c.reset} \n`);
}
// Mode-switch-only (no query)
if (!q) {
if (wantHeaded || wantHeadless) {
const mode = wantHeaded ? 'headed' : 'headless';
console.log(`${c.green}✔${c.reset} Daemon running in ${c.cyan}${mode}${c.reset} mode.`);
}
process.exit(0);
}
// Execute search
const result = await query({ query: q });
if (result.error) {
console.error(`\n${c.red}✖ Error:${c.reset} ${result.error}`);
if (result.error.includes('CAPTCHA')) {
console.error(` ${c.dim}Run: bun run setup${c.reset}`);
}
console.log();
process.exit(1);
}
console.log(renderBox(q, result.markdown, {
fromCache: result.fromCache,
timeMs: result.timeMs,
startup: startup || undefined
}));
} catch (e) {
console.error(`\n${c.red}✖ Fatal:${c.reset} ${e.message}\n`);
process.exit(1);
}
}
main();