dsh-crate 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +243 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +447 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +871 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1978 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +353 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +405 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +904 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Reading a response body under a stall watchdog instead of a total budget.
3
+ *
4
+ * Lives on its own because two downloads need exactly this rule and they are
5
+ * not the same file: the catalog served from its origin (#750/#766) and the
6
+ * catalog carried by a published package (#1049). The npm source had kept a
7
+ * fixed 20s ceiling, which is fine for a metadata answer and wrong for a
8
+ * multi-megabyte tarball: at 3.2 MB it needs 158 KB/s sustained, and a China
9
+ * mirror jittering to 17–40 KB/s cannot make that, so both attempts died at
10
+ * the ceiling while the link was still delivering bytes.
11
+ */
12
+ /**
13
+ * How long to wait for the response to START answering.
14
+ *
15
+ * Headers arrive in one burst or not at all, so a fixed budget still fits
16
+ * them. It fits nothing else: the body of a catalog download keeps trickling
17
+ * long after any honest total budget, and a total timer cuts off a download
18
+ * that was still moving — measured: killed at 15s on both attempts, 89.9s
19
+ * end-to-end when allowed to run.
20
+ */
21
+ export const HEADERS_TIMEOUT_MS = 15_000;
22
+ /**
23
+ * How long the body may stay SILENT before we give up on it.
24
+ *
25
+ * Deliberately not a total budget. As long as bytes keep arriving, however
26
+ * slowly, the read continues; the watchdog only fires on a download that has
27
+ * actually stopped, which is the one failure a slow link cannot fake.
28
+ */
29
+ export const BODY_STALL_TIMEOUT_MS = 15_000;
30
+ /**
31
+ * How long the whole body may take, however much progress it keeps making.
32
+ *
33
+ * The stall watchdog can only act on a pause, so a mirror that sends one
34
+ * byte inside every 15s window would hold the read open forever. 10 minutes
35
+ * is ~7x the slowest measured full download (89.9s); a body still going
36
+ * after that is broken, not slow, and the byte count in the message says
37
+ * which of the two it was.
38
+ */
39
+ export const BODY_TOTAL_CEILING_MS = 600_000;
40
+ /**
41
+ * The most body bytes to accept before declaring the response not a catalog.
42
+ *
43
+ * The catalog passed 5 MB in September 2026 (9.5 MB unpacked by October);
44
+ * 256 MB is decades of headroom — and still a hard bound on memory, because
45
+ * the whole body is buffered before parsing and a mirror streaming garbage
46
+ * at line speed would otherwise grow that buffer until the process dies.
47
+ * backup.ts and gist.ts cap their downloads for the same reason.
48
+ */
49
+ export const MAX_BODY_BYTES = 256 * 1024 * 1024;
50
+ /**
51
+ * Read a body under a stall watchdog instead of a total budget.
52
+ *
53
+ * One timer for the whole fetch was the mistake both before and after #188:
54
+ * at 4s it hid slowness behind a stale snapshot, at 15s it kills downloads
55
+ * that are still moving. On a lossy proxied link the catalog body trickles
56
+ * for far longer than 15s while never once going silent — measured 89.9s
57
+ * end-to-end for a body the 15s cutoff had declared dead twice. This reader
58
+ * lets a moving body run as long as it keeps moving, in either direction's
59
+ * sense of "slow", and ends one that goes quiet for `stallMs` with a message
60
+ * that says what actually happened and how much had arrived.
61
+ *
62
+ * The rejection comes from here, not from an abort: undici's abort message
63
+ * ("This operation was aborted") cannot tell a user anything actionable, and
64
+ * a bug report containing this string will contain the byte count too.
65
+ *
66
+ * Two backstops keep "still moving" from meaning "forever", because the
67
+ * watchdog can only see pauses: a total ceiling for a body that trickles
68
+ * without ever pausing, and a size cap for one that outruns any catalog.
69
+ *
70
+ * @param res - the response whose body to read.
71
+ * @param stallMs - silence that ends the read, in milliseconds.
72
+ * @param what - the download, for the rejection message ("the catalog").
73
+ */
74
+ export function readBodyWhileProgressing(res, stallMs, what = 'the catalog') {
75
+ // The stand-in closes at once, so an absent body reads as "no body"
76
+ // below instead of parking this reader on a stream that never ends.
77
+ const reader = (res.body ?? new ReadableStream({ start(controller) { controller.close(); } })).getReader();
78
+ return new Promise((resolve, reject) => {
79
+ const chunks = [];
80
+ let received = 0;
81
+ let settled = false;
82
+ let timer;
83
+ const finish = (error) => {
84
+ if (settled)
85
+ return;
86
+ settled = true;
87
+ if (timer !== undefined)
88
+ clearTimeout(timer);
89
+ clearTimeout(ceiling);
90
+ // Tell the origin we are done with the socket; its refusal is not ours to report.
91
+ reader.cancel().catch(() => { });
92
+ if (error !== undefined)
93
+ reject(error);
94
+ // An empty body otherwise surfaces as a JSON parse error, which tells
95
+ // the user nothing about the network that caused it.
96
+ else if (received === 0)
97
+ reject(new Error(`${what} response carried no body`));
98
+ else
99
+ resolve(concatBytes(chunks));
100
+ };
101
+ const ceiling = setTimeout(() => {
102
+ finish(new DOMException(`${what} download did not finish within ${String(Math.round(BODY_TOTAL_CEILING_MS / 1000))}s (received ${String(received)} bytes)`, 'TimeoutError'));
103
+ }, BODY_TOTAL_CEILING_MS);
104
+ const arm = () => {
105
+ if (timer !== undefined)
106
+ clearTimeout(timer);
107
+ timer = setTimeout(() => {
108
+ finish(new DOMException(`no new data for ${String(Math.round(stallMs / 1000))}s while downloading ${what} (received ${String(received)} bytes)`, 'TimeoutError'));
109
+ }, stallMs);
110
+ };
111
+ const step = () => {
112
+ reader.read().then((r) => {
113
+ if (settled)
114
+ return;
115
+ if (r.done || r.value === undefined) {
116
+ finish();
117
+ return;
118
+ }
119
+ chunks.push(r.value);
120
+ 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)`));
123
+ return;
124
+ }
125
+ arm();
126
+ step();
127
+ }, (error) => {
128
+ finish(error instanceof Error ? error : new Error(String(error)));
129
+ });
130
+ };
131
+ arm();
132
+ step();
133
+ });
134
+ }
135
+ function concatBytes(chunks) {
136
+ const all = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0));
137
+ let at = 0;
138
+ for (const chunk of chunks) {
139
+ all.set(chunk, at);
140
+ at += chunk.byteLength;
141
+ }
142
+ return all;
143
+ }
144
+ /**
145
+ * Fetch with a headers-only deadline, then hand the body to the watchdog.
146
+ *
147
+ * Two clocks, because they measure different things: how long the origin
148
+ * takes to start answering, and how long it keeps answering. The abort signal
149
+ * covers only the first — once headers are in, the watchdog owns the read,
150
+ * which is what lets a slow-but-moving tarball finish.
151
+ *
152
+ * @param fetchImpl - the project's fetch (proxy-aware), injected for tests.
153
+ * @param url - what to fetch.
154
+ * @param what - the download, for messages.
155
+ * @param init - extra request options.
156
+ * @returns the body bytes.
157
+ */
158
+ export async function fetchBodyWhileProgressing(fetchImpl, url, what, init = {}) {
159
+ const controller = new AbortController();
160
+ const deadline = setTimeout(() => {
161
+ controller.abort(new DOMException('the response did not start in time', 'TimeoutError'));
162
+ }, HEADERS_TIMEOUT_MS);
163
+ let res;
164
+ try {
165
+ res = await fetchImpl(url, { ...init, signal: controller.signal });
166
+ }
167
+ finally {
168
+ clearTimeout(deadline);
169
+ }
170
+ if (!res.ok)
171
+ throw new Error(`HTTP ${String(res.status)} reading ${what}`);
172
+ return readBodyWhileProgressing(res, BODY_STALL_TIMEOUT_MS, what);
173
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Catalog matching for locally linked / file: installs. Shared by the host
3
+ * restore route and the Market client so both refuse the same wrong guesses.
4
+ */
5
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
6
+ function validSubpath(subpath) {
7
+ if (!/^[A-Za-z0-9_./-]+$/.test(subpath))
8
+ return false;
9
+ return !subpath.split('/').some(seg => seg === '' || seg === '.' || seg === '..');
10
+ }
11
+ /**
12
+ * Keys a catalog URL contributes to restore matching.
13
+ * A `/tree/` entry is ONLY its exact `#path:` id — never the bare repo —
14
+ * so a collection-root identity cannot select a sibling subpackage.
15
+ */
16
+ function catalogMatchKeys(url) {
17
+ const m = /^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\/tree\/[^/]+\/(.+?))?\/?$/.exec(url);
18
+ if (m === null || !REPO_RE.test(m[1]))
19
+ return { path: null, repo: null };
20
+ const subpath = m[2] ?? null;
21
+ if (subpath !== null && !validSubpath(subpath))
22
+ return { path: null, repo: null };
23
+ const repo = m[1].toLowerCase();
24
+ return subpath === null
25
+ ? { path: null, repo }
26
+ : { path: `${repo}#path:/${subpath.toLowerCase()}`, repo: null };
27
+ }
28
+ function catalogEntryMatchesHints(url, hintSet) {
29
+ const keys = catalogMatchKeys(url);
30
+ return (keys.path !== null && hintSet.has(keys.path))
31
+ || (keys.repo !== null && hintSet.has(keys.repo));
32
+ }
33
+ /**
34
+ * The catalog entry a locally linked / file: install should restore to.
35
+ * Exact `#path:` identities win, then collection-root identities against
36
+ * root-only catalog rows, then a unique name/npm match when nothing
37
+ * contradicts it. A bare repo identity never selects a root row while
38
+ * `/tree/` siblings exist for that repo — the checkout did not say which
39
+ * package it is, and guessing wrong installs a different plugin.
40
+ * Same-named forks without identities or a matching hint stay unmatched
41
+ * rather than guessing; declared repo evidence that matches nothing in the
42
+ * catalog must not fall back to a coincidental unique name.
43
+ */
44
+ /**
45
+ * Memo for findCatalogEntryForLocal, keyed on the catalog array identity and
46
+ * then the full lookup input (#589).
47
+ *
48
+ * The market client calls this once per rendered card for every link:/file:
49
+ * dependency, and each call filtered the whole catalog and walked every URL —
50
+ * measured ~300ms per render at 24 cards against a 3,627-entry catalog, on
51
+ * every keystroke of the search box. The result is a pure function of the
52
+ * catalog, the name, the identities, and the hints, so caching by the array
53
+ * identity never serves a stale answer: a refetched catalog is a new array,
54
+ * and the old inner map becomes collectable. Null results are cached too —
55
+ * they are the common answer for same-named forks without evidence.
56
+ *
57
+ * The input key is the JSON form of the whole tuple, not a delimiter join:
58
+ * an empty array and an array holding one empty string serialize
59
+ * differently, and the matcher treats them differently (`identitySet.size >
60
+ * 0` chooses the evidence branch), so the key must not conflate them
61
+ * (#485's lesson: weak signals must never override strong ones).
62
+ */
63
+ const localMatchCache = new WeakMap();
64
+ export function findCatalogEntryForLocal(plugins, name, identities = [], hints = []) {
65
+ const cacheKey = JSON.stringify([name, identities, hints]);
66
+ let byCatalog = localMatchCache.get(plugins);
67
+ if (byCatalog === undefined) {
68
+ byCatalog = new Map();
69
+ localMatchCache.set(plugins, byCatalog);
70
+ }
71
+ const hit = byCatalog.get(cacheKey);
72
+ if (hit !== undefined)
73
+ return hit;
74
+ const result = findCatalogEntryForLocalUncached(plugins, name, identities, hints);
75
+ byCatalog.set(cacheKey, result);
76
+ return result;
77
+ }
78
+ function findCatalogEntryForLocalUncached(plugins, name, identities, hints) {
79
+ const nameKey = name.toLowerCase();
80
+ const byName = plugins.filter(plugin => plugin.name.toLowerCase() === nameKey
81
+ || (typeof plugin.npm === 'string' && plugin.npm.toLowerCase() === nameKey));
82
+ const identitySet = new Set(identities.map(value => value.toLowerCase()));
83
+ const hintSet = new Set(hints.map(value => value.toLowerCase()));
84
+ const treeRepos = new Set();
85
+ for (const plugin of plugins) {
86
+ const keys = catalogMatchKeys(plugin.url);
87
+ if (keys.path !== null)
88
+ treeRepos.add(keys.path.slice(0, keys.path.indexOf('#path:/')));
89
+ }
90
+ if (identitySet.size > 0) {
91
+ const pathHit = plugins.find(plugin => {
92
+ const keys = catalogMatchKeys(plugin.url);
93
+ return keys.path !== null && identitySet.has(keys.path);
94
+ });
95
+ if (pathHit !== undefined)
96
+ return pathHit;
97
+ const rootHit = plugins.find(plugin => {
98
+ const keys = catalogMatchKeys(plugin.url);
99
+ if (keys.repo === null || !identitySet.has(keys.repo))
100
+ return false;
101
+ return !treeRepos.has(keys.repo) || byName.includes(plugin);
102
+ });
103
+ if (rootHit !== undefined)
104
+ return rootHit;
105
+ return null;
106
+ }
107
+ if (byName.length === 1) {
108
+ const only = byName[0];
109
+ if (hintSet.size > 0 && !catalogEntryMatchesHints(only.url, hintSet))
110
+ return null;
111
+ return only;
112
+ }
113
+ if (byName.length > 1 && hintSet.size > 0) {
114
+ const hinted = byName.find(plugin => catalogEntryMatchesHints(plugin.url, hintSet));
115
+ if (hinted !== undefined)
116
+ return hinted;
117
+ }
118
+ return null;
119
+ }
120
+ function catalogEntriesByName(plugins, name) {
121
+ const nameKey = name.toLowerCase();
122
+ return plugins.filter(plugin => plugin.name.toLowerCase() === nameKey
123
+ || (typeof plugin.npm === 'string' && plugin.npm.toLowerCase() === nameKey));
124
+ }
125
+ /**
126
+ * Why a local restore was blocked, when findCatalogEntryForLocal returned
127
+ * null — and, when it matched, whether anything but the NAME agreed.
128
+ *
129
+ * `verified` is the difference between "put this back where it came from"
130
+ * and "install the catalog's plugin that happens to share this name". A
131
+ * local checkout with no declared repo — no git remote, no `repository`
132
+ * field — gives the market nothing to match on, so a unique same-named
133
+ * catalog entry is a guess. Usually a good one (#429: the local copy IS a
134
+ * tweaked copy of that entry). Not always: @liuwenji007 reported a fork of
135
+ * their own `dsh-humanizer` restored to a different author's plugin of the
136
+ * same name (#485), which is someone else's code arriving under a button
137
+ * labelled "restore".
138
+ *
139
+ * The match is kept, because refusing it would break the ordinary case, and
140
+ * the caller is told not to present it as a certainty.
141
+ */
142
+ export function resolveCatalogRestore(plugins, name, identities = [], hints = []) {
143
+ const entry = findCatalogEntryForLocal(plugins, name, identities, hints);
144
+ if (entry !== null) {
145
+ // Evidence is what every other branch of the matcher requires; the
146
+ // name-only branch is reachable only when there is none of it.
147
+ const verified = identities.length > 0 || hints.length > 0;
148
+ return { ok: true, entry, verified };
149
+ }
150
+ const byName = catalogEntriesByName(plugins, name);
151
+ if (byName.length === 0)
152
+ return { ok: false, reason: 'no-catalog' };
153
+ const identitySet = new Set(identities.map(value => value.toLowerCase()));
154
+ const hintSet = new Set(hints.map(value => value.toLowerCase()));
155
+ if (identitySet.size > 0 || hintSet.size > 0)
156
+ return { ok: false, reason: 'repo-mismatch' };
157
+ // Only ambiguous same-name rows reach here: a unique name with no evidence
158
+ // would have matched inside findCatalogEntryForLocal.
159
+ return { ok: false, reason: 'no-catalog' };
160
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Reading the plugin catalog out of a published npm package.
3
+ *
4
+ * The catalog's own host is the thing being worked around. `plugins.json` is
5
+ * served from GitHub Pages, and the public GitHub proxies that make GitHub
6
+ * usable from mainland China refuse any hostname that is not github.com's
7
+ * own — measured: the project domain comes back 403. So the file cannot be
8
+ * carried through the same route as everything else while it lives there.
9
+ *
10
+ * Published to npm it can be. Every China npm mirror already carries it, it
11
+ * is the same infrastructure the plugins themselves arrive on, and it needs
12
+ * no service that did not already have to work. It also gains a version
13
+ * number, which the origin never had: a catalog build that ships bad data
14
+ * can be rolled back instead of only being fixed forwards.
15
+ *
16
+ * Mirrors rewrite `dist.tarball` to point at themselves, so following that
17
+ * field is what keeps the download on the mirror rather than bouncing back
18
+ * to the origin registry — verified against the Tencent mirror, which serves
19
+ * its own host in that field.
20
+ */
21
+ import { gunzipSync } from 'node:zlib';
22
+ import { fetchBodyWhileProgressing } from './body-progress.js';
23
+ import { marketFetch } from './net.js';
24
+ /** Long enough for a multi-megabyte tarball on a slow link, short enough to fall back. */
25
+ const TIMEOUT_MS = 20_000;
26
+ /**
27
+ * `dist.tarball` as an absolute URL.
28
+ *
29
+ * A registry behind a path prefix — Nexus, Verdaccio, a reverse proxy — may
30
+ * answer that field as a relative path (`/dsh-plugin-catalog/-/…`). pnpm
31
+ * resolves it against the registry; passing it straight to `fetch` threw
32
+ * "Failed to parse URL" instead, the npm source dropped out of the list, and
33
+ * the market read the catalog from somewhere else without saying so (#1117).
34
+ *
35
+ * Relative resolution follows the URL rules: a value starting with `/` is
36
+ * root-relative and a bare path is relative to the registry's own directory,
37
+ * which is where the registry serves it from. Nothing is rewritten when the
38
+ * field is already absolute.
39
+ */
40
+ export function absoluteTarballUrl(tarball, registry) {
41
+ try {
42
+ return new URL(tarball).href;
43
+ }
44
+ catch {
45
+ // Not absolute — resolve below, and keep the raw value if even that fails
46
+ // so the error still names what the registry answered.
47
+ }
48
+ try {
49
+ return new URL(tarball, `${registry.replace(/\/+$/u, '')}/`).href;
50
+ }
51
+ catch {
52
+ return tarball;
53
+ }
54
+ }
55
+ /**
56
+ * A tar entry header, as far as this needs to read one.
57
+ *
58
+ * Written out rather than pulled from a dependency: the format is 512-byte
59
+ * headers with the name at offset 0 and an octal size at 124, and a reader
60
+ * for one known filename is shorter than the argument for adding a package
61
+ * to a plugin's runtime.
62
+ */
63
+ const NAME_OFFSET = 0;
64
+ const NAME_LENGTH = 100;
65
+ const SIZE_OFFSET = 124;
66
+ const SIZE_LENGTH = 12;
67
+ const TYPE_OFFSET = 156;
68
+ const BLOCK = 512;
69
+ /**
70
+ * One file's bytes from a gzipped tar, or null when it is not in there.
71
+ *
72
+ * @param gz - the gzipped tarball.
73
+ * @param wanted - the exact entry name, npm-style (`package/plugins.json`).
74
+ */
75
+ export function fileFromTarball(gz, wanted) {
76
+ const buf = gunzipSync(gz);
77
+ let offset = 0;
78
+ while (offset + BLOCK <= buf.length) {
79
+ const name = buf.toString('utf8', offset + NAME_OFFSET, offset + NAME_OFFSET + NAME_LENGTH).replace(/\0.*$/s, '');
80
+ // Two consecutive empty headers end a tar; one is enough to stop here.
81
+ if (name === '')
82
+ break;
83
+ const rawSize = buf.toString('ascii', offset + SIZE_OFFSET, offset + SIZE_OFFSET + SIZE_LENGTH).replace(/\0.*$/s, '').trim();
84
+ const size = Number.parseInt(rawSize, 8);
85
+ if (!Number.isFinite(size) || size < 0)
86
+ break;
87
+ const type = String.fromCharCode(buf[offset + TYPE_OFFSET] ?? 0);
88
+ offset += BLOCK;
89
+ // '0' and NUL both mean a regular file; anything else (directories,
90
+ // links, pax headers) is skipped rather than mistaken for content.
91
+ if ((type === '0' || type === '\0') && name === wanted) {
92
+ return buf.subarray(offset, offset + size);
93
+ }
94
+ offset += Math.ceil(size / BLOCK) * BLOCK;
95
+ }
96
+ return null;
97
+ }
98
+ /**
99
+ * The catalog carried by a published package, and the version it came from.
100
+ *
101
+ * The version doubles as the cache validator — a better one than an ETag,
102
+ * because it is meaningful to a human reading a log and it is the thing a
103
+ * rollback would change.
104
+ *
105
+ * @param registry - registry base, no trailing slash.
106
+ * @param pkg - package name.
107
+ * @param known - a version already held, to skip re-downloading.
108
+ * @returns the parsed JSON and its version, or `{ version, data: null }` when
109
+ * the published version is the one already held.
110
+ * @throws when the package, the tarball or the file inside it cannot be read.
111
+ */
112
+ export async function catalogFromPackage(registry, pkg, known,
113
+ /** The entry to extract; the catalog package carries `plugins.json`, companions theirs. */
114
+ file = 'package/plugins.json') {
115
+ const metaRes = await marketFetch(`${registry}/${encodeURIComponent(pkg)}/latest`, {
116
+ signal: AbortSignal.timeout(TIMEOUT_MS),
117
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
118
+ });
119
+ if (!metaRes.ok)
120
+ throw new Error(`HTTP ${String(metaRes.status)} reading ${pkg} metadata`);
121
+ const meta = (await metaRes.json());
122
+ const version = typeof meta.version === 'string' ? meta.version : null;
123
+ const tarball = typeof meta.dist?.tarball === 'string' ? meta.dist.tarball : null;
124
+ if (version === null || tarball === null)
125
+ throw new Error(`${pkg} metadata names no version or tarball`);
126
+ // Nothing changed, so nothing to download. The whole point of putting the
127
+ // catalog on a mirror is the bytes it saves; re-fetching a package we
128
+ // already hold would give most of them back.
129
+ if (known !== undefined && known === version)
130
+ return { version, data: null };
131
+ // Follow `dist.tarball` rather than composing a URL. A mirror rewrites
132
+ // this field to its own host, and composing one would send the download
133
+ // back to the origin registry the region exists to avoid.
134
+ //
135
+ // The body is read under a stall watchdog rather than a total budget
136
+ // (#1049). A 3.2 MB tarball needs 158 KB/s to clear a fixed 20s ceiling,
137
+ // and a China mirror jittering to 17–40 KB/s cannot: both attempts died at
138
+ // the ceiling while bytes were still arriving, and the catalog fell through
139
+ // to a source that took longer still. TIMEOUT_MS still bounds the wait for
140
+ // the response to start, the one thing a fixed timer is good at.
141
+ const bytes = fileFromTarball(Buffer.from(await fetchBodyWhileProgressing(marketFetch, absoluteTarballUrl(tarball, registry), `${pkg} tarball`)), file);
142
+ if (bytes === null)
143
+ throw new Error(`${pkg}@${version} carries no ${file}`);
144
+ return { version, data: JSON.parse(bytes.toString('utf8')) };
145
+ }
146
+ /**
147
+ * One file out of a package's newest tarball, or null when it cannot be read
148
+ * (#1012).
149
+ *
150
+ * The install route asks a package what it declares before it installs it: a
151
+ * rename can only be detected from the rows the artifact carries, not from
152
+ * the name it was published under. A failed read is not a verdict — the
153
+ * caller treats null as "not declared", because a registry hiccup must never
154
+ * become a refusal to install.
155
+ *
156
+ * @param registry - registry base, no trailing slash.
157
+ * @param pkg - package name.
158
+ * @param file - exact entry name inside the tarball (`package/cordis.patch.yml`).
159
+ */
160
+ export async function packageFileFromRegistry(registry, pkg, file) {
161
+ try {
162
+ const metaRes = await marketFetch(`${registry}/${encodeURIComponent(pkg)}/latest`, {
163
+ signal: AbortSignal.timeout(TIMEOUT_MS),
164
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
165
+ });
166
+ if (!metaRes.ok)
167
+ return null;
168
+ const meta = (await metaRes.json());
169
+ const tarball = typeof meta.dist?.tarball === 'string' ? meta.dist.tarball : null;
170
+ if (tarball === null)
171
+ return null;
172
+ const tarRes = await marketFetch(absoluteTarballUrl(tarball, registry), { signal: AbortSignal.timeout(TIMEOUT_MS) });
173
+ if (!tarRes.ok)
174
+ return null;
175
+ return fileFromTarball(Buffer.from(await tarRes.arrayBuffer()), file);
176
+ }
177
+ catch {
178
+ return null;
179
+ }
180
+ }