infopack
Version:
Information package generator
348 lines (347 loc) • 15.3 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Executor = exports.Pipeline = exports.PipelineStep = void 0;
var fs = __importStar(require("fs"));
var path = __importStar(require("path"));
var bluebird_1 = require("bluebird");
var Handlebars = __importStar(require("handlebars"));
var promises_1 = require("fs/promises");
var lodash_1 = __importDefault(require("lodash"));
var process_1 = require("process");
function truncateString(str, maxLength) {
if (maxLength === void 0) { maxLength = 70; }
if (str.length > maxLength) {
return str.slice(0, maxLength - 3) + '...';
}
return str;
}
Handlebars.registerHelper('ifEquals', function (arg1, arg2, options) {
// @ts-ignore
return (arg2.split('|').indexOf(arg1) > -1) ? options.fn(this) : options.inverse(this);
});
var PipelineStep = /** @class */ (function () {
function PipelineStep(runFn, settings) {
this.settings = settings || {};
this.run = runFn;
}
return PipelineStep;
}());
exports.PipelineStep = PipelineStep;
/**
* Main class that produces output from the input via a pipeline
*/
var Pipeline = /** @class */ (function () {
function Pipeline(inputSteps, options) {
if (options === void 0) { options = {}; }
var _this = this;
this.indexHtml = '';
this.sidecarHtml = '';
/**
* Method to start the pipeline operation
*/
this.run = function () {
console.log('Pipeline run started...');
console.log('Base path: ' + _this.basePath);
console.log('Input folder: ' + _this.inputPath);
console.log('Output folder: ' + _this.outputPath);
console.log('Cache folder: ' + _this.cachePath);
bluebird_1.Promise
.resolve()
.then(function () { return _this.importIndexTemplate(_this.indexHtmlPath); })
.then(function () { return _this.importSidecarTemplate(_this.sidecarHtmlPath); })
.then(function () {
var executor = new Executor(_this);
return executor.execute();
});
};
this.addStep = function (step) {
_this.steps.push(step);
};
// cmd prioritized
var tmpVersionSuffix = process_1.argv[2] || options.versionSuffix;
this.steps = inputSteps;
this.namespace = options.namespace || '';
this.title = options.title || '';
this.versionSuffix = process_1.argv[2] || undefined;
this.versionSuffix = tmpVersionSuffix || undefined;
this.basePath = path.resolve(options.basePath || '');
this.inputPath = path.join(this.basePath, options.inputFolderName || 'input');
this.outputPath = path.join(this.basePath, options.outputFolderName || 'output');
this.cachePath = path.join(this.basePath, options.cacheFolderName || 'cache');
this.indexHtmlPath = options.indexHtmlPath || path.join(__dirname, '..', 'templates', 'index.template.html');
this.sidecarHtmlPath = options.sidecarHtmlPath || path.join(__dirname, '..', 'templates', 'sidecar.template.html');
}
Pipeline.prototype.getSteps = function () {
return this.steps;
};
Pipeline.prototype.getBasePath = function (relPath) {
return path.join(this.basePath, relPath || '');
};
Pipeline.prototype.getInputPath = function (relPath) {
return path.join(this.inputPath, relPath || '');
};
Pipeline.prototype.getOutputPath = function () {
return this.outputPath;
};
Pipeline.prototype.getCachePath = function () {
return this.cachePath;
};
Pipeline.prototype.getNamespace = function () {
return this.namespace;
};
Pipeline.prototype.getTitle = function () {
return this.title;
};
Pipeline.prototype.getVersionSuffix = function () {
return this.versionSuffix;
};
/**
* Import index template
* @param filePath Optional absolute path to template
*/
Pipeline.prototype.importIndexTemplate = function (filePath) {
var _this = this;
return (0, promises_1.readFile)(filePath)
.then(function (buff) { return buff.toString(); })
.then(function (html) {
_this.indexHtml = html;
return html;
});
};
/**
* Import sidecar template
* @param filePath Optional absolute path to template
*/
Pipeline.prototype.importSidecarTemplate = function (filePath) {
var _this = this;
return (0, promises_1.readFile)(filePath)
.then(function (buff) { return buff.toString(); })
.then(function (html) {
_this.sidecarHtml = html;
return html;
});
};
return Pipeline;
}());
exports.Pipeline = Pipeline;
var Executor = /** @class */ (function () {
function Executor(pipeline) {
var _this = this;
this.finished = false;
this.currentStep = 0;
this.writeQueue = [];
this.meta = { $schema: 'https://schemas.infopack.io/infopack-index.2.schema.json' };
this.files = [];
this.test = {};
this.execute = function () {
console.log('Executing');
return bluebird_1.Promise
.resolve()
.then(function () { return _this.rmdir(_this.getOutputPath()); })
.then(function () { return _this.rmdir(_this.getCachePath()); })
.then(function () { return _this.mkdir(_this.getOutputPath()); })
.then(function () { return _this.createMeta(); })
.then(function () { return bluebird_1.Promise.mapSeries(_this.pipeline.getSteps(), function (step, i) {
console.log('== running step ' + i + ' ==');
return step.run(_this)
.then(function () { return _this.writeOutput('cache'); })
.then(function () { return _this.currentStep++; });
}); })
.then(function () { return _this.writeOutput(); })
.then(function () {
console.log('=== Steps complete ===');
console.log(' Writing index');
_this.files = lodash_1.default.sortBy(_this.files, 'path');
var tempFiles = lodash_1.default.map(_this.files, function (file) {
var $schema = file.$schema, fileWithout$schema = __rest(file, ["$schema"]);
return fileWithout$schema;
});
var templateData = Object.assign({ files: tempFiles }, _this.meta);
// write .json file
fs.writeFileSync(_this.getOutputPath() + '/index.json', JSON.stringify(templateData, null, 2));
// write .html file
var template = Handlebars.compile(_this.pipeline.indexHtml);
var output = template(templateData);
fs.writeFileSync(_this.getOutputPath() + '/index.html', output);
});
};
this.pipeline = pipeline;
}
/**
* This method will add infopackContent to the files queue.
* @param infopackContent
*/
Executor.prototype.toOutput = function (infopackContentInput) {
var infopackContent = {
$schema: 'https://schemas.infopack.io/infopack-meta.2.schema.json',
path: infopackContentInput.path,
dirname: path.dirname(infopackContentInput.path),
filename: path.basename(infopackContentInput.path),
extname: path.extname(infopackContentInput.path),
data: infopackContentInput.data,
title: infopackContentInput.title,
description: infopackContentInput.description
};
if (infopackContentInput.labels) {
infopackContent.labels = infopackContentInput.labels;
}
if (infopackContentInput.origin) {
infopackContent.origin = infopackContentInput.origin;
}
this.writeQueue.push(infopackContent);
};
Executor.prototype.rmdir = function (path) {
return new bluebird_1.Promise(function (resolve, reject) {
if (!fs.existsSync(path))
resolve();
console.log('Cleaning ' + path);
fs.rm(path, { recursive: true, force: true }, function (err) {
if (err)
reject(err);
resolve();
});
});
};
Executor.prototype.mkdir = function (path) {
return new bluebird_1.Promise(function (resolve, reject) {
fs.mkdir(path, { recursive: true }, function (err) {
if (err)
reject(err);
return resolve();
});
});
};
/**
* Write buffered files to disk
* @param target Specifies output target. Provide cache to write to cache
* @returns Promise<any>
*/
Executor.prototype.writeOutput = function (target) {
var _this = this;
var outputPath = (target === 'cache') ? path.join(this.getCachePath(), this.currentStep + '') : this.getOutputPath();
var indexPath = outputPath + '/index.html';
console.log(' Writing output to: ' + outputPath);
console.log(' Index file path: ' + indexPath);
return bluebird_1.Promise
.resolve()
.then(function () { return bluebird_1.Promise.mapSeries(_this.writeQueue, function (content) {
var absFilePath = path.join(outputPath, content.path);
var absDirPath = path.join(outputPath, content.path.replace(content.filename, ''));
console.log(' Writing to folder: ' + absDirPath);
console.log(' Writing file "' + content.title + '" to path ' + absFilePath);
return _this
.mkdir(path.dirname(absFilePath))
.then(function (made) {
// if (made) console.log('Created folder: ' + made)
var data = content.data, fileMeta = __rest(content
// write file to disk
, ["data"]);
// write file to disk
fs.writeFileSync(absFilePath, data);
// create sidecar json file
var _a = _this.meta, $schema = _a.$schema, metaWithout$schema = __rest(_a, ["$schema"]);
var sidecarData = Object.assign({ meta: metaWithout$schema }, fileMeta);
fs.writeFileSync(absFilePath + '.meta.json', JSON.stringify(sidecarData, null, 2));
// create sidecar html file
var template = Handlebars.compile(_this.pipeline.sidecarHtml);
/**
* Handle https://html-validate.org/rules/long-title.html
*/
var cappedTitle = truncateString(sidecarData.title + " - " + sidecarData.meta.title);
fs.writeFileSync(absFilePath + '.meta.html', template(__assign(__assign({}, sidecarData), { cappedTitle: cappedTitle })));
// push file to meta file index
if (target !== 'cache') {
var temp = Object.assign({
metaHtmlPath: "".concat(fileMeta.path, ".meta.html"),
metaJsonPath: "".concat(fileMeta.path, ".meta.json")
}, fileMeta);
_this.files.push(temp);
}
// console.log(' write finished')
return true;
});
}); })
.then(function () { return fs.writeFileSync(outputPath + '/infopack.json', JSON.stringify({ $schema: 'https://schemas.infopack.io/infopack-infopack.1.schema.json', framework_version: '2.0.0', implementation: 'node' }, null, 2)); });
};
Executor.prototype.getBasePath = function (relPath) {
return this.pipeline.getBasePath(relPath);
};
Executor.prototype.getInputPath = function (relPath) {
return this.pipeline.getInputPath(relPath);
};
Executor.prototype.getOutputPath = function () {
return this.pipeline.getOutputPath();
};
Executor.prototype.getCachePath = function () {
return this.pipeline.getCachePath();
};
Executor.prototype.createMeta = function () {
var packageInfo = JSON.parse(fs.readFileSync(this.getBasePath('package.json')).toString());
this.meta.namespace = this.pipeline.getNamespace();
this.meta.title = this.pipeline.getTitle();
this.meta.name = packageInfo.name;
this.meta.description = packageInfo.description;
this.meta.version = this.pipeline.getVersionSuffix() ? "".concat(packageInfo.version, "-").concat(this.pipeline.getVersionSuffix()) : packageInfo.version;
this.meta.packagedAt = new Date().toISOString().slice(0, 10);
};
return Executor;
}());
exports.Executor = Executor;