dsh-clash-subscription 0.2.3 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/discovery.js CHANGED
@@ -1,94 +1,52 @@
1
1
  /**
2
- * Optional local Clash/mihomo installation discovery.
2
+ * Where the core comes from.
3
3
  *
4
- * This module deliberately knows nothing about a user's subscriptions, node choices,
5
- * or profile files: a published plugin must not read whatever proxy configuration
6
- * happens to sit on the installation machine. What it does provide is the two pieces
7
- * of machine-level information that are genuinely reusable and contain no personal
8
- * data:
4
+ * This plugin owns its core. It does not look for a Clash installation, does not read
5
+ * another client's directories, and does not use one it happens to find: a machine with a
6
+ * desktop Clash client and a machine without one must behave identically, or the plugin's
7
+ * behaviour depends on something the user never asked it to depend on.
9
8
  *
10
- * - where a mihomo-compatible executable lives, so the user does not have to type a
11
- * path to a core the machine already has; and
12
- * - where downloaded GeoIP/GeoSite databases live, because the core needs them before
13
- * it can classify a single connection, and the alternative is a download over the
14
- * very tunnel those databases are needed to establish.
9
+ * Two sources exist, in this order:
15
10
  *
16
- * Everything else — subscription URL, node choice, routing rules — comes from the
17
- * plugin's own configuration.
11
+ * 1. `corePath` from the plugin's own configuration, when the user deliberately points at
12
+ * an executable; and
13
+ * 2. the copy this plugin unpacked from `vendor/` into its own data directory.
14
+ *
15
+ * Nothing else. A search of `Program Files` for a mihomo binary was removed on purpose:
16
+ * borrowing another client's executable is the kind of hidden dependency that makes a
17
+ * failure unexplainable later.
18
18
  *
19
19
  * @module dsh-clash-proxy/discovery
20
20
  */
21
21
  import { existsSync } from 'node:fs'
22
22
  import { join } from 'node:path'
23
23
 
24
- /** Core executable names a Clash/mihomo installation ships, most specific first. */
25
- const CORE_BINARIES = ['verge-mihomo.exe', 'verge-mihomo-alpha.exe', 'mihomo.exe', 'clash-meta.exe', 'clash.exe']
26
-
27
- /** Directories a desktop Clash client installs its core into. */
28
- const CORE_DIRS = [
29
- 'C:/Program Files/Clash Verge',
30
- 'C:/Program Files/Clash Verge Rev',
31
- 'C:/Program Files/mihomo',
32
- 'C:/Program Files/Clash Meta',
33
- ]
34
-
35
- /** Directory names a desktop Clash client uses for its data under the roaming profile. */
36
- const DATA_DIR_NAMES = ['io.github.clash-verge-rev.clash-verge-rev', 'clash-verge', 'mihomo', 'Clash Verge']
24
+ /** Executable name this plugin stores its verified core under. */
25
+ export const CORE_NAME = process.platform === 'win32' ? 'mihomo.exe' : 'mihomo'
37
26
 
38
27
  /**
39
- * Find a mihomo-compatible core.
28
+ * The executable this plugin unpacked into its own data directory.
40
29
  *
41
- * @param configured - an explicit path from plugin config; when it names a file it wins.
42
- * @returns the absolute binary path, or undefined when none was found.
30
+ * @param dataDir - the plugin's data directory.
31
+ * @returns the path when present, else undefined.
43
32
  */
44
- export function findCoreBinary(configured) {
45
- if (typeof configured === 'string' && configured.trim() !== '') {
46
- const path = configured.trim()
47
- if (existsSync(path)) return path
48
- }
49
- for (const dir of CORE_DIRS) {
50
- for (const name of CORE_BINARIES) {
51
- const candidate = join(dir, name)
52
- if (existsSync(candidate)) return candidate
53
- }
54
- }
55
- for (const root of [process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']]) {
56
- if (typeof root !== 'string' || root === '') continue
57
- for (const name of CORE_BINARIES) {
58
- for (const sub of ['Clash Verge', 'mihomo', 'Clash Meta', '']) {
59
- const candidate = join(root, sub, name)
60
- if (existsSync(candidate)) return candidate
61
- }
62
- }
63
- }
64
- return undefined
33
+ export function ownCorePath(dataDir) {
34
+ if (typeof dataDir !== 'string' || dataDir.trim() === '') return undefined
35
+ const candidate = join(dataDir.trim(), 'bin', CORE_NAME)
36
+ return existsSync(candidate) ? candidate : undefined
65
37
  }
66
38
 
67
39
  /**
68
- * Directories that may hold downloaded geo databases.
40
+ * Resolve the executable to run.
69
41
  *
70
- * Only the directory itself is used; no file in it is read except the four database
71
- * files named by {@link GEO_ASSETS}, and nothing is written back.
72
- *
73
- * @returns existing candidate directories, most likely first.
42
+ * @param configured - `corePath` from this plugin's configuration; empty means "use ours".
43
+ * @param dataDir - the plugin's data directory.
44
+ * @returns the absolute binary path, or undefined when neither source has one.
74
45
  */
75
- export function geoDirs() {
76
- const found = []
77
- const roots = [process.env.APPDATA, process.env.LOCALAPPDATA]
78
- for (const root of roots) {
79
- if (typeof root !== 'string' || root === '') continue
80
- for (const name of DATA_DIR_NAMES) {
81
- const dir = join(root, name)
82
- if (existsSync(dir) && !found.includes(dir)) found.push(dir)
83
- }
46
+ export function findCoreBinary(configured, dataDir) {
47
+ if (typeof configured === 'string' && configured.trim() !== '') {
48
+ const path = configured.trim()
49
+ if (existsSync(path)) return path
84
50
  }
85
- return found
51
+ return ownCorePath(dataDir)
86
52
  }
87
-
88
- /** Geo assets a core needs before it can evaluate GEOIP/GEOSITE rules. */
89
- export const GEO_ASSETS = [
90
- { source: 'Country.mmdb', targets: ['Country.mmdb', 'geoip.metadb'] },
91
- { source: 'geoip.dat', targets: ['geoip.dat'] },
92
- { source: 'geosite.dat', targets: ['geosite.dat'] },
93
- { source: 'ASN.mmdb', targets: ['ASN.mmdb'] },
94
- ]
package/lib/geo.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Optional GeoIP upgrade, performed only after the tunnel works.
3
+ *
4
+ * The plugin already classifies Chinese addresses correctly from its own embedded CIDR
5
+ * list, so a GeoIP database is an *upgrade*, not a requirement. That distinction decides
6
+ * the order of operations: a database can only be fetched over a working connection, and
7
+ * the connection only exists once a subscription is imported and the core is up. Fetching
8
+ * it during startup was the original mistake — the core refused to boot while it tried, and
9
+ * the fallback then sent domestic `.com` sites through a foreign node.
10
+ *
11
+ * So this runs after routing is confirmed healthy, in the background, and a failure is
12
+ * recorded and forgotten rather than surfaced as a fault.
13
+ *
14
+ * @module dsh-clash-proxy/geo
15
+ */
16
+ import { createHash } from 'node:crypto'
17
+ import { existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /**
21
+ * GeoIP databases worth having, with the mirror that serves them without GitHub.
22
+ *
23
+ * `Country.mmdb` is the one that matters: it is what `GEOIP,` rules read. The `.dat` files
24
+ * serve `GEOSITE,` rules, which this plugin's generated rule set does not use, so they are
25
+ * listed for completeness and fetched only when a mirror offers them.
26
+ *
27
+ * jsDelivr is tried first because it is reachable from mainland China; the GitHub raw URLs
28
+ * are the fallback for a machine that already has a working tunnel but no jsDelivr route.
29
+ */
30
+ const GEO_SOURCES = {
31
+ 'Country.mmdb': [
32
+ 'https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/country.mmdb',
33
+ 'https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/release/country.mmdb',
34
+ ],
35
+ 'geoip.dat': [
36
+ 'https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat',
37
+ 'https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/release/geoip.dat',
38
+ ],
39
+ }
40
+
41
+ /**
42
+ * The file names this module manages.
43
+ *
44
+ * @type {readonly string[]}
45
+ */
46
+ export const GEO_FILES = Object.keys(GEO_SOURCES)
47
+
48
+ /**
49
+ * Whether a usable database is already in place.
50
+ *
51
+ * @param workDir - the core's data directory.
52
+ * @returns true when `Country.mmdb` exists and is not a stub.
53
+ */
54
+ export function hasGeoDatabase(workDir) {
55
+ const path = join(workDir, 'Country.mmdb')
56
+ try {
57
+ // A zero-byte or tiny file is what a failed download leaves behind; treat it as absent.
58
+ return existsSync(path) && statSync(path).size > 1024
59
+ } catch {
60
+ return false
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Download one database, trying each source in turn.
66
+ *
67
+ * @param name - target file name.
68
+ * @param workDir - destination directory.
69
+ * @param fetchImpl - fetch implementation, injectable for a test.
70
+ * @param timeoutMs - per-attempt budget.
71
+ * @returns the byte count and the source that served it.
72
+ */
73
+ async function fetchOne(name, workDir, fetchImpl, timeoutMs) {
74
+ const problems = []
75
+ for (const url of GEO_SOURCES[name] ?? []) {
76
+ try {
77
+ const response = await fetchImpl(url, {
78
+ redirect: 'follow',
79
+ headers: { 'user-agent': 'dsh-clash-subscription' },
80
+ signal: AbortSignal.timeout(timeoutMs),
81
+ })
82
+ if (!response.ok) throw new Error(`answered ${response.status}`)
83
+ const buffer = Buffer.from(await response.arrayBuffer())
84
+ if (buffer.length < 1024) throw new Error(`only ${buffer.length} bytes`)
85
+ // A database is read by the core at startup, so it must never be half-written: stage
86
+ // it under a temporary name and rename into place.
87
+ const staged = join(workDir, `${name}.part`)
88
+ writeFileSync(staged, buffer)
89
+ const destination = join(workDir, name)
90
+ if (existsSync(destination)) rmSync(destination, { force: true })
91
+ renameSync(staged, destination)
92
+ return { name, bytes: buffer.length, source: new URL(url).host, digest: createHash('sha256').update(buffer).digest('hex').slice(0, 16) }
93
+ } catch (error) {
94
+ problems.push(`${new URL(url).host}: ${String(error?.message ?? error).slice(0, 60)}`)
95
+ }
96
+ }
97
+ throw new Error(`no source served ${name} — ${problems.join(' | ')}`)
98
+ }
99
+
100
+ /**
101
+ * Fetch the GeoIP databases into the core's data directory.
102
+ *
103
+ * Called only once routing is healthy. Idempotent: an existing database is left alone
104
+ * unless `force` is set, so this costs nothing on every subsequent start.
105
+ *
106
+ * @param workDir - the core's data directory.
107
+ * @param options - `force` re-downloads, `fetch` and `timeoutMs` for tests.
108
+ * @returns what was fetched, what was skipped, and what failed.
109
+ */
110
+ export async function fetchGeoDatabases(workDir, options = {}) {
111
+ mkdirSync(workDir, { recursive: true })
112
+ const fetchImpl = options.fetch ?? fetch
113
+ const timeoutMs = options.timeoutMs ?? 60_000
114
+ const fetched = []
115
+ const skipped = []
116
+ const failed = []
117
+ for (const name of GEO_FILES) {
118
+ const present = existsSync(join(workDir, name)) && statSync(join(workDir, name)).size > 1024
119
+ if (present && options.force !== true) {
120
+ skipped.push(name)
121
+ continue
122
+ }
123
+ try {
124
+ fetched.push(await fetchOne(name, workDir, fetchImpl, timeoutMs))
125
+ } catch (error) {
126
+ failed.push({ name, reason: String(error?.message ?? error) })
127
+ }
128
+ }
129
+ return { fetched, skipped, failed, ok: failed.length === 0 }
130
+ }
package/lib/routes.js CHANGED
@@ -22,6 +22,7 @@ const MAX_BODY_BYTES = 16 * 1024
22
22
  * key written into the row config would be passed straight to the loader.
23
23
  */
24
24
  export const EDITABLE_FIELDS = [
25
+ 'subscriptionUrls',
25
26
  'subscriptionUrl',
26
27
  'node',
27
28
  'corePath',
@@ -32,6 +33,9 @@ export const EDITABLE_FIELDS = [
32
33
  'proxyDomains',
33
34
  'speedTestMinutes',
34
35
  'speedTestCount',
36
+ 'healthCheckMinutes',
37
+ 'autoFetchCore',
38
+ 'autoFetchGeo',
35
39
  ]
36
40
 
37
41
  /**
@@ -185,9 +189,22 @@ export function mountRoutes(webServer, runtime, log) {
185
189
  const body = await readJson(request, response)
186
190
  if (body === undefined) return
187
191
  const action = String(body.action ?? '')
192
+ if (action === 'bootstrap') {
193
+ // Download and verify a private core. Long-running, so the answer carries the
194
+ // final report rather than a progress stream; the panel polls status meanwhile.
195
+ const report = await runtime.bootstrapCore()
196
+ sendJson(response, 200, { ok: true, ...report, binary: runtime.binary })
197
+ return
198
+ }
188
199
  if (action === 'start') {
189
200
  const report = await runtime.start()
190
- sendJson(response, 200, { ok: true, endpoint: report.endpoint, node: report.group.now, geo: report.geo })
201
+ sendJson(response, 200, {
202
+ ok: true,
203
+ endpoint: report.endpoint,
204
+ node: report.group.now,
205
+ geo: report.geo,
206
+ providers: report.providers,
207
+ })
191
208
  return
192
209
  }
193
210
  if (action === 'stop') {
@@ -200,6 +217,32 @@ export function mountRoutes(webServer, runtime, log) {
200
217
  sendJson(response, 200, { ok: true, provider })
201
218
  return
202
219
  }
220
+ if (action === 'refreshOne') {
221
+ // Re-download a single subscription, so a broken provider can be retried without
222
+ // spending the others' interval.
223
+ const provider = String(body.provider ?? '').trim()
224
+ if (provider === '') {
225
+ sendJson(response, 400, { error: 'provider is required' })
226
+ return
227
+ }
228
+ const failed = []
229
+ try {
230
+ await runtime.core.api(`/providers/proxies/${encodeURIComponent(provider)}`, { method: 'PUT' })
231
+ } catch (error) {
232
+ failed.push({ provider, reason: String(error?.message ?? error) })
233
+ }
234
+ const status = await runtime.core.providerStatus()
235
+ const row = (status.providers ?? []).find((entry) => entry.provider === provider)
236
+ sendJson(response, 200, { ok: failed.length === 0, provider: row, failed })
237
+ return
238
+ }
239
+ if (action === 'probe') {
240
+ // Probe the list as typed, without saving it: the panel checks all lines at once
241
+ // and names the one that failed.
242
+ const answer = await runtime.probe(String(body.url ?? ''))
243
+ sendJson(response, answer.ok ? 200 : 400, answer)
244
+ return
245
+ }
203
246
  if (action === 'test') {
204
247
  // A `node` narrows the run to one node and `all` covers every node; without
205
248
  // either the cycle measures the configured sample. The panel offers all three.
@@ -227,7 +270,8 @@ export function mountRoutes(webServer, runtime, log) {
227
270
  })
228
271
 
229
272
  // Probe a subscription before it is saved, so a typo is caught in the form
230
- // rather than in the next activation.
273
+ // rather than in the next activation. The body may carry several lines; each is
274
+ // probed and reported separately.
231
275
  route('/clash-proxy/probe', async (request, response) => {
232
276
  if (methodOf(request) !== 'POST') {
233
277
  sendJson(response, 405, { error: 'POST only' })
@@ -235,7 +279,7 @@ export function mountRoutes(webServer, runtime, log) {
235
279
  }
236
280
  const body = await readJson(request, response)
237
281
  if (body === undefined) return
238
- const answer = await runtime.probe(String(body.url ?? ''))
282
+ const answer = await runtime.probe(String(body.url ?? body.urls ?? ''))
239
283
  sendJson(response, answer.ok ? 200 : 400, answer)
240
284
  })
241
285
 
@@ -9,6 +9,11 @@
9
9
  * `vless://`, `trojan://`, `anytls://`, `hysteria2://`) that a Clash document
10
10
  * cannot express and no plugin-side parser should try to re-implement.
11
11
  *
12
+ * Several subscriptions may be configured at once. Each one becomes its own
13
+ * `proxy-providers` entry and contributes its nodes to the single `PROXY` group, so
14
+ * the node table shows every provider's nodes side by side and one dead provider
15
+ * never stops the core from booting.
16
+ *
12
17
  * @module dsh-clash-proxy/subscription
13
18
  */
14
19
 
@@ -18,6 +23,15 @@ const CLASH_MARKERS = ['proxy-groups:', 'proxy-providers:', 'proxies:', 'rules:'
18
23
  /** Share-link schemes a mihomo provider accepts. */
19
24
  const SHARE_SCHEMES = ['ss://', 'ssr://', 'vmess://', 'vless://', 'trojan://', 'anytls://', 'hysteria://', 'hysteria2://', 'tuic://', 'wireguard://']
20
25
 
26
+ /**
27
+ * One subscription entry as the configuration holds it.
28
+ *
29
+ * @typedef {object} SubscriptionEntry
30
+ * @property {string} url - normalized subscription URL.
31
+ * @property {string} name - display name; empty means "subscription N".
32
+ * @property {number} index - stable position, used for the provider name.
33
+ */
34
+
21
35
  /**
22
36
  * Convert a Clash Verge import link into the raw subscription URL.
23
37
  *
@@ -49,6 +63,142 @@ export function normalizeSubscriptionUrl(input) {
49
63
  return parsed.toString()
50
64
  }
51
65
 
66
+ /**
67
+ * Split the multi-line subscription field into raw entries.
68
+ *
69
+ * Accepted forms, one per line:
70
+ *
71
+ * - `https://…/subscribe?token=…` — a bare URL
72
+ * - `clash://install-config?url=…` — an importer link
73
+ * - `主用 https://…` — a display name, whitespace, then the URL
74
+ * - `#` or `//` at the start of a line — a comment, skipped
75
+ *
76
+ * Blank lines and comments are dropped so a user may group entries visually. The
77
+ * name is optional everywhere; without one the entry is called "订阅 N" by the panel.
78
+ *
79
+ * @param text - the field value, possibly with several lines.
80
+ * @returns the raw entries, in the order they were written.
81
+ */
82
+ export function parseSubscriptionLines(text) {
83
+ const entries = []
84
+ for (const line of String(text ?? '').split(/\r?\n/)) {
85
+ const trimmed = line.trim()
86
+ if (trimmed === '' || trimmed.startsWith('#') || trimmed.startsWith('//')) continue
87
+ // A name is any leading token without a scheme separator; everything after the
88
+ // first whitespace is the URL. A name containing "://" would be a URL, so this
89
+ // only treats the prefix as a name when it clearly is not one.
90
+ const split = trimmed.match(/^(\S+)\s+(\S.*)$/)
91
+ if (split !== null && !split[1].includes('://') && split[2].includes('://')) {
92
+ entries.push({ name: split[1], raw: split[2].trim() })
93
+ continue
94
+ }
95
+ entries.push({ name: '', raw: trimmed })
96
+ }
97
+ return entries
98
+ }
99
+
100
+ /**
101
+ * Parse the configuration field into validated subscription entries.
102
+ *
103
+ * Duplicates are dropped by normalized URL: the same subscription listed twice would
104
+ * add every node twice under two provider prefixes, which looks like a bug to the
105
+ * user and doubles every latency measurement.
106
+ *
107
+ * @param text - the multi-line field value.
108
+ * @returns `{ entries, errors }`; a bad line is reported, never silently skipped.
109
+ */
110
+ export function parseSubscriptions(text) {
111
+ const entries = []
112
+ const errors = []
113
+ const seen = new Set()
114
+ for (const [at, line] of parseSubscriptionLines(text).entries()) {
115
+ let url
116
+ try {
117
+ url = normalizeSubscriptionUrl(line.raw)
118
+ } catch (error) {
119
+ errors.push({ line: at + 1, reason: String(error?.message ?? error), raw: line.raw.slice(0, 120) })
120
+ continue
121
+ }
122
+ if (seen.has(url)) {
123
+ errors.push({ line: at + 1, reason: 'duplicate subscription URL, ignored', raw: line.raw.slice(0, 120) })
124
+ continue
125
+ }
126
+ seen.add(url)
127
+ entries.push({
128
+ url,
129
+ name: String(line.name ?? '').trim().slice(0, 40),
130
+ index: entries.length,
131
+ // The provider name is derived here, not at the call site: `start()` and `status()`
132
+ // both read it, and a caller that forgot to derive it silently produced
133
+ // `provider: undefined` in the parsed list.
134
+ provider: `sub${entries.length}`,
135
+ })
136
+ }
137
+ return { entries, errors }
138
+ }
139
+
140
+ /**
141
+ * Migrate the single-URL field into the multi-line one.
142
+ *
143
+ * An existing profile carries `subscriptionUrl`; reading it as the first line keeps
144
+ * that profile working with no edit. The old field is never written back, so a
145
+ * user's next save naturally moves them onto the list form.
146
+ *
147
+ * @param config - the resolved configuration.
148
+ * @returns the effective multi-line text.
149
+ */
150
+ export function effectiveSubscriptionText(config) {
151
+ const list = String(config?.subscriptionUrls ?? '').trim()
152
+ if (list !== '') return list
153
+ const single = String(config?.subscriptionUrl ?? '').trim()
154
+ return single
155
+ }
156
+
157
+ /**
158
+ * The provider name one entry contributes.
159
+ *
160
+ * mihomo names a provider's proxy namespace after the provider, so this is also the
161
+ * namespace `/providers/proxies/<name>` addresses. The index keeps it stable across
162
+ * a reorder-free edit.
163
+ *
164
+ * @param entry - a parsed entry.
165
+ * @returns the provider name.
166
+ */
167
+ export function providerName(entry) {
168
+ const named = String(entry?.provider ?? '').trim()
169
+ if (named !== '') return named
170
+ return `sub${Number(entry?.index ?? 0)}`
171
+ }
172
+
173
+ /**
174
+ * The display name one entry carries.
175
+ *
176
+ * @param entry - a parsed entry.
177
+ * @returns the user's name, or a positional fallback.
178
+ */
179
+ export function displayName(entry) {
180
+ const named = String(entry?.name ?? '').trim()
181
+ return named !== '' ? named : `订阅 ${Number(entry?.index ?? 0) + 1}`
182
+ }
183
+
184
+ /**
185
+ * The node prefix one provider's nodes carry.
186
+ *
187
+ * Two subscriptions routinely list the same node names ("香港01", "日本02"). Without a
188
+ * per-provider prefix the group holds duplicate names, and selecting "香港01" cannot
189
+ * say which provider it meant — measured: `PROXY.all` came back with each name twice.
190
+ * `override.additional-prefix` makes them unique; the prefix is only applied when more
191
+ * than one subscription is configured, so a single subscription keeps its clean names.
192
+ *
193
+ * @param entry - a parsed entry.
194
+ * @param total - how many subscriptions are configured.
195
+ * @returns the prefix, or an empty string for a single subscription.
196
+ */
197
+ export function nodePrefix(entry, total) {
198
+ if (Number(total) <= 1) return ''
199
+ return `${displayName(entry)} · `
200
+ }
201
+
52
202
  /**
53
203
  * Classify a subscription response body.
54
204
  *
@@ -136,3 +286,49 @@ export async function probeSubscription(url, options = {}) {
136
286
  hints: response.headers.get('subscription-userinfo') ?? response.headers.get('profile-update-interval') ?? '',
137
287
  }
138
288
  }
289
+
290
+ /**
291
+ * Probe several subscriptions at once and label each answer.
292
+ *
293
+ * Probes run concurrently: a slow provider must not delay the report on a fast one,
294
+ * and the panel shows one row per subscription either way. A failure carries the
295
+ * entry it belongs to, so the panel can point at the exact line.
296
+ *
297
+ * @param entries - parsed entries.
298
+ * @param options - per-probe timeout and an optional fetch implementation.
299
+ * @returns one labelled result per entry, in the configured order.
300
+ */
301
+ export async function probeSubscriptions(entries, options = {}) {
302
+ const list = Array.isArray(entries) ? entries : []
303
+ const results = await Promise.all(
304
+ list.map(async (entry) => {
305
+ try {
306
+ const answer = await probeSubscription(entry.url, options)
307
+ return { ...answer, name: displayName(entry), provider: providerName(entry), url: entry.url }
308
+ } catch (error) {
309
+ return {
310
+ ok: false,
311
+ status: 0,
312
+ bytes: 0,
313
+ format: 'unreachable',
314
+ nodeCount: 0,
315
+ error: String(error?.message ?? error),
316
+ name: displayName(entry),
317
+ provider: providerName(entry),
318
+ url: entry.url,
319
+ }
320
+ }
321
+ }),
322
+ )
323
+ const reachable = results.filter((result) => result.ok)
324
+ return {
325
+ results,
326
+ ok: results.length > 0 && reachable.length === results.length,
327
+ total: results.length,
328
+ reachable: reachable.length,
329
+ nodeCount: results.reduce((sum, result) => sum + (Number(result.nodeCount) || 0), 0),
330
+ bytes: results.reduce((sum, result) => sum + (Number(result.bytes) || 0), 0),
331
+ /** Present when some, but not all, subscriptions answered. */
332
+ partial: results.length > 0 && reachable.length > 0 && reachable.length < results.length,
333
+ }
334
+ }