@audiofool/moondog 0.3.0-beta.15 → 0.3.0-beta.16

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
@@ -4,7 +4,7 @@
4
4
 
5
5
  <h1 align="center">Moondog</h1>
6
6
 
7
- <p align="center">Source candidate 0.3.0-beta.15</p>
7
+ <p align="center">Source candidate 0.3.0-beta.16</p>
8
8
 
9
9
  <p align="center"><strong>On the air, just for you.</strong></p>
10
10
 
@@ -42,10 +42,12 @@ See [updating and release channels](docs/UPDATES.md), including the one-time upg
42
42
 
43
43
  ## On your Mac
44
44
 
45
- [Moondog for Mac](app/README.md) is a native window on the same core as the terminal room.
45
+ [Moondog desktop](app/README.md) is a native window on the same core as the terminal room, with build targets for macOS (Apple silicon), Windows (x64), and Linux (x64).
46
46
  It shares your profile, settings, sign-ins, and conversations with `moondog`, and draws its own conversation, now playing, and up next.
47
47
  Download the notarized build for Apple silicon from the [project page](https://moondog.audiofool.ai), or run it from this checkout with `cd app && npm ci && npm start`.
48
48
  It updates itself, on a Stable or Beta channel you choose in Settings.
49
+ The Windows and Linux desktop builds use Spotify playback and Apple Music previews; full Apple Music songs and reading the Music app require macOS.
50
+ Windows support applies to the desktop app; the terminal launcher and its updater remain supported on macOS and Linux.
49
51
 
50
52
  The [project page](https://moondog.audiofool.ai) plays a short scene in this window, in a browser, with a made-up listener ([how](site/README.md)).
51
53
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audiofool/moondog",
3
- "version": "0.3.0-beta.15",
3
+ "version": "0.3.0-beta.16",
4
4
  "type": "module",
5
5
  "description": "A local-first AI radio host, just for you.",
6
6
  "license": "Apache-2.0",
@@ -71,7 +71,8 @@
71
71
  "@earendil-works/pi-tui": "1.0.1",
72
72
  "ajv": "8.20.0",
73
73
  "ajv-formats": "3.0.1",
74
- "plist": "5.0.0"
74
+ "plist": "5.0.0",
75
+ "yauzl": "3.4.0"
75
76
  },
76
77
  "devDependencies": {
77
78
  "yaml": "2.9.0"
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { execFile } from "node:child_process";
4
- import { promisify } from "node:util";
5
3
  import { createApplicationUpdater } from "../src/core/application-update.mjs";
4
+ import { openInDefaultBrowser } from "../src/core/host.mjs";
6
5
  import { runUpdateCommand } from "../src/surfaces/cli/update-command.mjs";
7
6
 
8
7
  import { MoondogApplication } from "../src/core/moondog-application.mjs";
@@ -407,9 +406,7 @@ async function prepareTuiHistoryImport(filePath, { recentPage, librarySnapshot,
407
406
  async function openImportHelp(destination) {
408
407
  const url = IMPORT_GUIDE_URLS[destination];
409
408
  if (!url) throw new Error("Unknown import guide.");
410
- await promisify(execFile)(process.platform === "darwin" ? "open" : "xdg-open", [url], {
411
- timeout: 10_000,
412
- });
409
+ await openInDefaultBrowser(url);
413
410
  }
414
411
 
415
412
  function tasteCoverage(profile) {
@@ -0,0 +1,30 @@
1
+ // What differs between the operating systems the core runs on: the environment's PATH key and
2
+ // how a link opens in the listener's browser.
3
+ import { spawn } from "node:child_process";
4
+
5
+ /** Windows spells the PATH variable as it likes (often "Path"); the others use PATH. */
6
+ export function environmentPathKey(environment) {
7
+ return Object.keys(environment).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
8
+ }
9
+
10
+ /** Opens a link in the default browser, and resolves once the opener has started. */
11
+ export function openInDefaultBrowser(url, platform = process.platform) {
12
+ const [command, args] =
13
+ platform === "darwin"
14
+ ? ["open", [url]]
15
+ : platform === "win32"
16
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
17
+ : ["xdg-open", [url]];
18
+ return new Promise((resolve, reject) => {
19
+ const child = spawn(command, args, {
20
+ detached: true,
21
+ stdio: "ignore",
22
+ windowsHide: true,
23
+ });
24
+ child.once("error", reject);
25
+ child.once("spawn", () => {
26
+ child.unref();
27
+ resolve();
28
+ });
29
+ });
30
+ }
@@ -0,0 +1,61 @@
1
+ // Read ZIP members in process on every desktop platform. Nothing is extracted to disk.
2
+ import { crc32 } from "node:zlib";
3
+ import yauzl from "yauzl";
4
+
5
+ /**
6
+ * Opens a ZIP file or buffer once, so several members can be read without reading the central
7
+ * directory again. `names` lists every member in archive order. Call close() when done.
8
+ */
9
+ export async function openZipArchive(source, maximumNameBytes = 1024 * 1024) {
10
+ // The archive stays open after its entries are listed, so members can be read in any order.
11
+ const options = { strictFileNames: true, validateEntrySizes: true, autoClose: false };
12
+ const zip = Buffer.isBuffer(source) ? await yauzl.fromBufferPromise(source, options) : await yauzl.openPromise(source, options);
13
+ const names = [];
14
+ const entries = new Map();
15
+ try {
16
+ let bytes = 0;
17
+ for await (const entry of zip.eachEntry()) {
18
+ if (/[\u0000-\u001f\u007f]/u.test(entry.fileName)) throw new Error("Unsupported ZIP member name.");
19
+ bytes += Buffer.byteLength(entry.fileName, "utf8") + 1;
20
+ if (bytes > maximumNameBytes) throw new Error("ZIP member list exceeds the supported size.");
21
+ names.push(entry.fileName);
22
+ if (!entries.has(entry.fileName)) entries.set(entry.fileName, entry);
23
+ }
24
+ } catch (error) {
25
+ zip.close();
26
+ throw error;
27
+ }
28
+
29
+ async function read(name, maximumBytes) {
30
+ const entry = entries.get(name);
31
+ if (!entry) throw new Error("ZIP member was not found.");
32
+ if (entry.uncompressedSize > maximumBytes) throw new Error("ZIP member exceeds the supported size.");
33
+ const stream = await zip.openReadStreamPromise(entry);
34
+ const chunks = [];
35
+ let bytes = 0;
36
+ let checksum = 0;
37
+ try {
38
+ for await (const chunk of stream) {
39
+ bytes += chunk.length;
40
+ if (bytes > maximumBytes) throw new Error("ZIP member exceeds the supported size.");
41
+ checksum = crc32(chunk, checksum);
42
+ chunks.push(chunk);
43
+ }
44
+ } finally { stream.destroy(); }
45
+ if (checksum !== entry.crc32) throw new Error("ZIP member checksum does not match.");
46
+ return Buffer.concat(chunks, bytes);
47
+ }
48
+
49
+ return { names, read, close: () => zip.close() };
50
+ }
51
+
52
+ export async function listZipMembers(source, maximumBytes = 1024 * 1024) {
53
+ const zip = await openZipArchive(source, maximumBytes);
54
+ zip.close();
55
+ return zip.names;
56
+ }
57
+
58
+ export async function readZipMember(source, name, maximumBytes) {
59
+ const zip = await openZipArchive(source);
60
+ try { return await zip.read(name, maximumBytes); } finally { zip.close(); }
61
+ }
@@ -172,8 +172,9 @@ function nowPlayingOf(answer) {
172
172
  };
173
173
  }
174
174
 
175
- export function createMusicAppPlayer({ platform = process.platform, run = osascript, now = Date.now } = {}) {
176
- const available = platform === "darwin";
175
+ export function createMusicAppPlayer({ platform = process.platform, environment = process.env, run = osascript, now = Date.now } = {}) {
176
+ // Disposable desktop checks can opt out of the listener's system Music app as well as local data.
177
+ const available = platform === "darwin" && environment.MOONDOG_SYSTEM_MUSIC !== "off";
177
178
  let refusedAt = null;
178
179
  const covers = new Map();
179
180
 
@@ -4,9 +4,11 @@
4
4
  // original recordings, NetEase marks songs as not playable (`visible: false`), most often for
5
5
  // copyright, and no membership changes that.
6
6
  import { execFile } from "node:child_process";
7
- import { access, constants, stat } from "node:fs/promises";
7
+ import { access, constants, readFile, stat } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
 
10
+ import { environmentPathKey } from "../../core/host.mjs";
11
+
10
12
  const COMMAND_TIMEOUT_MS = 20_000;
11
13
  // Where Homebrew and npm put ncm-cli, the node it runs on, and mpv, for a PATH that lacks them.
12
14
  const EXTRA_FOLDERS = ["/opt/homebrew/bin", "/usr/local/bin"];
@@ -22,37 +24,59 @@ const KNOWN_SONGS = 300;
22
24
  const failure = (code, message) => Object.assign(new Error(message), { code });
23
25
 
24
26
  const folders = (value) => String(value ?? "").split(path.delimiter).filter((folder) => path.isAbsolute(folder));
25
- const searchPath = (environment) => [...new Set([...folders(environment.PATH), ...EXTRA_FOLDERS])];
27
+ const searchPath = (environment, platform) => [...new Set([...folders(environment[environmentPathKey(environment)]),
28
+ ...(platform === "win32" ? (environment.APPDATA ? [path.join(environment.APPDATA, "npm")] : []) : EXTRA_FOLDERS)])];
29
+
30
+ async function executable(file) {
31
+ try {
32
+ if (!(await stat(file)).isFile()) return false;
33
+ await access(file, constants.X_OK);
34
+ return true;
35
+ } catch { return false; }
36
+ }
26
37
 
27
- async function findIn(places) {
38
+ async function findIn(places, platform) {
28
39
  for (const folder of places) {
29
- const file = path.join(folder, "ncm-cli");
30
- try {
31
- if (!(await stat(file)).isFile()) continue;
32
- await access(file, constants.X_OK);
33
- return file;
34
- } catch {}
40
+ const file = path.join(folder, platform === "win32" ? "ncm-cli.exe" : "ncm-cli");
41
+ if (await executable(file)) return { file, args: [] };
42
+ if (platform !== "win32") continue;
43
+ // npm's Windows launcher is a .cmd file. Run its package entry with Node directly so
44
+ // artist names and queries never pass through cmd.exe's quoting and expansion rules.
45
+ for (const packageRoot of [path.join(folder, "node_modules", "@music163", "ncm-cli"), path.resolve(folder, "..", "@music163", "ncm-cli")]) {
46
+ try {
47
+ const metadata = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
48
+ const bin = typeof metadata.bin === "string" ? metadata.bin : metadata.bin?.["ncm-cli"];
49
+ if (typeof bin !== "string") continue;
50
+ const entry = path.resolve(packageRoot, bin);
51
+ if (!(await stat(entry)).isFile()) continue;
52
+ for (const nodeFolder of [folder, ...places]) {
53
+ const node = path.join(nodeFolder, "node.exe");
54
+ if (await executable(node)) return { file: node, args: [entry] };
55
+ }
56
+ } catch {}
57
+ }
35
58
  }
36
59
  return null;
37
60
  }
38
61
 
39
62
  // Opened from Finder, the app has its login shell's PATH, which lacks the folders ~/.zshrc adds,
40
63
  // such as nvm's for npm's global commands. There, the listener's shell as Terminal opens it says.
41
- function terminalPath(environment) {
64
+ function terminalPath(environment, platform) {
65
+ if (platform === "win32") return Promise.resolve([]);
42
66
  return new Promise((resolve) => {
43
- execFile(environment.SHELL || "/bin/zsh", ["-ilc", 'printf "\\n__MOONDOG_PATH__%s\\n" "$PATH"'], { env: environment, timeout: 5_000 },
67
+ execFile(environment.SHELL || (platform === "darwin" ? "/bin/zsh" : "/bin/sh"), ["-ilc", 'printf "\\n__MOONDOG_PATH__%s\\n" "$PATH"'], { env: environment, timeout: 5_000 },
44
68
  (_error, stdout) => resolve(folders(String(stdout ?? "").match(/__MOONDOG_PATH__(.+)/u)?.[1])));
45
69
  });
46
70
  }
47
71
 
48
72
  /** ncm-cli and the PATH to run it with, which has the node it runs on, or null. */
49
- async function findNcmCli(environment) {
50
- const places = searchPath(environment);
51
- const file = await findIn(places);
52
- if (file) return { file, places };
53
- const terminal = await terminalPath(environment);
54
- const found = await findIn(terminal);
55
- return found ? { file: found, places: [...new Set([...terminal, ...places])] } : null;
73
+ export async function findNcmCli(environment, platform = process.platform) {
74
+ const places = searchPath(environment, platform);
75
+ const command = await findIn(places, platform);
76
+ if (command) return { ...command, places };
77
+ const terminal = await terminalPath(environment, platform);
78
+ const found = await findIn(terminal, platform);
79
+ return found ? { ...found, places: [...new Set([...terminal, ...places])] } : null;
56
80
  }
57
81
 
58
82
  // Runs one ncm-cli command and parses its JSON. ncm-cli reports most failures as
@@ -64,9 +88,9 @@ function cliRunner({ environment }) {
64
88
  return async (args) => {
65
89
  found ??= await findNcmCli(environment);
66
90
  if (!found) throw failure("netease_cli_missing", "ncm-cli is not installed. Install it with: npm install -g @music163/ncm-cli");
67
- const env = { ...environment, PATH: found.places.join(path.delimiter) };
91
+ const env = { ...environment, [environmentPathKey(environment)]: found.places.join(path.delimiter) };
68
92
  const stdout = await new Promise((resolve, reject) => {
69
- execFile(found.file, args, { env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 }, (error, out) =>
93
+ execFile(found.file, [...found.args, ...args], { env, windowsHide: true, timeout: COMMAND_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 }, (error, out) =>
70
94
  (error && !out ? reject(failure("netease_failed", `ncm-cli ${args[0]} failed: ${String(error.message).slice(0, 200)}`)) : resolve(String(out ?? ""))));
71
95
  });
72
96
  const start = stdout.indexOf("{");
@@ -1,9 +1,8 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash } from "node:crypto";
3
2
  import { createReadStream } from "node:fs";
4
3
  import { lstat } from "node:fs/promises";
5
4
  import path from "node:path";
6
- import { promisify } from "node:util";
5
+ import { openZipArchive } from "../../importers/zip-reader.mjs";
7
6
 
8
7
  import { isUuid, uuidV5 } from "../../core/uuid-v5.mjs";
9
8
  import {
@@ -32,7 +31,6 @@ export const SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS = Object.freeze({
32
31
  maximumRecords: 500_000,
33
32
  });
34
33
 
35
- const execFileAsync = promisify(execFile);
36
34
  const musicMemberPattern =
37
35
  /^Spotify Account Data\/StreamingHistory_music_([0-9]+)\.json$/u;
38
36
  const endTimePattern =
@@ -376,14 +374,20 @@ async function sha256File(filePath) {
376
374
  return hash.digest("hex");
377
375
  }
378
376
 
379
- async function unzip(args, maximumBytes) {
377
+ async function openArchive(archivePath) {
380
378
  try {
381
- const { stdout } = await execFileAsync("/usr/bin/unzip", args, {
382
- encoding: "utf8",
383
- maxBuffer: maximumBytes,
384
- windowsHide: true,
385
- });
386
- return stdout;
379
+ return await openZipArchive(archivePath);
380
+ } catch {
381
+ fail(
382
+ "The Spotify account-data ZIP could not be read safely.",
383
+ "spotify_account_data_archive_unreadable",
384
+ );
385
+ }
386
+ }
387
+
388
+ async function zipText(archive, maximumBytes, member) {
389
+ try {
390
+ return (await archive.read(member, maximumBytes)).toString("utf8");
387
391
  } catch {
388
392
  fail(
389
393
  "The Spotify account-data ZIP could not be read safely.",
@@ -468,58 +472,60 @@ export async function readSpotifyAccountDataHistoryArchive({
468
472
  fail("The Spotify account-data ZIP is not a supported regular file.");
469
473
  }
470
474
 
471
- const listing = await unzip(["-Z1", resolvedPath], 1024 * 1024);
472
- const members = selectedMusicMembers(listing);
473
- const profileMembers = selectedProfileMembers(listing);
475
+ // One open archive serves the listing and every member, and is closed even when a check fails.
476
+ const archive = await openArchive(resolvedPath);
477
+ let members;
478
+ let profileMembers;
474
479
  const records = [];
475
480
  const documents = {};
476
- let totalJsonBytes = 0;
477
- for (const member of members) {
478
- const jsonText = await unzip(
479
- ["-p", resolvedPath, member.name],
480
- SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes,
481
- );
482
- totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
483
- if (
484
- totalJsonBytes >
485
- SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
486
- ) {
487
- fail("Spotify music history JSON is too large to import safely.");
488
- }
489
- let parsed;
490
- try {
491
- parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
492
- } catch {
493
- fail(`Spotify music history segment ${member.index} is invalid JSON.`);
494
- }
495
- if (!Array.isArray(parsed)) {
496
- fail(`Spotify music history segment ${member.index} is not an array.`);
497
- }
498
- records.push(...parsed);
499
- if (records.length > SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumRecords) {
500
- fail("Spotify music history contains too many records.");
481
+ try {
482
+ const listing = archive.names.join("\n");
483
+ members = selectedMusicMembers(listing);
484
+ profileMembers = selectedProfileMembers(listing);
485
+ let totalJsonBytes = 0;
486
+ for (const member of members) {
487
+ const jsonText = await zipText(archive, SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes, member.name);
488
+ totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
489
+ if (
490
+ totalJsonBytes >
491
+ SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
492
+ ) {
493
+ fail("Spotify music history JSON is too large to import safely.");
494
+ }
495
+ let parsed;
496
+ try {
497
+ parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
498
+ } catch {
499
+ fail(`Spotify music history segment ${member.index} is invalid JSON.`);
500
+ }
501
+ if (!Array.isArray(parsed)) {
502
+ fail(`Spotify music history segment ${member.index} is not an array.`);
503
+ }
504
+ records.push(...parsed);
505
+ if (records.length > SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumRecords) {
506
+ fail("Spotify music history contains too many records.");
507
+ }
501
508
  }
502
- }
503
509
 
504
- for (const member of profileMembers) {
505
- const jsonText = await unzip(
506
- ["-p", resolvedPath, member.name],
507
- SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes,
508
- );
509
- totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
510
- if (
511
- totalJsonBytes >
512
- SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
513
- ) {
514
- fail("Spotify account-profile JSON is too large to import safely.");
515
- }
516
- try {
517
- documents[member.basename] = JSON.parse(
518
- jsonText.replace(/^\uFEFF/u, ""),
519
- );
520
- } catch {
521
- fail(`Spotify account-profile file ${member.basename} is invalid JSON.`);
510
+ for (const member of profileMembers) {
511
+ const jsonText = await zipText(archive, SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumMemberBytes, member.name);
512
+ totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
513
+ if (
514
+ totalJsonBytes >
515
+ SPOTIFY_ACCOUNT_DATA_HISTORY_LIMITS.maximumTotalJsonBytes
516
+ ) {
517
+ fail("Spotify account-profile JSON is too large to import safely.");
518
+ }
519
+ try {
520
+ documents[member.basename] = JSON.parse(
521
+ jsonText.replace(/^\uFEFF/u, ""),
522
+ );
523
+ } catch {
524
+ fail(`Spotify account-profile file ${member.basename} is invalid JSON.`);
525
+ }
522
526
  }
527
+ } finally {
528
+ archive.close();
523
529
  }
524
530
 
525
531
  const archiveSha256 = await sha256File(resolvedPath);
@@ -1,4 +1,3 @@
1
- import { spawn } from "node:child_process";
2
1
  import {
3
2
  createHash,
4
3
  randomBytes,
@@ -6,6 +5,8 @@ import {
6
5
  } from "node:crypto";
7
6
  import { createServer } from "node:http";
8
7
 
8
+ import { openInDefaultBrowser } from "../../core/host.mjs";
9
+
9
10
  const SPOTIFY_AUTHORIZE_URL = "https://accounts.spotify.com/authorize";
10
11
  const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
11
12
  const ACCESS_TOKEN_DEFAULT_LIFETIME_SECONDS = 60 * 60;
@@ -499,27 +500,6 @@ export async function refreshSpotifyAccessToken({
499
500
  );
500
501
  }
501
502
 
502
- function openInDefaultBrowser(url) {
503
- const [command, args] =
504
- process.platform === "darwin"
505
- ? ["open", [url]]
506
- : process.platform === "win32"
507
- ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
508
- : ["xdg-open", [url]];
509
- return new Promise((resolve, reject) => {
510
- const child = spawn(command, args, {
511
- detached: true,
512
- stdio: "ignore",
513
- windowsHide: true,
514
- });
515
- child.once("error", reject);
516
- child.once("spawn", () => {
517
- child.unref();
518
- resolve();
519
- });
520
- });
521
- }
522
-
523
503
  async function createCallbackListener({ redirectUri, expectedState, signal }) {
524
504
  const redirect = normalizeRedirectUri(redirectUri);
525
505
  let resolveCode;
@@ -1,9 +1,8 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash } from "node:crypto";
3
2
  import { createReadStream } from "node:fs";
4
3
  import { lstat } from "node:fs/promises";
5
4
  import path from "node:path";
6
- import { promisify } from "node:util";
5
+ import { openZipArchive } from "../../importers/zip-reader.mjs";
7
6
 
8
7
  import { isUuid, uuidV5 } from "../../core/uuid-v5.mjs";
9
8
  import {
@@ -30,7 +29,6 @@ export const SPOTIFY_EXTENDED_HISTORY_LIMITS = Object.freeze({
30
29
  maximumRecords: 500_000,
31
30
  });
32
31
 
33
- const execFileAsync = promisify(execFile);
34
32
  const historyMemberPattern =
35
33
  /^Spotify Extended Streaming History\/Streaming_History_(?:Audio|Video)_([0-9]{4})(?:_([0-9]+))?\.json$/u;
36
34
  const trackUriPattern = /^spotify:track:([A-Za-z0-9]{22})$/u;
@@ -402,14 +400,20 @@ async function sha256File(filePath) {
402
400
  return hash.digest("hex");
403
401
  }
404
402
 
405
- async function unzip(args, maximumBytes) {
403
+ async function openArchive(archivePath) {
406
404
  try {
407
- const { stdout } = await execFileAsync("/usr/bin/unzip", args, {
408
- encoding: "utf8",
409
- maxBuffer: maximumBytes,
410
- windowsHide: true,
411
- });
412
- return stdout;
405
+ return await openZipArchive(archivePath);
406
+ } catch {
407
+ fail(
408
+ "The Spotify Extended History ZIP could not be read safely.",
409
+ "spotify_extended_history_archive_unreadable",
410
+ );
411
+ }
412
+ }
413
+
414
+ async function zipText(archive, maximumBytes, member) {
415
+ try {
416
+ return (await archive.read(member, maximumBytes)).toString("utf8");
413
417
  } catch {
414
418
  fail(
415
419
  "The Spotify Extended History ZIP could not be read safely.",
@@ -480,38 +484,42 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
480
484
  fail("The Spotify Extended History ZIP is not a supported regular file.");
481
485
  }
482
486
 
483
- const listing = await unzip(["-Z1", resolvedPath], 1024 * 1024);
484
- const members = selectedHistoryMembers(listing);
487
+ // One open archive serves the listing and every member, and is closed even when a check fails.
488
+ const archive = await openArchive(resolvedPath);
489
+ let members;
485
490
  const records = [];
486
- let totalJsonBytes = 0;
487
- for (const member of members) {
488
- const jsonText = await unzip(
489
- ["-p", resolvedPath, member.name],
490
- SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumMemberBytes,
491
- );
492
- totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
493
- if (
494
- totalJsonBytes > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumTotalJsonBytes
495
- ) {
496
- fail("Spotify Extended History JSON is too large to import safely.");
497
- }
498
- let parsed;
499
- try {
500
- parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
501
- } catch {
502
- fail(
503
- `Spotify Extended History audio/video file for ${member.year} is invalid JSON.`,
504
- );
505
- }
506
- if (!Array.isArray(parsed)) {
507
- fail(
508
- `Spotify Extended History audio/video file for ${member.year} is not an array.`,
509
- );
510
- }
511
- records.push(...parsed);
512
- if (records.length > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumRecords) {
513
- fail("Spotify Extended History contains too many records.");
491
+ try {
492
+ const listing = archive.names.join("\n");
493
+ members = selectedHistoryMembers(listing);
494
+ let totalJsonBytes = 0;
495
+ for (const member of members) {
496
+ const jsonText = await zipText(archive, SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumMemberBytes, member.name);
497
+ totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
498
+ if (
499
+ totalJsonBytes > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumTotalJsonBytes
500
+ ) {
501
+ fail("Spotify Extended History JSON is too large to import safely.");
502
+ }
503
+ let parsed;
504
+ try {
505
+ parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
506
+ } catch {
507
+ fail(
508
+ `Spotify Extended History audio/video file for ${member.year} is invalid JSON.`,
509
+ );
510
+ }
511
+ if (!Array.isArray(parsed)) {
512
+ fail(
513
+ `Spotify Extended History audio/video file for ${member.year} is not an array.`,
514
+ );
515
+ }
516
+ records.push(...parsed);
517
+ if (records.length > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumRecords) {
518
+ fail("Spotify Extended History contains too many records.");
519
+ }
514
520
  }
521
+ } finally {
522
+ archive.close();
515
523
  }
516
524
 
517
525
  return projectSpotifyExtendedStreamingHistory({
@@ -1,12 +1,9 @@
1
- import { execFile } from "node:child_process";
2
1
  import path from "node:path";
3
- import { promisify } from "node:util";
2
+ import { listZipMembers } from "../../importers/zip-reader.mjs";
4
3
 
5
4
  import { readSpotifyAccountDataHistoryArchive } from "./account-data-history.mjs";
6
5
  import { readSpotifyExtendedStreamingHistoryArchive } from "./extended-streaming-history.mjs";
7
6
 
8
- const execFileAsync = promisify(execFile);
9
-
10
7
  function fail(message, code = "spotify_history_archive_invalid") {
11
8
  const error = new Error(message);
12
9
  error.code = code;
@@ -20,15 +17,7 @@ export async function readSpotifyHistoryArchive(options = {}) {
20
17
  const archivePath = path.resolve(options.archivePath);
21
18
  let listing;
22
19
  try {
23
- ({ stdout: listing } = await execFileAsync(
24
- "/usr/bin/unzip",
25
- ["-Z1", archivePath],
26
- {
27
- encoding: "utf8",
28
- maxBuffer: 1024 * 1024,
29
- windowsHide: true,
30
- },
31
- ));
20
+ listing = (await listZipMembers(archivePath)).join("\n");
32
21
  } catch {
33
22
  fail(
34
23
  "The Spotify history ZIP could not be read safely.",
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
 
7
7
  import Ajv from "ajv";
8
8
 
9
+ import { environmentPathKey } from "../../core/host.mjs";
9
10
  import { createWebOperations, failure, webResult } from "./web-result.mjs";
10
11
 
11
12
  export { projectWebResearchResult, publicWebUrl } from "./web-result.mjs";
@@ -101,7 +102,8 @@ export async function runCodexProcess(binary, args, { environment, cwd, input =
101
102
  async function findCodex(environment) {
102
103
  const candidates = environment.MOONDOG_CODEX_BIN
103
104
  ? [environment.MOONDOG_CODEX_BIN]
104
- : (environment.PATH ?? "").split(path.delimiter).filter(Boolean).map((entry) => path.resolve(entry, "codex"));
105
+ : (environment[environmentPathKey(environment)] ?? "").split(path.delimiter).filter(Boolean)
106
+ .map((entry) => path.resolve(entry, process.platform === "win32" ? "codex.exe" : "codex"));
105
107
  for (const candidate of candidates) {
106
108
  if (!path.isAbsolute(candidate)) continue;
107
109
  try { await access(candidate, constants.X_OK); return candidate; } catch {}
@@ -1,12 +1,9 @@
1
- import { execFile } from "node:child_process";
2
1
  import { constants } from "node:fs";
3
- import { open, mkdtemp, writeFile, rm } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
2
+ import { open } from "node:fs/promises";
5
3
  import path from "node:path";
6
- import { promisify } from "node:util";
4
+ import { openZipArchive } from "../../importers/zip-reader.mjs";
7
5
  import { musicHash, prepareMusicBundle } from "../../profile/music-import-bundle.mjs";
8
6
 
9
- const exec = promisify(execFile);
10
7
  const maximumBytes = 256 * 1024 * 1024;
11
8
  const memberBytes = 64 * 1024 * 1024;
12
9
  const maximumRecords = 100_000;
@@ -103,27 +100,25 @@ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt
103
100
  const sources = [];
104
101
  if (/\.zip$/iu.test(filePath)) {
105
102
  // Read from one private snapshot: manifest digest and preview describe exactly the same bytes.
106
- const root = await mkdtemp(path.join(tmpdir(), "moondog-takeout-"));
103
+ let zip;
107
104
  try {
108
- const zip = path.join(root, "takeout.zip");
109
- await writeFile(zip, bytes, { mode: 0o600 });
110
- const { stdout } = await exec("unzip", ["-Z1", zip], { maxBuffer: 1024 * 1024, timeout: 15_000 });
111
- const names = stdout.trimEnd().split("\n");
112
- const selected = names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
105
+ zip = await openZipArchive(bytes);
106
+ } catch {
107
+ throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file.");
108
+ }
109
+ try {
110
+ const selected = zip.names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
113
111
  if (!selected.length) throw new Error("No supported YouTube Music files in this ZIP. Include music library songs and history in Google Takeout; set history format to JSON, not HTML.");
114
112
  if (selected.length > 100 || new Set(selected).size !== selected.length) throw new Error("Takeout contains too many or duplicate music files.");
115
113
  let total = 0;
116
114
  for (const name of selected) {
117
115
  if (name.startsWith("/") || name.split("/").includes("..") || /[\\*?\[\]\u0000-\u001f\u007f]/u.test(name)) throw new Error("Unsupported archive member path.");
118
- const { stdout: content } = await exec("unzip", ["-p", zip, name], { encoding: "buffer", maxBuffer: memberBytes, timeout: 15_000 });
116
+ const content = await zip.read(name, memberBytes);
119
117
  total += content.length;
120
118
  if (total > maximumBytes) throw new Error("Unpacked music data exceeds 256 MB. Import the extracted files separately.");
121
119
  sources.push({ name: `${musicHash(name).slice(0, 12)}-${path.basename(name)}`, content });
122
120
  }
123
- } catch (error) {
124
- if (error.cmd || error.code === "ENOENT") throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file. ZIP reading requires unzip on this computer.");
125
- throw error;
126
- } finally { await rm(root, { recursive: true, force: true }); }
121
+ } finally { zip.close(); }
127
122
  } else {
128
123
  if (bytes.length > memberBytes) throw new Error("Choose a music CSV or history JSON smaller than 64 MB.");
129
124
  sources.push({ name: path.basename(filePath), content: bytes });
@@ -85,7 +85,9 @@ function literalPath(input) {
85
85
  if (quote && character === quote) {
86
86
  fail("history_import_path_invalid", "Paste one complete file path, not several quoted arguments.");
87
87
  }
88
- if (character === "\\" && quote !== "'") {
88
+ // Windows paths use backslashes as separators, including paths from the desktop file picker.
89
+ // Only POSIX input uses backslashes to escape spaces or shell punctuation.
90
+ if (character === "\\" && quote !== "'" && process.platform !== "win32") {
89
91
  const next = value[index + 1];
90
92
  const allowed = quote === '"' ? /["\\$`]/u : /[ \t()\[\]{}!&;'"\\#$~`]/u;
91
93
  if (!next || !allowed.test(next)) {
@@ -281,6 +281,8 @@ function safeOpenFlags(base) {
281
281
  }
282
282
 
283
283
  async function syncDirectory(directory) {
284
+ // Windows cannot open a directory for fsync. The new file is still synced before rename.
285
+ if (process.platform === "win32") return;
284
286
  let handle;
285
287
  try {
286
288
  handle = await open(directory, fsConstants.O_RDONLY);