@vltpkg/spec 1.0.0-rc.2 → 1.0.0-rc.23

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.
@@ -1,797 +0,0 @@
1
- import { error, typeError } from '@vltpkg/error-cause';
2
- import { parseRange } from '@vltpkg/semver';
3
- export * from "./types.js";
4
- export const kCustomInspect = Symbol.for('nodejs.util.inspect.custom');
5
- export const defaultRegistry = 'https://registry.npmjs.org/';
6
- export const defaultRegistries = {
7
- npm: defaultRegistry,
8
- gh: 'https://npm.pkg.github.com/',
9
- };
10
- export const defaultJsrRegistries = { jsr: 'https://npm.jsr.io/' };
11
- export const defaultGitHosts = {
12
- github: 'git+ssh://git@github.com:$1/$2.git',
13
- bitbucket: 'git+ssh://git@bitbucket.org:$1/$2.git',
14
- gitlab: 'git+ssh://git@gitlab.com:$1/$2.git',
15
- gist: 'git+ssh://git@gist.github.com/$1.git',
16
- };
17
- export const defaultGitHostArchives = {
18
- github: 'https://api.github.com/repos/$1/$2/tarball/$committish',
19
- bitbucket: 'https://bitbucket.org/$1/$2/get/$committish.tar.gz',
20
- gist: 'https://codeload.github.com/gist/$1/tar.gz/$committish',
21
- gitlab: 'https://gitlab.com/$1/$2/repository/archive.tar.gz?ref=$committish',
22
- };
23
- /**
24
- * These are just for legacy support of urls that are supported by npm
25
- * and observed in the wild.
26
- *
27
- * Not configurable, because no more will be added. If you wish to define
28
- * custom git hosts, use it with the `'git-hosts'` and `'git-host-archives'`
29
- * options.
30
- */
31
- export const gitHostWebsites = {
32
- github: 'https://github.com/',
33
- bitbucket: 'https://bitbucket.org/',
34
- gist: 'https://gist.github.com/',
35
- gitlab: 'https://gitlab.com/',
36
- };
37
- export const defaultScopeRegistries = {
38
- '@jsr': 'https://npm.jsr.io/',
39
- };
40
- export const getOptions = (options) => ({
41
- catalog: {},
42
- catalogs: {},
43
- ...options,
44
- 'jsr-registries': {
45
- ...(options?.['jsr-registries'] ?? {}),
46
- ...defaultJsrRegistries,
47
- },
48
- registry: options?.registry ?? defaultRegistry,
49
- 'scope-registries': options?.['scope-registries'] ?? {},
50
- 'git-hosts': options?.['git-hosts'] ?
51
- {
52
- ...defaultGitHosts,
53
- ...options['git-hosts'],
54
- }
55
- : defaultGitHosts,
56
- registries: options?.registries ?? {},
57
- 'git-host-archives': options?.['git-host-archives'] ?
58
- {
59
- ...defaultGitHostArchives,
60
- ...options['git-host-archives'],
61
- }
62
- : defaultGitHostArchives,
63
- });
64
- /**
65
- * Various nameless scenarios that are handled in the
66
- * standard spec parsing and should return an unknown name.
67
- *
68
- * Returns `true` if the name can not be inferred, `false` otherwise.
69
- */
70
- const startsWithSpecIdentifier = (spec, options) => spec.startsWith('/') ||
71
- spec.startsWith('./') ||
72
- spec.startsWith('../') ||
73
- spec.startsWith('file:') ||
74
- spec.startsWith('http:') ||
75
- spec.startsWith('https:') ||
76
- spec.startsWith('workspace:') ||
77
- spec.startsWith('catalog:') ||
78
- spec.startsWith('git@') ||
79
- spec.startsWith('git://') ||
80
- spec.startsWith('git+ssh://') ||
81
- spec.startsWith('git+http://') ||
82
- spec.startsWith('git+https://') ||
83
- spec.startsWith('git+file://') ||
84
- spec.startsWith('git@github.com') ||
85
- spec.startsWith('registry:') ||
86
- spec.startsWith('npm:') ||
87
- spec.startsWith('gh:') ||
88
- // anything that starts with a known git host key, or a
89
- // custom registered registry protocol e.g: `github:`, `custom:`
90
- [
91
- ...Object.keys(options['git-hosts']),
92
- ...Object.keys(options.registries),
93
- ...Object.keys(options['jsr-registries']),
94
- ].some(key => spec.startsWith(`${key}:`));
95
- /**
96
- * Returns the location in which the first `@` value is found in a given
97
- * string, also takes into account that a string starting with @ is
98
- * using a scoped-name.
99
- */
100
- const findFirstAt = (spec, hasScope) => spec.indexOf('@', hasScope ? 1 : 0);
101
- /**
102
- * Return `true` if a given spec string is likely to be a git spec.
103
- */
104
- const findGitIdentifier = (spec) => spec.indexOf('#') > 2;
105
- /**
106
- * Return `true` if a given spec string is likely to be a file spec.
107
- */
108
- const findFileIdentifier = (spec) => spec.includes('/');
109
- export const isSpec = (spec) => typeof spec === 'object' &&
110
- spec !== null &&
111
- 'spec' in spec &&
112
- 'bareSpec' in spec &&
113
- 'name' in spec &&
114
- 'type' in spec &&
115
- 'options' in spec &&
116
- typeof spec.spec === 'string' &&
117
- typeof spec.bareSpec === 'string' &&
118
- typeof spec.name === 'string';
119
- /**
120
- * The base, isomorphic Spec implementation.
121
- */
122
- export class Spec {
123
- static parse(spec, bareOrOptions, options) {
124
- return typeof spec === 'object' ? spec : (new this(spec, bareOrOptions, options));
125
- }
126
- static parseArgs(specOrBareSpec, opts) {
127
- const options = getOptions(opts ?? {});
128
- if (startsWithSpecIdentifier(specOrBareSpec, options)) {
129
- const parsed = this.parse('(unknown)', specOrBareSpec, options);
130
- // try to look into a potential parsed subspec for a name
131
- if (parsed.subspec) {
132
- const { namedJsrRegistry: jsrHost } = parsed;
133
- if (!jsrHost) {
134
- parsed.name = parsed.subspec.name;
135
- }
136
- parsed.spec = `${parsed.name}@${parsed.bareSpec}`;
137
- }
138
- return parsed;
139
- }
140
- else {
141
- const hasScope = specOrBareSpec.startsWith('@');
142
- const at = findFirstAt(specOrBareSpec, hasScope);
143
- if (at > -1) {
144
- return this.parse(specOrBareSpec.substring(0, at), specOrBareSpec.substring(at + 1), options);
145
- }
146
- else if (findGitIdentifier(specOrBareSpec) ||
147
- (!hasScope && findFileIdentifier(specOrBareSpec))) {
148
- return this.parse('(unknown)', specOrBareSpec, options);
149
- }
150
- else {
151
- // doesn't have an @, so it's just a name with no version
152
- return this.parse(`${specOrBareSpec}@`, options);
153
- }
154
- }
155
- }
156
- static nodejsDependencies;
157
- type;
158
- spec;
159
- options;
160
- name;
161
- scope;
162
- scopeRegistry;
163
- bareSpec;
164
- gitRemote;
165
- gitSelector;
166
- gitSelectorParsed;
167
- gitCommittish;
168
- namedGitHost;
169
- namedGitHostPath;
170
- workspaceSpec;
171
- workspace;
172
- namedRegistry;
173
- namedJsrRegistry;
174
- registry;
175
- registrySpec;
176
- conventionalRegistryTarball;
177
- semver;
178
- range;
179
- distTag;
180
- remoteURL;
181
- file;
182
- catalog;
183
- subspec;
184
- overridden = false;
185
- #final;
186
- #toString;
187
- /**
188
- * Return the final entry in the chain of subspecs
189
- * When deciding which thing to actually fetch, spec.final is the thing
190
- * to look at.
191
- */
192
- get final() {
193
- if (this.#final)
194
- return this.#final;
195
- const final = this.subspec ? this.subspec.final : this;
196
- /* c8 ignore start - impossible */
197
- if (final.type === 'catalog') {
198
- throw error('invalid Spec.final value, type is "catalog"');
199
- }
200
- /* c8 ignore stop */
201
- return (this.#final = final);
202
- }
203
- /**
204
- * Normally, the string value of a Spec is just the string passed in to
205
- * be parsed. However, in the case of a chain of subspecs, like
206
- * `foo@npm:bar@npm:baz@npm:quux@latest`, this simplifies out the middle
207
- * parts of the chain, returning just `foo@npm:quux@latest`
208
- */
209
- toString() {
210
- if (this.#toString !== undefined)
211
- return this.#toString;
212
- let sub = this;
213
- // we want the SECOND from the last in the chain
214
- while (sub.subspec?.subspec)
215
- sub = sub.subspec;
216
- if (sub.subspec && sub.subspec.type !== 'registry')
217
- sub = sub.subspec;
218
- return (this.#toString = this.name + '@' + sub.bareSpec);
219
- }
220
- constructor(spec, bareOrOptions, options = {}) {
221
- if (bareOrOptions && typeof bareOrOptions === 'object') {
222
- options = bareOrOptions;
223
- bareOrOptions = undefined;
224
- }
225
- this.options = getOptions(options);
226
- if (typeof bareOrOptions === 'string') {
227
- this.name = spec;
228
- this.#parseScope(spec);
229
- this.bareSpec = bareOrOptions;
230
- this.spec = `${this.name}@${bareOrOptions}`;
231
- }
232
- else {
233
- this.spec = spec;
234
- // Check if this spec starts with a known registry identifier
235
- // but exclude git specs like 'git@github:a/b'
236
- if (!spec.startsWith('git@') &&
237
- startsWithSpecIdentifier(spec, this.options) &&
238
- spec.includes(':') &&
239
- [
240
- ...Object.keys(this.options.registries),
241
- ...Object.keys(defaultRegistries),
242
- ].some(key => spec.startsWith(`${key}:`))) {
243
- // For specs like 'gh:@octocat/hello-world@1.0.0', don't split at the @
244
- // Instead, set a temporary name and let the registry logic handle it
245
- this.name = spec;
246
- this.bareSpec = spec;
247
- }
248
- else {
249
- const hasScope = spec.startsWith('@');
250
- let at = findFirstAt(spec, hasScope);
251
- if (at === -1) {
252
- // assume that an unadorned spec is just a name at the default
253
- // registry
254
- at = spec.length;
255
- spec += '@';
256
- }
257
- this.name = spec.substring(0, at);
258
- if (hasScope)
259
- this.#parseScope(this.name);
260
- this.bareSpec = spec.substring(at + 1);
261
- }
262
- }
263
- if (this.bareSpec.startsWith('catalog:')) {
264
- this.catalog = this.bareSpec.substring('catalog:'.length);
265
- const catalog = this.catalog ?
266
- this.options.catalogs[this.catalog]
267
- : this.options.catalog;
268
- if (!catalog) {
269
- throw this.#error('Named catalog not found', {
270
- name: this.catalog,
271
- validOptions: Object.keys(this.options.catalogs),
272
- });
273
- }
274
- const sub = catalog[this.name];
275
- if (!sub) {
276
- throw this.#error('Name not found in catalog', {
277
- name: this.name,
278
- validOptions: Object.keys(catalog),
279
- });
280
- }
281
- this.subspec = Spec.parse(this.name, sub);
282
- this.type = 'catalog';
283
- return;
284
- }
285
- // legacy affordance: allow project urls like
286
- // 'https://github.com/user/project#commitish' because npm suports it and
287
- // this pattern is observed in the wild.
288
- if (this.bareSpec.startsWith('https://')) {
289
- for (const [name, origin] of Object.entries(gitHostWebsites)) {
290
- if (this.bareSpec.startsWith(origin)) {
291
- const parsed = new URL(this.bareSpec);
292
- const [user, project] = parsed.pathname
293
- .replace(/\.git$/, '')
294
- .replace(/\/+/g, ' ')
295
- .trim()
296
- .split(' ');
297
- if (user && project) {
298
- this.bareSpec = `${name}:${user}/${project}${parsed.hash}`;
299
- this.spec = `${this.name}@${this.bareSpec}`;
300
- break;
301
- }
302
- }
303
- }
304
- }
305
- if (this.bareSpec.startsWith('workspace:')) {
306
- this.type = 'workspace';
307
- const ws = this.bareSpec.substring('workspace:'.length).trim();
308
- const w = ws.lastIndexOf('@');
309
- if (w === -1) {
310
- this.workspace = this.name;
311
- }
312
- else {
313
- const wsName = ws.substring(0, w);
314
- if (!wsName ||
315
- wsName === '*' ||
316
- wsName === '~' ||
317
- wsName === '^' ||
318
- (wsName.startsWith('@') ?
319
- wsName.split('/').length !== 2 ||
320
- wsName.substring(1).includes('@')
321
- : wsName.includes('@'))) {
322
- throw this.#error('workspace: name must be a path or valid package name', { found: wsName });
323
- }
324
- this.workspace = wsName;
325
- }
326
- // workspace: is the same as workspace:*
327
- const wss = w === -1 ? ws : ws.substring(w + 1) || '*';
328
- const range = wss === '*' ? undefined : parseRange(wss);
329
- if (wss !== '*' && wss !== '~' && wss !== '^' && !range) {
330
- throw this.#error('workspace: spec must be one of *, ~, or ^, or a valid semver range', {
331
- found: wss,
332
- wanted: `'*'|'~'|'^'|SemverRange`,
333
- });
334
- }
335
- this.workspaceSpec = wss;
336
- if (range) {
337
- this.semver = wss;
338
- this.range = range;
339
- }
340
- return;
341
- }
342
- if (this.bareSpec.startsWith('git://') ||
343
- this.bareSpec.startsWith('git+ssh://') ||
344
- this.bareSpec.startsWith('git+http://') ||
345
- this.bareSpec.startsWith('git+https://') ||
346
- this.bareSpec.startsWith('git+file://') ||
347
- // legacy affordance
348
- this.bareSpec.startsWith('git@github.com')) {
349
- if (this.bareSpec.startsWith('git@')) {
350
- this.bareSpec = `git+ssh://${this.bareSpec}`;
351
- this.spec = `${this.name}@${this.bareSpec}`;
352
- }
353
- this.type = 'git';
354
- // see if it's one of the known named hosts, and if so, prefer
355
- // the shorter syntax.
356
- for (const [name, host] of Object.entries(this.options['git-hosts'])) {
357
- const s = host.indexOf('$');
358
- if (s > 0 && this.bareSpec.startsWith(host.substring(0, s))) {
359
- const p = this.bareSpec
360
- .substring(s)
361
- .replace(/\.git(#.*)?$/, '$1');
362
- this.bareSpec = `${name}:${p}`;
363
- this.spec = `${this.name}@${this.bareSpec}`;
364
- this.#parseHostedGit(name, host);
365
- this.type = 'git';
366
- return;
367
- }
368
- }
369
- this.#parseGitSelector(this.bareSpec);
370
- return;
371
- }
372
- // Check registries before git hosts to avoid conflicts
373
- const regs = Object.entries(this.options.registries);
374
- if (!this.options.registries.npm) {
375
- regs.push(['npm', this.options.registry]);
376
- }
377
- if (!this.options.registries.gh) {
378
- regs.push(['gh', defaultRegistries.gh]);
379
- }
380
- if (this.bareSpec.startsWith('registry:')) {
381
- const reg = this.bareSpec.substring('registry:'.length);
382
- const h = reg.indexOf('#');
383
- if (h === -1) {
384
- throw this.#error('registry: must include name/version');
385
- }
386
- this.type = 'registry';
387
- let url = reg.substring(0, h);
388
- if (!url.endsWith('/'))
389
- url += '/';
390
- const regSpec = reg.substring(h + 1);
391
- for (let [name, u] of regs) {
392
- if (!u.endsWith('/')) {
393
- u += '/';
394
- this.options.registries[name] = u;
395
- }
396
- if (u === url)
397
- this.namedRegistry = name;
398
- }
399
- this.#parseRegistrySpec(regSpec, url);
400
- this.#guessRegistryTarball();
401
- return;
402
- }
403
- for (const [host, url] of regs) {
404
- const h = `${host}:`;
405
- if (this.bareSpec.startsWith(h)) {
406
- this.type = 'registry';
407
- this.namedRegistry = host;
408
- this.#parseRegistrySpec(this.bareSpec.substring(h.length), url).namedRegistry ??= host;
409
- // If we parsed a spec identifier, update the name and spec format
410
- if (this.subspec && this.name === this.bareSpec) {
411
- this.name = this.subspec.name;
412
- this.spec = `${this.name}@${this.bareSpec}`;
413
- }
414
- this.#guessRegistryTarball();
415
- return;
416
- }
417
- }
418
- // spooky
419
- const ghosts = Object.entries(this.options['git-hosts']);
420
- for (const [name, template] of ghosts) {
421
- if (this.#parseHostedGit(name, template)) {
422
- this.type = 'git';
423
- return;
424
- }
425
- }
426
- const jsrs = Object.entries(this.options['jsr-registries']);
427
- for (const [host, url] of jsrs) {
428
- const h = `${host}:`;
429
- if (this.bareSpec.startsWith(h)) {
430
- this.type = 'registry';
431
- this.namedJsrRegistry = host;
432
- this.#parseJsrRegistrySpec(this.bareSpec.substring(h.length), url).namedJsrRegistry ??= host;
433
- return;
434
- }
435
- }
436
- if (this.bareSpec.startsWith('https://') ||
437
- this.bareSpec.startsWith('http://')) {
438
- this.remoteURL = this.bareSpec;
439
- this.type = 'remote';
440
- return;
441
- }
442
- // explicit file: url
443
- if (this.bareSpec.startsWith('file:')) {
444
- this.type = 'file';
445
- const [path, uri] = getNormalizeFile(this.constructor.nodejsDependencies)(this.bareSpec, this);
446
- this.file = path;
447
- this.bareSpec = uri.replace(/\/+$/, '');
448
- this.spec = `${this.name}@${this.bareSpec}`;
449
- return;
450
- }
451
- // legacy! once upon a time, `user/project` was a shorthand for pulling
452
- // packages from github, instead of the more verbose and explicit
453
- // `github:user/project`.
454
- if (!this.bareSpec.startsWith('./') &&
455
- !this.bareSpec.startsWith('../') &&
456
- this.options['git-hosts'].github) {
457
- const hash = this.bareSpec.indexOf('#');
458
- const up = hash === -1 ? this.bareSpec : this.bareSpec.substring(0, hash);
459
- if (up.split('/').length === 2) {
460
- this.bareSpec = `github:${this.bareSpec}`;
461
- this.spec = `${this.name}@${this.bareSpec}`;
462
- this.#parseHostedGit('github', this.options['git-hosts'].github);
463
- this.type = 'git';
464
- return;
465
- }
466
- }
467
- // if it contains a / and isn't picked up in the github shorthand,
468
- // then convert to file: specifier
469
- if (this.bareSpec.includes('/') ||
470
- this.bareSpec === '.' ||
471
- this.bareSpec === '..') {
472
- this.type = 'file';
473
- const [file, uri] = getNormalizeFile(this.constructor.nodejsDependencies)(`file:${this.bareSpec}`, this);
474
- this.bareSpec = uri;
475
- this.spec = `${this.name}@${this.bareSpec}`;
476
- this.file = file;
477
- return;
478
- }
479
- // at this point, must be either semver range or dist-tag
480
- this.type = 'registry';
481
- const range = parseRange(this.bareSpec);
482
- if (range) {
483
- this.semver = this.bareSpec.trim();
484
- this.range = range;
485
- }
486
- else {
487
- this.distTag = this.bareSpec;
488
- }
489
- this.registrySpec = this.bareSpec;
490
- const { 'scope-registries': scopeRegs, registry } = this.options;
491
- const scopeReg = this.scope && scopeRegs[this.scope];
492
- this.registry = scopeReg ?? registry;
493
- // no guessing the tarball for JSR registries
494
- for (const r of Object.values(this.options['jsr-registries'])) {
495
- if (this.registry === r)
496
- return;
497
- }
498
- this.#guessRegistryTarball();
499
- }
500
- #parseScope(name) {
501
- if (!name.startsWith('@'))
502
- return;
503
- const s = name.indexOf('/');
504
- if (s > 1 && s < name.length - 1) {
505
- const scope = name.substring(0, s);
506
- this.registry = this.scopeRegistry =
507
- this.options['scope-registries'][scope];
508
- this.scope = scope;
509
- }
510
- }
511
- #parseHostedGit(name, template) {
512
- if (this.bareSpec.startsWith(`${name}:`)) {
513
- const h = this.bareSpec.indexOf('#');
514
- const bare = h === -1 ? this.bareSpec : this.bareSpec.substring(0, h);
515
- const hash = h === -1 ? '' : this.bareSpec.substring(h);
516
- const hostPath = bare.substring(name.length + 1);
517
- if (!hostPath) {
518
- throw this.#error('invalid named git host specifier');
519
- }
520
- const split = hostPath.split('/');
521
- let t = template;
522
- for (let i = 0; i < split.length; i++) {
523
- t = t.split(`$${i + 1}`).join(split[i]);
524
- }
525
- t += hash;
526
- this.namedGitHost = name;
527
- this.namedGitHostPath = hostPath;
528
- this.#parseGitSelector(t);
529
- if (this.gitCommittish && !this.gitSelectorParsed?.path) {
530
- const archiveHost = this.options['git-host-archives'][name];
531
- if (name === 'github' &&
532
- this.gitCommittish.startsWith('pull/') &&
533
- this.gitCommittish.match(/\//g)?.length === 1) {
534
- this.gitCommittish += '/head';
535
- }
536
- if (archiveHost) {
537
- this.type = 'remote';
538
- let t = archiveHost;
539
- t = t.split('$committish').join(this.gitCommittish);
540
- for (let i = 0; i < split.length; i++) {
541
- t = t.split(`$${i + 1}`).join(split[i]);
542
- }
543
- this.remoteURL = t;
544
- }
545
- }
546
- return true;
547
- }
548
- return false;
549
- }
550
- /* c8 ignore start */
551
- [kCustomInspect]() {
552
- return `@vltpkg/spec.Spec ${String(this)}`;
553
- }
554
- /* c8 ignore stop */
555
- #guessRegistryTarball() {
556
- // only try to guess if it's a single comparator for a single version
557
- const { name, registry, range } = this.final;
558
- if (!registry || !range?.isSingle)
559
- return;
560
- const stripScope = /^@[^/]+\//;
561
- this.conventionalRegistryTarball = String(new URL(`/${name}/-/${name.replace(stripScope, '')}-${range}.tgz`, registry));
562
- }
563
- #parseRegistrySpec(s, url) {
564
- // note: this takes priority over the scoped registry, if set
565
- this.registry = url;
566
- this.subspec = this.constructor.parse(s, {
567
- ...this.options,
568
- registry: url,
569
- });
570
- return this.subspec;
571
- }
572
- #parseJsrRegistrySpec(s, url) {
573
- this.registry = url;
574
- // @luca/cases@jsr:1.x
575
- if (!s.startsWith('@'))
576
- s = `${this.name}@${s}`;
577
- const name = `@jsr/${s.replace(/^@/, '').replace(/\//, '__')}`;
578
- this.subspec = this.constructor.parse(name, {
579
- ...this.options,
580
- 'scope-registries': {
581
- ...this.options['scope-registries'],
582
- '@jsr': url,
583
- },
584
- });
585
- if (this.name === '(unknown)') {
586
- const nextAt = s.indexOf('@', 1);
587
- if (nextAt === -1) {
588
- this.name = s;
589
- }
590
- else {
591
- this.name = s.substring(0, s.indexOf('@', 1));
592
- }
593
- }
594
- const reg = `${this.namedJsrRegistry}:`;
595
- const n = `${reg}${this.name}`;
596
- if (this.bareSpec.startsWith(n + '@')) {
597
- this.bareSpec = reg + this.bareSpec.substring(n.length + 1);
598
- }
599
- else if (this.bareSpec === n) {
600
- this.bareSpec = reg;
601
- }
602
- this.spec = this.name + '@' + this.bareSpec;
603
- return this.subspec;
604
- }
605
- #error(message, extra = {}) {
606
- return error(message, { spec: this.spec, ...extra }, this.#error);
607
- }
608
- #parseGitSelector(s) {
609
- const h = s.indexOf('#');
610
- if (h === -1) {
611
- this.gitRemote = s;
612
- return;
613
- }
614
- this.gitRemote = s.substring(0, h);
615
- this.gitSelector = s.substring(h + 1);
616
- const [selectorParsed, committish, range] = this.constructor.parseGitSelector(this.gitSelector, this);
617
- this.range = range;
618
- this.gitCommittish = committish;
619
- this.gitSelectorParsed = selectorParsed;
620
- }
621
- /**
622
- * Sets a registry value that should be used for this spec in case
623
- * it is currently just following the default registry.
624
- */
625
- set inheritedRegistry(reg) {
626
- if (reg != null &&
627
- this.type === 'registry' &&
628
- this.registry === this.options.registry) {
629
- this.registry = reg;
630
- }
631
- }
632
- /**
633
- * Should only ever be called with the bit that comes AFTER the #
634
- * in the git remote url.
635
- */
636
- static parseGitSelector(selector, spec) {
637
- if (!selector)
638
- return [{}];
639
- const split = selector.split('::');
640
- const first = split[0];
641
- let committish = undefined;
642
- let range = undefined;
643
- const parsed = {};
644
- /* c8 ignore start - for TS's benefit */
645
- if (typeof first !== 'string') {
646
- throw typeError('impossible', {
647
- found: first,
648
- wanted: String,
649
- });
650
- }
651
- /* c8 ignore stop */
652
- if (!first.includes(':')) {
653
- committish = first;
654
- split.shift();
655
- }
656
- for (const kv of split) {
657
- const c = kv.indexOf(':');
658
- /* c8 ignore next */
659
- if (c === -1)
660
- continue;
661
- const k = kv.substring(0, c);
662
- const v = kv.substring(c + 1);
663
- if (k === 'semver') {
664
- if (committish) {
665
- throw error('Cannot specify a semver range and committish value', { spec });
666
- }
667
- range = parseRange(v);
668
- if (!range) {
669
- throw error(`Invalid git tag semver range: ${v}`, { spec });
670
- }
671
- }
672
- if (k === 'semver' || k === 'path') {
673
- if (k === 'path') {
674
- if (
675
- /* c8 ignore next */ this.nodejsDependencies?.isAbsolute(v) ||
676
- /(^|\/|\\)\.\.($|\\|\/)/.test(v)) {
677
- throw error('Invalid path in git selector', { spec });
678
- }
679
- // normalize
680
- /* c8 ignore start */
681
- parsed.path = (this.nodejsDependencies ?
682
- this.nodejsDependencies.join('/', v).substring(1)
683
- : v).replace(/\\/g, '/');
684
- /* c8 ignore stop */
685
- }
686
- else {
687
- parsed[k] = v;
688
- }
689
- }
690
- }
691
- return [parsed, committish, range];
692
- }
693
- }
694
- // normalize our kinda-sorta spec compliant `file:` specifiers
695
- //
696
- // For historical reasons, we need to support a lot of non-spec-compliant
697
- // behaviors, but this massages the result into a *slightly* less offensive
698
- // shape.
699
- //
700
- // The result will be either a fully compliant `file://` with an absolute path,
701
- // or a `file:` with a relative path starting with `~`, `./`, or `../`.
702
- export const getNormalizeFile = (opts) => (bareSpec, spec) => {
703
- const slashes = bareSpec.substring('file:'.length, 'file://'.length);
704
- const pref = `file:${slashes === '//' ? slashes : ''}`;
705
- const rest = bareSpec.substring(pref.length);
706
- // default to '/' because eol == '/' for parsing purposes
707
- const [a = '', b = '/', c = '/', d = '/'] = rest.split('', 4);
708
- if (!a) {
709
- // file:// => file:.
710
- // file: => file:.
711
- return ['.', 'file:.'];
712
- }
713
- if ((a === '/' && b === '~' && c !== '/') ||
714
- (a === '~' && b !== '/')) {
715
- throw error(`invalid file: specifier. '~username' not supported`, { spec });
716
- }
717
- if (a === '~') {
718
- // file://~ => file:~
719
- // file://~/x => file:~/x
720
- return /* c8 ignore start */ opts ?
721
- [
722
- opts.resolve(opts.homedir(), rest.substring(2)),
723
- `file:${rest}`,
724
- ]
725
- : [rest, `file:${rest}`];
726
- }
727
- if (a === '/' && b === '~') {
728
- // file:///~ => file:~
729
- // file:/~/x => file:~/x
730
- /* c8 ignore start - tested in test/index.ts */
731
- return opts ?
732
- [
733
- opts.resolve(opts.homedir(), rest.substring(3)),
734
- `file:${rest.substring(1)}`,
735
- ]
736
- : /* c8 ignore stop */
737
- [rest.substring(1), `file:${rest.substring(1)}`];
738
- }
739
- if (a === '/' &&
740
- b === '.' &&
741
- (c === '/' || (c === '.' && d === '/'))) {
742
- // file:/./x => file:./x
743
- // file:///./x => file:./x
744
- // file:/../x => file:../x
745
- // file://../x => file:../x
746
- return [rest.substring(1), `file:${rest.substring(1)}`];
747
- }
748
- if (a === '.' && (b === '/' || (b === '.' && c === '/'))) {
749
- // file://. => file:.
750
- // file://./x => file:./x
751
- // file://../x => file:../x
752
- return [rest, `file:${rest}`];
753
- }
754
- if (slashes === '//') {
755
- // must be valid URI, since we ruled out relative and homedir above
756
- // not relative, but note that file://host/share is
757
- // windows-specific and does not work on darwin, so disallow it.
758
- try {
759
- const parsed = new URL(bareSpec);
760
- if (parsed.host) {
761
- if (parsed.host !== 'localhost') {
762
- throw error(`invalid file:// specifier. host must be empty or 'localhost'`, {
763
- spec,
764
- found: parsed.host,
765
- validOptions: ['', 'localhost'],
766
- });
767
- }
768
- }
769
- // normalize blank authority
770
- // file://X:/foo => file:///X:/foo
771
- // file://localhost/x => file:///x
772
- // interpret a `file:///D:/x` as `D:/x` though
773
- return [
774
- parsed.pathname.replace(/^\/([a-zA-Z]:\/)/, '$1'),
775
- `file://${parsed.pathname}`,
776
- ];
777
- }
778
- catch (er) {
779
- // invalid URI for other reasons, eg file://x\u0000y/z
780
- throw error('invalid file:// specifier', {
781
- spec,
782
- cause: er,
783
- });
784
- }
785
- }
786
- // no //, no authority, be ungovernable
787
- /* c8 ignore start */
788
- if (opts?.winPath.isAbsolute(rest)) {
789
- // file:/absolute => file:///absolute
790
- // file:/D:/foo => file:///D:/foo
791
- return [rest, `file://${rest}`];
792
- }
793
- /* c8 ignore stop */
794
- // file:x => file:./x
795
- return [`./${rest}`, `file:./${rest}`];
796
- };
797
- //# sourceMappingURL=browser.js.map