interpolate-json
Advanced tools
Comparing version 0.3.1 to 0.4.2
@@ -1,4 +0,1 @@ | ||
/** | ||
* interpolate-json: Interpolate a Javascript (Node.js V8) Object or string with json - Advanced | ||
*/ | ||
module.exports = require('./lib/main'); | ||
module.exports=require("./lib/main"); |
@@ -1,36 +0,1 @@ | ||
'use strict'; | ||
class CustomException extends Error { | ||
constructor(message) { | ||
this[Symbol.toStringTag] = 'Exception'; | ||
super(message || this.defaultMessage); | ||
} | ||
} | ||
class NotImplementedException extends CustomException { | ||
constructor(message) { | ||
this.defaultMessage = 'This functionality is not implemented yet.'; | ||
super(message); | ||
} | ||
} | ||
class InvalidInitialization extends CustomException { | ||
constructor(message) { | ||
this.defaultMessage = 'This initialization process is invalid.'; | ||
super(message); | ||
} | ||
} | ||
class BadRequest extends CustomException { | ||
constructor(message) { | ||
this.defaultMessage = 'This request has bad parameters.'; | ||
super(message); | ||
} | ||
} | ||
module.exports = { | ||
CustomException: CustomException, | ||
NotImplementedException: NotImplementedException, | ||
InvalidInitialization: InvalidInitialization, | ||
BadRequest: BadRequest | ||
}; | ||
"use strict";class CustomException extends Error{constructor(t){this[Symbol.toStringTag]="Exception",super(t||this.defaultMessage)}}class NotImplementedException extends CustomException{constructor(t){this.defaultMessage="This functionality is not implemented yet.",super(t)}}class InvalidInitialization extends CustomException{constructor(t){this.defaultMessage="This initialization process is invalid.",super(t)}}class BadRequest extends CustomException{constructor(t){this.defaultMessage="This request has bad parameters.",super(t)}}module.exports={CustomException,NotImplementedException,InvalidInitialization,BadRequest}; |
157
lib/main.js
@@ -1,156 +0,1 @@ | ||
const extend = require('extend'); | ||
const type = require('type-detect'); | ||
const { NotImplementedException, BadRequest } = require('./exceptions'); | ||
const regexEscaped = /[\\/|#<>{}()[\]^$+*?.-\:\!]/g; | ||
const escapeRegex = str => | ||
type(str) === 'string' ? str.replace(regexEscaped, '\\$&') : str; | ||
const main = () => { | ||
let defaultOptions = { | ||
debug: false, | ||
prefix: '${', | ||
suffix: '}', | ||
subKeyPointer: '.' | ||
}; | ||
const getParamRegex = opt => { | ||
return new RegExp( | ||
escapeRegex(opt.prefix.trim()) + | ||
'([\\s]*[\\w]+(?:' + | ||
escapeRegex(opt.subKeyPointer.trim()) + | ||
'[\\w]+)*[\\s]*)' + | ||
escapeRegex(opt.suffix.trim()), | ||
'g' | ||
); | ||
}; | ||
const backupOptions = { ...defaultOptions }; | ||
const log = message => { | ||
if (defaultOptions.debug) console.log(`[dotconfig][debug]: ${message}`); | ||
}; | ||
const trace = message => { | ||
if (defaultOptions.debug) console.trace(`[dotconfig][error]: ${message}`); | ||
}; | ||
const traceNThrow = (errMessage, ErrorHandler) => { | ||
trace(errMessage); | ||
if (type(ErrorHandler) === 'Exception') throw new ErrorHandler(errMessage); | ||
else throw new Error(errMessage); | ||
}; | ||
const traverse = (obj, path, subKeyPointer) => { | ||
let result = path | ||
.split(subKeyPointer) | ||
.reduce((parent, key) => parent[key] || {}, obj); | ||
return type(result) === 'number' || type(result) === 'string' ? result : ''; | ||
}; | ||
const getMatchSet = (matches, paramRegex) => | ||
new Set( | ||
matches.reduce((arr, match) => { | ||
arr.push(match.replace(paramRegex, (m, val) => val.trim())); | ||
return arr; | ||
}, []) | ||
); | ||
const getInterpolated = (str, regex, values, keepAlive = false) => { | ||
log(`Found match: ${str.match(regex)}`); | ||
return str.replace(regex, (match, param) => { | ||
param = param.trim(); | ||
return values.hasOwnProperty(param) | ||
? values[param].toString() | ||
: keepAlive | ||
? match | ||
: ''; | ||
}); | ||
}; | ||
const flattenAndResolve = (obj, matchSet, paramRegex, subKeyPointer) => { | ||
let cache = {}; | ||
matchSet.forEach(match => { | ||
// Step 1: Get current value | ||
let curVal = traverse(obj, match, subKeyPointer); | ||
// Step 2: Is it clean | ||
if (paramRegex.test(curVal)) { | ||
// Step 2.2: Try to clean it with existing state of cache | ||
curVal = getInterpolated(curVal, paramRegex, cache, true); | ||
} | ||
// Step 3: Is it clean after Step 2 check & cleanup | ||
if (paramRegex.test(curVal)) { | ||
// Step 3.2: If not, it's time to update cache with missing matchSet | ||
extend( | ||
cache, | ||
flattenAndResolve( | ||
obj, | ||
getMatchSet(curVal.match(paramRegex), paramRegex), | ||
paramRegex, | ||
subKeyPointer | ||
) | ||
); | ||
// Step 3.3: cache updated with missing matchSet. Clear to interpolate | ||
cache[match] = getInterpolated(curVal, paramRegex, cache); | ||
} else cache[match] = curVal; // Step 3(alt): cache updated | ||
}); | ||
return cache; | ||
}; | ||
const interpolation = { | ||
[Symbol.toStringTag]: 'Interpolate-Json', | ||
do: (obj, values = null, options = {}) => { | ||
let needToDo = false; | ||
let objType = type(obj); | ||
if (options.prefix && !options.suffix) options.suffix = ''; | ||
options = extend({}, defaultOptions, options); | ||
const paramRegex = getParamRegex(options); | ||
switch (objType) { | ||
case 'Object': | ||
let cachedValue = extend({}, obj, values || {}); | ||
obj = JSON.stringify(obj); | ||
if (paramRegex.test(obj)) { | ||
let matches = obj.match(paramRegex); | ||
values = flattenAndResolve( | ||
cachedValue, | ||
getMatchSet(matches, paramRegex), | ||
paramRegex, | ||
options.subKeyPointer | ||
); | ||
needToDo = true; | ||
} | ||
break; | ||
case 'string': | ||
log(`Input: "${obj}"`); | ||
if (paramRegex.test(obj)) needToDo = true; | ||
else break; | ||
if (null === values) { | ||
traceNThrow('Please provide "values"', BadRequest); | ||
} | ||
break; | ||
default: | ||
trace(`Interpolation for ${objType} has not yet been implemented`); | ||
return obj; | ||
} | ||
const result = needToDo ? getInterpolated(obj, paramRegex, values) : obj; | ||
switch (objType) { | ||
case 'Object': | ||
return JSON.parse(result); | ||
case 'string': | ||
default: | ||
return result; | ||
} | ||
}, | ||
debug: () => { | ||
defaultOptions.debug = true; | ||
}, | ||
reset: () => { | ||
defaultOptions = { ...backupOptions }; | ||
} | ||
}; | ||
return interpolation; | ||
}; | ||
module.exports = main(); | ||
"use strict";const extend=require("extend"),type=require("type-detect"),{BadRequest}=require("./exceptions"),regexEscaped=/[\\/|#<>{}()[\]^$+*?.-\:\!]/g,escapeRegex=e=>"string"===type(e)?e.replace(regexEscaped,"\\$&"):e,main=()=>{let e={debug:!1,prefix:"${",suffix:"}",subKeyPointer:"."};const t={...e},log=t=>{e.debug&&console.log(`[dotconfig][debug]: ${t}`)},trace=t=>{e.debug&&console.trace(`[dotconfig][error]: ${t}`)},getMatchSet=(e,t)=>new Set(e.reduce((e,r)=>(e.push(r.replace(t,(e,t)=>t.trim())),e),[])),getInterpolated=(e,t,r,s=!1)=>(log(`Found match: ${e.match(t)}`),e.replace(t,(e,t)=>(t=t.trim(),r.hasOwnProperty(t)?r[t].toString():s?e:""))),flattenAndResolve=(e,t,r,s)=>{let n={};return t.forEach(t=>{let i=((e,t,r)=>{let s=t.split(r).reduce((e,t)=>e[t]||{},e);return"number"===type(s)||"string"===type(s)?s:""})(e,t,s);r.test(i)&&(i=getInterpolated(i,r,n,!0)),r.test(i)?(extend(n,flattenAndResolve(e,getMatchSet(i.match(r),r),r,s)),n[t]=getInterpolated(i,r,n)):n[t]=i}),n};return{[Symbol.toStringTag]:"Interpolate-Json",do:(t,r=null,s={})=>{let n=!1,i=type(t);s.prefix&&!s.suffix&&(s.suffix=""),s=extend({},e,s);const a=(u=s,new RegExp(escapeRegex(u.prefix.trim())+"([\\s]*[\\w]+(?:"+escapeRegex(u.subKeyPointer.trim())+"[\\w]+)*[\\s]*)"+escapeRegex(u.suffix.trim()),"g"));var u;switch(i){case"Object":let e=extend({},t,r||{});if(t=JSON.stringify(t),a.test(t)){let i=t.match(a);r=flattenAndResolve(e,getMatchSet(i,a),a,s.subKeyPointer),n=!0}break;case"string":if(log(`Input: "${t}"`),!a.test(t))break;n=!0,null===r&&((e,t)=>{throw trace(e),"Exception"===type(t)?new t(e):new Error(e)})('Please provide "values"',BadRequest);break;default:return trace(`Interpolation for ${i} has not yet been implemented`),t}const c=n?getInterpolated(t,a,r):t;switch(i){case"Object":return JSON.parse(c);case"string":default:return c}},debug:()=>{e.debug=!0},reset:()=>{e={...t}}}};module.exports=main(); |
{ | ||
"name": "interpolate-json", | ||
"version": "0.3.1", | ||
"version": "0.4.2", | ||
"description": "Interpolate a Javascript (Node.js V8) Object or string with json - Advanced", | ||
@@ -30,2 +30,5 @@ "main": "index.js", | ||
"homepage": "https://github.com/Terran-Source/interpolate-json#readme", | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"contributors": [ | ||
@@ -46,4 +49,8 @@ { | ||
"chai": "^4.2.0", | ||
"mocha": "^6.2.2" | ||
"del": "^5.1.0", | ||
"gulp": "^4.0.2", | ||
"gulp-terser": "^1.2.0", | ||
"mocha": "^6.2.2", | ||
"readable-stream": "^3.4.0" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Empty package
Supply chain riskPackage does not contain any code. It may be removed, is name squatting, or the result of a faulty package publish.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5084
6
0
2
1