mahabhuta 0.8.2 → 0.8.3

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/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../lib/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ const commander_1 = require("commander");
26
+ const mahabhuta = __importStar(require("./index.js"));
27
+ const fs_1 = require("fs");
28
+ const yaml_1 = __importDefault(require("yaml"));
29
+ // mahabhuta process file.html -o file2.html -m mahafuncs.js -m mahafuncs2.js -m mahafuncs3.js --options options.yaml --metadata metadata.yaml
30
+ const packageJSON = require('../package.json');
31
+ process.title = 'mahabhuta';
32
+ commander_1.program.version(packageJSON.version, '-v, --version', 'output the current version');
33
+ // DEFAULT CHEERIO CONFIG
34
+ // Cheerio Config
35
+ // Trace Processing
36
+ // Trace Performance
37
+ // metadata
38
+ commander_1.program
39
+ .command('process <inputFN>')
40
+ .description('Process an input file using supplied mahabhuta arrays')
41
+ .option('-o, --output <outputFN>', 'Specify output file name')
42
+ .option('-m, --module <mahafuncFN...>', 'JavaScript file (or files) containing a defined MahafuncArray')
43
+ .option('-c, --config <cheerioConfig>', 'YAML file containing Cheerio configuration')
44
+ .option('--trace-performance', 'Trace performance data')
45
+ .option('--trace-processing', 'Trace processing')
46
+ .option('--metadata <metadataFN>', 'YAML file containing data')
47
+ .option('--options <optionsFN', 'YAML file containing options for mahabhuta arrays')
48
+ .option('--partials', 'Enable the <partial> MahaFuncs')
49
+ .option('--partials-dir <dirFN...>', 'Directory name for partial templates')
50
+ .action(async (inputFN, cmdObj) => {
51
+ try {
52
+ // console.log(inputFN);
53
+ // console.log(cmdObj);
54
+ if (!inputFN)
55
+ throw new Error('No input file specified');
56
+ if (cmdObj.config) {
57
+ const txt = await fs_1.promises.readFile(cmdObj.config, 'utf8');
58
+ // console.log(`Read config ${cmdObj.config}`, txt);
59
+ const cheerioConfig = yaml_1.default.parse(txt);
60
+ // For cheerio 1.0.0-rc.10 we need to use this setting.
61
+ // If the configuration has set this, we must not
62
+ // override their setting. But, generally, for correct
63
+ // operation and handling of Mahabhuta tags, we need
64
+ // this setting to be <code>true</code>
65
+ if (!('_useHtmlParser2' in cheerioConfig)) {
66
+ cheerioConfig._useHtmlParser2 = true;
67
+ }
68
+ // console.log(`Setting cheerioConfig `, cheerioConfig);
69
+ mahabhuta.config(cheerioConfig);
70
+ }
71
+ // console.log('After config');
72
+ if (cmdObj.tracePerformance)
73
+ mahabhuta.setTracePerformance(true);
74
+ if (cmdObj.traceProcessing)
75
+ mahabhuta.setTraceProcessing(true);
76
+ let metadata = {};
77
+ if (cmdObj.metadata) {
78
+ const txt = await fs_1.promises.readFile(cmdObj.metadata, 'utf8');
79
+ // console.log(`Read metadata ${cmdObj.metadata}`, txt);
80
+ metadata = yaml_1.default.parse(txt);
81
+ }
82
+ // console.log('After metadata');
83
+ let mhOptions = {};
84
+ if (cmdObj.options) {
85
+ const txt = await fs_1.promises.readFile(cmdObj.options, 'utf8');
86
+ // console.log(`Read options ${cmdObj.options}`, txt);
87
+ mhOptions = yaml_1.default.parse(txt);
88
+ }
89
+ // console.log('After options');
90
+ const inputFile = await fs_1.promises.readFile(inputFN, 'utf8');
91
+ // console.log(`input file ${inputFile}`, inputFile);
92
+ const mahafuncs = [];
93
+ for (const arrayFN of cmdObj.module) {
94
+ const arrayModule = require(arrayFN);
95
+ // console.log(`MahafuncArray ${arrayFN}`);
96
+ if (!arrayModule.mahabhutaArray) {
97
+ throw new Error(`No mahabhutaArray function in ${arrayFN}`);
98
+ }
99
+ mahafuncs.push(arrayModule.mahabhutaArray(mhOptions));
100
+ }
101
+ let partialsModule;
102
+ if (cmdObj.partials) {
103
+ partialsModule = require('../maha/partial.js');
104
+ // console.log(partialsModule);
105
+ if (!partialsModule.configuration.partialDirs) {
106
+ partialsModule.configuration.partialDirs = [];
107
+ }
108
+ if (cmdObj.partialsDir) {
109
+ for (const dirFN of cmdObj.partialsDir) {
110
+ partialsModule.configuration.partialDirs.push(dirFN);
111
+ }
112
+ }
113
+ mahafuncs.push(partialsModule.mahabhutaArray(mhOptions));
114
+ }
115
+ const output = await mahabhuta.processAsync(inputFile, metadata, mahafuncs);
116
+ if (cmdObj.output) {
117
+ await fs_1.promises.writeFile(cmdObj.output, output, 'utf8');
118
+ }
119
+ else {
120
+ // console.log('////////////////////////// OUTPUT');
121
+ console.log(output);
122
+ // console.log('\\\\\\\\\\\\\\\\\\\\\\\\\\ OUTPUT');
123
+ }
124
+ }
125
+ catch (e) {
126
+ console.error(`process command ERRORED ${e.stack}`);
127
+ }
128
+ });
129
+ commander_1.program.parse();
130
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoi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m93IG5ldyBFcnJvcignTm8gaW5wdXQgZmlsZSBzcGVjaWZpZWQnKTtcblxuICAgICAgICAgICAgaWYgKGNtZE9iai5jb25maWcpIHtcblxuICAgICAgICAgICAgICAgIGNvbnN0IHR4dCA9IGF3YWl0IGZzcC5yZWFkRmlsZShjbWRPYmouY29uZmlnLCAndXRmOCcpO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKGBSZWFkIGNvbmZpZyAke2NtZE9iai5jb25maWd9YCwgdHh0KTtcbiAgICAgICAgICAgICAgICBjb25zdCBjaGVlcmlvQ29uZmlnID0gWUFNTC5wYXJzZSh0eHQpO1xuXG4gICAgICAgICAgICAgICAgLy8gRm9yIGNoZWVyaW8gMS4wLjAtcmMuMTAgd2UgbmVlZCB0byB1c2UgdGhpcyBzZXR0aW5nLlxuICAgICAgICAgICAgICAgIC8vIElmIHRoZSBjb25maWd1cmF0aW9uIGhhcyBzZXQgdGhpcywgd2UgbXVzdCBub3RcbiAgICAgICAgICAgICAgICAvLyBvdmVycmlkZSB0aGVpciBzZXR0aW5nLiAgQnV0LCBnZW5lcmFsbHksIGZvciBjb3JyZWN0XG4gICAgICAgICAgICAgICAgLy8gb3BlcmF0aW9uIGFuZCBoYW5kbGluZyBvZiBNYWhhYmh1dGEgdGFncywgd2UgbmVlZFxuICAgICAgICAgICAgICAgIC8vIHRoaXMgc2V0dGluZyB0byBiZSA8Y29kZT50cnVlPC9jb2RlPlxuICAgICAgICAgICAgICAgIGlmICghKCdfdXNlSHRtbFBhcnNlcjInIGluIGNoZWVyaW9Db25maWcpKSB7XG4gICAgICAgICAgICAgICAgICAgIGNoZWVyaW9Db25maWcuX3VzZUh0bWxQYXJzZXIyID0gdHJ1ZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgLy8gY29uc29sZS5sb2coYFNldHRpbmcgY2hlZXJpb0NvbmZpZyBgLCBjaGVlcmlvQ29uZmlnKTtcbiAgICAgICAgICAgICAgICBtYWhhYmh1dGEuY29uZmlnKGNoZWVyaW9Db25maWcpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgLy8gY29uc29sZS5sb2coJ0FmdGVyIGNvbmZpZycpO1xuXG4gICAgICAgICAgICBpZiAoY21kT2JqLnRyYWNlUGVyZm9ybWFuY2UpIG1haGFiaHV0YS5zZXRUcmFjZVBlcmZvcm1hbmNlKHRydWUpO1xuICAgICAgICAgICAgaWYgKGNtZE9iai50cmFjZVByb2Nlc3NpbmcpICBtYWhhYmh1dGEuc2V0VHJhY2VQcm9jZXNzaW5nKHRydWUpO1xuXG4gICAgICAgICAgICBsZXQgbWV0YWRhdGEgPSB7fTtcbiAgICAgICAgICAgIGlmIChjbWRPYmoubWV0YWRhdGEpIHtcbiAgICAgICAgICAgICAgICBjb25zdCB0eHQgPSBhd2FpdCBmc3AucmVhZEZpbGUoY21kT2JqLm1ldGFkYXRhLCAndXRmOCcpO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKGBSZWFkIG1ldGFkYXRhICR7Y21kT2JqLm1ldGFkYXRhfWAsIHR4dCk7XG4gICAgICAgICAgICAgICAgbWV0YWRhdGEgPSBZQU1MLnBhcnNlKHR4dCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICAvLyBjb25zb2xlLmxvZygnQWZ0ZXIgbWV0YWRhdGEnKTtcblxuICAgICAgICAgICAgbGV0IG1oT3B0aW9ucyA9IHt9O1xuICAgICAgICAgICAgaWYgKGNtZE9iai5vcHRpb25zKSB7XG4gICAgICAgICAgICAgICAgY29uc3QgdHh0ID0gYXdhaXQgZnNwLnJlYWRGaWxlKGNtZE9iai5vcHRpb25zLCAndXRmOCcpO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKGBSZWFkIG9wdGlvbnMgJHtjbWRPYmoub3B0aW9uc31gLCB0eHQpO1xuICAgICAgICAgICAgICAgIG1oT3B0aW9ucyA9IFlBTUwucGFyc2UodHh0KTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKCdBZnRlciBvcHRpb25zJyk7XG5cbiAgICAgICAgICAgIGNvbnN0IGlucHV0RmlsZSA9IGF3YWl0IGZzcC5yZWFkRmlsZShpbnB1dEZOLCAndXRmOCcpO1xuICAgICAgICAgICAgLy8gY29uc29sZS5sb2coYGlucHV0IGZpbGUgJHtpbnB1dEZpbGV9YCwgaW5wdXRGaWxlKTtcblxuICAgICAgICAgICAgY29uc3QgbWFoYWZ1bmNzID0gW107XG4gICAgICAgICAgICBmb3IgKGNvbnN0IGFycmF5Rk4gb2YgY21kT2JqLm1vZHVsZSkge1xuICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5TW9kdWxlID0gcmVxdWlyZShhcnJheUZOKTtcbiAgICAgICAgICAgICAgICAvLyBjb25zb2xlLmxvZyhgTWFoYWZ1bmNBcnJheSAke2FycmF5Rk59YCk7XG4gICAgICAgICAgICAgICAgaWYgKCFhcnJheU1vZHVsZS5tYWhhYmh1dGFBcnJheSkge1xuICAgICAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYE5vIG1haGFiaHV0YUFycmF5IGZ1bmN0aW9uIGluICR7YXJyYXlGTn1gKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgbWFoYWZ1bmNzLnB1c2goYXJyYXlNb2R1bGUubWFoYWJodXRhQXJyYXkobWhPcHRpb25zKSk7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGxldCBwYXJ0aWFsc01vZHVsZTtcbiAgICAgICAgICAgIGlmIChjbWRPYmoucGFydGlhbHMpIHtcbiAgICAgICAgICAgICAgICBwYXJ0aWFsc01vZHVsZSA9IHJlcXVpcmUoJy4uL21haGEvcGFydGlhbC5qcycpO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKHBhcnRpYWxzTW9kdWxlKTtcbiAgICAgICAgICAgICAgICBpZiAoIXBhcnRpYWxzTW9kdWxlLmNvbmZpZ3VyYXRpb24ucGFydGlhbERpcnMpIHtcbiAgICAgICAgICAgICAgICAgICAgcGFydGlhbHNNb2R1bGUuY29uZmlndXJhdGlvbi5wYXJ0aWFsRGlycyA9IFtdO1xuICAgICAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgICAgIGlmIChjbWRPYmoucGFydGlhbHNEaXIpIHtcbiAgICAgICAgICAgICAgICAgICAgZm9yIChjb25zdCBkaXJGTiBvZiBjbWRPYmoucGFydGlhbHNEaXIpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHBhcnRpYWxzTW9kdWxlLmNvbmZpZ3VyYXRpb24ucGFydGlhbERpcnMucHVzaChkaXJGTik7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgbWFoYWZ1bmNzLnB1c2gocGFydGlhbHNNb2R1bGUubWFoYWJodXRhQXJyYXkobWhPcHRpb25zKSk7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGNvbnN0IG91dHB1dCA9IGF3YWl0IG1haGFiaHV0YS5wcm9jZXNzQXN5bmMoXG4gICAgICAgICAgICAgICAgaW5wdXRGaWxlLFxuICAgICAgICAgICAgICAgIG1ldGFkYXRhLFxuICAgICAgICAgICAgICAgIG1haGFmdW5jc1xuICAgICAgICAgICAgKTtcbiAgICAgICAgICAgIGlmIChjbWRPYmoub3V0cHV0KSB7XG4gICAgICAgICAgICAgICAgYXdhaXQgZnNwLndyaXRlRmlsZShjbWRPYmoub3V0cHV0LCBvdXRwdXQsICd1dGY4Jyk7XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKCcvLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLyBPVVRQVVQnKTtcbiAgICAgICAgICAgICAgICBjb25zb2xlLmxvZyhvdXRwdXQpO1xuICAgICAgICAgICAgICAgIC8vIGNvbnNvbGUubG9nKCdcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcIE9VVFBVVCcpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9IGNhdGNoIChlKSB7XG4gICAgICAgICAgICBjb25zb2xlLmVycm9yKGBwcm9jZXNzIGNvbW1hbmQgRVJST1JFRCAke2Uuc3RhY2t9YCk7XG4gICAgICAgIH1cblxuICAgIH0pO1xuXG5wcm9ncmFtLnBhcnNlKCk7XG4iXX0=
package/maha/partial.js CHANGED
@@ -70,15 +70,14 @@ module.exports.renderPartial = async function (fname, attrs, options) {
70
70
  } else {
71
71
  partialDirs = [ __dirname ];
72
72
  }
73
- } else {
73
+ } else {
74
74
  partialDirs = options.partialDirs;
75
- }
75
+ }
76
76
 
77
77
  // console.log(`renderPartial looking for ${util.inspect(partialDirs)} ${fname}`);
78
78
  const partialFound = await lookForPartial(partialDirs, fname);
79
79
  if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
80
- // console.log(`module.exports.configuration renderPartial ${partialFound}`);
81
- if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
80
+ // console.log(`module.exports.configuration renderPartial ${util.inspect(partialFound)}`);
82
81
 
83
82
  var stats = await fs.stat(partialFound.fullpath);
84
83
  if (!stats.isFile()) {
@@ -86,8 +85,11 @@ module.exports.renderPartial = async function (fname, attrs, options) {
86
85
  }
87
86
  if (/\.ejs$/i.test(partialFound.fullpath)) {
88
87
  try {
89
- let partialText = await fs.readFile(partialFound.fullpath, 'utf8');
90
- return ejs.render(partialText, attrs);
88
+ let partialText = await fs.readFile(partialFound.fullpath, 'utf8');
89
+ // console.log(`EJS loaded partial ${fname} => ${partialText}`);
90
+ let rendered = ejs.render(partialText, attrs);
91
+ // console.log(`EJS rendered ${fname} ==> ${rendered}`);
92
+ return rendered;
91
93
  } catch (e) {
92
94
  throw new Error(`EJS rendering of ${fname} failed because of ${e}`);
93
95
  }
@@ -148,7 +150,6 @@ module.exports.configuration = {
148
150
  const partialFound = await lookForPartial(partialDirs, fname);
149
151
  if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
150
152
  // console.log(`module.exports.configuration renderPartial ${partialFound}`);
151
- if (!partialFound) throw new Error(`No partial found for ${fname} in ${util.inspect(partialDirs)}`);
152
153
 
153
154
  var partialFname = path.join(partialFound.basedir, partialFound.path);
154
155
  var stats = await fs.stat(partialFname);
package/package.json CHANGED
@@ -28,16 +28,21 @@
28
28
  },
29
29
  "main": "./dist/index.js",
30
30
  "types": "./dist/index.d.ts",
31
- "version": "0.8.2",
31
+ "bin": {
32
+ "mahabhuta": "./dist/cli.js"
33
+ },
34
+ "version": "0.8.3",
32
35
  "engines": {
33
36
  "node": ">=12.4"
34
37
  },
35
38
  "dependencies": {
36
- "cheerio": "1.0.0-rc.10",
39
+ "cheerio": "1.0.0-rc.12",
40
+ "commander": "^9.4.0",
37
41
  "ejs": "^3.1.x",
38
42
  "handlebars": "4.7.7",
39
43
  "liquidjs": "9.34.0",
40
- "nunjucks": "3.2.3"
44
+ "nunjucks": "3.2.3",
45
+ "yaml": "^2.1.1"
41
46
  },
42
47
  "devDependencies": {
43
48
  "@types/node": "17.0.13",
@@ -1,55 +0,0 @@
1
-
2
- import { Mahafunc } from "./Mahafunc";
3
- import * as util from 'util';
4
- import { logProcessing, logPerformance } from './index';
5
-
6
- /**
7
- * Implements an HTML-ish element that is replaced with
8
- * some other HTML. For example, <embed-video> might take
9
- * an href= and other attributes to describe a video from
10
- * a known service, the process function discerns the HTML code
11
- * to use for the player, rendering that into the output.
12
- */
13
- export class CustomElement extends Mahafunc {
14
-
15
- /**
16
- * The name of the element that is implemented by
17
- * this function.
18
- */
19
- get elementName(): string {
20
- throw new Error("The 'elementName' getter must be overridden");
21
- }
22
-
23
- /**
24
- * The selector for a _CustomElement_ implementation
25
- * is simply the name of the element.
26
- */
27
- get selector(): string { return this.elementName; }
28
-
29
- async process($element, metadata, setDirty: Function, done?: Function) {
30
- throw new Error("The 'process' function must be overridden");
31
- }
32
-
33
- async processAll($, metadata, setDirty: Function) {
34
- try {
35
- let elements = this.findElements($);
36
- if (elements.length <= 0) return;
37
- // Performance testing
38
- const _start = new Date();
39
-
40
- for (let element of elements) {
41
- let replaceWith = await this.process($(element), metadata, setDirty);
42
- // console.log(`CustomElement ${this.elementName} process returned ${replaceWith}`);
43
- $(element).replaceWith(replaceWith);
44
- }
45
- /* if (this.elementName === "site-verification") {
46
- console.log(`CustomElement ${this.elementName} `, $.html());
47
- } */
48
- // Performance testing
49
- logPerformance(_start, `CustomElement ${this.array.name} ${this.elementName}`);
50
- } catch (e) {
51
- console.error(`CustomElement ${this.elementName} Errored with ${util.inspect(e)}`);
52
- throw e;
53
- }
54
- }
55
- }
@@ -1,8 +0,0 @@
1
-
2
- import { Mahafunc } from "./Mahafunc"
3
-
4
- export class ElementTweaker extends Mahafunc {
5
- async process($element, metadata, setDirty: Function, done?: Function) {
6
- throw new Error("The 'process' function must be overridden")
7
- }
8
- }
package/lib/Mahafunc.ts DELETED
@@ -1,81 +0,0 @@
1
-
2
- import { MahafuncArray } from "./MahafuncArray";
3
-
4
- const _mahafunc_array = Symbol('array');
5
-
6
- /**
7
- * A superclass for implementing processor functions
8
- * for use with Mahabhuta. This class is not meant to
9
- * be instantiated directly, but to be extended. Instead
10
- * it is meant for applications to instantiate subclasses
11
- * of this class.
12
- */
13
- export class Mahafunc {
14
-
15
- /**
16
- * Store the {@link MahafuncArray} containing
17
- * this function.
18
- */
19
- set array(array: MahafuncArray) { this[_mahafunc_array] = array; }
20
-
21
- /**
22
- * Retrieve the {@link MahafuncArray} containing
23
- * this function.
24
- */
25
- get array() { return this[_mahafunc_array]; }
26
-
27
- /**
28
- * Retrieve the options/configuration object
29
- * stored in the array containing this function.
30
- */
31
- get options() { return this[_mahafunc_array].options; }
32
-
33
- /**
34
- * Retrieve the jQuery-like _selector_ associated with
35
- * a Mahafunc. When the containing {@link MahafuncArray}
36
- * determines whether to execute this function, it uses
37
- * the selector to determine if it matches any elements.
38
- *
39
- * @returns the selector to use
40
- */
41
- get selector(): string {
42
- throw new Error("The 'selector' getter must be overridden");
43
- }
44
-
45
- /**
46
- * Look for any elements matching the _selector_.
47
- *
48
- * @param $ The parsed HTML
49
- * @returns An array of elements matching the selector. If none match, the array will have zero elements.
50
- */
51
- findElements($) {
52
- var ret = [];
53
- $(this.selector).each(function(i, elem) { ret.push(elem); });
54
- return ret;
55
- }
56
-
57
- /**
58
- * Run the function against an element.
59
- *
60
- * @param $element The element to process
61
- * @param metadata The metadata object passed from the application
62
- * @param setDirty The function to call if an element inserts code requiring further processing
63
- * @param done Callback function if needed
64
- */
65
- async process($element, metadata, setDirty: Function, done?: Function) {
66
- throw new Error("The 'process' function must be overridden");
67
- }
68
-
69
- /**
70
- * Call {@link process} for every matching element.
71
- * The {@link findElements} function is meant to be
72
- * used to determine the matching elements.
73
- *
74
- * @param $ The parsed version of the HTML
75
- * @param metadata The metadata object passed from the application
76
- * @param setDirty The function to call if an element inserts code requiring further processing
77
- */
78
- async processAll($, metadata, setDirty: Function) {
79
- throw new Error("The 'processAll' function must be overridden");
80
- }
81
- }
@@ -1,254 +0,0 @@
1
-
2
- import { logProcessing, logPerformance } from './index';
3
- import { Mahafunc } from './Mahafunc';
4
- import { PageProcessor } from './PageProcessor';
5
- import { CustomElement } from './CustomElement';
6
- import { Munger } from './Munger';
7
- import * as util from 'util';
8
-
9
- export type MahafuncType = Mahafunc | MahafuncArray | Function | [];
10
-
11
- const _mahaarray_name = Symbol('name');
12
- const _mahaarray_options = Symbol('options');
13
- const _mahaarray_functions = Symbol('functions');
14
- const _mahaarray_final_functions = Symbol('final_functions');
15
-
16
- /**
17
- * Holds a series of functions ({@link Mahafunc}) that
18
- * will execute in the order they were added.
19
- */
20
- export class MahafuncArray {
21
-
22
- constructor(name: string, config: Object) {
23
- this[_mahaarray_functions] = [];
24
- this[_mahaarray_final_functions] = [];
25
- this[_mahaarray_name] = name;
26
- this[_mahaarray_options] = config;
27
- // console.log(`new MahafuncArray ${this[_mahaarray_name]} ${util.inspect(this[_mahaarray_options])}`);
28
- }
29
-
30
- /**
31
- * Retrieve the configuration object supplied
32
- * to the array.
33
- */
34
- get options() { return this[_mahaarray_options]; }
35
-
36
- /**
37
- * Retrieve the name for the array. This name is
38
- * purely for informational purposes.
39
- */
40
- get name() { return this[_mahaarray_name]; }
41
-
42
- /**
43
- * Retrieve the array of functions.
44
- */
45
- get functions() { return this[_mahaarray_functions]; }
46
-
47
- /**
48
- * Retrieve the array of _final_ functions. These are
49
- * executed after the main array is fully finished.
50
- */
51
- get final_functions() { return this[_mahaarray_final_functions]; }
52
-
53
- /**
54
- * Return the number of elements in the function array.
55
- */
56
- get length(): number { return this[_mahaarray_functions].length; }
57
-
58
- /**
59
- * Return the number of elements in
60
- * the final function array.
61
- */
62
- get length_final(): number { return this[_mahaarray_final_functions].length; }
63
-
64
- /**
65
- * Add a function to the array.
66
- *
67
- * For historical purposes we support several types
68
- * of function. It's preferable to use {@link Mahafunc}
69
- * objects, or other {@link MahafuncArray}'s. But we
70
- * also allow bare functions.
71
- *
72
- * @param func A single item of type {@link MahafuncType}
73
- * @returns To support chaining, the array is returned
74
- */
75
- addMahafunc(func: MahafuncType): MahafuncArray {
76
- if (!(func instanceof Mahafunc
77
- || func instanceof MahafuncArray
78
- || typeof func === 'function'
79
- || Array.isArray(func))) {
80
- throw new Error("Improper addition "+ util.inspect(func));
81
- } else {
82
- this.functions.push(func);
83
- if (func instanceof Mahafunc) {
84
- func.array = this;
85
- }
86
- }
87
- return this; // support chaining
88
- }
89
-
90
- /**
91
- * Replace any existing function array with a
92
- * new array of either {@link Mahafunc} or
93
- * {@link MahafuncArray} objects
94
- *
95
- * @param functions
96
- * @returns To support chaining, the array is returned
97
- */
98
- setMahafuncArray(functions: Array<Mahafunc | MahafuncArray>): MahafuncArray {
99
- if (!(Array.isArray(functions))) {
100
- throw new Error("Improper mahafunction array "+ util.inspect(functions));
101
- } else {
102
- this[_mahaarray_functions] = functions;
103
- for (let func of this[_mahaarray_functions]) {
104
- if (func instanceof Mahafunc) {
105
- func.array = this;
106
- }
107
- }
108
- }
109
- return this; // support chaining
110
- }
111
-
112
- /**
113
- * Replace any existing final function array with a
114
- * new array of either {@link Mahafunc} or
115
- * {@link MahafuncArray} objects
116
- *
117
- * @param functions
118
- * @returns To support chaining, the array is returned
119
- */
120
- setFinalMahafuncArray(final_functions: Array<Mahafunc>): MahafuncArray {
121
- if (!(Array.isArray(final_functions))) {
122
- throw new Error("Improper mahafunction array "+ util.inspect(final_functions));
123
- } else {
124
- this[_mahaarray_final_functions] = final_functions;
125
- for (let func of this[_mahaarray_final_functions]) {
126
- if (func instanceof Mahafunc) {
127
- func.array = this;
128
- }
129
- }
130
- }
131
- return this; // support chaining
132
- }
133
-
134
- /**
135
- * Add a function to the array.
136
- *
137
- * For historical purposes we support several types
138
- * of function. It's preferable to use {@link Mahafunc}
139
- * objects, or other {@link MahafuncArray}'s. But we
140
- * also allow bare functions.
141
- *
142
- * @param func A single item of type {@link MahafuncType}
143
- * @returns To support chaining, the array is returned
144
- */
145
- addFinalMahafunc(func: MahafuncType): MahafuncArray {
146
- if (!(func instanceof Mahafunc
147
- || func instanceof MahafuncArray
148
- || typeof func === 'function'
149
- || Array.isArray(func))) {
150
- throw new Error("Improper addition "+ util.inspect(func));
151
- } else {
152
- this.final_functions.push(func);
153
- if (func instanceof Mahafunc) {
154
- func.array = this;
155
- }
156
- }
157
- return this; // support chaining
158
- }
159
-
160
- /**
161
- * Execute the functions in the array.
162
- *
163
- * @param $ The parsed form of the HTML ready to use with Cheerio functions
164
- * @param metadata A metadata object supplied by the application, and passed through to functions.
165
- * @param dirty A function provided by {@link processAsync} that notifies whether a function has inserted something in the HTML which requires further processing.
166
- * @returns
167
- */
168
- async process($, metadata, dirty: Function) {
169
- logProcessing(`Mahabhuta starting array ${this.name}`);
170
- const loops = [];
171
- // const startProcessing = new Date();
172
-
173
- // Run the functions, then run the final_functions
174
- for (let funclist of [ this.functions, this.final_functions]) {
175
- for (let mahafunc of funclist) {
176
- if (mahafunc instanceof CustomElement) {
177
- logProcessing(`Mahabhuta calling CustomElement ${this.name} ${mahafunc.elementName}`);
178
- try {
179
- await mahafunc.processAll($, metadata, dirty);
180
- } catch (errCustom) {
181
- throw new Error(`Mahabhuta ${this.name} caught error in CustomElement(${mahafunc.elementName}): ${errCustom.message}`);
182
- }
183
- // loops.push(`... CustomElement ${mahafunc.elementName} ${(new Date() - startProcessing) / 1000} seconds`);
184
- } else if (mahafunc instanceof Munger) {
185
- logProcessing(`Mahabhuta calling Munger ${this.name} ${mahafunc.selector}`);
186
- try {
187
- await mahafunc.processAll($, metadata, dirty);
188
- } catch (errMunger) {
189
- throw new Error(`Mahabhuta ${this.name} caught error in Munger(${mahafunc.selector}): ${errMunger.message}`);
190
- }
191
- logProcessing(`Mahabhuta FINISHED Munger ${this.name} ${mahafunc.selector}`);
192
- // loops.push(`... Munger ${mahafunc.selector} ${(new Date() - startProcessing) / 1000} seconds`);
193
- } else if (mahafunc instanceof PageProcessor) {
194
- // Performance testing
195
- const _start = new Date();
196
- logProcessing(`Mahabhuta calling ${this.name} PageProcessor `);
197
- try {
198
- await mahafunc.process($, metadata, dirty);
199
- } catch (errPageProcessor) {
200
- throw new Error(`Mahabhuta ${this.name} caught error in PageProcessor: ${errPageProcessor.message}`);
201
- }
202
- // Performance testing
203
- logPerformance(_start, `PageProcessor ${this.name}`);
204
- // loops.push(`... PageProcessor ${(new Date() - startProcessing) / 1000} seconds`);
205
- } else if (mahafunc instanceof MahafuncArray) {
206
- // Performance testing
207
- const _start = new Date();
208
- let results = [];
209
- try {
210
- results = await mahafunc.process($, metadata, dirty);
211
- } catch (errMahafuncArray) {
212
- throw new Error(`Mahabhuta ${this.name} caught error in MahafuncArray: ${errMahafuncArray.message}`);
213
- }
214
- // Performance testing
215
- logPerformance(_start, `MahafuncArray ${this.name} ${mahafunc.name}`)
216
-
217
- // results.forEach(result => { loops.push(` ... "${mahafunc.name} result" ${result} ${(new Date() - startProcessing) / 1000} seconds`); });
218
- // loops.push(`... MahafuncArray ${mahafunc.name} ${(new Date() - startProcessing) / 1000} seconds`);
219
- } else if (typeof mahafunc === 'function') {
220
- // Performance testing
221
- const _start = new Date();
222
- logProcessing(`Mahabhuta calling an ${this.name} "function" `);
223
- try {
224
- await new Promise((resolve, reject) => {
225
- mahafunc($, metadata, dirty, err => {
226
- if (err) reject(err);
227
- else resolve('ok');
228
- });
229
- });
230
- } catch (errFunction) {
231
- throw new Error(`Mahabhuta ${this.name} caught error in function: ${errFunction.message}`);
232
- }
233
- // Performance testing
234
- logPerformance(_start, `function ${this.name}`);
235
- // loops.push(`... MahafuncArray "function" ${(new Date() - startProcessing) / 1000} seconds`);
236
- } else if (Array.isArray(mahafunc)) {
237
- // Performance testing
238
- const _start = new Date();
239
- let mhObj = new MahafuncArray("inline", this.options);
240
- mhObj.setMahafuncArray(mahafunc);
241
- let results = await mhObj.process($, metadata, dirty);
242
- // Performance testing
243
- logPerformance(_start, `Array ${this.name} inline`);
244
- // results.forEach(result => { loops.push(` ... "inline result" ${result} ${(new Date() - startProcessing) / 1000} seconds`); });
245
- // loops.push(`... MahafuncArray "inline array" ${(new Date() - startProcessing) / 1000} seconds`);
246
- } else {
247
- console.error(`BAD MAHAFUNC in array ${this.name} - ${util.inspect(mahafunc)}`);
248
- }
249
- }
250
- }
251
- // return $.html();
252
- return loops;
253
- }
254
- }
package/lib/Munger.ts DELETED
@@ -1,44 +0,0 @@
1
-
2
- import { Mahafunc } from "./Mahafunc";
3
- import * as util from 'util';
4
- import { logProcessing, logPerformance } from './index';
5
-
6
- export class Munger extends Mahafunc {
7
- get elementName(): string {
8
- return ''; // This is a default
9
- }
10
-
11
- /**
12
- * For _Munger_ classes, the `process` function has access
13
- * to the entire HTML for the page. Hence, it is passed
14
- * both `$` for the whole page, and `$element` matching
15
- * a specific element on the page.
16
- *
17
- * @param $
18
- * @param $element
19
- * @param metadata
20
- * @param setDirty
21
- * @param done
22
- */
23
- async process($, $element, metadata, setDirty: Function, done?: Function) {
24
- throw new Error("The 'process' function must be overridden")
25
- }
26
-
27
- async processAll($, metadata, setDirty: Function) {
28
- try {
29
- var elements = this.findElements($);
30
- if (elements.length <= 0) return;
31
- // Performance testing
32
- const _start = new Date();
33
- // console.log(`Munger ${this.array.name} ${this.elementName} found ${elements.length} elements`);
34
- for (let element of elements) {
35
- await this.process($, $(element), metadata, setDirty);
36
- }
37
- // Performance testing
38
- logPerformance(_start, `Munger ${this.array.name} ${this.elementName}`);
39
- } catch (e) {
40
- console.error(`Munger ${this.selector} Errored with ${util.inspect(e)}`);
41
- throw e;
42
- }
43
- }
44
- }
@@ -1,8 +0,0 @@
1
-
2
- import { Mahafunc } from "./Mahafunc"
3
-
4
- export class PageProcessor extends Mahafunc {
5
- async process($, metadata, setDirty: Function) {
6
- throw new Error("The 'process' function must be overridden")
7
- }
8
- }
package/lib/index.ts DELETED
@@ -1,203 +0,0 @@
1
- /**
2
- * Copyright 2014-2019 David Herron
3
- *
4
- * The MIT License (MIT)
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- *
24
- */
25
-
26
- 'use strict';
27
-
28
- import * as cheerio from 'cheerio';
29
- import * as util from 'util';
30
-
31
- export { Mahafunc } from './Mahafunc';
32
- export { CustomElement } from './CustomElement';
33
- export { ElementTweaker } from './ElementTweaker';
34
- export { MahafuncArray, MahafuncType } from './MahafuncArray';
35
- export { Munger } from './Munger';
36
- export { PageProcessor } from './PageProcessor';
37
-
38
- import { Mahafunc } from './Mahafunc';
39
- import { MahafuncArray, MahafuncType } from './MahafuncArray';
40
-
41
- let configCheerio;
42
- let traceFlag = false;
43
- let tracePerf = false;
44
-
45
- /**
46
- * Set the Cheerio configuration.
47
- * @param _configCheerio Object corresponding to Cheerio documentation
48
- * @see {@link https://www.npmjs.com/package/cheerio} for Cheerio documentation
49
- */
50
- export function config(_configCheerio) {
51
- configCheerio = _configCheerio;
52
- }
53
-
54
- /**
55
- * Enable or disable "processing" tracing. Controls whether `logProcessing` does anything.
56
- * @param _traceFlag
57
- */
58
- export function setTraceProcessing(_traceFlag: boolean): void {
59
- traceFlag = _traceFlag;
60
- }
61
-
62
- /**
63
- * Enable or disable "performance" tracing.
64
- * @param _traceFlag
65
- */
66
- export function setTracePerformance(_traceFlag: boolean): void {
67
- tracePerf = _traceFlag;
68
- }
69
-
70
- /**
71
- * Perform "processing" tracing, if enabled.
72
- * @param text
73
- * @returns
74
- */
75
- export function logProcessing(text: string): void {
76
- if (!traceFlag) return;
77
- console.log(text);
78
- }
79
-
80
- /**
81
- * Perform "performance" tracing, if enabled.
82
- * @param start
83
- * @param text
84
- * @returns
85
- */
86
- export function logPerformance(start: Date, text: string): void {
87
- if (!tracePerf) return;
88
- // https://stackoverflow.com/questions/14980014/how-can-i-calculate-the-time-between-2-dates-in-typescript
89
- console.log(`${text} ${(new Date().getTime() - start.getTime()) / 1000} seconds`)
90
- }
91
-
92
- /**
93
- * Parse the supplied text using Cheerio. If a Cheerio Config
94
- * has been set, it will be used.
95
- *
96
- * @param text The HTML text to parse
97
- * @returns The object returned by Cheerio
98
- */
99
- export function parse(text: string) {
100
- return configCheerio
101
- ? cheerio.load(text, configCheerio)
102
- : cheerio.load(text);
103
- };
104
-
105
- /**
106
- * Process an array of functions against HTML text. This
107
- * function supports both Promise/async and Callback execution.
108
- * It uses {@link processAsync} for the processing and it
109
- * always returns the Promise generated by that function. If
110
- * the callback function is supplied in `done`, then it is called.
111
- *
112
- * @param text The HTML text to process
113
- * @param metadata Metadata object provided by the application and passed through to functions
114
- * @param mahabhutaFuncs The array of functions
115
- * @param done Optional callback function to call when processing is finished
116
- * @returns The Promise generated from processAsync
117
- */
118
- export async function process(
119
- text: string, metadata,
120
- mahabhutaFuncs: MahafuncArray | Array<MahafuncType>,
121
- done?: Function) {
122
-
123
- let ret = processAsync(text, metadata, mahabhutaFuncs);
124
- if (done) {
125
- ret.then(html => { done(undefined, html); })
126
- .catch(err => { done(err); });
127
- }
128
- return ret;
129
- }
130
-
131
- /**
132
- * Process the text using functions supplied in the array mahabhutaFuncs.
133
- */
134
- export async function processAsync(
135
- text: string, metadata: Object,
136
- mahabhutaFuncs: MahafuncArray | Array<MahafuncType>) {
137
-
138
- if (!mahabhutaFuncs || mahabhutaFuncs.length < 0) mahabhutaFuncs = [];
139
-
140
- let cleanOrDirty = 'first-time';
141
-
142
- // console.log(`processAsync text at start ${text}`);
143
-
144
- // Allow a pre-parsed context to be passed in
145
- const $ = typeof text === 'function' ? text : parse(text);
146
-
147
- // console.log(`processAsync $ at start `, $.html());
148
-
149
- // const loops = [];
150
- do {
151
- // let startProcessing = new Date();
152
- let mhObj;
153
- if (Array.isArray(mahabhutaFuncs)) {
154
- // console.log(`ARRAY substitution`);
155
- mhObj = new MahafuncArray("master", {});
156
- mhObj.setMahafuncArray(mahabhutaFuncs);
157
- } else if (mahabhutaFuncs instanceof MahafuncArray) {
158
- // console.log(`MahafuncArray`);
159
- mhObj = mahabhutaFuncs;
160
- } else throw new Error(`Bad mahabhutaFuncs object supplied`);
161
-
162
- cleanOrDirty = 'clean';
163
- /* let results = */ await mhObj.process($, metadata, () => { cleanOrDirty = 'dirty'; });
164
-
165
- // results.forEach(result => { loops.push(mhObj.name +' '+ result); });
166
- // console.log(`MAHABHUTA processAsync ${metadata.document.path} FINISH ${(new Date() - startProcessing) / 1000} seconds ${cleanOrDirty}`);
167
- } while (cleanOrDirty === 'dirty');
168
-
169
- // loops.forEach(l => { console.log(l); });
170
-
171
- return $.html();
172
- }
173
-
174
- /**
175
- * Process one function against the supplied text.
176
- *
177
- * @param text The text to process
178
- * @param metadata Metadata object provided by the application and passed through to functions
179
- * @param mahafunc A single function, or a {@link MahafuncArray}, to execute
180
- * @param done Optional callback function to call when processing is finished
181
- * @returns The Promise generated from processAsync
182
- */
183
- export async function process1(
184
- text: string, metadata,
185
- mahafunc: MahafuncType,
186
- done?: Function) {
187
-
188
- return process(text, metadata, [ mahafunc ], done);
189
- }
190
-
191
- /**
192
- * Construct a MahafuncArray
193
- * @param name The name for the array
194
- * @param config Configuration object
195
- * @param functions An optional list of functions to add
196
- * @returns A MahafuncArray
197
- */
198
- export default function(
199
- name: string, config: Object, functions?: MahafuncType): MahafuncArray {
200
- const array = new MahafuncArray(name, config);
201
- if (functions) array.addMahafunc(functions);
202
- return array;
203
- }