dsh-crate 0.5.2 → 0.5.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.
Files changed (46) hide show
  1. package/assets/logo.svg +11 -33
  2. package/client/client.js +2271 -561
  3. package/lib/body-progress.js +4 -3
  4. package/lib/changelog.js +15 -2
  5. package/lib/discovery-cache.js +210 -0
  6. package/lib/discovery-compatibility.js +135 -90
  7. package/lib/drain.js +28 -9
  8. package/lib/dsh-cli.js +36 -6
  9. package/lib/github-install-target.js +53 -0
  10. package/lib/hot.js +400 -33
  11. package/lib/index.js +23 -9
  12. package/lib/install.js +37 -0
  13. package/lib/patch.js +123 -73
  14. package/lib/pending-rows.js +3 -4
  15. package/lib/pnpm-compat.js +234 -2
  16. package/lib/proc-text.js +16 -1
  17. package/lib/profile.js +17 -1
  18. package/lib/recovery.js +2 -1
  19. package/lib/registry.js +24 -16
  20. package/lib/release-candidates.js +4 -0
  21. package/lib/release-updates.js +9 -2
  22. package/lib/routes.js +459 -134
  23. package/lib/themes.js +42 -9
  24. package/lib/types/body-progress.d.ts +2 -1
  25. package/lib/types/changelog.d.ts +10 -1
  26. package/lib/types/discovery-cache.d.ts +38 -0
  27. package/lib/types/discovery-compatibility.d.ts +24 -14
  28. package/lib/types/dsh-cli.d.ts +19 -2
  29. package/lib/types/github-install-target.d.ts +11 -0
  30. package/lib/types/hot.d.ts +91 -7
  31. package/lib/types/index.d.ts +17 -0
  32. package/lib/types/install.d.ts +19 -0
  33. package/lib/types/patch.d.ts +6 -2
  34. package/lib/types/profile.d.ts +4 -1
  35. package/lib/types/registry.d.ts +9 -8
  36. package/lib/types/release-candidates.d.ts +2 -0
  37. package/lib/types/routes.d.ts +2 -2
  38. package/lib/types/themes.d.ts +7 -1
  39. package/lib/types/update-notification-settings.d.ts +5 -0
  40. package/lib/types/update-notifications.d.ts +51 -0
  41. package/lib/types/updates.d.ts +5 -1
  42. package/lib/update-notification-settings.js +6 -0
  43. package/lib/update-notifications.js +166 -0
  44. package/lib/updates.js +41 -11
  45. package/lib/verify.js +24 -2
  46. package/package.json +1 -1
@@ -70,8 +70,9 @@ export const MAX_BODY_BYTES = 256 * 1024 * 1024;
70
70
  * @param res - the response whose body to read.
71
71
  * @param stallMs - silence that ends the read, in milliseconds.
72
72
  * @param what - the download, for the rejection message ("the catalog").
73
+ * @param maxBytes - maximum decoded response size.
73
74
  */
74
- export function readBodyWhileProgressing(res, stallMs, what = 'the catalog') {
75
+ export function readBodyWhileProgressing(res, stallMs, what = 'the catalog', maxBytes = MAX_BODY_BYTES) {
75
76
  // The stand-in closes at once, so an absent body reads as "no body"
76
77
  // below instead of parking this reader on a stream that never ends.
77
78
  const reader = (res.body ?? new ReadableStream({ start(controller) { controller.close(); } })).getReader();
@@ -118,8 +119,8 @@ export function readBodyWhileProgressing(res, stallMs, what = 'the catalog') {
118
119
  }
119
120
  chunks.push(r.value);
120
121
  received += r.value.byteLength;
121
- if (received > MAX_BODY_BYTES) {
122
- finish(new Error(`${what} response grew past ${String(MAX_BODY_BYTES / 1024 / 1024)} MB without ending (received ${String(received)} bytes)`));
122
+ if (received > maxBytes) {
123
+ finish(new Error(`${what} response grew past ${String(maxBytes / 1024 / 1024)} MB without ending (received ${String(received)} bytes)`));
123
124
  return;
124
125
  }
125
126
  arm();
package/lib/changelog.js CHANGED
@@ -344,7 +344,9 @@ function catalogEntryForGitSource(plugins, spec) {
344
344
  * same contract the issue promised — a dialog that cannot load its data shows
345
345
  * a neutral statement, not an error.
346
346
  */
347
- export async function updateNotesFor(profile, explicitDir, name) {
347
+ export async function updateNotesFor(profile, explicitDir, name,
348
+ /** The version the Update button installs, when it is not simply "latest". */
349
+ target) {
348
350
  const activeProfileDir = profileDir(profile, explicitDir);
349
351
  const spec = readInstalled(profile, activeProfileDir)[name];
350
352
  if (spec === undefined || spec.startsWith('link:') || spec.startsWith('file:')) {
@@ -438,7 +440,18 @@ export async function updateNotesFor(profile, explicitDir, name) {
438
440
  && (compareVersions(released, installed) ?? 0) <= 0;
439
441
  const hasCommits = (entry.commits?.length ?? 0) > 0;
440
442
  if (!(behind && (hasCommits || (specKey === null && npmName !== null)))) {
441
- return { kind: 'release', release: entry.release };
443
+ const beyond = target !== undefined && released !== null
444
+ && (compareVersions(released, target) ?? 0) > 0;
445
+ // Attach the commit slice so the dialog can list what changed between
446
+ // the installed commit and the update target, not just the release (#1193).
447
+ // Only when the installed commit is found in the list: otherwise the
448
+ // slice is just "recent commits" unrelated to this update, and next to
449
+ // release notes it would be noise (npm installs never match a sha).
450
+ const sliced = hasCommits ? sliceCommitsAt(entry.commits, current) : undefined;
451
+ const withCommits = sliced !== undefined && sliced.found && sliced.items.length > 0 ? { commits: sliced } : {};
452
+ return beyond
453
+ ? { kind: 'release', release: entry.release, beyondTarget: target, ...withCommits }
454
+ : { kind: 'release', release: entry.release, ...withCommits };
442
455
  }
443
456
  }
444
457
  if (entry?.commits !== undefined && entry.commits.length > 0) {
@@ -0,0 +1,210 @@
1
+ import fs from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ const V1_SCHEMA = 'dsh-crate/discovery-compatibility-cache/v1';
4
+ const JOURNAL_HEADER = JSON.stringify({ schema: 'dsh-crate/discovery-compatibility-cache/v2' });
5
+ // A full scan of the catalog must stay cached (#1170).
6
+ const MAX_ENTRIES = 20_000;
7
+ const COMPACT_AFTER = 2 * MAX_ENTRIES;
8
+ const BATCH_DELAY_MS = 100;
9
+ const MIN_RETRY_MS = 1_000;
10
+ const MAX_RETRY_MS = 30_000;
11
+ function parseJson(text) {
12
+ try {
13
+ return JSON.parse(text);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ async function readIfPresent(path) {
20
+ try {
21
+ return await fs.readFile(path, 'utf8');
22
+ }
23
+ catch (error) {
24
+ if (error.code === 'ENOENT')
25
+ return null;
26
+ throw error;
27
+ }
28
+ }
29
+ function encodeRows(entries) {
30
+ return [...entries].map(([key, entry]) => JSON.stringify([key, entry]) + '\n').join('');
31
+ }
32
+ /**
33
+ * A single writer and shared view per cache path. The old JSON remains readable
34
+ * until a complete journal has been published. Later writes append only the
35
+ * changed rows, with occasional atomic snapshots to bound the log.
36
+ */
37
+ class DiscoveryCache {
38
+ file;
39
+ decode;
40
+ journal;
41
+ entries = new Map();
42
+ pending = new Map();
43
+ loaded;
44
+ timer;
45
+ writing;
46
+ journalRows = 0;
47
+ canAppend = false;
48
+ retryMs = 0;
49
+ owners = 0;
50
+ constructor(file, decode) {
51
+ this.file = file;
52
+ this.decode = decode;
53
+ this.journal = file + '.journal';
54
+ }
55
+ acquire() {
56
+ this.owners += 1;
57
+ this.schedule();
58
+ }
59
+ async release() {
60
+ this.owners -= 1;
61
+ if (this.owners !== 0)
62
+ return;
63
+ if (this.timer !== undefined)
64
+ clearTimeout(this.timer);
65
+ this.timer = undefined;
66
+ // Give a normal unload one immediate drain. A mounted replacement keeps
67
+ // sharing the same writer even if it arrives before that drain completes.
68
+ while (this.pending.size > 0 && await this.flushOnce()) {
69
+ if (this.owners !== 0)
70
+ break;
71
+ }
72
+ this.schedule();
73
+ }
74
+ async restore() {
75
+ const journal = await readIfPresent(this.journal);
76
+ const saved = new Map();
77
+ const add = (key, raw) => {
78
+ const entry = this.decode(raw);
79
+ if (entry === null || (saved.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt)
80
+ return;
81
+ saved.set(key, entry);
82
+ };
83
+ if (journal === null) {
84
+ const legacy = await readIfPresent(this.file);
85
+ const data = legacy === null ? null : parseJson(legacy);
86
+ if (data?.schema === V1_SCHEMA && data.entries !== null && typeof data.entries === 'object' && !Array.isArray(data.entries)) {
87
+ for (const [key, value] of Object.entries(data.entries))
88
+ add(key, value);
89
+ }
90
+ }
91
+ else {
92
+ const [header, ...rows] = journal.split('\n');
93
+ if (header === JOURNAL_HEADER) {
94
+ this.canAppend = true;
95
+ this.journalRows = rows.length - 1;
96
+ for (const row of rows) {
97
+ if (row === '')
98
+ continue;
99
+ const value = parseJson(row);
100
+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string')
101
+ add(value[0], value[1]);
102
+ }
103
+ }
104
+ }
105
+ // A prior read error may have left locally refreshed entries in memory.
106
+ // Replay must not replace them with old copies, including timestamp ties.
107
+ for (const [key, entry] of saved) {
108
+ if ((this.entries.get(key)?.checkedAt ?? -Infinity) < entry.checkedAt)
109
+ this.entries.set(key, entry);
110
+ }
111
+ this.trim();
112
+ }
113
+ ready() {
114
+ return this.loaded ??= this.restore();
115
+ }
116
+ async get(key) {
117
+ await this.ready().catch(() => { });
118
+ return this.entries.get(key);
119
+ }
120
+ set(key, entry) {
121
+ if ((this.entries.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt)
122
+ return;
123
+ this.entries.set(key, entry);
124
+ this.pending.set(key, entry);
125
+ this.schedule();
126
+ }
127
+ trim() {
128
+ if (this.entries.size <= MAX_ENTRIES)
129
+ return;
130
+ const newest = [...this.entries].sort(([, a], [, b]) => b.checkedAt - a.checkedAt);
131
+ for (const [key] of newest.slice(MAX_ENTRIES)) {
132
+ this.entries.delete(key);
133
+ this.pending.delete(key);
134
+ }
135
+ }
136
+ schedule() {
137
+ if (this.timer !== undefined || this.writing !== undefined)
138
+ return;
139
+ if (this.pending.size === 0) {
140
+ if (this.owners === 0 && caches.get(this.file) === this)
141
+ caches.delete(this.file);
142
+ return;
143
+ }
144
+ this.timer = setTimeout(() => {
145
+ this.timer = undefined;
146
+ void this.flushOnce().then(() => { this.schedule(); });
147
+ }, this.retryMs || BATCH_DELAY_MS);
148
+ this.timer.unref();
149
+ }
150
+ flushOnce() {
151
+ this.writing ??= this.write().then(() => {
152
+ this.retryMs = 0;
153
+ return true;
154
+ }, () => {
155
+ this.retryMs = Math.min(MAX_RETRY_MS, this.retryMs === 0 ? MIN_RETRY_MS : this.retryMs * 2);
156
+ return false;
157
+ }).finally(() => { this.writing = undefined; });
158
+ return this.writing;
159
+ }
160
+ async write() {
161
+ try {
162
+ await this.ready();
163
+ }
164
+ catch (error) {
165
+ this.loaded = undefined;
166
+ throw error;
167
+ }
168
+ this.trim();
169
+ const batch = new Map(this.pending);
170
+ if (batch.size === 0)
171
+ return;
172
+ if (!this.canAppend || this.journalRows + batch.size > COMPACT_AFTER) {
173
+ const snapshot = JOURNAL_HEADER + '\n' + encodeRows(this.entries);
174
+ const rows = this.entries.size;
175
+ const temporary = this.journal + '.tmp';
176
+ await fs.mkdir(dirname(this.journal), { recursive: true, mode: 0o700 });
177
+ try {
178
+ await fs.writeFile(temporary, snapshot, { mode: 0o600 });
179
+ await fs.rename(temporary, this.journal);
180
+ }
181
+ catch (error) {
182
+ await fs.rm(temporary, { force: true }).catch(() => { });
183
+ throw error;
184
+ }
185
+ this.canAppend = true;
186
+ this.journalRows = rows;
187
+ }
188
+ else {
189
+ // Start at a fresh line even if an interrupted append left a partial
190
+ // record behind. Recovery ignores malformed rows and keeps valid ones.
191
+ await fs.appendFile(this.journal, '\n' + encodeRows(batch), { mode: 0o600 });
192
+ this.journalRows += batch.size + 1;
193
+ }
194
+ for (const [key, entry] of batch) {
195
+ if (this.pending.get(key) === entry)
196
+ this.pending.delete(key);
197
+ }
198
+ }
199
+ }
200
+ const caches = new Map();
201
+ export function openDiscoveryCache(file, decode) {
202
+ const path = resolve(file);
203
+ let cache = caches.get(path);
204
+ if (cache === undefined) {
205
+ cache = new DiscoveryCache(path, decode);
206
+ caches.set(path, cache);
207
+ }
208
+ cache.acquire();
209
+ return cache;
210
+ }
@@ -8,22 +8,31 @@
8
8
  * profile state; conclusions are never cached because they depend on the DSH
9
9
  * version of the process serving the page.
10
10
  */
11
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
12
- import { dirname } from 'node:path';
11
+ import { createHash } from 'node:crypto';
13
12
  import { compareSemver, isSemver, satisfiesRange } from './check.js';
14
13
  import { classifyPeer, crossesImplicitCeiling } from './compatibility.js';
14
+ import { openDiscoveryCache } from './discovery-cache.js';
15
15
  import { marketFetch } from './net.js';
16
16
  import { isStableReleaseVersion } from './release-candidates.js';
17
17
  import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
18
18
  import { parseSourceUrl } from './sources.js';
19
- const CACHE_SCHEMA = 'dsh-crate/discovery-compatibility-cache/v1';
20
19
  const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
21
20
  const FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
22
21
  const OUTAGE_COOLDOWN_MS = 30 * 1000;
23
22
  const FETCH_TIMEOUT_MS = 8_000;
24
23
  const DEFAULT_CONCURRENCY = 8;
25
- const MAX_CACHE_ENTRIES = 5_000;
26
24
  const MAX_RANGE_LENGTH = 256;
25
+ /** Only the selected artifact and its declarations determine a discovery verdict. */
26
+ export function githubCompatibilityRevision(source) {
27
+ const facts = catalogReleaseManifest(source);
28
+ return createHash('sha256').update(JSON.stringify([
29
+ source.url,
30
+ source.tarball ?? null,
31
+ range(source.version),
32
+ facts === null ? null : [facts.version, facts.enginesDsh,
33
+ Object.entries(facts.peerDependencies).sort(), Object.entries(facts.dependencies ?? {}).sort()],
34
+ ])).digest('hex');
35
+ }
27
36
  /** Reuse catalog facts only for this repository's exact pinned install asset. */
28
37
  export function catalogReleaseManifest(source) {
29
38
  const facts = record(source.releaseManifest);
@@ -32,7 +41,20 @@ export function catalogReleaseManifest(source) {
32
41
  if (facts === null || !repository || !release || release[1].toLowerCase() !== repository.toLowerCase()
33
42
  || facts.tarball !== source.tarball || !validFacts(facts))
34
43
  return null;
35
- return { version: facts.version, enginesDsh: facts.enginesDsh, peerDependencies: facts.peerDependencies };
44
+ return {
45
+ version: facts.version,
46
+ enginesDsh: facts.enginesDsh,
47
+ peerDependencies: facts.peerDependencies,
48
+ dependencies: facts.dependencies ?? {},
49
+ };
50
+ }
51
+ function npmDiscoveryKey(name, registry, version) {
52
+ return version === undefined ? name : `npm:${registry}\u0000${name}\u0000${version}`;
53
+ }
54
+ function githubDiscoveryKey(source) {
55
+ const key = `github:${source.url}\u0000${source.tarball ?? ''}`;
56
+ const version = range(source.version);
57
+ return version === null ? key : `${key}\u0000${version}`;
36
58
  }
37
59
  /** Read the linked package at its selected release, never the repository root by accident. */
38
60
  async function githubManifest(source, fetcher) {
@@ -130,20 +152,43 @@ export function manifestFacts(value) {
130
152
  if (declared !== null)
131
153
  peerDependencies[name] = declared;
132
154
  }
155
+ const dependencies = record(manifest.dependencies);
156
+ const hostDependencies = {};
157
+ for (const [name, raw] of Object.entries(dependencies ?? {})) {
158
+ if (!name.startsWith('@deepseek-ai/'))
159
+ continue;
160
+ const declared = range(raw);
161
+ if (declared !== null)
162
+ hostDependencies[name] = declared;
163
+ }
133
164
  return {
134
165
  version: range(manifest.version),
135
166
  enginesDsh: range(engines?.dsh) ?? range(dshEngines?.dsh),
136
167
  peerDependencies,
168
+ dependencies: hostDependencies,
137
169
  };
138
170
  }
139
171
  function validFacts(value) {
140
172
  const facts = record(value);
141
173
  const peers = record(facts?.peerDependencies);
174
+ // A missing `dependencies` is a pre-upgrade cache entry or catalog manifest,
175
+ // not a malformed one: the durable cache must survive the upgrade rather than
176
+ // be discarded and refetched a thousand packages at once.
177
+ const dependencies = record(facts?.dependencies);
142
178
  return facts !== null
143
179
  && (facts.version === null || range(facts.version) === facts.version)
144
180
  && (facts.enginesDsh === null || range(facts.enginesDsh) === facts.enginesDsh)
145
181
  && peers !== null
146
- && Object.entries(peers).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item);
182
+ && Object.entries(peers).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item)
183
+ && (dependencies === null || Object.entries(dependencies).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item));
184
+ }
185
+ function decodeCacheEntry(value) {
186
+ const entry = record(value);
187
+ if (entry === null || typeof entry.checkedAt !== 'number' || !Number.isFinite(entry.checkedAt) || !validFacts(entry.facts))
188
+ return null;
189
+ // Normalize the pre-upgrade shape so every consumer sees an object.
190
+ const facts = entry.facts.dependencies === undefined ? { ...entry.facts, dependencies: {} } : entry.facts;
191
+ return { checkedAt: entry.checkedAt, facts };
147
192
  }
148
193
  function displayRequirement(declarations) {
149
194
  const unique = [...new Set(declarations.map(item => item.range))];
@@ -168,7 +213,12 @@ function rangeResult(hostVersion, declared) {
168
213
  */
169
214
  function declarationResult(declaration, hostVersion) {
170
215
  const satisfied = rangeResult(hostVersion, declaration.range);
171
- if (declaration.kind === 'engine' || satisfied !== false)
216
+ // Only a PEER may be stretched: it is a statement of intent about the host
217
+ // line, and the ecosystem is full of sloppy caret ceilings. An engine is a
218
+ // plain bound, and a DEPENDENCY is an install instruction — pnpm resolves
219
+ // the declared range and hoists the result, so a range that excludes the
220
+ // running version means a second copy shadows the host's.
221
+ if (declaration.kind !== 'peer' || satisfied !== false)
172
222
  return satisfied;
173
223
  if (crossesImplicitCeiling(hostVersion, declaration.range))
174
224
  return false;
@@ -203,6 +253,22 @@ export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
203
253
  continue;
204
254
  declarations.push({ kind: 'peer', package: name, range: declared });
205
255
  }
256
+ for (const [name, declared] of Object.entries(facts.dependencies ?? {})) {
257
+ // The peer filter above restricts itself to DSH's lockstep line because a
258
+ // peer range on cordis or schemastery says nothing about the DSH version.
259
+ // A dependency is different: it names a package the host itself provides,
260
+ // and pnpm will install the declared copy and hoist it over the host's.
261
+ // That is the dsh-qqbot failure — @deepseek-ai/dsh-settings and
262
+ // dsh-credentials as ordinary dependencies at `^0.1.0-rc.5` over a
263
+ // 0.2.2-rc.1 runtime — which the peer-only check could not see.
264
+ // Still only the lockstep line: the range is judged against the DSH
265
+ // version, and cordis (4.x) / schemastery (3.x) are not on it — a plugin
266
+ // that depends on `@deepseek-ai/cordis@^4` would otherwise read as
267
+ // incompatible with every host.
268
+ if (!hostPackages.has(name) || !/^@deepseek-ai\/dsh(?:-|$)/.test(name))
269
+ continue;
270
+ declarations.push({ kind: 'dependency', package: name, range: declared });
271
+ }
206
272
  const requirement = displayRequirement(declarations);
207
273
  if (declarations.length === 0) {
208
274
  return { status: 'unknown', basis: 'undeclared', requirement: null, declarations: [] };
@@ -219,110 +285,89 @@ export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
219
285
  return { status, basis: 'manifest', requirement, declarations };
220
286
  }
221
287
  /**
222
- * Durable, bounded lookup of npm `latest` and catalog GitHub manifests.
288
+ * Durable, bounded lookup of npm releases and catalog GitHub manifests.
223
289
  *
224
290
  * Failed requests are intentionally memory-only and short-lived: a mirror
225
291
  * outage must not become a day-long false "undeclared" result on disk.
226
292
  */
227
293
  export class DiscoveryManifestIndex {
228
- cacheFile;
229
- entries = new Map();
294
+ cache;
230
295
  failures = new Map();
231
296
  inflight = new Map();
232
297
  fetcher;
233
298
  now;
234
299
  ttlMs;
235
300
  concurrency;
236
- loaded = false;
237
301
  consecutiveFailures = 0;
238
302
  unavailableUntil = 0;
239
- dirty = false;
303
+ disposed = false;
240
304
  activeFetches = 0;
241
305
  fetchWaiters = [];
242
306
  constructor(cacheFile, options = {}) {
243
- this.cacheFile = cacheFile;
307
+ this.cache = openDiscoveryCache(cacheFile, decodeCacheEntry);
244
308
  this.fetcher = options.fetcher ?? marketFetch;
245
309
  this.now = options.now ?? Date.now;
246
310
  this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
247
311
  this.concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY));
248
312
  }
249
- load() {
250
- if (this.loaded)
313
+ /** Unmount this index, retaining any writes already queued for this profile. */
314
+ async dispose() {
315
+ if (this.disposed)
251
316
  return;
252
- this.loaded = true;
253
- try {
254
- const parsed = JSON.parse(readFileSync(this.cacheFile, 'utf8'));
255
- if (parsed.schema !== CACHE_SCHEMA || record(parsed.entries) === null)
256
- return;
257
- for (const [name, raw] of Object.entries(parsed.entries)) {
258
- const entry = record(raw);
259
- if (entry === null || typeof entry.checkedAt !== 'number' || !validFacts(entry.facts))
260
- continue;
261
- this.entries.set(name, { checkedAt: entry.checkedAt, facts: entry.facts });
262
- }
263
- }
264
- catch { /* first run or a truncated cache — fetch fresh */ }
265
- }
266
- persist() {
267
- try {
268
- mkdirSync(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
269
- const newest = [...this.entries.entries()]
270
- .sort(([, a], [, b]) => b.checkedAt - a.checkedAt)
271
- .slice(0, MAX_CACHE_ENTRIES);
272
- this.entries.clear();
273
- for (const [name, entry] of newest)
274
- this.entries.set(name, entry);
275
- const data = { schema: CACHE_SCHEMA, entries: Object.fromEntries(newest) };
276
- writeFileSync(this.cacheFile, JSON.stringify(data), { mode: 0o600 });
277
- }
278
- catch { /* cache failure degrades to in-memory lookups */ }
317
+ this.disposed = true;
318
+ await this.cache.release();
279
319
  }
280
320
  /** One semaphore for the whole index, including overlapping HTTP batches. */
281
321
  async withFetchPermit(operation) {
282
322
  if (this.activeFetches >= this.concurrency) {
283
323
  await new Promise(resolve => this.fetchWaiters.push(resolve));
284
324
  }
285
- this.activeFetches += 1;
325
+ else
326
+ this.activeFetches += 1;
286
327
  try {
287
328
  return await operation();
288
329
  }
289
330
  finally {
290
- this.activeFetches -= 1;
291
- this.fetchWaiters.shift()?.();
331
+ const next = this.fetchWaiters.shift();
332
+ if (next === undefined)
333
+ this.activeFetches -= 1;
334
+ else
335
+ next();
292
336
  }
293
337
  }
294
- async fetchOne(name, registry, record = true, readManifest) {
295
- this.load();
338
+ retryDelay(key, now = this.now()) {
339
+ return Math.max(0, Math.max(this.failures.get(key) ?? 0, this.unavailableUntil) - now);
340
+ }
341
+ npmRetryAfterMs(name, registry, version) {
342
+ return this.retryDelay(npmDiscoveryKey(name, registry, version));
343
+ }
344
+ githubRetryAfterMs(source) {
345
+ return this.retryDelay(githubDiscoveryKey(source));
346
+ }
347
+ async fetchOne(cacheKey, record, readManifest, expectedVersion) {
348
+ const cached = await this.cache.get(cacheKey);
296
349
  const now = this.now();
297
- const cached = this.entries.get(name);
298
- if (cached !== undefined && now - cached.checkedAt < this.ttlMs)
350
+ if (cached !== undefined && now - cached.checkedAt < this.ttlMs
351
+ && (expectedVersion === undefined || cached.facts.version === expectedVersion))
299
352
  return cached.facts;
300
- if ((this.failures.get(name) ?? 0) > now || this.unavailableUntil > now)
353
+ if (this.retryDelay(cacheKey, now) > 0)
301
354
  return null;
302
355
  // Advisory and recording lookups keep separate in-flight slots: an
303
356
  // advisory call must not be answered by — or hand its answer to — a
304
357
  // recording one, or `record` would stop meaning anything when the two
305
358
  // overlap on the same package.
306
- const key = record ? name : `${name}\u0000advisory`;
359
+ const key = record ? cacheKey : `${cacheKey}\u0000advisory`;
307
360
  const pending = this.inflight.get(key);
308
361
  if (pending !== undefined)
309
362
  return await pending;
310
363
  const request = (async () => {
311
364
  try {
312
- const value = await this.withFetchPermit(readManifest ?? (async () => {
313
- const response = await this.fetcher(`${registry}/${encodeURIComponent(name)}/latest`, {
314
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
315
- headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
316
- });
317
- if (!response.ok)
318
- throw new Error(`HTTP ${String(response.status)}`);
319
- return await response.json();
320
- }));
321
- const facts = manifestFacts(value);
322
- if (record) {
323
- this.entries.set(name, { checkedAt: this.now(), facts });
324
- this.dirty = true;
325
- this.failures.delete(name);
365
+ const facts = await this.withFetchPermit(readManifest);
366
+ if (expectedVersion !== undefined && facts.version !== expectedVersion)
367
+ throw new Error('npm returned a different release');
368
+ if (record && !this.disposed) {
369
+ this.cache.set(cacheKey, { checkedAt: this.now(), facts });
370
+ this.failures.delete(cacheKey);
326
371
  this.consecutiveFailures = 0;
327
372
  }
328
373
  return facts;
@@ -330,7 +375,7 @@ export class DiscoveryManifestIndex {
330
375
  catch {
331
376
  if (record) {
332
377
  const failedAt = this.now();
333
- this.failures.set(name, failedAt + FAILURE_COOLDOWN_MS);
378
+ this.failures.set(cacheKey, failedAt + FAILURE_COOLDOWN_MS);
334
379
  this.consecutiveFailures += 1;
335
380
  if (this.consecutiveFailures >= this.concurrency) {
336
381
  this.unavailableUntil = failedAt + OUTAGE_COOLDOWN_MS;
@@ -345,6 +390,15 @@ export class DiscoveryManifestIndex {
345
390
  this.inflight.set(key, request);
346
391
  return await request;
347
392
  }
393
+ async readNpmManifest(name, version, registry) {
394
+ const response = await this.fetcher(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
395
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
396
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
397
+ });
398
+ if (!response.ok)
399
+ throw new Error(`HTTP ${String(response.status)}`);
400
+ return await response.json();
401
+ }
348
402
  /**
349
403
  * Facts for ONE named release, rather than for `latest`.
350
404
  *
@@ -356,24 +410,16 @@ export class DiscoveryManifestIndex {
356
410
  * release declares a range this host misses), and it would equally pass a
357
411
  * pinned release that is itself incompatible.
358
412
  *
359
- * Deliberately outside the cache. The index is keyed by package name, and a
360
- * version-keyed one would grow with every release anyone ever pinned to
361
- * answer a question asked once per install. Nothing is recorded either: a
362
- * pre-flight verdict must not decide what the diagnostics panel sees next
363
- * (#619).
413
+ * Deliberately outside the cache. An install can target any old release,
414
+ * whereas a discovery query is for the version shown in the catalog. A
415
+ * pre-flight verdict must not decide what the diagnostics panel sees next (#619).
364
416
  *
365
417
  * A release whose manifest cannot be read is `null`, like every other
366
418
  * unreadable manifest: absence of a claim is not a verdict.
367
419
  */
368
420
  async lookupVersion(name, version, registry) {
369
421
  try {
370
- const response = await this.withFetchPermit(async () => await this.fetcher(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
371
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
372
- headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
373
- }));
374
- if (!response.ok)
375
- return null;
376
- return manifestFacts(await response.json());
422
+ return manifestFacts(await this.withFetchPermit(() => this.readNpmManifest(name, version, registry)));
377
423
  }
378
424
  catch {
379
425
  return null;
@@ -389,21 +435,25 @@ export class DiscoveryManifestIndex {
389
435
  * diagnostics panel sees next (#619).
390
436
  */
391
437
  async lookup(names, registry, options = {}) {
392
- const record = options.record !== false;
438
+ const shouldRecord = options.record !== false;
393
439
  const unique = [...new Set(names)];
394
440
  const result = {};
395
441
  let next = 0;
396
442
  const worker = async () => {
397
443
  while (next < unique.length) {
398
444
  const name = unique[next++];
399
- result[name] = await this.fetchOne(name, registry, record);
445
+ const version = options.versions?.get(name);
446
+ result[name] = await this.fetchOne(npmDiscoveryKey(name, registry, version), shouldRecord, async () => {
447
+ const manifest = await this.readNpmManifest(name, version ?? 'latest', registry);
448
+ const returnedName = record(manifest)?.name;
449
+ if (version !== undefined && returnedName !== undefined && returnedName !== name) {
450
+ throw new Error('npm returned a different package');
451
+ }
452
+ return manifestFacts(manifest);
453
+ }, version);
400
454
  }
401
455
  };
402
456
  await Promise.all(Array.from({ length: Math.min(this.concurrency, unique.length) }, worker));
403
- if (this.dirty) {
404
- this.dirty = false;
405
- this.persist();
406
- }
407
457
  return result;
408
458
  }
409
459
  /** Catalog-approved GitHub sources, cached by both package path and selected archive. */
@@ -414,15 +464,10 @@ export class DiscoveryManifestIndex {
414
464
  const worker = async () => {
415
465
  while (next < unique.length) {
416
466
  const source = unique[next++];
417
- const key = `github:${source.url}\u0000${source.tarball ?? ''}`;
418
- result[source.url] = await this.fetchOne(key, '', true, () => githubManifest(source, this.fetcher));
467
+ result[source.url] = await this.fetchOne(githubDiscoveryKey(source), true, async () => manifestFacts(await githubManifest(source, this.fetcher)));
419
468
  }
420
469
  };
421
470
  await Promise.all(Array.from({ length: Math.min(this.concurrency, unique.length) }, worker));
422
- if (this.dirty) {
423
- this.persist();
424
- this.dirty = false;
425
- }
426
471
  return result;
427
472
  }
428
473
  }