@kosatyi/ejs 0.0.77 → 0.0.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/bundler.js ADDED
@@ -0,0 +1,43 @@
1
+ #! /usr/bin/env node
2
+
3
+ import argv from 'process.argv'
4
+
5
+ import { Bundler } from '../dist/esm/bundler.js'
6
+
7
+ const schema = argv(process.argv.slice(2))
8
+
9
+ const params = schema({
10
+ target: null,
11
+ transform: false,
12
+ timestamp: true,
13
+ minify: false,
14
+ withObject: false,
15
+ export: 'ejsPrecompiled',
16
+ path: 'views',
17
+ extension: 'ejs',
18
+ })
19
+
20
+ if (typeof params.target !== 'string') {
21
+ throw new Error('target is not a string')
22
+ }
23
+
24
+ const options = {
25
+ target: params.target,
26
+ transform: params.transform,
27
+ timestamp: params.timestamp,
28
+ minify: params.minify,
29
+ }
30
+ const config = {
31
+ withObject: params.withObject,
32
+ path: params.path,
33
+ export: params.export,
34
+ extension: params.extension,
35
+ }
36
+
37
+ const bundler = new Bundler(options, config)
38
+
39
+ await bundler.build()
40
+
41
+ if (params.watch && params.path) {
42
+ await bundler.watch()
43
+ }
@@ -323,7 +323,7 @@ function Compiler(config) {
323
323
  });
324
324
  });
325
325
  source += "');";
326
- source = "try{".concat(source, "}catch(e){console.info(e)}");
326
+ source = "try{".concat(source, "}catch(e){return ").concat(BUFFER, ".error(e)}");
327
327
  if (compiler.withObject) {
328
328
  source = "with(".concat(SCOPE, "){").concat(source, "}");
329
329
  }
@@ -435,11 +435,36 @@ var element = function element(tag, attrs, content) {
435
435
  return result.join('');
436
436
  };
437
437
 
438
+ function TemplateError(message) {
439
+ this.code = 1;
440
+ this.name = 'TemplateError';
441
+ this.message = message;
442
+ Error.call(this);
443
+ }
444
+ Object.setPrototypeOf(TemplateNotFound.prototype, Error.prototype);
445
+ function TemplateNotFound(message) {
446
+ TemplateError.call(this);
447
+ this.code = 404;
448
+ this.name = 'TemplateNotFound';
449
+ this.message = message;
450
+ }
451
+ Object.setPrototypeOf(TemplateNotFound.prototype, TemplateError.prototype);
452
+ function TemplateSyntaxError(message) {
453
+ TemplateError.call(this);
454
+ this.code = 500;
455
+ this.name = 'TemplateSyntaxError';
456
+ this.message = message;
457
+ }
458
+ Object.setPrototypeOf(TemplateSyntaxError.prototype, TemplateError.prototype);
459
+
438
460
  function resolve(list) {
439
461
  return Promise.all(list || []).then(function (list) {
440
462
  return list.join('');
441
463
  });
442
464
  }
465
+ function reject(error) {
466
+ return Promise.reject(new TemplateSyntaxError(error.message));
467
+ }
443
468
  function createBuffer() {
444
469
  var store = [],
445
470
  array = [];
@@ -459,7 +484,7 @@ function createBuffer() {
459
484
  return resolve(result);
460
485
  };
461
486
  buffer.error = function (e) {
462
- throw e;
487
+ return reject(e);
463
488
  };
464
489
  buffer.end = function () {
465
490
  return resolve(array);
@@ -484,6 +509,11 @@ function Context(config) {
484
509
  this.helpers = function (methods) {
485
510
  extend(Scope.prototype, methods || {});
486
511
  };
512
+ /**
513
+ * @name ContextScope
514
+ * @param data
515
+ * @constructor
516
+ */
487
517
  function Scope(data) {
488
518
  this[BLOCKS] = {};
489
519
  this[MACRO] = {};
@@ -629,8 +659,8 @@ function Context(config) {
629
659
  var prop = path.pop();
630
660
  return hasProp(result, prop) ? result[prop] : defaults;
631
661
  },
632
- writable: false,
633
- configurable: false,
662
+ writable: true,
663
+ configurable: true,
634
664
  enumerable: false
635
665
  }), _defineProperty(_Object$definePropert, "set", {
636
666
  value: function value(name, _value2) {
@@ -770,13 +800,15 @@ function EJS(options) {
770
800
  var compiler = new Compiler(config);
771
801
  var cache = new Cache();
772
802
  var template = new Template(config, cache, compiler);
773
- var output = function output(path, context) {
774
- var params = [context, context.getComponent(), context.getBuffer(), safeValue];
775
- config.globalHelpers.forEach(function (name) {
776
- if (isFunction(context[name])) params.push(context[name].bind(context));
777
- });
803
+ var output = function output(path, scope) {
804
+ var globalHelpers = config.globalHelpers;
805
+ var params = [scope, scope.getComponent(), scope.getBuffer(), safeValue].concat(globalHelpers.filter(function (name) {
806
+ return isFunction(scope[name]);
807
+ }).map(function (name) {
808
+ return scope[name].bind(scope);
809
+ }));
778
810
  return template.get(path).then(function (callback) {
779
- return callback.apply(context, params);
811
+ return callback.apply(scope, params);
780
812
  });
781
813
  };
782
814
  var require = function require(name) {
@@ -837,7 +869,7 @@ var httpRequest = function httpRequest(path, template) {
837
869
  return fetch(joinPath(path, template)).then(function (response) {
838
870
  return response.text();
839
871
  }, function (reason) {
840
- return String(reason);
872
+ return new TemplateError(reason);
841
873
  });
842
874
  };
843
875
 
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var glob = require('glob');
5
+ var path = require('path');
6
+ var terser = require('terser');
7
+ var index_js = require('./index.js');
8
+ var babel = require('@babel/core');
9
+
10
+ const isPlainObject = function (obj) {
11
+ return Object.prototype.toString.call(obj) === '[object Object]'
12
+ };
13
+
14
+ const extend = (target, ...sources) => {
15
+ return Object.assign(target, ...sources.filter(isPlainObject))
16
+ };
17
+
18
+ class Bundler {
19
+ /**
20
+ * @type {BundlerOptions}
21
+ */
22
+ options = {
23
+ target: [],
24
+ transform: true,
25
+ minify: true,
26
+ timestamp: true,
27
+ }
28
+ /**
29
+ * @type {EjsConfig}
30
+ */
31
+ config = {}
32
+ constructor(options, config) {
33
+ extend(this.options, options || {});
34
+ this.config = index_js.configure(config || {});
35
+ this.templates = {};
36
+ }
37
+ stageRead(path$1) {
38
+ return fs.promises
39
+ .readFile(path.join(this.config.path, path$1))
40
+ .then((response) => response.toString())
41
+ }
42
+ stageCompile(content, name) {
43
+ return index_js.compile(content, name).source
44
+ }
45
+ async stageMinify(content) {
46
+ if (this.options.minify === false) return content
47
+ const config = {
48
+ compress: {
49
+ dead_code: false,
50
+ side_effects: false,
51
+ },
52
+ };
53
+ const response = await terser.minify(content, config);
54
+ return response.code
55
+ }
56
+ async stageTransform(content) {
57
+ if (this.options.transform === false) return content
58
+ const config = {
59
+ presets: [['@babel/preset-env']],
60
+ sourceType: 'script',
61
+ };
62
+ const response = await babel.transformAsync(content, config);
63
+ return response.code
64
+ }
65
+ getBundle() {
66
+ const transform = this.options.transform;
67
+ const moduleId = this.config.export;
68
+ const useStrict = this.config.withObject === false;
69
+ const timestamp = this.options.timestamp;
70
+ const out = [];
71
+ if (transform) {
72
+ out.push('(function(global,factory){');
73
+ out.push(
74
+ 'typeof exports === "object" && typeof module !== "undefined" ?'
75
+ );
76
+ out.push('module.exports = factory():');
77
+ out.push(
78
+ 'typeof define === "function" && define.amd ? define(factory):'
79
+ );
80
+ out.push(
81
+ '(global = typeof globalThis !== "undefined" ? globalThis:'
82
+ );
83
+ out.push('global || self,global["' + moduleId + '"] = factory())');
84
+ out.push('})(this,(function(){');
85
+ }
86
+ if (useStrict) out.push("'use strict'");
87
+ if (timestamp) out.push('const timestamp = '.concat(String(Date.now())));
88
+ out.push('const templates = {}');
89
+ Object.entries(this.templates).forEach(([name, content]) => {
90
+ name = JSON.stringify(name);
91
+ content = String(content);
92
+ out.push(`templates[${name}] = ${content}`);
93
+ });
94
+ if (transform) {
95
+ out.push('return templates');
96
+ out.push('}))');
97
+ } else {
98
+ out.push('export default templates');
99
+ }
100
+ return out.join('\n')
101
+ }
102
+ async watch() {
103
+ console.log(`ejs-bundle: watching directory - ${this.config.path}`);
104
+ try {
105
+ const watcher = fs.promises.watch(this.config.path, { recursive: true });
106
+ for await (const { filename } of watcher) {
107
+ if (path.extname(filename).slice(1) === this.config.extension) {
108
+ console.log(`ejs-bundle: file is changed - ${filename}`);
109
+ await this.build();
110
+ }
111
+ }
112
+ } catch (err) {
113
+ throw err
114
+ }
115
+ }
116
+ async build() {
117
+ if (this.buildInProgress === true) return false
118
+ this.buildInProgress = true;
119
+ await this.concat().catch(console.error);
120
+ await this.output().catch(console.error);
121
+ console.log(`ejs-bundle: bundle complete - ${this.options.target}`);
122
+ this.buildInProgress = false;
123
+ }
124
+ async concat() {
125
+ const pattern = '**/*.'.concat(this.config.extension);
126
+ const list = await glob.glob(pattern, { cwd: this.config.path });
127
+ for (let template of list) {
128
+ let content = '';
129
+ content = await this.stageRead(template);
130
+ content = await this.stageCompile(content, template);
131
+ this.templates[template] = content;
132
+ }
133
+ }
134
+ async output() {
135
+ const target = [].concat(this.options.target);
136
+ let content = this.getBundle();
137
+ if (this.options.transform) {
138
+ content = await this.stageTransform(content);
139
+ }
140
+ if (this.options.minify) {
141
+ content = await this.stageMinify(content);
142
+ }
143
+ for (let file of target) {
144
+ const folderPath = path.dirname(file);
145
+ const folderExists = await fs.promises
146
+ .stat(folderPath)
147
+ .then(() => true)
148
+ .catch(() => false);
149
+ if (folderExists === false) {
150
+ await fs.promises.mkdir(folderPath, { recursive: true });
151
+ }
152
+ await fs.promises.writeFile(file, content);
153
+ }
154
+ }
155
+ }
156
+
157
+ const ejsBundle = (options, config) => {
158
+ const bundler = new Bundler(options, config);
159
+ return {
160
+ name: 'ejs-bundle',
161
+ async buildStart() {
162
+ await bundler.concat();
163
+ },
164
+ async buildEnd() {
165
+ await bundler.output();
166
+ },
167
+ }
168
+ };
169
+
170
+ exports.Bundler = Bundler;
171
+ exports.ejsBundle = ejsBundle;
package/dist/cjs/index.js CHANGED
@@ -326,7 +326,7 @@ function Compiler(config) {
326
326
  });
327
327
  });
328
328
  source += "');";
329
- source = "try{".concat(source, "}catch(e){console.info(e)}");
329
+ source = "try{".concat(source, "}catch(e){return ").concat(BUFFER, ".error(e)}");
330
330
  if (compiler.withObject) {
331
331
  source = "with(".concat(SCOPE, "){").concat(source, "}");
332
332
  }
@@ -438,11 +438,36 @@ var element = function element(tag, attrs, content) {
438
438
  return result.join('');
439
439
  };
440
440
 
441
+ function TemplateError(message) {
442
+ this.code = 1;
443
+ this.name = 'TemplateError';
444
+ this.message = message;
445
+ Error.call(this);
446
+ }
447
+ Object.setPrototypeOf(TemplateNotFound.prototype, Error.prototype);
448
+ function TemplateNotFound(message) {
449
+ TemplateError.call(this);
450
+ this.code = 404;
451
+ this.name = 'TemplateNotFound';
452
+ this.message = message;
453
+ }
454
+ Object.setPrototypeOf(TemplateNotFound.prototype, TemplateError.prototype);
455
+ function TemplateSyntaxError(message) {
456
+ TemplateError.call(this);
457
+ this.code = 500;
458
+ this.name = 'TemplateSyntaxError';
459
+ this.message = message;
460
+ }
461
+ Object.setPrototypeOf(TemplateSyntaxError.prototype, TemplateError.prototype);
462
+
441
463
  function resolve(list) {
442
464
  return Promise.all(list || []).then(function (list) {
443
465
  return list.join('');
444
466
  });
445
467
  }
468
+ function reject(error) {
469
+ return Promise.reject(new TemplateSyntaxError(error.message));
470
+ }
446
471
  function createBuffer() {
447
472
  var store = [],
448
473
  array = [];
@@ -462,7 +487,7 @@ function createBuffer() {
462
487
  return resolve(result);
463
488
  };
464
489
  buffer.error = function (e) {
465
- throw e;
490
+ return reject(e);
466
491
  };
467
492
  buffer.end = function () {
468
493
  return resolve(array);
@@ -487,6 +512,11 @@ function Context(config) {
487
512
  this.helpers = function (methods) {
488
513
  extend(Scope.prototype, methods || {});
489
514
  };
515
+ /**
516
+ * @name ContextScope
517
+ * @param data
518
+ * @constructor
519
+ */
490
520
  function Scope(data) {
491
521
  this[BLOCKS] = {};
492
522
  this[MACRO] = {};
@@ -632,8 +662,8 @@ function Context(config) {
632
662
  var prop = path.pop();
633
663
  return hasProp(result, prop) ? result[prop] : defaults;
634
664
  },
635
- writable: false,
636
- configurable: false,
665
+ writable: true,
666
+ configurable: true,
637
667
  enumerable: false
638
668
  }), _defineProperty(_Object$definePropert, "set", {
639
669
  value: function value(name, _value2) {
@@ -773,13 +803,15 @@ function EJS(options) {
773
803
  var compiler = new Compiler(config);
774
804
  var cache = new Cache();
775
805
  var template = new Template(config, cache, compiler);
776
- var output = function output(path, context) {
777
- var params = [context, context.getComponent(), context.getBuffer(), safeValue];
778
- config.globalHelpers.forEach(function (name) {
779
- if (isFunction(context[name])) params.push(context[name].bind(context));
780
- });
806
+ var output = function output(path, scope) {
807
+ var globalHelpers = config.globalHelpers;
808
+ var params = [scope, scope.getComponent(), scope.getBuffer(), safeValue].concat(globalHelpers.filter(function (name) {
809
+ return isFunction(scope[name]);
810
+ }).map(function (name) {
811
+ return scope[name].bind(scope);
812
+ }));
781
813
  return template.get(path).then(function (callback) {
782
- return callback.apply(context, params);
814
+ return callback.apply(scope, params);
783
815
  });
784
816
  };
785
817
  var require = function require(name) {
@@ -840,7 +872,7 @@ function readFile(path, template) {
840
872
  return new Promise(function (resolve, reject) {
841
873
  fs.readFile(joinPath(path, template), function (error, data) {
842
874
  if (error) {
843
- reject(error);
875
+ reject(new TemplateError(error));
844
876
  } else {
845
877
  resolve(data.toString());
846
878
  }
@@ -678,7 +678,7 @@ function Compiler(config) {
678
678
  });
679
679
  });
680
680
  source += "');";
681
- source = "try{".concat(source, "}catch(e){console.info(e)}");
681
+ source = "try{".concat(source, "}catch(e){return ").concat(BUFFER, ".error(e)}");
682
682
  if (compiler.withObject) {
683
683
  source = "with(".concat(SCOPE, "){").concat(source, "}");
684
684
  }
@@ -761,11 +761,36 @@ var element = function element(tag, attrs, content) {
761
761
  return result.join('');
762
762
  };
763
763
 
764
+ function TemplateError(message) {
765
+ this.code = 1;
766
+ this.name = 'TemplateError';
767
+ this.message = message;
768
+ Error.call(this);
769
+ }
770
+ Object.setPrototypeOf(TemplateNotFound.prototype, Error.prototype);
771
+ function TemplateNotFound(message) {
772
+ TemplateError.call(this);
773
+ this.code = 404;
774
+ this.name = 'TemplateNotFound';
775
+ this.message = message;
776
+ }
777
+ Object.setPrototypeOf(TemplateNotFound.prototype, TemplateError.prototype);
778
+ function TemplateSyntaxError(message) {
779
+ TemplateError.call(this);
780
+ this.code = 500;
781
+ this.name = 'TemplateSyntaxError';
782
+ this.message = message;
783
+ }
784
+ Object.setPrototypeOf(TemplateSyntaxError.prototype, TemplateError.prototype);
785
+
764
786
  function resolve(list) {
765
787
  return Promise.all(list || []).then(function (list) {
766
788
  return list.join('');
767
789
  });
768
790
  }
791
+ function reject(error) {
792
+ return Promise.reject(new TemplateSyntaxError(error.message));
793
+ }
769
794
  function createBuffer() {
770
795
  var store = [],
771
796
  array = [];
@@ -785,7 +810,7 @@ function createBuffer() {
785
810
  return resolve(result);
786
811
  };
787
812
  buffer.error = function (e) {
788
- throw e;
813
+ return reject(e);
789
814
  };
790
815
  buffer.end = function () {
791
816
  return resolve(array);
@@ -810,6 +835,11 @@ function Context(config) {
810
835
  this.helpers = function (methods) {
811
836
  extend(Scope.prototype, methods || {});
812
837
  };
838
+ /**
839
+ * @name ContextScope
840
+ * @param data
841
+ * @constructor
842
+ */
813
843
  function Scope(data) {
814
844
  this[BLOCKS] = {};
815
845
  this[MACRO] = {};
@@ -955,8 +985,8 @@ function Context(config) {
955
985
  var prop = path.pop();
956
986
  return hasProp(result, prop) ? result[prop] : defaults;
957
987
  },
958
- writable: false,
959
- configurable: false,
988
+ writable: true,
989
+ configurable: true,
960
990
  enumerable: false
961
991
  }), _defineProperty(_Object$definePropert, "set", {
962
992
  value: function value(name, _value2) {
@@ -1096,13 +1126,15 @@ function EJS(options) {
1096
1126
  var compiler = new Compiler(config);
1097
1127
  var cache = new Cache();
1098
1128
  var template = new Template(config, cache, compiler);
1099
- var output = function output(path, context) {
1100
- var params = [context, context.getComponent(), context.getBuffer(), safeValue];
1101
- config.globalHelpers.forEach(function (name) {
1102
- if (isFunction(context[name])) params.push(context[name].bind(context));
1103
- });
1129
+ var output = function output(path, scope) {
1130
+ var globalHelpers = config.globalHelpers;
1131
+ var params = [scope, scope.getComponent(), scope.getBuffer(), safeValue].concat(globalHelpers.filter(function (name) {
1132
+ return isFunction(scope[name]);
1133
+ }).map(function (name) {
1134
+ return scope[name].bind(scope);
1135
+ }));
1104
1136
  return template.get(path).then(function (callback) {
1105
- return callback.apply(context, params);
1137
+ return callback.apply(scope, params);
1106
1138
  });
1107
1139
  };
1108
1140
  var require = function require(name) {
@@ -1159,33 +1191,73 @@ function EJS(options) {
1159
1191
  return this;
1160
1192
  }
1161
1193
 
1162
- var templates = {};
1194
+ var templateCache = {};
1163
1195
  var ejs = new EJS({
1164
1196
  cache: false,
1165
1197
  withObject: false,
1166
1198
  resolver: function resolver(path, name) {
1167
- if (name in templates) {
1168
- return Promise.resolve(templates[name]);
1169
- }
1170
- return Promise.resolve(['template not found', name]);
1199
+ return new Promise(function (resolve, reject) {
1200
+ if (templateCache.hasOwnProperty(name)) {
1201
+ resolve(templateCache[name]);
1202
+ } else {
1203
+ reject(new TemplateNotFound("template ".concat(name, " not found")));
1204
+ }
1205
+ });
1171
1206
  }
1172
1207
  });
1173
- function useTemplates(_x) {
1174
- return _useTemplates.apply(this, arguments);
1208
+ var getOrigin = function getOrigin(url, secure) {
1209
+ url = new URL(url);
1210
+ if (secure) url.protocol = 'https:';
1211
+ return url.origin;
1212
+ };
1213
+ function setTemplates(list) {
1214
+ Object.assign(templateCache, list || {});
1175
1215
  }
1176
- function _useTemplates() {
1177
- _useTemplates = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(list) {
1178
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1179
- while (1) switch (_context.prev = _context.next) {
1180
- case 0:
1181
- Object.assign(templates, list || {});
1182
- case 1:
1183
- case "end":
1184
- return _context.stop();
1185
- }
1186
- }, _callee);
1187
- }));
1188
- return _useTemplates.apply(this, arguments);
1216
+
1217
+ /**
1218
+ * @typedef {Object<string,any>} HonoContext
1219
+ * @property {function(*):Promise<Response>} html
1220
+ * @property {function(name:string,data:{}):Promise<string>} render
1221
+ * @property {function(name:string,data:{}):Promise<string>} ejs
1222
+ * @property {ContextScope} data
1223
+ */
1224
+
1225
+ /**
1226
+ *
1227
+ * @param {Object<string,any>} options
1228
+ * @return {(function(c:Context, next): Promise<any>)|*}
1229
+ */
1230
+ function setRenderer(_ref) {
1231
+ var _ref$secure = _ref.secure,
1232
+ secure = _ref$secure === void 0 ? true : _ref$secure,
1233
+ _ref$version = _ref.version,
1234
+ version = _ref$version === void 0 ? '1.0' : _ref$version;
1235
+ return /*#__PURE__*/function () {
1236
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(c, next) {
1237
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1238
+ while (1) switch (_context.prev = _context.next) {
1239
+ case 0:
1240
+ c.data = context({});
1241
+ c.data.set('version', version);
1242
+ c.data.set('origin', getOrigin(c.req.url, secure));
1243
+ c.ejs = function (name, data) {
1244
+ return render(name, Object.assign({}, c.data, data));
1245
+ };
1246
+ c.render = function (name, data) {
1247
+ return c.html(c.ejs(name, data));
1248
+ };
1249
+ _context.next = 7;
1250
+ return next();
1251
+ case 7:
1252
+ case "end":
1253
+ return _context.stop();
1254
+ }
1255
+ }, _callee);
1256
+ }));
1257
+ return function (_x, _x2) {
1258
+ return _ref2.apply(this, arguments);
1259
+ };
1260
+ }();
1189
1261
  }
1190
1262
  var render = ejs.render,
1191
1263
  context = ejs.context,
@@ -1202,4 +1274,5 @@ exports.create = create;
1202
1274
  exports.helpers = helpers;
1203
1275
  exports.preload = preload;
1204
1276
  exports.render = render;
1205
- exports.useTemplates = useTemplates;
1277
+ exports.setRenderer = setRenderer;
1278
+ exports.setTemplates = setTemplates;