akanjs 3.0.0-beta.28 → 3.0.0-beta.29

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 (34) hide show
  1. package/package.json +1 -1
  2. package/server/akanApp.ts +5 -3
  3. package/server/akanServer.ts +16 -6
  4. package/server/contentEncoding.ts +11 -0
  5. package/server/ops/appInfo.ts +3 -1
  6. package/server/selfExec.ts +12 -4
  7. package/types/server/ops/appInfo.d.ts +1 -0
  8. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +17 -1
  9. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +8 -0
  10. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +2 -0
  11. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +7 -1
  12. package/types/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.d.ts +21 -6
  13. package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +19 -5
  14. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +20 -1
  15. package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +18 -0
  16. package/types/vendor/@akanjs/native/plugins/app/src/index.d.ts +7 -0
  17. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +7 -1
  18. package/types/vendor/@akanjs/native/plugins/updates/src/index.d.ts +18 -6
  19. package/vendor/@akanjs/native/packages/cli/src/api.ts +32 -12
  20. package/vendor/@akanjs/native/packages/cli/src/commands/update.ts +9 -2
  21. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +22 -5
  22. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +2 -0
  23. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +51 -26
  24. package/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.ts +198 -33
  25. package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +9 -2
  26. package/vendor/@akanjs/native/packages/desktop/src/host.ts +21 -9
  27. package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +20 -5
  28. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +82 -5
  29. package/vendor/@akanjs/native/packages/desktop/src/server.ts +124 -7
  30. package/vendor/@akanjs/native/plugins/app/native-plugin.json +1 -1
  31. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +5 -0
  32. package/vendor/@akanjs/native/plugins/app/src/index.ts +6 -1
  33. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +410 -111
  34. package/vendor/@akanjs/native/plugins/updates/src/index.ts +18 -6
@@ -1,13 +1,32 @@
1
1
 
2
2
 
3
3
  import { createHash, createPublicKey, verify } from "node:crypto";
4
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import {
5
+ closeSync,
6
+ existsSync,
7
+ fsyncSync,
8
+ mkdirSync,
9
+ openSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ renameSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ writeSync,
16
+ } from "node:fs";
17
+ import { uptime } from "node:os";
5
18
  import { basename, dirname, join } from "node:path";
6
19
  import { AkanNativeError } from "../../../packages/core/src/index.ts";
7
20
  import { isBundleId } from "../../../packages/core/src/kernel.ts";
8
21
  import { applyDelta } from "../../../packages/desktop/src/delta.ts";
9
- import { type DesktopContext, type DesktopPlugin, defineDesktopPlugin } from "../../../packages/desktop/src/plugin.ts";
10
- import { relaunchAfterExit } from "../../../packages/desktop/src/relaunch.ts";
22
+ import {
23
+ type DesktopContext,
24
+ type DesktopPlugin,
25
+ type DesktopServerState,
26
+ type DesktopServerStatus,
27
+ defineDesktopPlugin,
28
+ } from "../../../packages/desktop/src/plugin.ts";
29
+ import { type RelaunchOptions, relaunchAfterExit } from "../../../packages/desktop/src/relaunch.ts";
11
30
  import type { UpdateCheck, UpdateState, UpdatesApi, UpdatesEvents } from "./index.ts";
12
31
 
13
32
  export interface UpdatesConfig {
@@ -31,16 +50,34 @@ interface Entry {
31
50
  build: number;
32
51
  }
33
52
 
53
+ type Trial = Entry & {
54
+ previous: string;
55
+ attempts: number;
56
+ pid?: number;
57
+ boot?: number;
58
+ from?: number;
59
+ staged?: string;
60
+ };
61
+
34
62
  interface State {
35
63
  current?: Entry;
36
64
  pending?: Entry & { staged: string };
37
65
  /**
38
- * `pid`: the process running the trial, so a second instance of the app leaves it alone. `from` (Windows, where a
39
- * helper swaps after the app exited): the build that applied it, which is still what runs when the swap failed.
66
+ * `pid` and `boot` (when the system started, s): the process running the trial, so a second instance of the app
67
+ * leaves it alone. `from` (Windows, where a helper swaps after the app exited): the build that applied it, which is
68
+ * still what runs when the swap failed, with the release still at `staged`.
40
69
  */
41
- trial?: Entry & { previous: string; attempts: number; pid?: number; from?: number };
70
+ trial?: Trial;
42
71
  failed: string[];
72
+ /** Why each release in `failed` was failed. */
73
+ reasons?: Record<string, string>;
74
+ /** Tries of a release that failed for a reason that may pass (MAX_STRIKES). */
75
+ strikes?: Record<string, number>;
43
76
  rolledBack?: string;
77
+ /** A rollback whose moves may not have happened: the failed build, while it still runs, makes them again. */
78
+ rollback?: { build: number; previous: string; to: string; attempts: number };
79
+ /** embeddedSequence of the build installed here: another one means the app was installed again. */
80
+ installed?: number;
44
81
  }
45
82
 
46
83
  interface Manifest {
@@ -56,6 +93,8 @@ interface Manifest {
56
93
  arch?: string;
57
94
  archive?: { sha256: string; url: string; size: number; gzSha256: string };
58
95
  patches?: { from: string; url: string; sha256: string; size: number }[];
96
+ /** Whether the release carries a server (resources/server.json); a manifest published before it says nothing. */
97
+ server?: boolean;
59
98
  }
60
99
 
61
100
  /**
@@ -64,6 +103,10 @@ interface Manifest {
64
103
  * launcher's own wait (READY_TIMEOUT, 8 s) only decides when the window opens.
65
104
  */
66
105
  export const SERVER_BOOT_ALLOWANCE = 120_000;
106
+ /** A server whose init throws answered ready first: its release is confirmed only once it stayed up this long. */
107
+ export const SERVER_SETTLE = 5_000;
108
+ /** Tries of a release whose server did not come up, or whose Windows swap did not happen, before it is failed. */
109
+ export const MAX_STRIKES = 3;
67
110
 
68
111
  const MAX_MANIFEST = 1 << 20;
69
112
  const MAX_SIGNATURE = 1024;
@@ -79,6 +122,42 @@ function alive(pid: number): boolean {
79
122
  }
80
123
  }
81
124
 
125
+ /** When the system started, in seconds: a PID recorded under another boot names another process now. */
126
+ const bootTime = () => Math.round(Date.now() / 1000 - uptime());
127
+
128
+ const tarBinary = () =>
129
+ process.platform === "win32"
130
+ ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe")
131
+ : (["/usr/bin/tar", "/bin/tar"].find((path) => existsSync(path)) ?? "tar");
132
+
133
+ /** fsync of a file, or of a folder on macOS and Linux; Windows flushes only a handle opened for writing. */
134
+ function flush(path: string, folder = false): void {
135
+ if (folder && process.platform === "win32") return;
136
+ let fd: number | undefined;
137
+ try {
138
+ fd = openSync(path, folder || process.platform !== "win32" ? "r" : "r+");
139
+ fsyncSync(fd);
140
+ } catch {
141
+ } finally {
142
+ if (fd !== undefined) closeSync(fd);
143
+ }
144
+ }
145
+
146
+ /** An unpacked release reaches the disk before a rename points the app at it: a power cut must not leave empty files. */
147
+ function flushTree(root: string): void {
148
+
149
+ if (process.platform === "linux" && Bun.spawnSync(["sync"]).exitCode === 0) return;
150
+ const walk = (folder: string) => {
151
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
152
+ const path = join(folder, entry.name);
153
+ if (entry.isDirectory()) walk(path);
154
+ else if (entry.isFile()) flush(path);
155
+ }
156
+ flush(folder, true);
157
+ };
158
+ walk(root);
159
+ }
160
+
82
161
  /**
83
162
  * The running app, from the executable path: macOS <App>.app/Contents/MacOS/<exe>, Windows and
84
163
  * Linux the folder of <exe> with resources/ (packages/desktop/src/ffi.ts resolvePaths).
@@ -127,8 +206,9 @@ export interface DesktopUpdatesOptions {
127
206
  config?: UpdatesConfig | null;
128
207
  /** The executable's file name inside an app; the running one's by default. */
129
208
  exeName?: string;
130
- relaunch?(exe: string, moves: [string, string][]): Promise<void>;
209
+ relaunch?(exe: string, moves: [string, string][], recover?: RelaunchOptions["recover"]): Promise<void>;
131
210
  serverBootAllowance?: number;
211
+ serverSettle?: number;
132
212
  }
133
213
 
134
214
  export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): DesktopPlugin<UpdatesApi, UpdatesEvents> {
@@ -138,31 +218,50 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
138
218
  const exeName = options.exeName ?? basename(process.execPath);
139
219
  const installed = options.app !== undefined ? options.app : appPath(mac);
140
220
  const config = options.config !== undefined ? options.config : readConfig(installed, mac);
141
- const relaunch = options.relaunch ?? ((exe, moves) => relaunchAfterExit(exe, moves));
221
+ const relaunch = options.relaunch ?? ((exe, moves, recover) => relaunchAfterExit(exe, moves, { recover }));
142
222
  const allowance = options.serverBootAllowance ?? SERVER_BOOT_ALLOWANCE;
223
+ const settleTime = options.serverSettle ?? SERVER_SETTLE;
143
224
  /** The executable inside an app with the running one's name. */
144
225
  const executableIn = (app: string) => (mac ? join(app, "Contents", "MacOS", exeName) : join(app, exeName));
145
226
  const resources = (app: string) => resourcesOf(app, mac);
227
+ const carries = (app: string) => existsSync(join(resources(app), "server.json"));
146
228
  let dir = "";
147
229
  let onTrial = false;
148
230
  let timer: ReturnType<typeof setTimeout> | undefined;
149
231
  let downloading = false;
150
- let serverAnswered: Promise<boolean> = Promise.resolve(true);
232
+ let unwritableTold = false;
233
+ const refusalsTold = new Set<string>();
234
+ let serverAnswered: Promise<string | null> = Promise.resolve(null);
151
235
 
152
236
  const statePath = () => join(dir, "state.json");
153
- const readState = (): State => {
237
+ const parseState = (path: string): State | null => {
154
238
  try {
155
- const s = JSON.parse(readFileSync(statePath(), "utf8")) as State;
239
+ const s = JSON.parse(readFileSync(path, "utf8")) as State;
156
240
  return { ...s, failed: Array.isArray(s.failed) ? s.failed : [] };
157
241
  } catch {
158
- return { failed: [] };
242
+ return null;
159
243
  }
160
244
  };
245
+
246
+ const readState = (): State => parseState(statePath()) ?? parseState(`${statePath()}.bak`) ?? { failed: [] };
161
247
  const writeState = (state: State) => {
162
248
  mkdirSync(dir, { recursive: true });
163
- const tmp = `${statePath()}.tmp`;
164
- writeFileSync(tmp, JSON.stringify({ ...state, failed: state.failed.slice(-20) }));
165
- renameSync(tmp, statePath());
249
+ const path = statePath();
250
+ const failed = state.failed.slice(-20);
251
+ const reasons = state.reasons
252
+ ? Object.fromEntries(Object.entries(state.reasons).filter(([bundle]) => failed.includes(bundle)))
253
+ : undefined;
254
+ const tmp = `${path}.tmp`;
255
+ const fd = openSync(tmp, "w");
256
+ try {
257
+ writeSync(fd, JSON.stringify({ ...state, failed, reasons }));
258
+ fsyncSync(fd);
259
+ } finally {
260
+ closeSync(fd);
261
+ }
262
+ if (existsSync(path)) renameSync(path, `${path}.bak`);
263
+ renameSync(tmp, path);
264
+ flush(dir, true);
166
265
  };
167
266
  const need = (): UpdatesConfig => {
168
267
  if (!config)
@@ -172,34 +271,85 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
172
271
  );
173
272
  return config;
174
273
  };
175
- /** The running app is this release (installed by an update), not another build. */
176
- const runningIs = (entry: Entry | undefined) => !!entry && !!config && entry.build === config.embeddedSequence;
177
-
178
- const moveThenRelaunch = (moves: [string, string][], app: string) => relaunch(executableIn(app), moves);
274
+ /** `entry` when the running app is that release (installed by an update), not another build. */
275
+ const ifRunning = <E extends Entry>(entry: E | undefined): E | undefined =>
276
+ entry && config && entry.build === config.embeddedSequence ? entry : undefined;
277
+ const runningIs = (entry: Entry | undefined) => ifRunning(entry) !== undefined;
278
+ /** The release running now; one on trial is running too, confirmed or not. */
279
+ const runningSequence = (c: UpdatesConfig, state: State) =>
280
+ (ifRunning(state.trial) ?? ifRunning(state.current))?.sequence ?? c.embeddedSequence;
281
+
282
+ const fail = (state: State, bundle: string, why: string) => {
283
+ if (!state.failed.includes(bundle)) state.failed.push(bundle);
284
+ state.reasons = { ...state.reasons, [bundle]: why };
285
+ if (state.strikes) delete state.strikes[bundle];
286
+ };
287
+ /** One more failed try of `bundle`: true once it had `limit` of them, which makes it a failed release. */
288
+ const strike = (state: State, bundle: string, why: string, limit = MAX_STRIKES): boolean => {
289
+ const tries = (state.strikes?.[bundle] ?? 0) + 1;
290
+ if (tries < limit) {
291
+ state.strikes = { ...state.strikes, [bundle]: tries };
292
+ return false;
293
+ }
294
+ fail(state, bundle, limit > 1 ? `${why} (${tries} tries)` : why);
295
+ return true;
296
+ };
297
+ const entryOf = ({ bundle, sequence, version, tar, build }: Entry): Entry => ({
298
+ bundle,
299
+ sequence,
300
+ version,
301
+ tar,
302
+ build,
303
+ });
304
+
305
+ const recover = (): RelaunchOptions["recover"] =>
306
+ windows && config ? { script: join(dir, "recover.ps1"), name: `akan-native-update ${config.app}` } : undefined;
307
+ const moveThenRelaunch = (moves: [string, string][], app: string) => relaunch(executableIn(app), moves, recover());
179
308
 
180
- /** Puts .previous back, marks the trial failed and relaunches the old app. */
181
- const rollBack = async (state: State, quit: (code: number) => void, why: string): Promise<void> => {
309
+ /**
310
+ * Puts .previous back, then relaunches it. A release that may pass another time (`retry`) stays downloaded as the
311
+ * pending update until it had MAX_STRIKES; any other is failed.
312
+ */
313
+ const rollBack = async (state: State, quit: (code: number) => void, why: string, retry = false): Promise<void> => {
182
314
  const trial = state.trial;
183
315
  if (!trial || !installed) return;
184
316
  const app = installed;
185
- console.warn(`[akan-native] updates: ${trial.bundle} ${why}; rolling back`);
317
+ const failed = strike(state, trial.bundle, why, retry ? MAX_STRIKES : 1);
318
+ const tries = failed ? "" : `, to be tried again (${state.strikes?.[trial.bundle]} of ${MAX_STRIKES})`;
319
+ console.warn(`[akan-native] updates: ${trial.bundle} ${why}; rolling back${tries}`);
186
320
  state.trial = undefined;
187
- state.failed.push(trial.bundle);
188
321
  state.rolledBack = trial.bundle;
189
- if (existsSync(trial.previous)) {
190
- const failed = `${app}.failed-${trial.bundle}`;
191
- rmSync(failed, { recursive: true, force: true });
322
+ if (!existsSync(trial.previous)) {
192
323
  writeState(state);
324
+ return;
325
+ }
326
+
327
+ const keep = !failed && !(state.pending && state.pending.sequence > trial.sequence);
328
+ const to = keep ? join(`${app}.update-${trial.bundle}`, basename(app)) : `${app}.failed-${trial.bundle}`;
329
+ rmSync(keep ? dirname(to) : to, { recursive: true, force: true });
330
+ if (keep) {
331
+ mkdirSync(dirname(to), { recursive: true });
332
+ state.pending = { ...entryOf(trial), staged: to };
333
+ }
334
+ state.rollback = { build: trial.build, previous: trial.previous, to, attempts: 1 };
335
+ writeState(state);
336
+ try {
193
337
 
194
338
  await moveThenRelaunch(
195
339
  [
196
- [app, failed],
340
+ [app, to],
197
341
  [trial.previous, app],
198
342
  ],
199
343
  app,
200
344
  );
201
- quit(0);
202
- } else writeState(state);
345
+ } catch (error) {
346
+ console.error(
347
+ `[akan-native] updates: ${trial.bundle} could not be rolled back; the next start tries again`,
348
+ error,
349
+ );
350
+ return;
351
+ }
352
+ quit(0);
203
353
  };
204
354
 
205
355
  /**
@@ -262,88 +412,186 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
262
412
  typeof m.build !== "number" ||
263
413
  !m.archive ||
264
414
  !hex(m.archive.sha256) ||
265
- !hex(m.archive.gzSha256)
415
+ !hex(m.archive.gzSha256) ||
416
+ (m.server !== undefined && typeof m.server !== "boolean")
266
417
  ) {
267
418
  throw new AkanNativeError("INTERNAL", "invalid release manifest");
268
419
  }
269
420
  return m;
270
421
  };
271
422
 
272
- const running = (state: State) => (runningIs(state.current) ? state.current!.sequence : config!.embeddedSequence);
273
- const isNewer = (m: Manifest, state: State) => m.sequence > running(state) && !state.failed.includes(m.bundle);
423
+ const isNewer = (c: UpdatesConfig, m: Manifest, state: State) =>
424
+ m.sequence > runningSequence(c, state) && !state.failed.includes(m.bundle);
274
425
  const patchFor = (m: Manifest, state: State) => {
275
- const tar = runningIs(state.current) ? state.current!.tar : undefined;
426
+ const tar = ifRunning(state.current)?.tar;
276
427
  return tar && existsSync(join(dir, "app", `${tar}.tar`)) ? m.patches?.find((p) => p.from === tar) : undefined;
277
428
  };
278
429
 
279
- /** The carried server's first answer, or false once the release's boot allowance ran out. */
280
- const serverVerdict = (ctx: DesktopContext): Promise<boolean> => {
430
+ const serverRefusal = (release: boolean, app: string) =>
431
+ release === carries(app)
432
+ ? null
433
+ : `the release ${release ? "carries a server, and this app does not" : "carries no server, and this app does"}; install it instead`;
434
+
435
+ /** null once the carried server answered ready and stayed up SERVER_SETTLE; else why it did not in time. */
436
+ const serverVerdict = (server: DesktopServerStatus): Promise<string | null> =>
437
+ new Promise((resolve) => {
438
+ let settling: ReturnType<typeof setTimeout> | undefined;
439
+ let unsubscribe = () => {};
440
+ const done = (why: string | null) => {
441
+ clearTimeout(boot);
442
+ clearTimeout(settling);
443
+ unsubscribe();
444
+ resolve(why);
445
+ };
446
+ const boot = setTimeout(() => done(`its server was not up within ${allowance / 1000} s`), allowance);
447
+ const watch = (state: DesktopServerState) => {
448
+ clearTimeout(settling);
449
+ if (state === "up") settling = setTimeout(() => done(null), settleTime);
450
+ else if (state === "gaveUp") done("its server gave up");
451
+ };
452
+ unsubscribe = server.onState(watch);
453
+ watch(server.state);
454
+ });
455
+ /** true once the server is up (now or at its next ready), false when it gave up or the app quits first. */
456
+ const upAgain = (server: DesktopServerStatus) =>
457
+ new Promise<boolean>((resolve) => {
458
+ if (server.state === "up") return resolve(true);
459
+ const unsubscribe = server.onState((state) => {
460
+ if (state !== "up" && state !== "gaveUp" && state !== "stopped") return;
461
+ unsubscribe();
462
+ resolve(state === "up");
463
+ });
464
+ });
465
+
466
+ const watchTrial = (ctx: DesktopContext, c: UpdatesConfig) => {
467
+ onTrial = true;
468
+ const failTrial = (why: string, retry: boolean) => {
469
+ if (!onTrial) return;
470
+ onTrial = false;
471
+ clearTimeout(timer);
472
+ void rollBack(readState(), (code) => ctx.quit(code), why, retry);
473
+ };
281
474
  const server = ctx.server;
282
- if (!server) return Promise.resolve(true);
283
- return new Promise((resolve) => {
284
- const timer = setTimeout(() => {
285
- console.warn(`[akan-native] updates: the app's server did not answer ready within ${allowance / 1000} s`);
286
- resolve(false);
287
- }, allowance);
288
- void server.ready.then((ready) => {
475
+ serverAnswered = server ? serverVerdict(server) : Promise.resolve(null);
476
+ void serverAnswered.then((why) => why !== null && failTrial(why, true));
477
+ server?.onState((state) => state === "gaveUp" && failTrial("its server gave up", true));
478
+ ctx.onNativeEvent("pageLoad", (e) => {
479
+ if (e.event !== "finished" || (e.window ?? 1) !== 1 || !onTrial) return;
480
+
481
+ void serverAnswered.then((why) => {
482
+ if (why !== null || !onTrial) return;
289
483
  clearTimeout(timer);
290
- resolve(ready);
484
+ timer = setTimeout(() => failTrial("did not call notifyReady() in time", false), c.readyTimeout);
291
485
  });
292
486
  });
293
487
  };
294
488
 
295
- const setup = (ctx: DesktopContext) => {
296
-
297
- dir = join(ctx.appLocalDataDir, "akan-native-updates");
489
+ const setup = async (ctx: DesktopContext) => {
490
+
491
+ dir = join(ctx.appLocalDataDir, ctx.dev ? "akan-native-updates-debug" : "akan-native-updates");
298
492
  const app = installed;
299
493
  if (!config || !app) return;
300
494
  const state = readState();
495
+ let changed = false;
301
496
 
302
- if (state.pending && state.pending.sequence <= running(state)) {
497
+ if (!runningIs(state.current) && !runningIs(state.trial) && state.installed !== config.embeddedSequence) {
498
+ if (state.installed !== undefined) {
499
+ state.failed = [];
500
+ state.reasons = undefined;
501
+ state.strikes = undefined;
502
+ }
503
+ state.installed = config.embeddedSequence;
504
+ changed = true;
505
+ }
506
+
507
+ if (state.pending && state.pending.sequence <= runningSequence(config, state)) {
303
508
  console.warn(`[akan-native] updates: ${state.pending.bundle} is not newer than this app; dropping it`);
304
509
  state.pending = undefined;
305
- writeState(state);
510
+ changed = true;
306
511
  }
512
+ const rollback = state.rollback;
513
+ if (rollback) {
514
+ state.rollback = undefined;
515
+ changed = true;
516
+
517
+ if (
518
+ rollback.build === config.embeddedSequence &&
519
+ existsSync(rollback.previous) &&
520
+ rollback.attempts < MAX_STRIKES
521
+ ) {
522
+ state.rollback = { ...rollback, attempts: rollback.attempts + 1 };
523
+ writeState(state);
524
+ console.warn("[akan-native] updates: the last rollback did not happen; trying it again");
525
+ try {
526
+ rmSync(rollback.to, { recursive: true, force: true });
527
+ mkdirSync(dirname(rollback.to), { recursive: true });
528
+ await moveThenRelaunch(
529
+ [
530
+ [app, rollback.to],
531
+ [rollback.previous, app],
532
+ ],
533
+ app,
534
+ );
535
+ ctx.launch.exit(0);
536
+ return;
537
+ } catch (error) {
538
+ console.error("[akan-native] updates: the rollback failed again", error);
539
+ }
540
+ }
541
+ }
542
+ if (state.trial && !runningIs(state.trial)) {
543
+ const trial = state.trial;
544
+ state.trial = undefined;
545
+ changed = true;
546
+
547
+ if (trial.from === config.embeddedSequence) {
548
+ const failed = strike(state, trial.bundle, "could not be moved into place");
549
+ const tries = failed
550
+ ? ""
551
+ : `; it is tried again at the next apply (${state.strikes?.[trial.bundle]} of ${MAX_STRIKES})`;
552
+ console.warn(`[akan-native] updates: ${trial.bundle} could not be moved into place${tries}`);
553
+ if (
554
+ !failed &&
555
+ trial.staged &&
556
+ existsSync(executableIn(trial.staged)) &&
557
+ !(state.pending && state.pending.sequence > trial.sequence)
558
+ )
559
+ state.pending = { ...entryOf(trial), staged: trial.staged };
560
+ }
561
+ }
562
+ if (changed) writeState(state);
307
563
 
564
+ const confirmed = !state.trial && !state.rollback && runningIs(state.current);
308
565
  for (const name of readdirSync(dirname(app))) {
309
566
  const path = join(dirname(app), name);
310
567
  if (
311
568
  name.startsWith(`${basename(app)}.failed-`) ||
312
- (name.startsWith(`${basename(app)}.update-`) && path !== dirname(state.pending?.staged ?? ""))
569
+ (name.startsWith(`${basename(app)}.update-`) && path !== dirname(state.pending?.staged ?? "")) ||
570
+ (name === `${basename(app)}.previous` && confirmed)
313
571
  ) {
314
572
  rmSync(path, { recursive: true, force: true });
315
573
  }
316
574
  }
317
- if (state.trial) {
318
- if (!runningIs(state.trial)) {
575
+ const trial = state.trial;
576
+ if (!trial) return;
577
+ const boot = bootTime();
319
578
 
320
- if (state.trial.from === config.embeddedSequence) {
321
- console.warn(`[akan-native] updates: ${state.trial.bundle} could not be moved into place`);
322
- state.failed.push(state.trial.bundle);
323
- }
324
- state.trial = undefined;
325
- writeState(state);
326
- } else if (state.trial.pid !== undefined && state.trial.pid !== process.pid && alive(state.trial.pid)) {
327
- } else if (++state.trial.attempts > 1) {
328
- return rollBack(state, (code) => ctx.launch.exit(code), "was started again without notifyReady()");
329
- } else {
330
- state.trial.pid = process.pid;
331
- writeState(state);
332
- onTrial = true;
333
- const startClock = () => {
334
- clearTimeout(timer);
335
- timer = setTimeout(() => {
336
- if (onTrial) void rollBack(readState(), (code) => ctx.quit(code), "did not call notifyReady() in time");
337
- }, config.readyTimeout);
338
- };
339
- serverAnswered = serverVerdict(ctx);
340
- ctx.onNativeEvent("pageLoad", (e) => {
341
- if (e.event !== "finished" || (e.window ?? 1) !== 1 || !onTrial) return;
342
-
343
- void serverAnswered.then(() => onTrial && startClock());
344
- });
345
- }
579
+ if (
580
+ !ctx.server &&
581
+ trial.pid !== undefined &&
582
+ trial.pid !== process.pid &&
583
+ (trial.boot === undefined || Math.abs(trial.boot - boot) <= 60) &&
584
+ alive(trial.pid)
585
+ ) {
586
+
587
+ return;
346
588
  }
589
+ if (++trial.attempts > 1)
590
+ return rollBack(state, (code) => ctx.launch.exit(code), "was started again without notifyReady()");
591
+ trial.pid = process.pid;
592
+ trial.boot = boot;
593
+ writeState(state);
594
+ watchTrial(ctx, config);
347
595
  };
348
596
 
349
597
  const plugin: DesktopPlugin<UpdatesApi, UpdatesEvents> = {
@@ -355,7 +603,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
355
603
  async getState() {
356
604
  const c = need();
357
605
  const state = readState();
358
- const current = runningIs(state.trial) ? state.trial : runningIs(state.current) ? state.current : undefined;
606
+ const current = ifRunning(state.trial) ?? ifRunning(state.current);
359
607
  return {
360
608
  bundle: current?.bundle ?? null,
361
609
  sequence: current?.sequence ?? 0,
@@ -371,13 +619,18 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
371
619
  const c = need();
372
620
  const m = await fetchRelease(c);
373
621
  const state = readState();
374
- const available = isNewer(m, state);
622
+ const refusal = typeof m.server === "boolean" && installed ? serverRefusal(m.server, installed) : null;
623
+ if (refusal && !refusalsTold.has(m.bundle)) {
624
+ refusalsTold.add(m.bundle);
625
+ console.warn(`[akan-native] updates: ${m.bundle}: ${refusal}`);
626
+ }
627
+ const available = !refusal && isNewer(c, m, state);
375
628
  return {
376
629
  available,
377
630
  bundle: m.bundle,
378
631
  version: m.version,
379
632
  sequence: m.sequence,
380
- downloadSize: available ? (patchFor(m, state)?.size ?? m.archive!.size) : null,
633
+ downloadSize: available ? (patchFor(m, state)?.size ?? m.archive?.size ?? null) : null,
381
634
  } satisfies UpdateCheck;
382
635
  },
383
636
 
@@ -388,9 +641,30 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
388
641
  downloading = true;
389
642
  try {
390
643
  const m = await fetchRelease(c);
644
+ const archive = m.archive as NonNullable<Manifest["archive"]>;
391
645
  const state = readState();
392
- if (!isNewer(m, state)) throw new AkanNativeError("NOT_FOUND", "no newer release for this app");
646
+ if (!isNewer(c, m, state)) throw new AkanNativeError("NOT_FOUND", "no newer release for this app");
647
+ const refusal = typeof m.server === "boolean" ? serverRefusal(m.server, app) : null;
648
+ if (refusal) throw new AkanNativeError("NOT_ALLOWED", refusal);
393
649
  if (state.pending?.bundle === m.bundle && existsSync(state.pending.staged)) return { bundle: m.bundle };
650
+
651
+ const staging = `${app}.update-${m.bundle}`;
652
+ try {
653
+ rmSync(staging, { recursive: true, force: true });
654
+ mkdirSync(staging, { recursive: true });
655
+ } catch (error) {
656
+ if (!unwritableTold) {
657
+ unwritableTold = true;
658
+ console.warn(
659
+ `[akan-native] updates: cannot write beside ${app}; install new releases with the installer`,
660
+ error,
661
+ );
662
+ }
663
+ throw new AkanNativeError(
664
+ "NOT_ALLOWED",
665
+ `${dirname(app)} is not writable: install the release with its installer`,
666
+ );
667
+ }
394
668
 
395
669
  let tar: Uint8Array | null = null;
396
670
  const patch = patchFor(m, state);
@@ -408,26 +682,23 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
408
682
  }
409
683
  }
410
684
  if (!tar) {
411
- const gz = await fetchBytes(`${releases(c)}/${m.archive!.url}`, m.archive!.size, ctx);
412
- if (sha256(gz) !== m.archive!.gzSha256)
685
+ const gz = await fetchBytes(`${releases(c)}/${archive.url}`, archive.size, ctx);
686
+ if (sha256(gz) !== archive.gzSha256)
413
687
  throw new AkanNativeError("INTERNAL", "the release archive does not match its hash");
414
688
  tar = Bun.gunzipSync(gz as Uint8Array<ArrayBuffer>);
415
689
  }
416
- if (sha256(tar) !== m.archive!.sha256)
690
+ if (sha256(tar) !== archive.sha256)
417
691
  throw new AkanNativeError("INTERNAL", "the release does not match its hash");
418
692
 
419
- const staging = `${app}.update-${m.bundle}`;
420
- rmSync(staging, { recursive: true, force: true });
421
- mkdirSync(staging, { recursive: true });
422
693
  const tarFile = join(staging, "release.tar");
423
694
  writeFileSync(tarFile, tar);
424
695
  const run = async (cmd: string[]) => {
425
696
  const p = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" });
426
697
  const [err, code] = await Promise.all([new Response(p.stderr).text(), p.exited]);
427
- if (code !== 0) throw new AkanNativeError("INTERNAL", `${basename(cmd[0]!)} failed: ${err.trim()}`);
698
+ if (code !== 0) throw new AkanNativeError("INTERNAL", `${basename(cmd[0] ?? "")} failed: ${err.trim()}`);
428
699
  };
429
700
 
430
- await run([process.platform === "win32" ? "tar.exe" : "/usr/bin/tar", "-xf", tarFile, "-C", staging]);
701
+ await run([tarBinary(), "-xf", tarFile, "-C", staging]);
431
702
  rmSync(tarFile);
432
703
 
433
704
  const unpacked = readdirSync(staging);
@@ -461,30 +732,30 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
461
732
  throw new AkanNativeError("INTERNAL", `the release is ${id || "not an akan-native app"}, not ${c.app}`);
462
733
 
463
734
  if (mac) await run(["/usr/bin/codesign", "--verify", "--deep", "--strict", staged]);
464
-
465
- const carries = (root: string) => existsSync(join(resources(root), "server.json"));
466
- if (carries(staged) !== carries(app)) {
735
+ const unpackedRefusal = serverRefusal(carries(staged), app);
736
+ if (unpackedRefusal) {
467
737
  rmSync(staging, { recursive: true, force: true });
468
- state.failed.push(m.bundle);
469
- writeState(state);
470
- throw new AkanNativeError(
471
- "NOT_ALLOWED",
472
- `the release ${carries(app) ? "carries no server, and this app does" : "carries a server, and this app does not"}; install it instead`,
473
- );
738
+ const latest = readState();
739
+ fail(latest, m.bundle, unpackedRefusal);
740
+ writeState(latest);
741
+ throw new AkanNativeError("NOT_ALLOWED", unpackedRefusal);
474
742
  }
743
+ flushTree(staged);
475
744
 
476
745
  mkdirSync(join(dir, "app"), { recursive: true });
477
746
  for (const name of readdirSync(join(dir, "app"))) rmSync(join(dir, "app", name), { force: true });
478
- writeFileSync(join(dir, "app", `${m.archive!.sha256}.tar`), tar);
479
- state.pending = {
747
+ writeFileSync(join(dir, "app", `${archive.sha256}.tar`), tar);
748
+
749
+ const latest = readState();
750
+ latest.pending = {
480
751
  bundle: m.bundle,
481
752
  sequence: m.sequence,
482
753
  version: m.version,
483
- tar: m.archive!.sha256,
484
- build: m.build!,
754
+ tar: archive.sha256,
755
+ build: m.build as number,
485
756
  staged,
486
757
  };
487
- writeState(state);
758
+ writeState(latest);
488
759
  return { bundle: m.bundle };
489
760
  } finally {
490
761
  downloading = false;
@@ -495,15 +766,29 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
495
766
  const c = need();
496
767
  const app = installed as string;
497
768
  const state = readState();
769
+
770
+ if (runningIs(state.trial))
771
+ throw new AkanNativeError(
772
+ "NOT_ALLOWED",
773
+ "the running release is on trial: apply once notifyReady() confirmed it",
774
+ );
498
775
  const pending = state.pending;
499
- if (!pending || !existsSync(pending.staged) || pending.sequence <= running(state))
776
+ if (!pending || !existsSync(pending.staged) || pending.sequence <= runningSequence(c, state))
500
777
  throw new AkanNativeError("NOT_FOUND", "no downloaded update to apply");
778
+ const refusal = serverRefusal(carries(pending.staged), app);
779
+ if (refusal) {
780
+ rmSync(dirname(pending.staged), { recursive: true, force: true });
781
+ state.pending = undefined;
782
+ fail(state, pending.bundle, refusal);
783
+ writeState(state);
784
+ throw new AkanNativeError("NOT_ALLOWED", refusal);
785
+ }
501
786
  const previous = `${app}.previous`;
502
787
  rmSync(previous, { recursive: true, force: true });
503
- const { staged: _staged, ...entry } = pending;
788
+ const entry = entryOf(pending);
504
789
  if (windows) {
505
790
 
506
- state.trial = { ...entry, previous, attempts: 0, from: c.embeddedSequence };
791
+ state.trial = { ...entry, previous, attempts: 0, from: c.embeddedSequence, staged: pending.staged };
507
792
  state.pending = undefined;
508
793
  writeState(state);
509
794
  await moveThenRelaunch(
@@ -536,23 +821,30 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
536
821
  setTimeout(() => ctx.quit(0), 50);
537
822
  },
538
823
 
539
- async notifyReady() {
824
+ async notifyReady(_args, ctx) {
540
825
  const c = need();
541
826
  if (!onTrial) return;
542
827
 
543
- if (!(await serverAnswered)) return;
828
+ if ((await serverAnswered) !== null || !onTrial) return;
829
+
830
+ if (ctx.server && !(await upAgain(ctx.server))) return;
544
831
  if (!onTrial) return;
545
832
  clearTimeout(timer);
546
833
  onTrial = false;
547
834
  const state = readState();
548
835
  const trial = state.trial;
549
836
  if (!trial) return;
550
- const { previous, attempts: _attempts, ...entry } = trial;
837
+ const entry = entryOf(trial);
551
838
  state.current = entry;
552
839
  state.trial = undefined;
553
840
  state.rolledBack = undefined;
841
+ if (state.strikes) delete state.strikes[entry.bundle];
554
842
  writeState(state);
555
- rmSync(previous, { recursive: true, force: true });
843
+ try {
844
+ rmSync(trial.previous, { recursive: true, force: true });
845
+ } catch (error) {
846
+ console.warn(`[akan-native] updates: ${trial.previous} stays until the next start`, error);
847
+ }
556
848
  if (windows) void recordInstalledVersion(c.app, installed, entry.version);
557
849
  },
558
850
 
@@ -560,7 +852,14 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
560
852
  need();
561
853
  const state = readState();
562
854
  if (state.pending) rmSync(dirname(state.pending.staged), { recursive: true, force: true });
563
- writeState({ failed: [], ...(state.current ? { current: state.current } : {}) });
855
+
856
+ writeState({
857
+ failed: [],
858
+ ...(state.current ? { current: state.current } : {}),
859
+ ...(runningIs(state.trial) ? { trial: state.trial } : {}),
860
+ ...(state.rollback ? { rollback: state.rollback } : {}),
861
+ ...(state.installed !== undefined ? { installed: state.installed } : {}),
862
+ });
564
863
  },
565
864
  },
566
865
  };