1 | import fs from 'node:fs';
|
2 | import fsPromises from 'node:fs/promises';
|
3 | import path from 'node:path';
|
4 | import parseJson from 'parse-json';
|
5 | import normalizePackageData from 'normalize-package-data';
|
6 | import {toPath} from 'unicorn-magic';
|
7 |
|
8 | const getPackagePath = cwd => path.resolve(toPath(cwd) ?? '.', 'package.json');
|
9 |
|
10 | const _readPackage = (file, normalize) => {
|
11 | const json = typeof file === 'string'
|
12 | ? parseJson(file)
|
13 | : file;
|
14 |
|
15 | if (normalize) {
|
16 | normalizePackageData(json);
|
17 | }
|
18 |
|
19 | return json;
|
20 | };
|
21 |
|
22 | export async function readPackage({cwd, normalize = true} = {}) {
|
23 | const packageFile = await fsPromises.readFile(getPackagePath(cwd), 'utf8');
|
24 | return _readPackage(packageFile, normalize);
|
25 | }
|
26 |
|
27 | export function readPackageSync({cwd, normalize = true} = {}) {
|
28 | const packageFile = fs.readFileSync(getPackagePath(cwd), 'utf8');
|
29 | return _readPackage(packageFile, normalize);
|
30 | }
|
31 |
|
32 | export function parsePackage(packageFile, {normalize = true} = {}) {
|
33 | const isObject = packageFile !== null && typeof packageFile === 'object' && !Array.isArray(packageFile);
|
34 | const isString = typeof packageFile === 'string';
|
35 |
|
36 | if (!isObject && !isString) {
|
37 | throw new TypeError('`packageFile` should be either an `object` or a `string`.');
|
38 | }
|
39 |
|
40 | const clonedPackageFile = isObject ? structuredClone(packageFile) : packageFile;
|
41 |
|
42 | return _readPackage(clonedPackageFile, normalize);
|
43 | }
|