-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathManifestManager.class.ts
More file actions
322 lines (269 loc) · 7.9 KB
/
Copy pathManifestManager.class.ts
File metadata and controls
322 lines (269 loc) · 7.9 KB
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
// Import Node.js Dependencies
import fs from "node:fs/promises";
import fsSync from "node:fs";
import path from "node:path";
// Import Third-party Dependencies
import { parseAuthor } from "@nodesecure/utils";
import { toContactWithMetadata, type ContactWithMetadata } from "@nodesecure/contact";
import type {
PackumentVersion,
PackageJSON,
WorkspacesPackageJSON,
AbbreviatedManifestDocument
} from "@nodesecure/npm-types";
import { fromData } from "ssri";
// Import Internal Dependencies
import {
packageJSONIntegrityHash,
inspectModuleType
} from "./utils/index.ts";
type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
export type NonOptionalPackageJSONProperties =
"dependencies" |
"devDependencies" |
"scripts" |
"gypfile";
// CONSTANTS
const kNativeNpmPackages = new Set([
"node-gyp",
"node-pre-gyp",
"node-gyp-build",
"node-addon-api"
]);
/**
* @see https://www.nerdycode.com/prevent-npm-executing-scripts-security/
*/
export const kUnsafeNPMScripts = new Set([
"install",
"preinstall",
"postinstall",
"preuninstall",
"postuninstall"
]);
export type ManifestManagerDefaultProperties = Required<
Pick<PackumentVersion, NonOptionalPackageJSONProperties>
>;
export interface ManifestManagerOptions {
/**
* Optional absolute location (directory) to the manifest
*/
location?: string;
}
export type ManifestManagerDocument =
PackageJSON |
WorkspacesPackageJSON |
PackumentVersion;
export type LocatedManifestManager<
MetadataDef extends Record<string, any> = Record<string, any>
> = ManifestManager<MetadataDef> & { location: string; };
export class ManifestManager<
MetadataDef extends Record<string, any> = Record<string, any>
> {
static Default: Readonly<ManifestManagerDefaultProperties> = Object.freeze({
dependencies: {},
devDependencies: {},
scripts: {},
gypfile: false
});
/**
* Type guard to check if a ManifestManager instance has a location
*/
static isLocated<T extends Record<string, any>>(
mama: ManifestManager<T>
): mama is LocatedManifestManager<T> {
return typeof mama.location !== "undefined";
}
public metadata: MetadataDef = Object.create(null);
public document: WithRequired<
ManifestManagerDocument,
NonOptionalPackageJSONProperties
>;
public location: string | undefined;
public flags = Object.seal({
hasUnsafeScripts: false,
isNative: false
});
constructor(
document: ManifestManagerDocument | AbbreviatedManifestDocument,
options: ManifestManagerOptions = {}
) {
const { location } = options;
this.document = Object.assign(
{ ...ManifestManager.Default },
structuredClone(document)
) as WithRequired<ManifestManagerDocument, NonOptionalPackageJSONProperties>;
if (location) {
this.location = location.endsWith("package.json") ?
path.dirname(location) :
location;
}
this.flags.isNative = [
...this.dependencies,
...this.devDependencies
].some((pkg) => kNativeNpmPackages.has(pkg)) || this.document.gypfile;
this.flags.hasUnsafeScripts = Object
.keys(this.document.scripts)
.some((script) => kUnsafeNPMScripts.has(script.toLowerCase()));
}
get documentDigest() {
const isWorkspace = "workspaces" in this.document;
const data = JSON.stringify(this.document);
return isWorkspace ?
null :
fromData(data, { algorithms: ["sha512"] }).toString();
}
get name() {
return this.document.name ?? "workspace";
}
get version() {
return this.document.version ?? "1.0.0";
}
get moduleType() {
return inspectModuleType(this.document);
}
get hasZeroSemver() {
if (typeof this.document.version === "string") {
return /^0(\.\d+)*$/
.test(this.document.version);
}
return false;
}
get nodejsImports() {
return this.document.imports ?? {};
}
get dependencies() {
return Object.keys(this.document.dependencies);
}
get devDependencies() {
return Object.keys(this.document.devDependencies);
}
get spec(): `${string}@${string}` {
const hasBothProperties = ["name", "version"]
.every((key) => key in this.document);
if (this.isWorkspace && !hasBothProperties) {
throw new Error("spec is not available for the given workspace");
}
return `${this.document.name}@${this.document.version}`;
}
get author(): ContactWithMetadata | null {
const parsedAuthor = parseAuthor(this.document.author);
return parsedAuthor ? toContactWithMetadata(parsedAuthor) : null;
}
get isWorkspace(): boolean {
return "workspaces" in this.document;
}
get integrity(): string {
if (this.isWorkspace) {
throw new Error("integrity is not available for workspaces");
}
return packageJSONIntegrityHash(this.document).integrity;
}
get license(): string | null {
if (this.document.license) {
if (typeof this.document.license === "string") {
return this.document.license;
}
if (typeof this.document.license === "object") {
return this.document.license.type ?? null;
}
}
if (this.document.licenses) {
if (Array.isArray(this.document.licenses)) {
return this.document.licenses[0]?.type ?? null;
}
if (typeof this.document.licenses === "object") {
return this.document.licenses.type ?? null;
}
}
return null;
}
* getEntryFiles(): IterableIterator<string> {
if (this.document.main) {
yield this.document.main;
}
if (!this.document.exports) {
return;
}
if (typeof this.document.exports === "string") {
yield this.document.exports;
}
else {
yield* this.extractNodejsExport(this.document.exports);
}
}
private* extractNodejsExport(
exports: Record<string, string | null | Record<string, string | null>>
): IterableIterator<string> {
for (const node of Object.values(exports)) {
if (node === null) {
continue;
}
if (typeof node === "string") {
yield node;
}
else {
yield* this.extractNodejsExport(node);
}
}
}
static async fromPackageJSON(
locationOrManifest: string | ManifestManager
): Promise<ManifestManager> {
if (locationOrManifest instanceof ManifestManager) {
return locationOrManifest;
}
if (typeof locationOrManifest !== "string") {
throw new TypeError("locationOrManifest must be a string or a ManifestManager instance");
}
const location = locationOrManifest;
const packageLocation = location.endsWith("package.json") ?
location :
path.join(location, "package.json");
const packageStr = await fs.readFile(packageLocation, "utf-8");
try {
const packageJSON = JSON.parse(
packageStr
) as PackageJSON | WorkspacesPackageJSON;
return new ManifestManager(
packageJSON,
{ location }
);
}
catch (cause) {
throw new Error(
`Failed to parse package.json located at: ${packageLocation}`,
{ cause }
);
}
}
static fromPackageJSONSync(
locationOrManifest: string | ManifestManager
): ManifestManager {
if (locationOrManifest instanceof ManifestManager) {
return locationOrManifest;
}
if (typeof locationOrManifest !== "string") {
throw new TypeError("locationOrManifest must be a string or a ManifestManager instance");
}
const location = locationOrManifest;
const packageLocation = location.endsWith("package.json") ?
location :
path.join(location, "package.json");
const packageStr = fsSync.readFileSync(packageLocation, "utf-8");
try {
const packageJSON = JSON.parse(
packageStr
) as PackageJSON | WorkspacesPackageJSON;
return new ManifestManager(
packageJSON,
{ location }
);
}
catch (cause) {
throw new Error(
`Failed to parse package.json located at: ${packageLocation}`,
{ cause }
);
}
}
}