Skip to content

Commit 5067e5f

Browse files
committed
src: improve package.json reader performance
1 parent b85a2b1 commit 5067e5f

File tree

9 files changed

+171
-181
lines changed

9 files changed

+171
-181
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ const {
8282
pendingDeprecate,
8383
emitExperimentalWarning,
8484
kEmptyObject,
85-
filterOwnProperties,
8685
setOwnProperty,
8786
getLazy,
8887
} = require('internal/util');
@@ -353,36 +352,10 @@ function initializeCJS() {
353352
// -> a.<ext>
354353
// -> a/index.<ext>
355354

356-
const packageJsonCache = new SafeMap();
357-
358355
function readPackage(requestPath) {
359356
const jsonPath = path.resolve(requestPath, 'package.json');
360-
361-
const existing = packageJsonCache.get(jsonPath);
362-
if (existing !== undefined) return existing;
363-
364-
const result = packageJsonReader.read(jsonPath);
365-
const json = result.containsKeys === false ? '{}' : result.string;
366-
if (json === undefined) {
367-
packageJsonCache.set(jsonPath, false);
368-
return false;
369-
}
370-
371-
try {
372-
const filtered = filterOwnProperties(JSONParse(json), [
373-
'name',
374-
'main',
375-
'exports',
376-
'imports',
377-
'type',
378-
]);
379-
packageJsonCache.set(jsonPath, filtered);
380-
return filtered;
381-
} catch (e) {
382-
e.path = jsonPath;
383-
e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
384-
throw e;
385-
}
357+
// Return undefined or the filtered package.json as a JS object
358+
return packageJsonReader.read(jsonPath);
386359
}
387360

388361
let _readPackage = readPackage;

lib/internal/modules/esm/package_config.js

Lines changed: 13 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
11
'use strict';
22

33
const {
4-
JSONParse,
5-
ObjectPrototypeHasOwnProperty,
64
SafeMap,
75
StringPrototypeEndsWith,
86
} = primordials;
97
const { URL, fileURLToPath } = require('internal/url');
10-
const {
11-
ERR_INVALID_PACKAGE_CONFIG,
12-
} = require('internal/errors').codes;
13-
14-
const { filterOwnProperties } = require('internal/util');
15-
168

179
/**
1810
* @typedef {string | string[] | Record<string, unknown>} Exports
@@ -42,59 +34,22 @@ function getPackageConfig(path, specifier, base) {
4234
return existing;
4335
}
4436
const packageJsonReader = require('internal/modules/package_json_reader');
45-
const source = packageJsonReader.read(path).string;
46-
if (source === undefined) {
47-
const packageConfig = {
48-
pjsonPath: path,
49-
exists: false,
50-
main: undefined,
51-
name: undefined,
52-
type: 'none',
53-
exports: undefined,
54-
imports: undefined,
55-
};
56-
packageJSONCache.set(path, packageConfig);
57-
return packageConfig;
58-
}
59-
60-
let packageJSON;
61-
try {
62-
packageJSON = JSONParse(source);
63-
} catch (error) {
64-
throw new ERR_INVALID_PACKAGE_CONFIG(
65-
path,
66-
(base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
67-
error.message,
68-
);
69-
}
70-
71-
let { imports, main, name, type } = filterOwnProperties(packageJSON, ['imports', 'main', 'name', 'type']);
72-
const exports = ObjectPrototypeHasOwnProperty(packageJSON, 'exports') ? packageJSON.exports : undefined;
73-
if (typeof imports !== 'object' || imports === null) {
74-
imports = undefined;
75-
}
76-
if (typeof main !== 'string') {
77-
main = undefined;
78-
}
79-
if (typeof name !== 'string') {
80-
name = undefined;
81-
}
82-
// Ignore unknown types for forwards compatibility
83-
if (type !== 'module' && type !== 'commonjs') {
84-
type = 'none';
85-
}
37+
const result = packageJsonReader.read(path);
38+
const packageJSON = result ?? {
39+
main: undefined,
40+
name: undefined,
41+
type: 'none',
42+
exports: undefined,
43+
imports: undefined,
44+
};
8645

87-
const packageConfig = {
46+
const json = {
8847
pjsonPath: path,
89-
exists: true,
90-
main,
91-
name,
92-
type,
93-
exports,
94-
imports,
48+
exists: result !== undefined,
49+
...packageJSON,
9550
};
96-
packageJSONCache.set(path, packageConfig);
97-
return packageConfig;
51+
packageJSONCache.set(path, json);
52+
return json;
9853
}
9954

10055

lib/internal/modules/esm/resolve.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -734,8 +734,7 @@ function packageResolve(specifier, base, conditions) {
734734
const packageConfig = getPackageScopeConfig(base);
735735
if (packageConfig.exists) {
736736
const packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
737-
if (packageConfig.name === packageName &&
738-
packageConfig.exports !== undefined && packageConfig.exports !== null) {
737+
if (packageConfig.name === packageName && packageConfig.exports !== undefined) {
739738
return packageExportsResolve(
740739
packageJSONUrl, packageSubpath, packageConfig, base, conditions);
741740
}
@@ -760,7 +759,7 @@ function packageResolve(specifier, base, conditions) {
760759

761760
// Package match.
762761
const packageConfig = getPackageConfig(packageJSONPath, specifier, base);
763-
if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
762+
if (packageConfig.exports !== undefined) {
764763
return packageExportsResolve(
765764
packageJSONUrl, packageSubpath, packageConfig, base, conditions);
766765
}

lib/internal/modules/package_json_reader.js

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
'use strict';
22

3-
const { SafeMap } = primordials;
3+
const {
4+
JSONParse,
5+
JSONStringify,
6+
SafeMap,
7+
} = primordials;
48
const { internalModuleReadJSON } = internalBinding('fs');
59
const { pathToFileURL } = require('url');
610
const { toNamespacedPath } = require('path');
@@ -10,30 +14,60 @@ const cache = new SafeMap();
1014
let manifest;
1115

1216
/**
13-
*
17+
* Returns undefined for all failure cases.
1418
* @param {string} jsonPath
1519
*/
1620
function read(jsonPath) {
1721
if (cache.has(jsonPath)) {
1822
return cache.get(jsonPath);
1923
}
2024

21-
const { 0: string, 1: containsKeys } = internalModuleReadJSON(
25+
const {
26+
0: includesKeys,
27+
1: name,
28+
2: main,
29+
3: exports,
30+
4: imports,
31+
5: type,
32+
6: parseExports,
33+
7: parseImports,
34+
} = internalModuleReadJSON(
2235
toNamespacedPath(jsonPath),
2336
);
24-
const result = { string, containsKeys };
25-
const { getOptionValue } = require('internal/options');
26-
if (string !== undefined) {
37+
38+
let result;
39+
40+
if (includesKeys !== undefined) {
41+
result = {
42+
__proto__: null,
43+
name,
44+
main,
45+
exports,
46+
imports,
47+
type,
48+
};
49+
50+
// Execute JSONParse on demand for improved performance
51+
if (parseExports) {
52+
result.exports = JSONParse(exports);
53+
}
54+
55+
if (parseImports) {
56+
result.imports = JSONParse(imports);
57+
}
58+
2759
if (manifest === undefined) {
60+
const { getOptionValue } = require('internal/options');
2861
manifest = getOptionValue('--experimental-policy') ?
2962
require('internal/process/policy').manifest :
3063
null;
3164
}
3265
if (manifest !== null) {
3366
const jsonURL = pathToFileURL(jsonPath);
34-
manifest.assertIntegrity(jsonURL, string);
67+
manifest.assertIntegrity(jsonURL, JSONStringify(result));
3568
}
3669
}
70+
3771
cache.set(jsonPath, result);
3872
return result;
3973
}

src/node_file.cc

Lines changed: 84 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@
3232
#include "tracing/trace_event.h"
3333

3434
#include "req_wrap-inl.h"
35+
#include "simdjson.h"
3536
#include "stream_base-inl.h"
3637
#include "string_bytes.h"
38+
#include "v8-primitive.h"
3739

3840
#include <fcntl.h>
3941
#include <sys/types.h>
@@ -1079,41 +1081,94 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
10791081
}
10801082

10811083
const size_t size = offset - start;
1082-
char* p = &chars[start];
1083-
char* pe = &chars[size];
1084-
char* pos[2];
1085-
char** ppos = &pos[0];
1086-
1087-
while (p < pe) {
1088-
char c = *p++;
1089-
if (c == '\\' && p < pe && *p == '"') p++;
1090-
if (c != '"') continue;
1091-
*ppos++ = p;
1092-
if (ppos < &pos[2]) continue;
1093-
ppos = &pos[0];
1094-
1095-
char* s = &pos[0][0];
1096-
char* se = &pos[1][-1]; // Exclude quote.
1097-
size_t n = se - s;
1098-
1099-
if (n == 4) {
1100-
if (0 == memcmp(s, "main", 4)) break;
1101-
if (0 == memcmp(s, "name", 4)) break;
1102-
if (0 == memcmp(s, "type", 4)) break;
1103-
} else if (n == 7) {
1104-
if (0 == memcmp(s, "exports", 7)) break;
1105-
if (0 == memcmp(s, "imports", 7)) break;
1084+
simdjson::ondemand::parser parser;
1085+
simdjson::padded_string json_string(chars.data() + start, size);
1086+
simdjson::ondemand::document document;
1087+
simdjson::ondemand::object obj;
1088+
auto error = parser.iterate(json_string).get(document);
1089+
1090+
if (error || document.get_object().get(obj)) {
1091+
args.GetReturnValue().Set(Array::New(isolate));
1092+
return;
1093+
}
1094+
1095+
auto js_string = [&](std::string_view sv) {
1096+
return ToV8Value(env->context(), sv, isolate).ToLocalChecked();
1097+
};
1098+
1099+
bool includes_keys{false};
1100+
Local<Value> name = Undefined(isolate);
1101+
Local<Value> main = Undefined(isolate);
1102+
Local<Value> exports = Undefined(isolate);
1103+
Local<Value> imports = Undefined(isolate);
1104+
Local<Value> type = Undefined(isolate);
1105+
bool parse_exports{false};
1106+
bool parse_imports{false};
1107+
1108+
// Check for "name" field
1109+
std::string_view name_value{};
1110+
if (!obj["name"].get_string().get(name_value)) {
1111+
name = js_string(name_value);
1112+
includes_keys = true;
1113+
}
1114+
1115+
// Check for "main" field
1116+
std::string_view main_value{};
1117+
if (!obj["main"].get_string().get(main_value)) {
1118+
main = js_string(main_value);
1119+
includes_keys = true;
1120+
}
1121+
1122+
// Check for "exports" field
1123+
simdjson::ondemand::object exports_object;
1124+
std::string_view exports_value{};
1125+
if (!obj["exports"].get_object().get(exports_object)) {
1126+
if (!exports_object.raw_json().get(exports_value)) {
1127+
exports = js_string(exports_value);
1128+
includes_keys = true;
1129+
parse_exports = true;
1130+
}
1131+
} else if (!obj["exports"].get(exports_value)) {
1132+
exports = js_string(exports_value);
1133+
includes_keys = true;
1134+
}
1135+
1136+
// Check for "imports" field
1137+
simdjson::ondemand::object imports_object;
1138+
std::string_view imports_value;
1139+
if (!obj["imports"].get_object().get(imports_object)) {
1140+
if (!imports_object.raw_json().get(imports_value)) {
1141+
imports = js_string(imports_value);
1142+
includes_keys = true;
1143+
parse_imports = true;
11061144
}
1145+
} else if (!obj["imports"].get(imports_value)) {
1146+
imports = js_string(imports_value);
1147+
includes_keys = true;
11071148
}
11081149

1150+
// Check for "type" field
1151+
std::string_view type_value = "none";
1152+
if (!obj["type"].get(type_value)) {
1153+
// Ignore unknown types for forwards compatibility
1154+
if (type_value != "module" && type_value != "commonjs") {
1155+
type_value = "none";
1156+
}
1157+
includes_keys = true;
1158+
}
1159+
type = js_string(type_value);
11091160

11101161
Local<Value> return_value[] = {
1111-
String::NewFromUtf8(isolate,
1112-
&chars[start],
1113-
v8::NewStringType::kNormal,
1114-
size).ToLocalChecked(),
1115-
Boolean::New(isolate, p < pe ? true : false)
1162+
Boolean::New(isolate, includes_keys),
1163+
name,
1164+
main,
1165+
exports,
1166+
imports,
1167+
type,
1168+
Boolean::New(isolate, parse_exports),
1169+
Boolean::New(isolate, parse_imports),
11161170
};
1171+
11171172
args.GetReturnValue().Set(
11181173
Array::New(isolate, return_value, arraysize(return_value)));
11191174
}

0 commit comments

Comments
 (0)