UNPKG

@netlify/content-engine

Version:
93 lines 3.11 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sanitizeNode = void 0; const lodash_foreach_1 = __importDefault(require("lodash.foreach")); const lodash_isplainobject_1 = __importDefault(require("lodash.isplainobject")); const lodash_pickby_1 = __importDefault(require("lodash.pickby")); /** * @param {Object|Array} data * @returns {Object|Array} data without undefined values */ const omitUndefined = (data) => { const isPlain = (0, lodash_isplainobject_1.default)(data); if (isPlain) { return (0, lodash_pickby_1.default)(data, (p) => p !== undefined); } return data.filter((p) => p !== undefined); }; /** * @param {*} data * @return {boolean} Boolean if type is supported */ const isTypeSupported = (data) => { if (data === null) { return true; } const type = typeof data; const isSupported = type === `number` || type === `string` || type === `boolean` || data instanceof Date; return isSupported; }; /** * Make data serializable * @param {(Object|Array)} data to sanitize * @param {boolean} isNode = true * @param {Set<string>} path = new Set */ const sanitizeNode = (data, isNode = true, path = new Set()) => { const isPlain = (0, lodash_isplainobject_1.default)(data); const isArray = Array.isArray(data); if (isPlain || isArray) { if (path.has(data)) return data; path.add(data); const returnData = isPlain ? {} : []; let anyFieldChanged = false; // _.each is a "Collection" method and thus objects with "length" property are iterated as arrays const hasLengthProperty = isPlain ? Object.prototype.hasOwnProperty.call(data, `length`) : false; let lengthProperty; if (hasLengthProperty) { lengthProperty = data.length; delete data.length; } (0, lodash_foreach_1.default)(data, (value, key) => { if (isNode && key === `internal`) { returnData[key] = value; return; } returnData[key] = (0, exports.sanitizeNode)(value, false, path); if (returnData[key] !== value) { anyFieldChanged = true; } }); if (hasLengthProperty) { data.length = lengthProperty; returnData.length = (0, exports.sanitizeNode)(lengthProperty, false, path); if (returnData.length !== lengthProperty) { anyFieldChanged = true; } } if (anyFieldChanged) { data = omitUndefined(returnData); } // arrays and plain objects are supported - no need to to sanitize return data; } if (!isTypeSupported(data)) { return undefined; } else { return data; } }; exports.sanitizeNode = sanitizeNode; //# sourceMappingURL=sanitize-node.js.map