@dhlotter/ai-usage 0.2.6 → 0.2.8

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 (2) hide show
  1. package/cli.mjs +143 -30
  2. package/package.json +1 -1
package/cli.mjs CHANGED
@@ -1,19 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { readFileSync } from 'node:fs';
5
- import { lstat, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
6
- import { join, resolve } from 'node:path';
4
+ import { readFileSync, realpathSync } from 'node:fs';
5
+ import { lstat, mkdir, mkdtemp, rm, rmdir, writeFile } from 'node:fs/promises';
6
+ import { dirname, join, resolve } from 'node:path';
7
7
  import { parseArgs, promisify } from 'node:util';
8
+ import { fileURLToPath } from 'node:url';
8
9
 
9
10
  const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
10
- const asset = `https://github.com/dhlotter/ai-usage/releases/download/v${version}/AI.Usage_${version}_universal.dmg`;
11
- const sha256 = '7d34a4707588183e1b7b17b4cd83e0d9642de148dca0490b7fca5c60ca266ae7';
11
+ // Installer releases can change without a new Mac build.
12
+ export const appVersion = '0.2.8';
13
+ const asset = `https://github.com/dhlotter/ai-usage/releases/download/v${appVersion}/AI.Usage_${appVersion}_universal.dmg`;
14
+ const sha256 = 'a3711fb578664f40c856842b81502e69372bdf2106f8b97e5f2172f91268c1ba';
12
15
  const app = 'AI Usage.app';
16
+ const bundleId = 'com.dhlotter.ai-usage';
13
17
  const run = promisify(execFile);
14
18
  const usage = `Usage: ai-usage install [--app-dir DIRECTORY]
15
- Install AI Usage ${version} on macOS 14 or later (Apple Silicon or Intel).
16
- Defaults to /Applications. An existing copy is never replaced.`;
19
+ Install or update AI Usage to ${appVersion} on macOS 14 or later (Apple Silicon or Intel).
20
+ Defaults to /Applications. Current and newer versions are left alone.`;
17
21
 
18
22
  export async function downloadVerified(fetchRelease = fetch) {
19
23
  const response = await fetchRelease(asset, { signal: AbortSignal.timeout(120_000) });
@@ -31,13 +35,94 @@ export async function downloadVerified(fetchRelease = fetch) {
31
35
  return Buffer.concat(chunks, size);
32
36
  }
33
37
 
34
- async function exists(path) {
38
+ async function pathInfo(path) {
35
39
  try {
36
- await lstat(path);
37
- return true;
40
+ return await lstat(path);
38
41
  } catch (error) {
39
42
  if (error.code !== 'ENOENT') throw error;
40
- return false;
43
+ return null;
44
+ }
45
+ }
46
+
47
+ async function readBundle(path) {
48
+ const info = await pathInfo(path);
49
+ if (!info) return null;
50
+ const unrecognised = `The item at ${path} is not a recognised AI Usage app. It was not changed.`;
51
+ if (!info.isDirectory()) throw new Error(unrecognised);
52
+
53
+ const plist = join(path, 'Contents', 'Info.plist');
54
+ const readKey = async key => (await run('/usr/bin/plutil', ['-extract', key, 'raw', '-expect', 'string', '-o', '-', plist])).stdout.trim();
55
+ const id = await readKey('CFBundleIdentifier').catch(() => '');
56
+ if (id !== bundleId) throw new Error(unrecognised);
57
+ const installedVersion = await readKey('CFBundleShortVersionString').catch(() => '');
58
+ if (!/^\d+\.\d+\.\d+$/.test(installedVersion)) {
59
+ throw new Error(`Cannot determine the AI Usage version at ${path}. It was not changed.`);
60
+ }
61
+ return { info, version: installedVersion };
62
+ }
63
+
64
+ async function requireClosedApp() {
65
+ try {
66
+ await run('/usr/bin/pgrep', ['-x', 'ai-usage']);
67
+ } catch (error) {
68
+ if (error.code === 1) return;
69
+ throw new Error('Could not check if AI Usage is running. No update was made.', { cause: error });
70
+ }
71
+ throw new Error('Quit AI Usage from the menu bar, then run this command again to update.');
72
+ }
73
+
74
+ const renameOnMac = `
75
+ ObjC.import('Foundation');
76
+ ObjC.bindFunction('open', ['int', ['char *', 'int']]);
77
+ ObjC.bindFunction('flock', ['int', ['int', 'int']]);
78
+ ObjC.bindFunction('close', ['int', ['int']]);
79
+ ObjC.bindFunction('renamex_np', ['int', ['char *', 'char *', 'unsigned int']]);
80
+ function run(args) {
81
+ const [source, destination, directory, expectedDevice, expectedInode] = args;
82
+ const fd = $.open(directory, 0);
83
+ if (fd < 0) throw Error('Could not open the install directory');
84
+ try {
85
+ // LOCK_EX | LOCK_NB. The kernel releases the lock even if this process is interrupted.
86
+ if ($.flock(fd, 6) !== 0) throw Error('Could not lock the install directory');
87
+ if (expectedInode) {
88
+ const info = $.NSFileManager.defaultManager.attributesOfItemAtPathError(destination, null);
89
+ const field = key => ObjC.unwrap(info.objectForKey(key).stringValue);
90
+ if (!info || field($.NSFileSystemNumber) !== expectedDevice || field($.NSFileSystemFileNumber) !== expectedInode) {
91
+ throw Error('The installed app changed during the download');
92
+ }
93
+ }
94
+ // RENAME_SWAP for an update; RENAME_EXCL for a fresh install.
95
+ if ($.renamex_np(source, destination, expectedInode ? 2 : 4) !== 0) throw Error('Atomic rename failed');
96
+ } finally {
97
+ $.close(fd);
98
+ }
99
+ }
100
+ `;
101
+
102
+ export async function moveIntoPlace(source, destination, expected) {
103
+ try {
104
+ await run('/usr/bin/osascript', ['-l', 'JavaScript', '-e', renameOnMac, '--', source, destination,
105
+ dirname(destination), String(expected?.dev ?? ''), String(expected?.ino ?? '')]);
106
+ } catch (error) {
107
+ const reason = /installed app changed/.test(error.stderr ?? '') ? 'The installed app changed. Run the installer again.'
108
+ : /Could not lock/.test(error.stderr ?? '') ? 'The install folder is busy or could not be locked. Try again.'
109
+ : 'Check permissions and use a folder on a local APFS volume.';
110
+ throw new Error(`Could not place the app at ${destination}. ${reason}`, { cause: error });
111
+ }
112
+ }
113
+
114
+ function isSameBundle(current, previous) {
115
+ return current && current.version === previous.version &&
116
+ current.info.dev === previous.info.dev && current.info.ino === previous.info.ino;
117
+ }
118
+
119
+ export async function replaceApp(staged, destination, installed) {
120
+ if (!isSameBundle(await readBundle(destination), installed)) {
121
+ throw new Error('The installed app changed during the download. Run this command again.');
122
+ }
123
+ await moveIntoPlace(staged, destination, installed.info);
124
+ if (!isSameBundle(await readBundle(staged).catch(() => null), installed)) {
125
+ throw new Error(`The installer displaced an unexpected app. It was preserved at ${staged}.`);
41
126
  }
42
127
  }
43
128
 
@@ -60,8 +145,20 @@ async function main(args) {
60
145
  if (values['app-dir'] === '') throw new Error('--app-dir must not be empty.');
61
146
  const directory = resolve(values['app-dir'] ?? '/Applications');
62
147
  const destination = join(directory, app);
63
- const existing = `AI Usage already exists at ${destination}. Quit it and move it to the Trash before reinstalling.`;
64
- if (await exists(destination)) throw new Error(existing);
148
+ const installed = await readBundle(destination);
149
+ if (installed) {
150
+ const available = appVersion.split('.').map(BigInt);
151
+ const order = installed.version.split('.').map((part, i) => BigInt(part) - available[i]).find(part => part !== 0n) ?? 0n;
152
+ if (order === 0n) {
153
+ console.log(`AI Usage ${appVersion} is already up to date.`);
154
+ return;
155
+ }
156
+ if (order > 0n) {
157
+ console.log(`Installed AI Usage ${installed.version} is newer than ${appVersion}. No changes made.`);
158
+ return;
159
+ }
160
+ await requireClosedApp();
161
+ }
65
162
 
66
163
  let temp;
67
164
  try {
@@ -77,41 +174,57 @@ async function main(args) {
77
174
  const mount = join(temp, 'mount');
78
175
  const dmg = join(temp, 'release.dmg');
79
176
  const staged = join(temp, app);
80
- let mounted = false;
177
+ let keepStaging = false;
81
178
  try {
82
- console.log(`Downloading AI Usage ${version} from GitHub...`);
179
+ console.log(`Downloading AI Usage ${appVersion} from GitHub...`);
83
180
  await writeFile(dmg, await downloadVerified(), { flag: 'wx', mode: 0o600 });
84
181
  console.log('SHA-256 verified.');
85
182
  await mkdir(mount);
86
183
  await run('/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-quiet', '-mountpoint', mount, dmg]);
87
- mounted = true;
88
184
  await run('/usr/bin/ditto', [join(mount, app), staged]);
89
- await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '-R', '=identifier "com.dhlotter.ai-usage"', staged]);
185
+ await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '-R', `=identifier "${bundleId}"`, staged]);
186
+ if ((await readBundle(staged))?.version !== appVersion) throw new Error('The verified app has an unexpected version.');
90
187
 
91
188
  // npm downloads are not tagged as browser downloads. Keep first-launch assessment with macOS.
92
189
  await run('/usr/bin/xattr', ['-w', 'com.apple.quarantine', `0081;${Math.floor(Date.now() / 1000).toString(16)};AI Usage Installer;`, staged]);
93
190
  await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]);
94
- mounted = false;
95
191
 
96
- // Same filesystem, with no overwrite if another installer got there first.
97
- await run('/bin/mv', ['-n', staged, directory]);
98
- if (await exists(staged)) throw new Error(existing);
99
- console.log(`Installed ${destination}. Open it from Finder.`);
192
+ if (installed) {
193
+ await requireClosedApp();
194
+ const downloaded = await lstat(staged);
195
+ // If the swap or its verification fails, delete only the original staged download.
196
+ keepStaging = true;
197
+ try {
198
+ await replaceApp(staged, destination, installed);
199
+ keepStaging = false;
200
+ } catch (error) {
201
+ const remaining = await pathInfo(staged).catch(() => null);
202
+ keepStaging = remaining?.dev !== downloaded.dev || remaining?.ino !== downloaded.ino;
203
+ throw error;
204
+ }
205
+ } else {
206
+ await moveIntoPlace(staged, destination);
207
+ }
208
+ console.log(`${installed ? `Updated AI Usage from ${installed.version} to ${appVersion} at` : 'Installed'} ${destination}. Open it from Finder.`);
100
209
  console.log('This release is not notarized. macOS may ask you to review it in Privacy & Security.');
101
210
  } finally {
102
- if (mounted) {
103
- try {
104
- await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]);
105
- mounted = false;
106
- } catch {
107
- console.error(`Could not eject ${mount}. The temporary files were left in place.`);
211
+ // Only remove staging once the mount is gone, even if attach itself failed.
212
+ if (await pathInfo(mount)) {
213
+ try { await rmdir(mount); }
214
+ catch {
215
+ try { await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]); }
216
+ catch {
217
+ console.error(`Could not eject ${mount}. The temporary files were left in place.`);
218
+ keepStaging = true;
219
+ }
108
220
  }
109
221
  }
110
- if (!mounted) await rm(temp, { recursive: true, force: true });
222
+ if (keepStaging) console.error(`Kept the staging directory at ${temp}.`);
223
+ else await rm(temp, { recursive: true, force: true });
111
224
  }
112
225
  }
113
226
 
114
- if (import.meta.main) {
227
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
115
228
  main(process.argv.slice(2)).catch(error => {
116
229
  console.error(`Error: ${error.message}`);
117
230
  process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dhlotter/ai-usage",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Install the AI Usage menu bar app for macOS",
5
5
  "license": "MIT",
6
6
  "repository": {