amicookedyet 0.0.1 → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1462 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { readFileSync as readFileSync2 } from "node:fs";
5
+
6
+ // ../config/src/index.ts
7
+ var PRODUCT = {
8
+ name: "amicookedyet",
9
+ displayName: "Am I Cooked Yet?",
10
+ domain: "amicookedyet.com",
11
+ // Under the user's home directory.
12
+ configDir: ".amicookedyet",
13
+ configFile: "config.json",
14
+ soundsDir: "sounds",
15
+ // Inside soundsDir: library sounds a paid license downloaded. Deleted when it ends.
16
+ libraryDir: "library"
17
+ };
18
+ var BUILT_IN_SOUNDS = [
19
+ "sad-trombone",
20
+ "chime",
21
+ "alarm",
22
+ "boing",
23
+ "break-chime",
24
+ // Meme sounds, from myinstants.com.
25
+ "faaah",
26
+ "among-us-reveal",
27
+ "shocked",
28
+ "dexter",
29
+ "camera-shutter",
30
+ "end-credits",
31
+ "out-of-your-mind",
32
+ "funny-laugh",
33
+ "spiderman-song",
34
+ "chicken-scream",
35
+ "explosion",
36
+ "punch",
37
+ "cat-laugh",
38
+ "bark-fart",
39
+ "metal-gear-alert",
40
+ "baby-laugh",
41
+ "huh",
42
+ "du-bist-gut-genug",
43
+ "huh-cat",
44
+ "sad-violin",
45
+ "oh-my-god",
46
+ "ayyy-scream",
47
+ "e-lutador",
48
+ "duck-toy",
49
+ "aayein",
50
+ "gunshot",
51
+ "fortnite-death",
52
+ "social-credit-siren",
53
+ "brain-fart",
54
+ "galaxy",
55
+ "nuagghhhh",
56
+ "bruh",
57
+ "awkward",
58
+ "snapchat",
59
+ "run",
60
+ "vine-boom",
61
+ "damn",
62
+ "faaaaaa",
63
+ "yoooo"
64
+ ];
65
+ var PRESET_SOUND = "among-us-reveal";
66
+ var LIMIT_WINDOWS = ["five_hour", "seven_day"];
67
+ var ALARM_STEPS_USED = [
68
+ 1,
69
+ ...Array.from({ length: 18 }, (_, i) => (i + 1) * 5),
70
+ ...Array.from({ length: 10 }, (_, i) => 91 + i)
71
+ ];
72
+ var ALARM_STEPS_LEFT = ALARM_STEPS_USED.map((used) => 100 - used);
73
+ function snapPercentLeft(percentLeft) {
74
+ const value = Number.isFinite(percentLeft) ? percentLeft : 20;
75
+ return ALARM_STEPS_LEFT.reduce((best, step) => {
76
+ const gap = Math.abs(step - value) - Math.abs(best - value);
77
+ return gap < 0 || gap === 0 && step < best ? step : best;
78
+ });
79
+ }
80
+ var PLAN_LIMITS = {
81
+ // Free: the usage line, the jokes, and one 5-hour alarm at 10% left with the preset sound.
82
+ free: {
83
+ alarms: { five_hour: 1, seven_day: 0 },
84
+ fixedPercentLeft: 10,
85
+ fixedSound: PRESET_SOUND,
86
+ customSounds: false,
87
+ librarySounds: false,
88
+ phonePush: false,
89
+ breakReminders: false
90
+ },
91
+ // Paid: one alarm per step on each limit, the sound library, your own sounds,
92
+ // break reminders and phone alerts.
93
+ paid: {
94
+ alarms: { five_hour: ALARM_STEPS_LEFT.length, seven_day: ALARM_STEPS_LEFT.length },
95
+ customSounds: true,
96
+ librarySounds: true,
97
+ phonePush: true,
98
+ breakReminders: true
99
+ }
100
+ };
101
+ var DEFAULT_CONFIG = {
102
+ version: 1,
103
+ alarms: [{ id: "default", percentLeft: 20, window: "five_hour", sound: PRESET_SOUND, notify: true }],
104
+ line: { spinner: "always" },
105
+ customSounds: [],
106
+ alarmsOn: { five_hour: true, seven_day: true },
107
+ breaks: { enabled: true, minutes: 45, sound: "break-chime" }
108
+ };
109
+ function applyPlanLimits(config, tier) {
110
+ const limits = PLAN_LIMITS[tier];
111
+ const split = config.alarms.flatMap(
112
+ (alarm) => alarm.window === "any" ? [
113
+ { ...alarm, window: "five_hour" },
114
+ { ...alarm, id: `${alarm.id.slice(0, 32)}-weekly`, window: "seven_day" }
115
+ ] : [alarm]
116
+ );
117
+ const count = { five_hour: 0, seven_day: 0 };
118
+ const taken = /* @__PURE__ */ new Set();
119
+ const alarms = [];
120
+ for (const alarm of split) {
121
+ const window = alarm.window;
122
+ const percentLeft = limits.fixedPercentLeft ?? snapPercentLeft(alarm.percentLeft);
123
+ const step = `${window}:${percentLeft}`;
124
+ if (count[window] >= limits.alarms[window] || taken.has(step)) continue;
125
+ count[window]++;
126
+ taken.add(step);
127
+ const sound = limits.fixedSound ?? (!limits.customSounds && alarm.sound.startsWith("custom:") ? PRESET_SOUND : alarm.sound);
128
+ alarms.push({ ...alarm, window, percentLeft, sound });
129
+ }
130
+ if (limits.fixedPercentLeft !== void 0 && count.five_hour === 0) {
131
+ alarms.unshift({ id: "free", percentLeft: limits.fixedPercentLeft, window: "five_hour", sound: limits.fixedSound ?? PRESET_SOUND, notify: true });
132
+ }
133
+ const alarmsOn = { five_hour: config.alarmsOn?.five_hour !== false, seven_day: config.alarmsOn?.seven_day !== false };
134
+ const { phone, ...rest } = config;
135
+ return { ...rest, alarms, alarmsOn, customSounds: limits.customSounds ? config.customSounds : [], ...limits.phonePush && phone ? { phone } : {} };
136
+ }
137
+ var MAX_OWN_SOUNDS = 20;
138
+ var MAX_SOUND_BYTES = 1024 * 1024;
139
+ var isOwnSoundId = (value) => typeof value === "string" && /^[a-f0-9]{16}$/.test(value);
140
+ function dropPaidSettings(config) {
141
+ const { phone: _, sync: __, ...rest } = applyPlanLimits(config, "free");
142
+ return { ...rest, breaks: { ...DEFAULT_CONFIG.breaks } };
143
+ }
144
+ function ownSounds(raw) {
145
+ if (!Array.isArray(raw)) return [];
146
+ const sounds = [];
147
+ for (const item of raw) {
148
+ if (!isObject(item) || !isOwnSoundId(item.id) || sounds.some((sound) => sound.id === item.id)) continue;
149
+ const name = typeof item.name === "string" ? item.name.trim().slice(0, 60) : "";
150
+ sounds.push({ id: item.id, name: name || "My sound" });
151
+ }
152
+ return sounds.slice(0, MAX_OWN_SOUNDS);
153
+ }
154
+ var SYNCED_SETTINGS_MAX_BYTES = 16 * 1024;
155
+ var SPINNER_MODES = ["always", "low", "off"];
156
+ var ALARM_WINDOWS = ["any", ...LIMIT_WINDOWS];
157
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
158
+ var isBuiltInSound = (value) => BUILT_IN_SOUNDS.includes(value);
159
+ var isClock = (value) => typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value);
160
+ var MAX_BREAK_HOURS = 8;
161
+ var minutesOf = (clock) => Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3));
162
+ var endOf = (clock) => clock === "00:00" ? 24 * 60 : minutesOf(clock);
163
+ function breakHoursProblem(hours) {
164
+ if (hours.length > MAX_BREAK_HOURS) return `Up to ${MAX_BREAK_HOURS} time blocks.`;
165
+ for (const block of hours) {
166
+ if (!isClock(block.from) || !isClock(block.to)) return "Each time block needs a start and an end.";
167
+ if (endOf(block.to) <= minutesOf(block.from)) return `${block.from} to ${block.to}: the end must come after the start.`;
168
+ }
169
+ const sorted = [...hours].sort((a, b) => minutesOf(a.from) - minutesOf(b.from));
170
+ for (let i = 1; i < sorted.length; i++) {
171
+ const [before, block] = [sorted[i - 1], sorted[i]];
172
+ if (minutesOf(block.from) < endOf(before.to)) return `${before.from}-${before.to} and ${block.from}-${block.to} overlap.`;
173
+ }
174
+ return void 0;
175
+ }
176
+ function breakHoursOf(breaks) {
177
+ const raw = Array.isArray(breaks.hours) ? breaks.hours : isObject(breaks.quietHours) ? hoursAround(breaks.quietHours) : [];
178
+ const hours = [];
179
+ for (const item of raw.slice(0, MAX_BREAK_HOURS)) {
180
+ if (!isObject(item) || !isClock(item.from) || !isClock(item.to)) continue;
181
+ const block = { from: item.from, to: item.to };
182
+ if (!breakHoursProblem([...hours, block])) hours.push(block);
183
+ }
184
+ return hours.length ? hours.sort((a, b) => minutesOf(a.from) - minutesOf(b.from)) : void 0;
185
+ }
186
+ function hoursAround(quiet) {
187
+ const { from, to } = quiet;
188
+ if (!isClock(from) || !isClock(to) || from === to) return [];
189
+ if (minutesOf(from) > minutesOf(to)) return [{ from: to, to: from }];
190
+ return [
191
+ { from: "00:00", to: from },
192
+ { from: to, to: "00:00" }
193
+ ].filter((block) => block.from !== block.to);
194
+ }
195
+ function syncedAlarm(raw) {
196
+ if (!isObject(raw) || typeof raw.id !== "string" || !/^[\w-]{1,64}$/.test(raw.id)) return void 0;
197
+ if (typeof raw.percentLeft !== "number" || !Number.isFinite(raw.percentLeft)) return void 0;
198
+ if (!ALARM_WINDOWS.includes(raw.window)) return void 0;
199
+ const sound = raw.sound;
200
+ const isSound = sound === "none" || isBuiltInSound(sound) || typeof sound === "string" && /^custom:[\w-]{1,64}$/.test(sound);
201
+ if (!isSound) return void 0;
202
+ return { id: raw.id, percentLeft: raw.percentLeft, window: raw.window, sound, notify: raw.notify !== false };
203
+ }
204
+ function parseSyncedSettings(raw) {
205
+ if (!isObject(raw) || !Array.isArray(raw.alarms)) return void 0;
206
+ if (new TextEncoder().encode(JSON.stringify(raw)).length > SYNCED_SETTINGS_MAX_BYTES) return void 0;
207
+ const alarms = raw.alarms.map(syncedAlarm);
208
+ if (alarms.some((alarm) => alarm === void 0)) return void 0;
209
+ const on = isObject(raw.alarmsOn) ? raw.alarmsOn : {};
210
+ const line = isObject(raw.line) ? raw.line : {};
211
+ const breaks = isObject(raw.breaks) ? raw.breaks : {};
212
+ const hours = breakHoursOf(breaks);
213
+ const minutes = typeof breaks.minutes === "number" && Number.isFinite(breaks.minutes) ? breaks.minutes : DEFAULT_CONFIG.breaks.minutes;
214
+ const limited = applyPlanLimits(
215
+ {
216
+ ...DEFAULT_CONFIG,
217
+ alarms,
218
+ alarmsOn: { five_hour: on.five_hour !== false, seven_day: on.seven_day !== false },
219
+ line: { spinner: SPINNER_MODES.includes(line.spinner) ? line.spinner : "always" },
220
+ breaks: {
221
+ enabled: breaks.enabled !== false,
222
+ minutes: Math.min(120, Math.max(15, Math.round(minutes))),
223
+ sound: breaks.sound === "none" || isBuiltInSound(breaks.sound) ? breaks.sound : DEFAULT_CONFIG.breaks.sound,
224
+ ...hours ? { hours } : {}
225
+ }
226
+ },
227
+ "paid"
228
+ );
229
+ const phone = isObject(raw.phone) && raw.phone.enabled === true;
230
+ return { alarms: limited.alarms, alarmsOn: limited.alarmsOn, line: limited.line, breaks: limited.breaks, phone: { enabled: phone }, sounds: ownSounds(raw.sounds) };
231
+ }
232
+ function syncedOf(config) {
233
+ const alarms = config.alarms.filter((alarm) => syncedAlarm(alarm) !== void 0);
234
+ const sounds = config.customSounds.map(({ id, name }) => ({ id, name }));
235
+ const synced = parseSyncedSettings({ ...config, alarms, sounds, phone: config.phone ?? { enabled: false } });
236
+ return synced ?? parseSyncedSettings(DEFAULT_CONFIG);
237
+ }
238
+ var ownSoundFile = (id) => `${id}.wav`;
239
+ function withSyncedSettings(config, synced, rev) {
240
+ const { sounds, ...rest } = synced;
241
+ const customSounds = sounds.map((sound) => ({ ...sound, file: ownSoundFile(sound.id) }));
242
+ return { ...config, ...rest, customSounds, sync: { rev } };
243
+ }
244
+ function parseSync(raw) {
245
+ if (!isObject(raw) || typeof raw.rev !== "number" || !Number.isInteger(raw.rev) || raw.rev < 0) return void 0;
246
+ return raw.pending === true ? { rev: raw.rev, pending: true } : { rev: raw.rev };
247
+ }
248
+ var settingsRevOf = (config) => config.sync?.rev ?? 0;
249
+ function readSettingsAnswer(body) {
250
+ if (!isObject(body) || typeof body.settingsRev !== "number" || !Number.isInteger(body.settingsRev)) return void 0;
251
+ const settings = body.settings === void 0 ? void 0 : parseSyncedSettings(body.settings);
252
+ return { rev: body.settingsRev, ...settings ? { settings } : {} };
253
+ }
254
+ function nextSyncStep(config, answer) {
255
+ if (!answer) return void 0;
256
+ if (config.sync?.pending) return { upload: syncedOf(config), baseRev: config.sync.rev };
257
+ if (answer.rev === 0) return { upload: syncedOf(config), baseRev: 0 };
258
+ if (answer.settings && answer.rev > settingsRevOf(config)) return { apply: answer.settings, rev: answer.rev };
259
+ return void 0;
260
+ }
261
+ function afterUpload(config, status, body) {
262
+ const answer = isObject(body) ? body : {};
263
+ const settings = status === 200 || status === 409 ? parseSyncedSettings(answer.settings) : void 0;
264
+ if (status === 200 && typeof answer.rev === "number" && !settings) return { ...config, sync: { rev: answer.rev } };
265
+ if (settings && typeof answer.rev === "number") return withSyncedSettings(config, settings, answer.rev);
266
+ return { ...config, sync: { rev: config.sync?.rev ?? 0, pending: true } };
267
+ }
268
+
269
+ // src/config-command.ts
270
+ import { existsSync as existsSync5, readFileSync } from "node:fs";
271
+ import { fileURLToPath } from "node:url";
272
+
273
+ // src/browser.ts
274
+ import { spawn } from "node:child_process";
275
+ function openBrowser(url) {
276
+ const [command, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
277
+ spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
278
+ }).unref();
279
+ }
280
+
281
+ // src/config-store.ts
282
+ import { randomBytes } from "node:crypto";
283
+ import { existsSync } from "node:fs";
284
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
285
+ import { dirname } from "node:path";
286
+
287
+ // src/paths.ts
288
+ import { homedir } from "node:os";
289
+ import { join, resolve, sep } from "node:path";
290
+ function getPaths(home = homedir()) {
291
+ const dir = join(home, PRODUCT.configDir);
292
+ const sounds = join(dir, PRODUCT.soundsDir);
293
+ return { dir, config: join(dir, PRODUCT.configFile), sounds, library: join(sounds, PRODUCT.libraryDir) };
294
+ }
295
+ var SOUND_FILE = /^[a-f0-9]{16}\.wav$/;
296
+ function isSoundFileName(name) {
297
+ return typeof name === "string" && SOUND_FILE.test(name);
298
+ }
299
+ function soundFilePath(soundsDir, name) {
300
+ if (!isSoundFileName(name)) return void 0;
301
+ const base = resolve(soundsDir);
302
+ const full = resolve(base, name);
303
+ return full.startsWith(base + sep) ? full : void 0;
304
+ }
305
+
306
+ // src/config-store.ts
307
+ var WINDOWS = ["any", "five_hour", "seven_day"];
308
+ var SPINNER = ["always", "low", "off"];
309
+ var ID = /^[a-z0-9-]{1,40}$/;
310
+ var BREAK_MINUTES = { min: 15, max: 120 };
311
+ var MAX_ALARMS = Math.max(...Object.values(PLAN_LIMITS).map((limits) => limits.alarms.five_hour + limits.alarms.seven_day));
312
+ var MAX_CUSTOM_SOUNDS = 20;
313
+ function isObject2(value) {
314
+ return typeof value === "object" && value !== null && !Array.isArray(value);
315
+ }
316
+ function cleanName(value) {
317
+ const name = typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, "").trim() : "";
318
+ return name.slice(0, 60) || "My sound";
319
+ }
320
+ function cleanCustomSounds(value) {
321
+ if (!Array.isArray(value)) return [];
322
+ const seen = /* @__PURE__ */ new Set();
323
+ const sounds = [];
324
+ for (const item of value) {
325
+ if (!isObject2(item) || typeof item.id !== "string" || !ID.test(item.id) || seen.has(item.id)) continue;
326
+ if (!isSoundFileName(item.file)) continue;
327
+ seen.add(item.id);
328
+ sounds.push({ id: item.id, name: cleanName(item.name), file: item.file });
329
+ }
330
+ return sounds.slice(0, MAX_CUSTOM_SOUNDS);
331
+ }
332
+ function cleanAlarm(value, index) {
333
+ if (!isObject2(value)) return void 0;
334
+ const fallback = DEFAULT_CONFIG.alarms[0];
335
+ const percent = Number(value.percentLeft);
336
+ const sound = typeof value.sound === "string" ? value.sound : fallback.sound;
337
+ const validSound = sound === "none" || BUILT_IN_SOUNDS.includes(sound) || // An own sound from another computer, through the license's settings: it
338
+ // plays the preset here, and stays theirs (docs/SETTINGS-SYNC-PLAN.md).
339
+ sound.startsWith("custom:") && ID.test(sound.slice("custom:".length));
340
+ return {
341
+ id: typeof value.id === "string" && ID.test(value.id) ? value.id : `alarm-${index + 1}`,
342
+ percentLeft: Number.isFinite(percent) ? snapPercentLeft(percent) : fallback.percentLeft,
343
+ window: WINDOWS.includes(value.window) ? value.window : "any",
344
+ sound: validSound ? sound : fallback.sound,
345
+ notify: typeof value.notify === "boolean" ? value.notify : true
346
+ };
347
+ }
348
+ function cleanBreaks(value) {
349
+ const raw = isObject2(value) ? value : {};
350
+ const fallback = DEFAULT_CONFIG.breaks;
351
+ const minutes = Number(raw.minutes);
352
+ const sound = raw.sound === "none" || BUILT_IN_SOUNDS.includes(raw.sound) ? raw.sound : fallback.sound;
353
+ const breaks = {
354
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
355
+ minutes: Number.isFinite(minutes) ? Math.min(BREAK_MINUTES.max, Math.max(BREAK_MINUTES.min, Math.round(minutes))) : fallback.minutes,
356
+ sound
357
+ };
358
+ const hours = breakHoursOf(raw);
359
+ if (hours) breaks.hours = hours;
360
+ return breaks;
361
+ }
362
+ function sanitizeConfig(input) {
363
+ const raw = isObject2(input) ? input : {};
364
+ const customSounds = cleanCustomSounds(raw.customSounds);
365
+ const alarms = [];
366
+ const ids = /* @__PURE__ */ new Set();
367
+ for (const [index, item] of (Array.isArray(raw.alarms) ? raw.alarms : []).slice(0, MAX_ALARMS).entries()) {
368
+ const alarm = cleanAlarm(item, index);
369
+ if (!alarm) continue;
370
+ while (ids.has(alarm.id)) alarm.id = `${alarm.id.slice(0, 32)}-${randomBytes(2).toString("hex")}`;
371
+ ids.add(alarm.id);
372
+ alarms.push(alarm);
373
+ }
374
+ const line = isObject2(raw.line) ? raw.line : {};
375
+ const on = isObject2(raw.alarmsOn) ? raw.alarmsOn : {};
376
+ return {
377
+ version: 1,
378
+ alarms,
379
+ alarmsOn: { five_hour: on.five_hour !== false, seven_day: on.seven_day !== false },
380
+ line: {
381
+ spinner: SPINNER.includes(line.spinner) ? line.spinner : DEFAULT_CONFIG.line.spinner
382
+ },
383
+ customSounds,
384
+ breaks: cleanBreaks(raw.breaks),
385
+ ...isObject2(raw.phone) && raw.phone.enabled === true ? { phone: { enabled: true } } : {}
386
+ };
387
+ }
388
+ function cleanLicense(value) {
389
+ if (!isObject2(value) || typeof value.token !== "string" || value.token.length >= 4096) return void 0;
390
+ const license = { token: value.token };
391
+ if (typeof value.deviceId === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(value.deviceId)) license.deviceId = value.deviceId;
392
+ if (typeof value.refreshSecret === "string" && value.refreshSecret.length <= 512) license.refreshSecret = value.refreshSecret;
393
+ return license;
394
+ }
395
+ async function readConfig(paths) {
396
+ let text;
397
+ try {
398
+ text = await readFile(paths.config, "utf8");
399
+ } catch (error) {
400
+ if (error.code === "ENOENT") return { config: structuredClone(DEFAULT_CONFIG), exists: false };
401
+ throw error;
402
+ }
403
+ try {
404
+ const parsed = JSON.parse(text);
405
+ const config = sanitizeConfig(parsed);
406
+ const license = isObject2(parsed) ? cleanLicense(parsed.license) : void 0;
407
+ const sync = isObject2(parsed) ? parseSync(parsed.sync) : void 0;
408
+ return { config: { ...config, ...license ? { license } : {}, ...sync ? { sync } : {} }, exists: true };
409
+ } catch {
410
+ return { config: structuredClone(DEFAULT_CONFIG), exists: true, error: `${paths.config} is not valid JSON` };
411
+ }
412
+ }
413
+ async function writeConfig(paths, config) {
414
+ await mkdir(dirname(paths.config), { recursive: true, mode: 448 });
415
+ const temp = `${paths.config}.${randomBytes(6).toString("hex")}.tmp`;
416
+ await writeFile(temp, `${JSON.stringify(config, null, 2)}
417
+ `, { encoding: "utf8", mode: 384 });
418
+ try {
419
+ for (let attempt = 0; ; attempt++) {
420
+ try {
421
+ await rename(temp, paths.config);
422
+ return;
423
+ } catch (error) {
424
+ const code = error.code;
425
+ if (attempt >= 5 || code !== "EPERM" && code !== "EBUSY" && code !== "EACCES") throw error;
426
+ await new Promise((done) => setTimeout(done, 50 * (attempt + 1)));
427
+ }
428
+ }
429
+ } catch (error) {
430
+ await rm(temp, { force: true });
431
+ throw error;
432
+ }
433
+ }
434
+ async function ensureConfig(paths) {
435
+ if (existsSync(paths.config)) return false;
436
+ await writeConfig(paths, structuredClone(DEFAULT_CONFIG));
437
+ return true;
438
+ }
439
+
440
+ // src/account.ts
441
+ import { randomBytes as randomBytes2 } from "node:crypto";
442
+ import { hostname } from "node:os";
443
+ var ENV_PREFIX = PRODUCT.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
444
+ var API_ENV = `${ENV_PREFIX}_API`;
445
+ var WEB_ENV = `${ENV_PREFIX}_WEB`;
446
+ var PRICING_URL = `https://${PRODUCT.domain}/#pricing`;
447
+ function webOrigin(env = process.env) {
448
+ return (env[WEB_ENV] || `https://${PRODUCT.domain}`).replace(/\/+$/, "");
449
+ }
450
+ function accountLinks(env = process.env) {
451
+ const web = webOrigin(env);
452
+ return { buy: `${web}/#pricing`, manage: `${web}/manage/` };
453
+ }
454
+ function defaultApi(env = process.env) {
455
+ return { origin: (env[API_ENV] || `https://api.${PRODUCT.domain}`).replace(/\/+$/, ""), fetch: globalThis.fetch };
456
+ }
457
+ async function post(api, path, body, timeoutMs = 15e3) {
458
+ const res = await api.fetch(`${api.origin}${path}`, {
459
+ method: "POST",
460
+ headers: { "content-type": "application/json", accept: "application/json" },
461
+ body: JSON.stringify(body),
462
+ signal: AbortSignal.timeout(timeoutMs)
463
+ });
464
+ const data = await res.json().catch(() => ({}));
465
+ return { status: res.status, body: typeof data === "object" && data !== null ? data : {} };
466
+ }
467
+ var LAPSE_REASONS = {
468
+ refunded: "Your payment was refunded.",
469
+ disputed: "Your payment was disputed.",
470
+ device_revoked: "This computer was removed from your license.",
471
+ signed_out: "This computer was removed from your license."
472
+ };
473
+ var ENDED_FOR_GOOD = ["refunded", "disputed", "device_revoked"];
474
+ var lapseText = (reason) => LAPSE_REASONS[reason] ?? "Your paid license is not active.";
475
+ async function licenseStatus(api, license) {
476
+ if (!license?.deviceId || !license.refreshSecret) return void 0;
477
+ try {
478
+ const { status, body } = await post(api, "/license/status", { deviceId: license.deviceId, refreshSecret: license.refreshSecret }, 5e3);
479
+ if (status === 401) return { active: false, reason: "signed_out" };
480
+ if (status !== 200 || typeof body.active !== "boolean") return void 0;
481
+ return body.active ? { active: true } : { active: false, reason: typeof body.reason === "string" ? body.reason : "refunded" };
482
+ } catch {
483
+ return void 0;
484
+ }
485
+ }
486
+ var OS_NAMES = { win32: "Windows", darwin: "macOS", linux: "Linux" };
487
+ function deviceName() {
488
+ const os = ` (${OS_NAMES[process.platform] ?? process.platform})`;
489
+ return `${hostname().slice(0, 64 - os.length)}${os}`;
490
+ }
491
+ function cleanCode(text) {
492
+ return text.replace(/[\s-]/g, "").toUpperCase();
493
+ }
494
+ var looksLikeCode = (text) => /^[BCDFGHJKLMNPQRSTVWXZ]{10}$/.test(cleanCode(text));
495
+ function readGrant(body, deviceId) {
496
+ const { token, refreshSecret, plan, expiresAt } = body;
497
+ if (typeof token !== "string" || token.split(".").length !== 3 || token.length > 4096) return void 0;
498
+ if (typeof refreshSecret !== "string" || !refreshSecret || refreshSecret.length > 512) return void 0;
499
+ if (plan !== "paid") return void 0;
500
+ return { deviceId, licenseToken: token, refreshSecret, plan, expiresAt: Number(expiresAt) || 0 };
501
+ }
502
+ async function activateWithCode(api, code, existing, name = deviceName()) {
503
+ const deviceId = existing?.deviceId ?? `dev_${randomBytes2(16).toString("base64url")}`;
504
+ let reply;
505
+ try {
506
+ reply = await post(api, "/activate", { code: cleanCode(code), deviceId, deviceName: name });
507
+ } catch {
508
+ return { kind: "error", message: `Could not reach ${api.origin}. Check your connection and try again.` };
509
+ }
510
+ const { status, body } = reply;
511
+ if (status === 200) {
512
+ const grant = readGrant(body, deviceId);
513
+ return grant ? { kind: "activated", grant } : { kind: "error", message: "The activation service sent an unexpected reply." };
514
+ }
515
+ if (status === 400) return { kind: "invalid-code" };
516
+ if (status === 409) return { kind: "device-limit" };
517
+ if (status === 402) return { kind: "ended", reason: typeof body.reason === "string" ? body.reason : "refunded" };
518
+ if (status === 429) return { kind: "rate-limited" };
519
+ return { kind: "error", message: `Activation failed (${status}${typeof body.error === "string" ? ` ${body.error}` : ""}).` };
520
+ }
521
+ function describeActivation(outcome) {
522
+ switch (outcome.kind) {
523
+ case "invalid-code":
524
+ return `That code isn't valid, or it was already used. Get a new one on your account page: ${accountLinks().manage}`;
525
+ case "device-limit":
526
+ return `All 3 of your computers are in use. Remove one on your account page, get a new code there, then try again: ${accountLinks().manage}`;
527
+ case "ended":
528
+ return `${lapseText(outcome.reason)} To use the paid plan again, buy it again at ${PRICING_URL}`;
529
+ case "rate-limited":
530
+ return "Too many tries. Wait a little and try again.";
531
+ case "error":
532
+ return outcome.message;
533
+ }
534
+ }
535
+ async function saveGrant(paths, grant) {
536
+ await ensureConfig(paths);
537
+ const { config } = await readConfig(paths);
538
+ await writeConfig(paths, { ...config, license: { token: grant.licenseToken, deviceId: grant.deviceId, refreshSecret: grant.refreshSecret } });
539
+ }
540
+ async function clearLicense(paths) {
541
+ const { config, exists } = await readConfig(paths);
542
+ if (!exists || !config.license) return;
543
+ const { license: _, sync: __, ...rest } = config;
544
+ await writeConfig(paths, rest);
545
+ }
546
+ async function revokeDevice(api, license) {
547
+ if (!license?.token || !license.deviceId) return "not-activated";
548
+ if (!license.refreshSecret) return "failed";
549
+ try {
550
+ const { status } = await post(api, "/license/devices/revoke", { deviceId: license.deviceId, refreshSecret: license.refreshSecret });
551
+ if (status >= 200 && status < 300) return "revoked";
552
+ return status === 401 ? "already-revoked" : "failed";
553
+ } catch {
554
+ return "failed";
555
+ }
556
+ }
557
+
558
+ // src/remove.ts
559
+ import { existsSync as existsSync3 } from "node:fs";
560
+ import { rm as rm3 } from "node:fs/promises";
561
+
562
+ // src/claude-settings.ts
563
+ import { randomBytes as randomBytes3 } from "node:crypto";
564
+ import { copyFile, mkdir as mkdir2, readFile as readFile2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
565
+ import { homedir as homedir2 } from "node:os";
566
+ import { dirname as dirname2, join as join2 } from "node:path";
567
+ function claudeSettingsPath(env = process.env, home = homedir2()) {
568
+ return join2(env.CLAUDE_CONFIG_DIR || join2(home, ".claude"), "settings.json");
569
+ }
570
+ var SettingsError = class extends Error {
571
+ };
572
+ var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
573
+ async function readSettings(path) {
574
+ let text;
575
+ try {
576
+ text = await readFile2(path, "utf8");
577
+ } catch (error) {
578
+ if (error.code === "ENOENT") return void 0;
579
+ throw error;
580
+ }
581
+ let parsed;
582
+ try {
583
+ parsed = text.trim() ? JSON.parse(text) : {};
584
+ } catch {
585
+ throw new SettingsError(`${path} is not valid JSON, so it was left unchanged`);
586
+ }
587
+ if (!isObject3(parsed)) throw new SettingsError(`${path} is not a JSON object, so it was left unchanged`);
588
+ return parsed;
589
+ }
590
+ async function writeSettings(path, settings, existed) {
591
+ await mkdir2(dirname2(path), { recursive: true });
592
+ if (existed) await copyFile(path, `${path}.${PRODUCT.name}.bak`);
593
+ const temp = `${path}.${randomBytes3(6).toString("hex")}.tmp`;
594
+ await writeFile2(temp, `${JSON.stringify(settings, null, 2)}
595
+ `, "utf8");
596
+ try {
597
+ await rename2(temp, path);
598
+ } catch (error) {
599
+ await rm2(temp, { force: true });
600
+ throw error;
601
+ }
602
+ }
603
+ var marketplaces = (settings) => isObject3(settings.extraKnownMarketplaces) ? settings.extraKnownMarketplaces : {};
604
+ async function setAutoUpdate(path, url, enabled, name = PRODUCT.name) {
605
+ const current = await readSettings(path);
606
+ const settings = current ?? {};
607
+ const all = marketplaces(settings);
608
+ const entry = isObject3(all[name]) ? all[name] : {};
609
+ const source = isObject3(entry.source) ? entry.source : {};
610
+ const isOurs = source.source === "url" && source.url === url;
611
+ if (current && isOurs && entry.autoUpdate === enabled) return "unchanged";
612
+ settings.extraKnownMarketplaces = { ...all, [name]: { ...entry, source: isOurs ? source : { source: "url", url }, autoUpdate: enabled } };
613
+ await writeSettings(path, settings, current !== void 0);
614
+ return "changed";
615
+ }
616
+ async function removeMarketplaceEntry(path, name = PRODUCT.name) {
617
+ const current = await readSettings(path);
618
+ if (!current || !isObject3(current.extraKnownMarketplaces) || !(name in current.extraKnownMarketplaces)) return "absent";
619
+ const { [name]: _, ...rest } = current.extraKnownMarketplaces;
620
+ current.extraKnownMarketplaces = rest;
621
+ await writeSettings(path, current, true);
622
+ return "removed";
623
+ }
624
+ async function autoUpdateState(path, name = PRODUCT.name) {
625
+ try {
626
+ const entry = marketplaces(await readSettings(path) ?? {})[name];
627
+ return isObject3(entry) ? entry.autoUpdate === true : void 0;
628
+ } catch {
629
+ return void 0;
630
+ }
631
+ }
632
+
633
+ // src/tools.ts
634
+ import { spawnSync } from "node:child_process";
635
+ import { existsSync as existsSync2 } from "node:fs";
636
+ import { delimiter, join as join3 } from "node:path";
637
+ var MARKETPLACE_URL = `${(process.env.AMICOOKEDYET_SITE || `https://${PRODUCT.domain}`).replace(/\/+$/, "")}/marketplace.json`;
638
+ var PLUGIN_ID = `${PRODUCT.name}@${PRODUCT.name}`;
639
+ var RUN = `npx ${PRODUCT.name}@latest`;
640
+ function runClaude(args) {
641
+ const options = { encoding: "utf8", windowsHide: true };
642
+ const result = process.platform === "win32" ? spawnSync(["claude", ...args].join(" "), { ...options, shell: true }) : spawnSync("claude", args, options);
643
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
644
+ return { ok: !result.error && result.status === 0, output };
645
+ }
646
+ function claudeVersion() {
647
+ const { ok, output } = runClaude(["--version"]);
648
+ return ok ? output.split("\n")[0].replace(/\s*\(Claude Code\)$/, "").trim() : void 0;
649
+ }
650
+ function pluginState() {
651
+ const { ok, output } = runClaude(["plugin", "list", "--json"]);
652
+ if (!ok) return void 0;
653
+ try {
654
+ const plugins = JSON.parse(output.slice(output.indexOf("[")));
655
+ const plugin = plugins.find((item) => item.id === PLUGIN_ID);
656
+ return plugin ? { installed: true, enabled: plugin.enabled !== false, version: plugin.version } : { installed: false };
657
+ } catch {
658
+ return void 0;
659
+ }
660
+ }
661
+ function isOtherMarketplace(listJson, url) {
662
+ try {
663
+ const entries = JSON.parse(listJson.slice(listJson.indexOf("[")));
664
+ const ours = entries.find((entry) => entry.name === PRODUCT.name);
665
+ return ours !== void 0 && !(ours.source === "url" && ours.url === url);
666
+ } catch {
667
+ return false;
668
+ }
669
+ }
670
+ function setPluginEnabled(enabled) {
671
+ return runClaude(["plugin", enabled ? "enable" : "disable", PLUGIN_ID]);
672
+ }
673
+ function onPath(command, env = process.env) {
674
+ const dirs = (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean);
675
+ const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
676
+ return dirs.some((dir) => extensions.some((ext) => existsSync2(join3(dir, command + ext.toLowerCase())) || existsSync2(join3(dir, command + ext))));
677
+ }
678
+ var OTHER_TOOLS = [
679
+ { name: "Codex CLI", commands: ["codex"] },
680
+ { name: "OpenCode", commands: ["opencode"] },
681
+ { name: "Gemini CLI", commands: ["gemini"] },
682
+ { name: "Cursor", commands: ["cursor", "cursor-agent"] },
683
+ { name: "VS Code", commands: ["code"] },
684
+ { name: "Kiro", commands: ["kiro"] },
685
+ { name: "Windsurf", commands: ["windsurf"] }
686
+ ];
687
+ function findOtherTools(env = process.env) {
688
+ return OTHER_TOOLS.filter((tool) => tool.commands.some((command) => onPath(command, env))).map((tool) => tool.name);
689
+ }
690
+
691
+ // src/remove.ts
692
+ function setEnabled(enabled) {
693
+ if (!claudeVersion()) return [{ ok: false, text: "Claude Code not found" }];
694
+ const result = setPluginEnabled(enabled);
695
+ if (result.ok) return [{ ok: true, text: `${enabled ? "Turned on" : "Turned off"} the ${PRODUCT.displayName} plugin. Your settings are kept.` }];
696
+ if (/already (enabled|disabled)/i.test(result.output)) return [{ ok: true, text: `The plugin was already ${enabled ? "on" : "off"}` }];
697
+ return [{ ok: false, text: `Could not turn the plugin ${enabled ? "on" : "off"}: ${result.output}` }];
698
+ }
699
+ async function signOut(paths, api = defaultApi()) {
700
+ const { config } = await readConfig(paths);
701
+ if (!config.license) return [];
702
+ const steps = [];
703
+ const revoke = await revokeDevice(api, config.license);
704
+ if (revoke === "revoked") steps.push({ ok: true, text: "Freed this computer's slot on your license" });
705
+ if (revoke === "already-revoked") steps.push({ ok: true, text: "This computer was already removed from your license" });
706
+ if (revoke === "failed") steps.push({ ok: false, text: `Could not reach ${PRODUCT.domain} to free this computer's slot. Remove it on your account page.` });
707
+ await clearLicense(paths);
708
+ steps.push({ ok: true, text: "Removed the license from this computer" });
709
+ return steps;
710
+ }
711
+ async function removeProduct(paths, options) {
712
+ const steps = await signOut(paths, options.api);
713
+ if (!claudeVersion()) {
714
+ steps.push({ ok: true, text: "Claude Code not found, nothing to remove there" });
715
+ } else {
716
+ const plugin = runClaude(["plugin", "uninstall", PLUGIN_ID]);
717
+ if (plugin.ok) steps.push({ ok: true, text: `Removed the ${PRODUCT.displayName} plugin` });
718
+ else if (/not (found|installed)/i.test(plugin.output)) steps.push({ ok: true, text: "The plugin was not installed" });
719
+ else steps.push({ ok: false, text: `Could not remove the plugin: ${plugin.output}` });
720
+ const marketplace = runClaude(["plugin", "marketplace", "remove", PRODUCT.name]);
721
+ if (marketplace.ok) steps.push({ ok: true, text: `Removed the ${PRODUCT.displayName} marketplace` });
722
+ else if (/not found|no marketplace|does not exist/i.test(marketplace.output)) steps.push({ ok: true, text: "The marketplace was not added" });
723
+ else steps.push({ ok: false, text: `Could not remove the marketplace: ${marketplace.output}` });
724
+ }
725
+ try {
726
+ if (await removeMarketplaceEntry(claudeSettingsPath()) === "removed") {
727
+ steps.push({ ok: true, text: "Removed our entry from Claude Code settings" });
728
+ }
729
+ } catch (error) {
730
+ steps.push({ ok: false, text: `Could not edit Claude Code settings: ${error instanceof Error ? error.message : error}` });
731
+ }
732
+ if (options.deleteData && existsSync3(paths.dir)) {
733
+ await rm3(paths.dir, { recursive: true, force: true });
734
+ steps.push({ ok: true, text: `Deleted ${paths.dir}` });
735
+ } else if (existsSync3(paths.dir)) {
736
+ steps.push({ ok: true, text: `Kept your settings in ${paths.dir}` });
737
+ }
738
+ return steps;
739
+ }
740
+ function printSteps(steps) {
741
+ for (const step of steps) console.log(`${step.ok ? "\u2713" : "\u2717"} ${step.text}`);
742
+ return steps.every((step) => step.ok) ? 0 : 1;
743
+ }
744
+
745
+ // src/server.ts
746
+ import { randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
747
+ import { existsSync as existsSync4 } from "node:fs";
748
+ import { readFile as readFile3 } from "node:fs/promises";
749
+ import { createServer } from "node:http";
750
+ import { join as join5 } from "node:path";
751
+
752
+ // src/license.ts
753
+ import { createHash, createPublicKey, verify } from "node:crypto";
754
+ var LICENSE_PUBLIC_KEY_X = "tqrNMHCcpAZnCJeu39fK990uZdRLowO3-PuG_WdUzsU";
755
+ var TOKEN_TYPE = "license+jwt";
756
+ function keyId(x) {
757
+ return createHash("sha256").update(`ed25519:${x}`).digest("base64url").slice(0, 16);
758
+ }
759
+ function decodePart(part) {
760
+ return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
761
+ }
762
+ function verifyLicense(license, options = {}) {
763
+ const publicKeyX = options.publicKeyX ?? LICENSE_PUBLIC_KEY_X;
764
+ const token = license?.token;
765
+ if (!token || !publicKeyX || !license.deviceId) return void 0;
766
+ const parts = token.split(".");
767
+ if (parts.length !== 3) return void 0;
768
+ try {
769
+ const header = decodePart(parts[0]);
770
+ if (header.alg !== "EdDSA" || header.typ !== TOKEN_TYPE || header.kid !== keyId(publicKeyX)) return void 0;
771
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: publicKeyX }, format: "jwk" });
772
+ if (!verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], "base64url"))) return void 0;
773
+ const claims = decodePart(parts[1]);
774
+ const nowSec = Math.floor((options.now ?? Date.now()) / 1e3);
775
+ if (claims.v !== 1 || claims.plan !== "paid") return void 0;
776
+ if (typeof claims.sub !== "string" || claims.device !== license.deviceId) return void 0;
777
+ if (!(Number(claims.exp) > nowSec) || !(Number(claims.iat) <= nowSec + 300)) return void 0;
778
+ return claims;
779
+ } catch {
780
+ return void 0;
781
+ }
782
+ }
783
+ function unverifiedClaims(token) {
784
+ try {
785
+ const claims = decodePart(token?.split(".")[1] ?? "");
786
+ const exp = Number(claims.exp);
787
+ return { plan: typeof claims.plan === "string" ? claims.plan : void 0, exp: Number.isFinite(exp) && exp > 0 ? exp : void 0 };
788
+ } catch {
789
+ return void 0;
790
+ }
791
+ }
792
+
793
+ // src/library.ts
794
+ import { mkdir as mkdir3, readdir, rename as rename3, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
795
+ import { join as join4 } from "node:path";
796
+ var MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024;
797
+ async function download(api, path, token, target) {
798
+ try {
799
+ const response = await api.fetch(`${api.origin}${path}`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15e3) });
800
+ if (!response.ok) return false;
801
+ const data = Buffer.from(await response.arrayBuffer());
802
+ if (data.length === 0 || data.length > MAX_DOWNLOAD_BYTES) return false;
803
+ await writeFile3(`${target}.part`, data);
804
+ await rename3(`${target}.part`, target);
805
+ return true;
806
+ } catch {
807
+ return false;
808
+ }
809
+ }
810
+ async function downloadOwnSounds(paths, api) {
811
+ const { config } = await readConfig(paths);
812
+ const token = config.license?.token;
813
+ if (!token || config.customSounds.length === 0) return;
814
+ await mkdir3(paths.sounds, { recursive: true });
815
+ const existing = await readdir(paths.sounds).catch(() => []);
816
+ for (const sound of config.customSounds) {
817
+ if (!isSoundFileName(sound.file) || existing.includes(sound.file)) continue;
818
+ if (!await download(api, `/sounds/own?id=${encodeURIComponent(sound.id)}`, token, join4(paths.sounds, sound.file))) return;
819
+ }
820
+ }
821
+ async function downloadLibrary(paths, api, license) {
822
+ if (!license?.token) return [];
823
+ const have = await downloadLibrarySounds(paths, api, license.token);
824
+ await downloadOwnSounds(paths, api);
825
+ return have;
826
+ }
827
+ async function downloadLibrarySounds(paths, api, token) {
828
+ const have = [];
829
+ await mkdir3(paths.library, { recursive: true });
830
+ for (const name of BUILT_IN_SOUNDS) {
831
+ if (name === PRESET_SOUND) continue;
832
+ const target = join4(paths.library, `${name}.wav`);
833
+ const existing = await readdir(paths.library).catch(() => []);
834
+ if (existing.includes(`${name}.wav`)) {
835
+ have.push(name);
836
+ continue;
837
+ }
838
+ if (!await download(api, `/sounds/download?id=${name}`, token, target)) return have;
839
+ have.push(name);
840
+ }
841
+ return have;
842
+ }
843
+ async function removeUnusedSounds(paths, config) {
844
+ const used = new Set(config.customSounds.map((sound) => sound.file));
845
+ const files = await readdir(paths.sounds).catch(() => []);
846
+ await Promise.all(files.filter((file) => isSoundFileName(file) && !used.has(file)).map((file) => rm4(join4(paths.sounds, file), { force: true })));
847
+ }
848
+ async function endLicense(paths) {
849
+ const { config, exists } = await readConfig(paths);
850
+ if (!exists) return;
851
+ const { license: _, ...rest } = dropPaidSettings(config);
852
+ await writeConfig(paths, rest);
853
+ await removeUnusedSounds(paths, rest);
854
+ await rm4(paths.library, { recursive: true, force: true });
855
+ }
856
+
857
+ // src/sync.ts
858
+ async function pushSettings(api, paths, baseRev) {
859
+ let base = baseRev;
860
+ for (let attempt = 0; attempt < 3; attempt++) {
861
+ const { config } = await readConfig(paths);
862
+ const license = config.license;
863
+ if (!license?.deviceId || !license.refreshSecret) return { kind: "pending" };
864
+ const settings = syncedOf(config);
865
+ let reply;
866
+ try {
867
+ reply = await post(api, "/license/settings", { deviceId: license.deviceId, refreshSecret: license.refreshSecret, rev: base ?? settingsRevOf(config), settings }, 1e4);
868
+ } catch {
869
+ return { kind: "pending" };
870
+ }
871
+ if (reply.status === 409 && typeof reply.body.rev === "number" && reply.body.settings) {
872
+ const answer = readSettingsAnswer({ settingsRev: reply.body.rev, settings: reply.body.settings });
873
+ if (answer?.settings) return { kind: "conflict", rev: answer.rev, settings: answer.settings };
874
+ }
875
+ if (reply.status !== 200 || typeof reply.body.rev !== "number") return { kind: "pending" };
876
+ const { config: latest } = await readConfig(paths);
877
+ const changedMeanwhile = JSON.stringify(syncedOf(latest)) !== JSON.stringify(settings);
878
+ await writeConfig(paths, changedMeanwhile ? { ...latest, sync: { rev: reply.body.rev, pending: true } } : afterUpload(latest, reply.status, reply.body));
879
+ if (!changedMeanwhile) return { kind: "synced", rev: reply.body.rev };
880
+ base = void 0;
881
+ }
882
+ return { kind: "pending" };
883
+ }
884
+ async function useSaved(paths, rev, settings) {
885
+ const { config } = await readConfig(paths);
886
+ await writeConfig(paths, withSyncedSettings(config, settings, rev));
887
+ }
888
+ async function pullSettings(api, paths) {
889
+ const { config } = await readConfig(paths);
890
+ const license = config.license;
891
+ if (!license?.deviceId || !license.refreshSecret) return "none";
892
+ try {
893
+ const status = await post(api, "/license/status", { deviceId: license.deviceId, refreshSecret: license.refreshSecret, settingsRev: settingsRevOf(config) }, 1e4);
894
+ if (status.status !== 200 || status.body.active !== true) return "none";
895
+ const step = nextSyncStep(config, readSettingsAnswer(status.body));
896
+ if (!step) return "none";
897
+ if ("apply" in step) {
898
+ await writeConfig(paths, withSyncedSettings(config, step.apply, step.rev));
899
+ return "applied";
900
+ }
901
+ const reply = await post(api, "/license/settings", { deviceId: license.deviceId, refreshSecret: license.refreshSecret, rev: step.baseRev, settings: step.upload }, 1e4);
902
+ const synced = afterUpload(config, reply.status, reply.body);
903
+ await writeConfig(paths, synced);
904
+ return reply.status === 200 ? "uploaded" : reply.status === 409 ? "applied" : "none";
905
+ } catch {
906
+ return "none";
907
+ }
908
+ }
909
+ function syncText(config) {
910
+ if (!config.sync) return "not synced yet (it happens when Claude Code starts)";
911
+ return config.sync.pending ? "a change made here waits to be sent" : `synced with your license (rev ${config.sync.rev})`;
912
+ }
913
+
914
+ // src/server.ts
915
+ function accountState(license, plan, verified, lapsed) {
916
+ if (!license?.token) return { activated: false, plan, verified: false, ...lapsed ? { lapsed: lapseText(lapsed) } : {} };
917
+ const claims = verified ?? unverifiedClaims(license.token);
918
+ return {
919
+ ...lapsed ? { lapsed: lapseText(lapsed) } : {},
920
+ activated: true,
921
+ plan,
922
+ verified: Boolean(verified),
923
+ licenseExpiresAt: claims?.exp
924
+ };
925
+ }
926
+ var MAX_CONFIG_BYTES = 64 * 1024;
927
+ var STATUS_TTL_MS = 5 * 60 * 1e3;
928
+ function newToken() {
929
+ return randomBytes4(32).toString("hex");
930
+ }
931
+ function tokensMatch(expected, given) {
932
+ if (typeof given !== "string") return false;
933
+ const a = Buffer.from(expected);
934
+ const b = Buffer.from(given);
935
+ return a.length === b.length && timingSafeEqual(a, b);
936
+ }
937
+ function checkAccess(req, token, port) {
938
+ const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
939
+ if (!allowedHosts.includes(String(req.headers.host ?? "").toLowerCase())) return 421;
940
+ const origin = req.headers.origin;
941
+ if (origin !== void 0 && !allowedHosts.some((host) => origin === `http://${host}`)) return 403;
942
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
943
+ const given = req.headers["x-token"] ?? (req.method === "GET" ? url.searchParams.get("token") : void 0);
944
+ return tokensMatch(token, given) ? void 0 : 401;
945
+ }
946
+ var HttpError = class extends Error {
947
+ constructor(status, message) {
948
+ super(message);
949
+ this.status = status;
950
+ }
951
+ };
952
+ async function readBody(req, limit) {
953
+ const declared = Number(req.headers["content-length"]);
954
+ if (declared > limit) throw new HttpError(413, "Too large");
955
+ const chunks = [];
956
+ let total = 0;
957
+ for await (const chunk of req) {
958
+ total += chunk.length;
959
+ if (total > limit) throw new HttpError(413, "Too large");
960
+ chunks.push(chunk);
961
+ }
962
+ return Buffer.concat(chunks);
963
+ }
964
+ function send(res, status, body) {
965
+ const text = JSON.stringify(body);
966
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
967
+ res.end(text);
968
+ }
969
+ async function sendFile(res, file) {
970
+ if (!file || !existsSync4(file)) return send(res, 404, { error: "Not found" });
971
+ res.writeHead(200, { "content-type": "audio/wav", "cache-control": "no-store" });
972
+ res.end(await readFile3(file));
973
+ }
974
+ async function readJsonBody(req, limit) {
975
+ try {
976
+ return JSON.parse((await readBody(req, limit)).toString("utf8"));
977
+ } catch (error) {
978
+ if (error instanceof HttpError) throw error;
979
+ throw new HttpError(400, "Invalid JSON");
980
+ }
981
+ }
982
+ function createConfigServer(options) {
983
+ const { paths, token } = options;
984
+ const verify2 = options.verify ?? verifyLicense;
985
+ const askStatus = options.licenseStatus ?? ((license) => licenseStatus(options.api, license));
986
+ const statuses = /* @__PURE__ */ new Map();
987
+ function statusOf(license) {
988
+ const key = license?.token ?? "";
989
+ const known = statuses.get(key);
990
+ if (known && Date.now() - known.at < STATUS_TTL_MS) return known.status;
991
+ const status = askStatus(license);
992
+ statuses.set(key, { at: Date.now(), status });
993
+ return status;
994
+ }
995
+ async function planFor(license) {
996
+ const claims = verify2(license);
997
+ const status = license?.token ? await statusOf(license) : void 0;
998
+ if (status?.active === false) {
999
+ if (ENDED_FOR_GOOD.includes(status.reason)) {
1000
+ await endLicense(paths);
1001
+ statuses.clear();
1002
+ }
1003
+ return { plan: "free", lapsed: status.reason };
1004
+ }
1005
+ return { plan: claims ? "paid" : "free" };
1006
+ }
1007
+ let port = 0;
1008
+ let conflict;
1009
+ async function currentPlan() {
1010
+ return (await planFor((await readConfig(paths)).config.license)).plan;
1011
+ }
1012
+ async function handle(req, res) {
1013
+ const denied = checkAccess(req, token, port);
1014
+ if (denied) return send(res, denied, { error: "Forbidden" });
1015
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
1016
+ const route = `${req.method} ${url.pathname}`;
1017
+ if (route === "GET /") {
1018
+ const nonce = randomBytes4(16).toString("base64");
1019
+ res.writeHead(200, {
1020
+ "content-type": "text/html; charset=utf-8",
1021
+ "cache-control": "no-store",
1022
+ "referrer-policy": "no-referrer",
1023
+ "x-frame-options": "DENY",
1024
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; media-src 'self' blob:; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
1025
+ });
1026
+ return res.end(options.html.replaceAll("__NONCE__", nonce).replaceAll("__COMMAND__", RUN));
1027
+ }
1028
+ if (route === "GET /api/state") {
1029
+ const { config: read, error } = await readConfig(paths);
1030
+ const { plan, lapsed } = await planFor(read.license);
1031
+ const { config } = await readConfig(paths);
1032
+ const { license, ...rest } = config;
1033
+ const limited = applyPlanLimits(rest, plan);
1034
+ return send(res, 200, {
1035
+ product: PRODUCT.displayName,
1036
+ plan,
1037
+ account: accountState(license, plan, verify2(license), lapsed),
1038
+ links: accountLinks(),
1039
+ limits: PLAN_LIMITS,
1040
+ alarmSteps: ALARM_STEPS_LEFT,
1041
+ builtInSounds: BUILT_IN_SOUNDS,
1042
+ presetSound: PRESET_SOUND,
1043
+ configPath: paths.config,
1044
+ plugin: options.actions.pluginState() ?? null,
1045
+ // An `any` alarm splits in two, so count what the limits dropped, never below 0.
1046
+ hidden: {
1047
+ alarms: Math.max(0, config.alarms.length - limited.alarms.length),
1048
+ customSounds: config.customSounds.length - limited.customSounds.length
1049
+ },
1050
+ config: limited,
1051
+ error
1052
+ });
1053
+ }
1054
+ if (route === "PUT /api/config") {
1055
+ const clean = sanitizeConfig(await readJsonBody(req, MAX_CONFIG_BYTES));
1056
+ const { config: current } = await readConfig(paths);
1057
+ clean.customSounds = current.customSounds;
1058
+ const plan = await currentPlan();
1059
+ const config = applyPlanLimits(sanitizeConfig(clean), plan);
1060
+ if (!PLAN_LIMITS[plan].breakReminders) config.breaks = current.breaks;
1061
+ const sync = plan === "paid" && current.license?.deviceId ? { rev: settingsRevOf(current), pending: true } : current.sync;
1062
+ const saved = { ...config, ...current.license ? { license: current.license } : {}, ...sync ? { sync } : {} };
1063
+ await writeConfig(paths, saved);
1064
+ await removeUnusedSounds(paths, saved);
1065
+ const { license: _, sync: __, ...rest } = saved;
1066
+ return send(res, 200, { config: applyPlanLimits(rest, plan) });
1067
+ }
1068
+ if (route === "POST /api/sync") {
1069
+ if (await currentPlan() !== "paid") return send(res, 200, { sync: "off" });
1070
+ if (!(await readConfig(paths)).config.sync?.pending) return send(res, 200, { sync: "synced" });
1071
+ const result = await pushSettings(options.api, paths);
1072
+ conflict = result.kind === "conflict" ? result : void 0;
1073
+ await downloadOwnSounds(paths, options.api);
1074
+ return send(res, 200, { sync: result.kind });
1075
+ }
1076
+ if (route === "POST /api/sync/resolve") {
1077
+ const keep = (await readJsonBody(req, 1024))?.keep;
1078
+ if (!conflict || keep !== "mine" && keep !== "theirs") throw new HttpError(400, "Nothing to resolve");
1079
+ const theirs = conflict;
1080
+ conflict = void 0;
1081
+ if (keep === "theirs") {
1082
+ await useSaved(paths, theirs.rev, theirs.settings);
1083
+ return send(res, 200, { sync: "synced" });
1084
+ }
1085
+ const result = await pushSettings(options.api, paths, theirs.rev);
1086
+ conflict = result.kind === "conflict" ? result : void 0;
1087
+ return send(res, 200, { sync: result.kind });
1088
+ }
1089
+ if (req.method === "GET" && url.pathname.startsWith("/sounds/builtin/")) {
1090
+ const name = url.pathname.slice("/sounds/builtin/".length).replace(/\.wav$/, "");
1091
+ if (!BUILT_IN_SOUNDS.includes(name)) return sendFile(res, void 0);
1092
+ if (name === PRESET_SOUND) return sendFile(res, join5(options.builtInSoundsDir, `${name}.wav`));
1093
+ const downloaded = join5(paths.library, `${name}.wav`);
1094
+ if (existsSync4(downloaded)) return sendFile(res, downloaded);
1095
+ try {
1096
+ const preview = await options.api.fetch(`${options.api.origin}/sounds/preview?id=${name}`, { signal: AbortSignal.timeout(1e4) });
1097
+ if (!preview.ok) return send(res, 502, { error: "The preview is not available right now" });
1098
+ res.writeHead(200, { "content-type": "audio/wav", "cache-control": "no-store" });
1099
+ return res.end(Buffer.from(await preview.arrayBuffer()));
1100
+ } catch {
1101
+ return send(res, 502, { error: "Could not reach the server for the preview" });
1102
+ }
1103
+ }
1104
+ if (req.method === "GET" && url.pathname.startsWith("/sounds/custom/")) {
1105
+ return sendFile(res, soundFilePath(paths.sounds, url.pathname.slice("/sounds/custom/".length)));
1106
+ }
1107
+ if (route === "POST /api/plugin") {
1108
+ const body = await readJsonBody(req, 1024);
1109
+ const enabled = body?.enabled;
1110
+ if (typeof enabled !== "boolean") throw new HttpError(400, "Expected { enabled: boolean }");
1111
+ const steps = options.actions.setEnabled(enabled);
1112
+ return send(res, 200, { steps, plugin: options.actions.pluginState() ?? null });
1113
+ }
1114
+ if (route === "POST /api/uninstall") {
1115
+ const body = await readJsonBody(req, 1024);
1116
+ const steps = await options.actions.remove({ deleteData: body?.deleteData === true });
1117
+ send(res, 200, { steps });
1118
+ return options.onClose?.();
1119
+ }
1120
+ if (route === "POST /api/activate") {
1121
+ const code = (await readJsonBody(req, 1024))?.code;
1122
+ if (typeof code !== "string" || !looksLikeCode(code)) throw new HttpError(400, "That doesn't look like an activation code. It has 10 letters, like BCDFG-HJKLM.");
1123
+ const { config } = await readConfig(paths);
1124
+ const outcome = await activateWithCode(options.api, code, config.license);
1125
+ if (outcome.kind !== "activated") throw new HttpError(outcome.kind === "rate-limited" ? 429 : 400, describeActivation(outcome));
1126
+ await saveGrant(paths, outcome.grant);
1127
+ statuses.clear();
1128
+ await pullSettings(options.api, paths);
1129
+ await downloadLibrary(paths, options.api, { token: outcome.grant.licenseToken });
1130
+ return send(res, 200, { plan: outcome.grant.plan });
1131
+ }
1132
+ if (route === "POST /api/logout") {
1133
+ statuses.clear();
1134
+ return send(res, 200, { steps: await signOut(paths, options.api) });
1135
+ }
1136
+ if (route === "POST /api/close") {
1137
+ send(res, 200, { ok: true });
1138
+ return options.onClose?.();
1139
+ }
1140
+ send(res, 404, { error: "Not found" });
1141
+ }
1142
+ const server = createServer((req, res) => {
1143
+ handle(req, res).catch((error) => {
1144
+ if (res.headersSent) return res.end();
1145
+ if (error instanceof HttpError) return send(res, error.status, { error: error.message });
1146
+ send(res, 500, { error: "Something went wrong" });
1147
+ console.error(error);
1148
+ });
1149
+ });
1150
+ server.on("listening", () => {
1151
+ const address = server.address();
1152
+ if (address && typeof address === "object") port = address.port;
1153
+ });
1154
+ return server;
1155
+ }
1156
+
1157
+ // src/config-command.ts
1158
+ function builtInSoundsDir() {
1159
+ const bundled = fileURLToPath(new URL("./sounds", import.meta.url));
1160
+ return existsSync5(bundled) ? bundled : fileURLToPath(new URL("../../../plugin/sounds", import.meta.url));
1161
+ }
1162
+ async function configCommand(options) {
1163
+ const paths = getPaths();
1164
+ await ensureConfig(paths);
1165
+ if (await pullSettings(defaultApi(), paths) === "applied") console.log("\u2713 Applied the alarm settings saved with your license");
1166
+ const { error } = await readConfig(paths);
1167
+ if (error) console.log(`! ${error}. The page starts from the defaults; saving replaces the file.`);
1168
+ const token = newToken();
1169
+ const html = readFileSync(new URL("./ui/index.html", import.meta.url), "utf8");
1170
+ return new Promise((resolve2, reject) => {
1171
+ const server = createConfigServer({
1172
+ paths,
1173
+ token,
1174
+ api: defaultApi(),
1175
+ html,
1176
+ builtInSoundsDir: builtInSoundsDir(),
1177
+ actions: {
1178
+ pluginState,
1179
+ setEnabled: (enabled) => {
1180
+ const steps = setEnabled(enabled);
1181
+ printSteps(steps);
1182
+ return steps;
1183
+ },
1184
+ remove: async ({ deleteData }) => {
1185
+ const steps = await removeProduct(paths, { deleteData });
1186
+ printSteps(steps);
1187
+ return steps;
1188
+ }
1189
+ },
1190
+ onClose: () => stop()
1191
+ });
1192
+ function stop() {
1193
+ server.close(() => resolve2(0));
1194
+ server.closeAllConnections?.();
1195
+ }
1196
+ server.on("error", reject);
1197
+ server.listen(0, "127.0.0.1", () => {
1198
+ const address = server.address();
1199
+ const port = address && typeof address === "object" ? address.port : 0;
1200
+ const url = `http://127.0.0.1:${port}/?token=${token}`;
1201
+ console.log(`${PRODUCT.displayName} settings: ${url}`);
1202
+ console.log("Keep this window open while you edit. Press Ctrl+C or click Done to stop.");
1203
+ if (options.open) openBrowser(url);
1204
+ });
1205
+ process.once("SIGINT", stop);
1206
+ });
1207
+ }
1208
+
1209
+ // src/install.ts
1210
+ var AUTO_UPDATE_OFF = `/plugin \u2192 Marketplaces \u2192 ${PRODUCT.name}`;
1211
+ async function turnOnAutoUpdate() {
1212
+ try {
1213
+ await setAutoUpdate(claudeSettingsPath(), MARKETPLACE_URL, true);
1214
+ console.log(`\u2713 Turned on automatic updates. To turn them off, in Claude Code: ${AUTO_UPDATE_OFF}`);
1215
+ } catch (error) {
1216
+ const reason = error instanceof SettingsError ? error.message : String(error);
1217
+ console.log(`! Could not turn on automatic updates (${reason}). Turn them on in Claude Code: ${AUTO_UPDATE_OFF}`);
1218
+ }
1219
+ }
1220
+ async function installCommand(options = { autoUpdate: true }) {
1221
+ const paths = getPaths();
1222
+ let failed = false;
1223
+ const version2 = claudeVersion();
1224
+ if (!version2) {
1225
+ console.log("\u2717 Claude Code not found. Install it from https://claude.com/claude-code, then run this again.");
1226
+ failed = true;
1227
+ } else {
1228
+ console.log(`\u2713 Found Claude Code ${version2}`);
1229
+ const listed = runClaude(["plugin", "marketplace", "list", "--json"]);
1230
+ if (listed.ok && isOtherMarketplace(listed.output, MARKETPLACE_URL)) {
1231
+ const removed = runClaude(["plugin", "marketplace", "remove", PRODUCT.name]);
1232
+ console.log(removed.ok ? `\u2713 Replaced an older ${PRODUCT.displayName} marketplace` : `! Could not remove the older marketplace:
1233
+ ${removed.output}`);
1234
+ }
1235
+ const marketplace = runClaude(["plugin", "marketplace", "add", MARKETPLACE_URL]);
1236
+ if (marketplace.ok) {
1237
+ console.log(`\u2713 Added the ${PRODUCT.displayName} marketplace`);
1238
+ if (options.autoUpdate) await turnOnAutoUpdate();
1239
+ const plugin = runClaude(["plugin", "install", PLUGIN_ID]);
1240
+ if (plugin.ok) console.log(`\u2713 Installed the ${PRODUCT.displayName} plugin`);
1241
+ else {
1242
+ console.log(`\u2717 Could not install the plugin:
1243
+ ${plugin.output}`);
1244
+ failed = true;
1245
+ }
1246
+ } else {
1247
+ console.log(`\u2717 Could not add the marketplace:
1248
+ ${marketplace.output}`);
1249
+ failed = true;
1250
+ }
1251
+ }
1252
+ const created = await ensureConfig(paths);
1253
+ console.log(created ? `\u2713 Created ${paths.config}` : `\u2713 Kept your config at ${paths.config}`);
1254
+ const others = findOtherTools();
1255
+ if (others.length) console.log(`
1256
+ Also found (coming soon): ${others.join(", ")}`);
1257
+ console.log(
1258
+ failed ? `
1259
+ Fix the error above and run \`${RUN} install\` again.` : `
1260
+ Next steps:
1261
+ 1. Restart Claude Code to load the plugin. The free plan is on: the usage line and one alarm at 10% left.
1262
+ 2. In Claude Code, run /cooked to check it's working.
1263
+ 3. Want more alarms, the sound library, break reminders and phone alerts? Get the paid plan at ${PRODUCT.domain}/#pricing. Already paid? Get your activation code at ${PRODUCT.domain}/manage/, then run \`${RUN} activate\`.
1264
+
1265
+ Turn it off any time with \`${RUN} disable\`, or remove it with \`${RUN} uninstall\`.`
1266
+ );
1267
+ return failed ? 1 : 0;
1268
+ }
1269
+
1270
+ // src/activate.ts
1271
+ import { createInterface } from "node:readline/promises";
1272
+ async function askForCode() {
1273
+ if (!process.stdin.isTTY) return void 0;
1274
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1275
+ try {
1276
+ return (await rl.question("Activation code (like BCDFG-HJKLM): ")).trim();
1277
+ } finally {
1278
+ rl.close();
1279
+ }
1280
+ }
1281
+ async function activateCommand(options) {
1282
+ const api = options.api ?? defaultApi();
1283
+ const paths = getPaths();
1284
+ const code = options.code ?? await askForCode();
1285
+ if (!code) {
1286
+ console.log(`Usage: ${RUN} activate <code>
1287
+
1288
+ Get your code on your account page: ${accountLinks().manage}`);
1289
+ return 1;
1290
+ }
1291
+ if (!looksLikeCode(code)) {
1292
+ console.log(`\u2717 That doesn't look like an activation code. It has 10 letters, like BCDFG-HJKLM. Get one on your account page: ${accountLinks().manage}`);
1293
+ return 1;
1294
+ }
1295
+ const { config } = await readConfig(paths);
1296
+ const outcome = await activateWithCode(api, code, config.license);
1297
+ if (outcome.kind !== "activated") {
1298
+ console.log(`\u2717 ${describeActivation(outcome)}`);
1299
+ return 1;
1300
+ }
1301
+ await saveGrant(paths, outcome.grant);
1302
+ console.log(`\u2713 ${PRODUCT.displayName} is activated on this computer.`);
1303
+ const synced = await pullSettings(api, paths);
1304
+ if (synced === "applied") console.log("\u2713 Applied the alarm settings saved with your license");
1305
+ if (synced === "uploaded") console.log("\u2713 Saved this computer's alarm settings with your license");
1306
+ const sounds = await downloadLibrary(paths, api, { token: outcome.grant.licenseToken });
1307
+ if (sounds.length) console.log(`\u2713 Downloaded ${sounds.length} sound${sounds.length === 1 ? "" : "s"} from the library`);
1308
+ console.log("Restart Claude Code to apply it.");
1309
+ return 0;
1310
+ }
1311
+ async function logoutCommand(options = {}) {
1312
+ const steps = await signOut(getPaths(), options.api ?? defaultApi());
1313
+ if (!steps.length) {
1314
+ console.log("- This computer is not activated");
1315
+ return 0;
1316
+ }
1317
+ return printSteps(steps);
1318
+ }
1319
+
1320
+ // src/status.ts
1321
+ function describeExpiry(seconds, now = Date.now()) {
1322
+ const when = new Date(seconds * 1e3).toISOString().slice(0, 16).replace("T", " ") + " UTC";
1323
+ const hours = Math.floor((seconds * 1e3 - now) / 36e5);
1324
+ if (seconds * 1e3 <= now) return `${when} (expired)`;
1325
+ return `${when} (${hours < 1 ? "within the hour" : hours === 1 ? "in 1 hour" : `in ${hours} hours`})`;
1326
+ }
1327
+ async function statusCommand(api = defaultApi()) {
1328
+ const paths = getPaths();
1329
+ const rows = [];
1330
+ const version2 = claudeVersion();
1331
+ rows.push(["Claude Code", version2 ?? "not found"]);
1332
+ if (version2) {
1333
+ const plugin = pluginState();
1334
+ rows.push([
1335
+ "Plugin",
1336
+ !plugin ? "unknown" : !plugin.installed ? `not installed (run ${RUN} install)` : `${plugin.enabled ? "on" : "off"}${plugin.version ? `, v${plugin.version}` : ""}`
1337
+ ]);
1338
+ const autoUpdate = await autoUpdateState(claudeSettingsPath());
1339
+ rows.push(["Auto-update", autoUpdate === void 0 ? "unknown (marketplace not in Claude Code settings)" : autoUpdate ? "on" : `off (run ${RUN} install to turn it on)`]);
1340
+ }
1341
+ const { config, exists, error } = await readConfig(paths);
1342
+ rows.push(["Settings", !exists ? "not created yet" : error ? `${paths.config} (${error})` : paths.config]);
1343
+ const token = config.license?.token;
1344
+ const claims = verifyLicense(config.license);
1345
+ const status = token ? await licenseStatus(api, config.license) : void 0;
1346
+ const isOver = status?.active === false;
1347
+ const free = "Free: the usage line and one alarm at 10% left";
1348
+ if (!token) {
1349
+ rows.push(["Plan", `${free} (get the paid plan at ${accountLinks().buy}. Already paid? Get your code at ${accountLinks().manage}, then run ${RUN} activate)`]);
1350
+ } else if (isOver) {
1351
+ rows.push(["Plan", `${free}. ${lapseText(status.reason)}`]);
1352
+ if (ENDED_FOR_GOOD.includes(status.reason) && exists && !error) {
1353
+ await endLicense(paths);
1354
+ rows.push(["Removed", "The paid alarms, break settings and sounds were removed from this computer."]);
1355
+ }
1356
+ } else if (claims) {
1357
+ rows.push(["Plan", "Paid, yours for good"]);
1358
+ rows.push(["License renews", describeExpiry(claims.exp)]);
1359
+ rows.push(["Sync", syncText(config)]);
1360
+ } else {
1361
+ const unverified = unverifiedClaims(token);
1362
+ rows.push(["Plan", `${free} (the license on this computer is not valid here${LICENSE_PUBLIC_KEY_X ? "" : ": no key in this build yet"})`]);
1363
+ if (unverified?.exp) rows.push(["License", describeExpiry(unverified.exp)]);
1364
+ }
1365
+ const width = Math.max(...rows.map(([label]) => label.length));
1366
+ console.log(`${PRODUCT.displayName} status
1367
+ `);
1368
+ for (const [label, value] of rows) console.log(` ${label.padEnd(width)} ${value}`);
1369
+ return 0;
1370
+ }
1371
+
1372
+ // src/uninstall.ts
1373
+ import { existsSync as existsSync6 } from "node:fs";
1374
+ import { createInterface as createInterface2 } from "node:readline/promises";
1375
+ async function confirm(question) {
1376
+ if (!process.stdin.isTTY) return false;
1377
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
1378
+ try {
1379
+ return /^y(es)?$/i.test((await rl.question(question)).trim());
1380
+ } finally {
1381
+ rl.close();
1382
+ }
1383
+ }
1384
+ async function uninstallCommand(options) {
1385
+ const paths = getPaths();
1386
+ const deleteData = existsSync6(paths.dir) && (options.yes || await confirm(`Also delete ${paths.dir} (your settings and custom sounds)? [y/N] `));
1387
+ return printSteps(await removeProduct(paths, { deleteData }));
1388
+ }
1389
+
1390
+ // src/index.ts
1391
+ function version() {
1392
+ const pkg = JSON.parse(readFileSync2(new URL("../package.json", import.meta.url), "utf8"));
1393
+ return pkg.version;
1394
+ }
1395
+ var HELP = `${PRODUCT.displayName} An alarm for when your AI coding tool's usage runs low
1396
+
1397
+ Usage: ${RUN} <command> [options]
1398
+
1399
+ Commands:
1400
+ install Install the Claude Code plugin and create your settings
1401
+ config Open the settings page in your browser
1402
+ status Show whether it's installed and on, your plan and license
1403
+ activate [code] Turn this computer into a paid one with the code from your account page
1404
+ logout Remove the license from this computer and free its slot
1405
+ disable Turn the plugin off and keep your settings
1406
+ enable Turn the plugin back on
1407
+ uninstall Remove the plugin and marketplace, and sign this device out
1408
+
1409
+ Options:
1410
+ --no-open (config) Print the URL instead of opening a browser
1411
+ --no-auto-update (install) Leave plugin auto-update off in Claude Code
1412
+ -y, --yes (uninstall) Also delete your settings and sounds without asking
1413
+ -h, --help Show this help
1414
+ -v, --version Show the version
1415
+ `;
1416
+ async function main(argv) {
1417
+ const flags = new Set(argv.filter((arg) => arg.startsWith("-")));
1418
+ const [command, argument] = argv.filter((arg) => !arg.startsWith("-"));
1419
+ if (flags.has("-v") || flags.has("--version")) {
1420
+ console.log(version());
1421
+ return 0;
1422
+ }
1423
+ if (flags.has("-h") || flags.has("--help") || command === "help") {
1424
+ console.log(HELP);
1425
+ return 0;
1426
+ }
1427
+ if (!command) {
1428
+ console.log(HELP);
1429
+ return 1;
1430
+ }
1431
+ switch (command) {
1432
+ case "install":
1433
+ return installCommand({ autoUpdate: !flags.has("--no-auto-update") });
1434
+ case "config":
1435
+ return configCommand({ open: !flags.has("--no-open") });
1436
+ case "status":
1437
+ return statusCommand();
1438
+ case "activate":
1439
+ return activateCommand({ code: argument });
1440
+ case "logout":
1441
+ return logoutCommand();
1442
+ case "disable":
1443
+ case "enable":
1444
+ return printSteps(setEnabled(command === "enable"));
1445
+ case "uninstall":
1446
+ return uninstallCommand({ yes: flags.has("-y") || flags.has("--yes") });
1447
+ default:
1448
+ console.error(`Unknown command: ${command}
1449
+ `);
1450
+ console.log(HELP);
1451
+ return 1;
1452
+ }
1453
+ }
1454
+ main(process.argv.slice(2)).then(
1455
+ (code) => {
1456
+ process.exitCode = code;
1457
+ },
1458
+ (error) => {
1459
+ console.error(error instanceof Error ? error.message : error);
1460
+ process.exitCode = 1;
1461
+ }
1462
+ );