@kud/qobuz-cli 0.6.0 → 0.7.0

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 (3) hide show
  1. package/README.md +41 -2
  2. package/dist/index.js +1338 -203
  3. package/package.json +11 -4
package/dist/index.js CHANGED
@@ -1,4 +1,1306 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/lib.ts
13
+ import {
14
+ createKeychainStore,
15
+ createQobuzClient
16
+ } from "@kud/qobuz";
17
+ var store, connect, formatDuration, linkFor, deepLinkFor, appLinkFor;
18
+ var init_lib = __esm({
19
+ "src/lib.ts"() {
20
+ "use strict";
21
+ store = createKeychainStore();
22
+ connect = async () => {
23
+ try {
24
+ return await createQobuzClient({ store });
25
+ } catch (error) {
26
+ const qobuzError = error;
27
+ if (qobuzError.kind === "auth") {
28
+ console.error("Not connected \u2014 run `qobuz login` first.");
29
+ } else {
30
+ console.error(`Error: ${qobuzError.message ?? error}`);
31
+ }
32
+ process.exit(1);
33
+ }
34
+ };
35
+ formatDuration = (seconds) => {
36
+ if (!seconds) return "";
37
+ const minutes = Math.floor(seconds / 60);
38
+ const remainder = String(seconds % 60).padStart(2, "0");
39
+ return `${minutes}:${remainder}`;
40
+ };
41
+ linkFor = (links, type, id) => {
42
+ const builders = {
43
+ album: (value) => links.album(value),
44
+ track: (value) => links.track(Number(value)),
45
+ playlist: (value) => links.playlist(Number(value)),
46
+ artist: (value) => links.artist(Number(value))
47
+ };
48
+ return builders[type]?.(id);
49
+ };
50
+ deepLinkFor = (client, type, id) => linkFor(client.deepLink, type, id);
51
+ appLinkFor = (client, type, id) => linkFor(client.appLink, type, id);
52
+ }
53
+ });
54
+
55
+ // src/resolve.ts
56
+ var CRAWLER_UA, spotifySearchUrl, ytMusicSearchUrl, deezerByIsrc, isQobuz, isSpotify, isYouTube, metaContent, resolveSpotify, resolveYouTube, resolveLink, deezerSearch, findIsrc, normalize, tokenSet, overlap, isLikelyMatch, decodeEntities;
57
+ var init_resolve = __esm({
58
+ "src/resolve.ts"() {
59
+ "use strict";
60
+ CRAWLER_UA = "facebookexternalhit/1.1";
61
+ spotifySearchUrl = (query) => `https://open.spotify.com/search/${encodeURIComponent(query)}`;
62
+ ytMusicSearchUrl = (query) => `https://music.youtube.com/search?q=${encodeURIComponent(query)}`;
63
+ deezerByIsrc = async (isrc) => {
64
+ const res = await fetch(`https://api.deezer.com/track/isrc:${isrc}`).catch(
65
+ () => null
66
+ );
67
+ if (!res || !res.ok) return void 0;
68
+ const track2 = await res.json();
69
+ return track2.link;
70
+ };
71
+ isQobuz = (host) => host.endsWith("qobuz.com");
72
+ isSpotify = (host) => host.endsWith("open.spotify.com");
73
+ isYouTube = (host) => host.endsWith("music.youtube.com") || host.endsWith("youtube.com") || host.endsWith("youtu.be");
74
+ metaContent = (html, property) => html.match(
75
+ new RegExp(`<meta[^>]+property="${property}"[^>]+content="([^"]*)"`, "i")
76
+ )?.[1];
77
+ resolveSpotify = async (url2) => {
78
+ const res = await fetch(url2, { headers: { "User-Agent": CRAWLER_UA } });
79
+ if (!res.ok) return null;
80
+ const html = await res.text();
81
+ const title = metaContent(html, "og:title");
82
+ const artist2 = metaContent(html, "og:description")?.split(" \xB7 ")[0];
83
+ if (title && artist2)
84
+ return { title: decodeEntities(title), artist: decodeEntities(artist2) };
85
+ const match = html.match(/<title>(.*?)<\/title>/i)?.[1]?.match(/^(.+?) - song(?: and lyrics)? by (.+?) \| Spotify/i);
86
+ if (!match?.[1] || !match[2]) return null;
87
+ return { title: decodeEntities(match[1]), artist: decodeEntities(match[2]) };
88
+ };
89
+ resolveYouTube = async (url2) => {
90
+ const endpoint = `https://www.youtube.com/oembed?url=${encodeURIComponent(url2)}&format=json`;
91
+ const res = await fetch(endpoint);
92
+ if (!res.ok) return null;
93
+ const data = await res.json();
94
+ if (!data.title || !data.author_name) return null;
95
+ return {
96
+ title: data.title,
97
+ artist: data.author_name.replace(/ - Topic$/, "")
98
+ };
99
+ };
100
+ resolveLink = async (input) => {
101
+ let url2;
102
+ try {
103
+ url2 = new URL(input);
104
+ } catch {
105
+ return { ok: false, reason: "invalid" };
106
+ }
107
+ const host = url2.hostname;
108
+ const ok = (track2) => track2 ? { ok: true, direction: "to-qobuz", track: track2 } : { ok: false, reason: "unknown" };
109
+ if (isQobuz(host)) {
110
+ const match = url2.pathname.match(/\/track\/(\d+)/);
111
+ return match ? { ok: true, direction: "from-qobuz", qobuzTrackId: Number(match[1]) } : { ok: false, reason: "unsupported-type" };
112
+ }
113
+ if (isSpotify(host))
114
+ return url2.pathname.includes("/track/") ? ok(await resolveSpotify(input)) : { ok: false, reason: "unsupported-type" };
115
+ if (isYouTube(host))
116
+ return url2.pathname === "/watch" || host.endsWith("youtu.be") ? ok(await resolveYouTube(input)) : { ok: false, reason: "unsupported-type" };
117
+ return { ok: false, reason: "unknown" };
118
+ };
119
+ deezerSearch = async (query) => {
120
+ const res = await fetch(
121
+ `https://api.deezer.com/search?q=${encodeURIComponent(query)}&limit=1`
122
+ );
123
+ if (!res.ok) return void 0;
124
+ const data = await res.json();
125
+ return data.data?.[0]?.id;
126
+ };
127
+ findIsrc = async ({
128
+ title,
129
+ artist: artist2
130
+ }) => {
131
+ const id = await deezerSearch(`artist:"${artist2}" track:"${title}"`) ?? await deezerSearch(`${artist2} ${title}`);
132
+ if (id === void 0) return void 0;
133
+ const res = await fetch(`https://api.deezer.com/track/${id}`);
134
+ if (!res.ok) return void 0;
135
+ const track2 = await res.json();
136
+ return track2.isrc;
137
+ };
138
+ normalize = (text) => text.toLowerCase().normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").replace(/\([^)]*\)|\[[^\]]*\]/g, " ").replace(/\b(feat|ft|with)\b\.?/g, " ").replace(/[^a-z0-9]+/g, " ").trim();
139
+ tokenSet = (text) => new Set(normalize(text).split(" ").filter(Boolean));
140
+ overlap = (a, b) => {
141
+ if (a.size === 0 || b.size === 0) return 0;
142
+ let hits = 0;
143
+ for (const token of a) if (b.has(token)) hits += 1;
144
+ return hits / Math.min(a.size, b.size);
145
+ };
146
+ isLikelyMatch = (resolved, candidate) => {
147
+ const titleScore = overlap(
148
+ tokenSet(resolved.title),
149
+ tokenSet(candidate.title)
150
+ );
151
+ const artistScore = overlap(
152
+ tokenSet(resolved.artist),
153
+ tokenSet(candidate.artist?.name ?? "")
154
+ );
155
+ return titleScore >= 0.6 && artistScore > 0;
156
+ };
157
+ decodeEntities = (text) => text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'");
158
+ }
159
+ });
160
+
161
+ // src/prompts.ts
162
+ import readline from "readline";
163
+ import { execFile } from "child_process";
164
+ import { promisify } from "util";
165
+ var exec, createPrompts, openUrl, copyToClipboard, sleep, countdownAndOpen;
166
+ var init_prompts = __esm({
167
+ "src/prompts.ts"() {
168
+ "use strict";
169
+ exec = promisify(execFile);
170
+ createPrompts = () => {
171
+ const rl = readline.createInterface({
172
+ input: process.stdin,
173
+ output: process.stdout
174
+ });
175
+ const ask = (question) => new Promise(
176
+ (resolve) => rl.question(question, (answer) => resolve(answer.trim()))
177
+ );
178
+ const askHidden = (question) => new Promise((resolve) => {
179
+ let muted2 = false;
180
+ rl._writeToOutput = (chunk) => {
181
+ if (!muted2) process.stdout.write(chunk);
182
+ };
183
+ rl.question(question, (answer) => {
184
+ rl._writeToOutput = (chunk) => process.stdout.write(chunk);
185
+ process.stdout.write("\n");
186
+ resolve(answer);
187
+ });
188
+ muted2 = true;
189
+ });
190
+ return { ask, askHidden, close: () => rl.close() };
191
+ };
192
+ openUrl = async (url2) => {
193
+ try {
194
+ await exec("open", [url2]);
195
+ return true;
196
+ } catch {
197
+ return false;
198
+ }
199
+ };
200
+ copyToClipboard = async (text) => {
201
+ try {
202
+ const running = exec("pbcopy");
203
+ running.child.stdin?.end(text);
204
+ await running;
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ };
210
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
211
+ countdownAndOpen = async (url2, seconds = 3) => {
212
+ for (const n2 of Array.from({ length: seconds }, (_, i) => seconds - i)) {
213
+ process.stdout.write(`\r Opening ${url2} in ${n2}\u2026 `);
214
+ await sleep(1e3);
215
+ }
216
+ process.stdout.write(`\r Opening ${url2} now.${" ".repeat(20)}
217
+
218
+ `);
219
+ if (!await openUrl(url2))
220
+ console.log(` (couldn't open a browser \u2014 visit ${url2} manually)`);
221
+ };
222
+ }
223
+ });
224
+
225
+ // src/tui/lib/context.tsx
226
+ import { createContext, useContext } from "react";
227
+ var ClientContext, useClient, NavContext, useNav, InputFocusContext, useInputFocus;
228
+ var init_context = __esm({
229
+ "src/tui/lib/context.tsx"() {
230
+ "use strict";
231
+ ClientContext = createContext(null);
232
+ useClient = () => {
233
+ const client = useContext(ClientContext);
234
+ if (!client) throw new Error("ClientContext is not provided");
235
+ return client;
236
+ };
237
+ NavContext = createContext(null);
238
+ useNav = () => {
239
+ const nav = useContext(NavContext);
240
+ if (!nav) throw new Error("NavContext is not provided");
241
+ return nav;
242
+ };
243
+ InputFocusContext = createContext(null);
244
+ useInputFocus = () => {
245
+ const focus = useContext(InputFocusContext);
246
+ if (!focus) throw new Error("InputFocusContext is not provided");
247
+ return focus;
248
+ };
249
+ }
250
+ });
251
+
252
+ // src/tui/lib/client.ts
253
+ import { createQobuzClient as createQobuzClient2 } from "@kud/qobuz";
254
+ var connectTui;
255
+ var init_client = __esm({
256
+ "src/tui/lib/client.ts"() {
257
+ "use strict";
258
+ init_lib();
259
+ init_lib();
260
+ connectTui = async () => {
261
+ try {
262
+ const client = await createQobuzClient2({ store });
263
+ return { ok: true, client };
264
+ } catch (error) {
265
+ const qobuzError = error;
266
+ if (qobuzError.kind === "auth") return { ok: false, reason: "auth" };
267
+ return {
268
+ ok: false,
269
+ reason: "error",
270
+ message: qobuzError.message ?? String(error)
271
+ };
272
+ }
273
+ };
274
+ }
275
+ });
276
+
277
+ // src/tui/lib/media.ts
278
+ var mediaKeysAvailable, sendMediaKey;
279
+ var init_media = __esm({
280
+ "src/tui/lib/media.ts"() {
281
+ "use strict";
282
+ mediaKeysAvailable = process.platform === "darwin";
283
+ sendMediaKey = async (key) => {
284
+ try {
285
+ const { sendMediaKey: send } = await import("@kud/macos-media-keys");
286
+ await send(key);
287
+ return true;
288
+ } catch {
289
+ return false;
290
+ }
291
+ };
292
+ }
293
+ });
294
+
295
+ // src/tui/components/Spinner.tsx
296
+ import { useEffect, useState } from "react";
297
+ import { Text } from "ink";
298
+ import { jsxs } from "react/jsx-runtime";
299
+ var FRAMES, Spinner;
300
+ var init_Spinner = __esm({
301
+ "src/tui/components/Spinner.tsx"() {
302
+ "use strict";
303
+ FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
304
+ Spinner = ({ label = "Loading\u2026" }) => {
305
+ const [frame, setFrame] = useState(0);
306
+ useEffect(() => {
307
+ const timer = setInterval(
308
+ () => setFrame((value) => (value + 1) % FRAMES.length),
309
+ 80
310
+ );
311
+ return () => clearInterval(timer);
312
+ }, []);
313
+ return /* @__PURE__ */ jsxs(Text, { color: "cyan", children: [
314
+ FRAMES[frame],
315
+ " ",
316
+ label
317
+ ] });
318
+ };
319
+ }
320
+ });
321
+
322
+ // src/tui/components/ErrorBanner.tsx
323
+ import { Box, Text as Text2 } from "ink";
324
+ import { jsx, jsxs as jsxs2 } from "react/jsx-runtime";
325
+ var ErrorBanner;
326
+ var init_ErrorBanner = __esm({
327
+ "src/tui/components/ErrorBanner.tsx"() {
328
+ "use strict";
329
+ ErrorBanner = ({ message }) => /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsxs2(Text2, { color: "red", children: [
330
+ "\u2717 ",
331
+ message
332
+ ] }) });
333
+ }
334
+ });
335
+
336
+ // src/tui/views/NotLoggedIn.tsx
337
+ import { Box as Box2, Text as Text3, useApp, useInput } from "ink";
338
+ import { jsx as jsx2, jsxs as jsxs3 } from "react/jsx-runtime";
339
+ var NotLoggedIn;
340
+ var init_NotLoggedIn = __esm({
341
+ "src/tui/views/NotLoggedIn.tsx"() {
342
+ "use strict";
343
+ NotLoggedIn = () => {
344
+ const { exit } = useApp();
345
+ useInput((input, key) => {
346
+ if (input === "q" || key.escape || key.ctrl && input === "c") exit();
347
+ });
348
+ return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", padding: 1, children: [
349
+ /* @__PURE__ */ jsx2(Text3, { color: "yellow", children: "Not logged in." }),
350
+ /* @__PURE__ */ jsxs3(Text3, { dimColor: true, children: [
351
+ "Run ",
352
+ /* @__PURE__ */ jsx2(Text3, { color: "cyan", children: "qobuz login" }),
353
+ " to connect your account."
354
+ ] }),
355
+ /* @__PURE__ */ jsx2(Box2, { marginTop: 1, children: /* @__PURE__ */ jsx2(Text3, { dimColor: true, children: "q quit" }) })
356
+ ] });
357
+ };
358
+ }
359
+ });
360
+
361
+ // src/tui/components/SelectList.tsx
362
+ import { useState as useState2 } from "react";
363
+ import { Box as Box3, Text as Text4, useInput as useInput2 } from "ink";
364
+ import { jsx as jsx3, jsxs as jsxs4 } from "react/jsx-runtime";
365
+ var flatten, selectableIndices, SelectList;
366
+ var init_SelectList = __esm({
367
+ "src/tui/components/SelectList.tsx"() {
368
+ "use strict";
369
+ init_context();
370
+ flatten = (sections) => sections.flatMap(
371
+ (section) => section.items.length === 0 ? [] : [
372
+ ...section.title ? [{ kind: "header", title: section.title }] : [],
373
+ ...section.items.map((item) => ({ kind: "item", item }))
374
+ ]
375
+ );
376
+ selectableIndices = (rows) => rows.reduce((acc, row, index) => {
377
+ if (row.kind === "item") acc.push(index);
378
+ return acc;
379
+ }, []);
380
+ SelectList = ({
381
+ sections,
382
+ onSubmit,
383
+ viewport = 12,
384
+ arrowOnly = false
385
+ }) => {
386
+ const rows = flatten(sections);
387
+ const selectable = selectableIndices(rows);
388
+ const [cursor, setCursor] = useState2(0);
389
+ const { inputFocused } = useInputFocus();
390
+ const active = arrowOnly || !inputFocused;
391
+ const clampedCursor = Math.min(cursor, Math.max(0, selectable.length - 1));
392
+ useInput2(
393
+ (input, key) => {
394
+ if (selectable.length === 0) return;
395
+ if (key.downArrow || !arrowOnly && input === "j")
396
+ setCursor((value) => Math.min(value + 1, selectable.length - 1));
397
+ if (key.upArrow || !arrowOnly && input === "k")
398
+ setCursor((value) => Math.max(value - 1, 0));
399
+ if (key.return) {
400
+ const rowIndex = selectable[clampedCursor];
401
+ if (rowIndex === void 0) return;
402
+ const row = rows[rowIndex];
403
+ if (row && row.kind === "item") onSubmit(row.item.value);
404
+ }
405
+ },
406
+ { isActive: active }
407
+ );
408
+ if (selectable.length === 0) return /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: "No results." });
409
+ const activeRow = selectable[clampedCursor] ?? 0;
410
+ const half = Math.floor(viewport / 2);
411
+ const start = Math.max(0, Math.min(activeRow - half, rows.length - viewport));
412
+ const windowed = rows.slice(start, start + viewport);
413
+ return /* @__PURE__ */ jsx3(Box3, { flexDirection: "column", children: windowed.map((row, offset) => {
414
+ const index = start + offset;
415
+ if (row.kind === "header")
416
+ return /* @__PURE__ */ jsx3(Text4, { bold: true, color: "cyan", children: row.title }, `header-${index}`);
417
+ const selected = index === activeRow;
418
+ return /* @__PURE__ */ jsxs4(Text4, { color: selected ? "green" : void 0, children: [
419
+ selected ? "\u276F " : " ",
420
+ row.item.label,
421
+ row.item.hint ? /* @__PURE__ */ jsxs4(Text4, { dimColor: true, children: [
422
+ " ",
423
+ row.item.hint
424
+ ] }) : null
425
+ ] }, row.item.key);
426
+ }) });
427
+ };
428
+ }
429
+ });
430
+
431
+ // src/tui/components/Footer.tsx
432
+ import { Box as Box4, Text as Text5 } from "ink";
433
+ import { jsx as jsx4 } from "react/jsx-runtime";
434
+ var Footer;
435
+ var init_Footer = __esm({
436
+ "src/tui/components/Footer.tsx"() {
437
+ "use strict";
438
+ init_media();
439
+ Footer = ({ hints }) => {
440
+ const visible = hints.filter((hint) => !hint.playback || mediaKeysAvailable);
441
+ return /* @__PURE__ */ jsx4(Box4, { marginTop: 1, children: /* @__PURE__ */ jsx4(Text5, { dimColor: true, children: visible.map((hint) => `${hint.key} ${hint.label}`).join(" ") }) });
442
+ };
443
+ }
444
+ });
445
+
446
+ // src/tui/views/Home.tsx
447
+ import { Box as Box5, Text as Text6 } from "ink";
448
+ import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
449
+ var entries, Home;
450
+ var init_Home = __esm({
451
+ "src/tui/views/Home.tsx"() {
452
+ "use strict";
453
+ init_context();
454
+ init_SelectList();
455
+ init_Footer();
456
+ entries = [
457
+ { key: "search", label: "Search", value: { kind: "search" } },
458
+ { key: "favourites", label: "Favourites", value: { kind: "favourites" } },
459
+ { key: "playlists", label: "Playlists", value: { kind: "playlists" } },
460
+ { key: "nowPlaying", label: "Now Playing", value: { kind: "nowPlaying" } }
461
+ ];
462
+ Home = () => {
463
+ const nav = useNav();
464
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
465
+ /* @__PURE__ */ jsx5(Text6, { bold: true, children: "Qobuz" }),
466
+ /* @__PURE__ */ jsx5(Box5, { marginTop: 1, children: /* @__PURE__ */ jsx5(
467
+ SelectList,
468
+ {
469
+ sections: [{ title: "", items: entries }],
470
+ onSubmit: (view) => nav.push(view)
471
+ }
472
+ ) }),
473
+ /* @__PURE__ */ jsx5(
474
+ Footer,
475
+ {
476
+ hints: [
477
+ { key: "\u21B5", label: "open" },
478
+ { key: "\u2191\u2193/jk", label: "move" },
479
+ { key: "q", label: "quit" }
480
+ ]
481
+ }
482
+ )
483
+ ] });
484
+ };
485
+ }
486
+ });
487
+
488
+ // src/tui/lib/use-async.ts
489
+ import { useCallback, useEffect as useEffect2, useState as useState3 } from "react";
490
+ var useAsync;
491
+ var init_use_async = __esm({
492
+ "src/tui/lib/use-async.ts"() {
493
+ "use strict";
494
+ useAsync = (fn, deps) => {
495
+ const [data, setData] = useState3(void 0);
496
+ const [error, setError] = useState3(void 0);
497
+ const [loading, setLoading] = useState3(true);
498
+ const [nonce, setNonce] = useState3(0);
499
+ const run = useCallback(fn, deps);
500
+ useEffect2(() => {
501
+ let active = true;
502
+ setLoading(true);
503
+ setError(void 0);
504
+ run().then((result) => {
505
+ if (!active) return;
506
+ setData(result);
507
+ setLoading(false);
508
+ }).catch((cause) => {
509
+ if (!active) return;
510
+ setError(cause instanceof Error ? cause.message : String(cause));
511
+ setLoading(false);
512
+ });
513
+ return () => {
514
+ active = false;
515
+ };
516
+ }, [run, nonce]);
517
+ const reload = useCallback(() => setNonce((value) => value + 1), []);
518
+ return { data, error, loading, reload };
519
+ };
520
+ }
521
+ });
522
+
523
+ // src/tui/lib/use-debounced.ts
524
+ import { useEffect as useEffect3, useState as useState4 } from "react";
525
+ var useDebouncedValue;
526
+ var init_use_debounced = __esm({
527
+ "src/tui/lib/use-debounced.ts"() {
528
+ "use strict";
529
+ useDebouncedValue = (value, delay = 300) => {
530
+ const [debounced, setDebounced] = useState4(value);
531
+ useEffect3(() => {
532
+ const timer = setTimeout(() => setDebounced(value), delay);
533
+ return () => clearTimeout(timer);
534
+ }, [value, delay]);
535
+ return debounced;
536
+ };
537
+ }
538
+ });
539
+
540
+ // src/tui/views/Search.tsx
541
+ import { useEffect as useEffect4, useState as useState5 } from "react";
542
+ import { Box as Box6, Text as Text7 } from "ink";
543
+ import TextInput from "ink-text-input";
544
+ import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
545
+ var buildSections, Search;
546
+ var init_Search = __esm({
547
+ "src/tui/views/Search.tsx"() {
548
+ "use strict";
549
+ init_context();
550
+ init_client();
551
+ init_use_async();
552
+ init_use_debounced();
553
+ init_SelectList();
554
+ init_Spinner();
555
+ init_ErrorBanner();
556
+ init_Footer();
557
+ buildSections = (results) => {
558
+ if (!results) return [];
559
+ return [
560
+ {
561
+ title: "Tracks",
562
+ items: results.tracks.map((track2) => ({
563
+ key: `track-${track2.id}`,
564
+ label: track2.title,
565
+ hint: `${track2.artist?.name ?? ""} ${formatDuration(track2.duration)}`.trim(),
566
+ value: { type: "track", track: track2 }
567
+ }))
568
+ },
569
+ {
570
+ title: "Albums",
571
+ items: results.albums.map((album2) => ({
572
+ key: `album-${album2.id}`,
573
+ label: album2.title,
574
+ hint: album2.artist?.name,
575
+ value: { type: "album", album: album2 }
576
+ }))
577
+ },
578
+ {
579
+ title: "Artists",
580
+ items: results.artists.map((artist2) => ({
581
+ key: `artist-${artist2.id}`,
582
+ label: artist2.name,
583
+ value: { type: "artist", artist: artist2 }
584
+ }))
585
+ }
586
+ ];
587
+ };
588
+ Search = () => {
589
+ const client = useClient();
590
+ const nav = useNav();
591
+ const { setInputFocused } = useInputFocus();
592
+ const [query, setQuery] = useState5("");
593
+ const debounced = useDebouncedValue(query, 300);
594
+ const term = debounced.trim();
595
+ useEffect4(() => {
596
+ setInputFocused(true);
597
+ return () => setInputFocused(false);
598
+ }, [setInputFocused]);
599
+ const { data, error, loading } = useAsync(
600
+ () => term.length >= 2 ? client.search.search(term, { limit: 20 }) : Promise.resolve(void 0),
601
+ [term]
602
+ );
603
+ const sections = buildSections(data);
604
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", children: [
605
+ /* @__PURE__ */ jsxs6(Box6, { children: [
606
+ /* @__PURE__ */ jsx6(Text7, { bold: true, children: "Search " }),
607
+ /* @__PURE__ */ jsx6(TextInput, { value: query, onChange: setQuery, placeholder: "type\u2026" })
608
+ ] }),
609
+ /* @__PURE__ */ jsxs6(Box6, { marginTop: 1, flexDirection: "column", children: [
610
+ error ? /* @__PURE__ */ jsx6(ErrorBanner, { message: error }) : null,
611
+ term.length >= 2 && loading ? /* @__PURE__ */ jsx6(Spinner, {}) : null,
612
+ term.length >= 2 && !loading && !error ? /* @__PURE__ */ jsx6(
613
+ SelectList,
614
+ {
615
+ sections,
616
+ arrowOnly: true,
617
+ onSubmit: (item) => nav.push({ kind: "detail", item })
618
+ }
619
+ ) : null,
620
+ term.length < 2 ? /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "Type at least 2 characters." }) : null
621
+ ] }),
622
+ /* @__PURE__ */ jsx6(
623
+ Footer,
624
+ {
625
+ hints: [
626
+ { key: "\u21B5", label: "open" },
627
+ { key: "esc", label: "back" }
628
+ ]
629
+ }
630
+ )
631
+ ] });
632
+ };
633
+ }
634
+ });
635
+
636
+ // src/tui/views/Detail.tsx
637
+ import { useEffect as useEffect5 } from "react";
638
+ import { Box as Box7, Text as Text8 } from "ink";
639
+ import { jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
640
+ var Field, TrackDetail, AlbumDetail, ArtistDetail, Detail, PlaylistRedirect;
641
+ var init_Detail = __esm({
642
+ "src/tui/views/Detail.tsx"() {
643
+ "use strict";
644
+ init_context();
645
+ init_client();
646
+ init_use_async();
647
+ init_SelectList();
648
+ init_Spinner();
649
+ init_ErrorBanner();
650
+ init_Footer();
651
+ Field = ({ label, value }) => value ? /* @__PURE__ */ jsxs7(Text8, { children: [
652
+ /* @__PURE__ */ jsxs7(Text8, { dimColor: true, children: [
653
+ label,
654
+ " "
655
+ ] }),
656
+ value
657
+ ] }) : null;
658
+ TrackDetail = ({
659
+ target
660
+ }) => {
661
+ const { track: track2 } = target;
662
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", children: [
663
+ /* @__PURE__ */ jsxs7(Text8, { bold: true, children: [
664
+ "\u{1F3B5} ",
665
+ track2.title
666
+ ] }),
667
+ /* @__PURE__ */ jsx7(Field, { label: "Artist", value: track2.artist?.name }),
668
+ /* @__PURE__ */ jsx7(Field, { label: "Album", value: track2.album?.title }),
669
+ /* @__PURE__ */ jsx7(Field, { label: "Duration", value: formatDuration(track2.duration) }),
670
+ track2.hires ? /* @__PURE__ */ jsx7(Text8, { color: "green", children: "Hi-Res" }) : null,
671
+ /* @__PURE__ */ jsx7(
672
+ Footer,
673
+ {
674
+ hints: [
675
+ { key: "o", label: "open in Qobuz" },
676
+ { key: "c", label: "convert" },
677
+ { key: "space", label: "play", playback: true },
678
+ { key: "esc", label: "back" }
679
+ ]
680
+ }
681
+ )
682
+ ] });
683
+ };
684
+ AlbumDetail = ({
685
+ target
686
+ }) => {
687
+ const { album: album2 } = target;
688
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", children: [
689
+ /* @__PURE__ */ jsxs7(Text8, { bold: true, children: [
690
+ "\u{1F4BF} ",
691
+ album2.title
692
+ ] }),
693
+ /* @__PURE__ */ jsx7(Field, { label: "Artist", value: album2.artist?.name }),
694
+ /* @__PURE__ */ jsx7(Field, { label: "Released", value: album2.releaseDate }),
695
+ /* @__PURE__ */ jsx7(Field, { label: "Genre", value: album2.genre }),
696
+ /* @__PURE__ */ jsx7(
697
+ Field,
698
+ {
699
+ label: "Tracks",
700
+ value: album2.tracksCount ? String(album2.tracksCount) : void 0
701
+ }
702
+ ),
703
+ album2.hires ? /* @__PURE__ */ jsx7(Text8, { color: "green", children: "Hi-Res" }) : null,
704
+ /* @__PURE__ */ jsx7(
705
+ Footer,
706
+ {
707
+ hints: [
708
+ { key: "o", label: "open in Qobuz" },
709
+ { key: "esc", label: "back" }
710
+ ]
711
+ }
712
+ )
713
+ ] });
714
+ };
715
+ ArtistDetail = ({
716
+ target
717
+ }) => {
718
+ const client = useClient();
719
+ const nav = useNav();
720
+ const artistId = target.artist.id;
721
+ const { data, error, loading } = useAsync(async () => {
722
+ const [artist2, similar2] = await Promise.all([
723
+ client.artists.get(artistId),
724
+ client.artists.getSimilar(artistId, { limit: 20 })
725
+ ]);
726
+ return { artist: artist2, similar: similar2 };
727
+ }, [artistId]);
728
+ const items = (data?.similar ?? []).map((artist2) => ({
729
+ key: `artist-${artist2.id}`,
730
+ label: artist2.name,
731
+ value: artist2
732
+ }));
733
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", children: [
734
+ /* @__PURE__ */ jsxs7(Text8, { bold: true, children: [
735
+ "\u{1F3A4} ",
736
+ data?.artist.name ?? target.artist.name
737
+ ] }),
738
+ /* @__PURE__ */ jsx7(
739
+ Field,
740
+ {
741
+ label: "Albums",
742
+ value: data?.artist.albumsCount ? String(data.artist.albumsCount) : void 0
743
+ }
744
+ ),
745
+ /* @__PURE__ */ jsxs7(Box7, { marginTop: 1, flexDirection: "column", children: [
746
+ /* @__PURE__ */ jsx7(Text8, { bold: true, color: "cyan", children: "Similar artists" }),
747
+ error ? /* @__PURE__ */ jsx7(ErrorBanner, { message: error }) : null,
748
+ loading ? /* @__PURE__ */ jsx7(Spinner, {}) : null,
749
+ !loading && !error ? /* @__PURE__ */ jsx7(
750
+ SelectList,
751
+ {
752
+ sections: [{ title: "", items }],
753
+ onSubmit: (artist2) => nav.push({ kind: "detail", item: { type: "artist", artist: artist2 } })
754
+ }
755
+ ) : null
756
+ ] }),
757
+ /* @__PURE__ */ jsx7(
758
+ Footer,
759
+ {
760
+ hints: [
761
+ { key: "\u21B5", label: "open artist" },
762
+ { key: "o", label: "open in Qobuz" },
763
+ { key: "esc", label: "back" }
764
+ ]
765
+ }
766
+ )
767
+ ] });
768
+ };
769
+ Detail = ({ target }) => {
770
+ switch (target.type) {
771
+ case "track":
772
+ return /* @__PURE__ */ jsx7(TrackDetail, { target });
773
+ case "album":
774
+ return /* @__PURE__ */ jsx7(AlbumDetail, { target });
775
+ case "artist":
776
+ return /* @__PURE__ */ jsx7(ArtistDetail, { target });
777
+ case "playlist":
778
+ return /* @__PURE__ */ jsx7(PlaylistRedirect, { target });
779
+ }
780
+ };
781
+ PlaylistRedirect = ({
782
+ target
783
+ }) => {
784
+ const nav = useNav();
785
+ useEffect5(() => {
786
+ nav.replace({ kind: "playlist", playlist: target.playlist });
787
+ }, [nav, target.playlist]);
788
+ return null;
789
+ };
790
+ }
791
+ });
792
+
793
+ // src/tui/views/Favourites.tsx
794
+ import { Box as Box8, Text as Text9 } from "ink";
795
+ import { jsx as jsx8, jsxs as jsxs8 } from "react/jsx-runtime";
796
+ var buildSections2, Favourites;
797
+ var init_Favourites = __esm({
798
+ "src/tui/views/Favourites.tsx"() {
799
+ "use strict";
800
+ init_context();
801
+ init_client();
802
+ init_use_async();
803
+ init_SelectList();
804
+ init_Spinner();
805
+ init_ErrorBanner();
806
+ init_Footer();
807
+ buildSections2 = (favourites) => {
808
+ if (!favourites) return [];
809
+ return [
810
+ {
811
+ title: "Tracks",
812
+ items: favourites.tracks.map((track2) => ({
813
+ key: `track-${track2.id}`,
814
+ label: track2.title,
815
+ hint: `${track2.artist?.name ?? ""} ${formatDuration(track2.duration)}`.trim(),
816
+ value: { type: "track", track: track2 }
817
+ }))
818
+ },
819
+ {
820
+ title: "Albums",
821
+ items: favourites.albums.map((album2) => ({
822
+ key: `album-${album2.id}`,
823
+ label: album2.title,
824
+ hint: album2.artist?.name,
825
+ value: { type: "album", album: album2 }
826
+ }))
827
+ },
828
+ {
829
+ title: "Artists",
830
+ items: favourites.artists.map((artist2) => ({
831
+ key: `artist-${artist2.id}`,
832
+ label: artist2.name,
833
+ value: { type: "artist", artist: artist2 }
834
+ }))
835
+ }
836
+ ];
837
+ };
838
+ Favourites = () => {
839
+ const client = useClient();
840
+ const nav = useNav();
841
+ const { data, error, loading } = useAsync(async () => {
842
+ const [albums, artists, tracks] = await Promise.all([
843
+ client.favourites.list("albums", { limit: 50 }),
844
+ client.favourites.list("artists", { limit: 50 }),
845
+ client.favourites.list("tracks", { limit: 50 })
846
+ ]);
847
+ return {
848
+ albums: albums.albums,
849
+ artists: artists.artists,
850
+ tracks: tracks.tracks
851
+ };
852
+ }, []);
853
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
854
+ /* @__PURE__ */ jsx8(Text9, { bold: true, children: "Favourites" }),
855
+ /* @__PURE__ */ jsxs8(Box8, { marginTop: 1, flexDirection: "column", children: [
856
+ error ? /* @__PURE__ */ jsx8(ErrorBanner, { message: error }) : null,
857
+ loading ? /* @__PURE__ */ jsx8(Spinner, {}) : null,
858
+ !loading && !error ? /* @__PURE__ */ jsx8(
859
+ SelectList,
860
+ {
861
+ sections: buildSections2(data),
862
+ onSubmit: (item) => nav.push({ kind: "detail", item })
863
+ }
864
+ ) : null
865
+ ] }),
866
+ /* @__PURE__ */ jsx8(
867
+ Footer,
868
+ {
869
+ hints: [
870
+ { key: "\u21B5", label: "open" },
871
+ { key: "esc", label: "back" }
872
+ ]
873
+ }
874
+ )
875
+ ] });
876
+ };
877
+ }
878
+ });
879
+
880
+ // src/tui/views/Playlists.tsx
881
+ import { Box as Box9, Text as Text10 } from "ink";
882
+ import { jsx as jsx9, jsxs as jsxs9 } from "react/jsx-runtime";
883
+ var Playlists;
884
+ var init_Playlists = __esm({
885
+ "src/tui/views/Playlists.tsx"() {
886
+ "use strict";
887
+ init_context();
888
+ init_use_async();
889
+ init_SelectList();
890
+ init_Spinner();
891
+ init_ErrorBanner();
892
+ init_Footer();
893
+ Playlists = () => {
894
+ const client = useClient();
895
+ const nav = useNav();
896
+ const { data, error, loading } = useAsync(
897
+ () => client.playlists.listForUser({ limit: 50 }),
898
+ []
899
+ );
900
+ const items = (data ?? []).map((playlist2) => ({
901
+ key: `playlist-${playlist2.id}`,
902
+ label: playlist2.name,
903
+ hint: playlist2.tracksCount ? `${playlist2.tracksCount} tracks` : void 0,
904
+ value: playlist2
905
+ }));
906
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", children: [
907
+ /* @__PURE__ */ jsx9(Text10, { bold: true, children: "Playlists" }),
908
+ /* @__PURE__ */ jsxs9(Box9, { marginTop: 1, flexDirection: "column", children: [
909
+ error ? /* @__PURE__ */ jsx9(ErrorBanner, { message: error }) : null,
910
+ loading ? /* @__PURE__ */ jsx9(Spinner, {}) : null,
911
+ !loading && !error ? /* @__PURE__ */ jsx9(
912
+ SelectList,
913
+ {
914
+ sections: [{ title: "", items }],
915
+ onSubmit: (playlist2) => nav.push({ kind: "playlist", playlist: playlist2 })
916
+ }
917
+ ) : null
918
+ ] }),
919
+ /* @__PURE__ */ jsx9(
920
+ Footer,
921
+ {
922
+ hints: [
923
+ { key: "\u21B5", label: "open" },
924
+ { key: "esc", label: "back" }
925
+ ]
926
+ }
927
+ )
928
+ ] });
929
+ };
930
+ }
931
+ });
932
+
933
+ // src/tui/views/Playlist.tsx
934
+ import { Box as Box10, Text as Text11 } from "ink";
935
+ import { jsx as jsx10, jsxs as jsxs10 } from "react/jsx-runtime";
936
+ var Playlist;
937
+ var init_Playlist = __esm({
938
+ "src/tui/views/Playlist.tsx"() {
939
+ "use strict";
940
+ init_context();
941
+ init_client();
942
+ init_use_async();
943
+ init_SelectList();
944
+ init_Spinner();
945
+ init_ErrorBanner();
946
+ init_Footer();
947
+ Playlist = ({ playlist: playlist2 }) => {
948
+ const client = useClient();
949
+ const nav = useNav();
950
+ const { data, error, loading } = useAsync(
951
+ () => client.playlists.get(playlist2.id, { limit: 100 }),
952
+ [playlist2.id]
953
+ );
954
+ const tracks = data?.tracks ?? [];
955
+ const items = tracks.map((track2) => ({
956
+ key: `track-${track2.id}`,
957
+ label: track2.title,
958
+ hint: `${track2.artist?.name ?? ""} ${formatDuration(track2.duration)}`.trim(),
959
+ value: track2
960
+ }));
961
+ return /* @__PURE__ */ jsxs10(Box10, { flexDirection: "column", children: [
962
+ /* @__PURE__ */ jsx10(Text11, { bold: true, children: data?.name ?? playlist2.name }),
963
+ /* @__PURE__ */ jsxs10(Box10, { marginTop: 1, flexDirection: "column", children: [
964
+ error ? /* @__PURE__ */ jsx10(ErrorBanner, { message: error }) : null,
965
+ loading ? /* @__PURE__ */ jsx10(Spinner, {}) : null,
966
+ !loading && !error ? /* @__PURE__ */ jsx10(
967
+ SelectList,
968
+ {
969
+ sections: [{ title: "", items }],
970
+ onSubmit: (track2) => nav.push({ kind: "detail", item: { type: "track", track: track2 } })
971
+ }
972
+ ) : null
973
+ ] }),
974
+ /* @__PURE__ */ jsx10(
975
+ Footer,
976
+ {
977
+ hints: [
978
+ { key: "\u21B5", label: "open track" },
979
+ { key: "esc", label: "back" }
980
+ ]
981
+ }
982
+ )
983
+ ] });
984
+ };
985
+ }
986
+ });
987
+
988
+ // src/tui/views/NowPlaying.tsx
989
+ import { useEffect as useEffect6 } from "react";
990
+ import { Box as Box11, Text as Text12, useInput as useInput3 } from "ink";
991
+ import { jsx as jsx11, jsxs as jsxs11 } from "react/jsx-runtime";
992
+ var NowPlaying;
993
+ var init_NowPlaying = __esm({
994
+ "src/tui/views/NowPlaying.tsx"() {
995
+ "use strict";
996
+ init_context();
997
+ init_client();
998
+ init_prompts();
999
+ init_use_async();
1000
+ init_Spinner();
1001
+ init_ErrorBanner();
1002
+ init_Footer();
1003
+ NowPlaying = () => {
1004
+ const client = useClient();
1005
+ const { data, error, loading, reload } = useAsync(
1006
+ () => client.nowPlaying(),
1007
+ []
1008
+ );
1009
+ const { inputFocused } = useInputFocus();
1010
+ useEffect6(() => {
1011
+ const timer = setInterval(reload, 3e3);
1012
+ return () => clearInterval(timer);
1013
+ }, [reload]);
1014
+ useInput3(
1015
+ (input) => {
1016
+ if (input !== "o" || !data) return;
1017
+ const url2 = deepLinkFor(client, "track", String(data.id));
1018
+ if (url2) void openUrl(url2);
1019
+ },
1020
+ { isActive: !inputFocused }
1021
+ );
1022
+ return /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", children: [
1023
+ /* @__PURE__ */ jsx11(Text12, { bold: true, children: "Now Playing" }),
1024
+ /* @__PURE__ */ jsxs11(Box11, { marginTop: 1, flexDirection: "column", children: [
1025
+ error ? /* @__PURE__ */ jsx11(ErrorBanner, { message: error }) : null,
1026
+ loading && !data ? /* @__PURE__ */ jsx11(Spinner, {}) : null,
1027
+ !loading && !error && !data ? /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: "Nothing is playing." }) : null,
1028
+ data ? /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", children: [
1029
+ /* @__PURE__ */ jsxs11(Text12, { bold: true, children: [
1030
+ "\u{1F3B5} ",
1031
+ data.title
1032
+ ] }),
1033
+ /* @__PURE__ */ jsxs11(Text12, { children: [
1034
+ /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: "Artist " }),
1035
+ data.artist?.name ?? "?"
1036
+ ] }),
1037
+ data.album?.title ? /* @__PURE__ */ jsxs11(Text12, { children: [
1038
+ /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: "Album " }),
1039
+ data.album.title
1040
+ ] }) : null,
1041
+ /* @__PURE__ */ jsxs11(Text12, { children: [
1042
+ /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: "Duration " }),
1043
+ formatDuration(data.duration)
1044
+ ] })
1045
+ ] }) : null
1046
+ ] }),
1047
+ /* @__PURE__ */ jsx11(
1048
+ Footer,
1049
+ {
1050
+ hints: [
1051
+ { key: "o", label: "open in Qobuz" },
1052
+ { key: "space", label: "play/pause", playback: true },
1053
+ { key: "n", label: "next", playback: true },
1054
+ { key: "p", label: "prev", playback: true },
1055
+ { key: "esc", label: "back" }
1056
+ ]
1057
+ }
1058
+ )
1059
+ ] });
1060
+ };
1061
+ }
1062
+ });
1063
+
1064
+ // src/tui/views/Convert.tsx
1065
+ import { useState as useState6 } from "react";
1066
+ import { Box as Box12, Text as Text13 } from "ink";
1067
+ import { jsx as jsx12, jsxs as jsxs12 } from "react/jsx-runtime";
1068
+ var Convert;
1069
+ var init_Convert = __esm({
1070
+ "src/tui/views/Convert.tsx"() {
1071
+ "use strict";
1072
+ init_use_async();
1073
+ init_resolve();
1074
+ init_prompts();
1075
+ init_SelectList();
1076
+ init_Spinner();
1077
+ init_ErrorBanner();
1078
+ init_Footer();
1079
+ Convert = ({ track: track2 }) => {
1080
+ const [status, setStatus] = useState6(void 0);
1081
+ const { data, error, loading } = useAsync(async () => {
1082
+ const query = `${track2.artist?.name ?? ""} ${track2.title}`.trim();
1083
+ const deezer = track2.isrc ? await deezerByIsrc(track2.isrc) : void 0;
1084
+ const links = [
1085
+ { service: "YouTube Music", url: ytMusicSearchUrl(query) },
1086
+ { service: "Spotify", url: spotifySearchUrl(query) }
1087
+ ];
1088
+ if (deezer) links.push({ service: "Deezer", url: deezer, exact: true });
1089
+ return links;
1090
+ }, [track2.id]);
1091
+ const items = (data ?? []).map((link2) => ({
1092
+ key: link2.service,
1093
+ label: link2.service,
1094
+ hint: link2.exact ? "exact" : link2.url,
1095
+ value: link2
1096
+ }));
1097
+ return /* @__PURE__ */ jsxs12(Box12, { flexDirection: "column", children: [
1098
+ /* @__PURE__ */ jsxs12(Text13, { bold: true, children: [
1099
+ "\u{1F3B5} ",
1100
+ track2.title
1101
+ ] }),
1102
+ /* @__PURE__ */ jsxs12(Text13, { dimColor: true, children: [
1103
+ "by ",
1104
+ track2.artist?.name ?? "?"
1105
+ ] }),
1106
+ /* @__PURE__ */ jsxs12(Box12, { marginTop: 1, flexDirection: "column", children: [
1107
+ /* @__PURE__ */ jsx12(Text13, { bold: true, color: "cyan", children: "Find elsewhere" }),
1108
+ error ? /* @__PURE__ */ jsx12(ErrorBanner, { message: error }) : null,
1109
+ loading ? /* @__PURE__ */ jsx12(Spinner, {}) : null,
1110
+ !loading && !error ? /* @__PURE__ */ jsx12(
1111
+ SelectList,
1112
+ {
1113
+ sections: [{ title: "", items }],
1114
+ onSubmit: async (link2) => {
1115
+ const opened = await openUrl(link2.url);
1116
+ setStatus(
1117
+ opened ? `Opened ${link2.service}.` : `Couldn't open ${link2.service}.`
1118
+ );
1119
+ }
1120
+ }
1121
+ ) : null,
1122
+ status ? /* @__PURE__ */ jsx12(Text13, { dimColor: true, children: status }) : null
1123
+ ] }),
1124
+ /* @__PURE__ */ jsx12(
1125
+ Footer,
1126
+ {
1127
+ hints: [
1128
+ { key: "\u21B5", label: "open link" },
1129
+ { key: "esc", label: "back" }
1130
+ ]
1131
+ }
1132
+ )
1133
+ ] });
1134
+ };
1135
+ }
1136
+ });
1137
+
1138
+ // src/tui/App.tsx
1139
+ import { useEffect as useEffect7, useMemo, useState as useState7 } from "react";
1140
+ import { Box as Box13, Text as Text14, useApp as useApp2, useInput as useInput4 } from "ink";
1141
+ import { jsx as jsx13, jsxs as jsxs13 } from "react/jsx-runtime";
1142
+ var renderView, openTargetUrl, App;
1143
+ var init_App = __esm({
1144
+ "src/tui/App.tsx"() {
1145
+ "use strict";
1146
+ init_context();
1147
+ init_client();
1148
+ init_media();
1149
+ init_prompts();
1150
+ init_Spinner();
1151
+ init_ErrorBanner();
1152
+ init_NotLoggedIn();
1153
+ init_Home();
1154
+ init_Search();
1155
+ init_Detail();
1156
+ init_Favourites();
1157
+ init_Playlists();
1158
+ init_Playlist();
1159
+ init_NowPlaying();
1160
+ init_Convert();
1161
+ renderView = (view) => {
1162
+ switch (view.kind) {
1163
+ case "home":
1164
+ return /* @__PURE__ */ jsx13(Home, {});
1165
+ case "search":
1166
+ return /* @__PURE__ */ jsx13(Search, {});
1167
+ case "detail":
1168
+ return /* @__PURE__ */ jsx13(Detail, { target: view.item });
1169
+ case "favourites":
1170
+ return /* @__PURE__ */ jsx13(Favourites, {});
1171
+ case "playlists":
1172
+ return /* @__PURE__ */ jsx13(Playlists, {});
1173
+ case "playlist":
1174
+ return /* @__PURE__ */ jsx13(Playlist, { playlist: view.playlist });
1175
+ case "nowPlaying":
1176
+ return /* @__PURE__ */ jsx13(NowPlaying, {});
1177
+ case "convert":
1178
+ return /* @__PURE__ */ jsx13(Convert, { track: view.track });
1179
+ }
1180
+ };
1181
+ openTargetUrl = async (client, view) => {
1182
+ if (view.kind === "detail") {
1183
+ const { item } = view;
1184
+ const url2 = item.type === "track" ? deepLinkFor(client, "track", String(item.track.id)) : item.type === "album" ? deepLinkFor(client, "album", item.album.id) : item.type === "artist" ? deepLinkFor(client, "artist", String(item.artist.id)) : deepLinkFor(client, "playlist", String(item.playlist.id));
1185
+ if (url2) await openUrl(url2);
1186
+ }
1187
+ };
1188
+ App = () => {
1189
+ const { exit } = useApp2();
1190
+ const [stack, setStack] = useState7([{ kind: "home" }]);
1191
+ const [connectState, setConnectState] = useState7({
1192
+ status: "pending"
1193
+ });
1194
+ const [inputFocused, setInputFocused] = useState7(false);
1195
+ useEffect7(() => {
1196
+ let active = true;
1197
+ connectTui().then((result) => {
1198
+ if (!active) return;
1199
+ if (result.ok) setConnectState({ status: "ready", client: result.client });
1200
+ else if (result.reason === "auth") setConnectState({ status: "auth" });
1201
+ else
1202
+ setConnectState({
1203
+ status: "error",
1204
+ message: result.message ?? "Failed to connect."
1205
+ });
1206
+ });
1207
+ return () => {
1208
+ active = false;
1209
+ };
1210
+ }, []);
1211
+ const nav = useMemo(
1212
+ () => ({
1213
+ push: (view) => setStack((views) => [...views, view]),
1214
+ pop: () => setStack((views) => views.length > 1 ? views.slice(0, -1) : views),
1215
+ replace: (view) => setStack((views) => [...views.slice(0, -1), view])
1216
+ }),
1217
+ []
1218
+ );
1219
+ const focus = useMemo(
1220
+ () => ({ inputFocused, setInputFocused }),
1221
+ [inputFocused]
1222
+ );
1223
+ const current = stack[stack.length - 1] ?? { kind: "home" };
1224
+ const atRoot = stack.length <= 1;
1225
+ useInput4((input, key) => {
1226
+ if (key.ctrl && input === "c") {
1227
+ exit();
1228
+ return;
1229
+ }
1230
+ if (key.escape) {
1231
+ if (atRoot) exit();
1232
+ else nav.pop();
1233
+ return;
1234
+ }
1235
+ if (inputFocused) return;
1236
+ if (input === "q") {
1237
+ exit();
1238
+ return;
1239
+ }
1240
+ if (key.backspace && !key.meta) {
1241
+ if (atRoot) exit();
1242
+ else nav.pop();
1243
+ return;
1244
+ }
1245
+ if (connectState.status !== "ready") return;
1246
+ if (input === "o") {
1247
+ void openTargetUrl(connectState.client, current);
1248
+ return;
1249
+ }
1250
+ if (input === "c" && current.kind === "detail" && current.item.type === "track")
1251
+ nav.push({ kind: "convert", track: current.item.track });
1252
+ if (mediaKeysAvailable) {
1253
+ if (input === " ") void sendMediaKey("play");
1254
+ if (input === "n") void sendMediaKey("next");
1255
+ if (input === "p") void sendMediaKey("previous");
1256
+ }
1257
+ });
1258
+ if (connectState.status === "pending") return /* @__PURE__ */ jsx13(Spinner, { label: "Connecting\u2026" });
1259
+ if (connectState.status === "auth") return /* @__PURE__ */ jsx13(NotLoggedIn, {});
1260
+ return /* @__PURE__ */ jsx13(InputFocusContext.Provider, { value: focus, children: /* @__PURE__ */ jsx13(Box13, { flexDirection: "column", padding: 1, children: connectState.status === "error" ? /* @__PURE__ */ jsx13(ClientContext.Provider, { value: null, children: /* @__PURE__ */ jsxs13(NavContext.Provider, { value: nav, children: [
1261
+ /* @__PURE__ */ jsx13(ErrorBanner, { message: connectState.message }),
1262
+ /* @__PURE__ */ jsx13(Box13, { marginTop: 1, children: /* @__PURE__ */ jsx13(Text14, { dimColor: true, children: "q quit" }) })
1263
+ ] }) }) : /* @__PURE__ */ jsx13(ClientContext.Provider, { value: connectState.client, children: /* @__PURE__ */ jsx13(NavContext.Provider, { value: nav, children: renderView(current) }) }) }) });
1264
+ };
1265
+ }
1266
+ });
1267
+
1268
+ // src/tui/index.ts
1269
+ var tui_exports = {};
1270
+ __export(tui_exports, {
1271
+ runTui: () => runTui
1272
+ });
1273
+ import { render } from "ink";
1274
+ import { createElement } from "react";
1275
+ var runTui;
1276
+ var init_tui = __esm({
1277
+ "src/tui/index.ts"() {
1278
+ "use strict";
1279
+ init_App();
1280
+ runTui = async () => {
1281
+ if (!process.stdin.isTTY) {
1282
+ console.error("The interactive TUI needs an interactive terminal.");
1283
+ return;
1284
+ }
1285
+ process.stdout.write("\x1B[?1049h");
1286
+ let restored = false;
1287
+ const restore = () => {
1288
+ if (restored) return;
1289
+ restored = true;
1290
+ process.stdout.write("\x1B[?1049l\x1B[?25h");
1291
+ };
1292
+ process.once("SIGINT", restore);
1293
+ process.once("SIGTERM", restore);
1294
+ process.once("exit", restore);
1295
+ const { waitUntilExit } = render(createElement(App), { exitOnCtrlC: false });
1296
+ try {
1297
+ await waitUntilExit();
1298
+ } finally {
1299
+ restore();
1300
+ }
1301
+ };
1302
+ }
1303
+ });
2
1304
 
3
1305
  // src/index.ts
4
1306
  import { defineCommand as defineCommand16, runMain } from "citty";
@@ -21,45 +1323,9 @@ var renderGenericUsage = async (command2) => {
21
1323
  };
22
1324
 
23
1325
  // src/commands/album.ts
1326
+ init_lib();
24
1327
  import { defineCommand } from "citty";
25
1328
 
26
- // src/lib.ts
27
- import {
28
- createKeychainStore,
29
- createQobuzClient
30
- } from "@kud/qobuz";
31
- var store = createKeychainStore();
32
- var connect = async () => {
33
- try {
34
- return await createQobuzClient({ store });
35
- } catch (error) {
36
- const qobuzError = error;
37
- if (qobuzError.kind === "auth") {
38
- console.error("Not connected \u2014 run `qobuz login` first.");
39
- } else {
40
- console.error(`Error: ${qobuzError.message ?? error}`);
41
- }
42
- process.exit(1);
43
- }
44
- };
45
- var formatDuration = (seconds) => {
46
- if (!seconds) return "";
47
- const minutes = Math.floor(seconds / 60);
48
- const remainder = String(seconds % 60).padStart(2, "0");
49
- return `${minutes}:${remainder}`;
50
- };
51
- var linkFor = (links, type, id) => {
52
- const builders = {
53
- album: (value) => links.album(value),
54
- track: (value) => links.track(Number(value)),
55
- playlist: (value) => links.playlist(Number(value)),
56
- artist: (value) => links.artist(Number(value))
57
- };
58
- return builders[type]?.(id);
59
- };
60
- var deepLinkFor = (client, type, id) => linkFor(client.deepLink, type, id);
61
- var appLinkFor = (client, type, id) => linkFor(client.appLink, type, id);
62
-
63
1329
  // src/ui.ts
64
1330
  var ESC2 = String.fromCharCode(27);
65
1331
  var colour = process.stdout.isTTY;
@@ -118,6 +1384,7 @@ ${bold2(`\u{1F4BF} ${album2.title}`)}`);
118
1384
  });
119
1385
 
120
1386
  // src/commands/artist.ts
1387
+ init_lib();
121
1388
  import { defineCommand as defineCommand2 } from "citty";
122
1389
  var artist = defineCommand2({
123
1390
  meta: { name: "artist", description: "Show artist details" },
@@ -136,109 +1403,9 @@ ${bold2(`\u{1F3A4} ${artist2.name}`)}`);
136
1403
  });
137
1404
 
138
1405
  // src/commands/convert.ts
1406
+ init_lib();
139
1407
  import { defineCommand as defineCommand3 } from "citty";
140
-
141
- // src/resolve.ts
142
- var CRAWLER_UA = "facebookexternalhit/1.1";
143
- var spotifySearchUrl = (query) => `https://open.spotify.com/search/${encodeURIComponent(query)}`;
144
- var ytMusicSearchUrl = (query) => `https://music.youtube.com/search?q=${encodeURIComponent(query)}`;
145
- var deezerByIsrc = async (isrc) => {
146
- const res = await fetch(`https://api.deezer.com/track/isrc:${isrc}`).catch(
147
- () => null
148
- );
149
- if (!res || !res.ok) return void 0;
150
- const track2 = await res.json();
151
- return track2.link;
152
- };
153
- var isQobuz = (host) => host.endsWith("qobuz.com");
154
- var isSpotify = (host) => host.endsWith("open.spotify.com");
155
- var isYouTube = (host) => host.endsWith("music.youtube.com") || host.endsWith("youtube.com") || host.endsWith("youtu.be");
156
- var metaContent = (html, property) => html.match(
157
- new RegExp(`<meta[^>]+property="${property}"[^>]+content="([^"]*)"`, "i")
158
- )?.[1];
159
- var resolveSpotify = async (url2) => {
160
- const res = await fetch(url2, { headers: { "User-Agent": CRAWLER_UA } });
161
- if (!res.ok) return null;
162
- const html = await res.text();
163
- const title = metaContent(html, "og:title");
164
- const artist2 = metaContent(html, "og:description")?.split(" \xB7 ")[0];
165
- if (title && artist2)
166
- return { title: decodeEntities(title), artist: decodeEntities(artist2) };
167
- const match = html.match(/<title>(.*?)<\/title>/i)?.[1]?.match(/^(.+?) - song(?: and lyrics)? by (.+?) \| Spotify/i);
168
- if (!match?.[1] || !match[2]) return null;
169
- return { title: decodeEntities(match[1]), artist: decodeEntities(match[2]) };
170
- };
171
- var resolveYouTube = async (url2) => {
172
- const endpoint = `https://www.youtube.com/oembed?url=${encodeURIComponent(url2)}&format=json`;
173
- const res = await fetch(endpoint);
174
- if (!res.ok) return null;
175
- const data = await res.json();
176
- if (!data.title || !data.author_name) return null;
177
- return {
178
- title: data.title,
179
- artist: data.author_name.replace(/ - Topic$/, "")
180
- };
181
- };
182
- var resolveLink = async (input) => {
183
- let url2;
184
- try {
185
- url2 = new URL(input);
186
- } catch {
187
- return { ok: false, reason: "invalid" };
188
- }
189
- const host = url2.hostname;
190
- const ok = (track2) => track2 ? { ok: true, direction: "to-qobuz", track: track2 } : { ok: false, reason: "unknown" };
191
- if (isQobuz(host)) {
192
- const match = url2.pathname.match(/\/track\/(\d+)/);
193
- return match ? { ok: true, direction: "from-qobuz", qobuzTrackId: Number(match[1]) } : { ok: false, reason: "unsupported-type" };
194
- }
195
- if (isSpotify(host))
196
- return url2.pathname.includes("/track/") ? ok(await resolveSpotify(input)) : { ok: false, reason: "unsupported-type" };
197
- if (isYouTube(host))
198
- return url2.pathname === "/watch" || host.endsWith("youtu.be") ? ok(await resolveYouTube(input)) : { ok: false, reason: "unsupported-type" };
199
- return { ok: false, reason: "unknown" };
200
- };
201
- var deezerSearch = async (query) => {
202
- const res = await fetch(
203
- `https://api.deezer.com/search?q=${encodeURIComponent(query)}&limit=1`
204
- );
205
- if (!res.ok) return void 0;
206
- const data = await res.json();
207
- return data.data?.[0]?.id;
208
- };
209
- var findIsrc = async ({
210
- title,
211
- artist: artist2
212
- }) => {
213
- const id = await deezerSearch(`artist:"${artist2}" track:"${title}"`) ?? await deezerSearch(`${artist2} ${title}`);
214
- if (id === void 0) return void 0;
215
- const res = await fetch(`https://api.deezer.com/track/${id}`);
216
- if (!res.ok) return void 0;
217
- const track2 = await res.json();
218
- return track2.isrc;
219
- };
220
- var normalize = (text) => text.toLowerCase().normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").replace(/\([^)]*\)|\[[^\]]*\]/g, " ").replace(/\b(feat|ft|with)\b\.?/g, " ").replace(/[^a-z0-9]+/g, " ").trim();
221
- var tokenSet = (text) => new Set(normalize(text).split(" ").filter(Boolean));
222
- var overlap = (a, b) => {
223
- if (a.size === 0 || b.size === 0) return 0;
224
- let hits = 0;
225
- for (const token of a) if (b.has(token)) hits += 1;
226
- return hits / Math.min(a.size, b.size);
227
- };
228
- var isLikelyMatch = (resolved, candidate) => {
229
- const titleScore = overlap(
230
- tokenSet(resolved.title),
231
- tokenSet(candidate.title)
232
- );
233
- const artistScore = overlap(
234
- tokenSet(resolved.artist),
235
- tokenSet(candidate.artist?.name ?? "")
236
- );
237
- return titleScore >= 0.6 && artistScore > 0;
238
- };
239
- var decodeEntities = (text) => text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'");
240
-
241
- // src/commands/convert.ts
1408
+ init_resolve();
242
1409
  var FAILURE = {
243
1410
  invalid: "Not a URL. Pass a Spotify, YouTube Music, or Qobuz track link.",
244
1411
  qobuz: "Unsupported Qobuz link \u2014 pass a track link.",
@@ -300,6 +1467,7 @@ No Qobuz match found.`);
300
1467
  });
301
1468
 
302
1469
  // src/commands/fav.ts
1470
+ init_lib();
303
1471
  import { defineCommand as defineCommand4 } from "citty";
304
1472
  var list = defineCommand4({
305
1473
  meta: { name: "list", description: "List favourites" },
@@ -399,67 +1567,9 @@ var fav = defineCommand4({
399
1567
  import { defineCommand as defineCommand5 } from "citty";
400
1568
 
401
1569
  // src/connect.ts
1570
+ init_lib();
1571
+ init_prompts();
402
1572
  import { fetchAppId, validateCredentials } from "@kud/qobuz";
403
-
404
- // src/prompts.ts
405
- import readline from "readline";
406
- import { execFile } from "child_process";
407
- import { promisify } from "util";
408
- var exec = promisify(execFile);
409
- var createPrompts = () => {
410
- const rl = readline.createInterface({
411
- input: process.stdin,
412
- output: process.stdout
413
- });
414
- const ask = (question) => new Promise(
415
- (resolve) => rl.question(question, (answer) => resolve(answer.trim()))
416
- );
417
- const askHidden = (question) => new Promise((resolve) => {
418
- let muted2 = false;
419
- rl._writeToOutput = (chunk) => {
420
- if (!muted2) process.stdout.write(chunk);
421
- };
422
- rl.question(question, (answer) => {
423
- rl._writeToOutput = (chunk) => process.stdout.write(chunk);
424
- process.stdout.write("\n");
425
- resolve(answer);
426
- });
427
- muted2 = true;
428
- });
429
- return { ask, askHidden, close: () => rl.close() };
430
- };
431
- var openUrl = async (url2) => {
432
- try {
433
- await exec("open", [url2]);
434
- return true;
435
- } catch {
436
- return false;
437
- }
438
- };
439
- var copyToClipboard = async (text) => {
440
- try {
441
- const running = exec("pbcopy");
442
- running.child.stdin?.end(text);
443
- await running;
444
- return true;
445
- } catch {
446
- return false;
447
- }
448
- };
449
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
450
- var countdownAndOpen = async (url2, seconds = 3) => {
451
- for (const n2 of Array.from({ length: seconds }, (_, i) => seconds - i)) {
452
- process.stdout.write(`\r Opening ${url2} in ${n2}\u2026 `);
453
- await sleep(1e3);
454
- }
455
- process.stdout.write(`\r Opening ${url2} now.${" ".repeat(20)}
456
-
457
- `);
458
- if (!await openUrl(url2))
459
- console.log(` (couldn't open a browser \u2014 visit ${url2} manually)`);
460
- };
461
-
462
- // src/connect.ts
463
1573
  var runConnect = async () => {
464
1574
  console.log("Connect your Qobuz account.");
465
1575
  console.log(
@@ -503,6 +1613,7 @@ var login = defineCommand5({
503
1613
  });
504
1614
 
505
1615
  // src/commands/logout.ts
1616
+ init_lib();
506
1617
  import { defineCommand as defineCommand6 } from "citty";
507
1618
  var logout = defineCommand6({
508
1619
  meta: {
@@ -516,6 +1627,7 @@ var logout = defineCommand6({
516
1627
  });
517
1628
 
518
1629
  // src/commands/now-playing.ts
1630
+ init_lib();
519
1631
  import { defineCommand as defineCommand7 } from "citty";
520
1632
  var nowPlaying = defineCommand7({
521
1633
  meta: {
@@ -540,6 +1652,8 @@ ${bold2(`\u{1F3B5} ${track2.title}`)}`);
540
1652
  });
541
1653
 
542
1654
  // src/commands/open.ts
1655
+ init_lib();
1656
+ init_prompts();
543
1657
  import { defineCommand as defineCommand8 } from "citty";
544
1658
  var open = defineCommand8({
545
1659
  meta: {
@@ -572,8 +1686,8 @@ var playbackCommand = (name, description, key) => defineCommand9({
572
1686
  meta: { name, description },
573
1687
  run: async () => {
574
1688
  try {
575
- const { sendMediaKey } = await import("@kud/macos-media-keys");
576
- await sendMediaKey(key);
1689
+ const { sendMediaKey: sendMediaKey2 } = await import("@kud/macos-media-keys");
1690
+ await sendMediaKey2(key);
577
1691
  } catch (error) {
578
1692
  console.error(error.message ?? `playback (${key}) failed`);
579
1693
  process.exit(1);
@@ -603,6 +1717,7 @@ var rewind = playbackCommand(
603
1717
  );
604
1718
 
605
1719
  // src/commands/playlist.ts
1720
+ init_lib();
606
1721
  import { defineCommand as defineCommand10 } from "citty";
607
1722
  var list2 = defineCommand10({
608
1723
  meta: { name: "list", description: "List your playlists" },
@@ -709,6 +1824,7 @@ var playlist = defineCommand10({
709
1824
  });
710
1825
 
711
1826
  // src/commands/search.ts
1827
+ init_lib();
712
1828
  import { defineCommand as defineCommand11 } from "citty";
713
1829
  var search = defineCommand11({
714
1830
  meta: {
@@ -769,6 +1885,7 @@ var search = defineCommand11({
769
1885
  });
770
1886
 
771
1887
  // src/commands/similar.ts
1888
+ init_lib();
772
1889
  import { defineCommand as defineCommand12 } from "citty";
773
1890
  var similar = defineCommand12({
774
1891
  meta: {
@@ -862,6 +1979,7 @@ var stats = defineCommand13({
862
1979
  });
863
1980
 
864
1981
  // src/commands/track.ts
1982
+ init_lib();
865
1983
  import { defineCommand as defineCommand14 } from "citty";
866
1984
  var track = defineCommand14({
867
1985
  meta: { name: "track", description: "Show track details" },
@@ -886,6 +2004,8 @@ ${bold2(`\u{1F3B5} ${track2.title}`)}`);
886
2004
  });
887
2005
 
888
2006
  // src/commands/url.ts
2007
+ init_lib();
2008
+ init_prompts();
889
2009
  import { defineCommand as defineCommand15 } from "citty";
890
2010
  import { readNowPlayingTrackId } from "@kud/qobuz";
891
2011
  var currentTrackLink = async (client) => {
@@ -945,12 +2065,23 @@ var url = defineCommand15({
945
2065
  });
946
2066
 
947
2067
  // src/index.ts
2068
+ var tui = defineCommand16({
2069
+ meta: {
2070
+ name: "tui",
2071
+ description: "Browse Qobuz in an interactive terminal UI"
2072
+ },
2073
+ run: async () => {
2074
+ const { runTui: runTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
2075
+ await runTui2();
2076
+ }
2077
+ });
948
2078
  var main = defineCommand16({
949
2079
  meta: {
950
2080
  name: "qobuz",
951
2081
  description: "Qobuz from the command line \u2014 search, library, and quick-open in the app"
952
2082
  },
953
2083
  subCommands: {
2084
+ tui,
954
2085
  login,
955
2086
  logout,
956
2087
  search,
@@ -982,9 +2113,13 @@ var aliases = {
982
2113
  var args = process.argv.slice(2);
983
2114
  var [command, ...rest] = args;
984
2115
  var rawArgs = command && aliases[command] ? [aliases[command], ...rest] : args;
985
- var isTopLevelHelp = rawArgs.length === 0 || rawArgs[0] === "--help" || rawArgs[0] === "-h";
986
- if (isTopLevelHelp) {
2116
+ var isHelp = rawArgs[0] === "--help" || rawArgs[0] === "-h";
2117
+ var isTui = rawArgs.length === 0 || rawArgs[0] === "tui";
2118
+ if (isHelp) {
987
2119
  console.log(await renderGenericUsage(main));
2120
+ } else if (isTui) {
2121
+ const { runTui: runTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
2122
+ await runTui2();
988
2123
  } else {
989
2124
  runMain(main, { rawArgs });
990
2125
  }