@soffits/dsh-media-hub 0.15.2 → 0.15.4

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 CHANGED
@@ -8972,6 +8972,156 @@ var require_build = __commonJS({
8972
8972
  // index.js
8973
8973
  import { join as join18, resolve as resolve7 } from "node:path";
8974
8974
 
8975
+ // node_modules/@soffits/dsh-host-kit/src/locales.js
8976
+ import { readdir, readFile } from "node:fs/promises";
8977
+ import { join } from "node:path";
8978
+ var BASE = "en";
8979
+ var TAG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
8980
+ async function readLocales(dir, { warn = () => {
8981
+ } } = {}) {
8982
+ const locales = {};
8983
+ for (const name2 of (await readdir(dir)).filter((file) => file.endsWith(".json")).sort()) {
8984
+ const tag = name2.slice(0, -".json".length);
8985
+ if (!TAG.test(tag)) {
8986
+ warn(`locale/${name2}: the name is not a language tag; skipped`);
8987
+ continue;
8988
+ }
8989
+ try {
8990
+ const { ui } = JSON.parse(await readFile(join(dir, name2), "utf8"));
8991
+ if (ui === null || typeof ui !== "object" || Array.isArray(ui)) throw new Error('no "ui" table');
8992
+ locales[tag] = Object.fromEntries(Object.entries(ui).filter(([, text3]) => typeof text3 === "string"));
8993
+ } catch (error) {
8994
+ warn(`locale/${name2}: ${error.message}; skipped`);
8995
+ }
8996
+ }
8997
+ if (locales[BASE] === void 0) warn(`locale/${BASE}.json is missing or unreadable; every language falls back to it`);
8998
+ return locales;
8999
+ }
9000
+
9001
+ // node_modules/@soffits/dsh-host-kit/src/notices.js
9002
+ function createNotices({ settleMs = 0, spacingMs = 0 } = {}) {
9003
+ const listeners = /* @__PURE__ */ new Set();
9004
+ let pending = [];
9005
+ let timer;
9006
+ let lastAt = -Infinity;
9007
+ function flush() {
9008
+ timer = void 0;
9009
+ lastAt = Date.now();
9010
+ const batch = pending;
9011
+ pending = [];
9012
+ for (const listener of [...listeners]) {
9013
+ const what = /* @__PURE__ */ new Set();
9014
+ for (const notice of batch) {
9015
+ if (notice.scope === void 0 || listener.accepts === void 0 || listener.accepts(notice.scope)) what.add(notice.what);
9016
+ }
9017
+ if (what.size > 0) listener.send([...what]);
9018
+ }
9019
+ }
9020
+ return {
9021
+ /**
9022
+ * Something of kind `what` changed, for `scope` (omit for everyone).
9023
+ * @param {string} what
9024
+ * @param {string} [scope]
9025
+ */
9026
+ notify(what, scope) {
9027
+ pending.push({ what, scope });
9028
+ if (timer !== void 0) return;
9029
+ timer = setTimeout(flush, Math.max(settleMs, lastAt + spacingMs - Date.now()));
9030
+ },
9031
+ /**
9032
+ * Hear batches of kinds (`send(['library', 'rooms'])`), only for the scopes `accepts` takes
9033
+ * (omit it to hear every scope).
9034
+ * @param {(what: string[]) => void} send
9035
+ * @param {(scope: string) => boolean} [accepts]
9036
+ * @returns {() => void} stop listening
9037
+ */
9038
+ listen(send, accepts) {
9039
+ const listener = { send, accepts };
9040
+ listeners.add(listener);
9041
+ return () => listeners.delete(listener);
9042
+ },
9043
+ /** Drop every listener and anything pending (the plugin is going away). */
9044
+ close() {
9045
+ clearTimeout(timer);
9046
+ timer = void 0;
9047
+ pending = [];
9048
+ listeners.clear();
9049
+ }
9050
+ };
9051
+ }
9052
+
9053
+ // node_modules/@soffits/dsh-host-kit/src/event-streams.js
9054
+ function createEventStreams({ heartbeatMs = 25e3, headers = {} } = {}) {
9055
+ const open4 = /* @__PURE__ */ new Set();
9056
+ function respond(request, start) {
9057
+ const encoder = new TextEncoder();
9058
+ let finish = () => {
9059
+ };
9060
+ const body2 = new ReadableStream({
9061
+ async start(controller) {
9062
+ let live = true;
9063
+ let stop = () => {
9064
+ };
9065
+ const write2 = (text3) => {
9066
+ if (!live) return;
9067
+ try {
9068
+ controller.enqueue(encoder.encode(text3));
9069
+ } catch {
9070
+ end();
9071
+ }
9072
+ };
9073
+ const beat = setInterval(() => write2(": beat\n\n"), heartbeatMs);
9074
+ finish = () => {
9075
+ if (!live) return;
9076
+ live = false;
9077
+ clearInterval(beat);
9078
+ open4.delete(end);
9079
+ request.signal?.removeEventListener?.("abort", end);
9080
+ stop();
9081
+ };
9082
+ const end = () => {
9083
+ finish();
9084
+ try {
9085
+ controller.close();
9086
+ } catch {
9087
+ }
9088
+ };
9089
+ open4.add(end);
9090
+ request.signal?.addEventListener?.("abort", end, { once: true });
9091
+ if (request.signal?.aborted) return end();
9092
+ write2("retry: 5000\n: open\n\n");
9093
+ let stopping;
9094
+ try {
9095
+ stopping = await start({ send: (value) => write2(`data: ${JSON.stringify(value)}
9096
+
9097
+ `), end });
9098
+ } catch (error) {
9099
+ finish();
9100
+ controller.error(error);
9101
+ return;
9102
+ }
9103
+ if (typeof stopping !== "function") return;
9104
+ if (live) stop = stopping;
9105
+ else stopping();
9106
+ },
9107
+ cancel() {
9108
+ finish();
9109
+ }
9110
+ });
9111
+ return new Response(body2, {
9112
+ status: 200,
9113
+ headers: { ...headers, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no", "x-content-type-options": "nosniff" }
9114
+ });
9115
+ }
9116
+ return {
9117
+ respond,
9118
+ /** End every open stream (the plugin is going away). */
9119
+ close() {
9120
+ for (const end of [...open4]) end();
9121
+ }
9122
+ };
9123
+ }
9124
+
8975
9125
  // node_modules/ws/wrapper.mjs
8976
9126
  var import_stream = __toESM(require_stream(), 1);
8977
9127
  var import_extension = __toESM(require_extension(), 1);
@@ -8985,7 +9135,7 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
8985
9135
  // src/config.js
8986
9136
  import { existsSync } from "node:fs";
8987
9137
  import { homedir } from "node:os";
8988
- import { join as join9 } from "node:path";
9138
+ import { join as join10 } from "node:path";
8989
9139
 
8990
9140
  // node_modules/@deepseek-ai/cosmokit/lib/index.js
8991
9141
  function isNullable(value) {
@@ -9855,6 +10005,11 @@ defineMethod("transform", [
9855
10005
 
9856
10006
  // src/delivery.js
9857
10007
  import { basename } from "node:path";
10008
+
10009
+ // src/errors.js
10010
+ var codedError = (code, message, fields = {}) => Object.assign(new Error(message), { code, ...fields });
10011
+
10012
+ // src/delivery.js
9858
10013
  var PREFIX = "media-hub";
9859
10014
  var DELIVERY_MODES = Object.freeze(["origin", "r2"]);
9860
10015
  function createDelivery({ mode }) {
@@ -9869,11 +10024,11 @@ function createDelivery({ mode }) {
9869
10024
  if (mode === "r2") {
9870
10025
  const reason = 'R2 delivery is not built yet; use delivery mode "origin".';
9871
10026
  const missing = () => {
9872
- throw Object.assign(new Error(reason), { code: "unsupported" });
10027
+ throw codedError("unsupported", reason);
9873
10028
  };
9874
10029
  return { mode, available: false, reason, mediaUrl: missing, subtitleUrl: missing };
9875
10030
  }
9876
- throw Object.assign(new Error(`unknown delivery mode ${String(mode)}`), { code: "invalid" });
10031
+ throw codedError("invalid", `unknown delivery mode ${String(mode)}`);
9877
10032
  }
9878
10033
 
9879
10034
  // src/proxy.js
@@ -10453,8 +10608,7 @@ function omit2(obj, ...keys) {
10453
10608
  }
10454
10609
 
10455
10610
  // src/hosts.js
10456
- import { readFile, stat } from "node:fs/promises";
10457
- var hostsError = (code, message) => Object.assign(new Error(message), { code });
10611
+ import { readFile as readFile2, stat } from "node:fs/promises";
10458
10612
  function hostOf(url) {
10459
10613
  try {
10460
10614
  return new URL(url).hostname.toLowerCase().replace(/\.$/, "");
@@ -10470,7 +10624,7 @@ function hostMatches(host, pattern2) {
10470
10624
  return host === pattern2 || host.endsWith(`.${pattern2}`);
10471
10625
  }
10472
10626
  function createHostRules(rules = [], io = {}) {
10473
- const read = io.read ?? ((path) => readFile(path, "utf8"));
10627
+ const read = io.read ?? ((path) => readFile2(path, "utf8"));
10474
10628
  const version = io.version ?? (async (path) => (await stat(path)).mtimeMs);
10475
10629
  const files = /* @__PURE__ */ new Map();
10476
10630
  async function patternsOf(rule) {
@@ -10481,7 +10635,7 @@ function createHostRules(rules = [], io = {}) {
10481
10635
  if (files.get(rule.hostsFile)?.version !== current) files.set(rule.hostsFile, { version: current, patterns: parseHosts(await read(rule.hostsFile)) });
10482
10636
  } catch (error) {
10483
10637
  files.delete(rule.hostsFile);
10484
- throw hostsError("hosts_unreadable", `cannot read the hosts file ${rule.hostsFile}: ${error.message}`);
10638
+ throw codedError("hosts_unreadable", `cannot read the hosts file ${rule.hostsFile}: ${error.message}`);
10485
10639
  }
10486
10640
  return [...listed2, ...files.get(rule.hostsFile).patterns];
10487
10641
  }
@@ -10507,7 +10661,6 @@ var PROXY_URL = /^(socks4a?|socks5h?|https?):\/\/[^\s/]+\/?$/;
10507
10661
  var MAX_REDIRECTS = 5;
10508
10662
  var USER_AGENT = "dsh-media-hub";
10509
10663
  var PROBE_TIMEOUT_MS = 3e3;
10510
- var proxyError = (code, message) => Object.assign(new Error(message), { code });
10511
10664
  function proxyAnswers(proxy, timeoutMs = PROBE_TIMEOUT_MS) {
10512
10665
  const { hostname, port, protocol } = new URL(proxy);
10513
10666
  const defaultPort = protocol.startsWith("socks") ? 1080 : protocol === "https:" ? 443 : 80;
@@ -10529,7 +10682,7 @@ function createProxies(rules = [], io = {}) {
10529
10682
  try {
10530
10683
  return (await hostRules.match(url, page))?.url ?? "";
10531
10684
  } catch (error) {
10532
- throw proxyError("proxy_unavailable", error.message);
10685
+ throw codedError("proxy_unavailable", error.message);
10533
10686
  }
10534
10687
  }
10535
10688
  function agentFor(proxy) {
@@ -10539,12 +10692,12 @@ function createProxies(rules = [], io = {}) {
10539
10692
  }
10540
10693
  async function get(url, page, timeoutMs) {
10541
10694
  const protocol = new URL(url).protocol;
10542
- if (protocol !== "https:" && protocol !== "http:") throw proxyError("invalid", `not a web address: ${url}`);
10695
+ if (protocol !== "https:" && protocol !== "http:") throw codedError("invalid", `not a web address: ${url}`);
10543
10696
  const agent = agentFor(await route(url, page));
10544
10697
  return new Promise((resolve8, reject) => {
10545
10698
  const send = protocol === "https:" ? httpsRequest : httpRequest;
10546
10699
  const req = send(url, { agent, headers: { "user-agent": USER_AGENT, accept: "image/*,*/*;q=0.5" }, timeout: timeoutMs }, resolve8);
10547
- req.on("timeout", () => req.destroy(proxyError("timeout", `no answer from ${hostOf(url)} in ${timeoutMs / 1e3} s`)));
10700
+ req.on("timeout", () => req.destroy(codedError("timeout", `no answer from ${hostOf(url)} in ${timeoutMs / 1e3} s`)));
10548
10701
  req.on("error", reject);
10549
10702
  req.end();
10550
10703
  });
@@ -10567,44 +10720,41 @@ function createProxies(rules = [], io = {}) {
10567
10720
  }
10568
10721
  if (statusCode !== 200) {
10569
10722
  response.resume();
10570
- throw proxyError("fetch_failed", `${hostOf(target)} answered ${statusCode}`);
10723
+ throw codedError("fetch_failed", `${hostOf(target)} answered ${statusCode}`);
10571
10724
  }
10572
10725
  if (Number(headers["content-length"]) > maxBytes) {
10573
10726
  response.destroy();
10574
- throw proxyError("too_large", `the file is over ${maxBytes} bytes`);
10727
+ throw codedError("too_large", `the file is over ${maxBytes} bytes`);
10575
10728
  }
10576
10729
  let received = 0;
10577
10730
  response.on("data", (chunk) => {
10578
10731
  received += chunk.length;
10579
- if (received > maxBytes) response.destroy(proxyError("too_large", `the file is over ${maxBytes} bytes`));
10732
+ if (received > maxBytes) response.destroy(codedError("too_large", `the file is over ${maxBytes} bytes`));
10580
10733
  });
10581
10734
  await pipeline(response, createWriteStream(file));
10582
10735
  return;
10583
10736
  }
10584
- throw proxyError("fetch_failed", `more than ${MAX_REDIRECTS} redirects from ${hostOf(url)}`);
10737
+ throw codedError("fetch_failed", `more than ${MAX_REDIRECTS} redirects from ${hostOf(url)}`);
10585
10738
  }
10586
10739
  };
10587
10740
  }
10588
10741
 
10589
10742
  // src/sources/command.js
10590
- import { createHash } from "node:crypto";
10591
- import { createReadStream } from "node:fs";
10592
10743
  import { mkdir, rm, stat as stat2 } from "node:fs/promises";
10593
- import { basename as basename2, join as join2 } from "node:path";
10744
+ import { basename as basename2, join as join3 } from "node:path";
10594
10745
 
10595
10746
  // src/i18n.js
10596
- var BASE = "en";
10597
- var TAG = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i;
10598
- function chain(tag) {
10747
+ var BASE2 = "en";
10748
+ function chain2(tag) {
10599
10749
  const parts = String(tag ?? "").toLowerCase().split("-").filter(Boolean);
10600
10750
  const tags = parts.map((_, i) => parts.slice(0, parts.length - i).join("-"));
10601
- return tags.includes(BASE) ? tags : [...tags, BASE];
10751
+ return tags.includes(BASE2) ? tags : [...tags, BASE2];
10602
10752
  }
10603
10753
  function pick2(value, tag) {
10604
10754
  if (typeof value === "string") return value;
10605
10755
  if (value === null || typeof value !== "object") return "";
10606
10756
  const byTag = new Map(Object.entries(value).map(([key, text3]) => [key.toLowerCase(), text3]));
10607
- for (const candidate of chain(tag)) {
10757
+ for (const candidate of chain2(tag)) {
10608
10758
  const text3 = byTag.get(candidate);
10609
10759
  if (typeof text3 === "string" && text3 !== "") return text3;
10610
10760
  }
@@ -10642,14 +10792,23 @@ function heightChoices(raw) {
10642
10792
  return heights.length > 1 ? [AUTO, ...heights] : [];
10643
10793
  }
10644
10794
 
10795
+ // src/sha256.js
10796
+ import { createHash } from "node:crypto";
10797
+ import { createReadStream } from "node:fs";
10798
+ function sha256Of(path) {
10799
+ return new Promise((resolve8, reject) => {
10800
+ const hash = createHash("sha256");
10801
+ createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve8(hash.digest("hex")));
10802
+ });
10803
+ }
10804
+
10645
10805
  // src/sources/process.js
10646
10806
  import { spawn } from "node:child_process";
10647
10807
  import { access, constants } from "node:fs/promises";
10648
- import { delimiter, isAbsolute, join } from "node:path";
10808
+ import { delimiter, isAbsolute, join as join2 } from "node:path";
10649
10809
  var MAX_OUTPUT = 16 * 1024 * 1024;
10650
- var sourceError = (code, message) => Object.assign(new Error(message), { code });
10651
10810
  async function commandExists(command, path = process.env.PATH ?? "") {
10652
- const candidates = isAbsolute(command) ? [command] : path.split(delimiter).filter(Boolean).map((dir) => join(dir, command));
10811
+ const candidates = isAbsolute(command) ? [command] : path.split(delimiter).filter(Boolean).map((dir) => join2(dir, command));
10653
10812
  for (const candidate of candidates) {
10654
10813
  try {
10655
10814
  await access(candidate, constants.X_OK);
@@ -10699,7 +10858,7 @@ function run(argv, { signal, timeoutMs, onStdoutLine, cwd, env, input } = {}) {
10699
10858
  });
10700
10859
  child.on("error", (error) => {
10701
10860
  if (timer) clearTimeout(timer);
10702
- reject(error.code === "ENOENT" ? sourceError("unavailable", `${command} is not installed`) : error);
10861
+ reject(error.code === "ENOENT" ? codedError("unavailable", `${command} is not installed`) : error);
10703
10862
  });
10704
10863
  child.on("close", (code) => {
10705
10864
  if (timer) clearTimeout(timer);
@@ -10725,7 +10884,6 @@ var TRENDING_LIMIT = 20;
10725
10884
  var QUERY_TIMEOUT_MS = 6e4;
10726
10885
  var COVER_TIMEOUT_MS = 3e4;
10727
10886
  var ID = /^[^\s\0]{1,200}$/;
10728
- var sourceError2 = (code, message) => Object.assign(new Error(message), { code });
10729
10887
  var text = (value) => typeof value === "string" || typeof value === "number" ? String(value).trim() : "";
10730
10888
  var numberOrNull = (value) => Number.isFinite(value) ? value : null;
10731
10889
  var STATUSES = /* @__PURE__ */ new Set(["finished", "ongoing", "stopped"]);
@@ -10785,7 +10943,7 @@ function resultOf(raw, kindIds) {
10785
10943
  return { id, title: text(raw.title), kind, author: text(raw.author), score: numberOrNull(raw.score), blurb: text(raw.blurb).replace(/\s+/g, " "), episodes: countOrNull(raw.episode_count), ...factsOf(raw) };
10786
10944
  }
10787
10945
  function parseSearch(document2, kinds) {
10788
- if (!Array.isArray(document2?.results)) throw sourceError2("source_failed", "the search answer has no results list");
10946
+ if (!Array.isArray(document2?.results)) throw codedError("source_failed", "the search answer has no results list");
10789
10947
  const kindIds = new Set(kinds.map((kind) => kind.id));
10790
10948
  return document2.results.map((raw) => resultOf(raw, kindIds)).filter((result) => result !== null);
10791
10949
  }
@@ -10801,7 +10959,7 @@ function labelOf(value) {
10801
10959
  function parseTrending(document2, kinds, kind) {
10802
10960
  const kindIds = new Set(kinds.map((entry) => entry.id));
10803
10961
  const raw = Array.isArray(document2?.lists) ? document2.lists : Array.isArray(document2?.results) ? [{ id: "trending", results: document2.results }] : null;
10804
- if (raw === null) throw sourceError2("source_failed", "the trending answer has no lists");
10962
+ if (raw === null) throw codedError("source_failed", "the trending answer has no lists");
10805
10963
  const seen = /* @__PURE__ */ new Set();
10806
10964
  return raw.slice(0, MAX_LISTS).flatMap((list, index) => {
10807
10965
  const results = Array.isArray(list?.results) ? list.results.map((item) => resultOf(item, kindIds)).filter((result) => result !== null && result.kind === kind) : [];
@@ -10816,7 +10974,7 @@ function nextOffset(document2, offset = 0) {
10816
10974
  }
10817
10975
  function parseInfo(document2) {
10818
10976
  const id = text(document2?.id);
10819
- if (!ID.test(id)) throw sourceError2("source_failed", "the source returned no work");
10977
+ if (!ID.test(id)) throw codedError("source_failed", "the source returned no work");
10820
10978
  const listed2 = Array.isArray(document2.episodes) ? document2.episodes.length : 0;
10821
10979
  const related = (Array.isArray(document2.related) ? document2.related : []).map((raw) => {
10822
10980
  const work = resultOf(raw, null);
@@ -10833,12 +10991,12 @@ var COMMENTS_PAGE = 20;
10833
10991
  var count = (value) => Number.isInteger(value) && value >= 0 ? value : 0;
10834
10992
  function parseDanmaku(lines, number) {
10835
10993
  const found = lines.find((line) => line?.episode === number) ?? (lines.length === 1 ? lines[0] : null);
10836
- if (!Array.isArray(found?.items)) throw sourceError2("source_failed", "the danmaku answer has no items");
10994
+ if (!Array.isArray(found?.items)) throw codedError("source_failed", "the danmaku answer has no items");
10837
10995
  return found.items.map((raw) => ({ time: Number.isFinite(raw?.time) && raw.time >= 0 ? raw.time : null, text: text(raw?.text).replace(/\s+/g, " ").slice(0, MAX_DANMAKU_TEXT), likes: count(raw?.likes) })).filter((item) => item.time !== null && item.text !== "").sort((a, b) => a.time - b.time).slice(0, MAX_DANMAKU);
10838
10996
  }
10839
10997
  var ISO_TIME = (value) => typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
10840
10998
  function parseComments(document2) {
10841
- if (!Array.isArray(document2?.items)) throw sourceError2("source_failed", "the comments answer has no items");
10999
+ if (!Array.isArray(document2?.items)) throw codedError("source_failed", "the comments answer has no items");
10842
11000
  const items = document2.items.map((raw) => ({
10843
11001
  id: text(raw?.id),
10844
11002
  name: text(raw?.user?.name ?? raw?.name),
@@ -10851,16 +11009,10 @@ function parseComments(document2) {
10851
11009
  const next = text(document2.next_cursor ?? document2.next);
10852
11010
  return { total: countOrNull(document2.total), items, next: next !== "" && next.length <= MAX_CURSOR && items.length > 0 ? next : null };
10853
11011
  }
10854
- function sha256Of(path) {
10855
- return new Promise((resolve8, reject) => {
10856
- const hash = createHash("sha256");
10857
- createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve8(hash.digest("hex")));
10858
- });
10859
- }
10860
11012
  async function verify(dir, event, label, logger) {
10861
11013
  const name2 = typeof event.name === "string" ? event.name : "";
10862
11014
  if (name2 === "" || basename2(name2) !== name2 || name2.startsWith(".")) return { ok: false, name: name2 };
10863
- const path = join2(dir, name2);
11015
+ const path = join3(dir, name2);
10864
11016
  try {
10865
11017
  const intact = (await stat2(path)).size === event.bytes && (typeof event.sha256 !== "string" || await sha256Of(path) === event.sha256);
10866
11018
  if (intact) return { ok: true, name: name2 };
@@ -10886,15 +11038,15 @@ function filterArgs({ language = "", format = "", yearFrom = null, yearTo = null
10886
11038
  function createCommandSource(definition, { logger, cwd }) {
10887
11039
  const { id: sourceId, label, kinds, command, env = {}, filters: understood = [] } = definition;
10888
11040
  const kindIds = new Set(kinds.map((kind) => kind.id));
10889
- const name2 = () => pick2(label, BASE) || sourceId;
11041
+ const name2 = () => pick2(label, BASE2) || sourceId;
10890
11042
  async function workDir() {
10891
11043
  await mkdir(cwd, { recursive: true });
10892
11044
  return cwd;
10893
11045
  }
10894
11046
  async function answer(args) {
10895
11047
  const { code, stdout, stderr, oversized } = await run([...command, ...args], { timeoutMs: QUERY_TIMEOUT_MS, cwd: await workDir(), env });
10896
- if (oversized) throw sourceError2("source_failed", `${name2()}: the answer is too large`);
10897
- if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
11048
+ if (oversized) throw codedError("source_failed", `${name2()}: the answer is too large`);
11049
+ if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10898
11050
  return stdout;
10899
11051
  }
10900
11052
  async function query(args) {
@@ -10902,12 +11054,12 @@ function createCommandSource(definition, { logger, cwd }) {
10902
11054
  try {
10903
11055
  return JSON.parse(stdout);
10904
11056
  } catch {
10905
- throw sourceError2("source_failed", `${name2()}: the answer is not JSON`);
11057
+ throw codedError("source_failed", `${name2()}: the answer is not JSON`);
10906
11058
  }
10907
11059
  }
10908
11060
  const offers = (kind, verb) => kinds.some((entry) => entry.id === kind && entry[verb] === true);
10909
11061
  const checkId = (id) => {
10910
- if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
11062
+ if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
10911
11063
  };
10912
11064
  return {
10913
11065
  id: sourceId,
@@ -10917,7 +11069,7 @@ function createCommandSource(definition, { logger, cwd }) {
10917
11069
  available: () => commandExists(command[0]),
10918
11070
  /** @returns {{ results: object[], next: number | null }} `next` is the offset of the following page when the source offers one. */
10919
11071
  async search(textQuery, { kind = kinds[0]?.id, limit = SEARCH_LIMIT, offset = 0, filters = {} } = {}) {
10920
- if (!kindIds.has(kind)) throw sourceError2("invalid", `${name2()} has no kind ${kind}`);
11072
+ if (!kindIds.has(kind)) throw codedError("invalid", `${name2()} has no kind ${kind}`);
10921
11073
  const q = String(textQuery ?? "").trim();
10922
11074
  if (q === "") return { results: [], next: null };
10923
11075
  const paging = offset > 0 ? ["--offset", String(offset)] : [];
@@ -10926,36 +11078,36 @@ function createCommandSource(definition, { logger, cwd }) {
10926
11078
  },
10927
11079
  /** What the site itself puts forward for a kind that declares `trending`: lists of works, in the site's order. */
10928
11080
  async trending(kind, { limit = TRENDING_LIMIT } = {}) {
10929
- if (!kinds.some((entry) => entry.id === kind && entry.trending === true)) throw sourceError2("invalid", `${name2()} has no trending list for ${kind}`);
11081
+ if (!kinds.some((entry) => entry.id === kind && entry.trending === true)) throw codedError("invalid", `${name2()} has no trending list for ${kind}`);
10930
11082
  return parseTrending(await query(["trending", "--kind", kind, "--limit", String(limit), "--json"]), kinds, kind);
10931
11083
  },
10932
11084
  async info(id) {
10933
- if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
11085
+ if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
10934
11086
  return parseInfo(await query(["info", "--json", "--", String(id)]));
10935
11087
  },
10936
11088
  /** Fetch a cover image into `file` through the command, which keeps its own network policy. Rejects when the command has no `cover` verb or cannot fetch it. */
10937
11089
  async cover(url, file) {
10938
- if (!WEB_URL.test(String(url))) throw sourceError2("invalid", "not a cover url");
11090
+ if (!WEB_URL.test(String(url))) throw codedError("invalid", "not a cover url");
10939
11091
  const { code, stderr } = await run([...command, "cover", "--output", file, "--", String(url)], { timeoutMs: COVER_TIMEOUT_MS, cwd: await workDir(), env });
10940
- if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
11092
+ if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10941
11093
  },
10942
11094
  offers,
10943
11095
  /** The danmaku of episode `number` of a work of a kind that declares `danmaku`: `[{ time, text, likes }]`. */
10944
11096
  async danmaku(id, number, kind) {
10945
11097
  checkId(id);
10946
- if (!offers(kind, "danmaku") || !Number.isInteger(number) || number < 1) throw sourceError2("invalid", `${name2()} has no danmaku for this`);
11098
+ if (!offers(kind, "danmaku") || !Number.isInteger(number) || number < 1) throw codedError("invalid", `${name2()} has no danmaku for this`);
10947
11099
  const lines = (await answer(["danmaku", "--episodes", String(number), "--json", "--", String(id)])).split("\n").map(parseLine).filter((line) => line !== null);
10948
11100
  return parseDanmaku(lines, number);
10949
11101
  },
10950
11102
  /** A page of the comments on a work of a kind that declares `comments`; `cursor` continues where an earlier page's `next` left off. */
10951
11103
  async comments(id, kind, { cursor = "", limit = COMMENTS_PAGE } = {}) {
10952
11104
  checkId(id);
10953
- if (!offers(kind, "comments")) throw sourceError2("invalid", `${name2()} has no comments for this`);
11105
+ if (!offers(kind, "comments")) throw codedError("invalid", `${name2()} has no comments for this`);
10954
11106
  const paging = cursor === "" ? [] : ["--cursor", String(cursor).slice(0, MAX_CURSOR)];
10955
11107
  return parseComments(await query(["comments", "--limit", String(limit), ...paging, "--json", "--", String(id)]));
10956
11108
  },
10957
11109
  async download({ id, dir, from: from2 = 1, to = null, quality = "", signal, onEpisode, onStart, onPartial }) {
10958
- if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
11110
+ if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
10959
11111
  const failed = [];
10960
11112
  let result = null;
10961
11113
  let checking = Promise.resolve();
@@ -10974,7 +11126,7 @@ function createCommandSource(definition, { logger, cwd }) {
10974
11126
  const names = Array.isArray(event.files) ? event.files.filter((file) => typeof file === "string" && file !== "" && basename2(file) === file) : [];
10975
11127
  if (names.length === 0) return;
10976
11128
  const until = new Promise((done) => growing.set(event.number, done));
10977
- onPartial?.(event.number, { files: names.map((file) => join2(dir, file)), subtitles: [], growing: until });
11129
+ onPartial?.(event.number, { files: names.map((file) => join3(dir, file)), subtitles: [], growing: until });
10978
11130
  } else if (event?.event === "done") {
10979
11131
  if (Number.isInteger(event.number)) settle2(event.number);
10980
11132
  checking = checking.then(() => verify(dir, event, name2(), logger)).then((file) => {
@@ -10994,9 +11146,9 @@ function createCommandSource(definition, { logger, cwd }) {
10994
11146
  if (signal?.aborted) return { failed };
10995
11147
  if (code !== 0 && failed.length === 0) {
10996
11148
  logger.warn("%s download %s ended with %s: %s", name2(), id, code, lastLine(stderr));
10997
- throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
11149
+ throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
10998
11150
  }
10999
- if (code === 0 && result === null) throw sourceError2("source_failed", `${name2()}: the download ended without a result`);
11151
+ if (code === 0 && result === null) throw codedError("source_failed", `${name2()}: the download ended without a result`);
11000
11152
  return { failed };
11001
11153
  },
11002
11154
  /**
@@ -11004,8 +11156,8 @@ function createCommandSource(definition, { logger, cwd }) {
11004
11156
  * @returns {Promise<{ name: string, bytes: number, sha256: string }>} the file, checked against what the command reported
11005
11157
  */
11006
11158
  async downloadFile({ id, format, dir, signal }) {
11007
- if (!ID.test(String(id))) throw sourceError2("invalid", `not a ${name2()} id`);
11008
- if (!FORMAT.test(String(format))) throw sourceError2("invalid", `not a format: ${format}`);
11159
+ if (!ID.test(String(id))) throw codedError("invalid", `not a ${name2()} id`);
11160
+ if (!FORMAT.test(String(format))) throw codedError("invalid", `not a format: ${format}`);
11009
11161
  await mkdir(dir, { recursive: true });
11010
11162
  const reported = [];
11011
11163
  let result = null;
@@ -11016,27 +11168,27 @@ function createCommandSource(definition, { logger, cwd }) {
11016
11168
  };
11017
11169
  const argv = [...command, "download", `--id=${String(id)}`, "--format", String(format), "--output", dir, "--json"];
11018
11170
  const { code, stderr } = await run(argv, { signal, cwd: await workDir(), env, onStdoutLine: onLine });
11019
- if (signal?.aborted) throw sourceError2("cancelled", `${name2()}: cancelled`);
11020
- if (code !== 0) throw sourceError2("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
11021
- if (result === null || reported.length === 0) throw sourceError2("source_failed", `${name2()}: the download ended without a file`);
11171
+ if (signal?.aborted) throw codedError("cancelled", `${name2()}: cancelled`);
11172
+ if (code !== 0) throw codedError("source_failed", `${name2()}: ${lastLine(stderr) || `exit ${code}`}`);
11173
+ if (result === null || reported.length === 0) throw codedError("source_failed", `${name2()}: the download ended without a file`);
11022
11174
  const event = reported[reported.length - 1];
11023
11175
  const file = await verify(dir, event, name2(), logger);
11024
- if (!file.ok) throw sourceError2("source_failed", `${name2()}: the file did not arrive whole`);
11025
- return { name: file.name, bytes: event.bytes, sha256: typeof event.sha256 === "string" ? event.sha256 : await sha256Of(join2(dir, file.name)) };
11176
+ if (!file.ok) throw codedError("source_failed", `${name2()}: the file did not arrive whole`);
11177
+ return { name: file.name, bytes: event.bytes, sha256: typeof event.sha256 === "string" ? event.sha256 : await sha256Of(join3(dir, file.name)) };
11026
11178
  }
11027
11179
  };
11028
11180
  }
11029
11181
 
11030
11182
  // src/sources/index.js
11031
- import { join as join8 } from "node:path";
11183
+ import { join as join9 } from "node:path";
11032
11184
 
11033
11185
  // src/sources/link.js
11034
- import { mkdir as mkdir5, readdir as readdir3, rename as rename2, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
11035
- import { dirname as dirname2, extname as extname4, join as join7 } from "node:path";
11186
+ import { mkdir as mkdir5, readdir as readdir4, rename as rename2, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
11187
+ import { dirname as dirname2, extname as extname4, join as join8 } from "node:path";
11036
11188
 
11037
11189
  // src/captions.js
11038
11190
  var MARKS = Object.freeze(["auto", "original"]);
11039
- var known = new Intl.DisplayNames([BASE], { type: "language", fallback: "none" });
11191
+ var known = new Intl.DisplayNames([BASE2], { type: "language", fallback: "none" });
11040
11192
  function captionLanguage(tag) {
11041
11193
  try {
11042
11194
  const { language } = new Intl.Locale(tag);
@@ -11104,8 +11256,8 @@ function noteFor(entry, notes, name2) {
11104
11256
  }
11105
11257
 
11106
11258
  // src/library.js
11107
- import { open, readdir, stat as stat3 } from "node:fs/promises";
11108
- import { basename as basename4, dirname, extname as extname2, join as join3 } from "node:path";
11259
+ import { open, readdir as readdir2, stat as stat3 } from "node:fs/promises";
11260
+ import { basename as basename4, dirname, extname as extname2, join as join4 } from "node:path";
11109
11261
  import { execFile } from "node:child_process";
11110
11262
  import { promisify } from "node:util";
11111
11263
  var run2 = promisify(execFile);
@@ -11139,13 +11291,13 @@ var titleOf2 = (file) => basename4(file, extname2(file));
11139
11291
  async function scanSource(path) {
11140
11292
  const info = await stat3(path);
11141
11293
  const folder = info.isDirectory() ? path : dirname(path);
11142
- const names = await readdir(folder);
11294
+ const names = await readdir2(folder);
11143
11295
  const videos = info.isDirectory() ? naturalSort(names.filter(isMedia)) : [basename4(path)];
11144
- if (videos.length === 0) throw Object.assign(new Error(`no video or audio files in ${path}`), { code: "empty" });
11296
+ if (videos.length === 0) throw codedError("empty", `no video or audio files in ${path}`);
11145
11297
  return videos.map((name2) => ({
11146
11298
  title: titleOf2(name2),
11147
- path: join3(folder, name2),
11148
- subtitles: matchSubtitles(name2, names).map((sub) => ({ path: join3(folder, sub.name), label: sub.label }))
11299
+ path: join4(folder, name2),
11300
+ subtitles: matchSubtitles(name2, names).map((sub) => ({ path: join4(folder, sub.name), label: sub.label }))
11149
11301
  }));
11150
11302
  }
11151
11303
  async function probe(path, { ffprobe = "ffprobe" } = {}) {
@@ -11208,8 +11360,7 @@ function planVideo(path, info, { fastStart, maxHeight }) {
11208
11360
  // src/cookies.js
11209
11361
  import { randomBytes } from "node:crypto";
11210
11362
  import { copyFile, chmod, mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
11211
- import { join as join4 } from "node:path";
11212
- var cookiesError = (code, message) => Object.assign(new Error(message), { code });
11363
+ import { join as join5 } from "node:path";
11213
11364
  var accountView = (account) => account === null ? null : { name: account.name || account.person || "" };
11214
11365
  function createCookies(rules = [], io = {}) {
11215
11366
  const hostRules = createHostRules(rules, io);
@@ -11231,13 +11382,13 @@ function createCookies(rules = [], io = {}) {
11231
11382
  if (account === null) return { args: [], done: async () => {
11232
11383
  } };
11233
11384
  await mkdir2(dir, { recursive: true });
11234
- const copy = join4(dir, `.cookies-${randomBytes(6).toString("hex")}.txt`);
11385
+ const copy = join5(dir, `.cookies-${randomBytes(6).toString("hex")}.txt`);
11235
11386
  try {
11236
11387
  await copyFile(account.file, copy);
11237
11388
  await chmod(copy, 384);
11238
11389
  } catch (error) {
11239
11390
  await rm2(copy, { force: true });
11240
- throw cookiesError("cookies_unavailable", `cannot read the cookies of the account ${accountView(account).name}: ${error.code ?? error.message}`);
11391
+ throw codedError("cookies_unavailable", `cannot read the cookies of the account ${accountView(account).name}: ${error.code ?? error.message}`);
11241
11392
  }
11242
11393
  const args = ["--cookies", copy, ...account.userAgent ? ["--user-agent", account.userAgent] : []];
11243
11394
  return { args, done: () => rm2(copy, { force: true }) };
@@ -11248,14 +11399,14 @@ function createCookies(rules = [], io = {}) {
11248
11399
  // src/prepare.js
11249
11400
  import { spawn as spawn3 } from "node:child_process";
11250
11401
  import { createHash as createHash3 } from "node:crypto";
11251
- import { mkdir as mkdir4, readFile as readFile3, readdir as readdir2, rename, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
11252
- import { extname as extname3, join as join6 } from "node:path";
11402
+ import { mkdir as mkdir4, readFile as readFile4, readdir as readdir3, rename, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
11403
+ import { extname as extname3, join as join7 } from "node:path";
11253
11404
 
11254
11405
  // src/stream.js
11255
11406
  import { spawn as spawn2 } from "node:child_process";
11256
11407
  import { createHash as createHash2 } from "node:crypto";
11257
- import { mkdir as mkdir3, open as open2, readFile as readFile2, rm as rm3, stat as stat4 } from "node:fs/promises";
11258
- import { join as join5 } from "node:path";
11408
+ import { mkdir as mkdir3, open as open2, readFile as readFile3, rm as rm3, stat as stat4 } from "node:fs/promises";
11409
+ import { join as join6 } from "node:path";
11259
11410
  import { Readable } from "node:stream";
11260
11411
  var PLAYLIST = "index.m3u8";
11261
11412
  var READY_SEGMENTS = 3;
@@ -11350,8 +11501,8 @@ function hlsArgs(plan, inputs, dir, { maxHeight = 1080, threads = 2 } = {}) {
11350
11501
  "-hls_flags",
11351
11502
  "independent_segments+temp_file",
11352
11503
  "-hls_segment_filename",
11353
- join5(dir, "%05d.m4s"),
11354
- join5(dir, PLAYLIST)
11504
+ join6(dir, "%05d.m4s"),
11505
+ join6(dir, PLAYLIST)
11355
11506
  ];
11356
11507
  }
11357
11508
  async function probeGrowing(file, ended, { ffprobe, signal }) {
@@ -11373,8 +11524,8 @@ function playable(text3) {
11373
11524
  return text3.includes("#EXT-X-ENDLIST") || (text3.match(/#EXTINF:/g) ?? []).length >= READY_SEGMENTS;
11374
11525
  }
11375
11526
  async function finishedPlaylist(dir) {
11376
- const file = join5(dir, PLAYLIST);
11377
- const text3 = await readFile2(file, "utf8").catch(() => "");
11527
+ const file = join6(dir, PLAYLIST);
11528
+ const text3 = await readFile3(file, "utf8").catch(() => "");
11378
11529
  return text3.includes("#EXT-X-ENDLIST") ? file : null;
11379
11530
  }
11380
11531
  async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe = "ffprobe", maxHeight = 1080, threads = 2, onReady, signal }) {
@@ -11388,7 +11539,7 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11388
11539
  const duration = Math.max(0, ...infos.map((info) => info.duration ?? 0)) || null;
11389
11540
  const inputs = growing === void 0 ? files : files.map((_, n) => `pipe:${n + 3}`);
11390
11541
  const args = hlsArgs(plan, inputs, dir, { maxHeight, threads });
11391
- const playlist = join5(dir, PLAYLIST);
11542
+ const playlist = join6(dir, PLAYLIST);
11392
11543
  const child = spawn2("nice", ["-n", "10", ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", ...args], {
11393
11544
  stdio: ["ignore", "ignore", "pipe", ...growing === void 0 ? [] : files.map(() => "pipe")],
11394
11545
  signal
@@ -11414,7 +11565,7 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11414
11565
  const running = settledFlag(exited);
11415
11566
  let told = false;
11416
11567
  while (!running.done && !told) {
11417
- if (playable(await readFile2(playlist, "utf8").catch(() => ""))) {
11568
+ if (playable(await readFile3(playlist, "utf8").catch(() => ""))) {
11418
11569
  told = true;
11419
11570
  onReady?.({ playlist, duration });
11420
11571
  } else {
@@ -11433,7 +11584,7 @@ function createStreams({ cacheDir, tools, need, ready, lost, logger, convert })
11433
11584
  function start(key, entry) {
11434
11585
  const { show, number, partial: { files, subtitles = [], growing } } = entry;
11435
11586
  const controller = new AbortController();
11436
- const dir = join5(cacheDir, `stream-${createHash2("sha256").update(`${key}\0${Date.now()}`).digest("hex").slice(0, 20)}`);
11587
+ const dir = join6(cacheDir, `stream-${createHash2("sha256").update(`${key}\0${Date.now()}`).digest("hex").slice(0, 20)}`);
11437
11588
  entry.controller = controller;
11438
11589
  entry.prepared = null;
11439
11590
  streamEpisode({
@@ -11539,12 +11690,12 @@ async function preparedBytes(cacheDir, path) {
11539
11690
  const key = await cacheKey(path).catch(() => null);
11540
11691
  if (key === null) return 0;
11541
11692
  let total = 0;
11542
- for (const name2 of await readdir2(join6(cacheDir, key)).catch(() => [])) total += (await stat5(join6(cacheDir, key, name2)).catch(() => null))?.size ?? 0;
11693
+ for (const name2 of await readdir3(join7(cacheDir, key)).catch(() => [])) total += (await stat5(join7(cacheDir, key, name2)).catch(() => null))?.size ?? 0;
11543
11694
  return total;
11544
11695
  }
11545
11696
  async function dropPrepared(cacheDir, path) {
11546
11697
  const key = await cacheKey(path).catch(() => null);
11547
- if (key !== null) await rm4(join6(cacheDir, key), { recursive: true, force: true });
11698
+ if (key !== null) await rm4(join7(cacheDir, key), { recursive: true, force: true });
11548
11699
  }
11549
11700
  function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11550
11701
  return new Promise((resolve8, reject) => {
@@ -11568,14 +11719,14 @@ async function writeAtomic(path, data) {
11568
11719
  }
11569
11720
  var exists = (path) => stat5(path).then(() => true, () => false);
11570
11721
  async function convertSubtitle(source, dir, name2, { ffmpeg = "ffmpeg" } = {}) {
11571
- const out = join6(dir, `${name2}.vtt`);
11722
+ const out = join7(dir, `${name2}.vtt`);
11572
11723
  if (await exists(out)) return out;
11573
- const text3 = decodeText(await readFile3(source));
11724
+ const text3 = decodeText(await readFile4(source));
11574
11725
  const ext = extname3(source).toLowerCase();
11575
11726
  if (ext === ".srt") await writeAtomic(out, srtToVtt(text3));
11576
11727
  else if (ext === ".vtt" || isVtt(text3)) await writeAtomic(out, text3);
11577
11728
  else {
11578
- const utf8 = join6(dir, `${name2}.utf8${ext}`);
11729
+ const utf8 = join7(dir, `${name2}.utf8${ext}`);
11579
11730
  await writeFile(utf8, text3);
11580
11731
  try {
11581
11732
  await runFfmpeg(["-y", "-i", utf8, "-f", "webvtt", `${out}.part`], { ffmpeg, duration: null });
@@ -11591,7 +11742,7 @@ async function prepareEpisode(episode, options) {
11591
11742
  if (extname3(episode.path).toLowerCase() === ".m3u8") {
11592
11743
  return { file: episode.path, kind: "hls", duration: null, plan: "direct", subtitles: await externalSubtitles(episode, null, ffmpeg, cacheDir) };
11593
11744
  }
11594
- const dir = join6(cacheDir, await cacheKey(episode.path));
11745
+ const dir = join7(cacheDir, await cacheKey(episode.path));
11595
11746
  await mkdir4(dir, { recursive: true });
11596
11747
  const info = await probe(episode.path, { ffprobe });
11597
11748
  const mp4Family = [".mp4", ".m4v", ".mov", ".m4a"].includes(extname3(episode.path).toLowerCase());
@@ -11599,7 +11750,7 @@ async function prepareEpisode(episode, options) {
11599
11750
  const subtitles = await externalSubtitles(episode, dir, ffmpeg, cacheDir);
11600
11751
  await embeddedSubtitles(episode.path, info, dir, ffmpeg, subtitles);
11601
11752
  if (plan === "transcode") {
11602
- const hls = join6(dir, "hls");
11753
+ const hls = join7(dir, "hls");
11603
11754
  const prepared = (file2) => ({ file: file2, kind: "hls", duration: info.duration, plan, subtitles });
11604
11755
  const done = await finishedPlaylist(hls);
11605
11756
  if (done !== null) return prepared(done);
@@ -11608,7 +11759,7 @@ async function prepareEpisode(episode, options) {
11608
11759
  }
11609
11760
  let file = episode.path;
11610
11761
  if (plan === "remux") {
11611
- file = join6(dir, "video.mp4");
11762
+ file = join7(dir, "video.mp4");
11612
11763
  if (!await exists(file)) {
11613
11764
  await runFfmpeg(remuxArgs(episode.path, `${file}.part`), { ffmpeg, duration: info.duration, onProgress, signal });
11614
11765
  await rename(`${file}.part`, file);
@@ -11618,7 +11769,7 @@ async function prepareEpisode(episode, options) {
11618
11769
  }
11619
11770
  async function embeddedSubtitles(path, info, dir, ffmpeg, subtitles) {
11620
11771
  for (const stream of info.subtitles.filter((s) => isTextSubtitle(s.codec))) {
11621
- const out = join6(dir, `embedded-${stream.index}.vtt`);
11772
+ const out = join7(dir, `embedded-${stream.index}.vtt`);
11622
11773
  if (!await exists(out)) {
11623
11774
  try {
11624
11775
  await runFfmpeg(["-y", "-i", path, "-map", `0:s:${stream.index}`, "-f", "webvtt", `${out}.part`], { ffmpeg, duration: null });
@@ -11632,7 +11783,7 @@ async function embeddedSubtitles(path, info, dir, ffmpeg, subtitles) {
11632
11783
  }
11633
11784
  async function externalSubtitles(episode, dir, ffmpeg, cacheDir) {
11634
11785
  if (episode.subtitles.length === 0) return [];
11635
- const target = dir ?? join6(cacheDir, await cacheKey(episode.path));
11786
+ const target = dir ?? join7(cacheDir, await cacheKey(episode.path));
11636
11787
  await mkdir4(target, { recursive: true });
11637
11788
  const out = [];
11638
11789
  for (const [n, sub] of episode.subtitles.entries()) {
@@ -11645,10 +11796,10 @@ async function externalSubtitles(episode, dir, ffmpeg, cacheDir) {
11645
11796
  }
11646
11797
  async function pruneCache(cacheDir, used, days, now = Date.now()) {
11647
11798
  const keep = new Set(used.filter((file) => typeof file === "string" && file.startsWith(`${cacheDir}/`)).map((file) => file.slice(cacheDir.length + 1).split("/")[0]));
11648
- for (const name2 of await readdir2(cacheDir).catch(() => [])) {
11799
+ for (const name2 of await readdir3(cacheDir).catch(() => [])) {
11649
11800
  if (keep.has(name2)) continue;
11650
- const info = await stat5(join6(cacheDir, name2)).catch(() => null);
11651
- if (info !== null && now - info.mtimeMs > days * 864e5) await rm4(join6(cacheDir, name2), { recursive: true, force: true });
11801
+ const info = await stat5(join7(cacheDir, name2)).catch(() => null);
11802
+ if (info !== null && now - info.mtimeMs > days * 864e5) await rm4(join7(cacheDir, name2), { recursive: true, force: true });
11652
11803
  }
11653
11804
  }
11654
11805
 
@@ -11749,8 +11900,7 @@ var REASON_TEXT = Object.freeze({
11749
11900
  proxy_down: "the proxy for this site is not answering",
11750
11901
  failed: "the site did not give the video"
11751
11902
  });
11752
- var linkError = (code, message, reason) => Object.assign(new Error(message), { code, ...reason ? { reason } : {} });
11753
- var failure = (reason) => linkError("source_failed", REASON_TEXT[reason], reason);
11903
+ var failure = (reason) => codedError("source_failed", REASON_TEXT[reason], { reason });
11754
11904
  var isWebAddress = (value) => {
11755
11905
  try {
11756
11906
  return ["http:", "https:"].includes(new URL(value).protocol);
@@ -11815,7 +11965,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11815
11965
  return cwd;
11816
11966
  }
11817
11967
  async function access2(url, person) {
11818
- if (!isWebAddress(url)) throw linkError("invalid", "not a web address");
11968
+ if (!isWebAddress(url)) throw codedError("invalid", "not a web address");
11819
11969
  let proxy;
11820
11970
  try {
11821
11971
  proxy = await proxies.route(url);
@@ -11857,37 +12007,37 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11857
12007
  }
11858
12008
  async function lookUp(url, args, options) {
11859
12009
  const result = await ytdlp(url, ["-J", ...args], options);
11860
- if (result.oversized) throw linkError("source_failed", "the page lists too much to read", "failed");
12010
+ if (result.oversized) throw codedError("source_failed", "the page lists too much to read", { reason: "failed" });
11861
12011
  if (result.code !== 0) throw await reasonOf(url, result);
11862
12012
  try {
11863
12013
  return { data: JSON.parse(result.stdout), account: result.account };
11864
12014
  } catch {
11865
- throw linkError("source_failed", "yt-dlp answered something that is not JSON", "failed");
12015
+ throw codedError("source_failed", "yt-dlp answered something that is not JSON", { reason: "failed" });
11866
12016
  }
11867
12017
  }
11868
12018
  async function fetchCaptions(url, { entry, load, work, dir, stem, language, person, signal }) {
11869
12019
  const chosen = chooseCaptions(entry, language);
11870
12020
  if (chosen.length === 0) return [];
11871
- const result = await ytdlp(url, ["--skip-download", ...captionArgs(chosen), "-o", join7(work, "captions")], { person, load, signal });
12021
+ const result = await ytdlp(url, ["--skip-download", ...captionArgs(chosen), "-o", join8(work, "captions")], { person, load, signal });
11872
12022
  if (result.code !== 0) logger.warn("link %s: captions: %s", url, lastLine(result.stderr));
11873
12023
  const placed = [];
11874
12024
  for (const track of chosen) {
11875
12025
  const label = captionLabel(track);
11876
- const target = join7(dir, `${stem}.${label}.vtt`);
11877
- if (await rename2(join7(work, `captions.${track.tag}.vtt`), target).then(() => true, () => false)) placed.push({ path: target, label });
12026
+ const target = join8(dir, `${stem}.${label}.vtt`);
12027
+ if (await rename2(join8(work, `captions.${track.tag}.vtt`), target).then(() => true, () => false)) placed.push({ path: target, label });
11878
12028
  }
11879
12029
  return placed;
11880
12030
  }
11881
12031
  async function assemble(files, dir, stem) {
11882
12032
  if (files.length === 1) {
11883
- const target = join7(dir, `${stem}${extname4(files[0])}`);
12033
+ const target = join8(dir, `${stem}${extname4(files[0])}`);
11884
12034
  await rename2(files[0], target);
11885
12035
  return target;
11886
12036
  }
11887
12037
  let last = null;
11888
12038
  for (const ext of MERGED) {
11889
- const target = join7(dir, `${stem}.${ext}`);
11890
- const part = join7(dirname2(files[0]), `merged.${ext}`);
12039
+ const target = join8(dir, `${stem}.${ext}`);
12040
+ const part = join8(dirname2(files[0]), `merged.${ext}`);
11891
12041
  try {
11892
12042
  await runFfmpeg(["-y", ...files.flatMap((file) => ["-i", file]), ...files.flatMap((_, n) => ["-map", String(n)]), "-c", "copy", ...ext === "mp4" ? ["-movflags", "+faststart"] : [], part], { ffmpeg, duration: null });
11893
12043
  await rename2(part, target);
@@ -11909,8 +12059,8 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11909
12059
  async info(url, { person = "" } = {}) {
11910
12060
  const { data, account } = await lookUp(String(url), ["--flat-playlist"], { person, timeoutMs: INFO_TIMEOUT_MS });
11911
12061
  const document2 = infoDocument(data, String(url), maxHeight);
11912
- if (document2.id.length > MAX_URL) throw linkError("invalid", "the address is too long");
11913
- if (document2.episodes.length === 0) throw linkError("empty", "there is no video at this address", "not_found");
12062
+ if (document2.id.length > MAX_URL) throw codedError("invalid", "the address is too long");
12063
+ if (document2.episodes.length === 0) throw codedError("empty", "there is no video at this address", { reason: "not_found" });
11914
12064
  return { ...parseInfo(document2), qualities: document2.qualities, account: accountView(account) };
11915
12065
  },
11916
12066
  /** The thumbnail, through the route of its own host or its page's. */
@@ -11929,9 +12079,9 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11929
12079
  const failed = [];
11930
12080
  let first = null;
11931
12081
  for (let number = from2; number <= to && !signal?.aborted; number++) {
11932
- if ((await readdir3(dir)).some((name2) => isMedia(name2) && episodeNumber(name2) === number)) continue;
12082
+ if ((await readdir4(dir)).some((name2) => isMedia(name2) && episodeNumber(name2) === number)) continue;
11933
12083
  onStart?.(number);
11934
- const work = join7(dir, INCOMING, String(number));
12084
+ const work = join8(dir, INCOMING, String(number));
11935
12085
  try {
11936
12086
  await fetchEpisode(number, work);
11937
12087
  } catch (error) {
@@ -11952,7 +12102,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11952
12102
  const { data } = await lookUp(url, [...formatArgs(quality, maxHeight), "--write-subs", "--playlist-items", String(number)], { person, signal, timeoutMs: INFO_TIMEOUT_MS });
11953
12103
  const entry = data._type === "playlist" ? (data.entries ?? []).find((item) => item !== null && typeof item === "object") : data;
11954
12104
  if (entry === void 0) throw failure("not_found");
11955
- const load = join7(work, "info.json");
12105
+ const load = join8(work, "info.json");
11956
12106
  await writeFile2(load, JSON.stringify(entry));
11957
12107
  const stem = episodeStem(number, entry.title);
11958
12108
  const captions = await fetchCaptions(url, { entry, load, work, dir, stem, language, person, signal });
@@ -11966,7 +12116,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11966
12116
  ...quality === AUDIO ? AUDIO_FILE : [],
11967
12117
  ...PROGRESS_ARGS,
11968
12118
  "-o",
11969
- join7(work, `part${n}.%(ext)s`)
12119
+ join8(work, `part${n}.%(ext)s`)
11970
12120
  ], { person, load, signal, onStdoutLine: (line) => {
11971
12121
  const event = parseLine(line);
11972
12122
  if (event !== null) progress.event(event);
@@ -11974,12 +12124,12 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11974
12124
  if (result.code === 0) progress.finished(part.format_id);
11975
12125
  return result;
11976
12126
  }));
11977
- if (quality !== AUDIO) onPartial?.(number, { files: parts.map((part, n) => join7(work, `part${n}.${part.ext}`)), subtitles: captions, growing: Promise.allSettled(runs) });
12127
+ if (quality !== AUDIO) onPartial?.(number, { files: parts.map((part, n) => join8(work, `part${n}.${part.ext}`)), subtitles: captions, growing: Promise.allSettled(runs) });
11978
12128
  const results = await Promise.all(runs);
11979
12129
  const broken = results.find((result) => result.code !== 0);
11980
12130
  if (broken !== void 0) throw await reasonOf(url, broken);
11981
- const names = (await readdir3(work)).filter((name2) => /^part\d+\./.test(name2)).sort();
11982
- await assemble(names.map((name2) => join7(work, name2)), dir, stem);
12131
+ const names = (await readdir4(work)).filter((name2) => /^part\d+\./.test(name2)).sort();
12132
+ await assemble(names.map((name2) => join8(work, name2)), dir, stem);
11983
12133
  } catch (error) {
11984
12134
  for (const caption of captions) await rm5(caption.path, { force: true });
11985
12135
  throw error;
@@ -12003,8 +12153,8 @@ function createSources(definitions, { stateDir, logger, link }) {
12003
12153
  seen.add(id);
12004
12154
  }
12005
12155
  return [
12006
- ...definitions.map((definition) => createCommandSource(definition, { logger, cwd: join8(stateDir, definition.id) })),
12007
- createLinkSource({ ...link, logger, cwd: join8(stateDir, LINK_SOURCE) })
12156
+ ...definitions.map((definition) => createCommandSource(definition, { logger, cwd: join9(stateDir, definition.id) })),
12157
+ createLinkSource({ ...link, logger, cwd: join9(stateDir, LINK_SOURCE) })
12008
12158
  ];
12009
12159
  }
12010
12160
  async function describeSources(sources) {
@@ -12016,10 +12166,10 @@ async function describeSources(sources) {
12016
12166
  }
12017
12167
 
12018
12168
  // src/config.js
12019
- var DSH_HOME = process.env.DSH_HOME || join9(homedir(), ".dsh");
12169
+ var DSH_HOME = process.env.DSH_HOME || join10(homedir(), ".dsh");
12020
12170
  function defaultStateDir(home = DSH_HOME, exists2 = existsSync) {
12021
- const current = join9(home, "media-hub");
12022
- const earlier = join9(home, "videosync");
12171
+ const current = join10(home, "media-hub");
12172
+ const earlier = join10(home, "videosync");
12023
12173
  return !exists2(current) && exists2(earlier) ? earlier : current;
12024
12174
  }
12025
12175
  var DEFAULT_STATE_DIR = defaultStateDir();
@@ -12168,30 +12318,10 @@ function interleave(lists) {
12168
12318
  }
12169
12319
 
12170
12320
  // src/locales.js
12171
- import { readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
12172
- import { dirname as dirname3, join as join10, resolve as resolve2 } from "node:path";
12321
+ import { dirname as dirname3, resolve as resolve2 } from "node:path";
12173
12322
  import { fileURLToPath } from "node:url";
12174
12323
  var LOCALE_DIR = resolve2(dirname3(fileURLToPath(import.meta.url)), "../locale");
12175
- async function readLocales(dir, logger) {
12176
- const names = (await readdir4(dir).catch(() => [])).filter((name2) => name2.endsWith(".json")).sort();
12177
- const locales = {};
12178
- for (const name2 of names) {
12179
- const tag = name2.slice(0, -".json".length);
12180
- if (!TAG.test(tag)) {
12181
- logger?.warn("locale/%s: the name is not a language tag; skipped", name2);
12182
- continue;
12183
- }
12184
- try {
12185
- const { ui } = JSON.parse(await readFile4(join10(dir, name2), "utf8"));
12186
- if (ui === null || typeof ui !== "object" || Array.isArray(ui)) throw new Error('no "ui" table');
12187
- locales[tag] = Object.fromEntries(Object.entries(ui).filter(([, text3]) => typeof text3 === "string"));
12188
- } catch (error) {
12189
- logger?.warn("locale/%s: %s; skipped", name2, error.message);
12190
- }
12191
- }
12192
- if (locales[BASE] === void 0) logger?.warn("locale/%s.json is missing; every other language falls back to it", BASE);
12193
- return locales;
12194
- }
12324
+ var readWords = (dir, logger) => readLocales(dir, { warn: (message) => logger?.warn(message) });
12195
12325
 
12196
12326
  // src/vendored.js
12197
12327
  var VENDORED = Object.freeze({
@@ -12262,6 +12392,14 @@ function resolveRange(header, size) {
12262
12392
  if (start >= size || end < start) return { kind: "unsatisfiable" };
12263
12393
  return { kind: "window", start, end };
12264
12394
  }
12395
+ function rangePlan(header, size) {
12396
+ const range = resolveRange(header, size);
12397
+ if (range.kind === "unsatisfiable") return { status: 416, headers: { "content-range": `bytes */${size}` } };
12398
+ const start = range.kind === "window" ? range.start : 0;
12399
+ const end = range.kind === "window" ? range.end : size - 1;
12400
+ const headers = { "content-length": String(size === 0 ? 0 : end - start + 1), ...range.kind === "window" ? { "content-range": `bytes ${start}-${end}/${size}` } : {} };
12401
+ return { status: range.kind === "window" ? 206 : 200, start, end, headers };
12402
+ }
12265
12403
  async function sendFile(req, res, path, type = MEDIA_TYPES[extname5(path).toLowerCase()] ?? "application/octet-stream") {
12266
12404
  let info;
12267
12405
  try {
@@ -12270,24 +12408,13 @@ async function sendFile(req, res, path, type = MEDIA_TYPES[extname5(path).toLowe
12270
12408
  return sendText(res, 404, "Not found.");
12271
12409
  }
12272
12410
  if (!info.isFile()) return sendText(res, 404, "Not found.");
12273
- const size = info.size;
12274
- const range = resolveRange(req.headers.range, size);
12275
- const headers = { ...SECURITY_HEADERS, "cache-control": "private, no-store", "accept-ranges": "bytes", "content-type": type };
12276
- if (range.kind === "unsatisfiable") {
12277
- res.writeHead(416, { ...headers, "content-range": `bytes */${size}` }).end();
12278
- return;
12279
- }
12280
- const start = range.kind === "window" ? range.start : 0;
12281
- const end = range.kind === "window" ? range.end : size - 1;
12282
- const status = range.kind === "window" ? 206 : 200;
12283
- if (range.kind === "window") headers["content-range"] = `bytes ${start}-${end}/${size}`;
12284
- headers["content-length"] = String(size === 0 ? 0 : end - start + 1);
12285
- res.writeHead(status, headers);
12286
- if (req.method === "HEAD" || size === 0) {
12411
+ const plan = rangePlan(req.headers.range, info.size);
12412
+ res.writeHead(plan.status, { ...SECURITY_HEADERS, "cache-control": "private, no-store", "accept-ranges": "bytes", "content-type": type, ...plan.headers });
12413
+ if (plan.status === 416 || req.method === "HEAD" || info.size === 0) {
12287
12414
  res.end();
12288
12415
  return;
12289
12416
  }
12290
- const stream = createReadStream2(path, { start, end });
12417
+ const stream = createReadStream2(path, { start: plan.start, end: plan.end });
12291
12418
  stream.on("error", () => res.destroy());
12292
12419
  res.on("close", () => stream.destroy());
12293
12420
  stream.pipe(res);
@@ -12323,17 +12450,68 @@ async function readJson(req) {
12323
12450
  throw Object.assign(new Error("request body is not JSON"), { status: 400 });
12324
12451
  }
12325
12452
  }
12453
+ var API = Object.freeze([
12454
+ ["GET", "rooms", async ({ hub }) => ({ rooms: await hub.listRooms() })],
12455
+ ["GET", "rooms/:room/work", ({ hub, params }) => hub.roomWork(params.room)],
12456
+ ["GET", "rooms/:room/danmaku/:index", ({ hub, params }) => hub.roomDanmaku(params.room, Number(params.index))],
12457
+ ["GET", "rooms/:room/comments", ({ hub, params, query }) => hub.roomComments(params.room, query("cursor"))],
12458
+ ["POST", "rooms/:room/quality", async ({ hub, params, body: body2 }) => hub.roomQuality(params.room, String((await body2()).quality ?? ""))],
12459
+ ["POST", "rooms/:room/together", ({ hub, params }) => hub.watchTogether(params.room)],
12460
+ ["DELETE", "rooms/:room", ({ hub, params }) => hub.closeRoom(params.room)],
12461
+ ["GET", "library", ({ hub }) => hub.library()],
12462
+ ["GET", "library/episodes", async ({ hub, query }) => ({ episodes: await hub.episodes(query("path")) })],
12463
+ ["DELETE", "library", ({ hub, query }) => query("episode") ? hub.removeEpisode(query("path"), query("episode"), query("by") || null) : hub.removeShow(query("path"), query("by") || null)],
12464
+ ["POST", "library/rename", async ({ hub, body: body2 }) => {
12465
+ const input = await body2();
12466
+ return hub.renameShow(input.path, input.name, byOf(input));
12467
+ }],
12468
+ ["POST", "library/keep", async ({ hub, body: body2 }) => {
12469
+ const input = await body2();
12470
+ return hub.keepShow(input.path, byOf(input));
12471
+ }],
12472
+ ["POST", "library/countdown", async ({ hub, body: body2 }) => {
12473
+ const input = await body2();
12474
+ return hub.countdownShow(input.path, byOf(input));
12475
+ }],
12476
+ ["POST", "library/retry", async ({ hub, body: body2 }) => hub.retryDownload((await body2()).path)],
12477
+ ["POST", "library/pin", async ({ hub, body: body2 }) => {
12478
+ const input = await body2();
12479
+ return hub.pinShow(input.path, input.pinned === true, byOf(input));
12480
+ }],
12481
+ ["POST", "library/seen", async ({ hub, body: body2 }) => hub.dismissNews((await body2()).path)],
12482
+ ["POST", "library/cancel", async ({ hub, body: body2 }) => hub.cancelDownload((await body2()).path)],
12483
+ ["POST", "follow", async ({ hub, body: body2 }) => hub.followWork(pick3(await body2(), ["source", "id", "follow"]))],
12484
+ ["GET", "settings", ({ settings }) => settings()],
12485
+ ["GET", "locales", ({ localeDir, logger }) => readWords(localeDir, logger)],
12486
+ ["GET", "sources", async ({ hub }) => ({ sources: await hub.sources() })],
12487
+ ["GET", "trending", ({ hub, query }) => hub.trending(query("source"), query("kind"))],
12488
+ ["GET", "search", ({ hub, query }) => hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query))]
12489
+ ].map(([method, path, answer]) => ({ method, segments: path.split("/"), answer })));
12490
+ function matchApi(method, parts) {
12491
+ for (const route of API) {
12492
+ if (route.method !== method || route.segments.length !== parts.length) continue;
12493
+ const params = {};
12494
+ if (route.segments.every((segment, n) => segment.startsWith(":") ? (params[segment.slice(1)] = parts[n]) !== void 0 : segment === parts[n])) return { answer: route.answer, params };
12495
+ }
12496
+ return null;
12497
+ }
12326
12498
  var STATUS = Object.freeze({ points: 402, invalid: 400, empty: 400, not_found: 404, unsupported: 501, outside: 403, in_use: 409, exists: 409, no_space: 507, source_failed: 424, unavailable: 503 });
12499
+ var statusOf = (error) => error?.status ?? STATUS[error?.code] ?? 500;
12327
12500
  var errorBody = (error) => ({ error: { code: error?.code ?? "error", ...error?.reason ? { reason: error.reason } : {}, ...error?.points ? { points: error.points } : {}, message: error?.message ?? String(error) } });
12328
12501
  function createHandler({ connection, service, settings = () => ({ label: "", presence: {} }), localeDir = LOCALE_DIR, logger }) {
12329
12502
  return async (req, res) => {
12330
12503
  const admitted = admitOwner(connection, req);
12331
12504
  if (!admitted.ok) return sendText(res, admitted.status, admitted.status === 401 ? "Sign in to DSH first." : "Forbidden.");
12332
12505
  const url = new URL(req.url ?? "/", "http://media-hub.invalid");
12333
- const parts = url.pathname.slice(ROUTE.length + 1).split("/").map(decodeURIComponent);
12334
12506
  const hub = service();
12335
12507
  if (hub === void 0) return sendText(res, 503, "The media hub is starting.");
12336
12508
  try {
12509
+ let parts;
12510
+ try {
12511
+ parts = url.pathname.slice(ROUTE.length + 1).split("/").map(decodeURIComponent);
12512
+ } catch {
12513
+ return sendText(res, 400, "Bad address.");
12514
+ }
12337
12515
  if (parts[0] === "web" && parts.length === 2 && req.method === "GET") {
12338
12516
  const file = webFile(parts[1]);
12339
12517
  const body2 = file === void 0 ? null : await readFile5(file).catch(() => null);
@@ -12361,51 +12539,15 @@ function createHandler({ connection, service, settings = () => ({ label: "", pre
12361
12539
  return file === void 0 ? sendText(res, 404, "Not found.") : sendFile(req, res, file, MEDIA_TYPES[".vtt"]);
12362
12540
  }
12363
12541
  if (parts[0] === "api") {
12364
- const route = `${req.method} ${parts.slice(1).join("/")}`;
12365
- const query = (name2) => url.searchParams.get(name2) ?? "";
12366
- if (route === "GET rooms") return sendJson(res, 200, { rooms: await hub.listRooms() });
12367
- if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "work") return sendJson(res, 200, hub.roomWork(parts[2]));
12368
- if (req.method === "GET" && parts[1] === "rooms" && parts.length === 5 && parts[3] === "danmaku") return sendJson(res, 200, await hub.roomDanmaku(parts[2], Number(parts[4])));
12369
- if (req.method === "GET" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "comments") return sendJson(res, 200, await hub.roomComments(parts[2], query("cursor")));
12370
- if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "quality") return sendJson(res, 200, await hub.roomQuality(parts[2], String((await readJson(req)).quality ?? "")));
12371
- if (req.method === "DELETE" && parts[1] === "rooms" && parts.length === 3) return sendJson(res, 200, hub.closeRoom(parts[2]));
12372
- if (req.method === "POST" && parts[1] === "rooms" && parts.length === 4 && parts[3] === "together") return sendJson(res, 200, hub.watchTogether(parts[2]));
12373
- if (route === "GET library") return sendJson(res, 200, await hub.library());
12374
- if (route === "GET library/episodes") return sendJson(res, 200, { episodes: await hub.episodes(query("path")) });
12375
- if (route === "DELETE library") {
12376
- const by = query("by") || null;
12377
- return sendJson(res, 200, query("episode") ? await hub.removeEpisode(query("path"), query("episode"), by) : await hub.removeShow(query("path"), by));
12378
- }
12379
- if (route === "POST library/rename") {
12380
- const body2 = await readJson(req);
12381
- return sendJson(res, 200, await hub.renameShow(body2.path, body2.name, byOf(body2)));
12382
- }
12383
- if (route === "POST library/keep") {
12384
- const body2 = await readJson(req);
12385
- return sendJson(res, 200, await hub.keepShow(body2.path, byOf(body2)));
12386
- }
12387
- if (route === "POST library/countdown") {
12388
- const body2 = await readJson(req);
12389
- return sendJson(res, 200, await hub.countdownShow(body2.path, byOf(body2)));
12390
- }
12391
- if (route === "POST library/retry") return sendJson(res, 200, await hub.retryDownload((await readJson(req)).path));
12392
- if (route === "POST library/pin") {
12393
- const body2 = await readJson(req);
12394
- return sendJson(res, 200, await hub.pinShow(body2.path, body2.pinned === true, byOf(body2)));
12395
- }
12396
- if (route === "POST follow") return sendJson(res, 200, await hub.followWork(pick3(await readJson(req), ["source", "id", "follow"])));
12397
- if (route === "POST library/seen") return sendJson(res, 200, hub.dismissNews((await readJson(req)).path));
12398
- if (route === "POST library/cancel") return sendJson(res, 200, await hub.cancelDownload((await readJson(req)).path));
12399
- if (route === "GET settings") return sendJson(res, 200, settings());
12400
- if (route === "GET locales") return sendJson(res, 200, await readLocales(localeDir, logger));
12401
- if (route === "GET sources") return sendJson(res, 200, { sources: await hub.sources() });
12402
- if (route === "GET trending") return sendJson(res, 200, await hub.trending(query("source"), query("kind")));
12403
- if (route === "GET search") return sendJson(res, 200, await hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query)));
12542
+ const found = matchApi(req.method, parts.slice(1));
12543
+ if (found !== null) {
12544
+ const query = (name2) => url.searchParams.get(name2) ?? "";
12545
+ return sendJson(res, 200, await found.answer({ hub, params: found.params, query, body: () => readJson(req), settings, localeDir, logger }));
12546
+ }
12404
12547
  }
12405
12548
  return sendText(res, 404, "Not found.");
12406
12549
  } catch (error) {
12407
- const status = error?.status ?? STATUS[error?.code] ?? 500;
12408
- if (!res.headersSent) sendJson(res, status, errorBody(error));
12550
+ if (!res.headersSent) sendJson(res, statusOf(error), errorBody(error));
12409
12551
  else res.destroy();
12410
12552
  }
12411
12553
  };
@@ -12426,9 +12568,48 @@ import { statfs as statfs2, stat as stat10 } from "node:fs/promises";
12426
12568
  import { join as join17, resolve as resolve6 } from "node:path";
12427
12569
 
12428
12570
  // src/downloads.js
12429
- import { readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
12430
12571
  import { join as join11 } from "node:path";
12431
12572
 
12573
+ // src/json-file.js
12574
+ import { mkdir as mkdir6, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
12575
+ import { dirname as dirname5 } from "node:path";
12576
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12577
+ async function readJson2(file, { logger, valid = isObject, now = Date.now }) {
12578
+ let problem;
12579
+ try {
12580
+ const value = JSON.parse(await readFile6(file, "utf8"));
12581
+ if (valid(value)) return { value, damaged: false };
12582
+ problem = "not the expected shape";
12583
+ } catch (error) {
12584
+ if (error.code === "ENOENT") return { value: void 0, damaged: false };
12585
+ problem = error.message;
12586
+ }
12587
+ const aside = `${file}.bad-${now()}`;
12588
+ await rename3(file, aside).then(
12589
+ () => logger.warn("could not read %s (%s); moved it to %s and started empty", file, problem, aside),
12590
+ (error) => logger.warn("could not read %s (%s) nor move it aside: %s", file, problem, error.message)
12591
+ );
12592
+ return { value: void 0, damaged: true };
12593
+ }
12594
+ var serialize = (value) => JSON.stringify(value, null, 1);
12595
+ async function writeWhole(file, body2) {
12596
+ await mkdir6(dirname5(file), { recursive: true });
12597
+ await writeFile3(`${file}.part`, body2);
12598
+ await rename3(`${file}.part`, file);
12599
+ }
12600
+ var writeJson = (file, value) => writeWhole(file, serialize(value));
12601
+ function createJsonSaver(file, logger) {
12602
+ let saving = Promise.resolve();
12603
+ return {
12604
+ save(value) {
12605
+ const body2 = serialize(value);
12606
+ saving = saving.then(() => writeWhole(file, body2)).catch((error) => logger.warn("could not save %s: %s", file, error.message));
12607
+ return saving;
12608
+ },
12609
+ settled: () => saving
12610
+ };
12611
+ }
12612
+
12432
12613
  // src/window.js
12433
12614
  function windowOf(focus, total, { ahead, behind }) {
12434
12615
  return { first: Math.max(1, focus - behind), last: Math.min(total, focus + ahead) };
@@ -12480,23 +12661,24 @@ function nextOfRun(job, onDisk) {
12480
12661
  for (let n = job.at ?? from2; n <= to; n++) if (!onDisk.has(n)) return n;
12481
12662
  return null;
12482
12663
  }
12483
- var sourceError3 = (code, message) => Object.assign(new Error(message), { code });
12484
12664
  function createDownloads({ stateDir, sources, have, hasSpace = async () => true, onFiles, onProgress = () => {
12485
12665
  }, onPartial = () => {
12486
- }, logger, now = Date.now }) {
12666
+ }, logger, stopWaitMs = 1e4, now = Date.now }) {
12487
12667
  const file = join11(stateDir, "downloads.json");
12488
12668
  const jobs = /* @__PURE__ */ new Map();
12489
12669
  let running = null;
12490
12670
  let disposed = false;
12491
- let saving = Promise.resolve();
12671
+ const saver = createJsonSaver(file, logger);
12492
12672
  let notifying = Promise.resolve();
12673
+ async function letGo(busy) {
12674
+ const end = Date.now() + stopWaitMs;
12675
+ while (busy()) {
12676
+ if (Date.now() > end) return logger.warn("a download did not stop when asked; going on without waiting for it");
12677
+ await new Promise((done) => setTimeout(done, 50));
12678
+ }
12679
+ }
12493
12680
  function save() {
12494
- const body2 = JSON.stringify({ jobs: [...jobs.values()].map(({ controller, current, at, ...job }) => job) }, null, 1);
12495
- saving = saving.then(async () => {
12496
- await writeFile3(`${file}.part`, body2);
12497
- await rename3(`${file}.part`, file);
12498
- }).catch((error) => logger.warn("could not save downloads: %s", error.message));
12499
- return saving;
12681
+ return saver.save({ jobs: [...jobs.values()].map(({ controller, current, at, ...job }) => job) });
12500
12682
  }
12501
12683
  function notify(job) {
12502
12684
  notifying = notifying.then(() => onFiles(job)).catch((error) => logger.warn("after a download step: %s", error.message));
@@ -12528,11 +12710,11 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12528
12710
  const { signal } = job.controller;
12529
12711
  save();
12530
12712
  try {
12531
- if (source === void 0) throw sourceError3("unavailable", `source ${job.source} is not available`);
12713
+ if (source === void 0) throw codedError("unavailable", `source ${job.source} is not available`);
12532
12714
  for (; ; ) {
12533
12715
  const range = nextRun(job.want, await have(job.dir));
12534
12716
  if (range === null || signal.aborted) break;
12535
- if (!await hasSpace()) throw sourceError3("no_space", "the library disk is almost full; delete something first");
12717
+ if (!await hasSpace()) throw codedError("no_space", "the library disk is almost full; delete something first");
12536
12718
  job.current = range;
12537
12719
  job.at = range[0];
12538
12720
  const result = await source.download({ ...howOf(job.how), id: job.id, dir: job.dir, from: range[0], to: range[1], signal, onStart: (n) => {
@@ -12542,7 +12724,7 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12542
12724
  if (signal.aborted) break;
12543
12725
  if (result.failed.length > 0) {
12544
12726
  job.failed = result.failed;
12545
- throw sourceError3("source_failed", `${result.failed.length} episodes could not be downloaded`);
12727
+ throw codedError("source_failed", `${result.failed.length} episodes could not be downloaded`);
12546
12728
  }
12547
12729
  }
12548
12730
  if (signal.aborted) {
@@ -12568,12 +12750,7 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12568
12750
  }
12569
12751
  return {
12570
12752
  async load() {
12571
- let data = { jobs: [] };
12572
- try {
12573
- data = JSON.parse(await readFile6(file, "utf8"));
12574
- } catch (error) {
12575
- if (error.code !== "ENOENT") logger.warn("could not read %s: %s", file, error.message);
12576
- }
12753
+ const data = (await readJson2(file, { logger })).value ?? {};
12577
12754
  for (const job of data.jobs ?? []) if (Array.isArray(job.want)) jobs.set(job.dir, { ...job, status: job.status === "running" ? "queued" : job.status });
12578
12755
  pump();
12579
12756
  },
@@ -12652,29 +12829,30 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12652
12829
  jobs.delete(dir);
12653
12830
  job.controller?.abort("cancel");
12654
12831
  save();
12655
- while (running === job) await new Promise((done) => setTimeout(done, 50));
12832
+ await letGo(() => running === job);
12656
12833
  },
12657
12834
  async dispose() {
12658
12835
  disposed = true;
12659
12836
  running?.controller?.abort("stop");
12660
- while (running !== null) await new Promise((done) => setTimeout(done, 50));
12661
- await saving;
12837
+ await letGo(() => running !== null);
12838
+ await saver.settled();
12662
12839
  }
12663
12840
  };
12664
12841
  }
12665
12842
 
12666
12843
  // src/cache.js
12667
12844
  function createCache({ library, downloads, rooms, window: size, logger }) {
12668
- let chain2 = Promise.resolve();
12845
+ let chain3 = Promise.resolve();
12669
12846
  const serial = (step) => {
12670
- const result = chain2.then(step);
12671
- chain2 = result.catch((error) => logger.warn("rolling cache: %s", error.message));
12847
+ const result = chain3.then(step);
12848
+ chain3 = result.catch((error) => logger.warn("rolling cache: %s", error.message));
12672
12849
  return result;
12673
12850
  };
12674
12851
  async function protectedEpisodes() {
12675
12852
  const out = /* @__PURE__ */ new Map();
12676
12853
  for (const path of await library.sourcedShows()) {
12677
12854
  const info = await library.cacheInfo(path);
12855
+ if (info === null) continue;
12678
12856
  const set2 = /* @__PURE__ */ new Set();
12679
12857
  for (const focus of rooms.focusesOf(path)) {
12680
12858
  const { first, last } = windowOf(focus, info.total, size);
@@ -12722,6 +12900,7 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
12722
12900
  refreshActive: () => serial(async () => {
12723
12901
  for (const path of await library.sourcedShows()) {
12724
12902
  const info = await library.cacheInfo(path);
12903
+ if (info === null) continue;
12725
12904
  if (info.pinned || rooms.focusesOf(path).length > 0) await refreshShow(path);
12726
12905
  }
12727
12906
  await enforceCap();
@@ -12751,7 +12930,7 @@ function createCache({ library, downloads, rooms, window: size, logger }) {
12751
12930
  // src/books.js
12752
12931
  import { spawn as spawn4 } from "node:child_process";
12753
12932
  import { createHash as createHash4, randomUUID } from "node:crypto";
12754
- import { mkdir as mkdir6, readFile as readFile7, readdir as readdir5, rename as rename4, rm as rm6, stat as stat7, writeFile as writeFile4 } from "node:fs/promises";
12933
+ import { mkdir as mkdir7, readdir as readdir5, rename as rename4, rm as rm6, stat as stat7 } from "node:fs/promises";
12755
12934
  import { extname as extname6, join as join12 } from "node:path";
12756
12935
 
12757
12936
  // src/formats.js
@@ -12779,7 +12958,6 @@ var MAX_ENTRIES = 2e3;
12779
12958
  var CONVERT_TIMEOUT_MS = 10 * 6e4;
12780
12959
  var CONCURRENCY = 2;
12781
12960
  var ENTRY = /^[0-9a-f-]{36}$/;
12782
- var booksError = (code, message) => Object.assign(new Error(message), { code });
12783
12961
  var fileKey = (source, id, format) => createHash4("sha256").update(`${source}
12784
12962
  ${id}
12785
12963
  ${format}`).digest("hex").slice(0, 24);
@@ -12787,9 +12965,6 @@ function attachment(name2) {
12787
12965
  const fallback = name2.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_") || "book";
12788
12966
  return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name2)}`;
12789
12967
  }
12790
- function sha256Of2(path) {
12791
- return readFile7(path).then((body2) => createHash4("sha256").update(body2).digest("hex"));
12792
- }
12793
12968
  function runConverter(command, input, output) {
12794
12969
  return new Promise((resolve8, reject) => {
12795
12970
  const child = spawn4(command, [input, output], { stdio: ["ignore", "ignore", "pipe"], detached: true });
@@ -12810,27 +12985,22 @@ function runConverter(command, input, output) {
12810
12985
  child.on("close", (code) => {
12811
12986
  clearTimeout(timer);
12812
12987
  if (code === 0) resolve8();
12813
- else reject(booksError("convert_failed", `conversion failed: ${stderr.trim().split("\n").pop() || `exit ${code}`}`));
12988
+ else reject(codedError("convert_failed", `conversion failed: ${stderr.trim().split("\n").pop() || `exit ${code}`}`));
12814
12989
  });
12815
12990
  });
12816
12991
  }
12817
12992
  function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, changed = () => {
12818
12993
  }, now = Date.now }) {
12819
12994
  let state = { files: {}, shelves: {} };
12820
- let saving = Promise.resolve();
12995
+ const stateFile = join12(dir, STATE_FILE);
12996
+ const saver = createJsonSaver(stateFile, logger);
12821
12997
  const running = /* @__PURE__ */ new Map();
12822
12998
  const waiting = [];
12823
12999
  let active = 0;
12824
13000
  let disposed = false;
12825
13001
  const save = () => {
12826
13002
  changed();
12827
- saving = saving.then(async () => {
12828
- await mkdir6(dir, { recursive: true });
12829
- const temporary = join12(dir, `.${STATE_FILE}.${process.pid}.tmp`);
12830
- await writeFile4(temporary, JSON.stringify(state));
12831
- await rename4(temporary, join12(dir, STATE_FILE));
12832
- }).catch((error) => logger.warn("books: could not save the shelves: %s", error.message));
12833
- return saving;
13003
+ return saver.save(state);
12834
13004
  };
12835
13005
  const shelf = (person) => state.shelves[person] ??= [];
12836
13006
  const holders = (key) => Object.values(state.shelves).some((entries) => entries.some((entry) => entry.file === key));
@@ -12872,7 +13042,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12872
13042
  const native = (work.formats ?? []).some((entry) => entry.format === format) || (work.formats ?? []).length === 0;
12873
13043
  const scratch = join12(dir, "tmp", key);
12874
13044
  await rm6(scratch, { recursive: true, force: true });
12875
- await mkdir6(scratch, { recursive: true });
13045
+ await mkdir7(scratch, { recursive: true });
12876
13046
  try {
12877
13047
  let name2;
12878
13048
  let converted = false;
@@ -12880,7 +13050,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12880
13050
  name2 = (await source.downloadFile({ id, format, dir: scratch, signal })).name;
12881
13051
  } else {
12882
13052
  const base = convertBase(work.formats);
12883
- if (base === null || !await converter.available()) throw booksError("unsupported", `${work.title || id} is not offered as ${format}`);
13053
+ if (base === null || !await converter.available()) throw codedError("unsupported", `${work.title || id} is not offered as ${format}`);
12884
13054
  const downloaded = (await source.downloadFile({ id, format: base, dir: scratch, signal })).name;
12885
13055
  name2 = `${downloaded.slice(0, downloaded.length - extname6(downloaded).length)}.${format}`;
12886
13056
  await runConverter(converter.command, join12(scratch, downloaded), join12(scratch, name2));
@@ -12889,10 +13059,10 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12889
13059
  }
12890
13060
  const target = join12(dir, "files", key);
12891
13061
  await rm6(target, { recursive: true, force: true });
12892
- await mkdir6(join12(dir, "files"), { recursive: true });
13062
+ await mkdir7(join12(dir, "files"), { recursive: true });
12893
13063
  await rename4(scratch, target);
12894
13064
  const path = join12(target, name2);
12895
- return { name: name2, bytes: (await stat7(path)).size, sha256: await sha256Of2(path), converted, title: work.title, author: work.author, cover: work.cover };
13065
+ return { name: name2, bytes: (await stat7(path)).size, sha256: await sha256Of(path), converted, title: work.title, author: work.author, cover: work.cover };
12896
13066
  } finally {
12897
13067
  await rm6(scratch, { recursive: true, force: true });
12898
13068
  }
@@ -12913,7 +13083,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12913
13083
  entry.cover ||= got.cover ?? null;
12914
13084
  }
12915
13085
  }
12916
- return enforceCap();
13086
+ return enforceCap().catch((error) => logger.warn("books: could not keep the shelves under the cap: %s", error.message));
12917
13087
  }, (error) => {
12918
13088
  if (disposed) return;
12919
13089
  logger.warn("books: %s:%s as %s failed: %s", request.source, request.id, request.format, error.message);
@@ -12934,12 +13104,8 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12934
13104
  }
12935
13105
  return {
12936
13106
  async load() {
12937
- try {
12938
- const loaded = JSON.parse(await readFile7(join12(dir, STATE_FILE), "utf8"));
12939
- if (loaded && typeof loaded.files === "object" && typeof loaded.shelves === "object") state = loaded;
12940
- } catch (error) {
12941
- if (error.code !== "ENOENT") logger.warn("books: could not read the shelves: %s", error.message);
12942
- }
13107
+ const { value } = await readJson2(stateFile, { logger, valid: (loaded) => typeof loaded?.files === "object" && loaded.files !== null && typeof loaded.shelves === "object" && loaded.shelves !== null });
13108
+ if (value !== void 0) state = value;
12943
13109
  for (const [key, file] of Object.entries(state.files)) {
12944
13110
  if (file.state === "fetching") start(key, file);
12945
13111
  else if (file.state === "ready" && !await stat7(join12(dir, "files", key, file.name ?? "")).then((info) => info.isFile(), () => false)) state.files[key] = { ...file, state: "removed", name: null };
@@ -12947,10 +13113,17 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12947
13113
  await rm6(join12(dir, "tmp"), { recursive: true, force: true });
12948
13114
  await this.sweep();
12949
13115
  },
12950
- /** Folders under files/ that no record names (a crash between a rename and a save) are deleted. */
13116
+ /**
13117
+ * A folder under files/ that no record names and that is newer than the saved shelves is a fetch a crash cut off
13118
+ * before its save: deleted. An older one stays: its record was lost with a damaged shelves file, set aside to restore.
13119
+ */
12951
13120
  async sweep() {
13121
+ const savedAt = await stat7(stateFile).then((info) => info.mtimeMs, () => null);
13122
+ if (savedAt === null) return;
12952
13123
  for (const name2 of await readdir5(join12(dir, "files")).catch(() => [])) {
12953
- if (state.files[name2] === void 0) await rm6(join12(dir, "files", name2), { recursive: true, force: true });
13124
+ if (state.files[name2] !== void 0) continue;
13125
+ const folder = join12(dir, "files", name2);
13126
+ if (await stat7(folder).then((info) => info.mtimeMs > savedAt, () => false)) await rm6(folder, { recursive: true, force: true });
12954
13127
  }
12955
13128
  },
12956
13129
  async list(person) {
@@ -12968,14 +13141,14 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12968
13141
  */
12969
13142
  async add(person, { source: sourceId, id, format, title = "", author = "", by = "" }) {
12970
13143
  const source = sources.get(sourceId);
12971
- if (source === void 0 || typeof source.downloadFile !== "function") throw booksError("not_found", `no source ${sourceId}`);
12972
- if (typeof id !== "string" || !/^[^\s\0]{1,200}$/.test(id)) throw booksError("invalid", "not a work id");
12973
- if (typeof format !== "string" || !/^[a-z0-9]{1,8}$/.test(format)) throw booksError("invalid", "not a format");
13144
+ if (source === void 0 || typeof source.downloadFile !== "function") throw codedError("not_found", `no source ${sourceId}`);
13145
+ if (typeof id !== "string" || !/^[^\s\0]{1,200}$/.test(id)) throw codedError("invalid", "not a work id");
13146
+ if (typeof format !== "string" || !/^[a-z0-9]{1,8}$/.test(format)) throw codedError("invalid", "not a format");
12974
13147
  const key = fileKey(sourceId, id, format);
12975
13148
  const entries = shelf(person);
12976
13149
  let entry = entries.find((one) => one.file === key);
12977
13150
  if (entry === void 0) {
12978
- if (entries.length >= MAX_ENTRIES) throw booksError("invalid", "this shelf is full; delete some books first");
13151
+ if (entries.length >= MAX_ENTRIES) throw codedError("invalid", "this shelf is full; delete some books first");
12979
13152
  entry = { entry: randomUUID(), file: key, source: sourceId, id, format, title: String(title).slice(0, 300), author: String(author).slice(0, 200), cover: null, addedAt: new Date(now()).toISOString(), by: String(by).slice(0, 80) };
12980
13153
  entries.push(entry);
12981
13154
  }
@@ -12988,7 +13161,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12988
13161
  /** Fetch an entry's file again (it failed, or was removed to save space). */
12989
13162
  async retry(person, entryId) {
12990
13163
  const entry = shelf(person).find((one) => one.entry === entryId);
12991
- if (entry === void 0) throw booksError("not_found", "not on this shelf");
13164
+ if (entry === void 0) throw codedError("not_found", "not on this shelf");
12992
13165
  if (state.files[entry.file]?.state !== "ready") start(entry.file, entry);
12993
13166
  await save();
12994
13167
  return describe(entry);
@@ -12996,7 +13169,7 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
12996
13169
  async remove(person, entryId) {
12997
13170
  const entries = shelf(person);
12998
13171
  const index = entries.findIndex((one) => one.entry === entryId);
12999
- if (index === -1) throw booksError("not_found", "not on this shelf");
13172
+ if (index === -1) throw codedError("not_found", "not on this shelf");
13000
13173
  const [entry] = entries.splice(index, 1);
13001
13174
  if (!holders(entry.file)) {
13002
13175
  running.get(entry.file)?.abort();
@@ -13022,15 +13195,36 @@ function createBooks({ dir, sources, capBytes = 0, converter, covers, logger, ch
13022
13195
  disposed = true;
13023
13196
  waiting.length = 0;
13024
13197
  for (const controller of running.values()) controller.abort();
13025
- await saving;
13198
+ await saver.settled();
13026
13199
  }
13027
13200
  };
13028
13201
  }
13029
13202
 
13030
13203
  // src/covers.js
13031
13204
  import { createHash as createHash5 } from "node:crypto";
13032
- import { mkdir as mkdir7, open as open3, readdir as readdir6, rename as rename5, rm as rm7, stat as stat8, utimes } from "node:fs/promises";
13205
+ import { mkdir as mkdir8, open as open3, readdir as readdir6, rename as rename5, rm as rm7, stat as stat8, utimes } from "node:fs/promises";
13033
13206
  import { join as join13 } from "node:path";
13207
+
13208
+ // src/limit.js
13209
+ function createLimiter(concurrency) {
13210
+ const waiting = [];
13211
+ let running = 0;
13212
+ const pump = () => {
13213
+ while (running < concurrency && waiting.length > 0) {
13214
+ running += 1;
13215
+ waiting.shift()().finally(() => {
13216
+ running -= 1;
13217
+ pump();
13218
+ });
13219
+ }
13220
+ };
13221
+ return (job) => new Promise((resolve8, reject) => {
13222
+ waiting.push(() => job().then(resolve8, reject));
13223
+ pump();
13224
+ });
13225
+ }
13226
+
13227
+ // src/covers.js
13034
13228
  var KEY = /^[0-9a-f]{32}$/;
13035
13229
  var FAILED_FOR_MS = 5 * 6e4;
13036
13230
  var MAX_REMEMBERED = 5e3;
@@ -13062,8 +13256,6 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13062
13256
  const known2 = /* @__PURE__ */ new Map();
13063
13257
  const inFlight = /* @__PURE__ */ new Map();
13064
13258
  const failed = /* @__PURE__ */ new Map();
13065
- const waiting = [];
13066
- let running = 0;
13067
13259
  const makers = {
13068
13260
  async source({ sourceId, url, page }, file) {
13069
13261
  const source = sourceOf(sourceId);
@@ -13078,19 +13270,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13078
13270
  if (known2.size > MAX_REMEMBERED) known2.delete(known2.keys().next().value);
13079
13271
  return `covers/${key}`;
13080
13272
  };
13081
- const pump = () => {
13082
- while (running < concurrency && waiting.length > 0) {
13083
- running += 1;
13084
- waiting.shift()().finally(() => {
13085
- running -= 1;
13086
- pump();
13087
- });
13088
- }
13089
- };
13090
- const queued = (job) => new Promise((resolve8, reject) => {
13091
- waiting.push(() => job().then(resolve8, reject));
13092
- pump();
13093
- });
13273
+ const queued = createLimiter(concurrency);
13094
13274
  async function trim() {
13095
13275
  if (!(capBytes > 0)) return;
13096
13276
  const files = [];
@@ -13107,7 +13287,7 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13107
13287
  }
13108
13288
  }
13109
13289
  async function make(key, entry) {
13110
- await mkdir7(dir, { recursive: true });
13290
+ await mkdir8(dir, { recursive: true });
13111
13291
  const partial = join13(dir, `.${key}.part`);
13112
13292
  try {
13113
13293
  await makers[entry.by](entry, partial);
@@ -13192,8 +13372,8 @@ function createCovers({ dir, capBytes = 5e7, maxFileBytes = 2e6, concurrency = 3
13192
13372
 
13193
13373
  // src/hub.js
13194
13374
  import { randomBytes as randomBytes2 } from "node:crypto";
13195
- import { mkdir as mkdir8, readFile as readFile8, rename as rename6, writeFile as writeFile5 } from "node:fs/promises";
13196
- import { dirname as dirname5, isAbsolute as isAbsolute3, join as join14, resolve as resolve4 } from "node:path";
13375
+ import { mkdir as mkdir9 } from "node:fs/promises";
13376
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join14, resolve as resolve4 } from "node:path";
13197
13377
 
13198
13378
  // src/sync.js
13199
13379
  var DRIFT = Object.freeze({
@@ -13416,7 +13596,6 @@ var MAX_NAME = 40;
13416
13596
  var localItem = (episode) => ({ title: episode.title, kind: "file", status: "preparing", sourcePath: episode.path, sourceSubtitles: episode.subtitles });
13417
13597
  var slotItem = (entry, status) => ({ title: entry.title, kind: "file", slot: entry.n, status: entry.path === null ? status : "preparing", sourcePath: entry.path, sourceSubtitles: entry.subtitles ?? [] });
13418
13598
  var itemKey = (item) => item.slot ?? item.sourcePath;
13419
- var serviceError = (code, message) => Object.assign(new Error(message), { code });
13420
13599
  var isTogether = (room) => room.together !== false;
13421
13600
  var cleanText = (value, max) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, max) : "";
13422
13601
  function createRoomService(options) {
@@ -13461,15 +13640,10 @@ function createRoomService(options) {
13461
13640
  const sweepTimer = setInterval(() => sweep(), SWEEP_MS);
13462
13641
  const progressTimer = setInterval(() => progress(), PROGRESS_MS);
13463
13642
  async function load() {
13464
- await mkdir8(stateDir, { recursive: true });
13465
- for (const root of libraryRoots) await mkdir8(root, { recursive: true }).catch(() => {
13643
+ await mkdir9(stateDir, { recursive: true });
13644
+ for (const root of libraryRoots) await mkdir9(root, { recursive: true }).catch(() => {
13466
13645
  });
13467
- let data = { rooms: [] };
13468
- try {
13469
- data = JSON.parse(await readFile8(file, "utf8"));
13470
- } catch (error) {
13471
- if (error.code !== "ENOENT") logger.warn("could not read %s: %s", file, error.message);
13472
- }
13646
+ const data = (await readJson2(file, { logger })).value ?? {};
13473
13647
  for (const { holds, ...room } of data.rooms ?? []) rooms.set(room.id, { ...hold({ gate: null, gates: 0, startedAt: null, ...room }, now()), cooldown: {}, nextReady: null, emptySince: room.emptySince ?? (room.opened ? now() : null) });
13474
13648
  sweep();
13475
13649
  for (const room of [...rooms.values()]) await reopen(room);
@@ -13483,9 +13657,7 @@ function createRoomService(options) {
13483
13657
  }, SAVE_DELAY_MS);
13484
13658
  }
13485
13659
  async function flush() {
13486
- const body2 = JSON.stringify({ rooms: [...rooms.values()] }, null, 1);
13487
- await writeFile5(`${file}.part`, body2);
13488
- await rename6(`${file}.part`, file);
13660
+ await writeJson(file, { rooms: [...rooms.values()] });
13489
13661
  }
13490
13662
  function commit(room) {
13491
13663
  rooms.set(room.id, { ...room, touchedAt: now() });
@@ -13623,7 +13795,12 @@ function createRoomService(options) {
13623
13795
  } catch {
13624
13796
  return send(peer, { t: "error", message: "not JSON" });
13625
13797
  }
13626
- handle(peer, roomId, message);
13798
+ if (typeof message !== "object" || message === null) return send(peer, { t: "error", message: "not an object" });
13799
+ try {
13800
+ handle(peer, roomId, message);
13801
+ } catch (error) {
13802
+ logger.warn("room %s: a message failed: %s", roomId, error.message);
13803
+ }
13627
13804
  });
13628
13805
  ws.on("close", () => {
13629
13806
  clearInterval(ping);
@@ -13707,7 +13884,7 @@ function createRoomService(options) {
13707
13884
  return { ...room, items: room.items.map((entry, n) => n === room.index ? { ...entry, status: "preparing", error: null } : entry) };
13708
13885
  }
13709
13886
  async function reopen(room) {
13710
- const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(dirname5(item.file)) === null;
13887
+ const unfinished = async (item) => item.status === "ready" && item.kind === "hls" && typeof item.file === "string" && item.file.startsWith(`${cacheDir}/`) && await finishedPlaylist(dirname6(item.file)) === null;
13711
13888
  const items = [];
13712
13889
  for (const item of room.items) {
13713
13890
  if (!await unfinished(item)) items.push(item);
@@ -13765,10 +13942,10 @@ function createRoomService(options) {
13765
13942
  });
13766
13943
  }
13767
13944
  async function localItems(path, fromPanel) {
13768
- if (typeof path !== "string" || !isAbsolute3(path)) throw serviceError("invalid", "path must be an absolute path");
13945
+ if (typeof path !== "string" || !isAbsolute3(path)) throw codedError("invalid", "path must be an absolute path");
13769
13946
  const target = resolve4(path);
13770
13947
  if (fromPanel && !libraryRoots.some((root) => target === root || target.startsWith(`${root}/`))) {
13771
- throw serviceError("outside", "the panel can only open files from the library folders");
13948
+ throw codedError("outside", "the panel can only open files from the library folders");
13772
13949
  }
13773
13950
  const entries = await options.directory?.(target);
13774
13951
  if (entries) return entries.map((entry) => slotItem(entry, "remote"));
@@ -13776,7 +13953,7 @@ function createRoomService(options) {
13776
13953
  try {
13777
13954
  episodes = await scanSource(target);
13778
13955
  } catch (error) {
13779
- if (error.code === "ENOENT") throw serviceError("not_found", `${path} does not exist`);
13956
+ if (error.code === "ENOENT") throw codedError("not_found", `${path} does not exist`);
13780
13957
  throw error;
13781
13958
  }
13782
13959
  return episodes.map(localItem);
@@ -13813,7 +13990,7 @@ function createRoomService(options) {
13813
13990
  * @param {{ path: string, title?: string, by?: string, fromPanel?: boolean, together?: boolean, start?: { index: number, position: number } | null }} input - `together`: open to others from the start; else one person watches until they share it
13814
13991
  */
13815
13992
  async createRoom(input) {
13816
- if (!delivery.available) throw serviceError("unsupported", delivery.reason);
13993
+ if (!delivery.available) throw codedError("unsupported", delivery.reason);
13817
13994
  const items = await localItems(input.path, input.fromPanel === true);
13818
13995
  const id = randomBytes2(9).toString("base64url");
13819
13996
  const title = cleanText(input.title, 120) || (items.length === 1 ? items[0].title : input.path.split("/").filter(Boolean).pop());
@@ -13855,12 +14032,12 @@ function createRoomService(options) {
13855
14032
  /** Open a room someone watches alone to others, as it is: same episode, same position. */
13856
14033
  watchTogether(id) {
13857
14034
  const room = rooms.get(id);
13858
- if (room === void 0) throw serviceError("not_found", "no such room");
14035
+ if (room === void 0) throw codedError("not_found", "no such room");
13859
14036
  if (!isTogether(room)) commit({ ...room, together: true });
13860
14037
  return { room: summary(rooms.get(id)) };
13861
14038
  },
13862
14039
  closeRoom(id) {
13863
- if (!close(id)) throw serviceError("not_found", "no such room");
14040
+ if (!close(id)) throw codedError("not_found", "no such room");
13864
14041
  return { closed: id };
13865
14042
  },
13866
14043
  sweep,
@@ -13941,7 +14118,7 @@ function createRoomService(options) {
13941
14118
  }
13942
14119
 
13943
14120
  // src/watchlog.js
13944
- import { appendFile, readFile as readFile9 } from "node:fs/promises";
14121
+ import { appendFile, readFile as readFile7 } from "node:fs/promises";
13945
14122
  var LOG_NAME = "watch-log.jsonl";
13946
14123
  var isWatching = (type) => /^(?:room|viewer|episode)\./.test(type) || type === "position";
13947
14124
  function isNearEnd(position, duration) {
@@ -13960,7 +14137,7 @@ function createWatchLog({ file, now = Date.now, logger }) {
13960
14137
  await tail;
13961
14138
  let text3 = "";
13962
14139
  try {
13963
- text3 = await readFile9(file, "utf8");
14140
+ text3 = await readFile7(file, "utf8");
13964
14141
  } catch (error) {
13965
14142
  if (error.code !== "ENOENT") throw error;
13966
14143
  }
@@ -14070,8 +14247,8 @@ function createJournal({ log, library, now = Date.now }) {
14070
14247
  }
14071
14248
 
14072
14249
  // src/shows.js
14073
- import { mkdir as mkdir9, readFile as readFile10, readdir as readdir7, rename as rename7, rm as rm8, stat as stat9, statfs, writeFile as writeFile6 } from "node:fs/promises";
14074
- import { basename as basename5, dirname as dirname6, extname as extname7, join as join15, resolve as resolve5 } from "node:path";
14250
+ import { mkdir as mkdir10, readFile as readFile8, readdir as readdir7, rename as rename6, rm as rm8, stat as stat9, statfs, writeFile as writeFile4 } from "node:fs/promises";
14251
+ import { basename as basename5, dirname as dirname7, extname as extname7, join as join15, resolve as resolve5 } from "node:path";
14075
14252
 
14076
14253
  // src/presence.js
14077
14254
  var RATINGS = Object.freeze(["loved", "fine", "not-for-me", "unfinished"]);
@@ -14085,7 +14262,6 @@ var MAX_PROMPT_CHARS = 2e3;
14085
14262
  var PICKS_LIMIT = 8;
14086
14263
  var PICKS_TIMEOUT_MS = 6e4;
14087
14264
  var MAX_WHY_CHARS = 280;
14088
- var badInput = (message) => Object.assign(new Error(message), { code: "invalid_arguments" });
14089
14265
  function pendingRatings({ shows, events, person, now, days = RATE_WITHIN_DAYS, limit = MAX_PENDING }) {
14090
14266
  const since = now - days * 864e5;
14091
14267
  const rated = new Set(events.filter((event) => event.type === "rating" && event.person === person).map((event) => event.show));
@@ -14101,8 +14277,8 @@ function pendingRatings({ shows, events, person, now, days = RATE_WITHIN_DAYS, l
14101
14277
  return [...asks.values()].filter((ask) => ask.why === "finished" || !present.has(ask.show)).sort((a, b) => b.at - a.at).slice(0, limit);
14102
14278
  }
14103
14279
  function ratingLine({ show, title, rating }, person) {
14104
- if (!RATINGS.includes(rating)) throw badInput(`rating must be one of ${RATINGS.join(", ")}`);
14105
- if (typeof show !== "string" || show === "") throw badInput("rating needs the show");
14280
+ if (!RATINGS.includes(rating)) throw codedError("invalid_arguments", `rating must be one of ${RATINGS.join(", ")}`);
14281
+ if (typeof show !== "string" || show === "") throw codedError("invalid_arguments", "rating needs the show");
14106
14282
  return { show, title: typeof title === "string" ? title.slice(0, 200) : "", rating, person: person.key, by: person.name };
14107
14283
  }
14108
14284
  var textOrPerLanguage = (value, max) => {
@@ -14117,22 +14293,22 @@ function parseAnnotation({ recap, steps } = {}) {
14117
14293
  const out = {};
14118
14294
  if (recap === null) out.recap = null;
14119
14295
  else if (recap !== void 0) {
14120
- if (typeof recap?.text !== "string" || recap.text.trim() === "") throw badInput("recap needs text");
14121
- if (!Number.isInteger(recap.upTo) || recap.upTo < 1) throw badInput("recap needs upTo, the last episode it covers (1 or more)");
14296
+ if (typeof recap?.text !== "string" || recap.text.trim() === "") throw codedError("invalid_arguments", "recap needs text");
14297
+ if (!Number.isInteger(recap.upTo) || recap.upTo < 1) throw codedError("invalid_arguments", "recap needs upTo, the last episode it covers (1 or more)");
14122
14298
  out.recap = { text: recap.text.trim().slice(0, MAX_RECAP_CHARS), upTo: recap.upTo };
14123
14299
  }
14124
14300
  if (steps === null) out.steps = null;
14125
14301
  else if (steps !== void 0) {
14126
- if (!Array.isArray(steps) || steps.length > MAX_STEPS) throw badInput(`steps is a list of at most ${MAX_STEPS}`);
14302
+ if (!Array.isArray(steps) || steps.length > MAX_STEPS) throw codedError("invalid_arguments", `steps is a list of at most ${MAX_STEPS}`);
14127
14303
  out.steps = steps.map((step, n) => {
14128
14304
  const id = step?.id ?? `step-${n + 1}`;
14129
- if (typeof id !== "string" || !STEP_ID.test(id)) throw badInput("a step id is lowercase letters, digits, - and _");
14305
+ if (typeof id !== "string" || !STEP_ID.test(id)) throw codedError("invalid_arguments", "a step id is lowercase letters, digits, - and _");
14130
14306
  const label = textOrPerLanguage(step?.label, MAX_LABEL_CHARS);
14131
- if (label === null) throw badInput("a step needs a label that says the step");
14307
+ if (label === null) throw codedError("invalid_arguments", "a step needs a label that says the step");
14132
14308
  const prompt = textOrPerLanguage(step?.prompt, MAX_PROMPT_CHARS);
14133
14309
  return { kind: "step", id, label, ...prompt === null ? {} : { payload: { prompt } } };
14134
14310
  });
14135
- if (new Set(out.steps.map((step) => step.id)).size !== out.steps.length) throw badInput("step ids repeat");
14311
+ if (new Set(out.steps.map((step) => step.id)).size !== out.steps.length) throw codedError("invalid_arguments", "step ids repeat");
14136
14312
  if (out.steps.length === 0) out.steps = null;
14137
14313
  }
14138
14314
  return out;
@@ -14142,9 +14318,9 @@ function parsePicks(document2, hasSource, limit = PICKS_LIMIT) {
14142
14318
  if (!Array.isArray(document2?.picks)) throw new Error("the recommender answered without a picks list");
14143
14319
  const out = [];
14144
14320
  const seen = /* @__PURE__ */ new Set();
14145
- for (const pick5 of document2.picks) {
14146
- const raw = pick5?.work;
14147
- const why = typeof pick5?.why === "string" ? pick5.why.trim().slice(0, MAX_WHY_CHARS) : "";
14321
+ for (const pick4 of document2.picks) {
14322
+ const raw = pick4?.work;
14323
+ const why = typeof pick4?.why === "string" ? pick4.why.trim().slice(0, MAX_WHY_CHARS) : "";
14148
14324
  if (typeof raw?.source !== "string" || !hasSource(raw.source) || why === "") continue;
14149
14325
  const work = resultOf(raw, null);
14150
14326
  if (work === null || work.title === "") continue;
@@ -14169,10 +14345,9 @@ var STOP_DIFF_S = 30;
14169
14345
  var REFINISH_MS = 36e5;
14170
14346
  var MAX_NAME2 = 120;
14171
14347
  var SUMS = "SHA256SUMS.txt";
14172
- var libraryError = (code, message) => Object.assign(new Error(message), { code });
14173
14348
  function cleanName(value) {
14174
14349
  const name2 = String(value ?? "").replace(/[\u0000-\u001f\u007f/\\]/g, "").trim().slice(0, MAX_NAME2);
14175
- if (name2 === "" || name2.startsWith(".")) throw libraryError("invalid", "give a name");
14350
+ if (name2 === "" || name2.startsWith(".")) throw codedError("invalid", "give a name");
14176
14351
  return name2;
14177
14352
  }
14178
14353
  function groupSeasons(shows) {
@@ -14201,26 +14376,17 @@ function createLibrary(options) {
14201
14376
  const metaFile = join15(stateDir, "shows.json");
14202
14377
  const cacheDir = join15(stateDir, "cache");
14203
14378
  let meta = {};
14204
- let saving = Promise.resolve();
14379
+ const saver = createJsonSaver(metaFile, logger);
14205
14380
  const listeners = /* @__PURE__ */ new Set();
14206
14381
  const changed = (show) => {
14207
14382
  for (const listener of listeners) listener(show);
14208
14383
  };
14209
14384
  async function load() {
14210
- try {
14211
- meta = JSON.parse(await readFile10(metaFile, "utf8")).shows ?? {};
14212
- } catch (error) {
14213
- if (error.code !== "ENOENT") logger.warn("could not read %s: %s", metaFile, error.message);
14214
- }
14385
+ meta = (await readJson2(metaFile, { logger })).value?.shows ?? {};
14215
14386
  }
14216
14387
  function save() {
14217
14388
  options.changed?.();
14218
- const body2 = JSON.stringify({ shows: meta }, null, 1);
14219
- saving = saving.then(async () => {
14220
- await writeFile6(`${metaFile}.part`, body2);
14221
- await rename7(`${metaFile}.part`, metaFile);
14222
- }).catch((error) => logger.warn("could not save %s: %s", metaFile, error.message));
14223
- return saving;
14389
+ return saver.save({ shows: meta });
14224
14390
  }
14225
14391
  const record = (path) => meta[path] ?? {};
14226
14392
  function update(path, patch) {
@@ -14230,16 +14396,17 @@ function createLibrary(options) {
14230
14396
  function showPath(path) {
14231
14397
  if (typeof path !== "string") return null;
14232
14398
  const target = resolve5(path);
14233
- return roots.includes(dirname6(target)) && !basename5(target).startsWith(".") ? target : null;
14399
+ return roots.includes(dirname7(target)) && !basename5(target).startsWith(".") ? target : null;
14234
14400
  }
14401
+ const sourcedPaths = () => Object.keys(meta).filter((path) => isSourced(meta[path]) && showPath(path) === path);
14235
14402
  function requireShow(path) {
14236
14403
  const target = showPath(path);
14237
- if (target === null) throw libraryError("not_found", "not a show in the library");
14404
+ if (target === null) throw codedError("not_found", "not a show in the library");
14238
14405
  return target;
14239
14406
  }
14240
14407
  function showOf(episodePath) {
14241
14408
  if (typeof episodePath !== "string") return null;
14242
- return showPath(episodePath) ?? showPath(dirname6(episodePath));
14409
+ return showPath(episodePath) ?? showPath(dirname7(episodePath));
14243
14410
  }
14244
14411
  async function episodeFiles(path) {
14245
14412
  const info = await stat9(path).catch(() => null);
@@ -14270,13 +14437,14 @@ function createLibrary(options) {
14270
14437
  }
14271
14438
  async function forgetSum(show, file) {
14272
14439
  const sums = join15(show, SUMS);
14273
- const text3 = await readFile10(sums, "utf8").catch(() => null);
14274
- if (text3 !== null) await writeFile6(sums, text3.split("\n").filter((line) => !line.endsWith(` ${file}`) && !line.endsWith(` *${file}`)).join("\n"));
14440
+ const text3 = await readFile8(sums, "utf8").catch(() => null);
14441
+ if (text3 !== null) await writeFile4(sums, text3.split("\n").filter((line) => !line.endsWith(` ${file}`) && !line.endsWith(` *${file}`)).join("\n"));
14275
14442
  }
14276
14443
  const note = (type, path, fields = {}) => options.record?.(type, { show: path, title: basename5(path), ...fields });
14444
+ const autoDeletes = (path) => options.autoDeleteDays > 0 && dirname7(path) === roots[0];
14277
14445
  function deletesAt(path) {
14278
14446
  const { countdownFrom, keep } = record(path);
14279
- if (!countdownFrom || keep || !(options.autoDeleteDays > 0)) return null;
14447
+ if (!countdownFrom || keep || !autoDeletes(path)) return null;
14280
14448
  return countdownFrom + options.autoDeleteDays * DAY_MS;
14281
14449
  }
14282
14450
  function watchOf(episodePath) {
@@ -14356,6 +14524,7 @@ function createLibrary(options) {
14356
14524
  newSeason: entry.newSeason ?? null,
14357
14525
  newEpisodes: entry.newEpisodes ?? null,
14358
14526
  group: entry.group ?? null,
14527
+ autoDeletes: autoDeletes(path),
14359
14528
  deletesAt: deletesAt(path),
14360
14529
  resume: resume2,
14361
14530
  finished,
@@ -14372,7 +14541,7 @@ function createLibrary(options) {
14372
14541
  return {
14373
14542
  load,
14374
14543
  /** Resolves once the notes written so far are on disk. */
14375
- flush: () => saving,
14544
+ flush: () => saver.settled(),
14376
14545
  showPath,
14377
14546
  showOf,
14378
14547
  resumeFrom: async (path) => resumeFrom(path, slotsOf(record(path), await episodeFiles(path) ?? [])),
@@ -14429,7 +14598,7 @@ function createLibrary(options) {
14429
14598
  },
14430
14599
  /** Paths of the shows that came from a source. */
14431
14600
  async sourcedShows() {
14432
- return Object.keys(meta).filter((path) => isSourced(meta[path]));
14601
+ return sourcedPaths();
14433
14602
  },
14434
14603
  /** Forget that these episodes were deleted by hand. */
14435
14604
  async unskip(path, numbers) {
@@ -14459,9 +14628,9 @@ function createLibrary(options) {
14459
14628
  /** Every cached episode of the shows the cap counts (sourced, not pinned), with its bytes (the prepared copy included) and when it was last watched or fetched. */
14460
14629
  async cacheEntries() {
14461
14630
  const out = [];
14462
- for (const path of Object.keys(meta)) {
14631
+ for (const path of sourcedPaths()) {
14463
14632
  const entry = meta[path];
14464
- if (!isSourced(entry) || entry.pinned === true) continue;
14633
+ if (entry.pinned === true) continue;
14465
14634
  for (const file of await episodeFiles(path) ?? []) {
14466
14635
  const n = episodeNumber(file.name);
14467
14636
  if (n === null) continue;
@@ -14487,7 +14656,7 @@ function createLibrary(options) {
14487
14656
  /** Keep a show's every episode on disk (or go back to the rolling cache). */
14488
14657
  async pin(path, pinned, { by = null } = {}) {
14489
14658
  const target = requireShow(path);
14490
- if (!isSourced(record(target))) throw libraryError("invalid", "only a show from a source can be kept offline");
14659
+ if (!isSourced(record(target))) throw codedError("invalid", "only a show from a source can be kept offline");
14491
14660
  update(target, { pinned });
14492
14661
  note(pinned ? "library.pinned" : "library.unpinned", target, { by });
14493
14662
  return { path: target, pinned };
@@ -14526,7 +14695,7 @@ function createLibrary(options) {
14526
14695
  setQuality(path, quality) {
14527
14696
  const target = requireShow(path);
14528
14697
  const entry = record(target);
14529
- if (!isSourced(entry)) throw libraryError("invalid", "this show has no source to fetch from");
14698
+ if (!isSourced(entry)) throw codedError("invalid", "this show has no source to fetch from");
14530
14699
  update(target, { source: { ...entry.source, quality } });
14531
14700
  },
14532
14701
  /** The saved (offline fallback) copy of a show's work, or null. */
@@ -14542,12 +14711,12 @@ function createLibrary(options) {
14542
14711
  },
14543
14712
  /** Note a show coming from a source, before its files arrive. */
14544
14713
  async adopt(path, source, { pinned = false } = {}) {
14545
- await mkdir9(path, { recursive: true });
14714
+ await mkdir10(path, { recursive: true });
14546
14715
  update(path, { source, addedAt: record(path).addedAt ?? now(), ...pinned ? { pinned: true } : {} });
14547
14716
  },
14548
14717
  async remove(path, { by = null, reason = "by hand" } = {}) {
14549
14718
  const target = requireShow(path);
14550
- if (inUse(target)) throw libraryError("in_use", "a room is playing this show; close the room first");
14719
+ if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
14551
14720
  await forget(target);
14552
14721
  await rm8(target, { recursive: true, force: true });
14553
14722
  delete meta[target];
@@ -14558,9 +14727,9 @@ function createLibrary(options) {
14558
14727
  async removeEpisode(path, name2, { by = null } = {}) {
14559
14728
  const target = requireShow(path);
14560
14729
  if ((await stat9(target)).isFile()) return this.remove(target, { by });
14561
- if (inUse(target)) throw libraryError("in_use", "a room is playing this show; close the room first");
14730
+ if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
14562
14731
  const file = cleanName(name2);
14563
- if (!isMedia(file)) throw libraryError("invalid", "not an episode");
14732
+ if (!isMedia(file)) throw codedError("invalid", "not an episode");
14564
14733
  await deleteEpisode(target, file);
14565
14734
  note("library.episodeDeleted", target, { episode: titleOf(file), by });
14566
14735
  const entry = record(target);
@@ -14571,14 +14740,14 @@ function createLibrary(options) {
14571
14740
  },
14572
14741
  async rename(path, name2, { by = null } = {}) {
14573
14742
  const target = requireShow(path);
14574
- if (inUse(target)) throw libraryError("in_use", "a room is playing this show; close the room first");
14575
- if (download(target)?.active) throw libraryError("in_use", "this show is still downloading");
14743
+ if (inUse(target)) throw codedError("in_use", "a room is playing this show; close the room first");
14744
+ if (download(target)?.active) throw codedError("in_use", "this show is still downloading");
14576
14745
  const isFile = (await stat9(target)).isFile();
14577
14746
  const clean = cleanName(name2);
14578
- const next = join15(dirname6(target), isFile && extname7(clean) === "" ? `${clean}${extname7(target)}` : clean);
14747
+ const next = join15(dirname7(target), isFile && extname7(clean) === "" ? `${clean}${extname7(target)}` : clean);
14579
14748
  if (next === target) return { path: target };
14580
- if (await stat9(next).then(() => true, () => false)) throw libraryError("exists", "a show with that name is already in the library");
14581
- await rename7(target, next);
14749
+ if (await stat9(next).then(() => true, () => false)) throw codedError("exists", "a show with that name is already in the library");
14750
+ await rename6(target, next);
14582
14751
  if (meta[target] !== void 0) {
14583
14752
  meta[next] = meta[target];
14584
14753
  delete meta[target];
@@ -14597,7 +14766,8 @@ function createLibrary(options) {
14597
14766
  /** Start the countdown now (or restart it): deleted `autoDeleteDays` from now unless kept. */
14598
14767
  async countdown(path, { by = null } = {}) {
14599
14768
  const target = requireShow(path);
14600
- if (!(options.autoDeleteDays > 0)) throw libraryError("invalid", "automatic deleting is off");
14769
+ if (!(options.autoDeleteDays > 0)) throw codedError("invalid", "automatic deleting is off");
14770
+ if (!autoDeletes(target)) throw codedError("invalid", "shows outside the hub's own library are never deleted on their own");
14601
14771
  const restart = deletesAt(target) !== null;
14602
14772
  update(target, { keep: false, countdownFrom: now() });
14603
14773
  note(restart ? "library.countdownRestarted" : "library.countdownStarted", target, { by, deletesAt: new Date(deletesAt(target)).toISOString() });
@@ -14626,15 +14796,16 @@ function createLibrary(options) {
14626
14796
  const entry = record(show);
14627
14797
  const finished = new Set(entry.finished ?? []);
14628
14798
  finished.add(basename5(episodePath));
14629
- const names = (await episodeFiles(show) ?? []).map((file) => file.name);
14630
- const keys = slotsOf(entry, await episodeFiles(show) ?? []).map((slot) => slot.key);
14799
+ const files = await episodeFiles(show) ?? [];
14800
+ const names = files.map((file) => file.name);
14801
+ const keys = slotsOf(entry, files).map((slot) => slot.key);
14631
14802
  const done = new Set([...finished].map((name2) => keyOf(entry, name2)));
14632
14803
  const complete = isSourced(entry) || names.length >= (entry.source?.episodes ?? names.length);
14633
14804
  const lastDone = complete && keys.length > 0 && done.has(keys[keys.length - 1]);
14634
14805
  const allDone = complete && keys.every((key) => done.has(key));
14635
14806
  const newFinish = (lastDone || allDone) && (!entry.watchedAt || now() - entry.watchedAt > REFINISH_MS);
14636
14807
  update(show, { finished: [...finished], ...newFinish ? { watchedAt: now(), countdownFrom: now() } : {} });
14637
- if (newFinish && !entry.keep && options.autoDeleteDays > 0) note("library.countdownStarted", show, { by: null, reason: "watched to the end", deletesAt: new Date(deletesAt(show)).toISOString() });
14808
+ if (newFinish && !entry.keep && autoDeletes(show)) note("library.countdownStarted", show, { by: null, reason: "watched to the end", deletesAt: new Date(deletesAt(show)).toISOString() });
14638
14809
  changed(show);
14639
14810
  },
14640
14811
  /** Delete watched shows whose time has come, unless kept, open in a room or downloading. */
@@ -14655,7 +14826,7 @@ function createLibrary(options) {
14655
14826
  }
14656
14827
 
14657
14828
  // src/remarks.js
14658
- import { mkdir as mkdir10, readFile as readFile11, rename as rename8, writeFile as writeFile7 } from "node:fs/promises";
14829
+ import { readFile as readFile9 } from "node:fs/promises";
14659
14830
  import { join as join16 } from "node:path";
14660
14831
  var HOUR_MS = 36e5;
14661
14832
  var DAY_MS2 = 24 * HOUR_MS;
@@ -14664,16 +14835,14 @@ function createRemarks({ source, logger, now = Date.now, danmakuMaxAgeMs = DAY_M
14664
14835
  const flying = /* @__PURE__ */ new Map();
14665
14836
  async function read(file) {
14666
14837
  try {
14667
- const copy = JSON.parse(await readFile11(file, "utf8"));
14838
+ const copy = JSON.parse(await readFile9(file, "utf8"));
14668
14839
  return Number.isFinite(copy?.at) ? copy : null;
14669
14840
  } catch {
14670
14841
  return null;
14671
14842
  }
14672
14843
  }
14673
14844
  async function keep(file, value) {
14674
- await mkdir10(join16(file, ".."), { recursive: true });
14675
- await writeFile7(`${file}.part`, JSON.stringify(value));
14676
- await rename8(`${file}.part`, file);
14845
+ await writeJson(file, value);
14677
14846
  }
14678
14847
  function fetchInto(file, ask) {
14679
14848
  if (!flying.has(file)) {
@@ -14872,79 +15041,27 @@ function createExtras({ points, night, locales, now = Date.now }) {
14872
15041
  };
14873
15042
  }
14874
15043
 
14875
- // src/changes.js
14876
- function createChanges({ intervalMs = 300 } = {}) {
14877
- const listeners = /* @__PURE__ */ new Set();
14878
- let pending = /* @__PURE__ */ new Set();
14879
- let timer = null;
14880
- let lastAt = 0;
14881
- function flush() {
14882
- timer = null;
14883
- lastAt = Date.now();
14884
- const what = [...pending];
14885
- pending = /* @__PURE__ */ new Set();
14886
- for (const listener of listeners) listener(what);
14887
- }
14888
- return {
14889
- notify(kind) {
14890
- pending.add(kind);
14891
- if (timer !== null) return;
14892
- timer = setTimeout(flush, Math.max(0, lastAt + intervalMs - Date.now()));
14893
- timer.unref?.();
14894
- },
14895
- /** @returns {() => void} stop listening */
14896
- listen(listener) {
14897
- listeners.add(listener);
14898
- return () => listeners.delete(listener);
14899
- },
14900
- close() {
14901
- clearTimeout(timer);
14902
- timer = null;
14903
- listeners.clear();
14904
- }
14905
- };
14906
- }
14907
-
14908
15044
  // src/copies.js
14909
- import { mkdir as mkdir11, readFile as readFile12, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
14910
- import { dirname as dirname7 } from "node:path";
14911
15045
  var DAY_MS4 = 864e5;
14912
15046
  var HOUR_MS2 = 36e5;
14913
15047
  function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOUR_MS2, parallel = 4, now = Date.now }) {
14914
15048
  const copies = /* @__PURE__ */ new Map();
14915
15049
  const flying = /* @__PURE__ */ new Map();
14916
15050
  const failedAt = /* @__PURE__ */ new Map();
14917
- const waiting = [];
14918
- let running = 0;
14919
- let saving = Promise.resolve();
14920
- const loaded = readFile12(file, "utf8").then((text3) => {
14921
- for (const [key, copy] of Object.entries(JSON.parse(text3))) copies.set(key, copy);
14922
- }).catch((error) => {
14923
- if (error.code !== "ENOENT") logger.warn("the saved copies of Discover could not be read: %s", error.message);
15051
+ const saver = createJsonSaver(file, logger);
15052
+ const loaded = readJson2(file, { logger }).then(({ value }) => {
15053
+ for (const [key, copy] of Object.entries(value ?? {})) copies.set(key, copy);
14924
15054
  });
14925
15055
  function save() {
14926
- saving = saving.then(async () => {
14927
- await mkdir11(dirname7(file), { recursive: true });
14928
- await writeFile8(`${file}.part`, JSON.stringify(Object.fromEntries(copies)));
14929
- await rename9(`${file}.part`, file);
14930
- }).catch((error) => logger.warn("the copies of Discover could not be saved: %s", error.message));
14931
- return saving;
14932
- }
14933
- function pump() {
14934
- while (running < parallel && waiting.length > 0) {
14935
- running += 1;
14936
- waiting.shift()().finally(() => {
14937
- running -= 1;
14938
- pump();
14939
- });
14940
- }
15056
+ return saver.save(Object.fromEntries(copies));
14941
15057
  }
15058
+ const limit = createLimiter(parallel);
14942
15059
  function ask(key, produce) {
14943
15060
  let settled;
14944
15061
  flying.set(key, new Promise((resolve8) => {
14945
15062
  settled = resolve8;
14946
15063
  }));
14947
- waiting.push(async () => {
15064
+ limit(async () => {
14948
15065
  try {
14949
15066
  copies.set(key, { at: now(), value: await produce() });
14950
15067
  failedAt.delete(key);
@@ -14959,7 +15076,6 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
14959
15076
  settled();
14960
15077
  }
14961
15078
  });
14962
- pump();
14963
15079
  }
14964
15080
  return {
14965
15081
  /**
@@ -14989,12 +15105,11 @@ function createCopies({ file, changed, logger, maxAgeMs = DAY_MS4, retryMs = HOU
14989
15105
  }
14990
15106
 
14991
15107
  // src/discover.js
14992
- var notFound = (message) => Object.assign(new Error(message), { code: "not_found" });
14993
15108
  function createDiscover({ copies, sources, covers, recommender }) {
14994
15109
  async function sourcesFor(sourceId, kind, ability) {
14995
15110
  if (sourceId !== ALL_SOURCES) {
14996
15111
  const one = sources.get(sourceId);
14997
- if (one === void 0) throw notFound(`no source ${String(sourceId)}`);
15112
+ if (one === void 0) throw codedError("not_found", `no source ${String(sourceId)}`);
14998
15113
  return [one];
14999
15114
  }
15000
15115
  const found = [];
@@ -15038,7 +15153,7 @@ function createDiscover({ copies, sources, covers, recommender }) {
15038
15153
  }
15039
15154
  return recommend(recommender, { person, language, candidates });
15040
15155
  });
15041
- return { picks: (copy.value ?? []).map((pick5) => ({ ...pick5, work: withCovers(sources.get(pick5.work.source), pick5.work) })), loading: copy.loading };
15156
+ return { picks: (copy.value ?? []).map((pick4) => ({ ...pick4, work: withCovers(sources.get(pick4.work.source), pick4.work) })), loading: copy.loading };
15042
15157
  }
15043
15158
  };
15044
15159
  }
@@ -15049,17 +15164,7 @@ var HOUR_MS3 = 36e5;
15049
15164
  function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS3, parallel = 2, now = Date.now, logger }) {
15050
15165
  const flying = /* @__PURE__ */ new Set();
15051
15166
  const failedAt = /* @__PURE__ */ new Map();
15052
- const waiting = [];
15053
- let running = 0;
15054
- function pump() {
15055
- while (running < parallel && waiting.length > 0) {
15056
- running += 1;
15057
- waiting.shift()().finally(() => {
15058
- running -= 1;
15059
- pump();
15060
- });
15061
- }
15062
- }
15167
+ const limit = createLimiter(parallel);
15063
15168
  return function touch(path, entry) {
15064
15169
  const sourceId = entry.source?.source;
15065
15170
  const found = sourceId ? source(sourceId) : void 0;
@@ -15068,7 +15173,7 @@ function createWorkRefresh({ source, keep, maxAgeMs = DAY_MS5, retryMs = HOUR_MS
15068
15173
  ${entry.source.id}`;
15069
15174
  if (flying.has(key) || now() - (failedAt.get(key) ?? -Infinity) < retryMs) return;
15070
15175
  flying.add(key);
15071
- waiting.push(async () => {
15176
+ limit(async () => {
15072
15177
  try {
15073
15178
  keep(path, snapshotOf(await found.info(entry.source.id, { person: entry.source.person }), now()));
15074
15179
  failedAt.delete(key);
@@ -15079,7 +15184,6 @@ ${entry.source.id}`;
15079
15184
  flying.delete(key);
15080
15185
  }
15081
15186
  });
15082
- pump();
15083
15187
  };
15084
15188
  }
15085
15189
 
@@ -15087,14 +15191,13 @@ ${entry.source.id}`;
15087
15191
  var HOUR_MS4 = 36e5;
15088
15192
  var MIN_FREE_BYTES = 1e9;
15089
15193
  var NO_CONVERTER = Object.freeze({ command: "", available: async () => false });
15090
- var hubError = (code, message) => Object.assign(new Error(message), { code });
15091
15194
  function createMediaHub(options) {
15092
15195
  const { stateDir, libraryRoots, logger, now = Date.now } = options;
15093
15196
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
15094
15197
  const covers = createCovers({ dir: join17(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
15095
15198
  const log = createWatchLog({ file: join17(stateDir, LOG_NAME), now, logger });
15096
- const changes = createChanges({ intervalMs: options.changeIntervalMs });
15097
- const points = createExtras({ points: options.points ?? (() => void 0), night: options.bingeNight ?? { from: "01:00", to: "06:00" }, locales: () => readLocales(LOCALE_DIR, logger), now });
15199
+ const changes = createNotices({ spacingMs: options.changeIntervalMs ?? 300 });
15200
+ const points = createExtras({ points: options.points ?? (() => void 0), night: options.bingeNight ?? { from: "01:00", to: "06:00" }, locales: () => readWords(LOCALE_DIR, logger), now });
15098
15201
  const books = createBooks({ changed: () => changes.notify("shelf"), dir: join17(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
15099
15202
  let rooms;
15100
15203
  let cache;
@@ -15158,14 +15261,13 @@ function createMediaHub(options) {
15158
15261
  recommender: { command: options.recommender?.command ?? [], env: options.recommender?.env ?? {}, cwd: stateDir, hasSource: (id) => sources.has(id) }
15159
15262
  });
15160
15263
  const sweepTimer = setInterval(() => {
15161
- library.sweep().catch(() => {
15162
- });
15264
+ library.sweep().catch((error) => logger.warn("library sweep: %s", error.message));
15163
15265
  cache.enforce().catch(() => {
15164
15266
  });
15165
15267
  }, HOUR_MS4);
15166
15268
  function roomShow(id) {
15167
15269
  const room = rooms.listRooms().find((entry) => entry.id === id);
15168
- if (room === void 0) throw hubError("not_found", "no such room");
15270
+ if (room === void 0) throw codedError("not_found", "no such room");
15169
15271
  return room.show;
15170
15272
  }
15171
15273
  async function onFiles(job) {
@@ -15190,7 +15292,7 @@ function createMediaHub(options) {
15190
15292
  }
15191
15293
  const followStart = (info, at = now()) => ({ since: at, seen: seenAtStart(info.id, info), checkedAt: at, nextAt: nextCheckAt(at, (options.follow?.random ?? Math.random)()) });
15192
15294
  async function adoptEmpty(sourceId, item) {
15193
- if (!(item.episodes > 0)) throw hubError("empty", `${item.title || item.id} has no episodes yet`);
15295
+ if (!(item.episodes > 0)) throw codedError("empty", `${item.title || item.id} has no episodes yet`);
15194
15296
  const dir = await folderFor(sourceId, item);
15195
15297
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title });
15196
15298
  library.setWork(dir, snapshotOf(item, now()));
@@ -15222,7 +15324,7 @@ function createMediaHub(options) {
15222
15324
  const withCovers = (show) => show.work && show.source?.source ? { ...show, work: covers.decorate(show.source.source, show.work) } : show;
15223
15325
  function source(id) {
15224
15326
  const found = sources.get(id);
15225
- if (found === void 0) throw hubError("not_found", `no source ${String(id)}`);
15327
+ if (found === void 0) throw codedError("not_found", `no source ${String(id)}`);
15226
15328
  return found;
15227
15329
  }
15228
15330
  async function isNewSeries(sourceId, item) {
@@ -15247,7 +15349,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15247
15349
  const owner = shows.find((show) => show.path === path);
15248
15350
  if (!exists2 || owner?.source?.source === sourceId && owner.source.id === item.id) return path;
15249
15351
  }
15250
- throw hubError("exists", `${cleanName(item.title)} is already in the library`);
15352
+ throw codedError("exists", `${cleanName(item.title)} is already in the library`);
15251
15353
  }
15252
15354
  return {
15253
15355
  async load() {
@@ -15255,8 +15357,9 @@ ${work.id}`).digest("hex").slice(0, 8);
15255
15357
  await books.load();
15256
15358
  await rooms.load();
15257
15359
  await downloads.load();
15258
- await library.sweep();
15259
- await cache.refreshActive();
15360
+ await library.sweep().catch((error) => logger.warn("library sweep: %s", error.message));
15361
+ await cache.refreshActive().catch(() => {
15362
+ });
15260
15363
  follows.start();
15261
15364
  },
15262
15365
  // ---------------------------------------------------------- rooms
@@ -15317,7 +15420,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15317
15420
  },
15318
15421
  async startStep(path, id, person) {
15319
15422
  const show = library.showPath(path);
15320
- if (show === null || !library.stepStarted(show, id)) throw hubError("not_found", "no such step");
15423
+ if (show === null || !library.stepStarted(show, id)) throw codedError("not_found", "no such step");
15321
15424
  await log.append("step.started", { show, title: library.workOf(show)?.title ?? "", step: id, person: person.key, by: person.name });
15322
15425
  return { ok: true };
15323
15426
  },
@@ -15362,7 +15465,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15362
15465
  async roomQuality(id, quality) {
15363
15466
  const show = roomShow(id);
15364
15467
  const offered = show === null ? [] : library.workOf(show)?.qualities ?? [];
15365
- if (!isQuality(quality) || !offered.includes(quality)) throw hubError("invalid", "the show is not offered in this quality");
15468
+ if (!isQuality(quality) || !offered.includes(quality)) throw codedError("invalid", "the show is not offered in this quality");
15366
15469
  await cache.requality(show, quality);
15367
15470
  return { quality };
15368
15471
  },
@@ -15394,7 +15497,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15394
15497
  }
15395
15498
  const answers = await Promise.allSettled(candidates.map((one) => ask(one)));
15396
15499
  const failed = answers.flatMap((answer, index) => answer.status === "rejected" ? [{ source: candidates[index].id, message: answer.reason?.message ?? String(answer.reason) }] : []);
15397
- if (candidates.length > 0 && failed.length === candidates.length) throw hubError("source_failed", failed.map((entry) => entry.message).join("; "));
15500
+ if (candidates.length > 0 && failed.length === candidates.length) throw codedError("source_failed", failed.map((entry) => entry.message).join("; "));
15398
15501
  return { results: interleave(answers.map((answer) => answer.status === "fulfilled" ? answer.value.results : [])), next: null, failed };
15399
15502
  },
15400
15503
  /** A work's details; `person` and `language` say who asks (their account for its site) and in which language (subtitles). */
@@ -15410,12 +15513,12 @@ ${work.id}`).digest("hex").slice(0, 8);
15410
15513
  */
15411
15514
  async fetch({ source: sourceId, id, watch = false, together = false, all = false, quality = "", by = "", person = "", language = "" }) {
15412
15515
  const item = await source(sourceId).info(id, { person, language });
15413
- if (!(item.episodes > 0)) throw hubError("empty", `${item.title || id} has no episodes`);
15516
+ if (!(item.episodes > 0)) throw codedError("empty", `${item.title || id} has no episodes`);
15414
15517
  const dir = await folderFor(sourceId, item);
15415
15518
  const subject = `${sourceId}:${item.id}`;
15416
15519
  const isNew = points.enabled && await isNewSeries(sourceId, item);
15417
15520
  const disk = await statfs2(libraryRoots[0]).catch(() => null);
15418
- if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw hubError("no_space", "the library disk is almost full; delete something first");
15521
+ if (disk !== null && disk.bavail * disk.bsize < MIN_FREE_BYTES) throw codedError("no_space", "the library disk is almost full; delete something first");
15419
15522
  const tickets = await points.pay(person, points.wants({ isNew, starts: watch }), { subject });
15420
15523
  const how = { ...isQuality(quality) ? { quality } : {}, person, language };
15421
15524
  await library.adopt(dir, { source: sourceId, id: item.id, kind: item.kind, episodes: item.episodes, title: item.title, ...how }, { pinned: all });
@@ -15461,7 +15564,7 @@ ${work.id}`).digest("hex").slice(0, 8);
15461
15564
  /** Start a show's download again after it failed. */
15462
15565
  async retryDownload(path) {
15463
15566
  const show = library.showPath(path);
15464
- if (show === null || downloads.job(show) === void 0) throw hubError("not_found", "no download for this show");
15567
+ if (show === null || downloads.job(show) === void 0) throw codedError("not_found", "no download for this show");
15465
15568
  downloads.retry(show);
15466
15569
  await cache.refresh(show, { retry: true });
15467
15570
  return { download: downloads.state(show) };
@@ -15508,9 +15611,8 @@ ${identity.id}`).digest("hex").slice(0, 20);
15508
15611
 
15509
15612
  // src/person-routes.js
15510
15613
  var PERSON_PATH = "/api/media-hub";
15511
- var HEADERS = Object.freeze({ "cache-control": "no-store", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" });
15512
- var json = (status, body2) => new Response(JSON.stringify(body2), { status, headers: { ...HEADERS, "content-type": "application/json; charset=utf-8" } });
15513
- var failure2 = (error) => json(error?.status ?? STATUS[error?.code] ?? 500, errorBody(error));
15614
+ var json = (status, body2) => new Response(JSON.stringify(body2), { status, headers: { ...SECURITY_HEADERS, "content-type": "application/json; charset=utf-8" } });
15615
+ var failure2 = (error) => json(statusOf(error), errorBody(error));
15514
15616
  async function body(request) {
15515
15617
  try {
15516
15618
  const value = await request.json();
@@ -15519,7 +15621,6 @@ async function body(request) {
15519
15621
  throw Object.assign(new Error("request body is not JSON"), { status: 400 });
15520
15622
  }
15521
15623
  }
15522
- var pick4 = (value, keys) => Object.fromEntries(keys.filter((key) => value?.[key] !== void 0).map((key) => [key, value[key]]));
15523
15624
  var text2 = (value) => typeof value === "string" ? value : "";
15524
15625
  function createPersonRoutes({ hub, identity }) {
15525
15626
  const handle = (fn) => async (request) => {
@@ -15545,7 +15646,7 @@ function createPersonRoutes({ hub, identity }) {
15545
15646
  requestBody: "buffered",
15546
15647
  fetch: handle(async (request, current, person) => {
15547
15648
  const input = await body(request);
15548
- return current.fetch({ ...pick4(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id });
15649
+ return current.fetch({ ...pick3(input, ["source", "id", "watch", "together", "all", "quality", "by"]), language: text2(input.language), person: person.id });
15549
15650
  })
15550
15651
  },
15551
15652
  {
@@ -15554,7 +15655,7 @@ function createPersonRoutes({ hub, identity }) {
15554
15655
  requestBody: "buffered",
15555
15656
  fetch: handle(async (request, current, person) => {
15556
15657
  const input = await body(request);
15557
- return current.createRoom({ ...pick4(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id });
15658
+ return current.createRoom({ ...pick3(input, ["path", "title", "by", "start"]), fromPanel: true, person: person.id });
15558
15659
  })
15559
15660
  },
15560
15661
  {
@@ -15583,8 +15684,7 @@ function createPersonRoutes({ hub, identity }) {
15583
15684
 
15584
15685
  // src/events-route.js
15585
15686
  var EVENTS_PATH = "/api/media-hub/events";
15586
- var HEARTBEAT_MS = 25e3;
15587
- function createEventsRoute({ hub }) {
15687
+ function createEventsRoute({ hub, streams }) {
15588
15688
  return {
15589
15689
  path: EVENTS_PATH,
15590
15690
  methods: ["GET"],
@@ -15592,40 +15692,7 @@ function createEventsRoute({ hub }) {
15592
15692
  fetch: async (request) => {
15593
15693
  const current = hub();
15594
15694
  if (current === void 0) return json(503, { error: { code: "unavailable", message: "The media hub is starting." } });
15595
- const encoder = new TextEncoder();
15596
- let stop = () => {
15597
- };
15598
- const stream = new ReadableStream({
15599
- start(controller) {
15600
- const write2 = (chunk) => {
15601
- try {
15602
- controller.enqueue(encoder.encode(chunk));
15603
- } catch {
15604
- stop();
15605
- }
15606
- };
15607
- write2("retry: 5000\n: open\n\n");
15608
- const unlisten = current.listenChanges((what) => write2(`data: ${JSON.stringify({ type: "change", what })}
15609
-
15610
- `));
15611
- const beat = setInterval(() => write2(": beat\n\n"), HEARTBEAT_MS);
15612
- stop = () => {
15613
- unlisten();
15614
- clearInterval(beat);
15615
- };
15616
- request.signal?.addEventListener("abort", () => {
15617
- stop();
15618
- try {
15619
- controller.close();
15620
- } catch {
15621
- }
15622
- }, { once: true });
15623
- },
15624
- cancel() {
15625
- stop();
15626
- }
15627
- });
15628
- return new Response(stream, { status: 200, headers: { ...HEADERS, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no" } });
15695
+ return streams.respond(request, ({ send }) => current.listenChanges((what) => send({ type: "change", what })));
15629
15696
  }
15630
15697
  };
15631
15698
  }
@@ -15638,15 +15705,10 @@ var SHELF_PATH = "/api/media-hub/shelf";
15638
15705
  async function fileResponse(request, { path, name: name2, type }) {
15639
15706
  const info = await stat11(path).catch(() => null);
15640
15707
  if (info === null || !info.isFile()) return json(404, { error: { code: "not_found", message: "the file is gone" } });
15641
- const range = resolveRange(request.headers.get("range"), info.size);
15642
- const headers = { ...HEADERS, "content-type": type, "content-disposition": attachment(name2), "accept-ranges": "bytes" };
15643
- if (range.kind === "unsatisfiable") return new Response(null, { status: 416, headers: { ...headers, "content-range": `bytes */${info.size}` } });
15644
- const start = range.kind === "window" ? range.start : 0;
15645
- const end = range.kind === "window" ? range.end : info.size - 1;
15646
- headers["content-length"] = String(info.size === 0 ? 0 : end - start + 1);
15647
- if (range.kind === "window") headers["content-range"] = `bytes ${start}-${end}/${info.size}`;
15648
- const stream = request.method === "HEAD" || info.size === 0 ? null : Readable2.toWeb(createReadStream3(path, { start, end }));
15649
- return new Response(stream, { status: range.kind === "window" ? 206 : 200, headers });
15708
+ const plan = rangePlan(request.headers.get("range"), info.size);
15709
+ const headers = { ...SECURITY_HEADERS, "content-type": type, "content-disposition": attachment(name2), "accept-ranges": "bytes", ...plan.headers };
15710
+ const stream = plan.status === 416 || request.method === "HEAD" || info.size === 0 ? null : Readable2.toWeb(createReadStream3(path, { start: plan.start, end: plan.end }));
15711
+ return new Response(stream, { status: plan.status, headers });
15650
15712
  }
15651
15713
  function createShelfRoutes({ books, identity }) {
15652
15714
  const handle = (fn) => async (request) => {
@@ -15723,14 +15785,14 @@ function apply(ctx, config) {
15723
15785
  return service.pruneCache(config.cacheDays);
15724
15786
  }).catch((error) => logger.warn("could not start rooms: %s", error.message));
15725
15787
  const prune = setInterval(() => {
15726
- service.pruneCache(config.cacheDays).catch(() => {
15727
- });
15788
+ service.pruneCache(config.cacheDays).catch((error) => logger.warn("pruning the cache: %s", error.message));
15728
15789
  }, DAY_MS6);
15729
15790
  const identity = () => ctx.get("requestIdentity");
15791
+ const streams = createEventStreams({ headers: SECURITY_HEADERS });
15730
15792
  const fetchRoutes = [
15731
15793
  ...createShelfRoutes({ books: () => current?.books, identity }),
15732
15794
  ...createPersonRoutes({ hub: () => current, identity }),
15733
- createEventsRoute({ hub: () => current })
15795
+ createEventsRoute({ hub: () => current, streams })
15734
15796
  ].map((route) => ctx.connection.fetch.register(route));
15735
15797
  const sockets = new import_websocket_server.default({ noServer: true, maxPayload: 16 * 1024, perMessageDeflate: false });
15736
15798
  const disposeHttp = ctx.webServer.register({
@@ -15758,6 +15820,7 @@ function apply(ctx, config) {
15758
15820
  disposeUpgrade();
15759
15821
  disposeHttp();
15760
15822
  await Promise.all(fetchRoutes.map((dispose) => dispose()));
15823
+ streams.close();
15761
15824
  await loading;
15762
15825
  await service.dispose();
15763
15826
  sockets.close();