UNPKG

1.99 kBJavaScriptView Raw
1'use strict';
2
3const path = require('path');
4const { readFileSync } = require('fs');
5const readPkgUp = require('read-pkg-up');
6const { render } = require('mustache');
7
8const NAME = '@extensionengine/tailor-ce';
9const PREFIX = '\0virtual:';
10const REGISTRY = '__TAILOR_CONTENT_ELEMENTS__';
11const SCOPE = /^@[^/]+\//;
12const TEMPLATE = readFileSync(require.resolve('./dist/plugin'), 'utf-8');
13
14const isObject = arg => arg !== null && typeof arg === 'object';
15const normalize = modulePath => path.resolve(process.cwd(), modulePath);
16
17module.exports = function () {
18 let entryId;
19 let entryCode;
20 let pkg;
21
22 return {
23 name: NAME,
24 /** @param {import('rollup').InputOptions} options */
25 async options(options) {
26 // Create virtual entry module.
27 const [entry] = getInput(options.input);
28 const entryPath = normalize(entry);
29 const cwd = path.dirname(entryPath);
30 const { packageJson, path: packagePath } = await readPkgUp({ cwd });
31 pkg = packageJson;
32 entryId = [PREFIX, entryPath].join('');
33 entryCode = render(TEMPLATE, {
34 packagePath: normalize(packagePath),
35 entryPath
36 });
37 // Set `options.input` to newly created entry.
38 const entryName = pkg.name.replace(SCOPE, '');
39 const input = { [entryName]: entryId };
40 Object.assign(options, { input });
41 return options;
42 },
43 /** @param {import('rollup').OutputOptions} options */
44 outputOptions(options) {
45 const name = [REGISTRY, pkg.name].join('.');
46 return Object.assign(options, { name });
47 },
48 /** @param {string} id */
49 resolveId(id) {
50 return id === entryId ? id : null;
51 },
52 /** @param {string} id */
53 load(id) {
54 return id === entryId ? entryCode : null;
55 }
56 };
57};
58
59/**
60 * @param {import('rollup').InputOption} input
61 * @return {Array<string>}
62 */
63function getInput(input) {
64 if (isObject(input)) return Object.values(input);
65 if (Array.isArray(input)) return input;
66 return [input];
67}