New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

symply

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

symply - npm Package Compare versions

Comparing version 0.8.0 to 0.9.0

dist/handlebars/helpers.js

213

dist/commands/generate.js

@@ -32,9 +32,4 @@ "use strict";

const handlebars_1 = __importDefault(require("handlebars"));
const html_minifier_1 = require("html-minifier");
const lodash_1 = __importDefault(require("lodash"));
const minimatch_1 = __importDefault(require("minimatch"));
const path_1 = __importDefault(require("path"));
const prettier_1 = __importDefault(require("prettier"));
const sass_1 = __importDefault(require("sass"));
const blockHelpers = __importStar(require("../blockHelpers"));
const configuration_1 = __importDefault(require("../configuration"));

@@ -46,4 +41,10 @@ const Actions = __importStar(require("../entities/actions"));

const filesystem = __importStar(require("../filesystem"));
const helperRigistration = __importStar(require("../handlebars/helpers"));
const unusedPartials = __importStar(require("../handlebars/unusedPartials"));
const logger_1 = __importDefault(require("../logger"));
const progressBar_1 = __importDefault(require("../progressBar"));
const htmlFormatter = __importStar(require("../tools/htmlFormatter"));
const htmlMinifier = __importStar(require("../tools/htmlMinifier"));
const sassCompiler = __importStar(require("../tools/sassCompiler"));
const tsTranspiler = __importStar(require("../tools/tsTranspiler"));
async function generate() {

@@ -55,25 +56,40 @@ var _a, _b;

};
await Actions.runPreBuildAsync((_a = configuration_1.default.getActions().preBuild) === null || _a === void 0 ? void 0 : _a.filter((action) => !action.skip));
configuration_1.default.debugOutput && unusedPartials.initUnusedPartialsDetector();
await Actions.runPreBuildAsync((_a = configuration_1.default.actions.preBuild) === null || _a === void 0 ? void 0 : _a.filter((action) => !action.skip));
const globals = Globals.load();
const partials = Partials.load();
const { scssSourceFiles, cssSourceFiles, htmlSourceFiles, hbsSourceFiles, jsSourceFiles, otherSourceFiles } = scanSourceFiles();
registerPartials(partials);
registerMissingPropertyHelper();
helperRigistration.helperMissing();
// Block helpers registration
blockHelpers.if_eq();
blockHelpers.if_ne();
blockHelpers.if_gt();
blockHelpers.if_ge();
blockHelpers.if_lt();
blockHelpers.if_le();
blockHelpers.if_and();
blockHelpers.if_or();
blockHelpers.if_xor();
helperRigistration.if_eq();
helperRigistration.if_ne();
helperRigistration.if_gt();
helperRigistration.if_ge();
helperRigistration.if_lt();
helperRigistration.if_le();
helperRigistration.if_and();
helperRigistration.if_or();
helperRigistration.if_xor();
injectGlobalsToHelpers(globals);
clearDistributionDirectoryIfNeeded();
/*-----------------------------------------------------------------------------
* Processing files from `sourceDirectoryPath`
*----------------------------------------------------------------------------*/
const { scssSourceFiles, cssSourceFiles, htmlSourceFiles, hbsSourceFiles, jsSourceFiles, tsSourceFiles, otherSourceFiles, } = scanSourceFiles();
/*-----------------------------------------------------------------------------
* Styles
*----------------------------------------------------------------------------*/
const compiledSassSourceFiles = compileSassAndCopyToDistributionDirectory(scssSourceFiles, stats);
const cssSourceFilesWithContents = loadSourceFilesContents(cssSourceFiles);
helperRigistration.embeddedStyles([...compiledSassSourceFiles, ...cssSourceFilesWithContents]);
/*-----------------------------------------------------------------------------
* Scripts
*----------------------------------------------------------------------------*/
const jsSourceFilesWithContents = loadSourceFilesContents(jsSourceFiles);
registerEmbeddedStylesInjectorHelper([...compiledSassSourceFiles, ...cssSourceFilesWithContents]);
registerEmbeddedScriptInjectorHelper(jsSourceFilesWithContents);
const tsSourceFilesWithContents = loadSourceFilesContents(tsSourceFiles);
const tsTranspiledSourceFilesWithContents = transpileTypescriptFilesAndCopyToDistributionDirectory(tsSourceFilesWithContents, jsSourceFiles, stats);
helperRigistration.embeddedScript([...jsSourceFilesWithContents, ...tsTranspiledSourceFilesWithContents]);
/*-----------------------------------------------------------------------------
* Templates
*----------------------------------------------------------------------------*/
compileSourceFilesAndCopyToDistributionDirectory(htmlSourceFiles, hbsSourceFiles, globals, stats);

@@ -83,3 +99,7 @@ const copiedFilesCount = await copySourceFilesToDistributionDirectory(cssSourceFiles, jsSourceFiles, otherSourceFiles);

logger_1.default.info(`Copied ${stats.copiedFilesCount} files to the distribution directory.`);
await Actions.runPostBuildAsync((_b = configuration_1.default.getActions().postBuild) === null || _b === void 0 ? void 0 : _b.filter((action) => !action.skip));
/*-----------------------------------------------------------------------------
* Actions
*----------------------------------------------------------------------------*/
await Actions.runPostBuildAsync((_b = configuration_1.default.actions.postBuild) === null || _b === void 0 ? void 0 : _b.filter((action) => !action.skip));
configuration_1.default.debugOutput && unusedPartials.printUnusedPartialsMessage(partials);
return stats;

@@ -90,6 +110,38 @@ }

return sourceFiles.map((file) => {
const absolutePath = filesystem.joinAndResolvePath(configuration_1.default.getSourceDirectoryPath(), file.dirname, file.name);
const absolutePath = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.dirname, file.name);
return Object.assign(Object.assign({}, file), { contents: filesystem.getFileContents(absolutePath) });
});
}
function transpileTypescriptFilesAndCopyToDistributionDirectory(tsSourceFiles,
/** JS source files to detect possible shadowing by TS files */
jsSourceFiles, stats) {
const typescriptCompilationProgress = new progressBar_1.default(tsSourceFiles.length);
const createdFileSet = new Set();
jsSourceFiles.forEach((file) => {
createdFileSet.add(file.path);
});
const files = [];
tsSourceFiles.forEach((file, idx) => {
const absoluteTsFilePath = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.path);
typescriptCompilationProgress.tick(absoluteTsFilePath, `Compiling TS files:`, `${idx + 1}/${tsSourceFiles.length}`);
const tsFileTranspiledContents = tsTranspiler.transpile(file.contents);
files.push({
name: file.name,
dirname: file.dirname,
path: file.path,
contents: tsFileTranspiledContents,
});
stats.generatedFilesCount++;
const outputJsFileName = file.name.replace(/(\.ts)$/, '.js');
const sourceFilePath = path_1.default.join(file.dirname, outputJsFileName);
if (createdFileSet.has(sourceFilePath)) {
logger_1.default.warning(`Detected JS/TS source files with the same name ${chalk_1.default.blueBright(sourceFilePath.replace(/\.js$/, '.*'))}, but different extensions. TypeScript file compilation skipped.`);
}
else {
createdFileSet.add(sourceFilePath);
filesystem.createFile(filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath, file.dirname, outputJsFileName), tsFileTranspiledContents);
}
});
return files;
}
async function copySourceFilesToDistributionDirectory(...sourceFilesGroups) {

@@ -99,5 +151,5 @@ const copyPromises = [];

group.forEach((file) => {
const srcFilePath = filesystem.joinAndResolvePath(configuration_1.default.getSourceDirectoryPath(), file.dirname, file.name);
const fileDir = filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), file.dirname);
const distFilePath = filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), file.dirname, file.name);
const srcFilePath = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.dirname, file.name);
const fileDir = filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath, file.dirname);
const distFilePath = filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath, file.dirname, file.name);
copyPromises.push(filesystem.createDirectoryAsync(fileDir).then(() => {

@@ -122,3 +174,3 @@ return filesystem.copyFileAsync(srcFilePath, distFilePath);

var _a;
const absoluteTemplatePath = filesystem.joinAndResolvePath(configuration_1.default.getSourceDirectoryPath(), file.dirname, file.name);
const absoluteTemplatePath = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.dirname, file.name);
const templateContents = filesystem.getFileContents(absoluteTemplatePath);

@@ -130,23 +182,6 @@ let resultHTML = '';

if (configuration_1.default.minifyOutputHTML) {
resultHTML = (0, html_minifier_1.minify)(resultHTML, {
minifyJS: {
mangle: true,
compress: {
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true,
},
},
minifyCSS: true,
collapseWhitespace: true,
removeComments: true,
});
resultHTML = htmlMinifier.minify(resultHTML);
}
else if (configuration_1.default.formatOutputHTML) {
resultHTML = prettier_1.default.format(resultHTML, { parser: 'html' });
resultHTML = htmlFormatter.format(resultHTML);
}

@@ -179,37 +214,11 @@ stats.generatedFilesCount++;

createdFileSet.add(sourceFilePath);
filesystem.createFile(filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), file.dirname, outputHTMLFileName), resultHTML);
filesystem.createFile(filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath, file.dirname, outputHTMLFileName), resultHTML);
}
});
}
function registerEmbeddedStylesInjectorHelper(compiledSassSourceFiles) {
handlebars_1.default.registerHelper('embeddedStyles', embeddedStylesHelper);
function embeddedStylesHelper(cssFilePath, data) {
const cssStyles = compiledSassSourceFiles.find((file) => {
return path_1.default.join(file.dirname, file.name) === cssFilePath;
});
if (!cssStyles) {
logger_1.default.error(`CSS file ${filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), cssFilePath)} is not found.`);
process.exit(1);
}
return new handlebars_1.default.SafeString((data.hash.attributes ? `<style ${data.hash.attributes}>` : `<style>`) + cssStyles.contents + '</style>');
}
}
function registerEmbeddedScriptInjectorHelper(scriptSourceFiles) {
handlebars_1.default.registerHelper('embeddedScript', embeddedScriptHelper);
function embeddedScriptHelper(scriptFilePath, data) {
const scriptFile = scriptSourceFiles.find((file) => {
return path_1.default.join(file.dirname, file.name) === scriptFilePath;
});
if (!scriptFile) {
logger_1.default.error(`Script file ${filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), scriptFilePath)} is not found.`);
process.exit(1);
}
return new handlebars_1.default.SafeString((data.hash.attributes ? `<script ${data.hash.attributes}>` : '<script>') + scriptFile.contents + '</script>');
}
}
function compileSassAndCopyToDistributionDirectory(sassSourceFiles, stats) {
const sassStylesCompilationProgress = new progressBar_1.default(sassSourceFiles.length);
const compiledSassSourceFiles = sassSourceFiles.map((file, idx) => {
const absoluteFileDirectoryName = filesystem.joinAndResolvePath(configuration_1.default.getSourceDirectoryPath(), file.dirname);
const absoluteFilePath = filesystem.joinAndResolvePath(configuration_1.default.getSourceDirectoryPath(), file.dirname, file.name);
const absoluteFileDirectoryName = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.dirname);
const absoluteFilePath = filesystem.joinAndResolvePath(configuration_1.default.sourceDirectoryPath, file.dirname, file.name);
const fileContents = filesystem.getFileContents(absoluteFilePath);

@@ -223,5 +232,3 @@ sassStylesCompilationProgress.tick(absoluteFilePath, 'Compiling SASS files:', `${idx + 1}/${sassSourceFiles.length}`);

path: file.path,
contents: fileContents
? sass_1.default.compileString(fileContents, { loadPaths: [absoluteFileDirectoryName] }).css
: '',
contents: fileContents ? sassCompiler.compile(fileContents, absoluteFileDirectoryName) : '',
};

@@ -235,3 +242,3 @@ }

}
filesystem.createFile(filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath(), compiledSassSourceFile.dirname, compiledSassSourceFile.name), compiledSassSourceFile.contents);
filesystem.createFile(filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath, compiledSassSourceFile.dirname, compiledSassSourceFile.name), compiledSassSourceFile.contents);
stats.generatedFilesCount++;

@@ -244,3 +251,3 @@ return compiledSassSourceFile;

if (configuration_1.default.clearDistributionDirectoryOnRecompile) {
const absoluteDistDirectoryPath = filesystem.joinAndResolvePath(configuration_1.default.getDistributionDirectoryPath());
const absoluteDistDirectoryPath = filesystem.joinAndResolvePath(configuration_1.default.distributionDirectoryPath);
logger_1.default.info(`Clearing distribution directory: ${chalk_1.default.blueBright(absoluteDistDirectoryPath)}`);

@@ -261,37 +268,6 @@ filesystem.clearDirectoryContents(absoluteDistDirectoryPath);

}
function registerMissingPropertyHelper() {
if (!configuration_1.default.ignoreMissingProperties) {
handlebars_1.default.registerHelper('helperMissing', function (...passedArgs) {
const options = passedArgs[arguments.length - 1];
const args = Array.prototype.slice.call(passedArgs, 0, arguments.length - 1);
const helperName = options.name;
const lineNumber = options.loc.start.line;
const hashArgsObj = options.hash;
const argsStringified = args.length !== 0 ? ' ' + args.map((arg) => `"${arg}"`).join(' ') : '';
const hashArgsStringified = (0, lodash_1.default)(hashArgsObj)
.toPairs()
.map(([key, value]) => {
if (typeof value === 'number') {
return `${key}=${value}`;
}
else {
return `${key}="${value}"`;
}
})
.thru((value) => {
return value.length !== 0 ? ' ' + value.join(' ') : '';
})
.value();
const processingEntityPath = progressBar_1.default.processingEntityInfo;
const missingHelperType = !argsStringified.length && !hashArgsStringified.length ? 'helper/property' : 'helper';
const missingHelperExpression = `{{ ${helperName}${argsStringified}${hashArgsStringified} }}`;
logger_1.default.error(`Missing ${missingHelperType} ${chalk_1.default.red(missingHelperExpression)}. Check render tree in ${chalk_1.default.blueBright(processingEntityPath)} (line number: ${lineNumber}).`);
return new handlebars_1.default.SafeString(`<div style="color: red !important">Missing ${missingHelperType} ${missingHelperExpression}</div>`);
});
}
}
function scanSourceFiles() {
const filesConfiguration = configuration_1.default.getFilesConfiguration();
const filesConfiguration = configuration_1.default.filesConfiguration;
const allSourceFiles = filesystem
.scanFiles(configuration_1.default.getSourceDirectoryPath(), false, true, true)
.scanFiles(configuration_1.default.sourceDirectoryPath, false, true, true)
.filter((file) => shouldProcessFile(file, filesConfiguration.all));

@@ -315,6 +291,17 @@ const htmlSourceFiles = allSourceFiles.filter((file) => {

});
const tsSourceFiles = allSourceFiles.filter((file) => {
return filesystem.hasFileExtension(file.name, ['ts']) && shouldProcessFile(file, filesConfiguration.js);
});
const otherSourceFiles = allSourceFiles.filter((file) => {
return !filesystem.hasFileExtension(file.name, ['html', 'hbs', 'scss', 'sass', 'css', 'js']);
return !filesystem.hasFileExtension(file.name, ['html', 'hbs', 'scss', 'sass', 'css', 'js', 'ts']);
});
return { scssSourceFiles, cssSourceFiles, htmlSourceFiles, hbsSourceFiles, jsSourceFiles, otherSourceFiles };
return {
scssSourceFiles,
cssSourceFiles,
htmlSourceFiles,
hbsSourceFiles,
jsSourceFiles,
tsSourceFiles,
otherSourceFiles,
};
}

@@ -321,0 +308,0 @@ function shouldProcessFile(file, regexes) {

"use strict";
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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -9,3 +32,5 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

const path_1 = __importDefault(require("path"));
const filesystem = __importStar(require("./filesystem"));
const logger_1 = __importDefault(require("./logger"));
const jsoncParser = __importStar(require("./tools/jsoncParser"));
class Configuration {

@@ -16,6 +41,6 @@ constructor() {

*----------------------------------------------------------------------------*/
this.globals = {};
this.partials = {};
this.helpers = {};
this.actions = {};
this._globals = {};
this._partials = {};
this._helpers = {};
this._actions = {};
/*-----------------------------------------------------------------------------

@@ -35,12 +60,12 @@ * System configuration (default values)

this.defaultDirectoriesPrefix = '';
this.sourceDirectoryPath = 'src';
this.distributionDirectoryPath = 'dist';
this.globalsDirectoryPath = 'globals';
this.partialsDirectoryPath = 'partials';
this.helpersDirectoryPath = 'helpers';
this.configurationFilePath = 'symply-config.yaml';
this._sourceDirectoryPath = { default: 'src', custom: null };
this._distributionDirectoryPath = { default: 'dist', custom: null };
this._globalsDirectoryPath = { default: 'globals', custom: null };
this._partialsDirectoryPath = { default: 'partials', custom: null };
this._helpersDirectoryPath = { default: 'helpers', custom: null };
/*-----------------------------------------------------------------------------
* Files configuration (default values)
*----------------------------------------------------------------------------*/
this.filesConfiguration = {
this.configurationFilePathList = ['symply-config.json', 'symply-config.jsonc'];
this._filesConfiguration = {
all: {

@@ -62,7 +87,27 @@ include: ['**/*'],

},
ts: {
include: ['**/*'],
exclude: [],
compilerOptions: {},
},
};
}
get globals() {
return this._globals;
}
get partials() {
return this._partials;
}
get helpers() {
return this._helpers;
}
get actions() {
return this._actions;
}
get debugOutput() {
return this._debugOutput;
}
get ignoreMissingProperties() {
return this._ignoreMissingProperties;
}
get formatOutputHTML() {

@@ -83,33 +128,68 @@ return this._formatOutputHTML;

}
get ignoreMissingProperties() {
return this._ignoreMissingProperties;
get sourceDirectoryPath() {
return this.getPrefixedDirectoryPath(this._sourceDirectoryPath);
}
get distributionDirectoryPath() {
return this.getPrefixedDirectoryPath(this._distributionDirectoryPath);
}
get globalsDirectoryPath() {
return this.getPrefixedDirectoryPath(this._globalsDirectoryPath);
}
get partialsDirectoryPath() {
return this.getPrefixedDirectoryPath(this._partialsDirectoryPath);
}
get helpersDirectoryPath() {
return this.getPrefixedDirectoryPath(this._helpersDirectoryPath);
}
get filesConfiguration() {
return this._filesConfiguration;
}
/*-----------------------------------------------------------------------------
* Public methods
*----------------------------------------------------------------------------*/
/** Explicitly set configuration (module mode only) */
setModuleModeConfiguration(config) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
this.globals = lodash_1.default.defaultTo((_a = config.entities) === null || _a === void 0 ? void 0 : _a.globals, this.globals);
this.partials = lodash_1.default.defaultTo((_b = config.entities) === null || _b === void 0 ? void 0 : _b.partials, this.partials);
this.helpers = lodash_1.default.defaultTo((_c = config.entities) === null || _c === void 0 ? void 0 : _c.helpers, this.helpers);
this.actions = lodash_1.default.defaultTo(config.actions, this.actions);
this._debugOutput = lodash_1.default.defaultTo(config.debugOutput, this._debugOutput);
this._ignoreMissingProperties = lodash_1.default.defaultTo(config.ignoreMissingProperties, this.ignoreMissingProperties);
this._formatOutputHTML = lodash_1.default.defaultTo(config.formatOutputHTML, this._formatOutputHTML);
this._minifyOutputHTML = lodash_1.default.defaultTo(config.minifyOutputHTML, this._minifyOutputHTML);
this._omitWarnings = lodash_1.default.defaultTo(config.omitWarnings, this._omitWarnings);
this._ansiLogging = lodash_1.default.defaultTo(config.ansiLogging, this._ansiLogging);
this._clearDistributionDirectoryOnRecompile = lodash_1.default.defaultTo(config.clearDistributionDirectoryOnRecompile, this.clearDistributionDirectoryOnRecompile);
this.defaultDirectoriesPrefix = lodash_1.default.defaultTo((_d = config.paths) === null || _d === void 0 ? void 0 : _d.defaultDirectoriesPrefix, this.defaultDirectoriesPrefix);
/*-----------------------------------------------------------------------------
* Initialize all directories and (if needed) add prefixes to all default ones
*----------------------------------------------------------------------------*/
this.sourceDirectoryPath = this.getDirectoryPathAndAddPrefixIfNeeded((_e = config.paths) === null || _e === void 0 ? void 0 : _e.sourceDirectoryPath, this.sourceDirectoryPath);
this.distributionDirectoryPath = this.getDirectoryPathAndAddPrefixIfNeeded((_f = config.paths) === null || _f === void 0 ? void 0 : _f.distributionDirectoryPath, this.distributionDirectoryPath);
this.globalsDirectoryPath = this.getDirectoryPathAndAddPrefixIfNeeded((_g = config.paths) === null || _g === void 0 ? void 0 : _g.globalsDirectoryPath, this.globalsDirectoryPath);
this.partialsDirectoryPath = this.getDirectoryPathAndAddPrefixIfNeeded((_h = config.paths) === null || _h === void 0 ? void 0 : _h.partialsDirectoryPath, this.partialsDirectoryPath);
this.helpersDirectoryPath = this.getDirectoryPathAndAddPrefixIfNeeded((_j = config.paths) === null || _j === void 0 ? void 0 : _j.helpersDirectoryPath, this.helpersDirectoryPath);
this.configurationFilePath = this.getDirectoryPathAndAddPrefixIfNeeded(undefined, this.configurationFilePath);
this.filesConfiguration = lodash_1.default.defaultsDeep(config.files, this.filesConfiguration);
loadConfigurationFromConfigFile() {
for (let i = 0; i < this.configurationFilePathList.length; i++) {
const configurationFilePath = this.configurationFilePathList[i];
try {
const configuration = jsoncParser.parse(filesystem.getFileContents(configurationFilePath));
logger_1.default.info(`Detected ${chalk_1.default.blueBright(configurationFilePath)} configuration file.`);
if (configuration === undefined) {
logger_1.default.warning(`Cannot parse configuration file.`);
break;
}
return configuration;
}
catch (err) {
if (this.isErrorWithCodeProperty(err)) {
if (err.code === 'ENOENT') {
continue;
}
}
throw err;
}
}
return null;
}
mergeConfigurationAndVerify(config) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
this._globals = lodash_1.default.defaultsDeep((_a = config.entities) === null || _a === void 0 ? void 0 : _a.globals, this._globals);
this._partials = lodash_1.default.defaultsDeep((_b = config.entities) === null || _b === void 0 ? void 0 : _b.partials, this._partials);
this._helpers = lodash_1.default.defaultsDeep((_c = config.entities) === null || _c === void 0 ? void 0 : _c.helpers, this._helpers);
this._actions = (_d = config.actions) !== null && _d !== void 0 ? _d : this._actions;
this._debugOutput = (_e = config.debugOutput) !== null && _e !== void 0 ? _e : this._debugOutput;
this._ignoreMissingProperties = (_f = config.ignoreMissingProperties) !== null && _f !== void 0 ? _f : this._ignoreMissingProperties;
this._formatOutputHTML = (_g = config.formatOutputHTML) !== null && _g !== void 0 ? _g : this._formatOutputHTML;
this._minifyOutputHTML = (_h = config.minifyOutputHTML) !== null && _h !== void 0 ? _h : this._minifyOutputHTML;
this._omitWarnings = (_j = config.omitWarnings) !== null && _j !== void 0 ? _j : this._omitWarnings;
this._ansiLogging = (_k = config.ansiLogging) !== null && _k !== void 0 ? _k : this._ansiLogging;
this._clearDistributionDirectoryOnRecompile =
(_l = config.clearDistributionDirectoryOnRecompile) !== null && _l !== void 0 ? _l : this._clearDistributionDirectoryOnRecompile;
this.defaultDirectoriesPrefix = (_o = (_m = config.paths) === null || _m === void 0 ? void 0 : _m.defaultDirectoriesPrefix) !== null && _o !== void 0 ? _o : this.defaultDirectoriesPrefix;
this._sourceDirectoryPath.custom = (_q = (_p = config.paths) === null || _p === void 0 ? void 0 : _p.sourceDirectoryPath) !== null && _q !== void 0 ? _q : this._sourceDirectoryPath.custom;
this._distributionDirectoryPath.custom =
(_s = (_r = config.paths) === null || _r === void 0 ? void 0 : _r.distributionDirectoryPath) !== null && _s !== void 0 ? _s : this._distributionDirectoryPath.custom;
this._globalsDirectoryPath.custom = (_u = (_t = config.paths) === null || _t === void 0 ? void 0 : _t.globalsDirectoryPath) !== null && _u !== void 0 ? _u : this._globalsDirectoryPath.custom;
this._partialsDirectoryPath.custom = (_w = (_v = config.paths) === null || _v === void 0 ? void 0 : _v.partialsDirectoryPath) !== null && _w !== void 0 ? _w : this._partialsDirectoryPath.custom;
this._helpersDirectoryPath.custom = (_y = (_x = config.paths) === null || _x === void 0 ? void 0 : _x.helpersDirectoryPath) !== null && _y !== void 0 ? _y : this._helpersDirectoryPath.custom;
this._filesConfiguration = lodash_1.default.defaultsDeep(config.files, this._filesConfiguration);
this.validateConfiguration();

@@ -126,60 +206,14 @@ }

/*-----------------------------------------------------------------------------
* Public entities getters
*----------------------------------------------------------------------------*/
getGlobals() {
return this.globals;
}
getPartials() {
return this.partials;
}
getHelpers() {
return this.helpers;
}
getActions() {
return this.actions;
}
/*-----------------------------------------------------------------------------
* Public path getters
*----------------------------------------------------------------------------*/
getSourceDirectoryPath() {
return this.sourceDirectoryPath;
}
getDistributionDirectoryPath() {
return this.distributionDirectoryPath;
}
getGlobalsDirectoryPath() {
return this.globalsDirectoryPath;
}
getPartialsDirectoryPath() {
return this.partialsDirectoryPath;
}
getHelpersDirectoryPath() {
return this.helpersDirectoryPath;
}
getConfigurationFilePath() {
return this.configurationFilePath;
}
/*-----------------------------------------------------------------------------
* Private methods
*----------------------------------------------------------------------------*/
getDirectoryPathAndAddPrefixIfNeeded(newDirectoryPath, defaultDirectoryPath) {
if (this.defaultDirectoriesPrefix.length > 0) {
if (!newDirectoryPath) {
return path_1.default.join(this.defaultDirectoriesPrefix, defaultDirectoryPath);
}
else {
return newDirectoryPath;
}
getPrefixedDirectoryPath(directoryPath) {
if (directoryPath.custom !== null && directoryPath.custom.length > 0) {
return directoryPath.custom;
}
else {
return lodash_1.default.defaultTo(newDirectoryPath, defaultDirectoryPath);
}
return path_1.default.join(this.defaultDirectoriesPrefix, directoryPath.default);
}
/*-----------------------------------------------------------------------------
* Public include/exclude user configiration getters
*----------------------------------------------------------------------------*/
getFilesConfiguration() {
return this.filesConfiguration;
isErrorWithCodeProperty(error) {
return error instanceof Error && typeof Reflect.get(error, 'code') === 'string';
}
}
exports.default = new Configuration();

@@ -46,5 +46,5 @@ "use strict";

/*-----------------------------------------------------------------------------
* Import namespaced globals from `globals` directory
* Import namespaced globals from `globalsDirectoryPath`
*----------------------------------------------------------------------------*/
const globalsPath = configuration_1.default.getGlobalsDirectoryPath();
const globalsPath = configuration_1.default.globalsDirectoryPath;
const globalsFileList = filesystem.scanFiles(globalsPath, true, false, true);

@@ -93,11 +93,10 @@ // change nested globals files names to include its enclosing folder

*----------------------------------------------------------------------------*/
const shadowedGlobalsList = lodash_1.default.intersection(Object.keys(result), Object.keys(configuration_1.default.getGlobals()));
const shadowedGlobalsList = lodash_1.default.intersection(Object.keys(result), Object.keys(configuration_1.default.globals));
if (shadowedGlobalsList.length !== 0) {
logger_1.default.error(`Some globals are shadowed by module configuration: ${chalk_1.default.blueBright(shadowedGlobalsList)}`);
}
Object.assign(result, configuration_1.default.getGlobals());
Object.assign(result, configuration_1.default.globals);
if (configuration_1.default.debugOutput) {
logger_1.default.debug('Registered globals:');
logger_1.default.log(flat_1.default.flatten(result, { maxDepth: 1 }));
logger_1.default.log();
}

@@ -104,0 +103,0 @@ return result;

@@ -38,5 +38,5 @@ "use strict";

/*-----------------------------------------------------------------------------
* Import namespaced helpers from `helpers` directory
* Import namespaced helpers from `helpersDirectoryPath`
*----------------------------------------------------------------------------*/
const helpersPath = configuration_1.default.getHelpersDirectoryPath();
const helpersPath = configuration_1.default.helpersDirectoryPath;
const helpersFileList = filesystem.scanFiles(helpersPath, true, false, true);

@@ -57,8 +57,13 @@ // change each nested helpers' file name to include its enclosing folder

const result = helpersFileList.reduce((acc, helpersFile) => {
const helpersFileNameWithoutExtension = getHelpersFileNameWithoutExtension(helpersFile.name);
if (helpersFileNameWithoutExtension === null) {
logger_1.default.error(`Helpers file ${chalk_1.default.blueBright(helpersFile.path)} is not supported.`);
process.exit(1);
}
const helpersCode = helpersFile.contents;
const helpersObj = eval(helpersCode);
Object.keys(helpersObj).forEach((helperName) => {
const helperHashKey = `${getHelpersFileName(helpersFile.name)}.${helperName}`;
for (const helperName of Object.keys(helpersObj)) {
const helperHashKey = `${helpersFileNameWithoutExtension}.${helperName}`;
acc[helperHashKey] = helpersObj[helperName];
});
}
return acc;

@@ -69,9 +74,8 @@ }, {});

*----------------------------------------------------------------------------*/
Object.assign(result, configuration_1.default.getHelpers());
Object.assign(result, configuration_1.default.helpers);
if (configuration_1.default.debugOutput) {
logger_1.default.debug('Registered helpers:');
Object.keys(result).forEach((key) => {
logger_1.default.log(chalk_1.default.green(key));
logger_1.default.logWithPadding(chalk_1.default.green(key));
});
logger_1.default.log();
}

@@ -81,4 +85,7 @@ return result;

exports.load = load;
function getHelpersFileName(fileName) {
return fileName.replace(new RegExp(`\\${HELPERS_EXTENSION}$`), '');
function getHelpersFileNameWithoutExtension(fileName) {
if (fileName.endsWith(HELPERS_EXTENSION)) {
return fileName.replace(new RegExp(`\\${HELPERS_EXTENSION}$`), '');
}
return null;
}

@@ -39,5 +39,5 @@ "use strict";

/*-----------------------------------------------------------------------------
* Import partials from /partials
* Import partials from `partialsDirectoryPath`
*----------------------------------------------------------------------------*/
const partialsPath = configuration_1.default.getPartialsDirectoryPath();
const partialsPath = configuration_1.default.partialsDirectoryPath;
const partials = filesystem.scanFiles(partialsPath, true, false, true);

@@ -59,2 +59,6 @@ // change nestes partials names to include its enclosing folder

const partialNameWithoutExtension = getPartialNameWithoutExtension(partial.name);
if (partialNameWithoutExtension === null) {
logger_1.default.error(`Partial file ${chalk_1.default.blueBright(partial.path)} is not supported.`);
process.exit(1);
}
if (acc[partialNameWithoutExtension] !== undefined) {

@@ -72,13 +76,12 @@ const duplicatePartialPath = `${partial.dirname}${path_1.default.sep}${partialNameWithoutExtension}.*`;

*----------------------------------------------------------------------------*/
const shadowedPartialsList = lodash_1.default.intersection(Object.keys(result), Object.keys(configuration_1.default.getPartials()));
const shadowedPartialsList = lodash_1.default.intersection(Object.keys(result), Object.keys(configuration_1.default.partials));
if (shadowedPartialsList.length !== 0) {
logger_1.default.error(`Some partials are shadowed by module configuration: ${chalk_1.default.blueBright(shadowedPartialsList)}`);
}
Object.assign(result, configuration_1.default.getPartials());
Object.assign(result, configuration_1.default.partials);
if (configuration_1.default.debugOutput) {
logger_1.default.debug('Registered partials:');
logger_1.default.debug(`Registered ${partials.length} partial${partials.length === 1 ? '' : 's'}:`);
Object.keys(result).forEach((key) => {
logger_1.default.log(chalk_1.default.green(key));
logger_1.default.logWithPadding(chalk_1.default.green(key));
});
logger_1.default.log();
}

@@ -89,4 +92,7 @@ return result;

function getPartialNameWithoutExtension(fileName) {
const re = `(${SUPPORTED_PARTIAL_EXTENTION_LIST.map((ext) => '\\' + ext).join('|')})$`;
return fileName.replace(new RegExp(re), '');
if (SUPPORTED_PARTIAL_EXTENTION_LIST.some((supportedExtension) => fileName.endsWith(supportedExtension))) {
const re = `(${SUPPORTED_PARTIAL_EXTENTION_LIST.map((ext) => '\\' + ext).join('|')})$`;
return fileName.replace(new RegExp(re), '');
}
return null;
}

@@ -9,2 +9,3 @@ "use strict";

const fs_extra_1 = __importDefault(require("fs-extra"));
const junk_1 = __importDefault(require("junk"));
const path_1 = __importDefault(require("path"));

@@ -22,7 +23,12 @@ const util_1 = require("util");

/** If true - scanPath will be removed from FileEntry.dirname. */
removeScanPath, scanNestedDirectories) {
removeScanPath, scanNestedDirectories,
/**
* Ignore files like: `.DS_Store`, `Thumbs.db` and etc.
* {@link https://github.com/sindresorhus/junk/blob/main/index.js}
* @default true */
ignoreJunkFiles = true) {
if (removeScanPath) {
return scanFilesInDirectory(scanPath, scanPath, readFileContents, scanNestedDirectories);
return scanFilesInDirectory(scanPath, scanPath, readFileContents, scanNestedDirectories, ignoreJunkFiles);
}
return scanFilesInDirectory(scanPath, '', readFileContents, scanNestedDirectories);
return scanFilesInDirectory(scanPath, '', readFileContents, scanNestedDirectories, ignoreJunkFiles);
}

@@ -123,3 +129,3 @@ exports.scanFiles = scanFiles;

exports.moveFile = moveFile;
function scanFilesInDirectory(scanPath, basePath, readFileContents, scanNestedDirectories) {
function scanFilesInDirectory(scanPath, basePath, readFileContents, scanNestedDirectories, ignoreJunkFiles = true) {
let files = [];

@@ -138,2 +144,5 @@ try {

const stats = fs_extra_1.default.statSync(relativePath);
if (ignoreJunkFiles && junk_1.default.is(filename)) {
return;
}
if (stats.isDirectory()) {

@@ -140,0 +149,0 @@ if (scanNestedDirectories) {

@@ -20,2 +20,5 @@ "use strict";

},
logWithPadding(...strings) {
return this.log(' ', ...strings);
},
warning(...strings) {

@@ -22,0 +25,0 @@ if (configuration_1.default.omitWarnings) {

@@ -12,4 +12,12 @@ "use strict";

const start = Date.now();
configuration_1.default.setModuleModeConfiguration(configuration);
logger_1.default.info(chalk_1.default.magentaBright('SYMPLY::GENERATE'), chalk_1.default.greenBright('[START]'));
if (Object.keys(configuration).length > 0) {
configuration_1.default.mergeConfigurationAndVerify(configuration);
logger_1.default.info(`Configuration object verified and merged.`);
}
const configurationFromFile = configuration_1.default.loadConfigurationFromConfigFile();
if (configurationFromFile) {
configuration_1.default.mergeConfigurationAndVerify(configurationFromFile);
logger_1.default.info(`Configuration file verified and merged.`);
}
await (0, generate_1.generate)();

@@ -16,0 +24,0 @@ logger_1.default.info(chalk_1.default.magentaBright('SYMPLY::GENERATE'), chalk_1.default.greenBright(`[DONE in ${(Date.now() - start) / 1000}s]`));

{
"name": "symply",
"version": "0.8.0",
"version": "0.9.0",
"description": "A simple static site generator.",

@@ -32,2 +32,4 @@ "author": "Oleg Legun <oleg.legun@gmail.com>",

"js-yaml": "4.1.0",
"jsonc-parser": "^3.0.0",
"junk": "^3.1.0",
"lodash": "4.17.21",

@@ -37,3 +39,4 @@ "minimatch": "5.1.0",

"sass": "1.49.9",
"strip-ansi": "6.0.1"
"strip-ansi": "6.0.1",
"typescript": "4.7.2"
},

@@ -59,4 +62,3 @@ "devDependencies": {

"tap-spec": "^5.0.0",
"tape": "5.5.2",
"typescript": "4.6.2"
"tape": "5.5.2"
},

@@ -63,0 +65,0 @@ "overrides": {

@@ -83,2 +83,7 @@ /* eslint-disable */

export interface ConfigurableDirectoryPath {
default: string
custom: string | null
}
export interface PathsConfiguration {

@@ -92,3 +97,3 @@ /**

/**
* Override default __source__ directory path.
* Override default __source__ directory path. `defaultDirectoriesPrefix` will NOT be applied.
* @default 'src'

@@ -98,3 +103,3 @@ **/

/**
* Override default __distribution__ directory path.
* Override default __distribution__ directory path. `defaultDirectoriesPrefix` will NOT be applied.
* @default 'dist'

@@ -104,3 +109,3 @@ **/

/**
* Override default __globals__ directory path.
* Override default __globals__ directory path. `defaultDirectoriesPrefix` will NOT be applied.
* @default 'globals'

@@ -110,3 +115,3 @@ **/

/**
* Override default __partials__ directory path.
* Override default __partials__ directory path. `defaultDirectoriesPrefix` will NOT be applied.
* @default 'partials'

@@ -116,3 +121,3 @@ **/

/**
* Override default __helpers__ directory path.
* Override default __helpers__ directory path. `defaultDirectoriesPrefix` will NOT be applied.
* @default 'helpers'

@@ -126,3 +131,3 @@ **/

all: {
/**
/**
* Define global patterns for all files in the `sourceDirectoryPath` that must be included in the compilation process.

@@ -134,3 +139,3 @@ * Use forward slash `/` as a path separator on any platform.

include: string[]
/**
/**
* Define global patterns for all files in the `sourceDirectoryPath` that must be excluded from the compilation process.

@@ -145,3 +150,3 @@ * Use forward slash `/` as a path separator on any platform.

templates: {
/**
/**
* Define patterns for `.hbs` and `.html` template files in the `sourceDirectoryPath` that must be included in the compilation process.

@@ -153,3 +158,3 @@ * Use forward slash `/` as a path separator on any platform.

include: string[]
/**
/**
* Define patterns for `.hbs` and `.html` template files in the `sourceDirectoryPath` that must be excluded from the compilation process.

@@ -164,3 +169,3 @@ * Use forward slash `/` as a path separator on any platform.

styles: {
/**
/**
* Define patterns for `.css`, `.scss` and `.sass` style files in the `sourceDirectoryPath` that must be included in the compilation process.

@@ -172,3 +177,3 @@ * Use forward slash `/` as a path separator on any platform.

include: string[]
/**
/**
* Define patterns for `.css`, `.scss` and `.sass` style files in the `sourceDirectoryPath` that must be excluded from the compilation process.

@@ -183,3 +188,3 @@ * Use forward slash `/` as a path separator on any platform.

js: {
/**
/**
* Define patterns for `.js` script files in the `sourceDirectoryPath` that must be included in the compilation process.

@@ -191,3 +196,3 @@ * Use forward slash `/` as a path separator on any platform.

include: string[]
/**
/**
* Define patterns for `.js` script files in the `sourceDirectoryPath` that must be excluded from the compilation process.

@@ -200,2 +205,20 @@ * Use forward slash `/` as a path separator on any platform.

}
/** Settings for `.ts` script files transpilation in the `sourceDirectoryPath`. */
ts: {
/**
* Define patterns for `.ts` script files in the `sourceDirectoryPath` that must be included in the compilation process.
* Use forward slash `/` as a path separator on any platform.
* @default ['**\/*'] - Process all `.ts` script files
* @example ['main.ts', 'ts/*.ts'] - Process only files that match these patterns
*/
include: string[]
/**
* Define patterns for `.ts` script files in the `sourceDirectoryPath` that must be excluded from the compilation process.
* Use forward slash `/` as a path separator on any platform.
* @default []
* @example ['analytics.ts', 'ts/*.test.ts'] - Exclude files that match these patterns
*/
exclude: string[]
compilerOptions: import('typescript').CompilerOptions
}
}

@@ -371,4 +394,5 @@

export interface FileEntry {
/** File name with extension */
/** File name with extension. */
name: string
/** File path relative to `sourceDirectoryPath` without file name. */
dirname: string

@@ -375,0 +399,0 @@ /** File path relative to `sourceDirectoryPath`. */

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc