route-sage-react
Version:
A TypeScript utility for managing and configuring routes with type safety and nested route support
69 lines (68 loc) • 2.86 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectToJsString = objectToJsString;
exports.escapeRegExp = escapeRegExp;
/**
* Recursively converts a JavaScript object (including functions) into a string
* Recursively converts a JavaScript object into a string representation,
* handling the generation of the `url` function literal.
*
* @param {any} obj The object to convert.
* @param {number} indentLevel The current indentation level.
* @returns {string} The string representation of the object.
*/
function objectToJsString(obj, indentLevel = 0) {
const indent = " ".repeat(indentLevel);
const nextIndent = " ".repeat(indentLevel + 1);
if (typeof obj === "string") {
return `'${obj
.replace(/\\/g, "\\\\")
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n")}'`;
}
if (typeof obj === "number" || typeof obj === "boolean" || obj === null) {
return String(obj);
}
if (Array.isArray(obj)) {
if (obj.length === 0)
return "[]";
const elements = obj.map((item) => `${nextIndent}${objectToJsString(item, indentLevel + 1)}`);
return `[\n${elements.join(",\n")}\n${indent}]`;
}
if (typeof obj === "object" && obj !== null) {
if (Object.keys(obj).length === 0)
return "{}";
const properties = [];
for (const key in obj) {
const value = obj[key];
const keyString = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)
? key
: `'${key}'`;
// --- CRITICAL CHANGE HERE ---
// If the key is 'tempUrlString', generate the 'url' function literal.
if (key === "tempUrlString") {
console.log("value", { value, type: typeof value });
// The 'url' property will be a function literal that returns the value of tempUrlString
properties.push(`${nextIndent}url: () => \`${value}\``);
properties.push(`${nextIndent}tempUrlString: () => \`${value}\``);
}
else {
// Otherwise, process as a regular property
properties.push(`${nextIndent}${keyString}: ${objectToJsString(value, indentLevel + 1)}`);
}
}
return `{\n${properties.join(",\n")}\n${indent}}`;
}
return String(obj);
}
/**
* Escapes special characters in a string to be used in a regex pattern.
* @param {string} string The string to escape.
* @returns {string} The escaped string.
*/
function escapeRegExp(string) {
// Regex that matches any character that is special in regex syntax
// The characters are: ., *, +, ?, ^, $, {, }, (, ), |, [, ], \
// Note: Inside a character set, `]` and `\` must be escaped.
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}