code: function __toJSONSafe(obj, replacer) {
    if (obj !== Object(obj)) return obj; // primitive value
    if (obj._$visited) return undefined;
    replacer = replacer || __safeReplacer;
    if (obj.toJSON) {
      var newObj = obj.toJSON();
      if (newObj !== Object(newObj)) return newObj; // primitive value
      if (newObj !== obj) return __toJSONSafe(newObj, replacer);
      // toJSON returned the object unchanged.
      obj = newObj;
    }
    obj._$visited = true;
    var result;
    if (obj instanceof Array) {
      result = obj.map(function (o) {
        return __toJSONSafe(o, replacer);
      });
    } else if (typeof (obj) === "function") {
      result = undefined;
    } else {
      result = {};
      for (var prop in obj) {
        if (prop === "_$visited") continue;
        var val = obj[prop];
        if (replacer) {
          val = replacer(prop, val);
          if (val === undefined) continue;
        }
        val = __toJSONSafe(val, replacer);
        if (val === undefined) continue;
        result[prop] = val;
      }
    }
    delete obj._$visited;
    return result;
  }
docs: safely perform toJSON logic on objects with cycles.