gulp-template (lodash) falls over with javascript templating - gulp

I am running a gulp script with gulp-template to inject values into my javascript files.
e.g.
angular
.module("<%= module %>", [
"ngRoute",
"ui.bootstrap",
"ui.select"
]);
This works fine for all the files except if I have javascript templating in the file
e.g.
function controller() {
var vm = this;
vm.getMessage = getMessage;
//------------------------------------------
function getMessage() {
if (!vm.validator)
return "";
var message = vm.validator.getMessage(vm.property);
if (message === "")
return "";
return ` *${message}`;
}
}
I then get the following error
events.js:167
throw er; // Unhandled 'error' event
^
ReferenceError: message is not defined
at eval (lodash.templateSources[10]:9:10)
at DestroyableTransform._transform (C:\andre\sourcecode\pmslogic\buildassets\node_modules\gulp-template\index.js:23:41)
at DestroyableTransform.Transform._read (C:\andre\sourcecode\pmslogic\buildassets\node_modules\through2\node_modules\readable-stre
am\lib\_stream_transform.js:184:10)
at DestroyableTransform.Transform._write (C:\andre\sourcecode\pmslogic\buildassets\node_modules\through2\node_modules\readable-str
eam\lib\_stream_transform.js:172:83)
at doWrite ([my path]node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:42
8:64)
at writeOrBuffer ([my path]node_modules\through2\node_modules\readable-stream\lib\_stream_writable
.js:417:5)
at DestroyableTransform.Writable.write ([my path]node_modules\through2\node_modules\readable-strea
m\lib\_stream_writable.js:334:11)
at write ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:623:
24)
at flow ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:632:7
)
at DestroyableTransform.pipeOnReadable ([my path]node_modules\vinyl-fs\node_modules\readable-strea
m\lib\_stream_readable.js:664:5)
Emitted 'error' event at:
at DestroyableTransform.onerror ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_
stream_readable.js:558:12)
at DestroyableTransform.emit (events.js:182:13)
at DestroyableTransform._transform ([my path]node_modules\gulp-template\index.js:26:9)
at DestroyableTransform.Transform._read ([my path]node_modules\through2\node_modules\readable-stre
am\lib\_stream_transform.js:184:10)
[... lines matching original stack trace ...]
at flow ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:632:7
)
I suspect I can solve this by passing lodash template parameters into the gulp-template call, but am stumped as to what these are.
var gulp = require("gulp");
var concat = require("gulp-concat");
var template = require('gulp-template');
...
var cfg = ????
return gulp
.src(src)
.pipe(template({ module: "test-module-name" }, cfg))
.pipe(concat(`${module}.js`))
.pipe(gulp.dest(dest));
};

Related

semantic error TS2574: A rest element type must be an array type

Here is the code src/object.ts(50,58)
interface sanitizer<T> {
(val: T): T
}
type MapSanitizor<T extends any[]> = T extends [infer P, ...(infer R)]
? [sanitizer<P>, ...MapSanitizor<R>]
: [];
function isArrayAs<T extends any[]>(fn: MapSanitizor<T>): sanitizer<T> {
return function(val) {
if (!Array.isArray(val))
throw new Error(`
obj val \n
= ${JSON.stringify(val)} \n
is invalid value,\n
value passed in isArrayAs is not an array
`);
const newlist: T = [] as any;
for (let i = 0; i < fn.length; i++) {
newlist.push((fn[i] as any)(val[i]));
}
return newlist;
};
}
I am trying to build my package
it given me this error when i run npm run build
Error: D:/packages/npm/sanitize-json/src/object.ts(50,58): semantic error TS2574: A rest element type must be an array type.
at error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:5400:30)
at throwPluginError (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:11878:12)
at Object.error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:12912:24)
at Object.error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:12081:38)
at RollupContext.error (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:17237:30)
at D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:25033:23
at arrayEach (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:545:11)
at Function.forEach (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:9397:14)
at printDiagnostics (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:25006:12)
at Object.transform (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:29277:17)
what have i done wrong? i dont see any error popup in vscode compiler.

How to add huge number of elements from array to MySQL using Sequleize in Node.js

This is the operation going on in my method
if (result) {
const csvdata = result.body;
var csvarray = csvdata.split('\n') //array details are shown below
for (var i = 1; i <= length; i++) {
const eachdata = csvarray[i];
var symbolarray = eachdata.split(",");
const obj = {
"instrument_token": symbolarray[0],
"exchange_token": symbolarray[1],
"tradingsymbol": symbolarray[2],
"name": symbolarray[3],
"last_price": symbolarray[4],
"expiry": symbolarray[5],
"strike": symbolarray[6],
"tick_size": symbolarray[7],
"lot_size": symbolarray[8],
"instrument_type": symbolarray[9],
"segment": symbolarray[10],
"exchange": symbolarray[11]
}
db.symboltable.create(obj)
.then((response) => {
console.log("added to symbol table")
})
.catch((err) => {
console.log(err)
})
}
csvarray contains elements like :
[
"267556358,1045142,EURINR20AUGFUT,\"EURINR\",0,2020-08-27,0,0.0025,1,FUT,BCD-FUT,BCD",
"268660998,1049457,EURINR20DECFUT,\"EURINR\",0,2020-12-29,0,0.0025,1,FUT,BCD-FUT,BCD",
"266440966,1040785,EURINR20JULFUT,\"EURINR\",0,2020-07-29,0,0.0025,1,FUT,BCD-FUT,BCD",
"266073606,1039350,EURINR20JUNFUT,\"EURINR\",0,2020-06-26,0,0.0025,1,FUT,BCD-FUT,BCD",
]
it contains thousands of similar elements and when the methods calls, i am getting an error like :
D:\MEAN\node projects\Trade\controllers\apicontroller.js:135
var symbolarray = eachdata.split(",");
^
TypeError: Cannot read property 'split' of undefined
at Request._callback (D:\MEAN\node projects\Trade\controllers\apicontroller.js:135:48)
at Request.self.callback (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:268:12)
at Request.emit (events.js:311:20)
at Request.<anonymous> (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:1489:10)
at Request.emit (events.js:311:20)
at IncomingMessage.<anonymous> (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:1360:12)
at Object.onceWrapper (events.js:417:28)
at IncomingMessage.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
[nodemon] app crashed - waiting for file changes before starting...
can anyone get me out from this issue

webpack : is there a good hook / custom function to dump out resolved configuration?

I'm somewhat of a newbie with webpack and have been experimenting with easier ways to adjust/merge webpack configurations.
The following code, added to webpack/lib/webpack.js has been pretty helpful:
this is the standard webpack.js:
function webpack(options, callback) {
var compiler;
if(Array.isArray(options)) {
compiler = new MultiCompiler(options.map(function(options) {
return webpack(options);
}));
} else if(typeof options === "object") {
new WebpackOptionsDefaulter().process(options);
compiler = new Compiler();
compiler.options = options;
compiler.options = new WebpackOptionsApply().process(options, compiler);
new NodeEnvironmentPlugin().apply(compiler);
compiler.applyPlugins("environment");
compiler.applyPlugins("after-environment");
} else {
throw new Error("Invalid argument: options");
}
if(callback) {
if(typeof callback !== "function") throw new Error("Invalid argument: callback");
if(options.watch === true || (Array.isArray(options) &&
options.some(function(o) {
return o.watch;
}))) {
var watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
// TODO remove this in next major version
var watchDelay = (!Array.isArray(options) ? options : options[0]).watchDelay;
if(watchDelay) {
console.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
watchOptions.aggregateTimeout = watchDelay;
}
return compiler.watch(watchOptions, callback);
}
compiler.run(callback);
}
this is my code:
//customization start
fs = require('fs');
var fnp_dump = 'webpack.dump.json';
fs.writeFile(fnp_dump, JSON.stringify(options, null, 2), function(err) {
if(err) {
return console.log(err);
}
console.log("dumping dump.webpack.js.final.json from webpack.js to: " + fnp_dump);
});
//customization end
return compiler;
}
The basic idea is that it dumps out the final json/js options object after webpack has finished sorting out the usual webpack.base.js + webpack.development.js. Since it's, at that point, just a fully-resolved javascript object, it doesn't really matter how the config.js files were written by individual developers.
Now you can diff options sent to webpack (this is an example of tranforming webpack 1 to webpack 2 configurations:
diff 003/webpack.dump.json 004/webpack.dump.json
< "loader": "style!css!postcss-loader!sass"
---
> "use": [
> {
> "loader": "style-loader"
> },
> {
> "loader": "postcss-loader"
> },
> {
> "loader": "sass-loader"
> }
> ]
However, I am customizing webpack.js directly and need to re-apply my patch after each npm update webpack. Is there a better way?
If your webpack.config.js is a function, you can call it on your own to resolve to an object.
If you have several configs (you mentioned webpack.base.js and webpack.development.js) you can use Webpack Merge to just combine your options to a single object, and then write it to the file system.
I would recommend you to have an own script in package.json to do this job, which you can then always call after your webpack job:
...,
"scripts": {
"dump-options": "scriptThatMergesConfigsAndWritesToFS.js",
"webpack-job": "webpack ... && npm run dump-options",
...
},
...
UPDATE
After some more research I realized, that the resolved options object is stored in the compiler object. The compiler object is passed to Plugins, and therefore you can easily write a Plugin that writes the config to a file, as I did here (not tested).
I also realized, that the Plugins cannot be stringified, as they are functions, so be aware of losing the Plugin configuration information.
I ended up writing my own plugin (and now notice that wtho wrote one too). It worked for me - note you need to have the bit of code that handles circular references:
// WebPackCompilationObserver.js
function WebPackCompilationObserver(options) {
WebPackCompilationObserver.options = options || {};
}
WebPackCompilationObserver.prototype.apply = function(compiler) {
compiler.plugin("emit", function(compilation, callback) {
var fs = require('fs');
var fnp_dump = WebPackCompilationObserver.options.dump_filename;
if (! fnp_dump) {
fnp_dump = "./dump.webpack.options.json";
console.log("please specify dump_filename path in the WebPackCompilationObserver.options, otherwise using default:" % fnp_dump);
}
if (fnp_dump){
console.log("dumping compilation.options to: " + fnp_dump);
var cache = [];
fs.writeFile(fnp_dump, JSON.stringify(compilation.options, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
}, 2),
function(err) {
if (err) {
return console.log(err);
}
});
cache = null;
}
callback();
});
};
module.exports = WebPackCompilationObserver;
To use it:
webpack.config.development.js:
....
var WebPackCompilationObserver = require("./WebPackCompilationObserver");
....
config.plugins = config.plugins.concat([
....
,new WebPackCompilationObserver({dump_filename: '../dumpithere.json'})
])

npm start failure. $JSON.stringify.apply is not a function

I'm trying to run a react app but running into issues.
This is the error trace.
ERROR in Template execution failed: TypeError: $JSON.stringify.apply is not a function
ERROR in TypeError: $JSON.stringify.apply is not a function
- json-output-template.js:96 stringify
/CoD/src/origin-cms/origin-ui/ui.reactapps/src/json-output-template.js:96:26
- json-output-template.js:126 module.exports
/CoD/src/origin-cms/origin-ui/ui.reactapps/src/json-output-template.js:126:36
- index.js:265
[ui.reactapps]/[html-webpack-plugin]/index.js:265:16
- util.js:16 tryCatcher
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/util.js:16:23
- promise.js:512 Promise._settlePromiseFromHandler
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:512:31
- promise.js:569 Promise._settlePromise
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:569:18
- promise.js:606 Promise._settlePromiseCtx
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:606:10
- async.js:138 Async._drainQueue
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:138:12
- async.js:143 Async._drainQueues
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:143:10
- async.js:17 Immediate.Async.drainQueues
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:17:14
The template its trying to execute is
module.exports = function (templateParams) {
var obj = {};
obj.js = (templateParams.htmlWebpackPlugin.options.globalJs || []).concat( templateParams.htmlWebpackPlugin.files.js );
obj.css = templateParams.htmlWebpackPlugin.files.css;
return JSON.stringify(obj);
};
Application version's that I'm using
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ node --version
v7.8.0
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ npm --version
4.2.0
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ yarn --version
0.21.3
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ nvm --version
0.33.1
I've tried reinstalling node, yarn, cleared application caches, etc - all to no avail.
It all looks fine when I console the parameters from the template js:
module.exports = function (templateParams) {
var obj = {};
obj.js = (templateParams.htmlWebpackPlugin.options.globalJs || []).concat( templateParams.htmlWebpackPlugin.files.js );
obj.css = templateParams.htmlWebpackPlugin.files.css;
console.log("Object: ", obj);
console.log("JSON: ", JSON);
console.log("JSON.stringify: ", JSON.stringify);
return JSON.stringify(obj);
};
Console:
Object: { js:
[ '/etc/react-apps-chunks/b43f1ef1ef32e943333a.login-modal.js',
'/etc/react-apps-chunks/bb104a33ab4b80479b28.compare-plans.js' ],
css: [ '/etc/react-apps-chunks/ef77cfb892b9199adc95.login-modal.styles.css' ] }
JSON: {}
JSON.stringify: function stringify(it) {
// eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
}
Object: { js:
[ '/etc/react-apps-chunks/react.js',
'/etc/react-apps-chunks/react-dom.js',
'/etc/react-apps-chunks/8c3d64978772b4558f5b.originReactAemIntegrator.js' ],
css: [] }
JSON: {}
JSON.stringify: function stringify(it) {
// eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
}
Any idea if I'm missing something here?

Graniteds - ejb.Tide - Identity.hasRole() function - invalid arguments

I have this block of actionscript code which is executed when a login is appempted. I an trying to reload a set of roles for a the user. I've added a result handler to the hasRole() method
[Observer("loginAttempted")]
public function loginAttempted():void {
identity.isLoggedIn(isLoggedInResult);
trace(identity.loggedIn+" "+identity.username);
var perms:Array = Permission.constants;
var i:int
trace("Load permissions");
for(i=0;i<perms.length;i++)
{
var p:Permission = perms[i];
var res = identity.hasRole(p.name,permissionResult);
if(res == true)
{
p.allowed = res;
}
trace(i+" "+p.name +" "+p.allowed+" "+res);
}
}
private function permissionResult(event:TideResultEvent):void {
trace("permissionResult "+event.result);
}
but i keep getting this error. Based on the graniteds docs the function should only take a single argument.
[Fault] exception, information=ArgumentError: Error #1063:
Argument count mismatch on Main/permissionResult(). Expected 1, got 2.
at TideRoleResponder/result()[C:\workspace\graniteds\as3\framework\org\granite\tide\ejb\Identity.as:201]
at org.granite.tide::Tide/result()[C:\workspace\graniteds\as3\framework\org\granite\tide\Tide.as:1831]
at org.granite.tide.rpc::ComponentResponder/result()[C:\workspace\graniteds\as3\framework\org\granite\tide\rpc\ComponentResponder.as:65]
at mx.rpc::AsyncToken/http://www.adobe.com/2006/flex/mx/internal::applyResult()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\AsyncToken.as:199]
at mx.rpc.events::ResultEvent/http://www.adobe.com/2006/flex/mx/internal::callTokenResponders()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\events\ResultEvent.as:172]
at mx.rpc::AbstractOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\AbstractOperation.as:199]
at org.granite.tide.rpc::TideOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[C:\workspace\graniteds\as3\framework\org\granite\tide\rpc\TideOperation.as:73]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:263]
at mx.rpc::Responder/result()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:46]
at mx.rpc::AsyncRequest/acknowledge()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:74]
at NetConnectionMessageResponder/resultHandler()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:524]
at mx.messaging::MessageResponder/result()[C:\autobuild\3.5.0\frameworks\projects\rpc\src\mx\messaging\MessageResponder.as:199]
We are using the ifAnyGranted function on the identity to do something similar, and our result handler has 2 arguments: the TideResultEvent, and a String containing the role. Try changing the signature of the permissionResult function to:
private function permissionResult(event:TideResultEvent, role:String):void