forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage_json_reader.js
More file actions
203 lines (179 loc) · 5.58 KB
/
package_json_reader.js
File metadata and controls
203 lines (179 loc) · 5.58 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
'use strict';
const {
ArrayIsArray,
JSONParse,
ObjectDefineProperty,
} = primordials;
const modulesBinding = internalBinding('modules');
const { resolve } = require('path');
const { kEmptyObject } = require('internal/util');
const {
codes: {
ERR_INVALID_ARG_TYPE,
},
} = require('internal/errors');
/**
* @typedef {import('typings/internalBinding/modules').FullPackageConfig} FullPackageConfig
* @typedef {import('typings/internalBinding/modules').RecognisedPackageConfig} RecognisedPackageConfig
* @typedef {import('typings/internalBinding/modules').SerializedPackageConfig} SerializedPackageConfig
*/
/**
* @param {string} path
* @param {SerializedPackageConfig} contents
* @returns {RecognisedPackageConfig}
*/
function deserializePackageJSON(path, contents) {
if (contents === undefined) {
return {
__proto__: null,
exists: false,
pjsonPath: path,
type: 'none', // Ignore unknown types for forwards compatibility
};
}
let pjsonPath = path;
const {
0: name,
1: main,
2: type,
3: plainImports,
4: plainExports,
5: optionalFilePath,
} = contents;
// This is required to be used in getPackageScopeConfig.
if (optionalFilePath) {
pjsonPath = optionalFilePath;
}
// The imports and exports fields can be either undefined or a string.
// - If it's a string, it's either plain string or a stringified JSON string.
// - If it's a stringified JSON string, it starts with either '[' or '{'.
const requiresJSONParse = (value) => (value !== undefined && (value[0] === '[' || value[0] === '{'));
return {
__proto__: null,
exists: true,
pjsonPath,
name,
...(main != null && { main }),
...(type != null && { type }),
...(plainImports != null && {
// This getters are used to lazily parse the imports and exports fields.
get imports() {
const value = requiresJSONParse(plainImports) ? JSONParse(plainImports) : plainImports;
ObjectDefineProperty(this, 'imports', { __proto__: null, value });
return this.imports;
},
}),
...(plainExports != null && {
get exports() {
const value = requiresJSONParse(plainExports) ? JSONParse(plainExports) : plainExports;
ObjectDefineProperty(this, 'exports', { __proto__: null, value });
return this.exports;
},
}),
};
}
/**
* Reads a package.json file and returns the parsed contents.
* @param {string} jsonPath
* @param {{
* base?: URL | string,
* specifier?: URL | string,
* isESM?: boolean,
* }} options
* @returns {RecognisedPackageConfig}
*/
function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
// This function will be called by both CJS and ESM, so we need to make sure
// non-null attributes are converted to strings.
const parsed = modulesBinding.readPackageJSON(
jsonPath,
isESM,
base == null ? undefined : `${base}`,
specifier == null ? undefined : `${specifier}`,
);
return deserializePackageJSON(jsonPath, parsed);
}
/**
* @deprecated Expected to be removed in favor of `read` in the future.
* Behaves the same was as `read`, but appends package.json to the path.
* @param {string} requestPath
* @return {RecognisedPackageConfig}
*/
function readPackage(requestPath) {
// TODO(@anonrig): Remove this function.
return read(resolve(requestPath, 'package.json'));
}
/**
* Get the nearest parent package.json file from a given path.
* Return the package.json data and the path to the package.json file, or undefined.
* @param {URL['href'] | URL['pathname']} startPath The path to start searching from.
* @param {boolean} everything Whether to include the full contents of the package.json.
* @returns {undefined | {
* data: everything extends true ? FullPackageConfig : RecognisedPackageConfig,
* path: URL['pathname'],
* }}
*/
function getNearestParentPackageJSON(startPath, everything = false) {
if (typeof startPath !== 'string') {
throw new ERR_INVALID_ARG_TYPE('startPath', 'string', startPath);
}
if (
everything !== undefined &&
typeof everything !== 'boolean'
) {
throw new ERR_INVALID_ARG_TYPE('everything', 'boolean', everything);
}
if (everything) {
const result = modulesBinding.getNearestRawParentPackageJSON(startPath);
return {
data: {
__proto__: null,
...JSONParse(result[0]),
},
path: result[1],
};
}
const result = modulesBinding.getNearestParentPackageJSON(startPath);
if (result === undefined) {
return undefined;
}
const data = deserializePackageJSON(startPath, result);
const { pjsonPath: path } = data;
delete data.exists;
delete data.pjsonPath;
return { data, path };
}
/**
* Returns the package configuration for the given resolved URL.
* @param {URL | string} resolved - The resolved URL.
* @returns {RecognisedPackageConfig} - The package configuration.
*/
function getPackageScopeConfig(resolved) {
const result = modulesBinding.getPackageScopeConfig(`${resolved}`);
if (ArrayIsArray(result)) {
return deserializePackageJSON(`${resolved}`, result);
}
// This means that the response is a string
// and it is the path to the package.json file
return {
__proto__: null,
pjsonPath: result,
exists: false,
type: 'none',
};
}
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
*/
function getPackageType(url) {
// TODO(@anonrig): Write a C++ function that returns only "type".
return getPackageScopeConfig(url).type;
}
module.exports = {
read,
readPackage,
getNearestParentPackageJSON,
getPackageScopeConfig,
getPackageType,
};