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

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