@unieai/rabi-plugin-market 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,12 +1,270 @@
1
+ import { isAbsolute, join, posix, resolve } from "node:path";
1
2
  import z from "@unieai/schemastery";
2
3
  import semver from "semver";
3
4
  import { evaluatePluginCompatibility, getRabiRuntimeVersion } from "@unieai/rabi-app-boot";
4
5
  import { marketInstallTarget } from "@unieai/rabi-plugin-market-index";
6
+ import { pinnedGitOrigin } from "@unieai/rabi-plugin-manager";
5
7
  import { MAX_TIMER_DELAY_MS } from "@unieai/rabi-timeout";
6
8
  import { Remote, RemoteError, TypertRemoteService } from "@unieai/rabi-typert-protocol";
9
+ import { DetailFailure, NPM_FILE_SOURCES, README_NAMES, detailImage, detailImageResponse, encodePath, fetchBody, joinPath, languageChain, markdownOf, npmFileSourceOrder, npmFiles, readPackageDocument, readmeByName, readmeName } from "@unieai/rabi-plugin-detail";
10
+ import { createHash } from "node:crypto";
11
+ import { brandString } from "@unieai/rabi-brand";
12
+ import hostedGitInfo from "hosted-git-info";
13
+ import { existsSync } from "node:fs";
14
+ import { mkdir, mkdtemp, readdir, rename, rm, stat, utimes } from "node:fs/promises";
15
+ import { execa } from "execa";
16
+ import { withFileLock } from "@unieai/rabi-atomic-write";
17
+ import { scrubbedParentEnv } from "@unieai/rabi-subprocess";
7
18
  import { Worker } from "node:worker_threads";
8
19
  import MiniSearch from "minisearch";
9
20
  import { assertNever } from "@unieai/rabi-util-values";
21
+ //#region lib/types/detail-files.js
22
+ /**
23
+ * Git repository files for plugin detail documents, through GitHub or GitLab single-file APIs with a cached partial
24
+ * clone as the fallback for repositories those APIs cannot serve anonymously.
25
+ */
26
+ function apiUrl(api, repository, ref, path) {
27
+ return api === "github" ? `https://raw.githubusercontent.com/${repository.project}/${encodeURIComponent(ref)}/${encodePath(path)}` : `${new URL(repository.url).origin}/api/v4/projects/${encodeURIComponent(repository.project)}/repository/files/${encodeURIComponent(path)}/raw?ref=${encodeURIComponent(ref)}`;
28
+ }
29
+ /**
30
+ * Files of one repository at a commit, or at its default branch. Hosts with a single-file API are read through it; a
31
+ * missing answer is confirmed with an anonymous request to the repository's smart HTTP endpoint, and a repository that
32
+ * needs credentials, or a host without such an API, is read from the cached partial clone.
33
+ * @param repository - the repository.
34
+ * @param commit - a full commit id, or undefined for the default branch.
35
+ * @param options - API hosts, deadline, lifetime, and the clone cache.
36
+ * @returns the files.
37
+ */
38
+ function repositoryFiles(repository, commit, options) {
39
+ const api = repository.host === "github.com" ? "github" : options.gitlabHosts.includes(repository.host) ? "gitlab" : void 0;
40
+ const ref = commit ?? "HEAD";
41
+ /** An API read: the bytes, or undefined for an answer that does not distinguish a missing file from a private repository. */
42
+ const fromApi = async (path, maxBytes, signal, via) => {
43
+ const body = await fetchBody(apiUrl(via, repository, ref, path), maxBytes, signal, options);
44
+ if (body.ok) return body.bytes;
45
+ if (body.status !== 404 && body.status !== 401 && body.status !== 403) throw new DetailFailure("network", `${repository.url}: ${path} answered HTTP ${String(body.status)}`);
46
+ };
47
+ return {
48
+ key: `git:${repository.url}#${ref}`,
49
+ async read(path, maxBytes, signal) {
50
+ if (api !== void 0) {
51
+ const bytes = await fromApi(path, maxBytes, signal, api);
52
+ if (bytes !== void 0 || await options.cache.isPublic(repository.url)) return bytes;
53
+ }
54
+ return await options.cache.read(repository.url, commit, path, maxBytes, signal);
55
+ },
56
+ async readme(dir, maxBytes, signal) {
57
+ if (api !== void 0) {
58
+ const read = (path, max, readSignal) => fromApi(path, max, readSignal, api);
59
+ const found = await readmeByName(read, dir, maxBytes, signal, README_NAMES.slice(0, 1));
60
+ if (found !== void 0) return found;
61
+ if (await options.cache.isPublic(repository.url)) return await readmeByName(read, dir, maxBytes, signal, README_NAMES.slice(1));
62
+ }
63
+ return await options.cache.readme(repository.url, commit, dir, maxBytes, signal);
64
+ }
65
+ };
66
+ }
67
+ //#endregion
68
+ //#region lib/types/detail.js
69
+ /**
70
+ * Plugin market entry detail documents: the package document {@link readPackageDocument} selects from the entry
71
+ * version's source, otherwise the README of the repository directory the entry or its package declares; cached reads
72
+ * and the images beside a read document.
73
+ */
74
+ /** Failures that reading again within `ttlMs` would repeat. */
75
+ const LASTING_FAILURES = new Set([
76
+ "too-large",
77
+ "denied",
78
+ "invalid"
79
+ ]);
80
+ /**
81
+ * The repository a URL or shorthand names: hosts npm knows by their owner and project, so a GitHub page such as
82
+ * `/o/r/tree/main/pkg` names `o/r`; other http(s) URLs by their path, without a GitLab `/-/` page suffix.
83
+ * @param url - a manifest `repository` URL or shorthand, or a market index's `repository.url`.
84
+ * @returns the repository, or undefined for a gist, another protocol, or fewer than two path segments.
85
+ */
86
+ function repositoryOf(url) {
87
+ const declared = url.replace(/#.*$/u, "");
88
+ const hosted = hostedGitInfo.fromUrl(declared);
89
+ if (hosted !== void 0) {
90
+ if (hosted.type === "gist") return void 0;
91
+ const project = `${hosted.user}/${hosted.project}`;
92
+ return {
93
+ host: hosted.domain.toLowerCase(),
94
+ project,
95
+ url: `https://${hosted.domain}/${project}.git`
96
+ };
97
+ }
98
+ const address = declared.replace(/^git\+/u, "");
99
+ if (!URL.canParse(address)) return void 0;
100
+ const parsed = new URL(address);
101
+ const project = parsed.pathname.replace(/\/-\/.*$/u, "").replace(/^\/+|\/+$/gu, "").replace(/\.git$/u, "");
102
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username !== "" || parsed.password !== "" || project.split("/").length < 2) return;
103
+ return {
104
+ host: parsed.hostname.toLowerCase(),
105
+ project,
106
+ url: `${parsed.protocol}//${parsed.host}/${project}.git`
107
+ };
108
+ }
109
+ /**
110
+ * Parse a manifest `repository` into the repository and directory its README is read from.
111
+ * @param value - a manifest `repository` string or object.
112
+ * @returns the location, or undefined when it names no repository {@link repositoryOf} accepts; a `directory` that
113
+ * leaves the repository is dropped.
114
+ */
115
+ function manifestRepository(value) {
116
+ const object = typeof value === "object" && value !== null ? value : void 0;
117
+ const declared = object === void 0 ? value : object.url;
118
+ if (typeof declared !== "string") return void 0;
119
+ const repository = repositoryOf(declared);
120
+ if (repository === void 0) return void 0;
121
+ return {
122
+ ...repository,
123
+ directory: typeof object?.directory === "string" ? normalizedDirectory(object.directory) ?? "" : ""
124
+ };
125
+ }
126
+ /** A `/`-separated directory without empty, `.`, or `..` segments; undefined for one that leaves its root. */
127
+ function normalizedDirectory(directory) {
128
+ const normalized = posix.normalize(directory.replace(/\\/gu, "/")).replace(/\/+$/u, "");
129
+ if (normalized === "." || normalized === "") return "";
130
+ return normalized === ".." || normalized.startsWith("../") || posix.isAbsolute(normalized) ? void 0 : normalized;
131
+ }
132
+ /** Reads and caches detail documents for one service. */
133
+ var DetailReader = class {
134
+ limits;
135
+ repositories;
136
+ results = /* @__PURE__ */ new Map();
137
+ pending = /* @__PURE__ */ new Map();
138
+ documents = /* @__PURE__ */ new Map();
139
+ /**
140
+ * @param limits - document and image sizes and the result lifetime.
141
+ * @param repositories - single-file API, clone, and request settings of repository reads.
142
+ */
143
+ constructor(limits, repositories) {
144
+ this.limits = limits;
145
+ this.repositories = repositories;
146
+ }
147
+ /**
148
+ * Read a package's detail document, sharing concurrent reads and reusing a result, or a failure that reading again
149
+ * would repeat, for `ttlMs`.
150
+ * @param location - the package's sources.
151
+ * @param languages - the chain from `languageChain` of `rabi-plugin-detail`.
152
+ * @param refresh - read again instead of reusing a cached result.
153
+ * @returns the first document the sources provide, or `none`.
154
+ * @throws {DetailFailure} when a source that should provide a document cannot be read.
155
+ */
156
+ read(location, languages, refresh = false) {
157
+ const { repository } = location;
158
+ const repositoryKey = typeof repository === "string" ? repository : repository === void 0 ? "" : `${repository.url}:${repository.directory}`;
159
+ const key = JSON.stringify([
160
+ location.files?.key ?? "",
161
+ location.dir,
162
+ repositoryKey,
163
+ languages
164
+ ]);
165
+ const now = Date.now();
166
+ const cached = this.results.get(key);
167
+ if (!refresh && cached !== void 0 && cached.expiresAt > now) {
168
+ if ("failure" in cached) return Promise.reject(cached.failure);
169
+ if (cached.value.status === "found") this.use(cached.value.document);
170
+ return Promise.resolve(cached.value);
171
+ }
172
+ let pending = this.pending.get(key);
173
+ if (pending === void 0) {
174
+ pending = this.resolve(location, languages, this.repositories.lifetime).then((value) => {
175
+ this.remember(key, {
176
+ value,
177
+ expiresAt: Date.now() + this.limits.ttlMs
178
+ });
179
+ return value;
180
+ }, (error) => {
181
+ if (error instanceof DetailFailure && LASTING_FAILURES.has(error.reason)) this.remember(key, {
182
+ failure: error,
183
+ expiresAt: Date.now() + this.limits.ttlMs
184
+ });
185
+ throw error;
186
+ }).finally(() => {
187
+ this.pending.delete(key);
188
+ });
189
+ this.pending.set(key, pending);
190
+ }
191
+ return pending;
192
+ }
193
+ /**
194
+ * Read an image beside a document.
195
+ * @param id - the document id a detail read returned.
196
+ * @param authored - the image destination as the document writes it: relative to the document, or to the package or
197
+ * repository root when it starts with `/`; a query or fragment is ignored.
198
+ * @returns the bytes and media type, or undefined for an unknown document, a path outside its root, an unsupported
199
+ * image type, or a missing file.
200
+ * @throws {DetailFailure} when the source fails or the image exceeds `maxImageBytes`.
201
+ */
202
+ async image(id, authored) {
203
+ const document = this.use(brandString(id));
204
+ const image = document === void 0 ? void 0 : detailImage(document.path, authored);
205
+ if (document === void 0 || image === void 0) return void 0;
206
+ const bytes = await document.files.read(image.path, this.limits.maxImageBytes, this.repositories.lifetime);
207
+ return bytes === void 0 ? void 0 : {
208
+ bytes,
209
+ mediaType: image.mediaType
210
+ };
211
+ }
212
+ /**
213
+ * Mark a document used and forget documents unused for `ttlMs`, so ids live as long as a read or an image request
214
+ * returns them. A cached read is younger than `ttlMs` and marks its document, so no cached read names a forgotten id.
215
+ */
216
+ use(id) {
217
+ const now = Date.now();
218
+ for (const [known, document] of this.documents) if (now - document.usedAt > this.limits.ttlMs) this.documents.delete(known);
219
+ const document = this.documents.get(id);
220
+ if (document !== void 0) document.usedAt = now;
221
+ return document;
222
+ }
223
+ /** Cache a read and drop expired ones, so the cache holds only reads younger than `ttlMs`. */
224
+ remember(key, read) {
225
+ const now = Date.now();
226
+ for (const [cachedKey, cached] of this.results) if (cached.expiresAt <= now) this.results.delete(cachedKey);
227
+ this.results.set(key, read);
228
+ }
229
+ async resolve(location, languages, signal) {
230
+ const { files, dir } = location;
231
+ let repository = location.repository === "manifest" ? void 0 : location.repository;
232
+ if (files !== void 0) {
233
+ const document = await readPackageDocument(files, dir, languages, this.limits.maxDocumentBytes, signal);
234
+ if (document !== void 0) return this.found(document.origin, files, document.path, document.markdown);
235
+ if (location.repository === "manifest") repository = await this.manifestRepositoryOf(files, dir, signal);
236
+ }
237
+ if (repository === void 0) return { status: "none" };
238
+ const source = repositoryFiles(repository, void 0, this.repositories);
239
+ const readme = await source.readme(repository.directory, this.limits.maxDocumentBytes, signal);
240
+ return readme === void 0 ? { status: "none" } : this.found("repository", source, readme.path, markdownOf(readme.bytes));
241
+ }
242
+ async manifestRepositoryOf(files, dir, signal) {
243
+ const bytes = await files.read(joinPath(dir, "package.json"), this.limits.maxDocumentBytes, signal);
244
+ if (bytes === void 0) return void 0;
245
+ try {
246
+ return manifestRepository(JSON.parse(new TextDecoder().decode(bytes))?.repository);
247
+ } catch (_malformed) {
248
+ return;
249
+ }
250
+ }
251
+ found(origin, files, path, markdown) {
252
+ const document = brandString(createHash("sha256").update(`${files.key}\0${path}`).digest("hex").slice(0, 32));
253
+ this.documents.set(document, {
254
+ files,
255
+ path,
256
+ usedAt: Date.now()
257
+ });
258
+ this.use(document);
259
+ return {
260
+ status: "found",
261
+ origin,
262
+ markdown,
263
+ document
264
+ };
265
+ }
266
+ };
267
+ //#endregion
10
268
  //#region lib/types/index-url.js
11
269
  /** Index source URL validation shared by `setIndexes` and the per-use check of configured sources. */
12
270
  /**
@@ -37,6 +295,458 @@ function normalizeIndexUrl(text) {
37
295
  return url.href;
38
296
  }
39
297
  //#endregion
298
+ //#region lib/types/repository-cache.js
299
+ /**
300
+ * Cached partial clones for plugin detail documents of repositories that need the user's Git credentials or have no
301
+ * anonymous single-file API. Each repository is a bare repository fetched with depth 1 and without file contents; Git
302
+ * downloads a file's contents only when it is read. No working tree is created, so no checkout filter, hook, LFS
303
+ * download, or symbolic link takes effect. A repository whose operation fails or is cancelled is deleted, so an
304
+ * interrupted command never leaves a damaged clone behind.
305
+ */
306
+ /**
307
+ * Git deadlines one operation's lock waits for: an operation runs at most a fetch, its SSH retry, and a file read that
308
+ * contact the remote, each bounded by the deadline, plus short local commands.
309
+ */
310
+ const OPERATION_COMMANDS = 5;
311
+ /** Output that names a connection failure or a timeout rather than a refusal by the server. */
312
+ const NETWORK_FAILURE = new RegExp([
313
+ "Could not resolve host",
314
+ "Failed to connect",
315
+ "Connection (?:refused|reset)",
316
+ "timed out",
317
+ "Network is unreachable",
318
+ "SSL",
319
+ "TLS"
320
+ ].join("|"), "iu");
321
+ /** A file over the size its read accepts; the clone itself stays usable. */
322
+ var FileTooLarge = class extends DetailFailure {
323
+ /** @param path - the file. @param maxBytes - the accepted size. */
324
+ constructor(path, maxBytes) {
325
+ super("too-large", `${path} exceeds ${String(maxBytes)} bytes`);
326
+ }
327
+ };
328
+ /** The failure of a Git command that contacts the remote: `network` for a timeout or a connection failure, otherwise `denied`. */
329
+ function remoteFailureOf(result, label) {
330
+ return new DetailFailure(NETWORK_FAILURE.test(result.diagnostic) ? "network" : "denied", `${label}: ${result.diagnostic}`);
331
+ }
332
+ /**
333
+ * The SSH form of an http(s) repository URL: `ssh://git@<host>/<path>` on SSH's default port, the form that
334
+ * `sshGitSpec` in `@unieai/rabi-plugin-manager` gives installation.
335
+ * @returns undefined for another scheme, or a URL with credentials or a query.
336
+ */
337
+ function sshUrlOf(url) {
338
+ if (!/^https?:/iu.test(url)) return void 0;
339
+ const parsed = new URL(url);
340
+ if (parsed.username !== "" || parsed.password !== "" || parsed.search !== "") return void 0;
341
+ return `ssh://git@${parsed.hostname}${parsed.pathname}`;
342
+ }
343
+ async function sizeOf(path) {
344
+ let total = 0;
345
+ for (const entry of await readdir(path, {
346
+ withFileTypes: true,
347
+ recursive: true
348
+ })) if (entry.isFile()) total += (await stat(join(entry.parentPath, entry.name))).size;
349
+ return total;
350
+ }
351
+ /** Staging directories that an initialization in progress owns; an older one was left by a stopped process. */
352
+ const STAGING_PREFIX = ".init-";
353
+ /**
354
+ * The environment of every Git command: the scrubbed parent environment without Git overrides such as `GIT_DIR`, which a
355
+ * hook that launched RABI can leave, and without prompts or LFS downloads.
356
+ */
357
+ function gitEnv() {
358
+ const env = Object.fromEntries(Object.entries(scrubbedParentEnv()).filter(([name]) => !name.startsWith("GIT_") || name === "GIT_SSH" || name === "GIT_SSH_COMMAND"));
359
+ const ssh = env.GIT_SSH === void 0 && env.GIT_SSH_COMMAND === void 0 ? { GIT_SSH_COMMAND: "ssh -o BatchMode=yes" } : {};
360
+ return {
361
+ ...env,
362
+ ...ssh,
363
+ LC_ALL: "C",
364
+ GIT_TERMINAL_PROMPT: "0",
365
+ GIT_ASKPASS: "",
366
+ SSH_ASKPASS: "",
367
+ SSH_ASKPASS_REQUIRE: "never",
368
+ GCM_INTERACTIVE: "never",
369
+ GIT_LFS_SKIP_SMUDGE: "1",
370
+ GIT_LITERAL_PATHSPECS: "1"
371
+ };
372
+ }
373
+ /** Partial clones of detail repositories under one directory, owned by one service. */
374
+ var RepositoryCache = class {
375
+ options;
376
+ locks = /* @__PURE__ */ new Map();
377
+ heads = /* @__PURE__ */ new Map();
378
+ /**
379
+ * Whether `git --version` has succeeded. A missing Git is checked this way before any operation, because Windows
380
+ * reports a missing command as an ordinary exit code that would otherwise read as a refused fetch.
381
+ */
382
+ gitStarts = false;
383
+ visibility = /* @__PURE__ */ new Map();
384
+ checks = /* @__PURE__ */ new Map();
385
+ running = /* @__PURE__ */ new Set();
386
+ /** @param options - location, limits, deadline, transports, and lifetime. */
387
+ constructor(options) {
388
+ this.options = options;
389
+ }
390
+ /**
391
+ * Whether a repository's smart HTTP endpoint answers without credentials, which makes a missing single-file API answer
392
+ * authoritative. The request carries no user configuration, credential helper, or `.netrc` entry; concurrent checks of
393
+ * one repository share it, and its answer is reused for `ttlMs`.
394
+ * @param url - the repository's https URL, ending in `.git`.
395
+ * @returns true for a 2xx answer; false for 401, 403, 404, or a redirect, which hosts send for a private repository.
396
+ * @throws {DetailFailure} `network` when the host cannot be reached or answers another status.
397
+ */
398
+ isPublic(url) {
399
+ const cached = this.visibility.get(url);
400
+ if (cached !== void 0 && cached.expiresAt > Date.now()) return Promise.resolve(cached.value);
401
+ let pending = this.checks.get(url);
402
+ if (pending === void 0) {
403
+ pending = this.check(url).finally(() => {
404
+ this.checks.delete(url);
405
+ });
406
+ this.checks.set(url, pending);
407
+ }
408
+ return pending;
409
+ }
410
+ async check(url) {
411
+ const endpoint = `${url}/info/refs?service=git-upload-pack`;
412
+ let response;
413
+ try {
414
+ response = await fetch(endpoint, {
415
+ redirect: "manual",
416
+ signal: AbortSignal.any([this.options.lifetime, AbortSignal.timeout(this.options.timeoutMs)])
417
+ });
418
+ } catch (error) {
419
+ throw new DetailFailure("network", `Could not reach ${endpoint}: ${error.message}`, { cause: error });
420
+ }
421
+ await response.body?.cancel();
422
+ const { status } = response;
423
+ if (!response.ok && status !== 401 && status !== 403 && status !== 404 && (status < 300 || status > 399)) throw new DetailFailure("network", `${endpoint} answered HTTP ${String(status)}`);
424
+ this.visibility.set(url, {
425
+ value: response.ok,
426
+ expiresAt: Date.now() + this.options.ttlMs
427
+ });
428
+ return response.ok;
429
+ }
430
+ /**
431
+ * Read one regular file of a repository.
432
+ * @param url - the repository URL.
433
+ * @param commit - a full commit id, or undefined for the default branch.
434
+ * @param path - `/`-separated path relative to the repository root.
435
+ * @param maxBytes - largest accepted size.
436
+ * @param signal - cancellation of the read.
437
+ * @returns the bytes, or undefined when the commit has no regular file at `path`.
438
+ * @throws {DetailFailure} when Git cannot fetch the commit, the repository grows past its limit, or the file exceeds `maxBytes`.
439
+ */
440
+ read(url, commit, path, maxBytes, signal) {
441
+ return this.locked(url, async (repository) => {
442
+ const resolved = await this.commit(repository, url, commit, signal);
443
+ const blob = (await this.files(repository, resolved, path, signal)).get(path);
444
+ return blob === void 0 ? void 0 : await this.blob(repository, url, blob, path, maxBytes, signal);
445
+ });
446
+ }
447
+ /**
448
+ * Read the README of a repository directory: `README.md`, `README.markdown`, or `README` in any letter case.
449
+ * @param url - the repository URL.
450
+ * @param commit - a full commit id, or undefined for the default branch.
451
+ * @param dir - directory relative to the repository root; `''` for the root.
452
+ * @param maxBytes - largest accepted size.
453
+ * @param signal - cancellation of the read.
454
+ * @returns the file, or undefined when the directory has none.
455
+ * @throws {DetailFailure} as {@link read} does.
456
+ */
457
+ readme(url, commit, dir, maxBytes, signal) {
458
+ return this.locked(url, async (repository) => {
459
+ const resolved = await this.commit(repository, url, commit, signal);
460
+ const files = await this.files(repository, resolved, dir === "" ? void 0 : `${dir}/`, signal);
461
+ const prefix = dir === "" ? "" : `${dir}/`;
462
+ const name = readmeName([...files.keys()].map((path) => path.slice(prefix.length)));
463
+ if (name === void 0) return void 0;
464
+ const path = `${prefix}${name}`;
465
+ return {
466
+ path,
467
+ bytes: await this.blob(repository, url, files.get(path), path, maxBytes, signal)
468
+ };
469
+ });
470
+ }
471
+ /** Wait until every running Git command has ended; the lifetime signal stops them. */
472
+ async settled() {
473
+ await Promise.allSettled([...this.running]);
474
+ }
475
+ /**
476
+ * Serialize operations on one repository, so a fetch and the reads after it never interleave, and delete the
477
+ * repository when an operation fails or is cancelled for any reason but a file over its read's size.
478
+ */
479
+ locked(url, operation) {
480
+ const repository = join(this.options.dir, createHash("sha256").update(url).digest("hex").slice(0, 24));
481
+ return this.serialized(repository, () => operation(repository).catch(async (error) => {
482
+ if (!(error instanceof FileTooLarge)) await rm(repository, {
483
+ recursive: true,
484
+ force: true
485
+ });
486
+ throw error;
487
+ }));
488
+ }
489
+ /**
490
+ * Run an operation after every earlier operation on the same repository directory has ended, in this service and in
491
+ * other processes that share the cache directory, such as Web and Desktop on one profile.
492
+ */
493
+ serialized(repository, operation) {
494
+ const next = (this.locks.get(repository) ?? Promise.resolve()).then(async () => {
495
+ await mkdir(this.options.dir, { recursive: true });
496
+ return await withFileLock(repository, operation, {
497
+ waitMs: OPERATION_COMMANDS * this.options.timeoutMs,
498
+ signal: this.options.lifetime
499
+ });
500
+ });
501
+ const tracked = next.then(() => void 0, () => void 0).finally(() => {
502
+ if (this.locks.get(repository) === tracked) this.locks.delete(repository);
503
+ this.running.delete(tracked);
504
+ });
505
+ this.locks.set(repository, tracked);
506
+ this.running.add(tracked);
507
+ return next;
508
+ }
509
+ /** The commit to read: a fetched commit, fetching it or the default branch when necessary. */
510
+ async commit(repository, url, commit, signal) {
511
+ if (!this.gitStarts) {
512
+ await this.run(this.options.dir, ["--version"], signal, 1024).catch((error) => {
513
+ throw new DetailFailure("git-unavailable", error.message, { cause: error });
514
+ });
515
+ this.gitStarts = true;
516
+ }
517
+ if (!existsSync(repository)) {
518
+ const staging = await mkdtemp(join(this.options.dir, STAGING_PREFIX));
519
+ try {
520
+ await this.run(staging, [
521
+ "init",
522
+ "--quiet",
523
+ "--bare",
524
+ "--template="
525
+ ], signal);
526
+ for (const [key, value] of [
527
+ ["remote.origin.url", url],
528
+ ["remote.origin.promisor", "true"],
529
+ ["remote.origin.partialclonefilter", "blob:none"]
530
+ ]) await this.run(staging, [
531
+ "config",
532
+ key,
533
+ value
534
+ ], signal);
535
+ await rename(staging, repository);
536
+ } finally {
537
+ await rm(staging, {
538
+ recursive: true,
539
+ force: true
540
+ });
541
+ }
542
+ }
543
+ await utimes(repository, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
544
+ const head = this.heads.get(url);
545
+ const known = commit ?? (head !== void 0 && head.expiresAt > Date.now() ? head.value : void 0);
546
+ if (known !== void 0 && !(await this.git([
547
+ "show-ref",
548
+ "--verify",
549
+ "--quiet",
550
+ `refs/rabi/${known}`
551
+ ], repository, signal)).failed) return known;
552
+ await this.fetch(repository, commit ?? "HEAD", signal);
553
+ const fetched = commit ?? (await this.run(repository, ["rev-parse", "FETCH_HEAD"], signal)).toString("utf8").trim();
554
+ await this.run(repository, [
555
+ "update-ref",
556
+ `refs/rabi/${fetched}`,
557
+ fetched
558
+ ], signal);
559
+ if (commit === void 0) this.heads.set(url, {
560
+ value: fetched,
561
+ expiresAt: Date.now() + this.options.ttlMs
562
+ });
563
+ return fetched;
564
+ }
565
+ /**
566
+ * Fetch one commit without file contents. When Git refuses an http(s) URL, the clone's remote switches to the SSH form
567
+ * of that URL and the fetch runs again, so a user with only SSH credentials for the host can read it; later reads of
568
+ * the clone keep that remote. A failed SSH fetch reports both diagnostics, as `network` or `too-large` when it failed
569
+ * for that reason and as `denied` otherwise.
570
+ */
571
+ async fetch(repository, target, signal) {
572
+ const args = [
573
+ "fetch",
574
+ "--quiet",
575
+ "--depth",
576
+ "1",
577
+ "--filter=blob:none",
578
+ "--no-tags",
579
+ "origin",
580
+ target
581
+ ];
582
+ const remote = (await this.run(repository, ["config", "remote.origin.url"], signal, 64 * 1024)).toString("utf8").trim();
583
+ try {
584
+ await this.watched(repository, remote, args, signal, `${remote}: git fetch`);
585
+ } catch (error) {
586
+ const ssh = sshUrlOf(remote);
587
+ if (ssh === void 0 || !(error instanceof DetailFailure) || error.reason !== "denied") throw error;
588
+ await this.run(repository, [
589
+ "config",
590
+ "remote.origin.url",
591
+ ssh
592
+ ], signal);
593
+ await this.watched(repository, ssh, args, signal, `${ssh}: git fetch`).catch((sshError) => {
594
+ throw sshError instanceof DetailFailure && sshError.reason !== "too-large" ? new DetailFailure(sshError.reason === "network" ? "network" : "denied", `${error.message}\n${sshError.message}`, { cause: sshError }) : sshError;
595
+ });
596
+ }
597
+ await this.evict(repository);
598
+ }
599
+ /**
600
+ * Run a Git command that may download objects, stopping it when the repository grows past its limit during or by the
601
+ * command; the caller's lock then deletes the repository.
602
+ */
603
+ async watched(repository, url, args, signal, label, maxBuffer = this.options.maxRepositoryBytes) {
604
+ const limit = this.options.maxRepositoryBytes;
605
+ const before = await sizeOf(repository);
606
+ const oversized = new AbortController();
607
+ const timer = setInterval(() => {
608
+ sizeOf(repository).then(
609
+ (size) => {
610
+ if (size - before > limit) oversized.abort();
611
+ },
612
+ /* v8 ignore next -- Git renamed or
613
+ deleted a file during the walk, which no test can time; the next tick measures again */
614
+ (_racing) => {}
615
+ );
616
+ }, this.options.sizePollMs);
617
+ let result;
618
+ try {
619
+ result = await this.git(args, repository, signal, oversized.signal, maxBuffer);
620
+ } finally {
621
+ clearInterval(timer);
622
+ }
623
+ if (oversized.signal.aborted || !result.failed && await sizeOf(repository) - before > limit) throw new DetailFailure("too-large", `${url}: one fetch adds more than ${String(limit)} bytes`);
624
+ if (result.failed && !result.overflowed) throw remoteFailureOf(result, label);
625
+ return result;
626
+ }
627
+ /**
628
+ * Delete least recently used repositories until the cache fits, `kept` last, and staging directories older than the
629
+ * Git deadline. Each deletion is queued behind the operations on its repository and not awaited, because the caller
630
+ * holds the lock of `kept` and another repository's queued operation may be waiting to evict `kept`.
631
+ */
632
+ async evict(kept) {
633
+ const now = Date.now();
634
+ const entries = [];
635
+ for (const entry of await readdir(this.options.dir, { withFileTypes: true })) {
636
+ const path = join(this.options.dir, entry.name);
637
+ try {
638
+ const used = (await stat(path)).mtimeMs;
639
+ if (entry.name.startsWith(STAGING_PREFIX)) {
640
+ if (now - used > this.options.timeoutMs) await rm(path, {
641
+ recursive: true,
642
+ force: true
643
+ });
644
+ } else if (entry.isDirectory()) entries.push({
645
+ path,
646
+ size: await sizeOf(path),
647
+ used
648
+ });
649
+ } catch (_removed) {}
650
+ }
651
+ let total = entries.reduce((sum, entry) => sum + entry.size, 0);
652
+ for (const entry of entries.sort((a, b) => Number(a.path === kept) - Number(b.path === kept) || a.used - b.used)) {
653
+ if (total <= this.options.maxCacheBytes) return;
654
+ this.serialized(entry.path, () => rm(entry.path, {
655
+ recursive: true,
656
+ force: true
657
+ })).catch(
658
+ /* v8 ignore next -- a
659
+ forced recursive delete fails only on file permissions no test sets; the repository stays and is measured again
660
+ after the next fetch */
661
+ (_unremovable) => {}
662
+ );
663
+ total -= entry.size;
664
+ }
665
+ }
666
+ /**
667
+ * The regular files directly below a tree path, or the file at a path, with their blob ids; listing reads only trees,
668
+ * so it fetches no file contents.
669
+ */
670
+ async files(repository, commit, path, signal) {
671
+ const listing = (await this.run(repository, [
672
+ "ls-tree",
673
+ "-z",
674
+ commit,
675
+ ...path === void 0 ? [] : ["--", path]
676
+ ], signal)).toString("utf8");
677
+ const files = /* @__PURE__ */ new Map();
678
+ for (const line of listing.split("\0")) {
679
+ const fields = /^100(?:644|755) blob ([0-9a-f]+)\t(.+)$/su.exec(line);
680
+ if (fields !== null) files.set(fields[2], fields[1]);
681
+ }
682
+ return files;
683
+ }
684
+ /** Read a blob, fetching its contents under the repository size limit when the clone does not hold them yet. */
685
+ async blob(repository, url, blob, path, maxBytes, signal) {
686
+ const result = await this.watched(repository, url, [
687
+ "cat-file",
688
+ "blob",
689
+ blob
690
+ ], signal, `git cat-file ${path}`, maxBytes);
691
+ if (result.overflowed) throw new FileTooLarge(path, maxBytes);
692
+ await this.evict(repository);
693
+ return result.stdout;
694
+ }
695
+ /**
696
+ * Run a Git command on local objects and return its output. A failure, such as a missing Git, a full disk, or a timeout,
697
+ * is a plain error: it says nothing about the repository, so no read caches it.
698
+ */
699
+ async run(repository, args, signal, maxBuffer) {
700
+ const result = await this.git(args, repository, signal, void 0, maxBuffer);
701
+ if (result.failed) throw new Error(`git ${args[0]}: ${result.diagnostic}`);
702
+ return result.stdout;
703
+ }
704
+ /**
705
+ * Run Git with options that keep it from running repository-supplied programs and allow only the configured transports.
706
+ * Cancellation by `signal` or the lifetime rejects with its reason; `stop` ends Git with a failed result.
707
+ */
708
+ async git(args, cwd, signal, stop, maxBuffer = this.options.maxRepositoryBytes) {
709
+ const result = await execa("git", [...[
710
+ "core.askPass=",
711
+ "core.hooksPath=/dev/null",
712
+ "core.fsmonitor=false",
713
+ "submodule.recurse=false",
714
+ "gc.auto=0",
715
+ "maintenance.auto=false",
716
+ "protocol.allow=never",
717
+ ...this.options.transports.map((transport) => `protocol.${transport}.allow=always`)
718
+ ].flatMap((setting) => ["-c", setting]), ...args], {
719
+ cwd,
720
+ env: gitEnv(),
721
+ extendEnv: false,
722
+ stdin: "ignore",
723
+ encoding: "buffer",
724
+ stripFinalNewline: false,
725
+ reject: false,
726
+ maxBuffer: {
727
+ stdout: maxBuffer,
728
+ stderr: this.options.maxRepositoryBytes
729
+ },
730
+ timeout: this.options.timeoutMs,
731
+ cancelSignal: AbortSignal.any([
732
+ signal,
733
+ this.options.lifetime,
734
+ ...stop === void 0 ? [] : [stop]
735
+ ]),
736
+ killDescendants: true,
737
+ killSignal: "SIGKILL"
738
+ });
739
+ signal.throwIfAborted();
740
+ this.options.lifetime.throwIfAborted();
741
+ return {
742
+ stdout: Buffer.from(result.stdout),
743
+ failed: result.failed,
744
+ overflowed: result.isMaxBuffer && result.stdout.byteLength >= maxBuffer,
745
+ diagnostic: `${String(result.shortMessage)}\n${Buffer.from(result.stderr).toString("utf8").trim()}`
746
+ };
747
+ }
748
+ };
749
+ //#endregion
40
750
  //#region lib/types/parse-thread.js
41
751
  /** Runs index parsing in a fresh Worker Thread, so a large index does not block the Host event loop. */
42
752
  function workerSpawn() {
@@ -304,6 +1014,10 @@ const MAX_CAUSES = 4;
304
1014
  function causeChainOf(error, depth = 0) {
305
1015
  return error instanceof Error && error.cause !== void 0 && depth < MAX_CAUSES ? `${error.message}: ${causeChainOf(error.cause, depth + 1)}` : messageOf(error);
306
1016
  }
1017
+ /** The Fetch route serving images beside detail documents. */
1018
+ const DETAIL_FILE_PATH = "/api/plugin-market/detail-file";
1019
+ /** Registries whose packages the public npm file CDNs serve. */
1020
+ const PUBLIC_REGISTRIES = new Set(["registry.npmjs.org", "registry.npmmirror.com"]);
307
1021
  /** Largest page `search` returns. */
308
1022
  const MAX_LIMIT = 100;
309
1023
  let PluginMarket = (() => {
@@ -312,12 +1026,14 @@ let PluginMarket = (() => {
312
1026
  let _listIndexes_decorators;
313
1027
  let _setIndexes_decorators;
314
1028
  let _search_decorators;
1029
+ let _readEntryDetail_decorators;
315
1030
  return class PluginMarket extends _classSuper {
316
1031
  static {
317
1032
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
318
1033
  _listIndexes_decorators = [Remote];
319
1034
  _setIndexes_decorators = [Remote];
320
1035
  _search_decorators = [Remote];
1036
+ _readEntryDetail_decorators = [Remote];
321
1037
  __esDecorate(this, null, _listIndexes_decorators, {
322
1038
  kind: "method",
323
1039
  name: "listIndexes",
@@ -351,6 +1067,17 @@ let PluginMarket = (() => {
351
1067
  },
352
1068
  metadata: _metadata
353
1069
  }, null, _instanceExtraInitializers);
1070
+ __esDecorate(this, null, _readEntryDetail_decorators, {
1071
+ kind: "method",
1072
+ name: "readEntryDetail",
1073
+ static: false,
1074
+ private: false,
1075
+ access: {
1076
+ has: (obj) => "readEntryDetail" in obj,
1077
+ get: (obj) => obj.readEntryDetail
1078
+ },
1079
+ metadata: _metadata
1080
+ }, null, _instanceExtraInitializers);
354
1081
  if (_metadata) Object.defineProperty(this, Symbol.metadata, {
355
1082
  enumerable: true,
356
1083
  configurable: true,
@@ -364,17 +1091,58 @@ let PluginMarket = (() => {
364
1091
  indexes: z.array(z.string().pattern(/^https?:\/\/\S+$/u)).default([]).volatile(),
365
1092
  fetchTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(15e3),
366
1093
  maxBytes: z.natural().min(1).default(128 * 1024 * 1024),
367
- cacheTtlMs: z.natural().default(6e5)
1094
+ cacheTtlMs: z.natural().default(6e5),
1095
+ detailMaxBytes: z.natural().min(1).default(1024 * 1024),
1096
+ detailImageMaxBytes: z.natural().min(1).default(5 * 1024 * 1024),
1097
+ detailRepositoryMaxBytes: z.natural().min(1).default(50 * 1024 * 1024),
1098
+ detailCacheMaxBytes: z.natural().min(1).default(500 * 1024 * 1024),
1099
+ detailCacheDir: z.string(),
1100
+ detailGitTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(6e4),
1101
+ detailNpmFileSources: z.array(z.union(NPM_FILE_SOURCES)).min(1).default([...NPM_FILE_SOURCES]),
1102
+ detailGitlabHosts: z.array(z.string()).default(["gitlab.com"])
368
1103
  });
369
1104
  lifetime = new AbortController();
370
1105
  cache = /* @__PURE__ */ new Map();
371
1106
  pending = /* @__PURE__ */ new Map();
372
1107
  errors = /* @__PURE__ */ new Map();
373
1108
  entryId;
1109
+ repositories;
1110
+ details;
374
1111
  constructor(ctx, config) {
375
1112
  super(ctx, "pluginMarket");
376
1113
  this.config = config;
377
1114
  this.entryId = ctx.fiber.entry?.options.id;
1115
+ const profile = ctx.get("profileContext");
1116
+ const cacheDir = profile === void 0 ? config.detailCacheDir : resolve(profile.dir, config.detailCacheDir ?? join(".plugin-market", "repositories"));
1117
+ if (cacheDir === void 0 || !isAbsolute(cacheDir)) throw new Error("plugin-market: detailCacheDir must be an absolute path when the service runs without a rabi profile");
1118
+ const lifetime = this.lifetime.signal;
1119
+ this.repositories = new RepositoryCache({
1120
+ dir: cacheDir,
1121
+ maxRepositoryBytes: config.detailRepositoryMaxBytes,
1122
+ maxCacheBytes: config.detailCacheMaxBytes,
1123
+ timeoutMs: config.detailGitTimeoutMs,
1124
+ ttlMs: config.cacheTtlMs,
1125
+ transports: [
1126
+ "https",
1127
+ "http",
1128
+ "ssh"
1129
+ ],
1130
+ lifetime,
1131
+ sizePollMs: 200
1132
+ });
1133
+ this.details = new DetailReader({
1134
+ maxDocumentBytes: config.detailMaxBytes,
1135
+ maxImageBytes: config.detailImageMaxBytes,
1136
+ ttlMs: config.cacheTtlMs
1137
+ }, this.detailRepositoryOptions());
1138
+ ctx.inject(["connection"], (scope) => {
1139
+ scope.effect(() => scope.connection.fetch.register({
1140
+ path: DETAIL_FILE_PATH,
1141
+ methods: ["GET"],
1142
+ requestBody: "buffered",
1143
+ fetch: (request) => this.serveDetailFile(request)
1144
+ }), `plugin-market: ${DETAIL_FILE_PATH}`);
1145
+ });
378
1146
  ctx.on("loader/volatile-update", () => {
379
1147
  const configured = new Set(this.sources().flatMap((source) => source.error === void 0 ? [source.url] : []));
380
1148
  for (const url of [...this.cache.keys(), ...this.errors.keys()]) if (!configured.has(url)) {
@@ -385,7 +1153,7 @@ let PluginMarket = (() => {
385
1153
  });
386
1154
  ctx.effect(() => async () => {
387
1155
  this.lifetime.abort(/* @__PURE__ */ new Error("Plugin market disposed"));
388
- await Promise.allSettled(this.pending.values());
1156
+ await Promise.allSettled([...this.pending.values(), this.repositories.settled()]);
389
1157
  });
390
1158
  }
391
1159
  /**
@@ -477,6 +1245,109 @@ let PluginMarket = (() => {
477
1245
  const plugin = (await this.document(url, false)).index.plugins.find((candidate) => candidate.name === name);
478
1246
  return plugin === void 0 ? void 0 : (await this.annotator())(plugin);
479
1247
  }
1248
+ /**
1249
+ * Read the long description of one listed version of a plugin market entry, from the version's source: the npm file
1250
+ * CDNs for a public npm version, or its pinned Git commit. The Markdown file the package's locale `meta.detail` names
1251
+ * in `language` comes first, then the package's README, then the README of the entry's `repository`, or for an npm
1252
+ * version without one, of its `package.json` `repository`, at the default branch. An npm version from another
1253
+ * registry has no readable package files, so only the entry's `repository` is read.
1254
+ * @param url - a configured index URL.
1255
+ * @param name - the plugin's package name.
1256
+ * @param version - one listed version.
1257
+ * @param language - the display language, such as `zh-CN`; documents fall back through its prefixes to English.
1258
+ * @param options - `refresh` reads again instead of reusing a result cached for `cacheTtlMs`; `npmFileSources` names
1259
+ * npm file CDNs to ask first for an npm version, in order; configured CDNs it omits follow, and CDNs that are not
1260
+ * configured are not asked.
1261
+ * @returns the document with its origin and image document id, or `none`.
1262
+ * @throws {RemoteError} the failures of `search`, `plugin-market/unknown-plugin` for an unlisted plugin or version,
1263
+ * `plugin-market/invalid-query`, or `plugin-market/detail-unavailable`.
1264
+ */
1265
+ async readEntryDetail(url, name, version, language, options) {
1266
+ const languages = this.languages(language);
1267
+ const plugin = (await this.document(url, false)).index.plugins.find((candidate) => candidate.name === name);
1268
+ const listed = plugin?.versions.find((candidate) => candidate.version === version);
1269
+ if (plugin === void 0 || listed === void 0) throw new RemoteError("plugin-market/unknown-plugin", `${url} lists no ${name}@${version}`, {
1270
+ name,
1271
+ version
1272
+ });
1273
+ const declared = plugin.repository;
1274
+ const found = declared === void 0 ? void 0 : repositoryOf(declared.url);
1275
+ let repository = found === void 0 ? void 0 : {
1276
+ ...found,
1277
+ directory: declared?.directory ?? ""
1278
+ };
1279
+ const { source } = listed;
1280
+ let location;
1281
+ if (source.type === "git") {
1282
+ const ref = repositoryOf(source.url);
1283
+ /* v8 ignore next -- parseMarketIndex admits only https Git URLs with an owner and a project */
1284
+ if (ref === void 0) return { status: "none" };
1285
+ const dir = source.path ?? "";
1286
+ if (repository?.url === ref.url && repository.directory === dir) repository = void 0;
1287
+ location = {
1288
+ files: repositoryFiles(ref, source.commit, this.detailRepositoryOptions()),
1289
+ dir,
1290
+ repository
1291
+ };
1292
+ } else if (source.registry === void 0 || PUBLIC_REGISTRIES.has(new URL(source.registry).host)) location = this.npmLocation(name, version, repository ?? "manifest", options?.npmFileSources ?? []);
1293
+ else location = {
1294
+ dir: "",
1295
+ repository
1296
+ };
1297
+ return await this.readDetail(location, languages, options?.refresh === true);
1298
+ }
1299
+ languages(language) {
1300
+ try {
1301
+ return languageChain(language);
1302
+ } catch (error) {
1303
+ throw new RemoteError("plugin-market/invalid-query", messageOf(error), {
1304
+ field: "language",
1305
+ reason: "format"
1306
+ }, { cause: error });
1307
+ }
1308
+ }
1309
+ detailRepositoryOptions() {
1310
+ const { config } = this;
1311
+ return {
1312
+ timeoutMs: config.fetchTimeoutMs,
1313
+ lifetime: this.lifetime.signal,
1314
+ gitlabHosts: config.detailGitlabHosts.map((host) => host.toLowerCase()),
1315
+ cache: this.repositories
1316
+ };
1317
+ }
1318
+ /** The detail location of a published npm version on the configured CDNs, the preferred ones first. */
1319
+ npmLocation(name, version, repository, preferred) {
1320
+ return {
1321
+ dir: "",
1322
+ repository,
1323
+ files: npmFiles(name, version, npmFileSourceOrder(this.config.detailNpmFileSources, preferred), {
1324
+ timeoutMs: this.config.fetchTimeoutMs,
1325
+ lifetime: this.lifetime.signal
1326
+ })
1327
+ };
1328
+ }
1329
+ async readDetail(location, languages, refresh) {
1330
+ try {
1331
+ return await this.details.read(location, languages, refresh);
1332
+ } catch (error) {
1333
+ if (!(error instanceof DetailFailure)) throw error;
1334
+ throw new RemoteError("plugin-market/detail-unavailable", error.message, { reason: error.reason }, { cause: error });
1335
+ }
1336
+ }
1337
+ /** Answer `GET ${DETAIL_FILE_PATH}?document=<id>&path=<destination>` with one image beside a read detail document. */
1338
+ async serveDetailFile(request) {
1339
+ const params = new URL(request.url).searchParams;
1340
+ const document = params.get("document");
1341
+ const path = params.get("path");
1342
+ const cache = `private, max-age=${String(Math.floor(this.config.cacheTtlMs / 1e3))}`;
1343
+ if (document === null || path === null) return detailImageResponse("invalid", cache);
1344
+ try {
1345
+ return detailImageResponse(await this.details.image(document, path), cache);
1346
+ } catch (error) {
1347
+ if (!(error instanceof DetailFailure)) throw error;
1348
+ return detailImageResponse(error.reason, cache);
1349
+ }
1350
+ }
480
1351
  async document(url, refresh, fetchedAt) {
481
1352
  const source = this.sources().find((candidate) => candidate.url === url);
482
1353
  if (source === void 0) throw new RemoteError("plugin-market/unknown-index", `Not a configured index source: ${url}`, { url });
@@ -608,11 +1479,19 @@ let PluginMarket = (() => {
608
1479
  };
609
1480
  })();
610
1481
  function listingOf(plugin, bundles, exemptions, runtimeVersion) {
611
- const versions = plugin.versions.map((version) => ({
612
- ...version,
613
- install: marketInstallTarget(plugin.name, version),
614
- compatibility: compatibilityOf(plugin.name, version, exemptions, runtimeVersion)
615
- }));
1482
+ const bundle = bundles.find((candidate) => candidate.name === plugin.name);
1483
+ const origin = bundle?.update === "git" && bundle.source !== void 0 ? pinnedGitOrigin(bundle.source) : void 0;
1484
+ const installedVersion = bundle?.version;
1485
+ const versions = plugin.versions.map((version) => {
1486
+ const install = marketInstallTarget(plugin.name, version);
1487
+ const update = origin !== void 0 && installedVersion !== void 0 && semver.gt(version.version, installedVersion) && pinnedGitOrigin(install.spec) === origin;
1488
+ return {
1489
+ ...version,
1490
+ install,
1491
+ compatibility: compatibilityOf(plugin.name, version, exemptions, runtimeVersion),
1492
+ update
1493
+ };
1494
+ });
616
1495
  const compatible = versions.filter((version) => version.compatibility.compatible);
617
1496
  const stable = plugin.versions.some((version) => semver.prerelease(version.version) === null);
618
1497
  const defaultVersion = compatible.find((version) => !stable || semver.prerelease(version.version) === null)?.version;
@@ -622,11 +1501,10 @@ function listingOf(plugin, bundles, exemptions, runtimeVersion) {
622
1501
  ...plugin,
623
1502
  versions,
624
1503
  ...defaultVersion === void 0 ? {} : { defaultVersion },
625
- installation: installationOf(plugin.name, measured, bundles)
1504
+ installation: installationOf(bundle, measured)
626
1505
  };
627
1506
  }
628
- function installationOf(name, version, bundles) {
629
- const bundle = bundles.find((candidate) => candidate.name === name);
1507
+ function installationOf(bundle, version) {
630
1508
  if (bundle === void 0 || !bundle.installed && bundle.availability !== "installation") return { status: "not-installed" };
631
1509
  if (!bundle.installed) return {
632
1510
  status: "provided",