dshmarket 1.77.1 → 1.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/README.zh.md +13 -0
- package/client/client.js +801 -96
- package/lib/catalog-npm.js +3 -1
- package/lib/catalogs.js +567 -0
- package/lib/changelog.js +2 -1
- package/lib/discovery-compatibility.js +3 -2
- package/lib/hot.js +19 -0
- package/lib/http.js +13 -0
- package/lib/net.js +9 -1
- package/lib/npmrc.js +267 -0
- package/lib/offline.js +183 -0
- package/lib/policy.js +326 -0
- package/lib/regions.js +17 -4
- package/lib/registry.js +88 -1
- package/lib/routes.js +258 -13
- package/lib/sources.js +20 -2
- package/lib/telemetry.js +4 -0
- package/lib/types/catalog-npm.d.ts +1 -1
- package/lib/types/catalogs.d.ts +156 -0
- package/lib/types/hot.d.ts +9 -0
- package/lib/types/http.d.ts +2 -0
- package/lib/types/net.d.ts +1 -1
- package/lib/types/npmrc.d.ts +79 -0
- package/lib/types/offline.d.ts +54 -0
- package/lib/types/policy.d.ts +116 -0
- package/lib/types/regions.d.ts +2 -0
- package/lib/types/registry.d.ts +42 -18
- package/lib/types/sources.d.ts +3 -0
- package/lib/types/updates.d.ts +2 -0
- package/lib/updates.js +26 -5
- package/package.json +1 -1
package/lib/catalog-npm.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
import { gunzipSync } from 'node:zlib';
|
|
22
22
|
import { fetchBodyWhileProgressing } from './body-progress.js';
|
|
23
23
|
import { marketFetch } from './net.js';
|
|
24
|
+
import { registryFor } from './npmrc.js';
|
|
24
25
|
/** Long enough for a multi-megabyte tarball on a slow link, short enough to fall back. */
|
|
25
26
|
const TIMEOUT_MS = 20_000;
|
|
26
27
|
/**
|
|
@@ -157,7 +158,8 @@ file = 'package/plugins.json') {
|
|
|
157
158
|
* @param pkg - package name.
|
|
158
159
|
* @param file - exact entry name inside the tarball (`package/cordis.patch.yml`).
|
|
159
160
|
*/
|
|
160
|
-
export async function packageFileFromRegistry(
|
|
161
|
+
export async function packageFileFromRegistry(base, pkg, file) {
|
|
162
|
+
const registry = registryFor(pkg, base);
|
|
161
163
|
try {
|
|
162
164
|
const metaRes = await marketFetch(`${registry}/${encodeURIComponent(pkg)}/latest`, {
|
|
163
165
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
package/lib/catalogs.js
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalog sources beyond the public one: an organization's own list of
|
|
3
|
+
* plugins, in the same shape as the public `plugins.json`.
|
|
4
|
+
*
|
|
5
|
+
* Where they come from:
|
|
6
|
+
* - the policy file's `catalogs` (locked; the user cannot remove them), and
|
|
7
|
+
* - the user's own, added in the market's settings (stored in the profile's
|
|
8
|
+
* market state) unless the policy says `"userCatalogs": false`.
|
|
9
|
+
*
|
|
10
|
+
* This module holds everything about them EXCEPT the public catalog, whose
|
|
11
|
+
* fetch path (and its 304 validator) stays in src/registry.ts exactly as it
|
|
12
|
+
* was. `loadRegistry` there calls in here only when something is configured;
|
|
13
|
+
* with nothing configured it never gets here, which is what makes "no policy,
|
|
14
|
+
* no user catalogs" the same requests as before.
|
|
15
|
+
*
|
|
16
|
+
* ## Failure
|
|
17
|
+
*
|
|
18
|
+
* A source that cannot be read costs the user that source, not the market:
|
|
19
|
+
* every source is fetched on its own, what loaded is merged, and each failure
|
|
20
|
+
* is reported per source as a code plus detail (`SourceError`) for the UI to
|
|
21
|
+
* say in the user's language. Secrets: header values and `.npmrc` tokens are
|
|
22
|
+
* never put into a message — {@link scrub} removes any configured header value
|
|
23
|
+
* and URL credentials from every failure text before it leaves this module.
|
|
24
|
+
*/
|
|
25
|
+
import { createHash } from 'node:crypto';
|
|
26
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
27
|
+
import { basename, dirname, extname, isAbsolute, join } from 'node:path';
|
|
28
|
+
import { fileURLToPath } from 'node:url';
|
|
29
|
+
import { BODY_STALL_TIMEOUT_MS, HEADERS_TIMEOUT_MS, readBodyWhileProgressing } from './body-progress.js';
|
|
30
|
+
import { expandHomePath } from './home-paths.js';
|
|
31
|
+
import { logEvent } from './log.js';
|
|
32
|
+
import { marketFetch } from './net.js';
|
|
33
|
+
import { resolveBundleFile } from './offline.js';
|
|
34
|
+
import { asLabel, CATALOG_ID_RE, expandEnv, getPolicy, globMatch, pinnedVersion, PUBLIC_SOURCE_ID, } from './policy.js';
|
|
35
|
+
export const MAX_USER_CATALOGS = 8;
|
|
36
|
+
/** The public catalog's label, as plugin cards and the source list show it. */
|
|
37
|
+
export const PUBLIC_LABEL = { zh: '公开目录', en: 'Public catalog' };
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// Configuration: policy + the user's saved catalogs.
|
|
40
|
+
let userCatalogs = [];
|
|
41
|
+
/** Replace the user's saved catalogs (read from the profile's market state). */
|
|
42
|
+
export function setUserCatalogs(list) {
|
|
43
|
+
userCatalogs = [...list];
|
|
44
|
+
}
|
|
45
|
+
export function currentUserCatalogs() {
|
|
46
|
+
return userCatalogs;
|
|
47
|
+
}
|
|
48
|
+
/** Where a user catalog reads from, with the host's own tilde forms expanded. */
|
|
49
|
+
function userSource(entry) {
|
|
50
|
+
const fallback = fallbackLabel(entry);
|
|
51
|
+
return {
|
|
52
|
+
id: entry.id,
|
|
53
|
+
kind: 'user',
|
|
54
|
+
label: fallback,
|
|
55
|
+
...(entry.url !== undefined ? { url: entry.url } : {}),
|
|
56
|
+
...(entry.file !== undefined ? { file: entry.file } : {}),
|
|
57
|
+
headers: {},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** Host name or file name: a label for a catalog that did not name itself. */
|
|
61
|
+
export function fallbackLabel(entry) {
|
|
62
|
+
let text = '';
|
|
63
|
+
if (entry.url !== undefined) {
|
|
64
|
+
try {
|
|
65
|
+
text = new URL(entry.url).hostname;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
text = '';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else if (entry.file !== undefined) {
|
|
72
|
+
text = basename(entry.file, extname(entry.file));
|
|
73
|
+
}
|
|
74
|
+
text = text === '' ? 'catalog' : text.slice(0, 40);
|
|
75
|
+
return { zh: text, en: text };
|
|
76
|
+
}
|
|
77
|
+
/** The sources and filters in force right now. Cheap: the policy is cached. */
|
|
78
|
+
export function catalogConfig() {
|
|
79
|
+
const policy = getPolicy();
|
|
80
|
+
const extras = policy.catalogs.map(entry => ({
|
|
81
|
+
id: entry.id,
|
|
82
|
+
kind: 'policy',
|
|
83
|
+
label: entry.label,
|
|
84
|
+
...(entry.url !== undefined ? { url: entry.url } : {}),
|
|
85
|
+
...(entry.file !== undefined ? { file: entry.file } : {}),
|
|
86
|
+
headers: entry.headers,
|
|
87
|
+
}));
|
|
88
|
+
if (policy.userCatalogs) {
|
|
89
|
+
const taken = new Set(extras.map(source => source.id));
|
|
90
|
+
for (const entry of userCatalogs) {
|
|
91
|
+
if (!taken.has(entry.id))
|
|
92
|
+
extras.push(userSource(entry));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const active = extras.length > 0 || !policy.publicCatalog || policy.allow !== null || Object.keys(policy.pins).length > 0;
|
|
96
|
+
return {
|
|
97
|
+
policy,
|
|
98
|
+
publicEnabled: policy.publicCatalog,
|
|
99
|
+
extras,
|
|
100
|
+
active,
|
|
101
|
+
signature: JSON.stringify([
|
|
102
|
+
policy.publicCatalog, policy.allow, policy.pins,
|
|
103
|
+
extras.map(source => [source.id, source.url ?? null, source.file ?? null, source.headers]),
|
|
104
|
+
]),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Failures, without secrets.
|
|
109
|
+
/** Remove URL credentials, query strings, and any configured header value from a text. */
|
|
110
|
+
export function scrub(text, secrets = []) {
|
|
111
|
+
let out = text;
|
|
112
|
+
for (const secret of secrets) {
|
|
113
|
+
if (secret.length >= 4)
|
|
114
|
+
out = out.split(secret).join('***');
|
|
115
|
+
// `Bearer abc` is configured whole, but a server may echo only the token.
|
|
116
|
+
const token = /^\s*(?:bearer|basic|token)\s+(\S+)\s*$/iu.exec(secret)?.[1];
|
|
117
|
+
if (token !== undefined && token.length >= 4)
|
|
118
|
+
out = out.split(token).join('***');
|
|
119
|
+
}
|
|
120
|
+
return out
|
|
121
|
+
.replace(/(\bhttps?:\/\/)[^\s/@]+@/giu, '$1***@')
|
|
122
|
+
.replace(/(\bhttps?:\/\/[^\s?#]+)\?[^\s#]*/giu, '$1?***');
|
|
123
|
+
}
|
|
124
|
+
/** The plain location of a source for display: host and path, or the file path. */
|
|
125
|
+
export function displayWhere(source) {
|
|
126
|
+
if (source.file !== undefined)
|
|
127
|
+
return source.file;
|
|
128
|
+
if (source.url === undefined)
|
|
129
|
+
return '';
|
|
130
|
+
try {
|
|
131
|
+
const url = new URL(source.url);
|
|
132
|
+
return `${url.host}${url.pathname === '/' ? '' : url.pathname}`;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return '';
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function failure(error, secrets) {
|
|
139
|
+
if (error instanceof SourceFailure)
|
|
140
|
+
return { code: error.code, detail: scrub(error.detail, secrets).slice(0, 200) };
|
|
141
|
+
const name = error instanceof Error ? error.name : '';
|
|
142
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
143
|
+
const cause = error instanceof Error && error.cause instanceof Error ? error.cause.message : '';
|
|
144
|
+
const detail = scrub(cause !== '' && /fetch failed/iu.test(message) ? cause : message, secrets).slice(0, 200);
|
|
145
|
+
if (name === 'TimeoutError' || /timeout|timed out|no new data/iu.test(message))
|
|
146
|
+
return { code: 'timeout', detail };
|
|
147
|
+
return { code: 'network', detail };
|
|
148
|
+
}
|
|
149
|
+
class SourceFailure extends Error {
|
|
150
|
+
code;
|
|
151
|
+
detail;
|
|
152
|
+
constructor(code, detail) {
|
|
153
|
+
super(`${code}: ${detail}`);
|
|
154
|
+
this.code = code;
|
|
155
|
+
this.detail = detail;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const cache = new Map();
|
|
159
|
+
const lastLogged = new Map();
|
|
160
|
+
/** Drop every validator, so the next read of each source is unconditional. */
|
|
161
|
+
export function forgetExtraCatalogs() {
|
|
162
|
+
cache.clear();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* A git source an entry may install from, as pnpm's spec, or null.
|
|
166
|
+
*
|
|
167
|
+
* https and ssh remotes (plus plain http for hosts that only speak it), an
|
|
168
|
+
* optional `#ref`. A password in the address is refused: a catalog is shared
|
|
169
|
+
* text, and a secret does not belong in it. ssh keys are the machine's own.
|
|
170
|
+
*/
|
|
171
|
+
export function normalizeGitSpec(value) {
|
|
172
|
+
if (typeof value !== 'string')
|
|
173
|
+
return null;
|
|
174
|
+
const text = value.trim();
|
|
175
|
+
const ref = '(?:#[A-Za-z0-9][A-Za-z0-9._/@^~+-]{0,120})?';
|
|
176
|
+
let spec = null;
|
|
177
|
+
if (new RegExp(`^git\\+(?:https?|ssh)://[^\\s#@:/]+(?::\\d+)?(?:/[^\\s#]*)?${ref}$`, 'u').test(text.replace(/\/\/[^\s/@]*@/u, '//')))
|
|
178
|
+
spec = text;
|
|
179
|
+
else if (new RegExp(`^(?:https?|ssh)://[^\\s#]+\\.git${ref}$`, 'u').test(text.replace(/\/\/[^\s/@]*@/u, '//')))
|
|
180
|
+
spec = `git+${text}`;
|
|
181
|
+
else {
|
|
182
|
+
const scp = new RegExp(`^([A-Za-z0-9._-]+)@([A-Za-z0-9][A-Za-z0-9.-]*):([^\\s#]+)(${ref})$`, 'u').exec(text);
|
|
183
|
+
if (scp !== null)
|
|
184
|
+
spec = `git+ssh://${scp[1]}@${scp[2]}/${scp[3]}${scp[4] ?? ''}`;
|
|
185
|
+
}
|
|
186
|
+
if (spec === null)
|
|
187
|
+
return null;
|
|
188
|
+
try {
|
|
189
|
+
const url = new URL(spec.replace(/^git\+/u, '').replace(/#.*$/u, ''));
|
|
190
|
+
if (url.password !== '' || (url.protocol !== 'ssh:' && url.username !== ''))
|
|
191
|
+
return null;
|
|
192
|
+
// A host that starts with a dash would be read as an option by git.
|
|
193
|
+
if (!/^[A-Za-z0-9[]/u.test(url.hostname))
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
return spec;
|
|
200
|
+
}
|
|
201
|
+
/** Entries a private catalog may carry, made safe to hand to the rest of the market. */
|
|
202
|
+
function cleanEntries(value, baseDir) {
|
|
203
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
204
|
+
throw new SourceFailure('invalid', 'not a catalog document');
|
|
205
|
+
const doc = value;
|
|
206
|
+
if (!Array.isArray(doc.plugins))
|
|
207
|
+
throw new SourceFailure('invalid', 'no "plugins" list');
|
|
208
|
+
const plugins = [];
|
|
209
|
+
let skipped = 0;
|
|
210
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
211
|
+
for (const raw of doc.plugins) {
|
|
212
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
213
|
+
skipped += 1;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
const entry = raw;
|
|
217
|
+
const name = typeof entry.name === 'string' ? entry.name.trim() : '';
|
|
218
|
+
const url = typeof entry.url === 'string' ? entry.url.trim() : '';
|
|
219
|
+
const categories = (Array.isArray(entry.category) ? entry.category : [entry.category])
|
|
220
|
+
.filter((item) => typeof item === 'string' && item !== '');
|
|
221
|
+
if (name === '' || !/^https?:\/\//iu.test(url) || categories.length === 0) {
|
|
222
|
+
skipped += 1;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const npm = typeof entry.npm === 'string' && entry.npm !== '' ? entry.npm : null;
|
|
226
|
+
const description = typeof entry.description === 'string'
|
|
227
|
+
? { zh: entry.description, en: entry.description }
|
|
228
|
+
: entry.description !== null && typeof entry.description === 'object' && !Array.isArray(entry.description)
|
|
229
|
+
? Object.fromEntries(Object.entries(entry.description).filter(([, text]) => typeof text === 'string'))
|
|
230
|
+
: {};
|
|
231
|
+
// A catalog cannot claim to be another source: the market stamps `source`
|
|
232
|
+
// itself after the merge, so a stray one is dropped here.
|
|
233
|
+
const { source: _claimed, offlineTarball: _offline, pinned: _pinned, git: _git, tarball: declaredTarball, screenshots: _shots, ...rest } = entry;
|
|
234
|
+
// A package file that ships with the catalog: resolved here, once, against
|
|
235
|
+
// the catalog's own directory, and kept as an absolute path the install
|
|
236
|
+
// reads. The request never names a path; a bad one skips the entry.
|
|
237
|
+
let offlineTarball;
|
|
238
|
+
if (typeof declaredTarball === 'string' && baseDir !== undefined && !/^https?:/iu.test(declaredTarball)) {
|
|
239
|
+
const resolved = resolveBundleFile(baseDir, declaredTarball);
|
|
240
|
+
if (resolved === null) {
|
|
241
|
+
skipped += 1;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
offlineTarball = resolved;
|
|
245
|
+
}
|
|
246
|
+
const git = normalizeGitSpec(entry.git);
|
|
247
|
+
if (entry.git !== undefined && git === null) {
|
|
248
|
+
skipped += 1;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const screenshots = Array.isArray(entry.screenshots)
|
|
252
|
+
? entry.screenshots.filter((item) => typeof item === 'string' && /^https:\/\//iu.test(item)).slice(0, 6)
|
|
253
|
+
: [];
|
|
254
|
+
plugins.push({
|
|
255
|
+
...rest,
|
|
256
|
+
name,
|
|
257
|
+
owner: typeof entry.owner === 'string' ? entry.owner : '',
|
|
258
|
+
url,
|
|
259
|
+
category: categories.length === 1 ? categories[0] : categories,
|
|
260
|
+
description,
|
|
261
|
+
npm,
|
|
262
|
+
install: typeof entry.install === 'string' && entry.install !== '' ? entry.install : npm ?? name,
|
|
263
|
+
added: typeof entry.added === 'string' ? entry.added : today,
|
|
264
|
+
...(typeof declaredTarball === 'string' && offlineTarball === undefined ? { tarball: declaredTarball } : {}),
|
|
265
|
+
...(offlineTarball === undefined ? {} : { offlineTarball }),
|
|
266
|
+
...(git === null ? {} : { git }),
|
|
267
|
+
...(screenshots.length === 0 ? {} : { screenshots }),
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
const categories = {};
|
|
271
|
+
if (doc.categories !== null && typeof doc.categories === 'object' && !Array.isArray(doc.categories)) {
|
|
272
|
+
for (const [id, label] of Object.entries(doc.categories)) {
|
|
273
|
+
const parsed = asLabel(label);
|
|
274
|
+
if (parsed !== null)
|
|
275
|
+
categories[id] = parsed;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
plugins,
|
|
280
|
+
skipped,
|
|
281
|
+
categories,
|
|
282
|
+
updated: typeof doc.updated === 'string' ? doc.updated : '',
|
|
283
|
+
label: asLabel(doc.label ?? doc.name),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
function digestOf(bytes) {
|
|
287
|
+
return createHash('sha1').update(bytes).digest('hex').slice(0, 16);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Read one source. Throws a {@link SourceFailure} the caller turns into an
|
|
291
|
+
* error shown for this source only.
|
|
292
|
+
*
|
|
293
|
+
* `fresh` skips the validator: adding a catalog must test the real thing.
|
|
294
|
+
*/
|
|
295
|
+
async function readSource(source, fresh, env) {
|
|
296
|
+
const secrets = [];
|
|
297
|
+
const headers = {};
|
|
298
|
+
const missing = [];
|
|
299
|
+
for (const [name, template] of Object.entries(source.headers)) {
|
|
300
|
+
const expanded = expandEnv(template, env);
|
|
301
|
+
missing.push(...expanded.missing);
|
|
302
|
+
headers[name] = expanded.value;
|
|
303
|
+
if (expanded.value !== '')
|
|
304
|
+
secrets.push(expanded.value);
|
|
305
|
+
}
|
|
306
|
+
if (missing.length > 0) {
|
|
307
|
+
throw new SourceFailure('env', [...new Set(missing)].join(', '));
|
|
308
|
+
}
|
|
309
|
+
const previous = fresh ? undefined : cache.get(source.id);
|
|
310
|
+
if (source.file !== undefined) {
|
|
311
|
+
// A directory is an unpacked bundle: its catalog is `plugins.json` inside.
|
|
312
|
+
const file = (() => {
|
|
313
|
+
try {
|
|
314
|
+
return statSync(source.file).isDirectory() ? join(source.file, 'plugins.json') : source.file;
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
return source.file;
|
|
318
|
+
}
|
|
319
|
+
})();
|
|
320
|
+
let info;
|
|
321
|
+
try {
|
|
322
|
+
info = statSync(file);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
throw new SourceFailure('file', error.code === 'ENOENT' ? 'not found' : error instanceof Error ? error.message : String(error));
|
|
326
|
+
}
|
|
327
|
+
const fileStamp = `${String(info.mtimeMs)}:${String(info.size)}`;
|
|
328
|
+
const stamp = `file:${file}`;
|
|
329
|
+
if (previous !== undefined && previous.stamp === stamp && previous.fileStamp === fileStamp)
|
|
330
|
+
return { cached: previous, secrets };
|
|
331
|
+
let text;
|
|
332
|
+
try {
|
|
333
|
+
text = readFileSync(file, 'utf8');
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
throw new SourceFailure('file', error instanceof Error ? error.message : String(error));
|
|
337
|
+
}
|
|
338
|
+
return { cached: remember(source, stamp, null, null, fileStamp, text, previous, dirname(file)), secrets };
|
|
339
|
+
}
|
|
340
|
+
const url = source.url;
|
|
341
|
+
const stamp = `url:${url}:${digestOf(JSON.stringify(headers))}`;
|
|
342
|
+
const reusable = previous !== undefined && previous.stamp === stamp ? previous : undefined;
|
|
343
|
+
const sent = { ...headers };
|
|
344
|
+
if (reusable?.etag != null)
|
|
345
|
+
sent['if-none-match'] = reusable.etag;
|
|
346
|
+
else if (reusable?.modified != null)
|
|
347
|
+
sent['if-modified-since'] = reusable.modified;
|
|
348
|
+
const controller = new AbortController();
|
|
349
|
+
const deadline = setTimeout(() => {
|
|
350
|
+
controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
|
|
351
|
+
}, HEADERS_TIMEOUT_MS);
|
|
352
|
+
let res;
|
|
353
|
+
try {
|
|
354
|
+
res = await marketFetch(url, { signal: controller.signal, headers: sent });
|
|
355
|
+
}
|
|
356
|
+
finally {
|
|
357
|
+
clearTimeout(deadline);
|
|
358
|
+
}
|
|
359
|
+
if (res.status === 304 && reusable !== undefined)
|
|
360
|
+
return { cached: reusable, secrets };
|
|
361
|
+
if (res.status === 401 || res.status === 403)
|
|
362
|
+
throw new SourceFailure('auth', String(res.status));
|
|
363
|
+
if (!res.ok)
|
|
364
|
+
throw new SourceFailure('http', String(res.status));
|
|
365
|
+
const text = new TextDecoder().decode(await readBodyWhileProgressing(res, BODY_STALL_TIMEOUT_MS, 'the catalog'));
|
|
366
|
+
return {
|
|
367
|
+
cached: remember(source, stamp, res.headers.get('etag'), res.headers.get('last-modified'), null, text, previous),
|
|
368
|
+
secrets,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function remember(source, stamp, etag, modified, fileStamp, text, previous, baseDir) {
|
|
372
|
+
const digest = digestOf(text);
|
|
373
|
+
// The same content is the same object: nothing downstream (the discovery
|
|
374
|
+
// snapshot, the client's generation check) should see a change that is not one.
|
|
375
|
+
if (previous !== undefined && previous.stamp === stamp && previous.digest === digest) {
|
|
376
|
+
const kept = { ...previous, etag, modified, fileStamp };
|
|
377
|
+
cache.set(source.id, kept);
|
|
378
|
+
return kept;
|
|
379
|
+
}
|
|
380
|
+
let parsed;
|
|
381
|
+
try {
|
|
382
|
+
parsed = JSON.parse(text);
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
throw new SourceFailure('invalid', 'not JSON');
|
|
386
|
+
}
|
|
387
|
+
const clean = cleanEntries(parsed, baseDir);
|
|
388
|
+
if (clean.plugins.length === 0)
|
|
389
|
+
throw new SourceFailure('empty', clean.skipped > 0 ? `${String(clean.skipped)} unusable entries` : '');
|
|
390
|
+
const registry = {
|
|
391
|
+
updated: clean.updated,
|
|
392
|
+
count: clean.plugins.length,
|
|
393
|
+
categories: clean.categories,
|
|
394
|
+
plugins: clean.plugins,
|
|
395
|
+
};
|
|
396
|
+
const cached = { stamp, etag, modified, fileStamp, digest, registry, label: clean.label, skipped: clean.skipped, offline: clean.plugins.some(plugin => plugin.offlineTarball !== undefined) };
|
|
397
|
+
cache.set(source.id, cached);
|
|
398
|
+
return cached;
|
|
399
|
+
}
|
|
400
|
+
/** Read one source and report it; never throws. */
|
|
401
|
+
export async function loadExtra(source, options = {}) {
|
|
402
|
+
const base = {
|
|
403
|
+
id: source.id,
|
|
404
|
+
kind: source.kind,
|
|
405
|
+
where: displayWhere(source),
|
|
406
|
+
locked: source.kind === 'policy',
|
|
407
|
+
};
|
|
408
|
+
const secrets = Object.values(source.headers);
|
|
409
|
+
try {
|
|
410
|
+
const { cached } = await readSource(source, options.fresh === true, options.env ?? process.env);
|
|
411
|
+
lastLogged.delete(source.id);
|
|
412
|
+
// A user's catalog may name itself; the organization's label always wins.
|
|
413
|
+
const label = source.kind === 'user' && cached.label !== null ? cached.label : source.label;
|
|
414
|
+
return {
|
|
415
|
+
info: { ...base, label, status: 'ok', count: cached.registry.plugins.length, skipped: cached.skipped, ...(cached.offline ? { offline: true } : {}) },
|
|
416
|
+
registry: cached.registry,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
const reported = failure(error, secrets);
|
|
421
|
+
const line = `${reported.code}:${reported.detail}`;
|
|
422
|
+
if (lastLogged.get(source.id) !== line) {
|
|
423
|
+
lastLogged.set(source.id, line);
|
|
424
|
+
logEvent('warn', 'catalog', `catalog source "${source.id}" (${base.where}) could not be read — ${reported.code}${reported.detail === '' ? '' : `: ${reported.detail}`}`);
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
info: { ...base, label: source.label, status: 'failed', count: 0, skipped: 0, error: reported },
|
|
428
|
+
registry: null,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
// ---------------------------------------------------------------------------
|
|
433
|
+
// Merging and filtering.
|
|
434
|
+
/** Whether the policy's `allow` list lets this entry be shown and installed. */
|
|
435
|
+
export function entryAllowed(entry, allow) {
|
|
436
|
+
if (allow === null)
|
|
437
|
+
return true;
|
|
438
|
+
const names = [entry.name, typeof entry.npm === 'string' ? entry.npm : ''].filter(name => name !== '');
|
|
439
|
+
return allow.some(pattern => names.some(name => globMatch(pattern, name)));
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Combine the sources. Pure.
|
|
443
|
+
*
|
|
444
|
+
* - The same repository URL, or the same npm package, in two sources: the
|
|
445
|
+
* private one wins (earlier private sources before later ones). One plugin
|
|
446
|
+
* must not appear as two cards because two catalogs both list it.
|
|
447
|
+
* - Private entries come first: they are why the organization set this up.
|
|
448
|
+
* - Categories merge; a category id a private entry uses that nothing
|
|
449
|
+
* describes shows under its own id.
|
|
450
|
+
* - `source` is stamped here on every private entry, and removed from public
|
|
451
|
+
* ones, so a catalog cannot pass itself off as another source.
|
|
452
|
+
* - `allow` filters the union; `pins` fix the version an entry shows and installs.
|
|
453
|
+
*/
|
|
454
|
+
export function mergeSources(input) {
|
|
455
|
+
const taken = new Set();
|
|
456
|
+
const takenNpm = new Set();
|
|
457
|
+
const merged = [];
|
|
458
|
+
const categories = {};
|
|
459
|
+
const infos = [];
|
|
460
|
+
if (input.publicInfo !== null)
|
|
461
|
+
infos.push(input.publicInfo);
|
|
462
|
+
for (const { info, registry } of input.extras) {
|
|
463
|
+
infos.push(info);
|
|
464
|
+
if (registry === null)
|
|
465
|
+
continue;
|
|
466
|
+
for (const plugin of registry.plugins) {
|
|
467
|
+
const key = plugin.url.toLowerCase();
|
|
468
|
+
const npm = typeof plugin.npm === 'string' ? plugin.npm.toLowerCase() : '';
|
|
469
|
+
if (taken.has(key) || (npm !== '' && takenNpm.has(npm)))
|
|
470
|
+
continue;
|
|
471
|
+
taken.add(key);
|
|
472
|
+
if (npm !== '')
|
|
473
|
+
takenNpm.add(npm);
|
|
474
|
+
merged.push({ ...plugin, source: { id: info.id, label: info.label } });
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const publicPlugins = (input.publicRegistry?.plugins ?? []).flatMap(plugin => {
|
|
478
|
+
if (taken.has(plugin.url.toLowerCase()))
|
|
479
|
+
return [];
|
|
480
|
+
if (typeof plugin.npm === 'string' && takenNpm.has(plugin.npm.toLowerCase()))
|
|
481
|
+
return [];
|
|
482
|
+
if (plugin.source === undefined)
|
|
483
|
+
return [plugin];
|
|
484
|
+
const { source: _stray, ...rest } = plugin;
|
|
485
|
+
return [rest];
|
|
486
|
+
});
|
|
487
|
+
Object.assign(categories, input.publicRegistry?.categories ?? {});
|
|
488
|
+
for (const { registry } of input.extras) {
|
|
489
|
+
for (const [id, label] of Object.entries(registry?.categories ?? {}))
|
|
490
|
+
categories[id] ??= label;
|
|
491
|
+
}
|
|
492
|
+
const pins = input.pins ?? {};
|
|
493
|
+
const plugins = [...merged, ...publicPlugins].filter(plugin => entryAllowed(plugin, input.allow)).map(plugin => {
|
|
494
|
+
const pin = typeof plugin.npm === 'string' && Object.keys(pins).length > 0 ? pinnedVersion(plugin.npm, { pins }) : undefined;
|
|
495
|
+
// A pinned entry shows the pinned version, and says why.
|
|
496
|
+
return pin === undefined ? plugin : { ...plugin, version: pin, pinned: pin };
|
|
497
|
+
});
|
|
498
|
+
for (const plugin of plugins) {
|
|
499
|
+
const ids = Array.isArray(plugin.category) ? plugin.category : [plugin.category];
|
|
500
|
+
for (const id of ids)
|
|
501
|
+
categories[id] ??= { zh: id, en: id };
|
|
502
|
+
}
|
|
503
|
+
const extraDigest = digestOf(JSON.stringify(input.extras.map(({ info, registry }) => [info.id, registry?.plugins ?? null])));
|
|
504
|
+
const updated = input.publicRegistry === null
|
|
505
|
+
? `private-${extraDigest}`
|
|
506
|
+
: input.extras.some(({ registry }) => registry !== null) ? `${input.publicRegistry.updated}+${extraDigest}` : input.publicRegistry.updated;
|
|
507
|
+
return { updated, count: plugins.length, categories, plugins, sources: infos };
|
|
508
|
+
}
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
// The user's own "add a catalog".
|
|
511
|
+
/** What a person typed into the add box, as a source, or why not. */
|
|
512
|
+
export function parseCatalogInput(text) {
|
|
513
|
+
const value = text.trim();
|
|
514
|
+
if (value === '')
|
|
515
|
+
return { error: 'empty' };
|
|
516
|
+
if (/^https?:\/\//iu.test(value)) {
|
|
517
|
+
try {
|
|
518
|
+
const url = new URL(value);
|
|
519
|
+
if (url.username !== '' || url.password !== '')
|
|
520
|
+
return { error: 'credentials' };
|
|
521
|
+
return { url: url.href };
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
return { error: 'unrecognized' };
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (/^file:\/\//iu.test(value)) {
|
|
528
|
+
try {
|
|
529
|
+
return { file: fileURLToPath(value) };
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return { error: 'unrecognized' };
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
const expanded = expandHomePath(value);
|
|
536
|
+
if (isAbsolute(expanded))
|
|
537
|
+
return { file: expanded };
|
|
538
|
+
return { error: 'unrecognized' };
|
|
539
|
+
}
|
|
540
|
+
/** A stable id for a user catalog, so adding the same thing twice is one entry. */
|
|
541
|
+
export function userCatalogId(entry) {
|
|
542
|
+
return `user-${digestOf(entry.url ?? entry.file ?? '').slice(0, 8)}`;
|
|
543
|
+
}
|
|
544
|
+
/** Read a candidate once, for the add box: the count on success, the reason on failure. */
|
|
545
|
+
export async function probeCatalog(entry, env = process.env) {
|
|
546
|
+
const id = userCatalogId(entry);
|
|
547
|
+
return await loadExtra({
|
|
548
|
+
id, kind: 'user', label: fallbackLabel(entry), ...entry, headers: {},
|
|
549
|
+
}, { fresh: true, env });
|
|
550
|
+
}
|
|
551
|
+
/** The shape the id of a saved catalog must have; stored state is untrusted. */
|
|
552
|
+
export function validUserCatalog(value) {
|
|
553
|
+
if (value === null || typeof value !== 'object')
|
|
554
|
+
return null;
|
|
555
|
+
const raw = value;
|
|
556
|
+
const url = typeof raw.url === 'string' ? parseCatalogInput(raw.url) : null;
|
|
557
|
+
const file = typeof raw.file === 'string' && isAbsolute(raw.file) ? raw.file : null;
|
|
558
|
+
if ((url === null) === (file === null))
|
|
559
|
+
return null;
|
|
560
|
+
const where = url !== null ? ('url' in url ? { url: url.url } : null) : { file: file };
|
|
561
|
+
if (where === null)
|
|
562
|
+
return null;
|
|
563
|
+
const id = userCatalogId(where);
|
|
564
|
+
if (!CATALOG_ID_RE.test(id) || id === PUBLIC_SOURCE_ID)
|
|
565
|
+
return null;
|
|
566
|
+
return { id, ...where };
|
|
567
|
+
}
|
package/lib/changelog.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import { absoluteTarballUrl, fileFromTarball } from './catalog-npm.js';
|
|
24
24
|
import { marketFetch } from './net.js';
|
|
25
|
+
import { registryFor } from './npmrc.js';
|
|
25
26
|
import { activeRegion, routesFor } from './regions.js';
|
|
26
27
|
import { profileDir, readGitResolutionCommit, readInstalled, readInstalledRepoEvidence, readInstalledVersion, readLockCommits } from './profile.js';
|
|
27
28
|
import { githubRepoOfRemote, hostedRepoKey, isGitHostedSpec, lookupRepoFromUrl, parseHostShorthand, parseSourceUrl, repoOf, repoOfTarget } from './sources.js';
|
|
@@ -269,7 +270,7 @@ export async function npmPublishTimes(name) {
|
|
|
269
270
|
const hit = timesCache.get(name);
|
|
270
271
|
if (hit !== undefined && Date.now() - hit.at < TIMES_TTL_MS)
|
|
271
272
|
return hit.data;
|
|
272
|
-
const registry = routesFor(activeRegion()).npmRegistry;
|
|
273
|
+
const registry = registryFor(name, routesFor(activeRegion()).npmRegistry);
|
|
273
274
|
const res = await marketFetch(`${registry}/${encodeURIComponent(name)}`, {
|
|
274
275
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
275
276
|
headers: { accept: 'application/json', 'user-agent': 'dsh-market' },
|
|
@@ -13,6 +13,7 @@ import { compareSemver, isSemver, satisfiesRange } from './check.js';
|
|
|
13
13
|
import { classifyPeer, crossesImplicitCeiling } from './compatibility.js';
|
|
14
14
|
import { openDiscoveryCache } from './discovery-cache.js';
|
|
15
15
|
import { marketFetch } from './net.js';
|
|
16
|
+
import { registryFor } from './npmrc.js';
|
|
16
17
|
import { isStableReleaseVersion } from './release-candidates.js';
|
|
17
18
|
import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
|
|
18
19
|
import { parseSourceUrl } from './sources.js';
|
|
@@ -391,7 +392,7 @@ export class DiscoveryManifestIndex {
|
|
|
391
392
|
return await request;
|
|
392
393
|
}
|
|
393
394
|
async readNpmManifest(name, version, registry) {
|
|
394
|
-
const response = await this.fetcher(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
|
|
395
|
+
const response = await this.fetcher(`${registryFor(name, registry)}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
|
|
395
396
|
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
396
397
|
headers: { accept: 'application/json', 'user-agent': 'dsh-market' },
|
|
397
398
|
});
|
|
@@ -502,7 +503,7 @@ export class DiscoveryManifestIndex {
|
|
|
502
503
|
export async function findCompatibleVersion(npmName, hostVersion, hostPackages, registry, fetcher = marketFetch, minimumVersionExclusive = null, stableOnly = false) {
|
|
503
504
|
let doc;
|
|
504
505
|
try {
|
|
505
|
-
const res = await fetcher(`${registry}/${encodeURIComponent(npmName)}`, { signal: AbortSignal.timeout(15_000), headers: { accept: 'application/json', 'user-agent': 'dsh-market' } });
|
|
506
|
+
const res = await fetcher(`${registryFor(npmName, registry)}/${encodeURIComponent(npmName)}`, { signal: AbortSignal.timeout(15_000), headers: { accept: 'application/json', 'user-agent': 'dsh-market' } });
|
|
506
507
|
if (!res.ok)
|
|
507
508
|
return null;
|
|
508
509
|
doc = await res.json();
|