@vltpkg/package-info 1.3.3 → 1.3.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/README.md CHANGED
@@ -51,8 +51,8 @@ only ever sees `auto` from the CLI on Linux. A gzipped cached tarball
51
51
  that is not store-linked (`unpack`, git or remote tarballs, no sha512
52
52
  integrity) is queued too, so the child un-gzips it.
53
53
 
54
- Packages with install scripts are copied, never linked: when the store
55
- index says so, or with the `installScripts` extract option.
54
+ Packages with install scripts are linked too; reify copies them in
55
+ place right before their scripts run.
56
56
 
57
57
  A store link logs its request as `store`, a copy from the store as
58
58
  `cache`. Both also return `manifest` (the package.json as JSON text,
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ import type { SpecOptions } from '@vltpkg/spec';
5
5
  import { Spec } from '@vltpkg/spec';
6
6
  import type { Pool, StoreLinker } from '@vltpkg/tar';
7
7
  import type { Integrity, Manifest, Packument } from '@vltpkg/types';
8
+ import type { ResolveRequest } from './resolve-batch.ts';
9
+ export type { ResolveRequest } from './resolve-batch.ts';
8
10
  import { Monorepo } from '@vltpkg/workspaces';
9
11
  import type { Capabilities } from './capabilities.ts';
10
12
  export type { Capabilities } from './capabilities.ts';
@@ -106,11 +108,6 @@ export type PackageInfoClientExtractOptions = PackageInfoClientRequestOptions &
106
108
  * Other network bodies are always checked.
107
109
  */
108
110
  fromLockfile?: boolean;
109
- /**
110
- * The manifest declares install scripts: copy the package from the
111
- * global store, never link it, even if its package.json has none.
112
- */
113
- installScripts?: boolean;
114
111
  };
115
112
  export declare class PackageInfoClient {
116
113
  #private;
@@ -134,6 +131,22 @@ export declare class PackageInfoClient {
134
131
  */
135
132
  _manifestCachePath(spec: Spec, options: PackageInfoClientRequestOptions): string | undefined;
136
133
  tarball(spec: Spec | string, options?: PackageInfoClientExtractOptions): Promise<Buffer>;
134
+ /**
135
+ * Start a server-side resolve for `request` against `registry` and
136
+ * return without waiting. `manifest()` answers from what has arrived,
137
+ * and blocks on the request only when it needs a key that has not.
138
+ *
139
+ * A no-op unless the registry says it serves the endpoint. Anything it
140
+ * does not deliver is left to `manifest()`.
141
+ *
142
+ * Returns the function that releases the request. A build calls it once
143
+ * it has placed its last node; when the last build reading a request has
144
+ * released it, the stream is ended, so an install never waits on a
145
+ * stream nothing will read. The records it delivered stay answerable.
146
+ */
147
+ prefetchResolve(registry: string, request: ResolveRequest): () => void;
148
+ /** How many manifests resolve batches have delivered. For tests. */
149
+ get resolvedManifestCount(): number;
137
150
  manifest(spec: Spec | string, options?: PackageInfoClientRequestOptions): Promise<Manifest | import("@vltpkg/types").Override<Manifest, import("@vltpkg/types").NormalizedFields>>;
138
151
  /**
139
152
  * The packument for `spec`, with every version the registry has. Callers
package/dist/index.js CHANGED
@@ -9,12 +9,13 @@ import { registryErrorMessage, tokenRefusalAdvice, } from '@vltpkg/registry-clie
9
9
  import { storeRoot } from '@vltpkg/registry-client/store-root';
10
10
  import { Spec } from '@vltpkg/spec';
11
11
  import { asPackument, brotliTarballUrl, integrityHex, tarballFormat, } from '@vltpkg/types';
12
- import ssri from 'ssri';
12
+ import { fetchResolve } from "./resolve-batch.js";
13
13
  import { Monorepo } from '@vltpkg/workspaces';
14
14
  import { XDG } from '@vltpkg/xdg';
15
15
  import { createHash, randomBytes } from 'node:crypto';
16
16
  import { mkdir, readFile, rm, stat, symlink, unlink, writeFile, } from 'node:fs/promises';
17
17
  import { basename, dirname, resolve as pathResolve, relative, } from 'node:path';
18
+ import { setTimeout } from 'node:timers/promises';
18
19
  import { debuglog } from 'node:util';
19
20
  import { create as tarC } from 'tar';
20
21
  import { getCapabilities, peekCapabilities } from "./capabilities.js";
@@ -50,6 +51,30 @@ export const VLT_PACKUMENT_V2_MIME = 'application/vnd.vlt.packument-v2+json';
50
51
  * has something to match.
51
52
  */
52
53
  export const PACKUMENT_ACCEPT = `${VLT_PACKUMENT_V2_MIME}; q=1.0, ${VLT_PACKUMENT_MIME}; q=0.9, application/json; q=0.8, */*; q=0.1`;
54
+ /**
55
+ * How long a resolve stream may go without delivering a record before a
56
+ * lookup fetches the packument as well. A stream that is delivering gets
57
+ * this long to carry the key; one that has already been quiet for this long
58
+ * gets no more. The stream is still read after that: the lookup takes
59
+ * whichever answers first.
60
+ */
61
+ const resolveWaitMs = () => {
62
+ const configured = Number(process.env.VLT_BATCH_RESOLVE_WAIT_MS);
63
+ return Number.isFinite(configured) && configured >= 0 ?
64
+ configured
65
+ : 250;
66
+ };
67
+ // what the grace timer resolves to, so it cannot be mistaken for a manifest
68
+ const graceOver = Symbol('graceOver');
69
+ // request options that change which manifest is picked, or how; a batch
70
+ // entry never went through pickManifest under them, so they bypass it
71
+ const SELECTION_OPTIONS = [
72
+ 'before',
73
+ 'os',
74
+ 'arch',
75
+ 'libc',
76
+ 'node-version',
77
+ ];
53
78
  // the maximum duration of a manifest cache file
54
79
  const manifestCacheMaxAge = 5 * 60 * 1000;
55
80
  /**
@@ -96,6 +121,29 @@ const isStableSelector = (f) => {
96
121
  };
97
122
  // anything else, eg an unvalidated env value, means `unpack`
98
123
  const storeLinkers = new Set(['auto', 'hardlink', 'copy']);
124
+ // the hash a response answers for. a network body's is the hash of its
125
+ // bytes: the registry client already checked it against the expected
126
+ // hash, or recorded it when there was none, and memoized it, so this
127
+ // is no second pass.
128
+ //
129
+ // a cache hit answers with the hash the entry was stored under, never
130
+ // a fresh one: cache-unzip rewrites cached bodies un-gzipped in place,
131
+ // so hashing one again would pin a hash of bytes no other machine has.
132
+ // an entry stored before that hash was recorded can still be hashed
133
+ // while its body is the bytes that came off the wire, i.e. still
134
+ // gzipped; once rewritten it cannot be verified at all.
135
+ //
136
+ // nor can an entry with no content-type. request() labels a body
137
+ // served without one as it stores it under the hash it checked or
138
+ // recorded, so an entry with none was not stored that way. it may be
139
+ // from v1.2.0 to v1.3.3, which un-gzipped a gzipped one in memory and
140
+ // only then hashed it: its stored hash may be of that copy, which no
141
+ // cold cache reproduces. a body served un-gzipped hashes the same
142
+ // either way, so there is no telling which, and none is trusted.
143
+ const storedIntegrity = (response) => !response.fromCache ? response.integrityActual
144
+ : !response.contentType ? undefined
145
+ : (response.integrity ??
146
+ (response.isGzip ? response.integrityActual : undefined));
99
147
  export class PackageInfoClient {
100
148
  #registryClient;
101
149
  #projectRoot;
@@ -134,6 +182,31 @@ export class PackageInfoClient {
134
182
  // needed. entries are removed when the on-disk file is invalidated
135
183
  // so the refreshed manifest can be written again.
136
184
  #manifestWritePaths = new Set();
185
+ // Manifests a resolve batch delivered, keyed both as
186
+ // `${registry}${name}@${range}` for every spec that chose a version and
187
+ // `${registry}${name}@${version}` for the version itself.
188
+ #resolvedManifests = new Map();
189
+ /**
190
+ * The resolve requests in flight against each registry, with when the
191
+ * registry last delivered a record: the grace a lookup gives the stream
192
+ * is measured from there, and it is set when the request is sent, so
193
+ * a registry with a request in flight always has a time.
194
+ */
195
+ #resolveInflight = new Map();
196
+ /**
197
+ * each request in flight, by its `#resolveSent` key: its controller and
198
+ * how many builds are still reading it. a request that settled on its
199
+ * own stays in `#resolveSent`, since its records are still here
200
+ */
201
+ #resolveOwners = new Map();
202
+ // Requests already sent, so the same ask is not repeated. Keyed on the
203
+ // request rather than the registry: a later step asking for a different
204
+ // root set is a different question.
205
+ #resolveSent = new Set();
206
+ // Keys `manifest()` is waiting for, each woken by the record that carries
207
+ // it. Waiting per key rather than on the whole response is what lets a
208
+ // build place level N while the server still walks level N+1.
209
+ #resolveWaiters = new Map();
137
210
  #registryClientPromise;
138
211
  #tarPoolPromise;
139
212
  async getRegistryClient() {
@@ -231,7 +304,7 @@ export class PackageInfoClient {
231
304
  async extract(spec, target, options = {}) {
232
305
  if (typeof spec === 'string')
233
306
  spec = Spec.parse(spec, this.options);
234
- const { from = this.#projectRoot, integrity, resolved, fromLockfile = false, installScripts = false, } = options;
307
+ const { from = this.#projectRoot, integrity, resolved, fromLockfile = false, } = options;
235
308
  const f = spec.final;
236
309
  // If the caller already provides both integrity and resolved
237
310
  // (from lockfile or prior resolution), skip re-resolving. A
@@ -282,7 +355,7 @@ export class PackageInfoClient {
282
355
  const format = tarballFormat(r.resolved);
283
356
  // git tarballs keep the unpack path
284
357
  const storeOn = f.type === 'registry' && this.#storeLinker !== 'unpack';
285
- const copy = this.#storeLinker === 'copy' || installScripts;
358
+ const copy = this.#storeLinker === 'copy';
286
359
  // If we already have a hash, that is the store key. Some
287
360
  // tarballs arrive without one: a `.tar.br`, or anything a
288
361
  // registry serves with no `dist.integrity`. For those, read the
@@ -429,28 +502,113 @@ export class PackageInfoClient {
429
502
  return r;
430
503
  }
431
504
  case 'remote': {
432
- const response = await (await this.getRegistryClient()).request(r.resolved);
433
- if (response.statusCode !== 200) {
434
- throw this.#resolveError(spec, options, `failed to fetch remote tarball: ${registryErrorMessage(response)}`, {
435
- url: r.resolved,
436
- response,
437
- });
505
+ const rc = await this.getRegistryClient();
506
+ // lazy for the same reason getRegistryClient() is
507
+ const { CacheEntry: Entry, cacheKey } = await import('@vltpkg/registry-client');
508
+ const key = cacheKey('GET', new URL(r.resolved));
509
+ // v1.2.0 to v1.3.3 hashed a remote tarball after the registry
510
+ // client had un-gzipped it: always, for one served with no
511
+ // content-type, and on a cache hit once cache-unzip had
512
+ // rewritten the entry, so a lockfile they wrote may pin that
513
+ // hash. it pins the same tar: a body that un-gzips to it is
514
+ // accepted, and r.integrity re-pinned to the hash the body is
515
+ // stored under, the one reported. the graph keeps the hash a
516
+ // node was locked with, so the lockfile is never rewritten and
517
+ // every install from it takes this path. a body that will not
518
+ // un-gzip is no match.
519
+ const unzipped = (entry) => {
520
+ try {
521
+ return entry.unzippedIntegrity() === r.integrity;
522
+ }
523
+ catch {
524
+ return false;
525
+ }
526
+ };
527
+ const fetchTarball = async (readCache) => {
528
+ let response;
529
+ try {
530
+ response = await rc.request(r.resolved, {
531
+ integrity: r.integrity,
532
+ ...(readCache === false ? { readCache } : {}),
533
+ });
534
+ }
535
+ catch (er) {
536
+ // the registry client rejects a network body that does not
537
+ // hash to r.integrity before anything is written. store one
538
+ // that un-gzips to it the way the client would have: under
539
+ // the hash of its bytes it recorded for the check, labelled
540
+ // like one it stores (see storedIntegrity), and for a url
541
+ // that redirects, under the url the lockfile names only,
542
+ // all a cache hit needs.
543
+ const cause = er.cause;
544
+ if (cause?.code !== 'EINTEGRITY' ||
545
+ !(cause.response instanceof Entry) ||
546
+ !unzipped(cause.response)) {
547
+ throw er;
548
+ }
549
+ response = cause.response;
550
+ r.integrity = response.integrityActual;
551
+ response.labelArtifact();
552
+ rc.cache.set(key, response.encode(), {
553
+ integrity: r.integrity,
554
+ });
555
+ }
556
+ if (response.statusCode !== 200) {
557
+ throw this.#resolveError(spec, options, `failed to fetch remote tarball: ${registryErrorMessage(response)}`, {
558
+ url: r.resolved,
559
+ response,
560
+ });
561
+ }
562
+ return response;
563
+ };
564
+ let response = await fetchTarball();
565
+ let found = storedIntegrity(response);
566
+ // a cache hit that un-gzips to the lockfile hash, see above
567
+ if (response.fromCache &&
568
+ found &&
569
+ r.integrity &&
570
+ r.integrity !== found &&
571
+ unzipped(response)) {
572
+ r.integrity = found;
438
573
  }
439
- const buf = response.buffer();
440
- // Compute integrity for remote/git-with-tarball deps
441
- const computed = ssri
442
- .fromData(buf, { algorithms: ['sha512'] })
443
- .toString();
444
- if (r.integrity && r.integrity !== computed) {
574
+ // a cached entry that does not match the lockfile, or that
575
+ // cannot be verified any more: evict it and fetch again, once,
576
+ // so the cache converges on an entry that carries its hash.
577
+ // the link under r.integrity goes too: the lookup by it links
578
+ // the value file there when nothing was, and the disk write
579
+ // trusts an integrity file it finds, so it would link the old
580
+ // bytes back over the new ones. the refetch reads nothing from
581
+ // the cache, on this url or any it redirects to: a url that
582
+ // redirects has an entry under the final url too, stored by
583
+ // the same fetch and out of the eviction's reach.
584
+ if (response.fromCache &&
585
+ (!found || (r.integrity && r.integrity !== found))) {
586
+ rc.cache.delete(key, true, found);
587
+ if (r.integrity)
588
+ rc.cache.delete(key, true, r.integrity);
589
+ await rc.cache.promise();
590
+ response = await fetchTarball(false);
591
+ found = storedIntegrity(response);
592
+ }
593
+ /* c8 ignore start - defense in depth: anything but a cache hit
594
+ * that matched is a network body, the refetch included, since
595
+ * it reads nothing from the cache on any redirect hop. the
596
+ * registry client checks every network body against
597
+ * r.integrity before anything is written, and records the hash
598
+ * of one it had no expectation for; one it rejected is only
599
+ * here with r.integrity re-pinned to its hash. */
600
+ if (!found || (r.integrity && r.integrity !== found)) {
445
601
  throw error('Integrity check failure', {
446
602
  code: 'EINTEGRITY',
447
603
  spec,
448
604
  url: r.resolved,
449
605
  wanted: r.integrity,
450
- found: computed,
606
+ found,
451
607
  });
452
608
  }
453
- r.integrity = computed;
609
+ /* c8 ignore stop */
610
+ r.integrity = found;
611
+ const buf = response.buffer();
454
612
  try {
455
613
  await (await this.getTarPool()).unpack(buf, target);
456
614
  }
@@ -712,6 +870,173 @@ export class PackageInfoClient {
712
870
  }
713
871
  }
714
872
  }
873
+ /**
874
+ * Start a server-side resolve for `request` against `registry` and
875
+ * return without waiting. `manifest()` answers from what has arrived,
876
+ * and blocks on the request only when it needs a key that has not.
877
+ *
878
+ * A no-op unless the registry says it serves the endpoint. Anything it
879
+ * does not deliver is left to `manifest()`.
880
+ *
881
+ * Returns the function that releases the request. A build calls it once
882
+ * it has placed its last node; when the last build reading a request has
883
+ * released it, the stream is ended, so an install never waits on a
884
+ * stream nothing will read. The records it delivered stay answerable.
885
+ */
886
+ prefetchResolve(registry, request) {
887
+ if (!request.roots.length)
888
+ return () => { };
889
+ // keyed the way a spec names its registry, with the trailing slash
890
+ if (!registry.endsWith('/'))
891
+ registry += '/';
892
+ const sent = `${registry}${JSON.stringify(request)}`;
893
+ // the same question already in flight is read, not asked again
894
+ const owned = this.#resolveOwners.get(sent);
895
+ if (owned) {
896
+ owned.readers++;
897
+ return () => this.#releaseResolve(sent, owned);
898
+ }
899
+ if (this.#resolveSent.has(sent))
900
+ return () => { };
901
+ this.#resolveSent.add(sent);
902
+ const owner = { controller: new AbortController(), readers: 1 };
903
+ this.#resolveOwners.set(sent, owner);
904
+ let inflight = this.#resolveInflight.get(registry);
905
+ if (!inflight) {
906
+ inflight = { requests: new Set(), lastRecordAt: 0 };
907
+ this.#resolveInflight.set(registry, inflight);
908
+ }
909
+ // the stream's grace runs from the moment it is asked for
910
+ inflight.lastRecordAt = Date.now();
911
+ const promise = this.#runResolve(registry, request, owner.controller.signal, inflight);
912
+ inflight.requests.add(promise);
913
+ // dropped once settled, so manifest() stops waiting on a request that
914
+ // has already delivered everything it is going to
915
+ const clear = () => {
916
+ inflight.requests.delete(promise);
917
+ // a request released and asked again is a new owner by now
918
+ if (this.#resolveOwners.get(sent) === owner)
919
+ this.#resolveOwners.delete(sent);
920
+ };
921
+ promise.then(clear, clear);
922
+ return () => this.#releaseResolve(sent, owner);
923
+ }
924
+ /**
925
+ * One build is done reading the request; the last one out ends it, and
926
+ * the same question can then be asked again.
927
+ */
928
+ #releaseResolve(sent, owner) {
929
+ if (--owner.readers > 0)
930
+ return;
931
+ if (this.#resolveOwners.get(sent) === owner) {
932
+ this.#resolveOwners.delete(sent);
933
+ this.#resolveSent.delete(sent);
934
+ }
935
+ owner.controller.abort();
936
+ }
937
+ /** Never rejects: a resolve that fails leaves every spec to manifest(). */
938
+ async #runResolve(registry, request, signal, inflight) {
939
+ try {
940
+ if ((await this.capabilities(registry)).resolve === undefined)
941
+ return;
942
+ const client = await this.getRegistryClient();
943
+ await fetchResolve(client, registry, request, record => {
944
+ inflight.lastRecordAt = Date.now();
945
+ // A resolve record is a vlt manifest: `dist.tarball` is the
946
+ // tarball's basename, resolved against the package's `/-/`
947
+ // directory like a v2 packument's, and a tarball without a hash
948
+ // must carry a Repr-Digest.
949
+ absolutizeTarball(record.manifest, `${registry}${record.name}/-/`);
950
+ this.#vltPackuments.add(`${registry}${record.name}`);
951
+ // Indexed both ways: by the ranges that chose the version, which
952
+ // is what the graph build asks for, and by the exact version, for
953
+ // a lookup that already knows it.
954
+ for (const spec of record.requested) {
955
+ this.#deliverResolved(`${registry}${record.name}@${spec}`, record.manifest);
956
+ }
957
+ this.#deliverResolved(`${registry}${record.name}@${record.version}`, record.manifest);
958
+ }, signal);
959
+ }
960
+ catch {
961
+ // The per-name path still has every spec.
962
+ }
963
+ }
964
+ /** Record an arrived manifest and wake whoever was waiting for it. */
965
+ #deliverResolved(key, manifest) {
966
+ debug('resolve delivered %s', key);
967
+ this.#resolvedManifests.set(key, manifest);
968
+ const waiters = this.#resolveWaiters.get(key);
969
+ if (waiters) {
970
+ this.#resolveWaiters.delete(key);
971
+ for (const wake of waiters)
972
+ wake(manifest);
973
+ }
974
+ }
975
+ /**
976
+ * The manifest for `key` from an in-flight resolve, or from `fetch` when
977
+ * the resolve is not carrying it. Undefined when nothing is in flight.
978
+ *
979
+ * A stream that is delivering gets a short grace to carry the key, since
980
+ * its records come in the order the build asks for them; one that has
981
+ * gone quiet gets none, so a server that is slow to start never charges
982
+ * that grace to every level of the build. After the grace `fetch` runs as
983
+ * well and the first answer wins, so a slow server can never hold a
984
+ * lookup longer than fetching the packument would have. A fetch that
985
+ * fails while the stream is still open waits for the stream's verdict.
986
+ */
987
+ async #awaitResolved(registry, key, fetch) {
988
+ const inflight = this.#resolveInflight.get(registry);
989
+ if (!inflight?.requests.size)
990
+ return undefined;
991
+ let wake;
992
+ const arrival = new Promise(res => {
993
+ wake = res;
994
+ });
995
+ let waiters = this.#resolveWaiters.get(key);
996
+ if (!waiters)
997
+ this.#resolveWaiters.set(key, (waiters = new Set()));
998
+ waiters.add(wake);
999
+ const settled = Promise.all([...inflight.requests]).then(() => this.#resolvedManifests.get(key));
1000
+ const quietFor = Date.now() - inflight.lastRecordAt;
1001
+ const grace = Math.max(0, resolveWaitMs() - quietFor);
1002
+ try {
1003
+ const early = await Promise.race([
1004
+ arrival,
1005
+ settled,
1006
+ // unref'd: a pending wait must never be what keeps the process up
1007
+ setTimeout(grace, graceOver, { ref: false }),
1008
+ ]);
1009
+ if (early !== graceOver)
1010
+ return early ?? (await fetch());
1011
+ debug('resolve hedge %s', key);
1012
+ const hedge = fetch();
1013
+ const outcome = await Promise.race([
1014
+ arrival,
1015
+ settled,
1016
+ hedge.catch(() => undefined),
1017
+ ]);
1018
+ if (outcome)
1019
+ return outcome;
1020
+ // the hedge failed first, or the stream settled without the key:
1021
+ // the stream gets one more grace to contradict the failure, and
1022
+ // failing that, the failure is the answer
1023
+ const found = await Promise.race([
1024
+ arrival,
1025
+ settled,
1026
+ setTimeout(resolveWaitMs(), graceOver, { ref: false }),
1027
+ ]);
1028
+ return found && found !== graceOver ? found : await hedge;
1029
+ }
1030
+ finally {
1031
+ waiters.delete(wake);
1032
+ if (!waiters.size)
1033
+ this.#resolveWaiters.delete(key);
1034
+ }
1035
+ }
1036
+ /** How many manifests resolve batches have delivered. For tests. */
1037
+ get resolvedManifestCount() {
1038
+ return this.#resolvedManifests.size;
1039
+ }
715
1040
  async manifest(spec, options = {}) {
716
1041
  const { from = this.#projectRoot } = options;
717
1042
  if (typeof spec === 'string')
@@ -719,6 +1044,15 @@ export class PackageInfoClient {
719
1044
  const f = spec.final;
720
1045
  switch (f.type) {
721
1046
  case 'registry': {
1047
+ // a resolve entry never went through pickManifest under any
1048
+ // selection option, so those take the packument path
1049
+ const selecting = SELECTION_OPTIONS.some(k => options[k] !== undefined);
1050
+ const resolveKey = `${f.registry ?? ''}${f.name}@${f.bareSpec}`;
1051
+ if (!selecting) {
1052
+ const resolved = this.#resolvedManifests.get(resolveKey);
1053
+ if (resolved)
1054
+ return resolved;
1055
+ }
722
1056
  // Check if manifest is cached, if so just return it earlier
723
1057
  const cachePath = this._manifestCachePath(spec, options);
724
1058
  if (cachePath) {
@@ -753,18 +1087,28 @@ export class PackageInfoClient {
753
1087
  // Cache miss, fetch from packument
754
1088
  }
755
1089
  }
756
- const mani = pickManifest(await this.#packument(f, options, this.#stable(f)), spec, options);
757
- if (!mani)
758
- throw this.#resolveError(spec, options);
759
- // Cache the manifest data. Skip paths already written this
760
- // run — first writer wins, avoiding duplicate serialization
761
- // and racing writers for the same path.
762
- if (cachePath && !this.#manifestWritePaths.has(cachePath)) {
763
- this.#manifestWritePaths.add(cachePath);
764
- const vlt = this.#vltPackuments.has(`${f.registry}${f.name}`);
765
- void this.#writeManifestCache(cachePath, JSON.stringify(vlt ? { ...mani, __VLT_PACKUMENT: true } : mani));
1090
+ const fromPackument = async () => {
1091
+ const mani = pickManifest(await this.#packument(f, options, this.#stable(f)), spec, options);
1092
+ if (!mani)
1093
+ throw this.#resolveError(spec, options);
1094
+ // Cache the manifest data. Skip paths already written this
1095
+ // run — first writer wins, avoiding duplicate serialization
1096
+ // and racing writers for the same path.
1097
+ if (cachePath && !this.#manifestWritePaths.has(cachePath)) {
1098
+ this.#manifestWritePaths.add(cachePath);
1099
+ const vlt = this.#vltPackuments.has(`${f.registry}${f.name}`);
1100
+ void this.#writeManifestCache(cachePath, JSON.stringify(vlt ? { ...mani, __VLT_PACKUMENT: true } : mani));
1101
+ }
1102
+ return mani;
1103
+ };
1104
+ // Nothing local: the in-flight resolve is probably carrying this
1105
+ // key, so it gets a moment before the packument is fetched too
1106
+ if (!selecting && f.registry) {
1107
+ const resolved = await this.#awaitResolved(f.registry, resolveKey, fromPackument);
1108
+ if (resolved)
1109
+ return resolved;
766
1110
  }
767
- return mani;
1111
+ return fromPackument();
768
1112
  }
769
1113
  case 'git': {
770
1114
  const { gitRemote, gitCommittish, remoteURL, gitSelectorParsed, } = f;
@@ -793,19 +1137,20 @@ export class PackageInfoClient {
793
1137
  throw this.#resolveError(s, options, `failed to fetch URL: ${registryErrorMessage(response)}`, { response, url: remoteURL });
794
1138
  }
795
1139
  const buf = response.buffer();
796
- // Compute integrity for remote/git-with-tarball deps
797
- const computed = ssri
798
- .fromData(buf, { algorithms: ['sha512'] })
799
- .toString();
1140
+ // the graph hands this back to extract() as the lockfile
1141
+ // hash: the hash the entry is stored under, or none for an
1142
+ // entry that cannot be verified, which extract() then
1143
+ // fetches again and records
1144
+ const integrity = storedIntegrity(response);
800
1145
  try {
801
1146
  await (await this.getTarPool()).unpack(buf, dir);
802
1147
  }
803
1148
  catch (er) {
804
1149
  throw this.#resolveError(s, options, 'tar unpack failed', { cause: er });
805
1150
  }
806
- // return manifest with computed integrity
807
1151
  const mani = this.#readExtracted(dir, s, options);
808
- mani.dist = { integrity: computed };
1152
+ if (integrity)
1153
+ mani.dist = { integrity };
809
1154
  return mani;
810
1155
  });
811
1156
  }
@@ -1153,10 +1498,14 @@ export class PackageInfoClient {
1153
1498
  // Nothing downstream sees a relative URL: the manifest cache, the graph
1154
1499
  // and the lockfile all get the absolute one.
1155
1500
  const absolutizeTarballs = (paku, base) => {
1156
- for (const { dist } of Object.values(paku.versions)) {
1157
- const tarball = dist?.tarball;
1158
- if (tarball && !/^[a-z][a-z0-9+.-]*:/i.test(tarball)) {
1159
- dist.tarball = String(new URL(tarball, base));
1160
- }
1501
+ for (const manifest of Object.values(paku.versions)) {
1502
+ absolutizeTarball(manifest, base);
1503
+ }
1504
+ };
1505
+ /** Resolve a relative `dist.tarball` against `base`; an absolute one stays. */
1506
+ const absolutizeTarball = (manifest, base) => {
1507
+ const dist = manifest.dist;
1508
+ if (dist?.tarball && !/^[a-z][a-z0-9+.-]*:/i.test(dist.tarball)) {
1509
+ dist.tarball = String(new URL(dist.tarball, base));
1161
1510
  }
1162
1511
  };
@@ -0,0 +1,52 @@
1
+ import type { RegistryClient } from '@vltpkg/registry-client';
2
+ import type { Manifest } from '@vltpkg/types';
3
+ /**
4
+ * Server-side range resolution against a vlt registry's `/-/vlt/resolve`
5
+ * endpoint.
6
+ *
7
+ * One request resolves many `name@range` pairs and streams back the chosen
8
+ * manifests for the whole dependency closure. Records reach the caller as
9
+ * each line arrives, in the breadth-first order the server emits them, so
10
+ * the graph build can place level N while the server still walks level N+1.
11
+ *
12
+ * Everything here fails soft: a registry that does not answer, a request
13
+ * that errors, a stream that dies mid-body, and a record that does not
14
+ * parse all leave the caller with fewer manifests than it asked for, and
15
+ * the per-name path fills the rest in.
16
+ */
17
+ /** The request body `/-/vlt/resolve` takes. */
18
+ export type ResolveRequest = {
19
+ roots: {
20
+ name: string;
21
+ spec: string;
22
+ }[];
23
+ platform?: {
24
+ os?: string;
25
+ cpu?: string;
26
+ libc?: string;
27
+ node?: string;
28
+ };
29
+ tag?: string;
30
+ have?: string[];
31
+ stop?: {
32
+ names?: string[];
33
+ scopes?: string[];
34
+ };
35
+ closure?: boolean;
36
+ };
37
+ /** One resolved version, as the caller receives it. */
38
+ export type ResolveRecord = {
39
+ name: string;
40
+ version: string;
41
+ /** every spec of its level that chose this version */
42
+ requested: string[];
43
+ manifest: Manifest;
44
+ };
45
+ /**
46
+ * Resolve `request` against `registry`, calling `onRecord` for each version
47
+ * the server resolves, as its line arrives. Settles when the stream ends,
48
+ * however it ends: a caller waiting on a record that never came learns that
49
+ * from the request settling, not from an error. Aborting `signal` ends it
50
+ * early, keeping the records that had already arrived.
51
+ */
52
+ export declare const fetchResolve: (client: RegistryClient, registry: string, request: ResolveRequest, onRecord: (record: ResolveRecord) => void, signal?: AbortSignal) => Promise<void>;
@@ -0,0 +1,78 @@
1
+ import { createInterface } from 'node:readline';
2
+ /**
3
+ * Resolve `request` against `registry`, calling `onRecord` for each version
4
+ * the server resolves, as its line arrives. Settles when the stream ends,
5
+ * however it ends: a caller waiting on a record that never came learns that
6
+ * from the request settling, not from an error. Aborting `signal` ends it
7
+ * early, keeping the records that had already arrived.
8
+ */
9
+ export const fetchResolve = async (client, registry, request, onRecord, signal) => {
10
+ if (!request.roots.length)
11
+ return;
12
+ let body;
13
+ try {
14
+ const response = await client.requestStream(new URL('-/vlt/resolve', registry), {
15
+ // POST, not QUERY: CloudFront's allowed-method sets are fixed and
16
+ // none includes QUERY. The registry answers both.
17
+ method: 'POST',
18
+ signal,
19
+ headers: {
20
+ 'content-type': 'application/json',
21
+ accept: 'application/x-ndjson',
22
+ },
23
+ body: JSON.stringify(request),
24
+ });
25
+ if (response.statusCode !== 207) {
26
+ response.body.resume();
27
+ return;
28
+ }
29
+ body = response.body;
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ try {
35
+ // One record per line, so lines are the unit of work: a partial line
36
+ // left by a dead stream is simply never emitted.
37
+ for await (const line of createInterface({ input: body })) {
38
+ const record = parseRecord(line);
39
+ if (record)
40
+ onRecord(record);
41
+ }
42
+ }
43
+ catch {
44
+ // A stream that died mid-body leaves the records it did not carry to
45
+ // the per-name path, the same as specs the server did not resolve.
46
+ body.destroy();
47
+ }
48
+ };
49
+ const parseRecord = (l) => {
50
+ // parsed wire data: nothing about its shape can be assumed
51
+ let record;
52
+ try {
53
+ record = JSON.parse(l);
54
+ }
55
+ catch {
56
+ return;
57
+ }
58
+ const { status, name, requested, manifest } = record;
59
+ if (status !== 200 || typeof name !== 'string')
60
+ return;
61
+ if (!Array.isArray(requested) ||
62
+ !requested.every(s => typeof s === 'string'))
63
+ return;
64
+ if (typeof manifest !== 'object' || manifest === null)
65
+ return;
66
+ const mani = manifest;
67
+ // the manifest must be the package its record names, and carry the
68
+ // version it resolved to: these entries are handed out by key, so a
69
+ // registry mixup would poison the lookup
70
+ if (mani.name !== name || typeof mani.version !== 'string')
71
+ return;
72
+ return {
73
+ name,
74
+ version: mani.version,
75
+ requested: requested,
76
+ manifest: mani,
77
+ };
78
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/package-info",
3
3
  "description": "Resolve and fetch package metadata and tarballs",
4
- "version": "1.3.3",
4
+ "version": "1.3.5",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,18 +13,17 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/error-cause": "1.3.3",
17
- "@vltpkg/git": "1.3.3",
18
- "@vltpkg/output": "1.3.3",
19
- "@vltpkg/package-json": "1.3.3",
20
- "@vltpkg/pick-manifest": "1.3.3",
21
- "@vltpkg/registry-client": "1.3.3",
22
- "@vltpkg/spec": "1.3.3",
23
- "@vltpkg/tar": "1.3.3",
24
- "@vltpkg/types": "1.3.3",
25
- "@vltpkg/workspaces": "1.3.3",
26
- "@vltpkg/xdg": "1.3.3",
27
- "ssri": "^13.0.0",
16
+ "@vltpkg/error-cause": "1.3.5",
17
+ "@vltpkg/git": "1.3.5",
18
+ "@vltpkg/output": "1.3.5",
19
+ "@vltpkg/package-json": "1.3.5",
20
+ "@vltpkg/pick-manifest": "1.3.5",
21
+ "@vltpkg/registry-client": "1.3.5",
22
+ "@vltpkg/spec": "1.3.5",
23
+ "@vltpkg/tar": "1.3.5",
24
+ "@vltpkg/types": "1.3.5",
25
+ "@vltpkg/workspaces": "1.3.5",
26
+ "@vltpkg/xdg": "1.3.5",
28
27
  "tar": "^7.5.2"
29
28
  },
30
29
  "devDependencies": {
@@ -32,8 +31,8 @@
32
31
  "@types/node": "^22.19.2",
33
32
  "@types/pacote": "^11.1.8",
34
33
  "@vltpkg/benchmark": "0.0.0",
35
- "@vltpkg/cache-unzip": "1.3.3",
36
- "@vltpkg/vlt-json": "1.3.3",
34
+ "@vltpkg/cache-unzip": "1.3.5",
35
+ "@vltpkg/vlt-json": "1.3.5",
37
36
  "eslint": "^9.39.1",
38
37
  "pacote": "^21.0.4",
39
38
  "prettier": "^3.7.4",