@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
57 lines (56 loc) • 2.25 kB
JavaScript
//#region src/utils/stringifyYaml.ts
const NEEDS_QUOTING = /[\n\r\t#:{}[\],&*?|<>=!%@`'"\\]|^[-?!]|\s$|^\s|^[>|]|^[.]{2,}/;
const PRESERVED_LITERALS = new Set([
"true",
"false",
"null",
"undefined",
"yes",
"no",
"on",
"off",
"NaN",
"Infinity",
"-Infinity"
]);
const serializeString = (value, indent) => {
if (value.includes("\n")) return `|\n${value.split("\n").map((l) => `${indent} ${l}`).join("\n")}`;
if (NEEDS_QUOTING.test(value) || PRESERVED_LITERALS.has(value) || /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value)) return JSON.stringify(value);
return value;
};
const serializeValue = (value, indent) => {
if (value === null || value === void 0) return "null";
if (typeof value === "boolean" || typeof value === "number") return String(value);
if (typeof value === "string") return serializeString(value, indent);
if (Array.isArray(value)) {
if (value.length === 0) return "[]";
return value.map((item) => {
const serialized = serializeValue(item, `${indent} `);
if (typeof item === "object" && item !== null && !Array.isArray(item) && !serialized.startsWith("'") && !serialized.startsWith("\"")) {
const lines = serialized.split("\n");
return `${indent}- ${lines[0]}\n${lines.slice(1).map((l) => `${indent} ${l}`).join("\n")}`.trimEnd();
}
return `${indent}- ${serialized}`;
}).join("\n");
}
if (typeof value === "object") {
const entries = Object.entries(value).filter(([, v]) => v !== void 0);
if (entries.length === 0) return "{}";
return entries.map(([k, value]) => {
const key = /[\s:{}[\]]/.test(k) ? JSON.stringify(k) : k;
const childIndent = `${indent} `;
if (value === null || value === void 0) return `${indent}${key}: null`;
if (typeof value === "object" && !Array.isArray(value)) return `${indent}${key}:\n${serializeValue(value, childIndent)}`;
if (Array.isArray(value)) {
if (value.length === 0) return `${indent}${key}: []`;
return `${indent}${key}:\n${serializeValue(value, childIndent)}`;
}
return `${indent}${key}: ${serializeValue(value, indent)}`;
}).join("\n");
}
return String(value);
};
const stringifyYaml = (value) => `${serializeValue(value, "")}\n`;
//#endregion
export { stringifyYaml };
//# sourceMappingURL=stringifyYaml.mjs.map