UNPKG

3.15 kBJavaScriptView Raw
1import * as path from 'path';
2import * as constants from './constants.js';
3import { MessageError } from '@pika/types';
4import * as fs from './util/fs.js';
5import normalizeManifest from './util/normalize-manifest/index.js';
6import detectIndent from 'detect-indent';
7import executeLifecycleScript from './util/execute-lifecycle-script.js';
8import importFrom from 'import-from';
9export default class Config {
10 constructor(reporter, cwd, flags) {
11 this.reporter = reporter;
12 // Ensure the cwd is always an absolute path.
13 this.cwd = path.resolve(cwd || process.cwd());
14 this.flags = flags;
15 }
16 async loadPackageManifest() {
17 const loc = path.join(this.cwd, constants.NODE_PACKAGE_JSON);
18 if (await fs.exists(loc)) {
19 const info = await this.readJson(loc, fs.readJsonAndFile);
20 this._manifest = { ...info.object };
21 this.manifestIndent = detectIndent(info.content).indent || undefined;
22 this.manifest = await normalizeManifest(info.object, this.cwd, this, true);
23 return this.manifest;
24 }
25 else {
26 return null;
27 }
28 }
29 readJson(loc, factory = fs.readJson) {
30 try {
31 return factory(loc);
32 }
33 catch (err) {
34 if (err instanceof SyntaxError) {
35 throw new MessageError(this.reporter.lang('jsonError', loc, err.message));
36 }
37 else {
38 throw err;
39 }
40 }
41 }
42 async savePackageManifest(newManifestData) {
43 const loc = path.join(this.cwd, constants.NODE_PACKAGE_JSON);
44 const manifest = {
45 ...this._manifest,
46 ...newManifestData
47 };
48 await fs.writeFilePreservingEol(loc, JSON.stringify(manifest, null, this.manifestIndent || constants.DEFAULT_INDENT) + '\n');
49 return this.loadPackageManifest();
50 }
51 async getDistributions() {
52 const raw = this.manifest[`@pika/pack`] || {};
53 const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);
54 const cwd = this.cwd;
55 function cleanRawDistObject(rawVal) {
56 if (Array.isArray(rawVal)) {
57 let importStr = (rawVal[0].startsWith('./') || rawVal[0].startsWith('../')) ? path.join(cwd, rawVal[0]) : rawVal[0];
58 return [{ ...importFrom(cwd, importStr), name: rawVal[0] }, rawVal[1] || {}];
59 }
60 if (typeof rawVal === 'string') {
61 return [{ build: ({ cwd }) => {
62 return executeLifecycleScript({
63 // config: this,
64 args: [],
65 cwd,
66 cmd: rawVal,
67 isInteractive: false
68 });
69 } }, {}];
70 }
71 if (!rawVal) {
72 throw new Error('Cannot be false');
73 }
74 return false;
75 }
76 const pipeline = override || raw.pipeline || [];
77 return pipeline.map(cleanRawDistObject).filter(Boolean);
78 }
79}