Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
wsf to vbs conversion split into a new package for ease of use.
  • Loading branch information
pravynandas committed Nov 29, 2024
1 parent c4069e3 commit 8e37955
Show file tree
Hide file tree
Showing 6 changed files with 952 additions and 85 deletions.
136 changes: 133 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,133 @@
node_modules
.npmrc
package-lock.json
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Ignore any test outputs
test_out*
12 changes: 3 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,7 @@ parseWSFStr(xml).then((jobs2)=>{
```


Finally, to extract vbscript components (both inline & src reference content) into a string, call below method passing the parsed wsf json.
### Alternatives

```js
const {parseWSF, extractVBS} = require('wsf2json');

let wsfPath = __dirname + '/test.wsf';
let wsfJson = await parseWSF(wsfPath);
let vbs = extractVBS(wsfJson);
console.log('\r\nextracted vbs from wsf file')
```
## Convert wsf to formatted vbs file
Instead of generating a json file, if the use case is to convert wsf file to a well formatted vbs file, then please use npm package [wsf2vbs](https://www.npmjs.com/package/wsf2vbs?activeTab=readme). Note current project is a dependency of the said wsf2vbs package.
98 changes: 41 additions & 57 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
const fs = require('fs'),
path = require('path'),
async = require('async-waterfall'),
parseString = require('xml2js').parseString;

// To import relative paths from the src tags in wsf file,
// we need to know the base director of the wsf file
let _baseDir = '';
let debug = false;

String.prototype.htmlEscape = function htmlEscape(str) {
//Ampersand & &
Expand All @@ -24,30 +29,29 @@ String.prototype.htmlEscape = function htmlEscape(str) {
// .replace(/\</g, CHAR_LT);
};

const beingTaskFileVerification = (path) => function(done) {
if (!fs.existsSync(path))
return done(`File [${path}] not found.`)
let wsf = fs.readFileSync(path).toString();
const beingTaskFileVerification = (_path) => function(done) {
if (!fs.existsSync(_path))
return done(`File [${_path}] not found.`)
let wsf = fs.readFileSync(_path).toString();
if (!wsf)
return done(`File [${path}] is empty.`)
return done(`File [${_path}] is empty.`)
done(null, wsf)
};

const beginTaskWSFStrVerification = (wsf) => function(done) {
if (!wsf)
return done(`File [${path}] is empty.`)
return done(`empty wsf string.`)
done(null, wsf)
}

const taskPrintWSFtoConsole = function(wsf, done) {
console.log(wsf)
if (debug) console.log(wsf)
return done(null, wsf);
}

const taskParseWsfToXML = function(wsf, done) {
wsf = wsf.htmlEscape();
// console.log('wsf', wsf);
parseString(wsf, function (err, json) {
parseString(wsf, {normalize: false} ,function (err, json) {
if (err)
return done(err)
if (!json)
Expand All @@ -57,7 +61,7 @@ const taskParseWsfToXML = function(wsf, done) {
};

const taskPrintJSONtoConsole = function(json, done) {
console.log(JSON.stringify(json, null, 2))
if (debug) console.log(JSON.stringify(json, null, 2))
return done(null, json);
}

Expand Down Expand Up @@ -88,12 +92,12 @@ const taskReturn = (resolve) => function(jobs, done) {
}

const callback = (reject) => function(error) {
console.log("An error occurred while parsing the wsf file")
if (debug) console.log("An error occurred while parsing the wsf file")
console.error(error);
reject(error);
}

const extractJobTag = function(job, debug=false) {
const extractJobTag = function(job) {
let { $: {id}, runtime, script } = job;

let jobId = '';
Expand Down Expand Up @@ -128,18 +132,24 @@ const extractJobTag = function(job, debug=false) {
//src file present
obj['type'] = 'src';
obj['src'] = src;
if (fs.existsSync(src)) {
// normalize path sepeartors on posix
src = src.replace('\\', path.sep)
let _path = path.join(_baseDir, src);
if (debug) console.log("Checking src file exists at path: " + _path);
if (fs.existsSync(_path)) {
if (debug) console.log("File found");
obj['exists'] = true;
obj['value'] = fs.readFileSync(src).toString();
obj['value'] = fs.readFileSync(_path).toString();
} else {
if (debug) console.log("File NOT found");
obj['exists'] = false;
}
arr.push(obj);
}
if (_) {
//inline script present
inline = _.split("\r\n").reduce((arr, line)=>{
arr.push(line.trim())
arr.push(line)
return arr;
}, []);
obj['type'] = 'inline';
Expand All @@ -149,7 +159,6 @@ const extractJobTag = function(job, debug=false) {
return arr;
}, [])
}
if(debug) console.log(`jobScript`, JSON.stringify(jobScript, null, 2));

return {
id: jobId,
Expand All @@ -158,63 +167,38 @@ const extractJobTag = function(job, debug=false) {
}
}

const extractVBS = (jobs) => jobs.reduce((vbs, job)=>{
let { id, script, runtime } = job;
if (id) {
vbs += `\r\n\r\n\r\n' ================================== Job: ${id} ================================== \r\n`
}
if (script) {
vbs += script.reduce((s, scr)=>{
let {type, src, exists, language, value} = scr;
if (type) {
s += `\r\n' ================= ${type}`
if (type === 'src') {
s += ` : ${src}`
}
s += ` ================= \r\n`
}
if (language.toLowerCase() === "vbscript" && value) {
s += value;
}
return s;
}, '');
}
//Inject arguments usage
if (runtime) {
let usage = runtime.reduce((str, param)=>{
let {name, helpstring} = param;
str += `Wscript.Echo "/${name}: ${helpstring}"\r\n`;
return str;
},'');
vbs = vbs.replace('WScript.Arguments.ShowUsage', usage);
}
return vbs;
},'');

async function parseWSF(path = '', debug=false) {
async function parseWSF(_path = '', _debug=false) {
debug = _debug;
return new Promise((resolve, reject)=>{
if (debug) console.log('parsing WSF from file at path:' + _path);
_baseDir = path.parse(_path).dir;
if (debug) console.log("parseWSF()-> base directory: " + _baseDir);
let tasks = [];
tasks.push(beingTaskFileVerification(path));
if (debug) tasks.push(taskPrintWSFtoConsole);
tasks.push(beingTaskFileVerification(_path));
tasks.push(taskPrintWSFtoConsole);
tasks.push(taskParseWsfToXML);
if (debug) tasks.push(taskPrintJSONtoConsole);
tasks.push(taskPrintJSONtoConsole);
tasks.push(taskVerifyRootTags);
tasks.push(taskReturn(resolve));
async(tasks, callback(reject));
})
}

async function parseWSFStr(wsf = '', debug=false) {
async function parseWSFStr(wsf = '', baseDir = '', _debug=false) {
debug = _debug;
return new Promise((resolve, reject)=>{
if (debug) console.log('parsing WSF from string...')
_baseDir = baseDir ? baseDir : __dirname;
if (debug ) console.log("parseWSFStr()-> base directory: " + _baseDir)
let tasks = [];
tasks.push(beginTaskWSFStrVerification(wsf));
if (debug) tasks.push(taskPrintWSFtoConsole);
tasks.push(taskPrintWSFtoConsole);
tasks.push(taskParseWsfToXML);
if (debug) tasks.push(taskPrintJSONtoConsole);
tasks.push(taskPrintJSONtoConsole);
tasks.push(taskVerifyRootTags);
tasks.push(taskReturn(resolve));
async(tasks, callback(reject));
})
}

module.exports = { parseWSF, parseWSFStr, extractVBS }
module.exports = { parseWSF, parseWSFStr }
Loading

0 comments on commit 8e37955

Please sign in to comment.