UNPKG

8.12 kBJavaScriptView Raw
1'use strict';
2
3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
5var fs = _interopDefault(require('fs'));
6var path = _interopDefault(require('path'));
7var r = _interopDefault(require('rollup'));
8var commonjs = _interopDefault(require('rollup-plugin-commonjs'));
9var pify = _interopDefault(require('pify'));
10var pMap = _interopDefault(require('p-map'));
11var today = _interopDefault(require('time-stamp'));
12var isObject = _interopDefault(require('isobject'));
13var isPromise = _interopDefault(require('p-is-promise'));
14var prettyConfig = _interopDefault(require('@tunnckocore/pretty-config'));
15var builtinModules = _interopDefault(require('builtin-modules'));
16var isCI = _interopDefault(require('is-ci'));
17
18/* eslint-disable import/max-dependencies, import/no-nodejs-modules */
19
20/* eslint-disable */
21function _objectWithoutProperties(source, excluded) {
22 if (source == null) return {};
23 const target = {};
24 const sourceKeys = Object.keys(source);
25 let key, i;
26 for (i = 0; i < sourceKeys.length; i++) {
27 key = sourceKeys[i];
28 if (excluded.indexOf(key) >= 0) continue;
29 target[key] = source[key];
30 }
31 if (Object.getOwnPropertySymbols) {
32 const sourceSymbolKeys = Object.getOwnPropertySymbols(source);
33 for (i = 0; i < sourceSymbolKeys.length; i++) {
34 key = sourceSymbolKeys[i];
35 if (excluded.indexOf(key) >= 0) continue;
36 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
37 target[key] = source[key];
38 }
39 }
40 return target;
41}
42/* eslint-enable */
43
44function arrayify(val) {
45 if (!val) return [];
46 if (Array.isArray(val)) return val;
47 return [val];
48}
49
50function getName(fp) {
51 const ext = path.extname(fp);
52 const basename = path.basename(fp, ext);
53 return basename;
54}
55
56/**
57 * TODO
58 *
59 * @param {*} bundle
60 * @param {*} outputOptions
61 */
62// function rollupGenerate(bundle, outputOptions) {
63// return bundle.generate(outputOptions).then(({ code, map }) => ({
64// outputOptions,
65// code,
66// map,
67// }));
68// }
69
70function rollupWrite(bundle, inputOptions_, outputOptions) {
71 const inputOptions = _objectWithoutProperties(inputOptions_, ['output']);
72
73 return bundle.write(outputOptions).then(() => ({ inputOptions, outputOptions }));
74}
75
76let CACHE = null;
77async function rolldown(config) {
78 /**
79 * If returned is Rollup Config object
80 */
81
82 if (isObject(config)) {
83 const opts = Object.assign({}, config);
84
85 if (Array.isArray(opts.input) && !opts.experimentalCodeSplitting) {
86 const cfg = multipleInputs(opts);
87
88 return rolldown(cfg);
89 }
90
91 if (opts.input && opts.output) {
92 const outputs = arrayify(opts.output).reduce(
93 (acc, item) => acc.concat(typeof item === 'string' ? { format: item } : item),
94 [],
95 );
96 opts.output = outputs;
97 opts.cache = CACHE;
98
99 const bundle = await r.rollup(opts);
100 CACHE = bundle;
101
102 const targetMapper = createMapper(bundle, opts);
103
104 return pMap(outputs, targetMapper);
105 }
106
107 /**
108 * If configs found, but for example only `plugins` is given,
109 * then extend the defaults with these coming configs.
110 */
111
112 const obj = await extendDefaults(opts);
113
114 // todo
115 console.log('extendDefaults', obj);
116 return [];
117 // return rolldown(extendDefaults(opts))
118 }
119
120 /**
121 * If returned is Array of Rollup Config objects
122 */
123
124 if (Array.isArray(config)) {
125 return pMap(config, (cfg) => rolldown(cfg));
126 }
127
128 /**
129 * If not found configs and not passed,
130 * then create some basic defaults.
131 * The `config` is `null` here.
132 */
133
134 console.log('config', config);
135 return [];
136 // return rolldown(createDefaults())
137}
138
139function multipleInputs(opts) {
140 return opts.input.filter(Boolean).reduce((acc, inputItem) => {
141 const input = _objectWithoutProperties(inputItem, ['input']);
142
143 return acc.concat(Object.assign({ input }, opts));
144 }, []);
145}
146
147function createMapper(bundle, opts) {
148 return function targetMapper(outputOptions) {
149 const outFile = outputOptions.file || opts.file;
150 let options = null;
151
152 // if `output.file` exist, use it;
153 // otherwise create `output.file` from given `input` and `output.format`
154 if (outFile) {
155 // support basic placeholders
156 const file = outFile
157 .replace('[date]', today())
158 .replace('[name]', getName(opts.input))
159 .replace('[format]', outputOptions.format);
160
161 options = { file };
162 } else {
163 // construct `foo.es.js`
164 const fmt = outputOptions.format;
165 const basename = `${getName(opts.input)}.${fmt}.js`;
166 const file = path.join('dist', basename);
167 options = { file };
168 }
169
170 options = Object.assign({}, outputOptions, options);
171
172 return rollupWrite(bundle, opts, options);
173 };
174}
175
176async function extendDefaults(incomingOptions) {
177 const filepath = 'src/cli.js';
178 const hasCLI = fs.existsSync(filepath);
179
180 return Object.assign(
181 {
182 input: ['src/index.js', hasCLI ? filepath : false],
183 output: [{ format: 'cjs' }, { format: 'es' }],
184 external: builtinModules,
185 },
186 incomingOptions,
187 );
188}
189
190function getPkg(cwd) {
191 return pify(fs.readFile)(path.join(cwd, 'package.json'), 'utf8').then(JSON.parse);
192}
193
194async function run(cwd) {
195 const configFiles = prettyConfig.configFiles
196 .slice(0, -1)
197 .reduce((acc, item) => acc.concat(`src/${item}`, item), [])
198 .concat('package.json');
199
200 let settings = await prettyConfig('rollup', { configFiles });
201
202 if (!settings) {
203 settings = await prettyConfig('rolldown', { configFiles });
204 }
205
206 if (isPromise(settings)) {
207 settings = await settings;
208 }
209
210 const pkg = await getPkg(cwd);
211 settings.external = builtinModules.concat(Object.keys(pkg.dependencies));
212 settings.plugins = [commonjs()];
213
214 return rolldown(settings);
215}
216
217/**
218 * CLI?
219 */
220
221async function runnerWithLog(opts) {
222 const results = await run(opts.cwd);
223 const res = results.reduce((acc, config) => acc.concat(config), []).filter(Boolean);
224
225 const log = (cfg) => {
226 console.log(cfg.inputOptions.input, '->', cfg.outputOptions.file);
227 };
228
229 res.forEach((config) => {
230 if (Array.isArray(config)) {
231 config.forEach(log);
232 } else {
233 log(config);
234 }
235 });
236}
237
238/**
239 * @copyright 2017-present, Charlike Mike Reagent <olsten.larck@gmail.com>
240 * @license Apache-2.0
241 */
242
243const lint = async ({ argv, shell }) => {
244 let cmd = 'eslint src test -f codeframe --quiet --fix';
245
246 if (argv.dry) {
247 cmd = `${cmd} --fix-dry`;
248 } else {
249 cmd = `${cmd} --fix`;
250 }
251
252 return shell(cmd);
253};
254
255const build = async (opts) => {
256 const { shell } = opts;
257 await shell('rm -rf dist');
258 await runnerWithLog(opts);
259};
260
261const test = async (opts) => {
262 const { argv, shell } = opts;
263
264 const flags = Object.assign({ path: 'test', build: true }, argv);
265 const cmd = `node ${flags.path}`;
266
267 if (flags.build) {
268 await build(opts);
269 }
270
271 if (flags.cov === false) {
272 return shell(`node ${flags.path}`);
273 }
274 if (flags.check === false) {
275 return shell([`nyc --reporter=lcov ${cmd}`, 'nyc report']);
276 }
277
278 return shell([`nyc --reporter=lcov ${cmd}`, 'nyc report', 'nyc check-coverage']);
279};
280
281const commit = async (opts) => {
282 const { argv, shell } = opts;
283
284 if (argv.lint !== false) {
285 await lint(opts);
286 }
287
288 if (argv.dry) {
289 return shell(['git add --all', 'gitcommit -s -S']);
290 }
291
292 if (argv.docs !== false) {
293 await shell('yarn start docs');
294 }
295
296 if (argv.test !== false) {
297 await test(opts);
298 }
299
300 return shell(['git status --porcelain', 'git add --all', 'gitcommit -s -S']);
301};
302
303const docs = 'verb';
304
305const protect = async () => {
306 if (!isCI) {
307 const msg = 'the "npm publish" is forbidden, we release and publish on CI service';
308 throw new Error(msg);
309 }
310};
311
312const release = async (opts) => {
313 const { argv, shell } = opts;
314 const flags = Object.assign({ build: true }, argv);
315
316 if (flags.build) {
317 await build(opts);
318 }
319
320 await protect();
321
322 return shell('new-release');
323};
324
325const tasks = {
326 lint,
327 test,
328 commit,
329 docs,
330 build,
331 release,
332 protect,
333};
334
335var index = { tasks };
336
337module.exports = index;