UNPKG

@homer0/package-info

Version:

Gets the content of the project's package.json

74 lines 2.35 kB
import * as fsSync from "fs"; import * as fsPromises from "fs/promises"; import { pathUtils } from "@homer0/path-utils"; import { deferred } from "@homer0/deferred"; import { providerCreator, injectHelper } from "@homer0/jimple"; const deps = injectHelper(); class PackageInfo { /** * A deferred promise that resolves when the package.json file is read. It will be * `undefined` if the file hasn't been read yet, or the contents are already saved in * the service. */ defer; /** * This property will store the contents of the file once it is read. */ contents; /** * The absolute path to the package.json file. */ filepath; constructor({ inject = {} } = {}) { const usePathUtils = deps.get(inject, "pathUtils", () => pathUtils()); this.filepath = usePathUtils.join("package.json"); } /** * Gets the contents of the implementation's package.json file. */ async get() { if (this.contents) return this.contents; if (this.defer) return this.defer.promise; this.defer = deferred(); const packageJson = await fsPromises.readFile(this.filepath, "utf8"); return this.updateContents(packageJson); } /** * Synchronously gets the contents of the implementation's package.json file. */ getSync() { if (this.contents) return this.contents; const packageJson = fsSync.readFileSync(this.filepath, "utf8"); return this.updateContents(packageJson); } /** * This is a helper that takes care of updating the property with the file contents, and * if the deferred promise exists, resolve it and delete it. * * @param contents The contents of the package.json file. */ updateContents(contents) { this.contents = JSON.parse(contents); if (this.defer) { this.defer.resolve(this.contents); this.defer = void 0; } return this.contents; } } const packageInfo = (...args) => new PackageInfo(...args); const packageInfoProvider = providerCreator( ({ serviceName = "packageInfo", ...rest } = {}) => (container) => { container.set(serviceName, () => { const { services = {} } = rest; const inject = deps.resolve(["pathUtils"], container, services); return new PackageInfo({ inject }); }); } ); export { PackageInfo, packageInfo, packageInfoProvider }; //# sourceMappingURL=index.js.map