@smapiot/pilet-template-default
Version:
Official scaffolding template for pilets: 'default'.
1,412 lines (1,399 loc) • 53 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../packages/template-utils/lib/log.js
var require_log = __commonJS({
"../../packages/template-utils/lib/log.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.setLogLevel = setLogLevel;
exports2.log = log;
var logLevel = "warn";
function setLogLevel(level) {
logLevel = level;
}
function log(level, message) {
if (level === "error") {
if (logLevel !== "disabled") {
console.error(`[template] ${message}`);
}
} else if (level === "warn") {
if (logLevel !== "error" && logLevel !== "disabled") {
console.warn(`[template] ${message}`);
}
} else if (level === "info") {
if (logLevel === "verbose" || logLevel === "info") {
console.info(`[template] ${message}`);
}
} else if (level === "verbose") {
if (logLevel === "verbose") {
console.log(`[template] ${message}`);
}
}
}
}
});
// ../../packages/template-utils/lib/utils.js
var require_utils = __commonJS({
"../../packages/template-utils/lib/utils.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.makeRelative = makeRelative;
exports2.getPackageJsonWithSource = getPackageJsonWithSource;
exports2.getProjectJson = getProjectJson;
exports2.getPiralInstance = getPiralInstance;
exports2.getPlugins = getPlugins;
exports2.getLanguageExtension = getLanguageExtension;
var path_1 = require("path");
var fs_1 = require("fs");
var log_1 = require_log();
function makeRelative(path, root2) {
const relPath = (0, path_1.isAbsolute)(path) ? (0, path_1.relative)(root2, path) : path;
return relPath.split(path_1.sep).join(path_1.posix.sep);
}
function getPackageJsonWithSource(root2, targetDir, fileName) {
const path = makeRelative(path_1.posix.join(targetDir, fileName), root2);
(0, log_1.log)("verbose", `Adding "source" to package.json: "${path}"`);
return {
languages: ["ts", "js"],
name: "package.json",
content: JSON.stringify({ source: path }),
target: "<root>/package.json"
};
}
function getProjectJson(root2) {
try {
return require(`${root2}/package.json`);
} catch (ex) {
(0, log_1.log)("error", `Error when reading the "package.json": ${ex}`);
}
return void 0;
}
function getPiralInstance(root2, sourceName) {
try {
const packageJsonPath = require.resolve(`${sourceName}/package.json`, {
paths: [root2]
});
(0, log_1.log)("verbose", `Found package JSON in "${packageJsonPath}"`);
const sourcePath = (0, path_1.dirname)(packageJsonPath);
const details = require(packageJsonPath);
const types = details.types || details.typings;
(0, log_1.log)("verbose", `Looking for types in "${types}"`);
const typingsPath = types !== void 0 ? (0, path_1.resolve)(sourcePath, types) : void 0;
const app = details.app;
(0, log_1.log)("verbose", `Looking for types in "${app}"`);
const appPath = app !== void 0 ? (0, path_1.resolve)(sourcePath, app) : void 0;
return {
sourceName,
sourcePath,
details,
appPath,
typingsPath
};
} catch (ex) {
(0, log_1.log)("error", `Error when getting Piral instance: ${ex}`);
}
return void 0;
}
function getPlugins(root2, sourceName) {
const plugins = {};
(0, log_1.log)("verbose", `Getting the plugins of "${sourceName}/package.json" ...`);
const piralInstance = getPiralInstance(root2, sourceName);
const typingsPath = piralInstance === null || piralInstance === void 0 ? void 0 : piralInstance.typingsPath;
if (typingsPath) {
(0, log_1.log)("verbose", `Reading file in "${typingsPath}"`);
const typing = (0, fs_1.readFileSync)(typingsPath, "utf8");
const match = /export interface PiletCustomApi extends (.*?) \{/g.exec(typing);
if (!match) {
(0, log_1.log)("verbose", `No Piral instance plugins have been found`);
return [];
}
const apis = match[1].split(", ");
(0, log_1.log)("verbose", `Found Piral instance plugins "${match[1]}"`);
for (const api of apis) {
const pluginMatch = /^Pilet(.*)Api$/.exec(api);
if (pluginMatch) {
const name = pluginMatch[1].toLowerCase();
plugins[name] = true;
} else {
(0, log_1.log)("warn", `Could not find plugin for Pilet API "${api}"`);
}
}
}
return plugins;
}
function getLanguageExtension(language, isJsx = true) {
switch (language) {
case "js":
return isJsx ? ".jsx" : ".js";
case "ts":
default:
return isJsx ? ".tsx" : ".ts";
}
}
}
});
// ../../packages/template-utils/lib/bundler.js
var require_bundler = __commonJS({
"../../packages/template-utils/lib/bundler.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.detectBundler = detectBundler;
var utils_1 = require_utils();
function detectBundler(root2) {
const projectJson = (0, utils_1.getProjectJson)(root2);
const devDependencies = projectJson === null || projectJson === void 0 ? void 0 : projectJson.devDependencies;
if (projectJson) {
const bundlers = ["esbuild", "webpack5", "webpack", "vite", "parcel2", "parcel", "bun", "rspack", "rollup"];
for (const bundler of bundlers) {
const dependencyName = `piral-cli-${bundler}`;
if (dependencyName in devDependencies) {
return bundler;
}
}
}
return "xbuild";
}
}
});
// ../../packages/template-utils/lib/merge.js
var require_merge = __commonJS({
"../../packages/template-utils/lib/merge.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.deepMerge = deepMerge;
function isMergeableObject(val) {
const nonNullObject = val && typeof val === "object";
return nonNullObject && Object.prototype.toString.call(val) !== "[object RegExp]" && Object.prototype.toString.call(val) !== "[object Date]";
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {};
}
function cloneIfNecessary(value) {
switch (typeof value) {
case "boolean":
case "number":
case "string":
case "symbol":
case "undefined":
return value;
}
return deepMerge(emptyTarget(value), value);
}
function defaultArrayMerge(target, source) {
const destination = target.slice();
source.forEach((e, i) => {
if (typeof destination[i] === "undefined") {
destination[i] = cloneIfNecessary(e);
} else if (isMergeableObject(e)) {
destination[i] = deepMerge(target[i], e);
} else if (target.indexOf(e) === -1) {
destination.push(cloneIfNecessary(e));
}
});
return destination;
}
function mergeObject(target, source) {
const destination = {};
if (isMergeableObject(target)) {
Object.keys(target).forEach((key) => {
destination[key] = cloneIfNecessary(target[key]);
});
}
Object.keys(source).forEach((key) => {
if (!isMergeableObject(source[key]) || !target[key]) {
destination[key] = cloneIfNecessary(source[key]);
} else {
destination[key] = deepMerge(target[key], source[key]);
}
});
return destination;
}
function deepMerge(target, source) {
if (Array.isArray(source)) {
return Array.isArray(target) ? defaultArrayMerge(target, source) : cloneIfNecessary(source);
}
return mergeObject(target, source);
}
}
});
// ../../packages/template-utils/lib/io.js
var require_io = __commonJS({
"../../packages/template-utils/lib/io.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.mergeFiles = mergeFiles;
var merge_1 = require_merge();
function mergeFiles(files, deep) {
const result = {};
const tests = deep.map((m) => typeof m === "string" ? (path) => path === m : (path) => m.test(path));
for (const file of files) {
const items = result[file.path];
if (Array.isArray(items)) {
items.push(file);
} else {
result[file.path] = [file];
}
}
return Object.keys(result).map((path) => {
const items = result[path];
if (items.length !== 1 && tests.some((test) => test(path))) {
const obj = items.map(({ content }) => JSON.parse(content.toString("utf8"))).reduce((p, c) => (0, merge_1.deepMerge)(p, c), {});
const str = JSON.stringify(obj);
return {
path,
content: Buffer.from(str, "utf8")
};
}
return items.pop();
});
}
}
});
// ../../packages/template-utils/lib/assets.js
var require_assets = __commonJS({
"../../packages/template-utils/lib/assets.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.getAssetsSource = getAssetsSource;
var assetsDeclaration = `// Change the declarations in this file if your bundler
// is configured to handle them differently.
// Standard behavior is to treat default exports as a
// link to the imported asset.
declare module '*.jpg' {
const link: string;
export default link;
}
declare module '*.png' {
const link: string;
export default link;
}
declare module '*.svg' {
const link: string;
export default link;
}
declare module '*.jpeg' {
const link: string;
export default link;
}
declare module '*.webp' {
const link: string;
export default link;
}
declare module '*.mp4' {
const link: string;
export default link;
}
declare module '*.mp3' {
const link: string;
export default link;
}
declare module '*.ogg' {
const link: string;
export default link;
}
declare module '*.wav' {
const link: string;
export default link;
}
declare module '*.ogv' {
const link: string;
export default link;
}
declare module '*.wasm' {
const link: string;
export default link;
}
declare module '*.gif' {
const link: string;
export default link;
}
declare module '*.codegen';
`;
function getAssetsSource() {
return {
languages: ["ts"],
name: "assets.d.ts",
content: assetsDeclaration,
target: "<src>/assets.d.ts"
};
}
}
});
// ../../packages/template-utils/lib/version.js
var require_version = __commonJS({
"../../packages/template-utils/lib/version.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.checkVersion = checkVersion;
var log_1 = require_log();
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
var acceptsAll = ["*", "x", ">=0"];
var operatorResMap = {
">": [1],
">=": [0, 1],
"=": [0],
"<=": [-1, 0],
"<": [-1]
};
function indexOrEnd(str, q) {
return str.indexOf(q) === -1 ? str.length : str.indexOf(q);
}
function splitVersion(v) {
var c = v.replace(/^v/, "").replace(/\+.*$/, "");
var patchIndex = indexOrEnd(c, "-");
var arr = c.substring(0, patchIndex).split(".");
arr.push(c.substring(patchIndex + 1));
return arr;
}
function parseSegment(v) {
var n = parseInt(v, 10);
return isNaN(n) ? v : n;
}
function validateAndParse(v) {
const match = v.match(semver);
match.shift();
return match;
}
function compareStrings(a, b) {
const ap = parseSegment(a);
const bp = parseSegment(b);
if (ap > bp) {
return 1;
} else if (ap < bp) {
return -1;
} else {
return 0;
}
}
function compareSegments(a, b) {
for (let i = 0; i < 2; i++) {
const r = compareStrings(a[i] || "0", b[i] || "0");
if (r !== 0) {
return r;
}
}
return 0;
}
function compareVersions(v1, v2) {
const s1 = splitVersion(v1);
const s2 = splitVersion(v2);
const len = Math.max(s1.length - 1, s2.length - 1);
for (let i = 0; i < len; i++) {
const n1 = parseInt(s1[i] || "x", 10);
const n2 = parseInt(s2[i] || "x", 10);
if (n1 > n2) {
return 1;
} else if (n2 > n1) {
return -1;
}
}
const sp1 = s1[s1.length - 1];
const sp2 = s2[s2.length - 1];
if (sp1 && sp2) {
const p1 = sp1.split(".").map(parseSegment);
const p2 = sp2.split(".").map(parseSegment);
const len2 = Math.max(p1.length, p2.length);
for (let i = 0; i < len2; i++) {
if (p1[i] === void 0 || typeof p2[i] === "string" && typeof p1[i] === "number") {
return -1;
} else if (p2[i] === void 0 || typeof p1[i] === "string" && typeof p2[i] === "number") {
return 1;
} else if (p1[i] > p2[i]) {
return 1;
} else if (p2[i] > p1[i]) {
return -1;
}
}
} else if (sp1 || sp2) {
return sp1 ? -1 : 1;
}
return 0;
}
function compare(v1, v2, operator) {
const res = compareVersions(v1, v2);
return operatorResMap[operator].indexOf(res) > -1;
}
function satisfies(v, r) {
if (!acceptsAll.includes(r)) {
const match = r.match(/^([<>=~^]+)/);
const op = match ? match[1] : "=";
if (op !== "^" && op !== "~") {
return compare(v, r, op);
}
const [v1, v2, v3] = validateAndParse(v);
const [m1, m2, m3] = validateAndParse(r);
if (compareStrings(v1, m1) !== 0) {
return false;
} else if (op === "^") {
return compareSegments([v2, v3], [m2, m3]) >= 0;
} else if (compareStrings(v2, m2) !== 0) {
return false;
}
return compareStrings(v3, m3) >= 0;
}
return true;
}
function normalize(version) {
const dash = version.indexOf("-");
if (dash !== -1) {
return version.substring(0, dash);
}
return version;
}
function checkVersion(desired, actual) {
const normActual = normalize(actual);
const normDesired = normalize(desired);
if (!satisfies(normActual, normDesired)) {
(0, log_1.log)("warn", `The template was made for "piral-cli" version "${desired}" but was used with "${actual}".`);
}
}
}
});
// ../../packages/template-utils/lib/parent.js
var require_parent = __commonJS({
"../../packages/template-utils/lib/parent.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.LogLevels = exports2.ForceOverwrite = void 0;
exports2.configure = configure;
var path_1 = require("path");
var log_1 = require_log();
var version_1 = require_version();
var ForceOverwrite;
(function(ForceOverwrite2) {
ForceOverwrite2[ForceOverwrite2["no"] = 0] = "no";
ForceOverwrite2[ForceOverwrite2["prompt"] = 1] = "prompt";
ForceOverwrite2[ForceOverwrite2["yes"] = 2] = "yes";
})(ForceOverwrite || (exports2.ForceOverwrite = ForceOverwrite = {}));
var LogLevels;
(function(LogLevels2) {
LogLevels2[LogLevels2["disabled"] = 0] = "disabled";
LogLevels2[LogLevels2["error"] = 1] = "error";
LogLevels2[LogLevels2["warning"] = 2] = "warning";
LogLevels2[LogLevels2["info"] = 3] = "info";
LogLevels2[LogLevels2["verbose"] = 4] = "verbose";
LogLevels2[LogLevels2["debug"] = 5] = "debug";
})(LogLevels || (exports2.LogLevels = LogLevels = {}));
function configure(root2, details) {
var _a, _b;
if (details) {
const packageJsonPath = (0, path_1.resolve)(root2, "package.json");
const templateProject = require(packageJsonPath);
const desiredVersion = (_b = (_a = templateProject.engines) === null || _a === void 0 ? void 0 : _a.piral) !== null && _b !== void 0 ? _b : "*";
switch (details.logLevel) {
case LogLevels.disabled:
(0, log_1.setLogLevel)("disabled");
break;
case LogLevels.error:
(0, log_1.setLogLevel)("error");
break;
case LogLevels.warning:
(0, log_1.setLogLevel)("warn");
break;
case LogLevels.info:
(0, log_1.setLogLevel)("info");
break;
case LogLevels.verbose:
case LogLevels.debug:
(0, log_1.setLogLevel)("verbose");
break;
}
(0, version_1.checkVersion)(desiredVersion, details.cliVersion);
} else {
(0, log_1.log)("warn", `The used version of the "piral-cli" is outdated. The templating may still work - if not you should use a more recent version of the "piral-cli".`);
}
}
}
});
// ../../node_modules/ejs/lib/utils.js
var require_utils2 = __commonJS({
"../../node_modules/ejs/lib/utils.js"(exports2) {
"use strict";
var regExpChars = /[|\\{}()[\]^$+*?.]/g;
exports2.escapeRegExpChars = function(string) {
if (!string) {
return "";
}
return String(string).replace(regExpChars, "\\$&");
};
var _ENCODE_HTML_RULES = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
var _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
}
var escapeFuncStr = `var _ENCODE_HTML_RULES = {
"&": "&"
, "<": "<"
, ">": ">"
, '"': """
, "'": "'"
}
, _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
};
`;
exports2.escapeXML = function(markup) {
return markup == void 0 ? "" : String(markup).replace(_MATCH_HTML, encode_char);
};
exports2.escapeXML.toString = function() {
return Function.prototype.toString.call(this) + ";\n" + escapeFuncStr;
};
exports2.shallowCopy = function(to, from) {
from = from || {};
for (var p in from) {
to[p] = from[p];
}
return to;
};
exports2.shallowCopyFromList = function(to, from, list) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != "undefined") {
to[p] = from[p];
}
}
return to;
};
exports2.cache = {
_data: {},
set: function(key, val) {
this._data[key] = val;
},
get: function(key) {
return this._data[key];
},
remove: function(key) {
delete this._data[key];
},
reset: function() {
this._data = {};
}
};
}
});
// ../../node_modules/ejs/package.json
var require_package = __commonJS({
"../../node_modules/ejs/package.json"(exports2, module2) {
module2.exports = {
name: "ejs",
description: "Embedded JavaScript templates",
keywords: [
"template",
"engine",
"ejs"
],
version: "2.7.4",
author: "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
license: "Apache-2.0",
main: "./lib/ejs.js",
repository: {
type: "git",
url: "git://github.com/mde/ejs.git"
},
bugs: "https://github.com/mde/ejs/issues",
homepage: "https://github.com/mde/ejs",
dependencies: {},
devDependencies: {
browserify: "^13.1.1",
eslint: "^4.14.0",
"git-directory-deploy": "^1.5.1",
jake: "^10.3.1",
jsdoc: "^3.4.0",
"lru-cache": "^4.0.1",
mocha: "^5.0.5",
"uglify-js": "^3.3.16"
},
engines: {
node: ">=0.10.0"
},
scripts: {
test: "mocha",
postinstall: "node ./postinstall.js"
}
};
}
});
// ../../node_modules/ejs/lib/ejs.js
var require_ejs = __commonJS({
"../../node_modules/ejs/lib/ejs.js"(exports2) {
"use strict";
var fs = require("fs");
var path = require("path");
var utils = require_utils2();
var scopeOptionWarned = false;
var _VERSION_STRING = require_package().version;
var _DEFAULT_OPEN_DELIMITER = "<";
var _DEFAULT_CLOSE_DELIMITER = ">";
var _DEFAULT_DELIMITER = "%";
var _DEFAULT_LOCALS_NAME = "locals";
var _NAME = "ejs";
var _REGEX_STRING = "(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";
var _OPTS_PASSABLE_WITH_DATA = [
"delimiter",
"scope",
"context",
"debug",
"compileDebug",
"client",
"_with",
"rmWhitespace",
"strict",
"filename",
"async"
];
var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat("cache");
var _BOM = /^\uFEFF/;
exports2.cache = utils.cache;
exports2.fileLoader = fs.readFileSync;
exports2.localsName = _DEFAULT_LOCALS_NAME;
exports2.promiseImpl = new Function("return this;")().Promise;
exports2.resolveInclude = function(name, filename, isDir) {
var dirname = path.dirname;
var extname = path.extname;
var resolve2 = path.resolve;
var includePath = resolve2(isDir ? filename : dirname(filename), name);
var ext = extname(name);
if (!ext) {
includePath += ".ejs";
}
return includePath;
};
function getIncludePath(path2, options) {
var includePath;
var filePath;
var views = options.views;
var match = /^[A-Za-z]+:\\|^\//.exec(path2);
if (match && match.length) {
includePath = exports2.resolveInclude(path2.replace(/^\/*/, ""), options.root || "/", true);
} else {
if (options.filename) {
filePath = exports2.resolveInclude(path2, options.filename);
if (fs.existsSync(filePath)) {
includePath = filePath;
}
}
if (!includePath) {
if (Array.isArray(views) && views.some(function(v) {
filePath = exports2.resolveInclude(path2, v, true);
return fs.existsSync(filePath);
})) {
includePath = filePath;
}
}
if (!includePath) {
throw new Error('Could not find the include file "' + options.escapeFunction(path2) + '"');
}
}
return includePath;
}
function handleCache(options, template) {
var func;
var filename = options.filename;
var hasTemplate = arguments.length > 1;
if (options.cache) {
if (!filename) {
throw new Error("cache option requires a filename");
}
func = exports2.cache.get(filename);
if (func) {
return func;
}
if (!hasTemplate) {
template = fileLoader(filename).toString().replace(_BOM, "");
}
} else if (!hasTemplate) {
if (!filename) {
throw new Error("Internal EJS error: no file name or template provided");
}
template = fileLoader(filename).toString().replace(_BOM, "");
}
func = exports2.compile(template, options);
if (options.cache) {
exports2.cache.set(filename, func);
}
return func;
}
function tryHandleCache(options, data, cb) {
var result;
if (!cb) {
if (typeof exports2.promiseImpl == "function") {
return new exports2.promiseImpl(function(resolve2, reject) {
try {
result = handleCache(options)(data);
resolve2(result);
} catch (err) {
reject(err);
}
});
} else {
throw new Error("Please provide a callback function");
}
} else {
try {
result = handleCache(options)(data);
} catch (err) {
return cb(err);
}
cb(null, result);
}
}
function fileLoader(filePath) {
return exports2.fileLoader(filePath);
}
function includeFile(path2, options) {
var opts = utils.shallowCopy({}, options);
opts.filename = getIncludePath(path2, opts);
return handleCache(opts);
}
function includeSource(path2, options) {
var opts = utils.shallowCopy({}, options);
var includePath;
var template;
includePath = getIncludePath(path2, opts);
template = fileLoader(includePath).toString().replace(_BOM, "");
opts.filename = includePath;
var templ = new Template(template, opts);
templ.generateSource();
return {
source: templ.source,
filename: includePath,
template
};
}
function rethrow(err, str, flnm, lineno, esc) {
var lines = str.split("\n");
var start = Math.max(lineno - 3, 0);
var end = Math.min(lines.length, lineno + 3);
var filename = esc(flnm);
var context = lines.slice(start, end).map(function(line, i) {
var curr = i + start + 1;
return (curr == lineno ? " >> " : " ") + curr + "| " + line;
}).join("\n");
err.path = filename;
err.message = (filename || "ejs") + ":" + lineno + "\n" + context + "\n\n" + err.message;
throw err;
}
function stripSemi(str) {
return str.replace(/;(\s*$)/, "$1");
}
exports2.compile = function compile(template, opts) {
var templ;
if (opts && opts.scope) {
if (!scopeOptionWarned) {
console.warn("`scope` option is deprecated and will be removed in EJS 3");
scopeOptionWarned = true;
}
if (!opts.context) {
opts.context = opts.scope;
}
delete opts.scope;
}
templ = new Template(template, opts);
return templ.compile();
};
exports2.render = function(template, d, o) {
var data = d || {};
var opts = o || {};
if (arguments.length == 2) {
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
}
return handleCache(opts, template)(data);
};
exports2.renderFile = function() {
var args = Array.prototype.slice.call(arguments);
var filename = args.shift();
var cb;
var opts = { filename };
var data;
var viewOpts;
if (typeof arguments[arguments.length - 1] == "function") {
cb = args.pop();
}
if (args.length) {
data = args.shift();
if (args.length) {
utils.shallowCopy(opts, args.pop());
} else {
if (data.settings) {
if (data.settings.views) {
opts.views = data.settings.views;
}
if (data.settings["view cache"]) {
opts.cache = true;
}
viewOpts = data.settings["view options"];
if (viewOpts) {
utils.shallowCopy(opts, viewOpts);
}
}
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
}
opts.filename = filename;
} else {
data = {};
}
return tryHandleCache(opts, data, cb);
};
exports2.Template = Template;
exports2.clearCache = function() {
exports2.cache.reset();
};
function Template(text, opts) {
opts = opts || {};
var options = {};
this.templateText = text;
this.mode = null;
this.truncate = false;
this.currentLine = 1;
this.source = "";
this.dependencies = [];
options.client = opts.client || false;
options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
options.compileDebug = opts.compileDebug !== false;
options.debug = !!opts.debug;
options.filename = opts.filename;
options.openDelimiter = opts.openDelimiter || exports2.openDelimiter || _DEFAULT_OPEN_DELIMITER;
options.closeDelimiter = opts.closeDelimiter || exports2.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
options.delimiter = opts.delimiter || exports2.delimiter || _DEFAULT_DELIMITER;
options.strict = opts.strict || false;
options.context = opts.context;
options.cache = opts.cache || false;
options.rmWhitespace = opts.rmWhitespace;
options.root = opts.root;
options.outputFunctionName = opts.outputFunctionName;
options.localsName = opts.localsName || exports2.localsName || _DEFAULT_LOCALS_NAME;
options.views = opts.views;
options.async = opts.async;
options.destructuredLocals = opts.destructuredLocals;
options.legacyInclude = typeof opts.legacyInclude != "undefined" ? !!opts.legacyInclude : true;
if (options.strict) {
options._with = false;
} else {
options._with = typeof opts._with != "undefined" ? opts._with : true;
}
this.opts = options;
this.regex = this.createRegex();
}
Template.modes = {
EVAL: "eval",
ESCAPED: "escaped",
RAW: "raw",
COMMENT: "comment",
LITERAL: "literal"
};
Template.prototype = {
createRegex: function() {
var str = _REGEX_STRING;
var delim = utils.escapeRegExpChars(this.opts.delimiter);
var open = utils.escapeRegExpChars(this.opts.openDelimiter);
var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
str = str.replace(/%/g, delim).replace(/</g, open).replace(/>/g, close);
return new RegExp(str);
},
compile: function() {
var src;
var fn;
var opts = this.opts;
var prepended = "";
var appended = "";
var escapeFn = opts.escapeFunction;
var ctor;
if (!this.source) {
this.generateSource();
prepended += ' var __output = "";\n function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
prepended += " var " + opts.outputFunctionName + " = __append;\n";
}
if (opts.destructuredLocals && opts.destructuredLocals.length) {
var destructuring = " var __locals = (" + opts.localsName + " || {}),\n";
for (var i = 0; i < opts.destructuredLocals.length; i++) {
var name = opts.destructuredLocals[i];
if (i > 0) {
destructuring += ",\n ";
}
destructuring += name + " = __locals." + name;
}
prepended += destructuring + ";\n";
}
if (opts._with !== false) {
prepended += " with (" + opts.localsName + " || {}) {\n";
appended += " }\n";
}
appended += " return __output;\n";
this.source = prepended + this.source + appended;
}
if (opts.compileDebug) {
src = "var __line = 1\n , __lines = " + JSON.stringify(this.templateText) + "\n , __filename = " + (opts.filename ? JSON.stringify(opts.filename) : "undefined") + ";\ntry {\n" + this.source + "} catch (e) {\n rethrow(e, __lines, __filename, __line, escapeFn);\n}\n";
} else {
src = this.source;
}
if (opts.client) {
src = "escapeFn = escapeFn || " + escapeFn.toString() + ";\n" + src;
if (opts.compileDebug) {
src = "rethrow = rethrow || " + rethrow.toString() + ";\n" + src;
}
}
if (opts.strict) {
src = '"use strict";\n' + src;
}
if (opts.debug) {
console.log(src);
}
if (opts.compileDebug && opts.filename) {
src = src + "\n//# sourceURL=" + opts.filename + "\n";
}
try {
if (opts.async) {
try {
ctor = new Function("return (async function(){}).constructor;")();
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error("This environment does not support async/await");
} else {
throw e;
}
}
} else {
ctor = Function;
}
fn = new ctor(opts.localsName + ", escapeFn, include, rethrow", src);
} catch (e) {
if (e instanceof SyntaxError) {
if (opts.filename) {
e.message += " in " + opts.filename;
}
e.message += " while compiling ejs\n\n";
e.message += "If the above error is not helpful, you may want to try EJS-Lint:\n";
e.message += "https://github.com/RyanZim/EJS-Lint";
if (!opts.async) {
e.message += "\n";
e.message += "Or, if you meant to create an async function, pass `async: true` as an option.";
}
}
throw e;
}
var returnedFn = opts.client ? fn : function anonymous(data) {
var include = function(path2, includeData) {
var d = utils.shallowCopy({}, data);
if (includeData) {
d = utils.shallowCopy(d, includeData);
}
return includeFile(path2, opts)(d);
};
return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
};
returnedFn.dependencies = this.dependencies;
if (opts.filename && typeof Object.defineProperty === "function") {
var filename = opts.filename;
var basename = path.basename(filename, path.extname(filename));
try {
Object.defineProperty(returnedFn, "name", {
value: basename,
writable: false,
enumerable: false,
configurable: true
});
} catch (e) {
}
}
return returnedFn;
},
generateSource: function() {
var opts = this.opts;
if (opts.rmWhitespace) {
this.templateText = this.templateText.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, "");
}
this.templateText = this.templateText.replace(/[ \t]*<%_/gm, "<%_").replace(/_%>[ \t]*/gm, "_%>");
var self = this;
var matches = this.parseTemplateText();
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
if (matches && matches.length) {
matches.forEach(function(line, index) {
var opening;
var closing;
var include;
var includeOpts;
var includeObj;
var includeSrc;
if (line.indexOf(o + d) === 0 && line.indexOf(o + d + d) !== 0) {
closing = matches[index + 2];
if (!(closing == d + c || closing == "-" + d + c || closing == "_" + d + c)) {
throw new Error('Could not find matching close tag for "' + line + '".');
}
}
if (opts.legacyInclude && (include = line.match(/^\s*include\s+(\S+)/))) {
opening = matches[index - 1];
if (opening && (opening == o + d || opening == o + d + "-" || opening == o + d + "_")) {
includeOpts = utils.shallowCopy({}, self.opts);
includeObj = includeSource(include[1], includeOpts);
if (self.opts.compileDebug) {
includeSrc = " ; (function(){\n var __line = 1\n , __lines = " + JSON.stringify(includeObj.template) + "\n , __filename = " + JSON.stringify(includeObj.filename) + ";\n try {\n" + includeObj.source + " } catch (e) {\n rethrow(e, __lines, __filename, __line, escapeFn);\n }\n ; }).call(this)\n";
} else {
includeSrc = " ; (function(){\n" + includeObj.source + " ; }).call(this)\n";
}
self.source += includeSrc;
self.dependencies.push(exports2.resolveInclude(
include[1],
includeOpts.filename
));
return;
}
}
self.scanLine(line);
});
}
},
parseTemplateText: function() {
var str = this.templateText;
var pat = this.regex;
var result = pat.exec(str);
var arr = [];
var firstPos;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(str.substring(0, firstPos));
str = str.slice(firstPos);
}
arr.push(result[0]);
str = str.slice(result[0].length);
result = pat.exec(str);
}
if (str) {
arr.push(str);
}
return arr;
},
_addOutput: function(line) {
if (this.truncate) {
line = line.replace(/^(?:\r\n|\r|\n)/, "");
this.truncate = false;
}
if (!line) {
return line;
}
line = line.replace(/\\/g, "\\\\");
line = line.replace(/\n/g, "\\n");
line = line.replace(/\r/g, "\\r");
line = line.replace(/"/g, '\\"');
this.source += ' ; __append("' + line + '")\n';
},
scanLine: function(line) {
var self = this;
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
var newLineCount = 0;
newLineCount = line.split("\n").length - 1;
switch (line) {
case o + d:
case o + d + "_":
this.mode = Template.modes.EVAL;
break;
case o + d + "=":
this.mode = Template.modes.ESCAPED;
break;
case o + d + "-":
this.mode = Template.modes.RAW;
break;
case o + d + "#":
this.mode = Template.modes.COMMENT;
break;
case o + d + d:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")\n';
break;
case d + d + c:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")\n';
break;
case d + c:
case "-" + d + c:
case "_" + d + c:
if (this.mode == Template.modes.LITERAL) {
this._addOutput(line);
}
this.mode = null;
this.truncate = line.indexOf("-") === 0 || line.indexOf("_") === 0;
break;
default:
if (this.mode) {
switch (this.mode) {
case Template.modes.EVAL:
case Template.modes.ESCAPED:
case Template.modes.RAW:
if (line.lastIndexOf("//") > line.lastIndexOf("\n")) {
line += "\n";
}
}
switch (this.mode) {
// Just executing code
case Template.modes.EVAL:
this.source += " ; " + line + "\n";
break;
// Exec, esc, and output
case Template.modes.ESCAPED:
this.source += " ; __append(escapeFn(" + stripSemi(line) + "))\n";
break;
// Exec and output
case Template.modes.RAW:
this.source += " ; __append(" + stripSemi(line) + ")\n";
break;
case Template.modes.COMMENT:
break;
// Literal <%% mode, append as raw output
case Template.modes.LITERAL:
this._addOutput(line);
break;
}
} else {
this._addOutput(line);
}
}
if (self.opts.compileDebug && newLineCount) {
this.currentLine += newLineCount;
this.source += " ; __line = " + this.currentLine + "\n";
}
}
};
exports2.escapeXML = utils.escapeXML;
exports2.__express = exports2.renderFile;
if (require.extensions) {
require.extensions[".ejs"] = function(module3, flnm) {
console.log("Deprecated: this API will go away in EJS v2.8");
var filename = flnm || /* istanbul ignore next */
module3.filename;
var options = {
filename,
client: true
};
var template = fileLoader(filename).toString();
var fn = exports2.compile(template, options);
module3._compile("module.exports = " + fn.toString() + ";", filename);
};
}
exports2.VERSION = _VERSION_STRING;
exports2.name = _NAME;
if (typeof window != "undefined") {
window.ejs = exports2;
}
}
});
// ../../packages/template-utils/lib/template.js
var require_template = __commonJS({
"../../packages/template-utils/lib/template.js"(exports2) {
"use strict";
var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.normalizeData = normalizeData;
exports2.getFileFromTemplate = getFileFromTemplate;
var path_1 = require("path");
var ejs_1 = require_ejs();
var log_1 = require_log();
var utils_1 = require_utils();
var findVariable = /<(\w+)>/g;
function replaceVariables(str, data) {
let match = findVariable.exec(str);
while (match) {
const [m, id] = match;
const val = data[id];
if (typeof val === "string") {
str = str.replace(m, val);
} else {
str = str.replace(m, ".");
}
findVariable.lastIndex = 0;
match = findVariable.exec(str);
}
return str;
}
function fillTemplate(sourceDir, name, data) {
const path = (0, path_1.resolve)(sourceDir, `${name}.ejs`);
(0, log_1.log)("verbose", `Filling template of "${path}" ...`);
return new Promise((resolve2, reject) => {
(0, ejs_1.renderFile)(path, data, (err, str) => {
if (err) {
(0, log_1.log)("error", `Could not fill template at "${path}": ${err}`);
reject(err);
} else {
(0, log_1.log)("verbose", `Filled template at "${path}" ...`);
resolve2(str);
}
});
});
}
function normalizeData(data) {
data.src = (0, utils_1.makeRelative)(replaceVariables(data.src, data), data.projectRoot);
data.mocks = (0, utils_1.makeRelative)(replaceVariables(data.mocks, data), data.projectRoot);
return data;
}
function getFileFromTemplate(sourceDir, source, data) {
return __awaiter(this, void 0, void 0, function* () {
let { target, name, content } = source;
const path = (0, utils_1.makeRelative)(replaceVariables(target, data), data.projectRoot);
if (!content) {
(0, log_1.log)("verbose", `Return template "${name}" with path "${path}" (from "${target}")`);
content = yield fillTemplate(sourceDir, name, data);
} else {
(0, log_1.log)("verbose", `Return template "${name}" with content at path "${path}" (from "${target}")`);
}
return {
content: Buffer.from(content, "utf8"),
path
};
});
}
}
});
// ../../packages/template-utils/lib/factory.js
var require_factory = __commonJS({
"../../packages/template-utils/lib/factory.js"(exports2) {
"use strict";
var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createPiletTemplateFactory = createPiletTemplateFactory2;
exports2.createPiralTemplateFactory = createPiralTemplateFactory;
var path_1 = require("path");
var io_1 = require_io();
var assets_1 = require_assets();
var parent_1 = require_parent();
var template_1 = require_template();
var utils_1 = require_utils();
var mergePackageJson = [/package\.json$/];
function createPiletTemplateFactory2(templateRoot, getAllSources, defaultArgs = {}, deepMerged = mergePackageJson) {
const sourceDir = (0, path_1.resolve)(templateRoot, "templates");
return (projectRoot, args, details) => __awaiter(this, void 0, void 0, function* () {
(0, parent_1.configure)(templateRoot, details);
const allArgs = Object.assign(Object.assign({}, defaultArgs), args);
const { language = "ts", sourceName, src = "<root>/src", plugins = (0, utils_1.getPlugins)(projectRoot, sourceName), mocks = "<src>/mocks" } = allArgs;
const allSources = getAllSources(projectRoot, allArgs, details);
const data = (0, template_1.normalizeData)(Object.assign(Object.assign({}, allArgs), {
language,
plugins,
projectRoot,
root: ".",
piletName: (0, path_1.basename)(projectRoot),
sourceName,
extension: (0, utils_1.getLanguageExtension)(language),
src,
mocks
}));
const defaultSources = [
(0, assets_1.getAssetsSource)(),
(0, utils_1.getPackageJsonWithSource)(data.projectRoot, data.src, `index${data.extension}`)
];
const sources = [...allSources, ...defaultSources].filter((m) => m.languages.includes(language));
const files = yield Promise.all(sources.map((source) => (0, template_1.getFileFromTemplate)(sourceDir, source, data)));
return (0, io_1.mergeFiles)(files, deepMerged);
});
}
function createPiralTemplateFactory(templateRoot, getAllSources, defaultArgs = {}, deepMerged = mergePackageJson) {
const sourceDir = (0, path_1.resolve)(templateRoot, "templates");
return (projectRoot, args, details) => __awaiter(this, void 0, void 0, function* () {
(0, parent_1.configure)(templateRoot, details);
const allArgs = Object.assign(Object.assign({}, defaultArgs), args);
const { language = "ts", packageName = "piral", mocks = "<src>/mocks", src = "<root>/src", title = "My Piral Instance", reactVersion = 17, plugins = [] } = allArgs;
const allSources = getAllSources(projectRoot, allArgs, details);
const data = (0, template_1.normalizeData)(Object.assign(Object.assign({}, allArgs), {
title,
language,
plugins,
projectRoot,
root: ".",
reactVersion,
packageName,
extension: (0, utils_1.getLanguageExtension)(language, packageName !== "piral-base"),
src,
mocks
}));
const defaultSources = [(0, assets_1.getAssetsSource)()];
co