@androperator/emulator-macos-tweaks 1.0.0 → 1.0.2

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @androperator/emulator-macos-tweaks
2
2
 
3
- A completely and utterly unessential utility that makes Android™ emulators feel more at home on macOS. Give your phone, tablet, TV, watch and automotive emulators distinct icons that fit in with the rest of your apps, with safe backups and an easy way to undo the changes.
3
+ A completely and utterly unessential utility that makes Android™ emulators feel more at home on macOS. Give your phone, tablet, TV, watch and automotive emulators distinct icons and AVD labels that fit in with the rest of your apps, with safe backups and an easy way to undo the changes.
4
4
 
5
5
  **With `androperator-emulator-tweaks`:**
6
6
 
@@ -10,7 +10,7 @@ A completely and utterly unessential utility that makes Android™ emulators fee
10
10
 
11
11
  ![Without androperator-emulator-tweaks: three identical circular emulator icons, with qemu-system-aarch64 selected](docs/images/emulator-app-switcher-before.png)
12
12
 
13
- Per-device icons are supported by the CLI. The `Pixel_9` label in the screenshot uses the [experimental AVD naming launcher](experimental/README.md); ordinary CLI-patched launches keep their executable label.
13
+ The CLI applies both per-device icons and AVD names to standard SDK launches, including launches from ADBuddy. The screenshots show tablet, phone and watch emulators with `Pixel_9` selected.
14
14
 
15
15
  This is an independent CLI. It does not depend on ADBuddy or change emulator launch arguments, virtual devices, headless emulators, or Android Studio itself.
16
16
 
@@ -25,7 +25,7 @@ This first release intentionally supports one verified binary. Intel and other e
25
25
 
26
26
  Patching replaces Google's signature with a **local ad-hoc signature**, preserving the original entitlements and hardened runtime. The modified emulator is no longer Google-signed or notarized. No developer certificate or private key is used. Gatekeeper may treat the patched emulator differently. The CLI does not disable Gatekeeper or change system security settings.
27
27
 
28
- Automatic icons use a bundled arm64 AppKit helper loaded by a verified weak dependency added to the supported GUI executable. No Xcode, background service or launch wrapper is needed for CLI users. The helper selects artwork from the AVD metadata separately for each process and keeps it through Qt icon updates.
28
+ Automatic icons use a bundled arm64 AppKit helper loaded by a verified weak dependency added to the supported GUI executable. Xcode and a background service are not required. Naming uses a bundled native dispatcher at the SDK backend path; the standard SDK frontend remains unchanged. The helper selects artwork from the AVD metadata separately for each process and keeps it through Qt icon updates.
29
29
 
30
30
  Every `apply` invocation requires `--accept-adhoc-signing` to acknowledge this tradeoff, including repeated calls and reapplying a saved patch. Without it, the CLI explains the change and exits before SDK discovery or file modification. `status` and `restore` do not require the flag. Restore reinstates the exact original executable and Google’s original signature.
31
31
 
@@ -58,7 +58,7 @@ androperator-emulator-tweaks status --json
58
58
  androperator-emulator-tweaks apply --accept-adhoc-signing --icons phone
59
59
  ```
60
60
 
61
- Restart your emulator after applying or restoring. Existing running processes keep their current icon. Future standalone launches through Android Studio, the terminal, or other apps use the patched executable in that SDK. The artwork uses Apple's macOS 27 icon shape and lighting; it does not dynamically switch Liquid Glass appearances. Automatic selection reads initial AVD configuration, not live rotation or folding. Wear, TV and automotive tags take precedence; known tablet profiles or a configured minimum width of 600 density-independent pixels select tablet. Foldable profiles remain phone. Unknown or missing metadata falls back to phone. AVD metadata follows Android environment roots and custom `.ini` pointers; `-datadir` does not replace the named AVD's metadata. Android Studio embedded mode has not been validated.
61
+ Restart your emulator after applying or restoring. Existing running processes keep their current icon and label. Future standalone launches through Android Studio, the terminal, or other apps use the patched executable in that SDK. The artwork uses Apple's macOS 27 icon shape and lighting; it does not dynamically switch Liquid Glass appearances. Automatic selection reads initial AVD configuration, not live rotation or folding. Wear, TV and automotive tags take precedence; known tablet profiles or a configured minimum width of 600 density-independent pixels select tablet. Foldable profiles remain phone. Unknown or missing metadata falls back to phone. AVD metadata follows Android environment roots and custom `.ini` pointers; `-datadir` does not replace the named AVD's metadata. Android Studio embedded mode has not been validated.
62
62
 
63
63
  ## Backups and restoration
64
64
 
@@ -78,12 +78,35 @@ An interrupted run after signing has a prepared receipt and can recover on the n
78
78
 
79
79
  If you installed the prototype from a previous experiment, first run its own restore command. The CLI refuses to adopt an unrecognized pre-existing patch, even if it looks identical. Then run this CLI's `apply --accept-adhoc-signing` to create a managed backup.
80
80
 
81
- ## Experimental AVD names
82
-
83
- [Experimental tooling](experimental/README.md) provides optional per-AVD named
84
- preview launchers in temporary SDK copies. Naming is excluded from the npm
85
- package and has not been integrated with ordinary installed-SDK launches.
86
- The main CLI changes icons only; it does not rename Dock entries.
81
+ ## AVD names
82
+
83
+ `apply` enables AVD labels by default. The standard `emulator` launcher and
84
+ ADBuddy continue to pass the same arguments and environment. Each standalone
85
+ GUI backend gets an executable named after its AVD, with separate caches for
86
+ simultaneous devices. `-avd Name` and `@Name` are supported. Headless and unnamed
87
+ calls retain the conventional executable label. Android Studio embedded mode
88
+ has not been live-verified.
89
+
90
+ Use `apply --accept-adhoc-signing --names off` for icons only. `status --json`
91
+ reports `names` and `namingHealthy`; `restore` restores the exact original
92
+ backend and removes an unchanged managed naming configuration. Unrecognized
93
+ configuration files are never overwritten or deleted.
94
+
95
+ Naming requires Node.js at launch time. Apply records the current Node executable
96
+ as an absolute path, so ADBuddy does not need Node on its PATH. If an upgrade
97
+ removes that Node path, reapply using the new Node installation. Keep the printed
98
+ backup directory in place: it contains the backend, dispatcher, launch script,
99
+ configuration and per-AVD SDK copies. Missing or corrupt naming resources stop
100
+ launching with an error; restoration remains available through a working CLI.
101
+ The first launch copies the backend for that AVD. Later launches reuse the
102
+ hash-verified copy. These copies link SDK libraries and system images and must
103
+ not be used for SDK maintenance. No AVD data is copied or renamed.
104
+
105
+ Older icon-only receipts remain restorable, and applying naming creates a separate
106
+ generation without replacing the original backups. Use this CLI version or newer
107
+ to restore a naming patch; older icon-only CLI releases do not recognize it.
108
+ [Experimental tooling](experimental/README.md) remains available for development
109
+ of the older temporary preview approach.
87
110
 
88
111
  ## Development and release
89
112
 
@@ -92,15 +115,16 @@ npm test
92
115
  npm pack --dry-run
93
116
  # Developers with Xcode and a graphical macOS session:
94
117
  node scripts/verify-icons.mjs
118
+ node scripts/verify-names.mjs
95
119
  ```
96
120
 
97
121
  Tests use synthetic executables and fake process integrations. They require neither an Android SDK nor a device. macOS CI runs on Node.js 22 and 24. Real signing and boot checks supplement these tests for the supported build.
98
122
 
99
123
  To add support for a build, use an untouched, signature-verified vendor executable. Record its revision, build ID, architecture, full SHA-256, and each original PNG hash and allocation length in `src/profiles.json`. The patcher discovers images by content rather than fixed offsets. Provide replacement PNGs that fit those allocations exactly, with valid chunks and checksums. Verify signing, boot, Dock appearance, and exact restore on that build before adding it to the support table. Do not loosen hash checks to accept a new build.
100
124
 
101
- The editable `assets/Emulator.icon` source uses a vector phone/Android symbol, white background, and Apple's native icon renderer. The bundled 32, 128 and 256 pixel PNGs were compiled with Xcode's asset compiler and palette-compressed to fit the emulator's allocations. Xcode is not required by CLI users. Native helper source is in `native/`; `node scripts/build-runtime.mjs` rebuilds the packaged arm64 helper and all five icons and writes their content manifest. Rebuild and run native verification after changing those sources; review the regenerated manifest and runtime files together.
125
+ The editable `assets/Emulator.icon` source uses a vector phone/Android symbol, white background, and Apple's native icon renderer. The bundled 32, 128 and 256 pixel PNGs were compiled with Xcode's asset compiler and palette-compressed to fit the emulator's allocations. Xcode is not required by CLI users. Native helper source is in `native/`; `node scripts/build-runtime.mjs` rebuilds the packaged arm64 helper and all five icons and writes their content manifest. `npm run build:launcher` rebuilds the AVD dispatcher and its manifest. Rebuild and run native verification after changing those sources; review the regenerated manifest and runtime files together.
102
126
 
103
- Before publishing, run the tests and inspect the package contents, update the version and release notes, and publish explicitly with `npm publish --access public`. This repository has no automatic publishing workflow.
127
+ Releases are prepared through reviewed PRs, then published from version tags using GitHub Trusted Publishing. See [the release guide](docs/releasing.md) and [release skill](.agents/skills/release-package/SKILL.md). On macOS, `npm run release:pack` validates a temporary installation of the archive without modifying your SDK. Publishing requires explicit authorization.
104
128
 
105
129
  ## License and attribution
106
130
 
Binary file
@@ -0,0 +1,5 @@
1
+ {
2
+ "schema": 1,
3
+ "architecture": "arm64",
4
+ "sha256": "e0e01fd672c9595fd8b70e9525bf81438fc75ecda6662435c35007a2ed9550e0"
5
+ }
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
+ import { readFileSync } from 'node:fs';
3
4
  import { apply, restore, inspect } from '../src/core.js';
4
- const help = `Usage: androperator-emulator-tweaks <status|apply|restore> [--accept-adhoc-signing] [--icons auto|phone] [--sdk PATH] [--backup-dir PATH] [--json]
5
+ const help = `Usage: androperator-emulator-tweaks <status|apply|restore> [--accept-adhoc-signing] [--icons auto|phone] [--names avd|off] [--sdk PATH] [--backup-dir PATH] [--json]
5
6
 
6
7
  status Detect the SDK, version, executable support and backup state.
7
- apply Install automatic per-device icons; requires --accept-adhoc-signing.
8
+ apply Install per-device icons and AVD labels; requires --accept-adhoc-signing.
8
9
  restore Restore the exact original executable if the current patch matches.
9
10
 
10
11
  SDK discovery: --sdk, ANDROID_HOME, ANDROID_SDK_ROOT, ~/Library/Android/sdk.
@@ -15,26 +16,27 @@ used. Gatekeeper may treat the patched emulator differently. Restore reinstates
15
16
  the original executable and Google's signature.
16
17
  Example: androperator-emulator-tweaks apply --accept-adhoc-signing
17
18
  Icons: auto (default) selects phone, tablet, TV, watch or automotive from AVD metadata.
18
- Use --icons phone with apply for the fixed phone icon. AVD names remain experimental.
19
+ Use --icons phone with apply for the fixed phone icon. Names: avd (default) labels standard SDK launches, including ADBuddy. Use --names off for icons only.
19
20
  Restart emulators after apply or restore.
20
21
  SDK updates may remove the patch; unsupported builds are never modified.`;
21
22
  try {
22
23
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
23
- 'accept-adhoc-signing': { type: 'boolean' }, icons: { type: 'string' }, sdk: { type: 'string' }, 'backup-dir': { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }
24
+ 'accept-adhoc-signing': { type: 'boolean' }, icons: { type: 'string' }, names: { type: 'string' }, sdk: { type: 'string' }, 'backup-dir': { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }
24
25
  }});
25
26
  if (values.help || !positionals.length && !values.version) console.log(help);
26
- else if (values.version) console.log('1.0.0');
27
+ else if (values.version) console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
27
28
  else {
28
29
  if (positionals.length !== 1 || !['status', 'apply', 'restore'].includes(positionals[0])) throw new Error('Expected status, apply, or restore. Use --help.');
29
30
  const command = positionals[0];
30
31
  if (values.icons && (command !== 'apply' || !['auto', 'phone'].includes(values.icons))) throw new Error('--icons auto|phone is only valid with apply');
32
+ if (values.names && (command !== 'apply' || !['avd', 'off'].includes(values.names))) throw new Error('--names avd|off is only valid with apply');
31
33
  if (command === 'apply' && !values['accept-adhoc-signing']) {
32
34
  throw new Error("apply requires --accept-adhoc-signing. Applying this patch replaces Google's signature with a local ad-hoc signature while preserving its entitlements and hardened runtime. No developer certificate or private key is used. Gatekeeper may treat the patched emulator differently. Restore reinstates the original executable and Google's signature. No files changed.\nRun: androperator-emulator-tweaks apply --accept-adhoc-signing");
33
35
  }
34
- const result = await ({ status: inspect, apply, restore }[command])({ sdk: values.sdk, backupDir: values['backup-dir'], icons: values.icons });
35
- const output = { command, icons: result.icons, runtimeHealthy: result.runtimeHealthy, sdk: result.sdk, revision: result.revision, state: result.state, changed: result.changed ?? false, executable: result.target, sha256: result.targetHash, backup: result.backup ?? result.receipt?.directory ?? null };
36
+ const result = await ({ status: inspect, apply, restore }[command])({ sdk: values.sdk, backupDir: values['backup-dir'], icons: values.icons, names: values.names });
37
+ const output = { command, names: result.names, namingHealthy: result.namingHealthy, icons: result.icons, runtimeHealthy: result.runtimeHealthy, sdk: result.sdk, revision: result.revision, state: result.state, changed: result.changed ?? false, executable: result.target, sha256: result.targetHash, backup: result.backup ?? result.receipt?.directory ?? null };
36
38
  // Refresh the reported hash after a successful mutation.
37
39
  if (result.changed) output.sha256 = (await inspect({ sdk: values.sdk, backupDir: values['backup-dir'] })).targetHash;
38
- console.log(values.json ? JSON.stringify(output, null, 2) : `${result.state}${result.icons ? ` (${result.icons} icons${result.runtimeHealthy === false ? ', runtime missing or corrupt; restore remains available' : ''})` : ''}: Android Emulator ${result.revision}\n${result.target}${output.backup ? `\nBackup: ${output.backup}` : ''}${result.changed ? '\nRestart emulators to see the change.' : ''}`);
40
+ console.log(values.json ? JSON.stringify(output, null, 2) : `${result.state}${result.names === 'avd' ? ` (AVD names${result.namingHealthy === false ? ', naming runtime missing or corrupt; restore remains available' : ''})` : ''}${result.icons ? ` (${result.icons} icons${result.runtimeHealthy === false ? ', runtime missing or corrupt; restore remains available' : ''})` : ''}: Android Emulator ${result.revision}\n${result.target}${output.backup ? `\nBackup: ${output.backup}` : ''}${result.changed ? '\nRestart emulators to see the change.' : ''}`);
39
41
  }
40
42
  } catch (error) { console.error(`androperator-emulator-tweaks: ${error.message}`); process.exitCode = 1; }
package/package.json CHANGED
@@ -1,13 +1,43 @@
1
1
  {
2
2
  "name": "@androperator/emulator-macos-tweaks",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Reversible macOS tweaks for supported Android Emulator builds",
5
5
  "type": "module",
6
- "bin": { "androperator-emulator-tweaks": "bin/androperator-emulator-tweaks.js" },
7
- "engines": { "node": ">=22" },
8
- "os": ["darwin"],
6
+ "bin": {
7
+ "androperator-emulator-tweaks": "bin/androperator-emulator-tweaks.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=22"
11
+ },
12
+ "os": [
13
+ "darwin"
14
+ ],
9
15
  "license": "Apache-2.0",
10
- "publishConfig": { "access": "public" },
11
- "files": ["bin", "src", "assets", "NOTICE.md", "LICENSE"],
12
- "scripts": { "test": "node --test", "prepack": "npm test", "build:runtime": "node scripts/build-runtime.mjs", "verify:icons": "node scripts/verify-icons.mjs" }
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "files": [
20
+ "bin",
21
+ "src",
22
+ "assets",
23
+ "NOTICE.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "test": "node --test",
28
+ "prepack": "npm test",
29
+ "build:runtime": "node scripts/build-runtime.mjs",
30
+ "verify:icons": "node scripts/verify-icons.mjs",
31
+ "release:pack": "node scripts/release-pack.mjs",
32
+ "build:launcher": "node scripts/build-launcher.mjs",
33
+ "verify:names": "node scripts/verify-names.mjs"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/androperator/android-emulator-macos-tweaks.git"
38
+ },
39
+ "homepage": "https://github.com/androperator/android-emulator-macos-tweaks#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/androperator/android-emulator-macos-tweaks/issues"
42
+ }
13
43
  }
package/src/core.js CHANGED
@@ -7,6 +7,7 @@ import { sha256, patchImages } from './png.js';
7
7
  import { macOS } from './platform.js';
8
8
  import { addIconHelper } from './macho.js';
9
9
  import { readRuntime, copyRuntime, verifyRuntime, runtimeHash } from './runtime.js';
10
+ import { readNamingBundle, configurationHash, verifyNaming, installConfiguration, removeConfiguration } from './names.js';
10
11
  const packageRoot = fileURLToPath(new URL('../', import.meta.url));
11
12
  const bundledProfiles = JSON.parse(await readFile(new URL('./profiles.json', import.meta.url)));
12
13
  const hashFile = async file => sha256(await readFile(file));
@@ -56,30 +57,39 @@ export async function inspect({ sdk: explicit, backupDir, profiles = bundledProf
56
57
  let receipts = [];
57
58
  try {
58
59
  for (const name of await readdir(folder)) {
59
- if (!/^[a-f0-9]{64}(?:-automatic-[a-f0-9]{64})?$/.test(name)) continue;
60
+ if (!/^[a-f0-9]{64}(?:-(?:automatic|names)-[a-f0-9]{64})?$/.test(name)) continue;
60
61
  const receiptPath = join(folder, name, 'receipt.json');
61
62
  try {
62
63
  if (!(await lstat(receiptPath)).isFile()) throw new Error('Invalid backup receipt');
63
64
  const receipt = JSON.parse(await readFile(receiptPath, 'utf8'));
64
- if (![1, 2].includes(receipt.schema) || receipt.target !== target || receipt.originalHash !== name.slice(0, 64) || !/^[a-f0-9]{64}$/.test(receipt.patchedHash ?? '') || !['prepared','applied','restored'].includes(receipt.state)) throw new Error('Invalid backup receipt');
65
+ if (![1, 2, 3].includes(receipt.schema) || receipt.target !== target || receipt.originalHash !== name.slice(0, 64) || !/^[a-f0-9]{64}$/.test(receipt.patchedHash ?? '') || !['prepared','applied','restored'].includes(receipt.state)) throw new Error('Invalid backup receipt');
65
66
  if (receipt.schema === 1 && name !== receipt.originalHash) throw new Error('Invalid legacy backup directory');
66
67
  if (receipt.schema === 2 && (receipt.icons !== 'auto' || name !== `${receipt.originalHash}-automatic-${runtimeHash(receipt.runtime)}`)) throw new Error('Invalid automatic backup directory');
68
+ if (receipt.schema === 3 && (name !== `${receipt.originalHash}-names-${receipt.namesHash}` || !['auto', 'phone'].includes(receipt.icons) || ![receipt.namesHash, receipt.backendHash, receipt.scriptHash, receipt.configHash].every(hash => /^[a-f0-9]{64}$/.test(hash ?? '')))) throw new Error('Invalid naming backup directory');
69
+ if (receipt.schema === 3 && receipt.icons === 'auto') runtimeHash(receipt.runtime);
67
70
  receipts.push({ ...receipt, directory: join(folder, name) });
68
71
  } catch (error) {
69
72
  throw new Error(`Cannot read backup receipt ${receiptPath}: ${error.message}`);
70
73
  }
71
74
  }
72
75
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
73
- const receipt = receipts.find(record => record.patchedHash === targetHash) ?? receipts.find(record => record.originalHash === targetHash);
76
+ const configHash = await configurationHash(target);
77
+ const receipt = receipts.find(record => record.schema === 3 && record.configHash === configHash && [record.patchedHash, record.originalHash].includes(targetHash)) ?? receipts.find(record => record.patchedHash === targetHash) ?? receipts.find(record => record.originalHash === targetHash);
74
78
  const profile = profiles.find(item => item.revision === revision && item.sha256 === targetHash);
75
79
  const state = receipt?.patchedHash === targetHash ? 'patched' : profile ? 'original' : 'unsupported';
76
80
  let runtimeHealthy = null;
77
- if (receipt?.schema === 2 && state === 'patched') {
81
+ if (receipt?.runtime && state === 'patched') {
78
82
  try { await verifyRuntime(join(receipt.directory, 'runtime'), receipt.runtime); runtimeHealthy = true; }
79
83
  catch { runtimeHealthy = false; }
80
84
  }
81
- const icons = state === 'patched' ? (receipt.schema === 2 ? 'auto' : 'phone') : null;
82
- return { icons, runtimeHealthy, sdk, revision, target, targetHash, storage, folder, targetId, state, receipt, profile, adapter, mode: info.mode & 0o777, receipts };
85
+ const icons = state === 'patched' ? (receipt.icons ?? 'phone') : null;
86
+ const names = state === 'patched' && receipt.schema === 3 ? 'avd' : 'off';
87
+ let namingHealthy = null;
88
+ if (names === 'avd') {
89
+ try { await verifyNaming(receipt); namingHealthy = configHash === receipt.configHash; }
90
+ catch { namingHealthy = false; }
91
+ }
92
+ return { configHash, names, namingHealthy, icons, runtimeHealthy, sdk, revision, target, targetHash, storage, folder, targetId, state, receipt, profile, adapter, mode: info.mode & 0o777, receipts };
83
93
  }
84
94
 
85
95
  async function withLock(context, operation) {
@@ -113,6 +123,8 @@ async function replace(context, source, expectedHash) {
113
123
 
114
124
  export async function apply(options = {}) {
115
125
  const icons = options.icons ?? 'auto';
126
+ const names = options.names ?? 'avd';
127
+ if (!['avd', 'off'].includes(names)) throw new Error('Expected --names avd or off');
116
128
  if (!['auto', 'phone'].includes(icons)) throw new Error('Expected --icons auto or phone');
117
129
  const context = await inspect(options);
118
130
  const runtimeDirectory = options.runtimeDir ?? join(packageRoot, 'assets/runtime');
@@ -120,21 +132,31 @@ export async function apply(options = {}) {
120
132
  const profile = (options.profiles ?? bundledProfiles).find(item => item.revision === context.revision && item.sha256 === originalHash);
121
133
  if (!profile) throw new Error(`Unsupported emulator ${context.revision ?? 'version'} (${context.targetHash}). No files changed. See supported builds in README.`);
122
134
  const bundle = icons === 'auto' ? await readRuntime(runtimeDirectory, context.adapter) : null;
123
- const directory = join(context.folder, icons === 'auto' ? `${originalHash}-automatic-${bundle.hash}` : originalHash);
135
+ const naming = names === 'avd' ? await readNamingBundle(options.packageRoot ?? packageRoot, context.adapter, options.nodePath) : null;
136
+ const namesHash = naming ? sha256(Buffer.from(JSON.stringify([naming.hash, icons, bundle?.hash ?? null]))) : null;
137
+ const directory = join(context.folder, naming ? `${originalHash}-names-${namesHash}` : icons === 'auto' ? `${originalHash}-automatic-${bundle.hash}` : originalHash);
124
138
  return withLock(context, async () => {
125
139
  await context.adapter.verify(context.target);
140
+ const activeConfig = await configurationHash(context.target);
141
+ if (activeConfig && !context.receipts.some(record => record.schema === 3 && record.configHash === activeConfig)) throw new Error('Unrecognized naming configuration; nothing overwritten');
126
142
  const existing = context.receipts.find(record => record.directory === directory);
127
143
  if (existing) {
128
144
  if (await hashFile(join(directory, 'original')) !== originalHash) throw new Error('Original backup is corrupt; refusing to replace it');
129
145
  if (await hashFile(join(directory, 'patched')) !== existing.patchedHash) throw new Error('Patched backup is corrupt');
130
- if (existing.schema === 2) {
146
+ if (existing.runtime) {
131
147
  await verifyRuntime(join(directory, 'runtime'), existing.runtime);
132
148
  await context.adapter.verify(join(directory, 'runtime/helper.dylib'));
133
149
  }
134
- if (context.targetHash === existing.patchedHash) return { ...context, changed: false };
150
+ if (existing.schema === 3) {
151
+ await verifyNaming(existing);
152
+ await context.adapter.verify(join(directory, 'backend'));
153
+ await installConfiguration(context, existing);
154
+ }
155
+ if (context.targetHash === existing.patchedHash && (existing.schema !== 3 || activeConfig === existing.configHash)) return { ...context, changed: false };
135
156
  await replace(context, join(directory, 'patched'), existing.patchedHash);
157
+ if (!naming) await removeConfiguration(context);
136
158
  await atomicJSON(join(directory, 'receipt.json'), { ...existing, directory: undefined, state: 'applied' });
137
- return { ...context, state: 'patched', icons, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
159
+ return { ...context, state: 'patched', icons, names, namingHealthy: naming ? true : null, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
138
160
  }
139
161
  // Always derive a new patch from the verified original, including legacy upgrades.
140
162
  const originalSource = context.state === 'patched' ? join(context.receipt.directory, 'original') : context.target;
@@ -155,8 +177,20 @@ export async function apply(options = {}) {
155
177
  if (bundle) await copyRuntime(runtimeDirectory, join(preparation, 'runtime'), bundle.manifest);
156
178
  await writeFile(candidate, bundle ? addIconHelper(patched, join(directory, 'runtime/helper.dylib')) : patched);
157
179
  await context.adapter.sign(backup, candidate, preparation);
180
+ let namingFields = {};
181
+ if (naming) {
182
+ const backend = join(preparation, 'backend');
183
+ await rename(candidate, backend);
184
+ const backendHash = await hashFile(backend), scriptHash = sha256(naming.script);
185
+ await writeFile(join(preparation, 'launch.mjs'), naming.script, { mode: 0o600 });
186
+ const configuration = { schema: 1, sdk: context.sdk, target: context.target, directory, revision: context.revision, node: naming.node, script: join(directory, 'launch.mjs'), backend: join(directory, 'backend'), backendHash, scriptHash };
187
+ await atomicJSON(join(preparation, 'launch.json'), configuration);
188
+ namingFields = { namesHash, backendHash, scriptHash, configHash: await hashFile(join(preparation, 'launch.json')) };
189
+ await context.adapter.copy(naming.launcher, candidate);
190
+ await context.adapter.sign(backup, candidate, preparation);
191
+ }
158
192
  const patchedHash = await hashFile(candidate);
159
- const receipt = { schema: bundle ? 2 : 1, target: context.target, revision: context.revision, build: profile.build, originalHash, patchedHash, state: 'prepared', created: new Date().toISOString(), slots, ...(bundle ? { icons, runtime: bundle.manifest } : {}) };
193
+ const receipt = { schema: naming ? 3 : bundle ? 2 : 1, target: context.target, revision: context.revision, build: profile.build, originalHash, patchedHash, state: 'prepared', created: new Date().toISOString(), slots, ...(bundle ? { icons, runtime: bundle.manifest } : {}), ...(naming ? { icons, ...namingFields } : {}) };
160
194
  for (const file of [backup, candidate]) {
161
195
  const handle = await open(file, 'r');
162
196
  try { await handle.sync(); } finally { await handle.close(); }
@@ -167,21 +201,34 @@ export async function apply(options = {}) {
167
201
  await verifyRuntime(join(directory, 'runtime'), bundle.manifest);
168
202
  await context.adapter.verify(join(directory, 'runtime/helper.dylib'));
169
203
  }
204
+ if (naming) {
205
+ const prepared = { ...receipt, directory };
206
+ await verifyNaming(prepared);
207
+ await installConfiguration(context, prepared);
208
+ }
170
209
  await replace(context, join(directory, 'patched'), patchedHash);
210
+ if (!naming) await removeConfiguration(context);
171
211
  await atomicJSON(join(directory, 'receipt.json'), { ...receipt, state: 'applied' });
172
- return { ...context, state: 'patched', icons, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
212
+ return { ...context, state: 'patched', icons, names, namingHealthy: naming ? true : null, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
173
213
  });
174
214
  }
175
215
 
176
216
  export async function restore(options = {}) {
177
217
  const context = await inspect(options);
178
- if (context.receipt?.originalHash === context.targetHash) return { ...context, changed: false };
218
+ if (context.receipt?.originalHash === context.targetHash) {
219
+ if (context.configHash) return withLock(context, async () => {
220
+ await removeConfiguration(context);
221
+ return { ...context, changed: false };
222
+ });
223
+ return { ...context, changed: false };
224
+ }
179
225
  if (context.state !== 'patched') throw new Error('No matching applied backup for this executable. Refusing to overwrite an SDK update or unrecognized patch.');
180
226
  return withLock(context, async () => {
181
227
  const backup = join(context.receipt.directory, 'original');
182
228
  if (await hashFile(backup) !== context.receipt.originalHash) throw new Error('Original backup is corrupt; nothing restored');
183
229
  await replace(context, backup, context.receipt.originalHash);
230
+ await removeConfiguration(context);
184
231
  await atomicJSON(join(context.receipt.directory, 'receipt.json'), { ...context.receipt, directory: undefined, state: 'restored' });
185
- return { ...context, state: 'original', icons: null, runtimeHealthy: null, changed: true, backup: context.receipt.directory };
232
+ return { ...context, state: 'original', icons: null, names: 'off', namingHealthy: null, runtimeHealthy: null, changed: true, backup: context.receipt.directory };
186
233
  });
187
234
  }
package/src/launch.mjs ADDED
@@ -0,0 +1,72 @@
1
+ import { readFile, mkdir, lstat, realpath, readdir, symlink, copyFile, chmod, mkdtemp, rename, rm } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex');
7
+ export function avdName(arguments_) {
8
+ const names = [];
9
+ for (let i = 0; i < arguments_.length; i++) {
10
+ if (arguments_[i] === '-avd' && arguments_[i + 1]) names.push(arguments_[++i]);
11
+ else if (arguments_[i].startsWith('@')) names.push(arguments_[i].slice(1));
12
+ }
13
+ if (new Set(names).size > 1) throw new Error('Conflicting AVD names');
14
+ const name = names[0];
15
+ if (name && (!/^[A-Za-z0-9_.-]{1,255}$/.test(name) || ['.', '..', 'qemu-system-aarch64'].includes(name.toLowerCase()))) throw new Error('Invalid or reserved AVD name');
16
+ return arguments_.includes('-no-window') ? undefined : name;
17
+ }
18
+ async function regularFile(path) {
19
+ const info = await lstat(path);
20
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error(`Not a regular file: ${path}`);
21
+ return info;
22
+ }
23
+ export async function prepareLaunch(config, arguments_) {
24
+ if (config.schema !== 1 || await realpath(config.sdk) !== config.sdk || !config.directory.startsWith('/') ||
25
+ config.target !== join(config.sdk, 'emulator/qemu/darwin-aarch64/qemu-system-aarch64') ||
26
+ config.backend !== join(config.directory, 'backend') || config.script !== join(config.directory, 'launch.mjs')) throw new Error('Invalid naming configuration');
27
+ const revision = (await readFile(join(config.sdk, 'emulator/source.properties'), 'utf8')).match(/^Pkg\.Revision\s*=\s*(\S+)\s*$/m)?.[1];
28
+ if (revision !== config.revision) throw new Error('SDK version changed; restore or reapply emulator tweaks');
29
+ await regularFile(config.backend);
30
+ if (hash(await readFile(config.backend)) !== config.backendHash) throw new Error('Named emulator backend is corrupt');
31
+ const name = avdName(arguments_) ?? 'qemu-system-aarch64';
32
+ const launches = join(config.directory, 'launches');
33
+ await mkdir(launches, { recursive: true, mode: 0o700 });
34
+ const info = await lstat(launches);
35
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('Invalid naming cache directory');
36
+ const destination = join(launches, hash(Buffer.from(name)));
37
+ const executable = join(destination, 'sdk/emulator/qemu/darwin-aarch64', name);
38
+ try {
39
+ await regularFile(executable);
40
+ if (hash(await readFile(executable)) !== config.backendHash) throw new Error('Cached named emulator is corrupt');
41
+ return executable;
42
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
43
+ const temporary = await mkdtemp(join(launches, '.prepare-'));
44
+ try {
45
+ async function clone(from, to, relative = '') {
46
+ await mkdir(to, { mode: 0o700 });
47
+ for (const entry of await readdir(from, { withFileTypes: true })) {
48
+ const key = relative ? `${relative}/${entry.name}` : entry.name;
49
+ const source = join(from, entry.name), output = join(to, entry.name);
50
+ if (['emulator', 'emulator/qemu', 'emulator/qemu/darwin-aarch64'].includes(key)) await clone(source, output, key);
51
+ else if (key !== 'emulator/qemu/darwin-aarch64/qemu-system-aarch64' && entry.name !== '.emulator-tweaks-launch.json' && entry.name !== '.emulator-icon-macos.lock') await symlink(source, output);
52
+ }
53
+ }
54
+ await clone(config.sdk, join(temporary, 'sdk'));
55
+ const candidate = join(temporary, 'sdk/emulator/qemu/darwin-aarch64', name);
56
+ // Never overwrite a library or other SDK entry that happens to share the AVD name.
57
+ await copyFile(config.backend, candidate, constants.COPYFILE_EXCL);
58
+ await chmod(candidate, (await regularFile(config.backend)).mode & 0o777);
59
+ if (hash(await readFile(candidate)) !== config.backendHash) throw new Error('Named emulator copy changed');
60
+ try { await rename(temporary, destination); }
61
+ catch (error) { if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error; }
62
+ await regularFile(executable);
63
+ if (hash(await readFile(executable)) !== config.backendHash) throw new Error('Concurrent named emulator cache is corrupt');
64
+ return executable;
65
+ } finally { await rm(temporary, { recursive: true, force: true }); }
66
+ }
67
+ if (process.argv[1] && await realpath(process.argv[1]) === fileURLToPath(import.meta.url)) {
68
+ try {
69
+ const config = JSON.parse(await readFile(process.argv[2], 'utf8'));
70
+ console.log(await prepareLaunch(config, process.argv.slice(3)));
71
+ } catch (error) { console.error(`androperator-emulator-tweaks: ${error.message}`); process.exitCode = 1; }
72
+ }
package/src/names.js ADDED
@@ -0,0 +1,40 @@
1
+ import { readFile, lstat, writeFile, rename, rm } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { sha256 } from './png.js';
5
+ export const configurationPath = target => join(dirname(target), '.emulator-tweaks-launch.json');
6
+ export async function configurationHash(target) {
7
+ try {
8
+ const path = configurationPath(target), info = await lstat(path);
9
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Naming configuration must be a regular file');
10
+ return sha256(await readFile(path));
11
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
12
+ }
13
+ export async function readNamingBundle(root, adapter, node = process.execPath) {
14
+ const directory = join(root, 'assets/launcher');
15
+ const manifest = JSON.parse(await readFile(join(directory, 'manifest.json'), 'utf8'));
16
+ const launcher = join(directory, 'launcher');
17
+ const bytes = await readFile(launcher), script = await readFile(join(root, 'src/launch.mjs'));
18
+ if (bytes.length < 16 || manifest.schema !== 1 || manifest.architecture !== 'arm64' || sha256(bytes) !== manifest.sha256 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== 0x100000c || bytes.readUInt32LE(12) !== 2) throw new Error('Invalid bundled AVD launcher');
19
+ await adapter.verify(launcher);
20
+ return { launcher, script, node, hash: sha256(Buffer.from(JSON.stringify([manifest.sha256, sha256(script), node]))) };
21
+ }
22
+ export async function verifyNaming(receipt) {
23
+ for (const [name, expected] of [['backend', receipt.backendHash], ['launch.mjs', receipt.scriptHash], ['launch.json', receipt.configHash]]) {
24
+ const path = join(receipt.directory, name), info = await lstat(path);
25
+ if (!info.isFile() || info.isSymbolicLink() || sha256(await readFile(path)) !== expected) throw new Error('Naming runtime is missing or corrupt');
26
+ }
27
+ }
28
+ export async function installConfiguration(context, receipt) {
29
+ const current = await configurationHash(context.target);
30
+ if (current && !context.receipts.some(record => record.schema === 3 && record.configHash === current)) throw new Error('Unrecognized naming configuration; nothing overwritten');
31
+ const temporary = `${configurationPath(context.target)}.${randomUUID()}.tmp`;
32
+ try {
33
+ await writeFile(temporary, await readFile(join(receipt.directory, 'launch.json')), { flag: 'wx', mode: 0o600 });
34
+ await rename(temporary, configurationPath(context.target));
35
+ } finally { await rm(temporary, { force: true }); }
36
+ }
37
+ export async function removeConfiguration(context) {
38
+ const current = await configurationHash(context.target);
39
+ if (current && context.receipts.some(record => record.schema === 3 && record.configHash === current)) await rm(configurationPath(context.target));
40
+ }