-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
structUtils.ts
825 lines (704 loc) Β· 27.2 KB
/
structUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
import {PortablePath, toFilename} from '@yarnpkg/fslib';
import querystring from 'querystring';
import semver from 'semver';
import {makeParser} from 'tinylogic';
import {Configuration} from './Configuration';
import {Workspace} from './Workspace';
import * as formatUtils from './formatUtils';
import * as hashUtils from './hashUtils';
import * as miscUtils from './miscUtils';
import * as nodeUtils from './nodeUtils';
import * as structUtils from './structUtils';
import {IdentHash, DescriptorHash, LocatorHash} from './types';
import {Ident, Descriptor, Locator, Package} from './types';
const VIRTUAL_PROTOCOL = `virtual:`;
const VIRTUAL_ABBREVIATE = 5;
const conditionRegex = /(os|cpu|libc)=([a-z0-9_-]+)/;
const conditionParser = makeParser(conditionRegex);
/**
* Creates a package ident.
*
* @param scope The package scope without the `@` prefix (eg. `types`)
* @param name The name of the package
*/
export function makeIdent(scope: string | null, name: string): Ident {
if (scope?.startsWith(`@`))
throw new Error(`Invalid scope: don't prefix it with '@'`);
return {identHash: hashUtils.makeHash<IdentHash>(scope, name), scope, name};
}
/**
* Creates a package descriptor.
*
* @param ident The base ident (see `makeIdent`)
* @param range The range to attach (eg. `^1.0.0`)
*/
export function makeDescriptor(ident: Ident, range: string): Descriptor {
return {identHash: ident.identHash, scope: ident.scope, name: ident.name, descriptorHash: hashUtils.makeHash<DescriptorHash>(ident.identHash, range), range};
}
/**
* Creates a package locator.
*
* @param ident The base ident (see `makeIdent`)
* @param reference The reference to attach (eg. `1.0.0`)
*/
export function makeLocator(ident: Ident, reference: string): Locator {
return {identHash: ident.identHash, scope: ident.scope, name: ident.name, locatorHash: hashUtils.makeHash<LocatorHash>(ident.identHash, reference), reference};
}
/**
* Turns a compatible source to an ident. You won't really have to use this
* function since by virtue of structural inheritance all descriptors and
* locators are already valid idents.
*
* This function is only useful if you absolutely need to remove the non-ident
* fields from a structure before storing it somewhere.
*
* @param source The data structure to convert into an ident.
*/
export function convertToIdent(source: Descriptor | Locator | Package): Ident {
return {identHash: source.identHash, scope: source.scope, name: source.name};
}
/**
* Turns a descriptor into a locator.
*
* Note that this process may be unsafe, as descriptors may reference multiple
* packages, putting them at odd with locators' expected semantic. Only makes
* sense when used with single-resolution protocols, for instance `file:`.
*
* @param descriptor The descriptor to convert into a locator.
*/
export function convertDescriptorToLocator(descriptor: Descriptor): Locator {
return {identHash: descriptor.identHash, scope: descriptor.scope, name: descriptor.name, locatorHash: descriptor.descriptorHash as unknown as LocatorHash, reference: descriptor.range};
}
/**
* Turns a locator into a descriptor.
*
* This should be safe to do regardless of the locator, since all locator
* references are expected to be valid descriptor ranges.
*
* @param locator The locator to convert into a descriptor.
*/
export function convertLocatorToDescriptor(locator: Locator): Descriptor {
return {identHash: locator.identHash, scope: locator.scope, name: locator.name, descriptorHash: locator.locatorHash as unknown as DescriptorHash, range: locator.reference};
}
/**
* Turns a package structure into a simple locator. You won't often need to
* call this function since packages are already valid locators by virtue of
* structural inheritance.
*
* This function is only useful if you absolutely need to remove the
* non-locator fields from a structure before storing it somewhere.
*
* @param pkg The package to convert into a locator.
*/
export function convertPackageToLocator(pkg: Package): Locator {
return {identHash: pkg.identHash, scope: pkg.scope, name: pkg.name, locatorHash: pkg.locatorHash, reference: pkg.reference};
}
/**
* Deep copies a package then change its locator to something else.
*
* @param pkg The source package
* @param locator Its new new locator
*/
export function renamePackage(pkg: Package, locator: Locator): Package {
return {
identHash: locator.identHash,
scope: locator.scope,
name: locator.name,
locatorHash: locator.locatorHash,
reference: locator.reference,
version: pkg.version,
languageName: pkg.languageName,
linkType: pkg.linkType,
conditions: pkg.conditions,
dependencies: new Map(pkg.dependencies),
peerDependencies: new Map(pkg.peerDependencies),
dependenciesMeta: new Map(pkg.dependenciesMeta),
peerDependenciesMeta: new Map(pkg.peerDependenciesMeta),
bin: new Map(pkg.bin),
};
}
/**
* Deep copies a package. The copy will share the same locator as the original.
*
* @param pkg The source package
*/
export function copyPackage(pkg: Package) {
return renamePackage(pkg, pkg);
}
/**
* Creates a new virtual descriptor from a non virtual one.
*
* @param descriptor The descriptor to virtualize
* @param entropy A hash that provides uniqueness to this virtualized descriptor (normally a locator hash)
*/
export function virtualizeDescriptor(descriptor: Descriptor, entropy: string): Descriptor {
if (entropy.includes(`#`))
throw new Error(`Invalid entropy`);
return makeDescriptor(descriptor, `virtual:${entropy}#${descriptor.range}`);
}
/**
* Creates a new virtual package from a non virtual one.
*
* @param pkg The package to virtualize
* @param entropy A hash that provides uniqueness to this virtualized package (normally a locator hash)
*/
export function virtualizePackage(pkg: Package, entropy: string): Package {
if (entropy.includes(`#`))
throw new Error(`Invalid entropy`);
return renamePackage(pkg, makeLocator(pkg, `virtual:${entropy}#${pkg.reference}`));
}
/**
* Returns `true` if the descriptor is virtual.
*/
export function isVirtualDescriptor(descriptor: Descriptor): boolean {
return descriptor.range.startsWith(VIRTUAL_PROTOCOL);
}
/**
* Returns `true` if the locator is virtual.
*/
export function isVirtualLocator(locator: Locator): boolean {
return locator.reference.startsWith(VIRTUAL_PROTOCOL);
}
/**
* Returns a new devirtualized descriptor based on a virtualized descriptor
*/
export function devirtualizeDescriptor(descriptor: Descriptor): Descriptor {
if (!isVirtualDescriptor(descriptor))
throw new Error(`Not a virtual descriptor`);
return makeDescriptor(descriptor, descriptor.range.replace(/^[^#]*#/, ``));
}
/**
* Returns a new devirtualized locator based on a virtualized locator
* @param locator the locator
*/
export function devirtualizeLocator(locator: Locator): Locator {
if (!isVirtualLocator(locator))
throw new Error(`Not a virtual descriptor`);
return makeLocator(locator, locator.reference.replace(/^[^#]*#/, ``));
}
/**
* Some descriptors only make sense when bound with some internal state. For
* instance that would be the case for the `file:` ranges, which require to
* be bound to their parent packages in order to resolve relative paths from
* the right location.
*
* This function will apply the specified parameters onto the requested
* descriptor, but only if it didn't get bound before (important to handle the
* case where we replace a descriptor by another, since when that happens the
* replacement has probably been already bound).
*
* @param descriptor The original descriptor
* @param params The parameters to encode in the range
*/
export function bindDescriptor(descriptor: Descriptor, params: {[key: string]: string}) {
if (descriptor.range.includes(`::`))
return descriptor;
return makeDescriptor(descriptor, `${descriptor.range}::${querystring.stringify(params)}`);
}
/**
* Some locators only make sense when bound with some internal state. For
* instance that would be the case for the `file:` references, which require to
* be bound to their parent packages in order to resolve relative paths from
* the right location.
*
* This function will apply the specified parameters onto the requested
* locator, but only if it didn't get bound before (important to handle the
* case where we replace a locator by another, since when that happens the
* replacement has probably been already bound).
*
* @param locator The original locator
* @param params The parameters to encode in the reference
*/
export function bindLocator(locator: Locator, params: {[key: string]: string}) {
if (locator.reference.includes(`::`))
return locator;
return makeLocator(locator, `${locator.reference}::${querystring.stringify(params)}`);
}
/**
* Returns `true` if the idents are equal
*/
export function areIdentsEqual(a: Ident, b: Ident) {
return a.identHash === b.identHash;
}
/**
* Returns `true` if the descriptors are equal
*/
export function areDescriptorsEqual(a: Descriptor, b: Descriptor) {
return a.descriptorHash === b.descriptorHash;
}
/**
* Returns `true` if the locators are equal
*/
export function areLocatorsEqual(a: Locator, b: Locator) {
return a.locatorHash === b.locatorHash;
}
/**
* Virtual packages are considered equivalent when they belong to the same
* package identity and have the same dependencies. Note that equivalence
* is not the same as equality, as the references may be different.
*/
export function areVirtualPackagesEquivalent(a: Package, b: Package) {
if (!isVirtualLocator(a))
throw new Error(`Invalid package type`);
if (!isVirtualLocator(b))
throw new Error(`Invalid package type`);
if (!areIdentsEqual(a, b))
return false;
if (a.dependencies.size !== b.dependencies.size)
return false;
for (const dependencyDescriptorA of a.dependencies.values()) {
const dependencyDescriptorB = b.dependencies.get(dependencyDescriptorA.identHash);
if (!dependencyDescriptorB)
return false;
if (!areDescriptorsEqual(dependencyDescriptorA, dependencyDescriptorB)) {
return false;
}
}
return true;
}
/**
* Parses a string into an ident.
*
* Throws an error if the ident cannot be parsed.
*
* @param string The ident string (eg. `@types/lodash`)
*/
export function parseIdent(string: string): Ident {
const ident = tryParseIdent(string);
if (!ident)
throw new Error(`Invalid ident (${string})`);
return ident;
}
/**
* Parses a string into an ident.
*
* Returns `null` if the ident cannot be parsed.
*
* @param string The ident string (eg. `@types/lodash`)
*/
export function tryParseIdent(string: string): Ident | null {
const match = string.match(/^(?:@([^/]+?)\/)?([^/]+)$/);
if (!match)
return null;
const [, scope, name] = match;
const realScope = typeof scope !== `undefined`
? scope
: null;
return makeIdent(realScope, name);
}
/**
* Parses a `string` into a descriptor
*
* Throws an error if the descriptor cannot be parsed.
*
* @param string The descriptor string (eg. `lodash@^1.0.0`)
* @param strict If `false`, the range is optional (`unknown` will be used as fallback)
*/
export function parseDescriptor(string: string, strict: boolean = false): Descriptor {
const descriptor = tryParseDescriptor(string, strict);
if (!descriptor)
throw new Error(`Invalid descriptor (${string})`);
return descriptor;
}
/**
* Parses a `string` into a descriptor
*
* Returns `null` if the descriptor cannot be parsed.
*
* @param string The descriptor string (eg. `lodash@^1.0.0`)
* @param strict If `false`, the range is optional (`unknown` will be used as fallback)
*/
export function tryParseDescriptor(string: string, strict: boolean = false): Descriptor | null {
const match = strict
? string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))$/)
: string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))?$/);
if (!match)
return null;
const [, scope, name, range] = match;
if (range === `unknown`)
throw new Error(`Invalid range (${string})`);
const realScope = typeof scope !== `undefined`
? scope
: null;
const realRange = typeof range !== `undefined`
? range
: `unknown`;
return makeDescriptor(makeIdent(realScope, name), realRange);
}
/**
* Parses a `string` into a locator
*
* Throws an error if the locator cannot be parsed.
*
* @param string The locator `string` (eg. `lodash@1.0.0`)
* @param strict If `false`, the reference is optional (`unknown` will be used as fallback)
*/
export function parseLocator(string: string, strict: boolean = false): Locator {
const locator = tryParseLocator(string, strict);
if (!locator)
throw new Error(`Invalid locator (${string})`);
return locator;
}
/**
* Parses a `string` into a locator
*
* Returns `null` if the locator cannot be parsed.
*
* @param string The locator string (eg. `lodash@1.0.0`)
* @param strict If `false`, the reference is optional (`unknown` will be used as fallback)
*/
export function tryParseLocator(string: string, strict: boolean = false): Locator | null {
const match = strict
? string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))$/)
: string.match(/^(?:@([^/]+?)\/)?([^/]+?)(?:@(.+))?$/);
if (!match)
return null;
const [, scope, name, reference] = match;
if (reference === `unknown`)
throw new Error(`Invalid reference (${string})`);
const realScope = typeof scope !== `undefined`
? scope
: null;
const realReference = typeof reference !== `undefined`
? reference
: `unknown`;
return makeLocator(makeIdent(realScope, name), realReference);
}
type ParseRangeOptions = {
/** Throw an error if bindings are missing */
requireBindings?: boolean;
/** Throw an error if the protocol is missing or is not the specified one */
requireProtocol?: boolean | string;
/** Throw an error if the source is missing */
requireSource?: boolean;
/** Whether to parse the selector as a query string */
parseSelector?: boolean;
};
type ParseRangeReturnType<Opts extends ParseRangeOptions> =
& ({params: Opts extends {requireBindings: true} ? querystring.ParsedUrlQuery : querystring.ParsedUrlQuery | null})
& ({protocol: Opts extends {requireProtocol: true | string} ? string : string | null})
& ({source: Opts extends {requireSource: true} ? string : string | null})
& ({selector: Opts extends {parseSelector: true} ? querystring.ParsedUrlQuery : string});
/**
* Parses a range into its constituents. Ranges typically follow these forms,
* with both `protocol` and `bindings` being optionals:
*
* <protocol>:<selector>::<bindings>
* <protocol>:<source>#<selector>::<bindings>
*
* The selector is intended to "refine" the source, and is required. The source
* itself is optional (for instance we don't need it for npm packages, but we
* do for git dependencies).
*/
export function parseRange<Opts extends ParseRangeOptions>(range: string, opts?: Opts): ParseRangeReturnType<Opts> {
const match = range.match(/^([^#:]*:)?((?:(?!::)[^#])*)(?:#((?:(?!::).)*))?(?:::(.*))?$/);
if (match === null)
throw new Error(`Invalid range (${range})`);
const protocol = typeof match[1] !== `undefined`
? match[1]
: null;
if (typeof opts?.requireProtocol === `string` && protocol !== opts!.requireProtocol)
throw new Error(`Invalid protocol (${protocol})`);
else if (opts?.requireProtocol && protocol === null)
throw new Error(`Missing protocol (${protocol})`);
const source = typeof match[3] !== `undefined`
? decodeURIComponent(match[2])
: null;
if (opts?.requireSource && source === null)
throw new Error(`Missing source (${range})`);
const rawSelector = typeof match[3] !== `undefined`
? decodeURIComponent(match[3])
: decodeURIComponent(match[2]);
const selector = (opts?.parseSelector)
? querystring.parse(rawSelector)
: rawSelector;
const params = typeof match[4] !== `undefined`
? querystring.parse(match[4])
: null;
return {
// @ts-expect-error
protocol,
// @ts-expect-error
source,
// @ts-expect-error
selector,
// @ts-expect-error
params,
};
}
/**
* File-style ranges are bound to a parent locators that we need in order to
* resolve relative paths to the location of their parent packages. This
* function wraps `parseRange` to automatically extract the parent locator
* from the bindings and return it along with the selector.
*/
export function parseFileStyleRange(range: string, {protocol}: {protocol: string}) {
const {selector, params} = parseRange(range, {
requireProtocol: protocol,
requireBindings: true,
});
if (typeof params.locator !== `string`)
throw new Error(`Assertion failed: Invalid bindings for ${range}`);
const parentLocator = parseLocator(params.locator, true);
const path = selector as PortablePath;
return {parentLocator, path};
}
function encodeUnsafeCharacters(str: string) {
str = str.replace(/%/g, `%25`);
str = str.replace(/:/g, `%3A`);
str = str.replace(/#/g, `%23`);
return str;
}
function hasParams(params: querystring.ParsedUrlQuery | null): params is querystring.ParsedUrlQuery {
if (params === null)
return false;
return Object.entries(params).length > 0;
}
/**
* Turn the components returned by `parseRange` back into a string. Check
* `parseRange` for more details.
*/
export function makeRange({protocol, source, selector, params}: {protocol: string | null, source: string | null, selector: string, params: querystring.ParsedUrlQuery | null}) {
let range = ``;
if (protocol !== null)
range += `${protocol}`;
if (source !== null)
range += `${encodeUnsafeCharacters(source)}#`;
range += encodeUnsafeCharacters(selector);
if (hasParams(params))
range += `::${querystring.stringify(params)}`;
return range;
}
/**
* Some bindings are internal-only and not meant to be displayed anywhere (for
* instance that's the case with the parent locator bound to the `file:` ranges).
*
* this function strips them from a range.
*/
export function convertToManifestRange(range: string) {
const {params, protocol, source, selector} = parseRange(range);
for (const name in params)
if (name.startsWith(`__`))
delete params[name];
return makeRange({protocol, source, params, selector});
}
/**
* Returns a string from an ident (eg. `@types/lodash`).
*/
export function stringifyIdent(ident: Ident) {
if (ident.scope) {
return `@${ident.scope}/${ident.name}`;
} else {
return `${ident.name}`;
}
}
/**
* Returns a string from a descriptor (eg. `@types/lodash@^1.0.0`).
*/
export function stringifyDescriptor(descriptor: Descriptor) {
if (descriptor.scope) {
return `@${descriptor.scope}/${descriptor.name}@${descriptor.range}`;
} else {
return `${descriptor.name}@${descriptor.range}`;
}
}
/**
* Returns a string from a descriptor (eg. `@types/lodash@1.0.0`).
*/
export function stringifyLocator(locator: Locator) {
if (locator.scope) {
return `@${locator.scope}/${locator.name}@${locator.reference}`;
} else {
return `${locator.name}@${locator.reference}`;
}
}
/**
* Returns a string from an ident, formatted as a slug (eg. `@types-lodash`).
*/
export function slugifyIdent(ident: Ident) {
if (ident.scope !== null) {
return `@${ident.scope}-${ident.name}`;
} else {
return ident.name;
}
}
/**
* Returns a string from a locator, formatted as a slug (eg. `@types-lodash-npm-1.0.0-abcdef1234`).
*/
export function slugifyLocator(locator: Locator) {
const {protocol, selector} = parseRange(locator.reference);
const humanProtocol = protocol !== null
? protocol.replace(/:$/, ``)
: `exotic`;
const humanVersion = semver.valid(selector);
const humanReference = humanVersion !== null
? `${humanProtocol}-${humanVersion}`
: `${humanProtocol}`;
// 10 hex characters means that 47 different entries have 10^-9 chances of
// causing a hash collision. Since this hash is joined with the package name
// (making it highly unlikely you'll have more than a handful of instances
// of any single package), this should provide a good enough guard in most
// cases.
//
// Also note that eCryptfs eats some bytes, so the theoretical maximum for a
// file size is around 140 bytes (but we don't need as much, as explained).
const hashTruncate = 10;
const slug = locator.scope
? `${slugifyIdent(locator)}-${humanReference}-${locator.locatorHash.slice(0, hashTruncate)}`
: `${slugifyIdent(locator)}-${humanReference}-${locator.locatorHash.slice(0, hashTruncate)}`;
return toFilename(slug);
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param ident The ident to pretty print
*/
export function prettyIdent(configuration: Configuration, ident: Ident): string {
if (ident.scope) {
return `${formatUtils.pretty(configuration, `@${ident.scope}/`, formatUtils.Type.SCOPE)}${formatUtils.pretty(configuration, ident.name, formatUtils.Type.NAME)}`;
} else {
return `${formatUtils.pretty(configuration, ident.name, formatUtils.Type.NAME)}`;
}
}
function prettyRangeNoColors(range: string): string {
if (range.startsWith(VIRTUAL_PROTOCOL)) {
const nested = prettyRangeNoColors(range.substring(range.indexOf(`#`) + 1));
const abbrev = range.substring(VIRTUAL_PROTOCOL.length, VIRTUAL_PROTOCOL.length + VIRTUAL_ABBREVIATE);
// I'm not satisfied of how the virtual packages appear in the output
// eslint-disable-next-line no-constant-condition
return false ? `${nested} (virtual:${abbrev})` : `${nested} [${abbrev}]`;
} else {
return range.replace(/\?.*/, `?[...]`);
}
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param ident The range to pretty print
*/
export function prettyRange(configuration: Configuration, range: string): string {
return `${formatUtils.pretty(configuration, prettyRangeNoColors(range), formatUtils.Type.RANGE)}`;
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param descriptor The descriptor to pretty print
*/
export function prettyDescriptor(configuration: Configuration, descriptor: Descriptor): string {
return `${prettyIdent(configuration, descriptor)}${formatUtils.pretty(configuration, `@`, formatUtils.Type.RANGE)}${prettyRange(configuration, descriptor.range)}`;
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param reference The reference to pretty print
*/
export function prettyReference(configuration: Configuration, reference: string) {
return `${formatUtils.pretty(configuration, prettyRangeNoColors(reference), formatUtils.Type.REFERENCE)}`;
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param locator The locator to pretty print
*/
export function prettyLocator(configuration: Configuration, locator: Locator): string {
return `${prettyIdent(configuration, locator)}${formatUtils.pretty(configuration, `@`, formatUtils.Type.REFERENCE)}${prettyReference(configuration, locator.reference)}`;
}
/**
* Returns a string that is suitable to be printed to stdout. It will never
* be colored.
*
* @param locator The locator to pretty print
*/
export function prettyLocatorNoColors(locator: Locator) {
return `${stringifyIdent(locator)}@${prettyRangeNoColors(locator.reference)}`;
}
/**
* Sorts a list of descriptors, first by their idents then by their ranges.
*/
export function sortDescriptors(descriptors: Iterable<Descriptor>) {
return miscUtils.sortMap(descriptors, [
descriptor => stringifyIdent(descriptor),
descriptor => descriptor.range,
]);
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param workspace The workspace to pretty print
*/
export function prettyWorkspace(configuration: Configuration, workspace: Workspace) {
return prettyIdent(configuration, workspace.locator);
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param descriptor The descriptor to pretty print
* @param locator The locator is resolves to
*/
export function prettyResolution(configuration: Configuration, descriptor: Descriptor, locator: Locator | null): string {
const devirtualizedDescriptor = isVirtualDescriptor(descriptor)
? devirtualizeDescriptor(descriptor)
: descriptor;
if (locator === null) {
return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} β ${formatUtils.mark(configuration).Cross}`;
} else if (devirtualizedDescriptor.identHash === locator.identHash) {
return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} β ${prettyReference(configuration, locator.reference)}`;
} else {
return `${structUtils.prettyDescriptor(configuration, devirtualizedDescriptor)} β ${prettyLocator(configuration, locator)}`;
}
}
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param locator The locator to pretty print
* @param descriptor The descriptor that depends on it
*/
export function prettyDependent(configuration: Configuration, locator: Locator, descriptor: Descriptor | null) {
if (descriptor === null) {
return `${prettyLocator(configuration, locator)}`;
} else {
return `${prettyLocator(configuration, locator)} (via ${structUtils.prettyRange(configuration, descriptor.range)})`;
}
}
/**
* The presence of a `node_modules` directory in the path is extremely common
* in the JavaScript ecosystem to denote whether a path belongs to a vendor
* or not. I considered using a more generic path for packages that aren't
* always JS-only (such as when using the Git fetcher), but that unfortunately
* caused various JS apps to start showing errors when working with git repos.
*
* As a result, all packages from all languages will follow this convention. At
* least it'll be consistent, and linkers will always have the ability to remap
* them to a different location if that's a critical requirement.
*/
export function getIdentVendorPath(ident: Ident) {
return `node_modules/${stringifyIdent(ident)}` as PortablePath;
}
/**
* Returns whether the given package is compatible with the specified environment.
*/
export function isPackageCompatible(pkg: Package, architectures: nodeUtils.ArchitectureSet) {
if (!pkg.conditions)
return true;
return conditionParser(pkg.conditions, specifier => {
const [, name, value] = specifier.match(conditionRegex)!;
const supported = architectures[name as keyof typeof architectures];
return supported ? supported.includes(value) : true;
});
}