-
Notifications
You must be signed in to change notification settings - Fork 2
/
package-map.js
606 lines (489 loc) · 18.3 KB
/
package-map.js
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
import fs from "fs";
import path from "path";
import { gitSpecFromVersion } from "./util.js";
import { resource } from "./deps/lively.resources.js";
import semver from "./deps/semver.min.js";
/*
lively.lang.fun.timeToRun(() => {
let pm = PackageMap.build(["/Users/robert/Lively/lively-dev2/lively.next-node_modules"])
pm.lookup("lively.morphic")
}, 100);
let dir = System.resource(System.baseURL).join("lively.next-node_modules/")
let pmap = AsyncPackageMap.build([dir]); await pmap.whenReady()
let dir = "/Users/robert/Lively/lively-dev2/lively.next-node_modules/"
let pmap = PackageMap.build([dir]);
let json = pmap.allPackages().reduce((map, spec) => {
let {name,version} = spec;
map[name + "@" + version] = spec;
return map
}, {});
lively.lang.num.humanReadableByteSize(JSON.stringify(json).length)
await fs_dirList(pmap.lookup("react").location)
fs_dirList(pmap.lookup("react").location)
*/
function isAbsolute(path) {
return path.startsWith("/") || path.match(/^[a-z\.-_\+]+:/i)
}
function ensureResource(x) {
return x.isResource ? x : resource(x);
}
function parentDir(p) {
if (p.isResource) return p.parent();
return path.basename(p);
}
function equalLocation(a, b) {
if (a.isResource) return a.equals(b);
return a == b;
}
function join(a, b) {
if (a.isResource) return a.join(b);
return path.join(a, b);
}
function normalizePath(p) {
if (p.isResource) return p.withRelativePartsResolved()
return path.normalize(p);
}
function fs_isDirectory(location) {
if (location.isResource) return location.isDirectory();
return fs.statSync(location).isDirectory();
}
function fs_exists(location) {
if (location.isResource) return location.exists();
return fs.existsSync(location);
}
function fs_read(location) {
if (location.isResource) return location.read();
return fs.readFileSync(location);
}
function fs_write(location, content) {
if (location.isResource) return location.write(content);
return fs.writeFileSync(location, content);
}
function fs_readJson(location) {
if (location.isResource) return location.exists().then(exists => exists ? location.readJson() : null);
return fs.existsSync(location) ? JSON.parse(String(fs_read(location))) : null;
}
function fs_writeJson(location, jso) {
if (location.isResource) return location.writeJson(jso);
return fs_write(location, JSON.stringify(jso));
}
function fs_dirList(location) {
if (location.isResource) return location.dirList(1);
return fs.readdirSync(location).map(ea => join(location, ea));
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class PackageMap {
static empty() { return new this(); }
static get cache() { return this._cache || (this._cache = {}); }
static keyFor(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
return `all: ${packageCollectionDirs} ea: ${individualPackageDirs} dev: ${devPackageDirs}`
}
static ensure(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
let key = this.keyFor(packageCollectionDirs, individualPackageDirs, devPackageDirs);
return this.cache[key] || (this.cache[key] = this.build(
packageCollectionDirs, individualPackageDirs, devPackageDirs));
}
static build(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
let map = new this();
map.buildDependencyMap(
packageCollectionDirs,
individualPackageDirs,
devPackageDirs);
return map;
}
constructor() {
this.dependencyMap = {};
this.byPackageNames = {};
this.key = "";
this.devPackageDirs = [];
this.individualPackageDirs = [];
this.packageCollectionDirs = [];
this._readyPromise = null;
}
whenReady() { return this._readyPromise || Promise.resolve(); }
isReady() { return !this._readyPromise; }
withPackagesDo(doFn) {
let result = [];
for (let key in this.dependencyMap)
result.push(doFn(key, this.dependencyMap[key]))
return result;
}
findPackage(matchFn) {
for (let key in this.dependencyMap) {
let pkg = this.dependencyMap[key]
if (matchFn(key, pkg)) return pkg
}
return null;
}
allPackages() {
let pkgs = [];
for (let key in this.dependencyMap)
pkgs.push(this.dependencyMap[key]);
return pkgs;
}
coversDirectory(dir) {
let { packageCollectionDirs, devPackageDirs, individualPackageDirs } = this;
if (individualPackageDirs.some(ea => equalLocation(ea, dir))) return "individualPackageDirs";
if (devPackageDirs.some(ea => equalLocation(ea, dir))) return "devPackageDirs";
let parent = parentDir(dir);
if (packageCollectionDirs.some(ea => equalLocation(ea, parent))) {
return this.allPackages().find(pkg => equalLocation(pkg.location, parent)) ?
"packageCollectionDirs" : "maybe packageCollectionDirs";
}
return null;
}
addPackage(packageSpec, isDev = false) {
// returns false if package already installed, true otherwise
let self = this;
if (typeof packageSpec === "string")
packageSpec = PackageSpec.fromDir(packageSpec);
return packageSpec instanceof Promise ?
packageSpec.then(resolvedPackageSpec => {
packageSpec = resolvedPackageSpec;
return isPackageSpecIncluded();
}) : isPackageSpecIncluded();
function isPackageSpecIncluded() {
let { location, name, version } = packageSpec,
{ packageCollectionDirs, devPackageDirs, individualPackageDirs } = self,
isCovered = self.coversDirectory(location);
if (["devPackageDirs", "individualPackageDirs", "packageCollectionDirs"].includes(isCovered))
return false;
if (isDev) devPackageDirs = devPackageDirs.concat(location);
else individualPackageDirs = individualPackageDirs.concat(location);
// FIXME key changes....
let build = self.buildDependencyMap(
packageCollectionDirs,
individualPackageDirs,
devPackageDirs);
return build instanceof Promise ? build.then(() => true) : true;
}
}
buildDependencyMap(packageCollectionDirs, individualPackageDirs = [], devPackageDirs = []) {
// looks up all the packages in can find in packageDirs and creates
// packageSpecs for them. If a package specifies more flatn_package_dirs in its
// config then repeat the process until no more new package dirs are found.
// Finally, combine all the packages found into a single map, like
// {package-name@version: packageSpec, ...}.
//
// Merging of the results of the different package dirs happens so that dirs
// specified first take precedence. I.e. if a dependency foo@1 is found via
// packageDirs and then another package specifies a dir that leads to the
// discovery of another foo@1, the first one ends up in tha packageDir
let key = this.constructor.keyFor(
packageCollectionDirs,
individualPackageDirs,
devPackageDirs
);
let pkgMap = {},
byPackageNames = {},
seen = { packageDirs: {}, collectionDirs: {} };
// 1. find all the packages in collection dirs and separate package dirs;
for (let p of this._discoverPackagesInCollectionDirs(packageCollectionDirs, seen)) {
let { name, version } = p;
pkgMap[`${name}@${version}`] = p;
(byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
}
for (let dir of individualPackageDirs)
for (let p of this._discoverPackagesInPackageDir(dir, seen)) {
let { name, version } = p;
pkgMap[`${name}@${version}`] = p;
(byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
}
// 2. read dev packages, those shadow all normal dependencies with the same package name;
for (let dir of devPackageDirs)
for (let p of this._discoverPackagesInPackageDir(dir, seen)) {
let { name, version } = p;
pkgMap[`${name}`] = p;
p.isDevPackage = true;
let versionsOfPackage = byPackageNames[name] || (byPackageNames[name] = []);
if (versionsOfPackage) for (let key of versionsOfPackage) delete pkgMap[key];
versionsOfPackage.push(name);
}
this.dependencyMap = pkgMap;
this.byPackageNames = byPackageNames;
this.packageCollectionDirs = packageCollectionDirs;
this.individualPackageDirs = individualPackageDirs;
this.devPackageDirs = devPackageDirs;
this.key = key;
return this;
}
lookup(name, versionRange) {
// Query the package map if it has a package name@version
// Compatibility is either a semver match or if package comes from a git
// repo then if the git commit matches. Additionally dev packages are
// supported. If a dev package with `name` is found it always matches
let gitSpec = gitSpecFromVersion(versionRange || "");
if (!gitSpec && versionRange) {
try {
// parse stuff like "3001.0001.0000-dev-harmony-fb" into "3001.1.0-dev-harmony-fb"
versionRange = new semver.Range(versionRange, true).toString();
} catch (err) { }
}
return this.findPackage((key, pkg) => pkg.matches(name, versionRange, gitSpec));
}
_discoverPackagesInCollectionDirs(
packageCollectionDirs,
seen = { packageDirs: {}, collectionDirs: {} }
) {
// package collection dir structure is like
// packages
// |-package-1
// | |-0.1.0
// | | \-package.json
// | \-0.1.1
// | \-package.json
// |-package-2
// ...
let found = [];
for (let dir of packageCollectionDirs) {
if (!fs_exists(dir)) continue;
for (let packageDir of fs_dirList(dir)) {
if (!fs_isDirectory(packageDir)) continue;
for (let versionDir of fs_dirList(packageDir))
found.push(...this._discoverPackagesInPackageDir(versionDir, seen));
}
}
return found;
}
_discoverPackagesInPackageDir(
packageDir,
seen = { packageDirs: {}, collectionDirs: {} }
) {
let spec = fs_exists(packageDir) && PackageSpec.fromDir(packageDir);
if (!spec) return [];
let found = [spec],
{ location, flatn_package_dirs } = spec;
if (flatn_package_dirs) {
for (let dir of flatn_package_dirs) {
if (!isAbsolute(dir)) dir = normalizePath(join(location, dir));
if (seen.collectionDirs[dir]) continue;
console.log(`[flatn] project ${location} specifies package dir ${dir}`);
seen.collectionDirs[dir] = true;
found.push(...this._discoverPackagesInCollectionDirs([dir], seen));
}
}
return found;
}
}
class AsyncPackageMap extends PackageMap {
whenReady() { return this._readyPromise || Promise.resolve(); }
isReady() { return !this._readyPromise; }
async buildDependencyMap(
packageCollectionDirs,
individualPackageDirs = [],
devPackageDirs = []
) {
// looks up all the packages in can find in packageDirs and creates
// packageSpecs for them. If a package specifies more flatn_package_dirs in its
// config then repeat the process until no more new package dirs are found.
// Finally, combine all the packages found into a single map, like
// {package-name@version: packageSpec, ...}.
//
// Merging of the results of the different package dirs happens so that dirs
// specified first take precedence. I.e. if a dependency foo@1 is found via
// packageDirs and then another package specifies a dir that leads to the
// discovery of another foo@1, the first one ends up in tha packageDir
if (!this.isReady()) {
return this.whenReady().then(() =>
this.buildDependencyMap(
packageCollectionDirs,
individualPackageDirs,
devPackageDirs));
}
let resolve, reject;
this._readyPromise = new Promise((_resolve, _reject) => {
resolve = _resolve; reject = _reject;
});
try {
let key = this.constructor.keyFor(
packageCollectionDirs,
individualPackageDirs,
devPackageDirs
);
let pkgMap = {},
byPackageNames = {},
seen = { packageDirs: {}, collectionDirs: {} };
// 1. find all the packages in collection dirs and separate package dirs;
for (let p of await this._discoverPackagesInCollectionDirs(packageCollectionDirs, seen)) {
let { name, version } = p;
pkgMap[`${name}@${version}`] = p;
(byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
}
for (let dir of individualPackageDirs)
for (let p of await this._discoverPackagesInPackageDir(dir, seen)) {
let { name, version } = p;
pkgMap[`${name}@${version}`] = p;
(byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
}
// 2. read dev packages, those shadow all normal dependencies with the same package name;
for (let dir of devPackageDirs)
for (let p of await this._discoverPackagesInPackageDir(dir, seen)) {
let { name, version } = p;
pkgMap[`${name}`] = p;
p.isDevPackage = true;
let versionsOfPackage = byPackageNames[name] || (byPackageNames[name] = []);
if (versionsOfPackage) for (let key of versionsOfPackage) delete pkgMap[key];
versionsOfPackage.push(name);
}
this.dependencyMap = pkgMap;
this.byPackageNames = byPackageNames;
this.packageCollectionDirs = packageCollectionDirs;
this.individualPackageDirs = individualPackageDirs;
this.devPackageDirs = devPackageDirs;
this.key = key;
resolve();
}
catch (err) { reject(err); }
finally { this._readyPromise = null; }
return this;
}
async _discoverPackagesInCollectionDirs(
packageCollectionDirs,
seen = { packageDirs: {}, collectionDirs: {} }
) {
let found = [];
for (let dir of packageCollectionDirs) {
if (!await dir.exists()) continue;
for (let packageDir of await dir.dirList()) {
if (!packageDir.isDirectory()) continue;
for (let versionDir of await packageDir.dirList())
found.push(...await this._discoverPackagesInPackageDir(versionDir, seen));
}
}
return found;
}
async _discoverPackagesInPackageDir(
packageDir,
seen = { packageDirs: {}, collectionDirs: {} }
) {
let spec = await packageDir.exists() && await PackageSpec.fromDir(packageDir);
if (!spec) return [];
let found = [spec],
{ location, flatn_package_dirs } = spec;
location = ensureResource(location);
if (flatn_package_dirs) {
for (let dir of flatn_package_dirs) {
if (isAbsolute(dir)) dir = ensureResource(dir);
else dir = join(location, dir).withRelativePartsResolved();
if (seen.collectionDirs[dir.url]) continue;
console.log(`[flatn] project ${location.url} specifies package dir ${dir.url}`);
seen.collectionDirs[dir.url] = true;
found.push(...await this._discoverPackagesInCollectionDirs([dir], seen));
}
}
return found;
}
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// PackageSpec => package representation for dependency resolution and build
const lvInfoFileName = ".lv-npm-helper-info.json";
class PackageSpec {
static fromDir(packageDir) {
let spec = new this(packageDir),
read = spec.read();
return read instanceof Promise
? read.then(read => (read ? spec : null))
: read ? spec : null;
}
constructor(location) {
this.location = location;
this.isDevPackage = false;
// from config
this.scripts = null;
this.bin = null;
this.flatn_package_dirs = null;
this.name = "";
this.version = "";
this.dependencies = {};
this.devDependencies = {};
// from git spec
this.branch = null;
this.gitURL = null;
this.versionInFileName = null; // @https___github.com_foo_bar#zork
}
matches(pName, versionRange, gitSpec) {
// does this package spec match the package pName@versionRange?
let { name, version, isDevPackage } = this;
if (name !== pName) return false;
if (!versionRange || isDevPackage) return true;
if (gitSpec && (gitSpec.versionInFileName === version
|| this.versionInFileName === gitSpec.versionInFileName)) {
return true
}
if (semver.parse(version || "", true) && semver.satisfies(version, versionRange, true))
return true;
return false;
}
read() {
let self = this,
packageDir = this.location,
configFile = join(packageDir, "package.json");
if (!fs_isDirectory(packageDir)) return false;
let hasConfig = fs_exists(configFile);
return hasConfig instanceof Promise ? hasConfig.then(step2) : step2(hasConfig);
function step2(hasConfig) {
if (!hasConfig) return false;
let config = fs_readJson(configFile);
return config instanceof Promise ? config.then(step3) : step3(config);
}
function step3(config) {
let {
name, version, bin, scripts,
dependencies, devDependencies,
flatn_package_dirs
} = config;
if (bin) {
// npm allows bin to just be a string, it is then mapped to the package name
bin = typeof bin === "string" ? { [name]: bin } : Object.assign({}, bin);
}
Object.assign(self, {
location: packageDir,
name, version, bin, scripts,
dependencies, devDependencies,
flatn_package_dirs
});
let info = self.readLvInfo();
return info instanceof Promise ? info.then(step4) : step4(info);
}
function step4(info) {
if (info) {
let { branch, gitURL, versionInFileName } = info;
Object.assign(self, { branch, gitURL, versionInFileName });
}
return true;
}
}
readConfig() {
const config = fs_readJson(join(this.location, "package.json"));
return config instanceof Promise ?
config.then(ensureConfig) : ensureConfig(config);
function ensureConfig(config) {
if (config) return config;
const { name, version } = this;
return { name, version };
}
}
readLvInfo() {
let infoF = join(this.location, lvInfoFileName);
try {
let read = fs_readJson(infoF);
return read instanceof Promise ?
read.catch(err => null) : read;
} catch (err) { }
return null;
}
writeLvInfo(spec) {
return fs_writeJson(join(this.location, lvInfoFileName), spec);
}
changeLvInfo(changeFn) {
let read = this.readLvInfo();
return read instanceof Promise ?
read.then(read => this.writeLvInfo(changeFn(read))) :
this.writeLvInfo(changeFn(read));
}
}
export {
PackageMap,
AsyncPackageMap,
PackageSpec
}