-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnoticeme.ts
77 lines (60 loc) · 2.42 KB
/
noticeme.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
// Copyright (c) Houdini Project
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import fs from 'fs';
import fetch from 'node-fetch';
import NoticeService from './noticeService';
import readPkgTree from 'read-package-tree';
interface PackageNode {
name: string
package: {
name: string
version: string
license: string
}
children: PackageNode[]
}
const npmjsCoordinates = ({ name, version }: { name: string, version: string }): string =>
'npm/npmjs/' + (name.includes('/') ? name : `-/${name}`) + `/${version}`;
function retrieveIncludedJson(path: string): { name: string; version: string; }[] {
return fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')).packages : [];
}
function getPackages(rpt: typeof readPkgTree): (path: string) => Promise<PackageNode[]> {
return (path: string) => {
return new Promise((resolve, reject) => {
rpt(path, (err: any, { children }: { children: PackageNode[] }) => {
if (err)
reject(err)
else
resolve(children)
});
});
}
}
function argNormalization(args: { path: string, includedFile: string | null, chunkSize?: number | null, rpt?: typeof readPkgTree | null, http?: typeof fetch }): { chunkSize: number; rpt: typeof readPkgTree; http: typeof fetch; path: string; includedFile: string | null; } {
return {
...args,
chunkSize: args.chunkSize || 0,
rpt: args.rpt || readPkgTree,
http: args.http || fetch,
}
}
export default async function noticeme(args: { path: string, includedFile: string | null, chunkSize?: number | null, rpt?: typeof readPkgTree | null, http?: typeof fetch }): Promise<string> {
const { path, includedFile, chunkSize, rpt, http } = argNormalization(args);
const children = await getPackages(rpt)(path)
const pkgJsonLicenses = new Map();
let coordinates = children.map(({ package: pkg, children: more }: PackageNode) => {
children.push(...more);
const coordinate = npmjsCoordinates(pkg);
// TODO: make use of these as fallback
pkgJsonLicenses.set(coordinate, pkg.license);
return coordinate;
});
if (includedFile) {
coordinates = coordinates.concat(retrieveIncludedJson(includedFile).
map((pkg) => npmjsCoordinates(pkg)));
};
const service = new NoticeService('https://api.clearlydefined.io/notices', http);
const notice = await service.generateNotice(coordinates, chunkSize)
return notice.content;
}