diff --git a/lib/json-dry.js b/lib/json-dry.js index f69bbc9..79b4b4a 100644 --- a/lib/json-dry.js +++ b/lib/json-dry.js @@ -9,6 +9,18 @@ var special_char = '~', undriers = {}, driers = {}; +let global_this; + +if (typeof globalThis != 'undefined') { + global_this = globalThis; +} else if (typeof window != 'undefined') { + global_this = window; +} else if (typeof global != 'undefined') { + global_this = global; +} else { + global_this = {}; +} + /** * Generate a replacer function * @@ -822,13 +834,18 @@ function regenerateArray(root, holder, current, seen, retrieve, undry_paths, old * * @author Jelle De Loecker * @since 0.1.4 - * @version 1.0.11 + * @version 1.1.1 * * @return {Object} */ function regenerateObject(root, holder, current, seen, retrieve, undry_paths, old, current_path) { - var path, + // Do not regenerate the global object + if (current === global_this) { + return current; + } + + let path, temp, key; @@ -848,7 +865,14 @@ function regenerateObject(root, holder, current, seen, retrieve, undry_paths, ol // it's not needed to assign it again, so it won't throw an error, // but it's not an ideal solution. if (temp !== current[key]) { - current[key] = temp; + + if (current[key] && current[key] instanceof String) { + // String object instances are path/references, + // so we can just overwrite it with the regenerated result + current[key] = temp; + } else { + throw new Error('Failed to regenerate "' + key + '"'); + } } } } @@ -892,6 +916,8 @@ function regenerate(root, holder, current, seen, retrieve, undry_paths, old, cur new_error.code = err.code; new_error.stack = message + err.stack; new_error.is_dry_error = true; + new_error.root = root; + new_error.holder = holder; throw new_error; }