Debian Codegraph @

packages/babel-core/src/config/files/package.ts

raw
1 import path from "path";
2 import type { Handler } from "gensync";
3 import { makeStaticFileCache } from "./utils";
4
5 import type { ConfigFile, FilePackageData } from "./types";
6
7 import ConfigError from "../../errors/config-error";
8
9 const PACKAGE_FILENAME = "package.json";
10
11 const readConfigPackage = makeStaticFileCache(
12 (filepath, content): ConfigFile => {
13 let options;
14 try {
15 options = JSON.parse(content) as unknown;
16 } catch (err) {
17 throw new ConfigError(
18 `Error while parsing JSON - ${err.message}`,
19 filepath,
20 );
21 }
22
23 if (!options) throw new Error(`${filepath}: No config detected`);
24
25 if (typeof options !== "object") {
26 throw new ConfigError(
27 `Config returned typeof ${typeof options}`,
28 filepath,
29 );
30 }
31 if (Array.isArray(options)) {
32 throw new ConfigError(`Expected config object but found array`, filepath);
33 }
34
35 return {
36 filepath,
37 dirname: path.dirname(filepath),
38 options,
39 };
40 },
41 );
42
43 /**
44 * Find metadata about the package that this file is inside of. Resolution
45 * of Babel's config requires general package information to decide when to
46 * search for .babelrc files
47 */
48 export function* findPackageData(filepath: string): Handler<FilePackageData> {
49 let pkg = null;
50 const directories = [];
51 let isPackage = true;
52
53 let dirname = path.dirname(filepath);
54 while (!pkg && path.basename(dirname) !== "node_modules") {
55 directories.push(dirname);
56
57 pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME));
58
59 const nextLoc = path.dirname(dirname);
60 if (dirname === nextLoc) {
61 isPackage = false;
62 break;
63 }
64 dirname = nextLoc;
65 }
66
67 return { filepath, directories, pkg, isPackage };
68 }