@danhachuel/jobfinder 0.1.16 → 0.1.17
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/CHANGELOG.md +27 -0
- package/README.md +53 -42
- package/ecosystem.config.cjs +22 -12
- package/package.json +1 -1
- package/scripts/cli.mjs +542 -380
- package/scripts/manual-tests/fase1-auth-dryrun.mjs +1 -1
- package/scripts/manual-tests/fase1-dryrun-services.mjs +1 -1
- package/scripts/manual-tests/fase1-screens.mjs +1 -1
- package/scripts/manual-tests/fase1-ui-e2e.mjs +1 -1
- package/scripts/manual-tests/fase2-worker.mjs +2 -2
- package/scripts/manual-tests/fase3-seed-env.mjs +1 -0
- package/scripts/manual-tests/fase4-npx-start.mjs +13 -4
- package/scripts/manual-tests/fase5-daemon.mjs +34 -38
- package/scripts/manual-tests/fase6-runtime-daemon.mjs +274 -0
- package/scripts/manual-tests/startup-keepalive.mjs +84 -41
- package/scripts/start-windows.ps1 +31 -30
- package/src/server/index.mjs +43 -4
- package/src/ui/dist/assets/{index-BIl6BJNG.js → index-BhxoDkvQ.js} +1 -1
- package/src/ui/dist/index.html +1 -1
package/scripts/cli.mjs
CHANGED
|
@@ -1,45 +1,79 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* JobFinder CLI launcher (npx entrypoint).
|
|
3
|
+
* JobFinder CLI launcher (npx entrypoint) — runtime permanente + daemon.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* jobfinder install create ~/.jobfinder/ skeleton (safe to re-run)
|
|
7
|
-
* jobfinder start the local server (backend + UI) on localhost:4040
|
|
8
|
-
* jobfinder start alias of the default command
|
|
9
|
-
* jobfinder --version print version info
|
|
10
|
-
* jobfinder --help print usage
|
|
5
|
+
* ARQUITETURA (0.1.17, espelha o @danhachuel/pandanews):
|
|
11
6
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
7
|
+
* 1. RUNTIME PERMANENTE. O código do servidor é copiado para
|
|
8
|
+
* ~/.jobfinder/runtime (src/server + src/ui/dist + package.json). O
|
|
9
|
+
* Express NUNCA sobe de dentro do cache do npx: no Windows o npx
|
|
10
|
+
* renomeia/limpa esse cache ao final e o Windows devolve EBUSY quando
|
|
11
|
+
* um processo vivo segura arquivos lá dentro — o que derrubava o app.
|
|
12
|
+
*
|
|
13
|
+
* 2. DAEMON. O servidor sobe DESTACADO (detached + windowsHide), com stdio
|
|
14
|
+
* direto no arquivo ~/.jobfinder/jobfinder.log — não herda o console.
|
|
15
|
+
* O terminal volta ao prompt na hora; fechar o MobaXterm/PowerShell não
|
|
16
|
+
* mata o servidor.
|
|
17
|
+
*
|
|
18
|
+
* 3. LOCK DE PID. ~/.jobfinder/jobfinder.pid registra a instância. `stop`
|
|
19
|
+
* encerra por PID (taskkill /PID /T no Windows) e, como rede de
|
|
20
|
+
* segurança, por quem estiver dono da porta.
|
|
21
|
+
*
|
|
22
|
+
* Comandos:
|
|
23
|
+
* jobfinder install cria o esqueleto ~/.jobfinder/ (idempotente)
|
|
24
|
+
* jobfinder inicia em background (daemon) — padrão
|
|
25
|
+
* jobfinder start alias do padrão
|
|
26
|
+
* jobfinder --foreground sobe preso a este terminal (depuração)
|
|
27
|
+
* jobfinder stop | kill encerra o daemon
|
|
28
|
+
* jobfinder --version | --help
|
|
18
29
|
*/
|
|
19
30
|
import fs from 'node:fs';
|
|
20
31
|
import path from 'node:path';
|
|
21
32
|
import os from 'node:os';
|
|
22
33
|
import process from 'node:process';
|
|
23
34
|
import { fileURLToPath } from 'node:url';
|
|
24
|
-
import { spawn } from 'node:child_process';
|
|
35
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
36
|
+
import { createRequire } from 'node:module';
|
|
25
37
|
|
|
26
|
-
import { ensureDataDir,
|
|
27
|
-
import { JsonStore } from '../src/server/storage/jsonStore.mjs';
|
|
28
|
-
import { spawnWorker } from '../src/server/workerRuntime.mjs';
|
|
38
|
+
import { ensureDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
|
|
29
39
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
*
|
|
42
|
-
|
|
40
|
+
const require = createRequire(import.meta.url);
|
|
41
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
42
|
+
const PKG_ROOT = path.resolve(__dirname, '..');
|
|
43
|
+
const pkg = require('../package.json');
|
|
44
|
+
|
|
45
|
+
const VISUAL_VERSION = pkg.version;
|
|
46
|
+
const NPM_VERSION = String(pkg.version)
|
|
47
|
+
.split('.')
|
|
48
|
+
.map((part) => String(Number(part)))
|
|
49
|
+
.join('.');
|
|
50
|
+
|
|
51
|
+
/* ------------------------------------------------------------------ *
|
|
52
|
+
* Caminhos: lar estável, runtime permanente, lock de PID *
|
|
53
|
+
* ------------------------------------------------------------------ */
|
|
54
|
+
|
|
55
|
+
/** Raiz de instalação estável: JOBFINDER_HOME > JOBFINDER_DATA_DIR > ~/.jobfinder. */
|
|
56
|
+
export function resolveHome() {
|
|
57
|
+
if (process.env.JOBFINDER_HOME) return path.resolve(process.env.JOBFINDER_HOME);
|
|
58
|
+
if (process.env.JOBFINDER_DATA_DIR) return path.resolve(process.env.JOBFINDER_DATA_DIR);
|
|
59
|
+
return path.join(os.homedir(), '.jobfinder');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function runtimeDir(home) {
|
|
63
|
+
return path.join(home, 'runtime');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function serverEntry(home) {
|
|
67
|
+
return path.join(runtimeDir(home), 'src', 'server', 'index.mjs');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function pidFilePath(home) {
|
|
71
|
+
return path.join(home, 'jobfinder.pid');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/* ------------------------------------------------------------------ *
|
|
75
|
+
* Resiliência do launcher *
|
|
76
|
+
* ------------------------------------------------------------------ */
|
|
43
77
|
process.on('unhandledRejection', (reason) => {
|
|
44
78
|
const message = reason instanceof Error ? reason.message : String(reason);
|
|
45
79
|
console.error(`[jobfinder] unhandled promise rejection ignored: ${message}`);
|
|
@@ -50,439 +84,567 @@ process.on('uncaughtException', (err) => {
|
|
|
50
84
|
});
|
|
51
85
|
for (const stream of [process.stdout, process.stderr]) {
|
|
52
86
|
stream?.on?.('error', (err) => {
|
|
53
|
-
if (err?.code === 'EPIPE') return;
|
|
87
|
+
if (err?.code === 'EPIPE') return; // terminal/pipe fechado: seguir working
|
|
54
88
|
console.error(`[jobfinder] stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
|
|
55
89
|
});
|
|
56
90
|
}
|
|
57
91
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
|
63
|
-
const VISUAL_VERSION = pkg.version;
|
|
64
|
-
const NPM_VERSION = normalizeNpmVersion(pkg.version);
|
|
65
|
-
|
|
66
|
-
/** npm normalizes SemVer: 0.0.01 -> 0.0.1, 0.1.00 -> 0.1.0 */
|
|
67
|
-
function normalizeNpmVersion(v) {
|
|
68
|
-
return v
|
|
69
|
-
.split('.')
|
|
70
|
-
.map((part) => String(Number(part)))
|
|
71
|
-
.join('.');
|
|
72
|
-
}
|
|
73
|
-
|
|
92
|
+
/* ------------------------------------------------------------------ *
|
|
93
|
+
* USO *
|
|
94
|
+
* ------------------------------------------------------------------ */
|
|
74
95
|
const USAGE = `
|
|
75
96
|
JobFinder — LinkedIn automation platform
|
|
76
97
|
|
|
77
|
-
|
|
78
|
-
jobfinder install
|
|
79
|
-
jobfinder
|
|
80
|
-
jobfinder
|
|
81
|
-
jobfinder --
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
--
|
|
86
|
-
--
|
|
87
|
-
--
|
|
88
|
-
--
|
|
89
|
-
--
|
|
90
|
-
|
|
91
|
-
|
|
98
|
+
Uso:
|
|
99
|
+
jobfinder install Cria o esqueleto JSON em ~/.jobfinder/ (idempotente)
|
|
100
|
+
jobfinder Inicia o servidor EM BACKGROUND (daemon)
|
|
101
|
+
jobfinder start Alias do padrão
|
|
102
|
+
jobfinder --foreground Sobe preso a este terminal (para depuração)
|
|
103
|
+
jobfinder stop | kill Encerra o daemon em background
|
|
104
|
+
|
|
105
|
+
Opcoes:
|
|
106
|
+
--port <n> Porta (padrão 4040)
|
|
107
|
+
--host <addr> Endereço (padrão 127.0.0.1)
|
|
108
|
+
--data-dir <path> Diretório de dados (padrão ~/.jobfinder)
|
|
109
|
+
--dry-run Força o modo dry-run (nenhuma ação real no LinkedIn)
|
|
110
|
+
--foreground Não destaca: prende o servidor a este terminal
|
|
111
|
+
--help Mostra esta ajuda
|
|
112
|
+
--version Mostra a versão
|
|
113
|
+
|
|
114
|
+
Instalação (versão canônica do npm):
|
|
92
115
|
npx --yes @danhachuel/jobfinder@${NPM_VERSION} install
|
|
93
116
|
npx --yes @danhachuel/jobfinder@${NPM_VERSION}
|
|
117
|
+
|
|
118
|
+
Recomendado no Windows (evita o EBUSY do npx, que limpa o próprio cache):
|
|
119
|
+
npm install -g @danhachuel/jobfinder@latest
|
|
94
120
|
`;
|
|
95
121
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
case '--port':
|
|
108
|
-
args.port = Number(rest[i + 1]);
|
|
109
|
-
i += 1;
|
|
110
|
-
break;
|
|
111
|
-
case '--host':
|
|
112
|
-
args.host = rest[i + 1];
|
|
113
|
-
i += 1;
|
|
114
|
-
break;
|
|
115
|
-
case '--data-dir':
|
|
116
|
-
args.dataDir = rest[i + 1];
|
|
117
|
-
i += 1;
|
|
118
|
-
break;
|
|
119
|
-
// Deprecated no-ops: the browser is never opened automatically.
|
|
120
|
-
// The flags are still accepted so existing commands keep working.
|
|
121
|
-
case '--open':
|
|
122
|
-
case '--no-open':
|
|
123
|
-
break;
|
|
124
|
-
case '--dry-run':
|
|
125
|
-
args.dryRun = true;
|
|
126
|
-
break;
|
|
127
|
-
// Daemon mode: the server runs detached from this terminal (background
|
|
128
|
-
// service). The terminal returns to the prompt immediately.
|
|
129
|
-
case '--daemon':
|
|
130
|
-
args.daemon = true;
|
|
131
|
-
break;
|
|
132
|
-
// Shorthand to stop a daemon started with --daemon.
|
|
133
|
-
case '--daemon-stop':
|
|
134
|
-
case '--stop':
|
|
135
|
-
args.command = 'stop';
|
|
136
|
-
break;
|
|
137
|
-
case '--help':
|
|
138
|
-
case '-h':
|
|
139
|
-
args.command = 'help';
|
|
140
|
-
break;
|
|
141
|
-
case '--version':
|
|
142
|
-
case '-v':
|
|
143
|
-
args.command = 'version';
|
|
144
|
-
break;
|
|
145
|
-
default:
|
|
146
|
-
if (token.startsWith('-')) {
|
|
147
|
-
console.warn(`[jobfinder] ignoring unknown flag: ${token}`);
|
|
148
|
-
}
|
|
149
|
-
break;
|
|
122
|
+
/** Copia uma pasta sem node_modules (runtime enxuto). */
|
|
123
|
+
function copyTree(from, to) {
|
|
124
|
+
fs.mkdirSync(to, { recursive: true });
|
|
125
|
+
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
|
|
126
|
+
if (entry.name === 'node_modules' || entry.name === '.git') continue;
|
|
127
|
+
const src = path.join(from, entry.name);
|
|
128
|
+
const dest = path.join(to, entry.name);
|
|
129
|
+
if (entry.isDirectory()) {
|
|
130
|
+
copyTree(src, dest);
|
|
131
|
+
} else {
|
|
132
|
+
fs.copyFileSync(src, dest);
|
|
150
133
|
}
|
|
151
134
|
}
|
|
152
|
-
return args;
|
|
153
135
|
}
|
|
154
136
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
137
|
+
/**
|
|
138
|
+
* RUNTIME PERMANENTE: copia src/server + src/ui/dist para ~/.jobfinder/runtime
|
|
139
|
+
* e instala lá as dependências de produção. Só repovoa quando falta o
|
|
140
|
+
* entrypoint ou quando a versão mudou.
|
|
141
|
+
*
|
|
142
|
+
* As dependências são instaladas DENTRO do runtime (nunca um symlink/junction
|
|
143
|
+
* para o cache do npx): é isso que garante que o daemon não segure arquivos
|
|
144
|
+
* dentro do cache — a causa raiz do EBUSY no Windows.
|
|
145
|
+
*
|
|
146
|
+
* @param {string} home raiz estável
|
|
147
|
+
* @returns {string} caminho do servidor a executar
|
|
148
|
+
*/
|
|
149
|
+
export function setupRuntime(home) {
|
|
150
|
+
const dest = runtimeDir(home);
|
|
151
|
+
const entry = serverEntry(home);
|
|
152
|
+
const haveVersion = fs.existsSync(path.join(dest, '.version'))
|
|
153
|
+
? fs.readFileSync(path.join(dest, '.version'), 'utf8').trim()
|
|
154
|
+
: '';
|
|
155
|
+
const missing = !fs.existsSync(entry);
|
|
156
|
+
|
|
157
|
+
if (missing || haveVersion !== VISUAL_VERSION) {
|
|
158
|
+
if (missing) {
|
|
159
|
+
console.log('Preparando o runtime permanente (~/.jobfinder/runtime) — o servidor não roda mais do cache do npx...');
|
|
160
|
+
} else {
|
|
161
|
+
console.log(`Runtime defasado (${haveVersion || 'sem versão'} -> ${VISUAL_VERSION}) — atualizando a cópia...`);
|
|
162
|
+
}
|
|
163
|
+
const tmp = `${dest}.tmp-${process.pid}`;
|
|
164
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
165
|
+
fs.mkdirSync(path.join(tmp, 'src'), { recursive: true });
|
|
166
|
+
// Apenas o necessário ao servidor Express: código + UI buildada.
|
|
167
|
+
copyTree(path.join(PKG_ROOT, 'src', 'server'), path.join(tmp, 'src', 'server'));
|
|
168
|
+
const uiDist = path.join(PKG_ROOT, 'src', 'ui', 'dist');
|
|
169
|
+
if (fs.existsSync(uiDist)) {
|
|
170
|
+
copyTree(uiDist, path.join(tmp, 'src', 'ui', 'dist'));
|
|
171
|
+
}
|
|
172
|
+
// package.json enxuto: só o que o servidor precisa. Sem pm2 (ferramenta do
|
|
173
|
+
// launcher, não do runtime) e sem devDependencies.
|
|
174
|
+
const runtimePkg = {
|
|
175
|
+
name: pkg.name,
|
|
176
|
+
version: VISUAL_VERSION,
|
|
177
|
+
private: true,
|
|
178
|
+
type: 'module',
|
|
179
|
+
dependencies: { ...(pkg.dependencies ?? {}) },
|
|
180
|
+
// playwright continua opcional: só o Easy Apply ao vivo o usa.
|
|
181
|
+
...(pkg.optionalDependencies?.playwright
|
|
182
|
+
? { optionalDependencies: { playwright: pkg.optionalDependencies.playwright } }
|
|
183
|
+
: {}),
|
|
184
|
+
};
|
|
185
|
+
fs.writeFileSync(path.join(tmp, 'package.json'), `${JSON.stringify(runtimePkg, null, 2)}\n`, 'utf8');
|
|
186
|
+
fs.writeFileSync(path.join(tmp, '.version'), `${VISUAL_VERSION}\n`, 'utf8');
|
|
187
|
+
// Swap atômico: no Windows, rename sobre destino existente falha (EPERM).
|
|
188
|
+
fs.rmSync(dest, { recursive: true, force: true });
|
|
189
|
+
fs.renameSync(tmp, dest);
|
|
190
|
+
console.log(`Código copiado para ${dest}`);
|
|
191
|
+
|
|
192
|
+
installRuntimeDependencies(dest);
|
|
193
|
+
console.log(`Runtime pronto em ${dest}`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return entry;
|
|
161
197
|
}
|
|
162
198
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
199
|
+
/** Instala as dependências de produção dentro do runtime (silencioso). */
|
|
200
|
+
function installRuntimeDependencies(runtimeRoot) {
|
|
201
|
+
const modules = path.join(runtimeRoot, 'node_modules');
|
|
202
|
+
if (fs.existsSync(path.join(modules, 'express', 'package.json'))) return true;
|
|
203
|
+
|
|
204
|
+
console.log('Instalando dependências do runtime (express, mammoth, pdfjs-dist)...');
|
|
205
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
206
|
+
const { NODE_OPTIONS: _appPreloads, ...cleanEnv } = process.env;
|
|
207
|
+
const result = spawnSync(
|
|
208
|
+
npm,
|
|
209
|
+
['install', '--prefix', runtimeRoot, '--omit=dev', '--no-audit', '--no-fund', '--no-save', '--loglevel=error'],
|
|
210
|
+
// `shell: true` é obrigatório no Windows: .cmd/.bat não executam sem ele
|
|
211
|
+
// desde o Node 18.20 (spawn falha com EINVAL).
|
|
212
|
+
{
|
|
213
|
+
windowsHide: true,
|
|
214
|
+
shell: process.platform === 'win32',
|
|
215
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
216
|
+
encoding: 'utf8',
|
|
217
|
+
env: cleanEnv,
|
|
218
|
+
}
|
|
219
|
+
);
|
|
220
|
+
if (result.error || result.status !== 0) {
|
|
221
|
+
// Falha aqui é fatal: sem dependências o servidor não sobe. Melhor
|
|
222
|
+
// abortar com mensagem clara do que spawnar um processo que vai morrer.
|
|
223
|
+
throw new Error(
|
|
224
|
+
`falha ao instalar as dependências do runtime: ${(result.error?.message ?? result.stderr ?? result.stdout ?? '').trim()
|
|
225
|
+
.split('\n')
|
|
226
|
+
.slice(0, 3)
|
|
227
|
+
.join(' ')} (instale manualmente: npm install --prefix ${runtimeRoot})`
|
|
228
|
+
);
|
|
177
229
|
}
|
|
178
|
-
|
|
179
|
-
console.log(` 1. Connect LinkedIn in the app (Integracoes) — official API or cookies.txt fallback`);
|
|
180
|
-
console.log(` 2. Pick an LLM provider (OpenAI, Anthropic, DeepSeek or local Ollama) in Config`);
|
|
181
|
-
console.log(` 3. Start the app: npx --yes @danhachuel/jobfinder@${NPM_VERSION}`);
|
|
230
|
+
return true;
|
|
182
231
|
}
|
|
183
232
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
233
|
+
/** Entrypoint a executar: runtime permanente (padrão) ou o próprio pacote (dev). */
|
|
234
|
+
export function resolveServerEntry(home) {
|
|
235
|
+
if (process.env.JOBFINDER_NO_RUNTIME === '1' && fs.existsSync(path.join(PKG_ROOT, 'src', 'server', 'index.mjs'))) {
|
|
236
|
+
return path.join(PKG_ROOT, 'src', 'server', 'index.mjs');
|
|
237
|
+
}
|
|
238
|
+
return setupRuntime(home);
|
|
239
|
+
}
|
|
187
240
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
);
|
|
241
|
+
/** PID vivo? (EPERM = vivo, mas de outro usuário). */
|
|
242
|
+
function isAlive(pid) {
|
|
243
|
+
if (!pid || !Number.isInteger(Number(pid)) || Number(pid) <= 0) return false;
|
|
244
|
+
try {
|
|
245
|
+
process.kill(Number(pid), 0);
|
|
246
|
+
return true;
|
|
247
|
+
} catch (err) {
|
|
248
|
+
return err?.code === 'EPERM';
|
|
193
249
|
}
|
|
250
|
+
}
|
|
194
251
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
// empty the loop and take the process down anymore. The worker stays a
|
|
212
|
-
// separate child so its heavy tasks never block the server.
|
|
213
|
-
// ------------------------------------------------------------------ *
|
|
214
|
-
process.env.JOBFINDER_DATA_DIR = resolved;
|
|
215
|
-
process.env.JOBFINDER_PORT = String(listenPort);
|
|
216
|
-
process.env.JOBFINDER_HOST = listenHost;
|
|
217
|
-
// Version: read from THIS file's package.json (never cwd) and handed to the
|
|
218
|
-
// server via env. Under npx the cwd is the user's directory, so a server
|
|
219
|
-
// that read its own version from cwd would print 0.0.00.
|
|
220
|
-
process.env.JOBFINDER_VERSION = VISUAL_VERSION;
|
|
221
|
-
if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
|
|
222
|
-
|
|
223
|
-
// Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
|
|
224
|
-
// roda com stdio ['ignore','ignore','ignore'] (logs em arquivo) e, se
|
|
225
|
-
// morrer, o launcher apenas registra e reinicia — o servidor segue.
|
|
226
|
-
let worker = null;
|
|
227
|
-
let workerRestarts = 0;
|
|
228
|
-
let stopping = false;
|
|
229
|
-
let serverRef = null;
|
|
230
|
-
|
|
231
|
-
const stopChildren = () => {
|
|
232
|
-
if (worker && worker.exitCode === null && worker.signalCode === null) {
|
|
233
|
-
worker.kill('SIGTERM');
|
|
234
|
-
// Hard deadline: a worker that ignores SIGTERM must not linger.
|
|
235
|
-
setTimeout(() => {
|
|
236
|
-
if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
|
|
237
|
-
}, 2000).unref();
|
|
252
|
+
/** Mata a árvore de processos por PID — sempre em silêncio (sem janela). */
|
|
253
|
+
export function killTree(pid) {
|
|
254
|
+
if (!isAlive(pid)) return;
|
|
255
|
+
try {
|
|
256
|
+
if (process.platform === 'win32') {
|
|
257
|
+
spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], {
|
|
258
|
+
windowsHide: true, // CREATE_NO_WINDOW — sem tela preta
|
|
259
|
+
detached: true, // grupo isolado, imune a Ctrl+C do console
|
|
260
|
+
stdio: 'ignore', // taskkill não escreve no terminal
|
|
261
|
+
});
|
|
262
|
+
} else {
|
|
263
|
+
try {
|
|
264
|
+
process.kill(-Number(pid), 'SIGKILL'); // grupo: mata os filhos também
|
|
265
|
+
} catch {
|
|
266
|
+
process.kill(Number(pid), 'SIGTERM');
|
|
267
|
+
}
|
|
238
268
|
}
|
|
239
|
-
}
|
|
269
|
+
} catch {
|
|
270
|
+
/* processo já não existia */
|
|
271
|
+
}
|
|
272
|
+
}
|
|
240
273
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const serverAlive = Boolean(serverRef?.listening);
|
|
250
|
-
if (!stopping && serverAlive && workerRestarts < 5) {
|
|
251
|
-
workerRestarts += 1;
|
|
252
|
-
console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
|
|
253
|
-
// Re-check `stopping`: um shutdown que começa enquanto este timer
|
|
254
|
-
// está pendente nunca pode deixar um órfão para trás.
|
|
255
|
-
setTimeout(() => {
|
|
256
|
-
if (!stopping) startWorker();
|
|
257
|
-
}, 3000);
|
|
258
|
-
}
|
|
274
|
+
/** Descobre o PID dono de uma porta em LISTEN (Windows: netstat; Unix: null). */
|
|
275
|
+
function pidOfPort(port) {
|
|
276
|
+
if (process.platform !== 'win32') return null;
|
|
277
|
+
try {
|
|
278
|
+
const result = spawnSync('netstat', ['-ano'], {
|
|
279
|
+
windowsHide: true,
|
|
280
|
+
detached: true,
|
|
281
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
259
282
|
});
|
|
260
|
-
return
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
// Forensic trail: se o launcher morrer, o motivo fica visível. `beforeExit`
|
|
269
|
-
// avisa ANTES de o loop esvaziar (com os handles ativos) e permite re-armar
|
|
270
|
-
// o keep-alive; `exit` registra o código final.
|
|
271
|
-
process.on('beforeExit', (code) => {
|
|
272
|
-
const handles = process.getActiveResourcesInfo?.() ?? [];
|
|
273
|
-
console.error(
|
|
274
|
-
`[jobfinder] launcher: event loop esvaziando (beforeExit code=${code}) — ` +
|
|
275
|
-
`handles: ${handles.join(', ') || 'NENHUM'}`
|
|
276
|
-
);
|
|
277
|
-
if (!stopping) {
|
|
278
|
-
console.error('[jobfinder] launcher: re-armando o keep-alive para nao voltar ao prompt.');
|
|
279
|
-
clearInterval(keepAliveTimer);
|
|
280
|
-
setInterval(() => {}, 24 * 60 * 60 * 1000);
|
|
283
|
+
if (result.status !== 0 || !result.stdout) return null;
|
|
284
|
+
const target = `:${port}`;
|
|
285
|
+
for (const line of result.stdout.toString().split(/\r?\n/)) {
|
|
286
|
+
if (!line.includes(target) || !/LISTENING/i.test(line)) continue;
|
|
287
|
+
const columns = line.trim().split(/\s+/);
|
|
288
|
+
const pid = Number(columns[columns.length - 1]);
|
|
289
|
+
if (Number.isInteger(pid) && pid > 0) return pid;
|
|
281
290
|
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
291
|
+
} catch {
|
|
292
|
+
/* netstat indisponível — seguimos sem a rede de segurança */
|
|
293
|
+
}
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
286
296
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
297
|
+
/** Lê o lock de PID (corrompido nunca impede o arranque). */
|
|
298
|
+
export function readPidLock(home) {
|
|
299
|
+
try {
|
|
300
|
+
const data = JSON.parse(fs.readFileSync(pidFilePath(home), 'utf8'));
|
|
301
|
+
if (!data || typeof data !== 'object') return null;
|
|
302
|
+
return {
|
|
303
|
+
pid: Number.isInteger(data.pid) ? data.pid : null,
|
|
304
|
+
port: Number.isInteger(data.port) ? data.port : null,
|
|
305
|
+
version: typeof data.version === 'string' ? data.version : null,
|
|
306
|
+
};
|
|
307
|
+
} catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
300
311
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
312
|
+
function writePidLock(home, pid, port) {
|
|
313
|
+
try {
|
|
314
|
+
fs.writeFileSync(
|
|
315
|
+
pidFilePath(home),
|
|
316
|
+
`${JSON.stringify({ pid, port, version: VISUAL_VERSION, criado: new Date().toISOString() }, null, 2)}\n`,
|
|
317
|
+
'utf8'
|
|
318
|
+
);
|
|
319
|
+
} catch {
|
|
320
|
+
/* lock é melhor esforço — nunca derruba o arranque */
|
|
321
|
+
}
|
|
322
|
+
}
|
|
304
323
|
|
|
305
|
-
|
|
306
|
-
// --version e install leves, sem carregar o Express).
|
|
324
|
+
export function clearPidLock(home) {
|
|
307
325
|
try {
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
console.error('[jobfinder] falha ao iniciar o servidor:', err?.message ?? err);
|
|
312
|
-
stopChildren();
|
|
313
|
-
process.exit(1);
|
|
326
|
+
fs.unlinkSync(pidFilePath(home));
|
|
327
|
+
} catch {
|
|
328
|
+
/* já removido */
|
|
314
329
|
}
|
|
330
|
+
}
|
|
315
331
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
332
|
+
/**
|
|
333
|
+
* Mata instâncias anteriores antes de subir uma nova: PIDs do lock + quem
|
|
334
|
+
* estiver dono da porta (o lock pode ficar obsoleto se o processo foi morto
|
|
335
|
+
* externamente). Sem isso cada start empilhava outro servidor zombie e a
|
|
336
|
+
* UI nova era servida por um backend de versão velha.
|
|
337
|
+
*/
|
|
338
|
+
export async function killPreviousInstances(home, port) {
|
|
339
|
+
let killed = 0;
|
|
340
|
+
const lock = readPidLock(home);
|
|
341
|
+
if (lock?.pid && lock.pid !== process.pid && isAlive(lock.pid)) {
|
|
342
|
+
killTree(lock.pid);
|
|
343
|
+
killed += 1;
|
|
344
|
+
}
|
|
345
|
+
const owner = pidOfPort(port);
|
|
346
|
+
if (owner && owner !== process.pid) {
|
|
347
|
+
killTree(owner);
|
|
348
|
+
killed += 1;
|
|
321
349
|
}
|
|
350
|
+
if (killed > 0) {
|
|
351
|
+
console.log(`Encerrando instância anterior (${killed} processo(s))...`);
|
|
352
|
+
// 1s para o SO liberar arquivos e portas — sem isso o bind pode falhar.
|
|
353
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
354
|
+
}
|
|
355
|
+
clearPidLock(home);
|
|
356
|
+
return killed;
|
|
322
357
|
}
|
|
323
358
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
359
|
+
/* ------------------------------------------------------------------ *
|
|
360
|
+
* Health poll *
|
|
361
|
+
* ------------------------------------------------------------------ */
|
|
362
|
+
async function waitHealth(port, attempts = 40, intervalMs = 500) {
|
|
363
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
364
|
+
try {
|
|
365
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/health`);
|
|
366
|
+
if (res.ok) return true;
|
|
367
|
+
} catch {
|
|
368
|
+
/* ainda subindo */
|
|
369
|
+
}
|
|
370
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
371
|
+
}
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/* ------------------------------------------------------------------ *
|
|
376
|
+
* Comandos *
|
|
377
|
+
* ------------------------------------------------------------------ */
|
|
378
|
+
function commandInstall({ dataDir }) {
|
|
379
|
+
const home = resolveHome();
|
|
380
|
+
fs.mkdirSync(home, { recursive: true });
|
|
381
|
+
ensureDataDir(home);
|
|
382
|
+
console.log(` Diretório de dados: ${home}`);
|
|
383
|
+
if (!isDataDirHealthy(home)) {
|
|
384
|
+
console.error('[jobfinder] diretório de dados incompleto. Verifique permissões e tente novamente.');
|
|
385
|
+
process.exitCode = 1;
|
|
386
|
+
return;
|
|
332
387
|
}
|
|
388
|
+
console.log('\nPróximos passos:');
|
|
389
|
+
console.log(` 1. Iniciar: npx --yes @danhachuel/jobfinder@${NPM_VERSION}`);
|
|
390
|
+
console.log(` 2. Abrir: http://127.0.0.1:4040`);
|
|
391
|
+
console.log(` 3. Parar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
|
|
333
392
|
}
|
|
334
393
|
|
|
335
394
|
/**
|
|
336
|
-
*
|
|
337
|
-
* terminal
|
|
338
|
-
*
|
|
339
|
-
* A hostile terminal (MobaXterm wrapper, PowerShell, npx) can TerminateProcess
|
|
340
|
-
* the foreground child at any moment; a detached process with its own stdio
|
|
341
|
-
* pointed at a log file is immune to that. The terminal returns to the prompt
|
|
342
|
-
* immediately — that is the expected behaviour of a daemon.
|
|
395
|
+
* Sobe o servidor EM BACKGROUND (daemon), a partir do runtime permanente.
|
|
396
|
+
* O terminal volta ao prompt — é o comportamento correto de um daemon.
|
|
343
397
|
*/
|
|
344
398
|
async function commandDaemon(args) {
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
399
|
+
const home = resolveHome();
|
|
400
|
+
fs.mkdirSync(home, { recursive: true });
|
|
401
|
+
ensureDataDir(home);
|
|
402
|
+
|
|
403
|
+
const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
|
|
404
|
+
const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
|
|
405
|
+
const logFile = path.join(home, 'jobfinder.log');
|
|
406
|
+
|
|
407
|
+
// Runtime permanente: sem ele o servidor não sobe (e não vale a pena
|
|
408
|
+
// spawnar um processo que morreria em seguida).
|
|
409
|
+
let entry;
|
|
410
|
+
try {
|
|
411
|
+
entry = resolveServerEntry(home);
|
|
412
|
+
} catch (err) {
|
|
413
|
+
console.error(`[jobfinder] ${err?.message ?? err}`);
|
|
414
|
+
process.exit(1);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
await killPreviousInstances(home, port);
|
|
419
|
+
|
|
420
|
+
console.log(` Iniciando o JobFinder em background (porta ${port})...`);
|
|
421
|
+
console.log(` Log: ${logFile}`);
|
|
422
|
+
|
|
423
|
+
// stdio por FD (obrigatório com detached no Windows) — direto no arquivo,
|
|
424
|
+
// NUNCA herdando o console: um terminal hostil não pode perturbar o daemon.
|
|
425
|
+
const logFd = fs.openSync(logFile, 'a');
|
|
426
|
+
const child = spawn(process.execPath, [entry], {
|
|
427
|
+
detached: true, // CREATE_NEW_PROCESS_GROUP: imune a Ctrl+C do console
|
|
428
|
+
windowsHide: true, // sem janela de console fantasma
|
|
429
|
+
creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
|
|
430
|
+
stdio: ['ignore', logFd, logFd],
|
|
431
|
+
env: {
|
|
432
|
+
...process.env,
|
|
433
|
+
JOBFINDER_HOME: home,
|
|
434
|
+
JOBFINDER_DATA_DIR: home,
|
|
435
|
+
JOBFINDER_PORT: String(port),
|
|
436
|
+
JOBFINDER_HOST: host,
|
|
437
|
+
JOBFINDER_MODE: 'daemon',
|
|
438
|
+
JOBFINDER_VERSION: VISUAL_VERSION,
|
|
439
|
+
...(args.dryRun ? { JOBFINDER_DRY_RUN: '1' } : {}),
|
|
440
|
+
...(process.env.JOBFINDER_NO_WORKER ? { JOBFINDER_NO_WORKER: process.env.JOBFINDER_NO_WORKER } : {}),
|
|
441
|
+
},
|
|
442
|
+
});
|
|
443
|
+
fs.closeSync(logFd); // o filho tem a sua própria cópia herdada
|
|
444
|
+
child.unref(); // o launcher pode morrer sem levar o servidor junto
|
|
445
|
+
|
|
446
|
+
if (!child.pid) {
|
|
447
|
+
console.error('[jobfinder] falha ao iniciar o servidor em background.');
|
|
448
|
+
clearPidLock(home);
|
|
449
|
+
process.exit(1);
|
|
450
|
+
}
|
|
451
|
+
writePidLock(home, child.pid, port);
|
|
452
|
+
|
|
453
|
+
const up = await waitHealth(port);
|
|
454
|
+
const shown = host === '0.0.0.0' ? 'localhost' : host;
|
|
455
|
+
if (up) {
|
|
456
|
+
console.log('');
|
|
457
|
+
console.log(`JobFinder iniciado em background (PID: ${child.pid}). Acesse http://${shown}:${port}`);
|
|
458
|
+
console.log(`Para encerrar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
|
|
355
459
|
return;
|
|
356
460
|
}
|
|
461
|
+
console.error('');
|
|
462
|
+
console.error(`O servidor não respondeu em http://${shown}:${port}/api/health.`);
|
|
463
|
+
console.error(`Diagnóstico completo em: ${logFile}`);
|
|
464
|
+
process.exit(1);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Foreground (depuração): sobe o servidor do runtime preso a este terminal,
|
|
469
|
+
* com a saída encaminhada por pipe (nunca `inherit`).
|
|
470
|
+
*/
|
|
471
|
+
async function commandForeground(args) {
|
|
472
|
+
const home = resolveHome();
|
|
473
|
+
fs.mkdirSync(home, { recursive: true });
|
|
474
|
+
ensureDataDir(home);
|
|
357
475
|
|
|
358
476
|
const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
|
|
359
477
|
const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
|
|
360
|
-
|
|
478
|
+
let entry;
|
|
479
|
+
try {
|
|
480
|
+
entry = resolveServerEntry(home);
|
|
481
|
+
} catch (err) {
|
|
482
|
+
console.error(`[jobfinder] ${err?.message ?? err}`);
|
|
483
|
+
process.exit(1);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
361
486
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
487
|
+
console.log(` JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION}) — modo foreground (depuração)`);
|
|
488
|
+
console.log(` Servidor: ${entry}`);
|
|
489
|
+
console.log(` URL : http://${host === '0.0.0.0' ? 'localhost' : host}:${port}`);
|
|
490
|
+
console.log(' Pressione Ctrl+C para encerrar.\n');
|
|
365
491
|
|
|
366
|
-
const child = spawn(process.execPath, [
|
|
367
|
-
detached: true,
|
|
368
|
-
// stdio de arquivo: o daemon NUNCA herda os pipes do terminal. Se o canalho
|
|
369
|
-
// do MobaXterm fechar, o daemon não sente — e o log fica em disco.
|
|
370
|
-
stdio: ['ignore', logFd, logFd],
|
|
492
|
+
const child = spawn(process.execPath, [entry], {
|
|
371
493
|
windowsHide: true,
|
|
372
494
|
creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
|
|
495
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
373
496
|
env: {
|
|
374
497
|
...process.env,
|
|
375
|
-
|
|
376
|
-
JOBFINDER_DATA_DIR:
|
|
498
|
+
JOBFINDER_HOME: home,
|
|
499
|
+
JOBFINDER_DATA_DIR: home,
|
|
377
500
|
JOBFINDER_PORT: String(port),
|
|
378
501
|
JOBFINDER_HOST: host,
|
|
502
|
+
JOBFINDER_MODE: 'foreground',
|
|
379
503
|
JOBFINDER_VERSION: VISUAL_VERSION,
|
|
504
|
+
...(args.dryRun ? { JOBFINDER_DRY_RUN: '1' } : {}),
|
|
505
|
+
...(process.env.JOBFINDER_NO_WORKER ? { JOBFINDER_NO_WORKER: process.env.JOBFINDER_NO_WORKER } : {}),
|
|
380
506
|
},
|
|
381
507
|
});
|
|
382
508
|
|
|
383
|
-
child.on('
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
509
|
+
child.stdout.on('data', (chunk) => process.stdout.write(chunk));
|
|
510
|
+
child.stderr.on('data', (chunk) => process.stderr.write(chunk));
|
|
511
|
+
child.stdout.on('error', (err) => err?.code !== 'EPIPE' && console.error('[jobfinder] stdout', err?.message));
|
|
512
|
+
child.stderr.on('error', (err) => err?.code !== 'EPIPE' && console.error('[jobfinder] stderr', err?.message));
|
|
387
513
|
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
514
|
+
let stopping = false;
|
|
515
|
+
const stopChild = (signal) => () => {
|
|
516
|
+
if (stopping) process.exit(1); // segundo Ctrl+C força
|
|
517
|
+
stopping = true;
|
|
518
|
+
killTree(child.pid);
|
|
519
|
+
setTimeout(() => process.exit(0), 2000).unref();
|
|
520
|
+
};
|
|
521
|
+
process.on('SIGINT', stopChild('SIGINT'));
|
|
522
|
+
process.on('SIGTERM', stopChild('SIGTERM'));
|
|
523
|
+
process.on('SIGBREAK', stopChild('SIGBREAK'));
|
|
398
524
|
|
|
399
|
-
|
|
525
|
+
// Âncora inquebrável do launcher: o filho NÃO é detached, mas ainda assim
|
|
526
|
+
// garantimos um handle ativo (runtime-guard).
|
|
527
|
+
setInterval(() => {}, 2147483647);
|
|
400
528
|
|
|
401
|
-
const
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
console.
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
console.log(`\nRodando em background — este terminal esta livre.`);
|
|
408
|
-
console.log(` Parar com: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
|
|
529
|
+
const exit = await new Promise((resolve) => {
|
|
530
|
+
child.on('exit', (code, signal) => resolve({ code, signal }));
|
|
531
|
+
});
|
|
532
|
+
console.error(`[jobfinder] servidor encerrou (${exit.signal ? `signal ${exit.signal}` : `code ${exit.code}`}).`);
|
|
533
|
+
clearPidLock(home);
|
|
534
|
+
process.exit(exit.code ?? (exit.signal ? 1 : 0));
|
|
409
535
|
}
|
|
410
536
|
|
|
411
|
-
/**
|
|
537
|
+
/** Encerra o daemon: lock de PID + dono da porta (rede de segurança). */
|
|
412
538
|
async function commandStop() {
|
|
413
|
-
const
|
|
414
|
-
const
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
539
|
+
const home = resolveHome();
|
|
540
|
+
const lock = readPidLock(home);
|
|
541
|
+
// Porta: env > lock > padrão (o lock sabe em qual porta a instância subiu).
|
|
542
|
+
const port = Number(process.env.JOBFINDER_PORT) || lock?.port || 4040;
|
|
543
|
+
let killed = 0;
|
|
544
|
+
|
|
545
|
+
const candidates = [lock?.pid, pidOfPort(port)].filter((pid) => pid && pid !== process.pid);
|
|
546
|
+
for (const pid of candidates) {
|
|
547
|
+
if (isAlive(pid)) {
|
|
548
|
+
killTree(pid);
|
|
549
|
+
killed += 1;
|
|
550
|
+
}
|
|
421
551
|
}
|
|
422
552
|
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
553
|
+
// Confirma que a porta deixou de responder antes de declarar vitória.
|
|
554
|
+
const down = await new Promise(async (resolve) => {
|
|
555
|
+
for (let i = 0; i < 20; i += 1) {
|
|
556
|
+
let up = false;
|
|
557
|
+
try {
|
|
558
|
+
up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok;
|
|
559
|
+
} catch {
|
|
560
|
+
up = false;
|
|
561
|
+
}
|
|
562
|
+
if (!up) return resolve(true);
|
|
563
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
564
|
+
}
|
|
565
|
+
resolve(false);
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
clearPidLock(home);
|
|
569
|
+
if (killed > 0 || down) {
|
|
570
|
+
console.log(`JobFinder encerrado (${killed || 1} processo(s)).`);
|
|
571
|
+
return;
|
|
429
572
|
}
|
|
573
|
+
console.log('Nenhuma instância do JobFinder em execução.');
|
|
574
|
+
}
|
|
430
575
|
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
576
|
+
/* ------------------------------------------------------------------ *
|
|
577
|
+
* Argumentos *
|
|
578
|
+
* ------------------------------------------------------------------ */
|
|
579
|
+
function parseArgs(argv) {
|
|
580
|
+
const args = {
|
|
581
|
+
command: null,
|
|
582
|
+
foreground: false,
|
|
583
|
+
port: null,
|
|
584
|
+
host: null,
|
|
585
|
+
dataDir: null,
|
|
586
|
+
dryRun: false,
|
|
587
|
+
help: false,
|
|
588
|
+
version: false,
|
|
589
|
+
};
|
|
590
|
+
const rest = [...argv];
|
|
591
|
+
const first = rest[0];
|
|
592
|
+
if (first && !first.startsWith('-')) {
|
|
593
|
+
args.command = first;
|
|
594
|
+
rest.shift();
|
|
435
595
|
}
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
596
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
597
|
+
const token = rest[i];
|
|
598
|
+
switch (token) {
|
|
599
|
+
case '--port': args.port = Number(rest[i + 1]); i += 1; break;
|
|
600
|
+
case '--host': args.host = rest[i + 1]; i += 1; break;
|
|
601
|
+
case '--data-dir': args.dataDir = rest[i + 1]; i += 1; break;
|
|
602
|
+
case '--dry-run': args.dryRun = true; break;
|
|
603
|
+
case '--foreground': case '-f': args.foreground = true; break;
|
|
604
|
+
case '--daemon': break; // comportamento padrão; aceito por compatibilidade
|
|
605
|
+
case '--help': case '-h': args.help = true; break;
|
|
606
|
+
case '--version': case '-v': args.version = true; break;
|
|
607
|
+
case 'stop': case 'kill': args.command = 'stop'; break;
|
|
608
|
+
default:
|
|
609
|
+
if (token.startsWith('-')) console.warn(`[jobfinder] ignorando flag desconhecida: ${token}`);
|
|
610
|
+
break;
|
|
442
611
|
}
|
|
443
612
|
}
|
|
444
|
-
|
|
445
|
-
store.write('jobfinder-daemon.json', { ...info, pid: null, stoppedAt: new Date().toISOString() });
|
|
446
|
-
console.log('JobFinder parado.');
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
function commandVersion() {
|
|
450
|
-
console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
|
|
451
|
-
console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
|
|
613
|
+
return args;
|
|
452
614
|
}
|
|
453
615
|
|
|
454
616
|
async function main() {
|
|
455
617
|
const args = parseArgs(process.argv.slice(2));
|
|
456
618
|
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
619
|
+
if (args.help) {
|
|
620
|
+
console.log(USAGE.trim());
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (args.version) {
|
|
624
|
+
console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
|
|
625
|
+
console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
|
|
626
|
+
console.log(`home: ${resolveHome()}`);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
if (args.command === 'install') {
|
|
630
|
+
commandInstall(args);
|
|
460
631
|
return;
|
|
461
632
|
}
|
|
462
633
|
if (args.command === 'stop') {
|
|
463
634
|
await commandStop();
|
|
464
635
|
return;
|
|
465
636
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
break;
|
|
474
|
-
case 'version':
|
|
475
|
-
commandVersion();
|
|
476
|
-
break;
|
|
477
|
-
case 'start':
|
|
478
|
-
case null:
|
|
479
|
-
await commandStart(args);
|
|
480
|
-
break;
|
|
481
|
-
default:
|
|
482
|
-
console.error(`[jobfinder] unknown command: ${args.command}`);
|
|
483
|
-
console.log(USAGE.trim());
|
|
484
|
-
process.exit(1);
|
|
637
|
+
if (args.foreground) {
|
|
638
|
+
await commandForeground(args);
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
if (args.command === 'start' || args.command === 'daemon' || args.command === null) {
|
|
642
|
+
await commandDaemon(args);
|
|
643
|
+
return;
|
|
485
644
|
}
|
|
645
|
+
console.error(`[jobfinder] comando desconhecido: ${args.command}`);
|
|
646
|
+
console.log(USAGE.trim());
|
|
647
|
+
process.exit(1);
|
|
486
648
|
}
|
|
487
649
|
|
|
488
|
-
await main();
|
|
650
|
+
await main();
|