@aikyroon/installer-core 1.1.3 → 1.1.6

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.
Files changed (68) hide show
  1. package/dist/api.d.ts +5 -0
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +21 -4
  4. package/dist/api.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +80 -14
  7. package/dist/cli.js.map +1 -1
  8. package/dist/doctor.d.ts.map +1 -1
  9. package/dist/doctor.js +38 -4
  10. package/dist/doctor.js.map +1 -1
  11. package/dist/download.d.ts +12 -0
  12. package/dist/download.d.ts.map +1 -1
  13. package/dist/download.js +137 -7
  14. package/dist/download.js.map +1 -1
  15. package/dist/downloadsCache.d.ts +54 -0
  16. package/dist/downloadsCache.d.ts.map +1 -0
  17. package/dist/downloadsCache.js +153 -0
  18. package/dist/downloadsCache.js.map +1 -0
  19. package/dist/errors.d.ts +57 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +153 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/extract.d.ts +13 -3
  24. package/dist/extract.d.ts.map +1 -1
  25. package/dist/extract.js +64 -2
  26. package/dist/extract.js.map +1 -1
  27. package/dist/fsRetry.d.ts +14 -0
  28. package/dist/fsRetry.d.ts.map +1 -0
  29. package/dist/fsRetry.js +58 -0
  30. package/dist/fsRetry.js.map +1 -0
  31. package/dist/index.d.ts +11 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +9 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/install.d.ts +14 -0
  36. package/dist/install.d.ts.map +1 -1
  37. package/dist/install.js +486 -51
  38. package/dist/install.js.map +1 -1
  39. package/dist/lock.d.ts +7 -0
  40. package/dist/lock.d.ts.map +1 -0
  41. package/dist/lock.js +97 -0
  42. package/dist/lock.js.map +1 -0
  43. package/dist/logger.d.ts +34 -0
  44. package/dist/logger.d.ts.map +1 -1
  45. package/dist/logger.js +274 -1
  46. package/dist/logger.js.map +1 -1
  47. package/dist/manifest.d.ts +16 -2
  48. package/dist/manifest.d.ts.map +1 -1
  49. package/dist/manifest.js +30 -3
  50. package/dist/manifest.js.map +1 -1
  51. package/dist/processes.d.ts +28 -3
  52. package/dist/processes.d.ts.map +1 -1
  53. package/dist/processes.js +118 -7
  54. package/dist/processes.js.map +1 -1
  55. package/dist/retry.d.ts +26 -0
  56. package/dist/retry.d.ts.map +1 -0
  57. package/dist/retry.js +54 -0
  58. package/dist/retry.js.map +1 -0
  59. package/dist/types.d.ts +17 -0
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/uninstall.d.ts.map +1 -1
  62. package/dist/uninstall.js +5 -2
  63. package/dist/uninstall.js.map +1 -1
  64. package/dist/verify.d.ts +4 -3
  65. package/dist/verify.d.ts.map +1 -1
  66. package/dist/verify.js +14 -3
  67. package/dist/verify.js.map +1 -1
  68. package/package.json +1 -1
package/dist/install.js CHANGED
@@ -3,19 +3,51 @@ import fs from 'fs-extra';
3
3
  import { getLatestVersionInfo } from './api.js';
4
4
  import { defaultApiUrl, defaultInstallRoot, normalizeApiUrl, stripTrailingSep } from './config.js';
5
5
  import { downloadAndVerify } from './download.js';
6
+ import { findCachedPackage, formatBytes, pruneDownloads, recordDownload } from './downloadsCache.js';
7
+ import { EXIT, InstallError } from './errors.js';
6
8
  import { extractArchive, isTarball, locateBinary } from './extract.js';
7
- import { writeInstalledVersion, writeJsonAtomic } from './manifest.js';
9
+ import { removeQuiet, removeWithRetry, renameWithRetry } from './fsRetry.js';
10
+ import { acquireLock, releaseLock } from './lock.js';
11
+ import { markInstallInProgress, readInstalledVersion, writeInstalledVersion, writeJsonAtomic, } from './manifest.js';
8
12
  import { detectPlatform, resolveComponent } from './platform.js';
9
13
  import { ensurePythonLauncher } from './python.js';
10
- import { stopKyroonProcesses } from './processes.js';
14
+ import { anyProcessHoldingDir, isProcessAlive, stopKyroonProcesses } from './processes.js';
11
15
  import { createShortcuts } from './shortcuts.js';
12
16
  import { verifyInstall } from './verify.js';
13
17
  import * as log from './logger.js';
18
+ // ---------------------------------------------------------------------------
19
+ // Interrupção cooperativa (Ctrl+C)
20
+ //
21
+ // Matar o processo no meio da troca de arquivos é exatamente o que corrompia a
22
+ // instalação. Em vez de morrer na hora, o sinal levanta uma bandeira: o fluxo
23
+ // termina a operação atômica em curso e para no próximo ponto seguro.
24
+ // ---------------------------------------------------------------------------
25
+ let abortRequested = false;
26
+ export function requestGracefulAbort() {
27
+ abortRequested = true;
28
+ }
29
+ export function isAbortRequested() {
30
+ return abortRequested;
31
+ }
32
+ function throwIfAborted(step) {
33
+ if (!abortRequested)
34
+ return;
35
+ throw new InstallError('Instalação interrompida a pedido do usuário.', {
36
+ step,
37
+ exitCode: EXIT.INTERRUPTED,
38
+ hint: 'Nenhum arquivo ficou pela metade. Execute o instalador novamente quando quiser.',
39
+ });
40
+ }
14
41
  /**
15
42
  * Installs the requested components "flat" under `<installRoot>/<component>/`,
16
43
  * each with its own copy of the native updater (win/linux/macOS). Mirrors the
17
44
  * launcher-less `install.ps1` flow: detect -> download(+SHA256) -> stop -> python
18
45
  * -> extract -> updater -> manifest -> shortcuts -> activate/start.
46
+ *
47
+ * A substituição dos arquivos é ATÔMICA: o pacote é extraído e validado num
48
+ * diretório de staging irmão e só então trocado por `rename`, com backup e
49
+ * rollback. Em nenhum momento o diretório do componente fica parcialmente
50
+ * apagado — que era a causa raiz da perda de arquivos relatada em campo.
19
51
  */
20
52
  export async function installComponents(options) {
21
53
  const platform = detectPlatform();
@@ -26,6 +58,7 @@ export async function installComponents(options) {
26
58
  const selected = dedupeComponents(options.components);
27
59
  const specs = selected.map((name) => requireSpec(name, platform));
28
60
  await fs.ensureDir(installRoot);
61
+ log.openFileLog(installRoot);
29
62
  const downloadsDir = path.join(installRoot, 'downloads');
30
63
  await fs.ensureDir(downloadsDir);
31
64
  log.banner('Kyroon Enterprise Installer', [
@@ -33,7 +66,38 @@ export async function installComponents(options) {
33
66
  `Components : ${selected.join(', ')}`,
34
67
  `API URL : ${apiUrl}`,
35
68
  `InstallRoot : ${installRoot}`,
69
+ `Log : ${log.fileLogPath() ?? '(console apenas)'}`,
36
70
  ]);
71
+ // Repetido fora do banner porque é a primeira coisa que o suporte vai pedir
72
+ // quando alguém disser "travou e não apareceu nada".
73
+ if (log.fileLogPath()) {
74
+ log.info(`Em caso de problema, envie este arquivo ao suporte: ${log.fileLogPath()}`);
75
+ }
76
+ // Impede que dois instaladores (ou o Updater agendado) mexam no mesmo
77
+ // diretório ao mesmo tempo — corrida que também corrompe a instalação.
78
+ await acquireLock(installRoot);
79
+ try {
80
+ // Retoma uma troca interrompida por queda de energia/kill numa execução anterior.
81
+ await recoverInterruptedSwaps(installRoot);
82
+ return await runInstall({
83
+ platform,
84
+ apiUrl,
85
+ installRoot,
86
+ downloadsDir,
87
+ specs,
88
+ selected,
89
+ wantService,
90
+ wantStart,
91
+ force: options.force ?? false,
92
+ activationCode: options.activationCode,
93
+ });
94
+ }
95
+ finally {
96
+ await releaseLock(installRoot);
97
+ }
98
+ }
99
+ async function runInstall(ctx) {
100
+ const { platform, apiUrl, installRoot, downloadsDir, specs, selected } = ctx;
37
101
  // 1) Detect versions (components + native updater when distributed).
38
102
  log.step('[1/7] Detecting latest versions...');
39
103
  const updaterSpec = resolveComponent('updater', platform); // win/linux/macOS (null only on unsupported RIDs)
@@ -48,19 +112,65 @@ export async function installComponents(options) {
48
112
  infos.set(spec.name, info);
49
113
  log.info(`${spec.display} v${info.versionBuild}`);
50
114
  }
51
- // 2) Download everything (no running binary is touched yet).
115
+ // 1.5) O que realmente precisa ser (re)instalado?
116
+ //
117
+ // Sem esta comparação, `kyroon update` chamado duas vezes baixava e trocava
118
+ // tudo duas vezes. A referência é o `installed-version.json` de cada
119
+ // componente (mesmo critério do Updater .NET: comparação por SHA256).
120
+ const pending = [];
121
+ const upToDate = [];
122
+ for (const spec of specs) {
123
+ if (!ctx.force && (await isUpToDate(path.join(installRoot, spec.name), spec, infos.get(spec.name)))) {
124
+ upToDate.push(spec);
125
+ }
126
+ else {
127
+ pending.push(spec);
128
+ }
129
+ }
130
+ for (const spec of upToDate) {
131
+ log.success(`${spec.display} já está na v${infos.get(spec.name).versionBuild} — nada a baixar.`);
132
+ }
133
+ throwIfAborted('[1/7] Detecting latest versions');
134
+ // 2) Download apenas do que mudou (no running binary is touched yet).
52
135
  log.step('[2/7] Downloading packages...');
136
+ const needsUpdaterPackage = pending.length > 0 || (await anyUpdaterOutdated(installRoot, upToDate, updaterInfo));
53
137
  let updaterArchive = null;
54
- if (updaterSpec && updaterInfo) {
138
+ if (updaterSpec && updaterInfo && needsUpdaterPackage) {
55
139
  updaterArchive = await downloadAndVerify(updaterInfo, 'updater', downloadsDir);
140
+ await recordDownload(downloadsDir, 'updater', updaterInfo, updaterArchive, updaterSpec.fileType);
56
141
  }
57
142
  const archives = new Map();
58
- for (const spec of specs) {
59
- archives.set(spec.name, await downloadAndVerify(infos.get(spec.name), spec.name, downloadsDir));
143
+ for (const spec of pending) {
144
+ const info = infos.get(spec.name);
145
+ const cached = await findCachedPackage(downloadsDir, spec.name, info);
146
+ if (cached) {
147
+ // Acontece quando uma execução anterior baixou tudo e falhou depois — a
148
+ // segunda tentativa não repete os gigabytes.
149
+ log.info(`${spec.display}: pacote v${cached.versionBuild} já está em downloads/ (${formatBytes(cached.sizeBytes)}).`);
150
+ }
151
+ const file = await downloadAndVerify(info, spec.name, downloadsDir);
152
+ // Índice do cache: permite reaproveitar o pacote e descartar os antigos.
153
+ await recordDownload(downloadsDir, spec.name, info, file, spec.fileType);
154
+ archives.set(spec.name, file);
155
+ }
156
+ if (pending.length === 0)
157
+ log.info('Nenhum pacote para baixar — tudo já está atualizado.');
158
+ throwIfAborted('[2/7] Downloading packages');
159
+ // 3) Stop running processes (e CONFIRMA que saíram da memória).
160
+ //
161
+ // Só quando há algo a trocar: um `update` com tudo em dia não pode derrubar
162
+ // o Worker e o App que o usuário está usando.
163
+ const updaterArchiveForRefresh = updaterSpec && updaterInfo && updaterArchive
164
+ ? { spec: updaterSpec, info: updaterInfo, archive: updaterArchive }
165
+ : null;
166
+ if (pending.length > 0) {
167
+ log.step('[3/7] Stopping running Kyroon processes...');
168
+ await stopKyroonProcesses(platform);
169
+ }
170
+ else {
171
+ log.step('[3/7] Stopping running Kyroon processes...');
172
+ log.info('Nada a substituir — os componentes em execução foram preservados.');
60
173
  }
61
- // 3) Stop running processes.
62
- log.step('[3/7] Stopping running Kyroon processes...');
63
- await stopKyroonProcesses(platform);
64
174
  // 3.5) Ensure Python launcher for the Worker JSONL hooks.
65
175
  if (selected.includes('worker')) {
66
176
  await ensurePythonLauncher(platform).catch((err) => log.warn(`ensurePythonLauncher failed: ${err instanceof Error ? err.message : String(err)}`));
@@ -69,31 +179,60 @@ export async function installComponents(options) {
69
179
  log.step('[4/7] Installing components...');
70
180
  const installed = [];
71
181
  const binByComponent = new Map();
182
+ const failures = [];
72
183
  for (const spec of specs) {
184
+ throwIfAborted('[4/7] Installing components');
73
185
  const info = infos.get(spec.name);
74
186
  const componentDir = path.join(installRoot, spec.name);
75
- log.info(`${spec.display} -> ${componentDir}`);
76
- await cleanComponentDir(componentDir);
77
- await extractArchive(archives.get(spec.name), componentDir, {
78
- strip: stripFor(spec.name, info.fileName, platform),
79
- });
80
- await fs.remove(archives.get(spec.name));
81
- const binary = await locateBinary(componentDir, spec.binary);
82
- if (!binary)
83
- throw new Error(`${spec.binary} not found in ${componentDir} after extraction.`);
84
- await ensureExecutable(platform, binary);
85
- if (updaterSpec && updaterInfo && updaterArchive) {
86
- await installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec);
87
- }
88
- await writeInstalledVersion(componentDir, spec, info, platform, apiUrl);
89
- installed.push({ name: spec.name, dir: componentDir, binary, version: info.versionBuild });
90
- binByComponent.set(spec.name, binary);
91
- }
92
- if (updaterArchive)
93
- await fs.remove(updaterArchive);
187
+ // Já está na versão mais recente: nada é baixado nem trocado. Ainda assim
188
+ // o updater embutido é conferido — pular o componente não pode congelar o
189
+ // mecanismo que faz as próximas atualizações.
190
+ if (!pending.includes(spec)) {
191
+ try {
192
+ if (updaterArchiveForRefresh)
193
+ await refreshUpdaterIfNeeded(componentDir, updaterArchiveForRefresh);
194
+ const binary = await locateBinary(componentDir, spec.binary);
195
+ if (!binary)
196
+ throw new InstallError(`${spec.binary} não encontrado em ${componentDir}.`);
197
+ installed.push({ name: spec.name, dir: componentDir, binary, version: info.versionBuild, skipped: true });
198
+ binByComponent.set(spec.name, binary);
199
+ }
200
+ catch (err) {
201
+ failures.push({ spec, error: err });
202
+ log.error(`${spec.display}: ${err instanceof Error ? err.message : String(err)}`);
203
+ }
204
+ continue;
205
+ }
206
+ try {
207
+ const outcome = await installOneComponent({
208
+ spec,
209
+ info,
210
+ archive: archives.get(spec.name),
211
+ installRoot,
212
+ platform,
213
+ apiUrl,
214
+ updater: updaterArchiveForRefresh,
215
+ });
216
+ installed.push(outcome);
217
+ binByComponent.set(spec.name, outcome.binary);
218
+ }
219
+ catch (err) {
220
+ // BUG-08: a falha de um componente não pode cancelar os outros — e o
221
+ // usuário precisa saber o que ficou instalado e o que não ficou.
222
+ failures.push({ spec, error: err });
223
+ log.error(`${spec.display}: ${err instanceof Error ? err.message : String(err)}`);
224
+ log.warn(`${spec.display} não foi instalado — seguindo com os demais componentes.`);
225
+ }
226
+ }
227
+ // Os pacotes ficam em `downloads/` para a próxima execução; só as versões
228
+ // antigas são descartadas (senão o cache cresceria para sempre).
229
+ await pruneDownloads(downloadsDir);
230
+ if (failures.length > 0 && installed.length === 0) {
231
+ throw asInstallError(failures[0].error, failures, specs.length, installed.length);
232
+ }
94
233
  // 5) Shortcuts + boot auto-start.
95
234
  log.step('[5/7] Creating shortcuts and boot auto-start...');
96
- if (wantService) {
235
+ if (ctx.wantService) {
97
236
  const targets = [];
98
237
  for (const c of ['app', 'worker']) {
99
238
  const binary = binByComponent.get(c);
@@ -108,9 +247,9 @@ export async function installComponents(options) {
108
247
  // 6) Activation + start.
109
248
  log.step('[6/7] Activation and startup...');
110
249
  await activateAndStart(platform, binByComponent, {
111
- activationCode: options.activationCode,
112
- service: wantService,
113
- start: wantStart,
250
+ activationCode: ctx.activationCode,
251
+ service: ctx.wantService,
252
+ start: ctx.wantStart,
114
253
  });
115
254
  // 7) Verify the install is complete and runnable ("tudo certinho").
116
255
  log.step('[7/7] Verifying installation...');
@@ -118,14 +257,289 @@ export async function installComponents(options) {
118
257
  const problems = await verifyInstall(result, platform);
119
258
  const hard = problems.filter((p) => p.hard);
120
259
  if (hard.length > 0) {
121
- throw new Error(`Install verification failed: ${hard.map((p) => `${p.component} (${p.message})`).join('; ')}`);
260
+ throw new InstallError(`A verificação final falhou: ${hard.map((p) => `${p.component} (${p.message})`).join('; ')}`, { hint: "Execute 'repair' para refazer a instalação dos componentes com problema." });
122
261
  }
123
- log.banner('Kyroon Enterprise installed!', [
262
+ if (failures.length > 0) {
263
+ throw asInstallError(failures[0].error, failures, specs.length, installed.length);
264
+ }
265
+ const changed = installed.filter((c) => !c.skipped);
266
+ log.banner(changed.length === 0 ? 'Kyroon Enterprise já está atualizado!' : 'Kyroon Enterprise installed!', [
124
267
  `Install root : ${installRoot}`,
125
- ...installed.map((c) => `${c.name} : ${c.dir}`),
268
+ ...installed.map((c) => `${c.name} : v${c.version}${c.skipped ? ' (já atualizado)' : ''} — ${c.dir}`),
269
+ ...(log.fileLogPath() ? [`Log : ${log.fileLogPath()}`] : []),
126
270
  ]);
127
271
  return result;
128
272
  }
273
+ /** Consolida as falhas por componente numa mensagem única e acionável. */
274
+ function asInstallError(first, failures, total, ok) {
275
+ const names = failures.map((f) => f.spec.name).join(',');
276
+ return new InstallError(`${ok} de ${total} componentes instalados. Falhou: ${names}.`, {
277
+ cause: first,
278
+ exitCode: first instanceof InstallError ? first.exitCode : undefined,
279
+ hint: first instanceof InstallError && first.hint
280
+ ? first.hint
281
+ : `Execute 'repair -c ${names}' para tentar novamente apenas o que faltou.`,
282
+ });
283
+ }
284
+ async function installOneComponent(args) {
285
+ const { spec, info, archive, installRoot, platform, apiUrl, updater } = args;
286
+ const componentDir = path.join(installRoot, spec.name);
287
+ const staging = path.join(installRoot, `.staging-${spec.name}-${process.pid}`);
288
+ const backup = path.join(installRoot, `.backup-${spec.name}-${process.pid}`);
289
+ log.info(`${spec.display} -> ${componentDir}`);
290
+ // ── Fase 1: montar a nova versão COMPLETA em staging ────────────────────
291
+ // Nada em `componentDir` é tocado aqui. Se qualquer coisa falhar, a
292
+ // instalação atual continua íntegra e funcionando.
293
+ log.debug(`${spec.name}: staging=${staging} · backup=${backup} · archive=${archive}`);
294
+ let end = log.beginOp(`${spec.name}: limpar staging anterior`);
295
+ await removeWithRetry(staging, { label: `${spec.name} staging` });
296
+ await fs.ensureDir(staging);
297
+ end();
298
+ try {
299
+ end = log.beginOp(`${spec.name}: extrair pacote`);
300
+ await extractArchive(archive, staging, {
301
+ strip: stripFor(spec.name, info.fileName, platform),
302
+ label: spec.display,
303
+ });
304
+ end();
305
+ end = log.beginOp(`${spec.name}: localizar ${spec.binary}`);
306
+ const stagedBinary = await locateBinary(staging, spec.binary);
307
+ end(stagedBinary ?? 'NÃO ENCONTRADO');
308
+ if (!stagedBinary) {
309
+ throw new InstallError(`O pacote do ${spec.display} não contém ${spec.binary} — instalação abortada sem alterar ${componentDir}.`, { hint: 'Nenhum arquivo foi perdido. Tente novamente; se persistir, informe o suporte.' });
310
+ }
311
+ await ensureExecutable(platform, stagedBinary);
312
+ end = log.beginOp(`${spec.name}: instalar updater`);
313
+ if (updater) {
314
+ await installUpdater(staging, updater.archive, updater.info, updater.spec);
315
+ }
316
+ else {
317
+ await carryOverUpdater(componentDir, staging);
318
+ }
319
+ end();
320
+ // Manifesto definitivo já vai dentro do staging: assim, no instante em que
321
+ // a troca termina, o diretório final já está consistente.
322
+ end = log.beginOp(`${spec.name}: gravar installed-version.json`);
323
+ await writeInstalledVersion(staging, spec, info, platform, apiUrl, 'ok');
324
+ end();
325
+ }
326
+ catch (err) {
327
+ await removeQuiet(staging);
328
+ throw err;
329
+ }
330
+ // ── Fase 2: portão antes de tocar no destino ────────────────────────────
331
+ end = log.beginOp(`${spec.name}: conferir processos segurando a pasta`);
332
+ const holding = await anyProcessHoldingDir(platform, componentDir);
333
+ end(holding ? 'HÁ processo na pasta' : 'nenhum processo na pasta');
334
+ if (holding) {
335
+ await removeQuiet(staging);
336
+ throw new InstallError(`Não foi possível atualizar ${componentDir}: ainda há processos do Kyroon em execução nessa pasta.`, {
337
+ exitCode: EXIT.LOCKED,
338
+ hint: 'Feche o Kyroon App, o Kyroon Terminal e o Worker (ícone ao lado do relógio), ' +
339
+ 'aguarde 10 segundos e execute o instalador novamente. Nenhum arquivo foi alterado.',
340
+ });
341
+ }
342
+ // ── Fase 3: troca atômica com backup e rollback ─────────────────────────
343
+ const hadPrevious = await fs.pathExists(componentDir);
344
+ if (hadPrevious) {
345
+ // Marca "em transição": se o processo morrer daqui em diante, o estado é
346
+ // DETECTÁVEL (verify/doctor/Updater veem `installing` e mandam reparar) em
347
+ // vez de o manifesto antigo seguir mentindo que está tudo certo.
348
+ await markInstallInProgress(componentDir, spec, info, platform, apiUrl).catch((err) => log.debug(`não foi possível marcar ${spec.name} como 'installing': ${String(err)}`));
349
+ }
350
+ let swapped = false;
351
+ try {
352
+ if (hadPrevious) {
353
+ end = log.beginOp(`${spec.name}: mover instalação atual para backup`);
354
+ await removeWithRetry(backup, { label: `${spec.name} backup antigo` });
355
+ await renameWithRetry(componentDir, backup, { label: `${spec.name}: backup` });
356
+ end();
357
+ }
358
+ end = log.beginOp(`${spec.name}: publicar nova versão (rename)`);
359
+ await renameWithRetry(staging, componentDir, { label: `${spec.name}: publicação` });
360
+ end();
361
+ swapped = true;
362
+ }
363
+ catch (err) {
364
+ // Rollback: restaura a versão anterior INTEIRA.
365
+ if (hadPrevious && !swapped && (await fs.pathExists(backup))) {
366
+ try {
367
+ await removeWithRetry(componentDir, { attempts: 3 });
368
+ await renameWithRetry(backup, componentDir, { attempts: 8 });
369
+ log.warn(`${spec.display}: alteração revertida — a versão anterior foi preservada.`);
370
+ }
371
+ catch (rollbackErr) {
372
+ log.error(`${spec.display}: FALHA CRÍTICA no rollback — a versão anterior ficou em ${backup}. ` +
373
+ `Detalhe: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
374
+ }
375
+ }
376
+ await removeQuiet(staging);
377
+ throw new InstallError(`Falha ao substituir os arquivos do ${spec.display}: ${err instanceof Error ? err.message : String(err)}`, { cause: err, exitCode: EXIT.ROLLBACK });
378
+ }
379
+ await removeQuiet(backup);
380
+ // O pacote NÃO é apagado: fica em `downloads/` para que a próxima execução
381
+ // (`update` rodado de novo, `repair`) não precise baixar tudo outra vez.
382
+ // `pruneDownloads` cuida de descartar as versões antigas.
383
+ const binary = await locateBinary(componentDir, spec.binary);
384
+ if (!binary) {
385
+ throw new InstallError(`${spec.binary} não encontrado em ${componentDir} após a instalação.`, {
386
+ hint: "Execute 'repair' para refazer a instalação deste componente.",
387
+ });
388
+ }
389
+ log.success(`${spec.display} v${info.versionBuild} instalado.`);
390
+ return { name: spec.name, dir: componentDir, binary, version: info.versionBuild };
391
+ }
392
+ // ---------------------------------------------------------------------------
393
+ // "Preciso mesmo mexer neste componente?"
394
+ // ---------------------------------------------------------------------------
395
+ /**
396
+ * `true` quando o componente já está na versão publicada e íntegro.
397
+ *
398
+ * A comparação é por **SHA256** — o mesmo critério do `Kyroon.Updater` (.NET) —
399
+ * e não por número de versão, para que um rebuild da mesma versão também seja
400
+ * detectado. Exige ainda que a instalação tenha terminado (`status !== 'installing'`)
401
+ * e que o executável exista de fato: um manifesto "em dia" apontando para uma
402
+ * pasta mutilada é justamente o cenário que deixava a máquina quebrada em
403
+ * silêncio, e ele tem que resultar em REINSTALAR, não em pular.
404
+ */
405
+ async function isUpToDate(componentDir, spec, info) {
406
+ const manifest = await readInstalledVersion(componentDir);
407
+ if (!manifest)
408
+ return false;
409
+ if (manifest.status === 'installing')
410
+ return false;
411
+ if (manifest.sha256?.toLowerCase() !== info.sha256.toLowerCase())
412
+ return false;
413
+ return (await locateBinary(componentDir, spec.binary)) !== null;
414
+ }
415
+ /** SHA do updater atualmente instalado sob `<componentDir>/updater`. */
416
+ async function installedUpdaterSha(componentDir) {
417
+ try {
418
+ const sentinel = await fs.readJson(path.join(componentDir, 'updater', '.updater-version.json'));
419
+ const sha = sentinel.sha256;
420
+ return typeof sha === 'string' ? sha.toLowerCase() : null;
421
+ }
422
+ catch {
423
+ return null;
424
+ }
425
+ }
426
+ /**
427
+ * Algum componente "em dia" está com um updater desatualizado? Se sim, o pacote
428
+ * do updater precisa ser baixado mesmo sem nenhum componente para trocar —
429
+ * caso contrário pular componentes congelaria o mecanismo de atualização.
430
+ */
431
+ async function anyUpdaterOutdated(installRoot, upToDate, updaterInfo) {
432
+ if (!updaterInfo)
433
+ return false;
434
+ const expected = updaterInfo.sha256.toLowerCase();
435
+ for (const spec of upToDate) {
436
+ if ((await installedUpdaterSha(path.join(installRoot, spec.name))) !== expected)
437
+ return true;
438
+ }
439
+ return false;
440
+ }
441
+ /** Troca o `updater/` de um componente que não foi reinstalado, se estiver velho. */
442
+ async function refreshUpdaterIfNeeded(componentDir, updater) {
443
+ if (!(await fs.pathExists(componentDir)))
444
+ return;
445
+ if ((await installedUpdaterSha(componentDir)) === updater.info.sha256.toLowerCase())
446
+ return;
447
+ // Mesma disciplina do componente: monta ao lado e troca por rename.
448
+ const staging = path.join(componentDir, `.updater-new-${process.pid}`);
449
+ const old = path.join(componentDir, `.updater-old-${process.pid}`);
450
+ const target = path.join(componentDir, 'updater');
451
+ await removeWithRetry(staging);
452
+ try {
453
+ await installUpdater(staging, updater.archive, updater.info, updater.spec, { asDir: true });
454
+ const hadPrevious = await fs.pathExists(target);
455
+ if (hadPrevious)
456
+ await renameWithRetry(target, old);
457
+ try {
458
+ await renameWithRetry(staging, target);
459
+ }
460
+ catch (err) {
461
+ if (hadPrevious)
462
+ await renameWithRetry(old, target).catch(() => { });
463
+ throw err;
464
+ }
465
+ await removeQuiet(old);
466
+ log.info(`Updater atualizado para v${updater.info.versionBuild} em ${componentDir}.`);
467
+ }
468
+ catch (err) {
469
+ await removeQuiet(staging);
470
+ // Updater desatualizado não impede o uso do componente — avisa e segue.
471
+ log.warn(`Não foi possível atualizar o updater em ${componentDir}: ` +
472
+ `${err instanceof Error ? err.message : String(err)}`);
473
+ }
474
+ }
475
+ /**
476
+ * Recupera uma troca interrompida por morte abrupta do processo (queda de
477
+ * energia, kill -9) numa execução ANTERIOR: se sobrou `.backup-<comp>-<pid>` e
478
+ * o diretório do componente não existe, devolve o backup ao lugar.
479
+ */
480
+ async function recoverInterruptedSwaps(installRoot) {
481
+ let entries;
482
+ try {
483
+ entries = await fs.readdir(installRoot);
484
+ }
485
+ catch {
486
+ return;
487
+ }
488
+ // Trocas do `updater/` interrompidas (são internas a cada componente).
489
+ for (const component of ['worker', 'terminal', 'app']) {
490
+ await recoverUpdaterSwap(path.join(installRoot, component));
491
+ }
492
+ for (const entry of entries) {
493
+ const match = /^\.backup-(worker|terminal|app)-\d+$/.exec(entry);
494
+ if (!match) {
495
+ if (/^\.staging-(worker|terminal|app)-\d+$/.test(entry)) {
496
+ await removeQuiet(path.join(installRoot, entry));
497
+ }
498
+ continue;
499
+ }
500
+ const component = match[1];
501
+ const backupDir = path.join(installRoot, entry);
502
+ const componentDir = path.join(installRoot, component);
503
+ if (await fs.pathExists(componentDir)) {
504
+ await removeQuiet(backupDir); // troca concluiu; backup é lixo
505
+ continue;
506
+ }
507
+ try {
508
+ await renameWithRetry(backupDir, componentDir, { label: `recuperar ${component}` });
509
+ log.warn(`${component}: uma instalação anterior foi interrompida no meio da troca — ` +
510
+ 'a versão que estava instalada foi restaurada.');
511
+ }
512
+ catch (err) {
513
+ log.warn(`${component}: não foi possível restaurar automaticamente ${backupDir}: ` +
514
+ `${err instanceof Error ? err.message : String(err)}`);
515
+ }
516
+ }
517
+ }
518
+ /** Idem para a troca isolada do `updater/` dentro de um componente. */
519
+ async function recoverUpdaterSwap(componentDir) {
520
+ let entries;
521
+ try {
522
+ entries = await fs.readdir(componentDir);
523
+ }
524
+ catch {
525
+ return;
526
+ }
527
+ const target = path.join(componentDir, 'updater');
528
+ for (const entry of entries) {
529
+ if (/^\.updater-new-\d+$/.test(entry)) {
530
+ await removeQuiet(path.join(componentDir, entry));
531
+ continue;
532
+ }
533
+ if (!/^\.updater-old-\d+$/.test(entry))
534
+ continue;
535
+ const old = path.join(componentDir, entry);
536
+ if (await fs.pathExists(target)) {
537
+ await removeQuiet(old);
538
+ continue;
539
+ }
540
+ await renameWithRetry(old, target).catch(() => log.warn(`Não foi possível restaurar o updater a partir de ${old}.`));
541
+ }
542
+ }
129
543
  /** Guarantees a POSIX binary is executable (zip extraction can drop the bit). */
130
544
  async function ensureExecutable(platform, binary) {
131
545
  if (platform.os === 'win')
@@ -146,13 +560,13 @@ function dedupeComponents(components) {
146
560
  out.push(c);
147
561
  }
148
562
  if (out.length === 0)
149
- throw new Error('No components selected to install.');
563
+ throw new InstallError('Nenhum componente selecionado para instalar.');
150
564
  return out;
151
565
  }
152
566
  function requireSpec(name, platform) {
153
567
  const spec = resolveComponent(name, platform);
154
568
  if (!spec) {
155
- throw new Error(`Component '${name}' is not distributed for ${platform.slug}.`);
569
+ throw new InstallError(`O componente '${name}' não é distribuído para ${platform.slug}.`);
156
570
  }
157
571
  return spec;
158
572
  }
@@ -164,22 +578,31 @@ function stripFor(name, fileName, platform) {
164
578
  return 0;
165
579
  return 1;
166
580
  }
167
- /** Wipes a component dir but preserves `updater/` and `installed-version.json`. */
168
- async function cleanComponentDir(dir) {
169
- if (!(await fs.pathExists(dir))) {
170
- await fs.ensureDir(dir);
581
+ /**
582
+ * Sem pacote de updater para este RID, preserva o `updater/` já instalado
583
+ * copiando-o para o staging (o swap substitui a pasta inteira, então o que não
584
+ * for carregado junto se perde).
585
+ */
586
+ async function carryOverUpdater(componentDir, staging) {
587
+ const from = path.join(componentDir, 'updater');
588
+ if (!(await fs.pathExists(from)))
171
589
  return;
590
+ try {
591
+ await fs.copy(from, path.join(staging, 'updater'), { overwrite: true, errorOnExist: false });
592
+ log.debug(`updater/ preservado a partir de ${from}`);
172
593
  }
173
- for (const entry of await fs.readdir(dir)) {
174
- if (entry === 'updater' || entry === 'installed-version.json')
175
- continue;
176
- await fs.remove(path.join(dir, entry));
594
+ catch (err) {
595
+ log.warn(`Não foi possível preservar o updater existente: ${err instanceof Error ? err.message : String(err)}`);
177
596
  }
178
597
  }
179
- /** Installs a fresh copy of the native updater under `<componentDir>/updater`. */
180
- async function installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec) {
181
- const updaterDir = path.join(componentDir, 'updater');
182
- await fs.remove(updaterDir);
598
+ /**
599
+ * Installs a fresh copy of the native updater under `<componentDir>/updater`.
600
+ * Com `asDir`, o primeiro argumento JÁ É o diretório de destino do updater
601
+ * (usado pela troca isolada do `refreshUpdaterIfNeeded`).
602
+ */
603
+ async function installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec, opts = {}) {
604
+ const updaterDir = opts.asDir ? componentDir : path.join(componentDir, 'updater');
605
+ await removeWithRetry(updaterDir, { label: 'updater' });
183
606
  await fs.ensureDir(updaterDir);
184
607
  await extractArchive(updaterArchive, updaterDir, { strip: isTarball(updaterInfo.fileName) ? 1 : 0 });
185
608
  const bin = await locateBinary(updaterDir, updaterSpec.binary);
@@ -213,7 +636,7 @@ async function activateAndStart(platform, binByComponent, opts) {
213
636
  log.info('Startup skipped.');
214
637
  return;
215
638
  }
216
- if (workerBin) {
639
+ if (workerBin && !(await alreadyRunning(platform, workerBin))) {
217
640
  try {
218
641
  // Windows: no args -> the Worker opens its System Tray (stays alive and
219
642
  // consumes tasks). Linux/macOS: bare invocation only prints help and
@@ -227,7 +650,7 @@ async function activateAndStart(platform, binByComponent, opts) {
227
650
  }
228
651
  }
229
652
  const appBin = binByComponent.get('app');
230
- if (appBin) {
653
+ if (appBin && !(await alreadyRunning(platform, appBin))) {
231
654
  try {
232
655
  if (platform.os === 'osx') {
233
656
  // The macOS app is a `.app` bundle (kyroon_app.app) and cannot be
@@ -243,4 +666,16 @@ async function activateAndStart(platform, binByComponent, opts) {
243
666
  }
244
667
  }
245
668
  }
669
+ /**
670
+ * Um componente que não foi substituído continua rodando — relançá-lo abriria
671
+ * uma segunda instância. Só sobe o que está fora do ar.
672
+ */
673
+ async function alreadyRunning(platform, binary) {
674
+ const name = path.basename(binary, path.extname(binary));
675
+ if (await isProcessAlive(platform, name)) {
676
+ log.info(`${name} já está em execução — não será iniciado novamente.`);
677
+ return true;
678
+ }
679
+ return false;
680
+ }
246
681
  //# sourceMappingURL=install.js.map