/** * Type definition for the global object store that allows arbitrary string indexing. * Uses 'any' intentionally as this is a dynamic storage mechanism for cross-module state. */ export interface GlobalObjectStore { [key: string]: any; } /** * The Global Object Store is a place to store global objects that need to be shared across the application. Depending on the execution environment, this could be the window object in a browser, or the global object in a node environment, or something else in other contexts. The key here is that in some cases static variables are not truly shared * because it is possible that a given class might have copies of its code in multiple paths in a deployed application. This approach ensures that no matter how many code copies might exist, there is only one instance of the object in question by using the Global Object Store. * @returns */ export declare function GetGlobalObjectStore(): GlobalObjectStore | null; /** * This utility function will copy all scalar and array properties from an object to a new object and return the new object. * This function will NOT copy non-plain object instances (unless they implement `toJSON()` or `resolveCircularReferences` is true). * * The function respects the standard JavaScript `toJSON()` protocol: if a value exposes a `toJSON()` method * (as `Date`, `BaseInfo` subclasses, and user-defined classes can), the method is invoked and its return value * is processed in place of the original. This mirrors how `JSON.stringify()` handles serialization. * * Arrays are recursively processed — each item is copied/toJSON'd individually — so nested objects with * `toJSON()` are unwrapped to their serializable form. * * @param input - The object to copy * @param resolveCircularReferences - If true, handles circular references and complex objects for safe JSON serialization. * When enabled, circular references are replaced with '[Circular Reference]', * complex objects without `toJSON()` are replaced with their type names, * Error objects are specially handled to extract name/message/stack, * and Dates are converted to ISO strings. Default: false * @param maxDepth - Maximum recursion depth when resolveCircularReferences is true (default: 10) * @returns A new object with scalars and arrays copied */ export declare function CopyScalarsAndArrays(input: T, resolveCircularReferences?: boolean, maxDepth?: number): Partial; /** * Combines CleanJSON and SafeJSONParse to clean, extract, and parse JSON in one operation. * This is a convenience function that first cleans the input string using CleanJSON to handle * various formats (double-escaped, markdown blocks, etc.), then safely parses the result. * * @param inputString - The string to clean and parse, which may contain JSON in various formats * @param logErrors - If true, parsing errors will be logged to console (default: false) * @returns The parsed object of type T, or null if cleaning/parsing fails * * @example * // Parse double-escaped JSON * const result = CleanAndParseJSON<{name: string}>('{\\"name\\": \\"test\\"}', true); * // Returns: {name: "test"} * * @example * // Parse JSON from markdown * const data = CleanAndParseJSON<{id: number}>('```json\n{"id": 123}\n```', false); * // Returns: {id: 123} * * @example * // Parse complex AI response with type safety * interface AIResponse { * status: string; * data: any; * } * const response = CleanAndParseJSON(aiOutput, true); * // Returns typed object or null */ export declare function CleanAndParseJSON(inputString: string | null, logErrors?: boolean): T | null; /** * Cleans and extracts valid JSON from various input formats including double-escaped strings, * strings with embedded JSON, and markdown code blocks. * * This function handles multiple scenarios in the following priority order: * 1. **Valid JSON**: If the input is already valid JSON, it returns it formatted * 2. **Double-escaped JSON**: Handles strings with escaped quotes (\\") and newlines (\\n) * 3. **Markdown blocks**: Extracts JSON from ```json code blocks (only as last resort) * 4. **Mixed content**: Extracts JSON objects/arrays from strings with surrounding text * * @param inputString - The string to process, which may contain JSON in various formats * @returns A formatted JSON string if valid JSON is found, otherwise null * * @example * // Simple JSON * CleanJSON('{"name": "test"}') * // Returns: '{\n "name": "test"\n}' * * @example * // Double-escaped JSON * CleanJSON('{\\"name\\": \\"test\\", \\"value\\": 123}') * // Returns: '{\n "name": "test",\n "value": 123\n}' * * @example * // JSON with embedded markdown (preserves the markdown in string values) * CleanJSON('{"text": "```json\\n{\\"inner\\": true}\\n```"}') * // Returns: '{\n "text": "```json\\n{\\"inner\\": true}\\n```"\n}' * * @example * // Markdown block extraction (only when not valid JSON) * CleanJSON('Some text ```json\n{"extracted": true}\n``` more text') * // Returns: '{\n "extracted": true\n}' */ export declare function CleanJSON(inputString: string | null): string | null; /** * Outcome of a {@link RepairJSONEscaping} attempt. */ export interface JSONEscapingRepairResult { /** True only when the input parsed after repair. */ repaired: boolean; /** The repaired JSON text, present only when `repaired` is true. */ text?: string; /** The parsed value, present only when `repaired` is true. */ value?: any; /** Zero-based offsets that were escaped, in the order they were fixed. */ repairedOffsets: number[]; /** Why the repair stopped, when `repaired` is false. */ reason?: string; } /** * Deterministically repairs the single most common way an LLM breaks otherwise-valid JSON: * a double quote or raw control character left unescaped inside a string value. * * ## Why this exists * * Models embed rich markdown in string fields — mermaid diagrams, HTML mockups, code samples — * and reliably escape most of it. A single missed quote inside a 25KB response invalidates the * whole document. Nothing else in the repair chain recovers that: JSON5's leniency covers trailing * commas, comments and unquoted keys, but an unescaped `"` terminates a string in JSON5 exactly as * it does in JSON. The remaining fallback is an LLM round-trip on the full payload, which is slow, * costly, and itself unreliable at that size. * * ## How it works * * Purely error-driven, one character per pass: * * 1. `JSON.parse` the text and read the failure offset from the thrown error. * 2. Scan backwards from that offset for the character that ended the string early. * 3. Escape that one character. * 4. Re-parse. Repeat until it parses or a stopping condition trips. * * Every pass is validated by a real parse, so this never "pattern matches" its way to a wrong * answer the way a global regex rewrite would. It converges in one pass per offending character * (about two per quoted mermaid label) and gives up rather than guessing when it cannot make * progress. * * ## Safety * * This can, in principle, produce valid-but-wrong JSON: escaping a quote that legitimately ended a * string would merge two pieces of structure. Three properties keep that in check — it only runs * after a parse has already failed (so a correct document is never touched), it only ever *adds* * escapes and never deletes or reorders content, and it reports every offset it changed so callers * can log, audit, or schema-check the result before trusting it. Callers holding an expected shape * should validate against it; a wrong guess almost always fails shape validation. * * @param inputString - Raw model output, expected to be a JSON envelope * @param maxRepairs - Maximum characters to escape before giving up * @returns The repair outcome; `repaired` is false when the input could not be recovered * * @example * // A mermaid relationship label whose quotes were not escaped * RepairJSONEscaping('{"doc":"```mermaid\\nerDiagram\\n A ||--o{ B : "has items"\\n```"}') * // => { repaired: true, repairedOffsets: [...], value: { doc: '...' } } */ export declare function RepairJSONEscaping(inputString: string | null, maxRepairs?: number): JSONEscapingRepairResult; /** * This function takes in a string that may contain JavaScript code in a markdown code block and returns the JavaScript code without the code block. * @param javaScriptCode * @returns */ export declare function CleanJavaScript(javaScriptCode: string): string; /** * Simple wrapper method to JSON.parse that catches any errors and optionally logs them to the console. * This method is useful when you want to parse JSON but don't want to crash the application if the JSON is invalid. * * @param jsonString - The JSON string to parse * @param logErrors - If true, parsing errors will be logged to console (default: false) * @returns The parsed object of type T (default: any), or null if parsing fails or input is empty * * @example * // Basic usage without type * const data = SafeJSONParse('{"name": "test"}'); * * @example * // With type parameter * interface User { name: string; age: number; } * const user = SafeJSONParse('{"name": "John", "age": 30}', true); * * @example * // Invalid JSON returns null * const result = SafeJSONParse('invalid json', true); // logs error, returns null */ export declare function SafeJSONParse(jsonString: string, logErrors?: boolean): T | null; /** * This function takes in a string of text(assuming markdown, or just newline formatted), and converts it to an HTML list. The list type can be either ordered or unordered. * @param htmlListType * @param text * @returns */ export declare function ConvertMarkdownStringToHtmlList(htmlListType: 'Ordered' | 'Unordered', text: string): string | null; /** * Configuration options for entity and field name normalization. * These control how ALL CAPS database identifiers are converted to human-readable names. */ export interface EntityNamingOptions { /** Normalize ALL CAPS names to Title Case (e.g., PAYMENT -> Payment). Default: true */ normalizeAllCaps?: boolean; /** Attempt to split compound ALL CAPS words using dictionary matching (e.g., INDIVIDUALDESIGNATION -> Individual Designation). Default: true */ splitCompoundWords?: boolean; /** Additional domain-specific words for the compound word splitter */ additionalDomainWords?: string[]; } /** * Creates a human-readable display name from a database identifier. Handles: * - snake_case: "organization_email" -> "Organization Email" * - PascalCase/camelCase: "OrganizationEmail" -> "Organization Email" * - ALL CAPS: "PAYMENT" -> "Payment" (when normalizeAllCaps is true) * - ALL CAPS compound: "INDIVIDUALDESIGNATION" -> "Individual Designation" (when splitCompoundWords is true) * * Snake_case identifiers are split on underscores and title-cased first, then fed through * the existing camelCase logic to handle mixed conventions like "org_emailAddress" -> "Org Email Address". * * @param s - The database identifier to convert * @param options - Optional naming configuration. When omitted, ALL CAPS normalization and compound splitting are enabled by default. */ export declare function createDisplayName(s: string, options?: EntityNamingOptions): string; /** * Converts a string that uses camel casing or contains consecutive uppercase letters to have spaces between words. * For example: * "DatabaseVersion" -> "Database Version" * "AIAgentLearningCycle" -> "AI Agent Learning Cycle" */ export declare function convertCamelCaseToHaveSpaces(s: string): string; /** * Removes all whitespace characters (spaces, tabs, newlines) from a given string. * * @param s - The input string from which to remove whitespace. * @returns A new string with all whitespace characters removed. * * @example * ```typescript * stripWhitespace(" Hello World "); // "HelloWorld" * stripWhitespace("\tExample\nString "); // "ExampleString" * stripWhitespace(""); // "" * ``` */ export declare function stripWhitespace(s: string): string; /** * Retrieves the plural form of a word if it is an irregular plural. * * @param singularName - The singular form of the word to check. * @returns The irregular plural form if found, or `null` if not found. * * @example * ```typescript * getIrregularPlural('child'); // returns 'children' * getIrregularPlural('dog'); // returns null * ``` */ export declare function getIrregularPlural(singularName: string): string | null; /** * Converts a singular word to its plural form, handling common pluralization rules * and irregular plurals. * * @param singularName - The singular form of the word to pluralize. * @returns The plural form of the word. * * @example * ```typescript * generatePluralName('child'); // returns 'children' * generatePluralName('box'); // returns 'boxes' * generatePluralName('party'); // returns 'parties' * generatePluralName('dog'); // returns 'dogs' * ``` */ export declare function generatePluralName(singularName: string, options?: { capitalizeFirstLetterOnly?: boolean; capitalizeEntireWord?: boolean; }): string; /** * Utility method that will adjust the casing of a word based on the options provided. The options object can have two properties: * * capitalizeFirstLetterOnly: If true, only the first letter of the word will be capitalized, and the rest will be lower case. * * capitalizeEntireWord: If true, the entire word will be capitalized. * @param word * @param options * @returns */ export declare function adjustCasing(word: string, options?: { capitalizeFirstLetterOnly?: boolean; capitalizeEntireWord?: boolean; forceRestOfWordLowerCase?: boolean; }): string; /** * Removes trailing characters from a string if they match the specified substring. * * @param s - The input string from which trailing characters should be stripped. * @param charsToStrip - The substring to remove if it appears at the end of the input string. * @param skipIfExactMatch - If `true`, does not strip the trailing characters when the string is exactly equal to `charsToStrip`. * @returns The modified string with trailing characters stripped, or the original string if no match is found. * * @example * ```typescript * stripTrailingChars("example.txt", ".txt", false); // "example" * stripTrailingChars("example.txt", ".txt", true); // "example" * stripTrailingChars("file.txt", "txt", false); // "file.txt" (no match) * stripTrailingChars(".txt", ".txt", true); // ".txt" (exact match, not stripped) * ``` */ export declare function stripTrailingChars(s: string, charsToStrip: string, skipIfExactMatch: boolean): string; /** * Recursively removes all spaces from a given string. * * @param s - The input string from which to remove all spaces. * @returns A new string with all spaces removed. * * @example * ```typescript * replaceAllSpaces("Hello World"); // "HelloWorld" * replaceAllSpaces(" Leading spaces"); // "Leadingspaces" * replaceAllSpaces("Trailing spaces "); // "Trailingspaces" * replaceAllSpaces("NoSpacesHere"); // "NoSpacesHere" * replaceAllSpaces(""); // "" * ``` */ export declare function replaceAllSpaces(s: string): string; /** * Generates a version 4 UUID (Universally Unique Identifier) using the uuid library. * @returns the generated UUID as a string. */ export declare function uuidv4(): string; /** * Compares two strings line by line and logs the differences to the console. * This function is useful for debugging purposes to identify discrepancies between two text inputs. * It will print the total number of lines in each string, and for each line that differs, * it will log the line number, the content of each line, and the first character difference * along with its position and character codes. * @param str1 * @param str2 * @returns An array of strings representing the differences found between the two input strings. If array is empty, it means no differences were found. */ export declare function compareStringsByLine(str1: string, str2: string, logToConsole?: boolean): string[]; /** * Options for the ParseJSONRecursive function */ export interface ParseJSONOptions { /** Maximum recursion depth to prevent infinite loops (default: 100) */ maxDepth?: number; /** If true, extracts embedded JSON from strings and places it in a separate key with '_' suffix (default: false) */ extractInlineJson?: boolean; /** If true, enables debug logging to console (default: false) */ debug?: boolean; } /** * Recursively parse JSON strings within an object/array structure. * This function will traverse through objects and arrays, attempting to parse * any string values as JSON. If parsing succeeds, it continues recursively. * This is particularly useful for handling deeply nested JSON structures * where JSON is stored as strings within other JSON objects. * * The function makes no assumptions about property names - it will attempt * to parse any string value it encounters, regardless of the key name. * * @param obj The object to process * @param options Configuration options for parsing * @returns The object with all JSON strings parsed * * @example * const input = { * data: '{"nested": "{\\"deeply\\": \\"nested\\"}"}', * payload: '{"foo": "bar"}', * someOtherProp: '["a", "b", "c"]' * }; * const output = ParseJSONRecursive(input); * // Returns: { * // data: { nested: { deeply: "nested" } }, * // payload: { foo: "bar" }, * // someOtherProp: ["a", "b", "c"] * // } * * @example with options * const input = { * content: 'Action results:\n[{"action": "test"}]' * }; * const output = ParseJSONRecursive(input, { extractInlineJson: true, maxDepth: 50 }); * // Returns: { * // content: "Action results:", * // content_: [{ action: "test" }] * // } */ export declare function ParseJSONRecursive(obj: any, options?: ParseJSONOptions): any; /** * Escape HTML entities in a string to prevent Cross-Site Scripting (XSS) attacks. * This is particularly important when rendering un-sanitized user input via mechanisms * like Angular's `[innerHTML]`. * * @param text - The string to escape. * @returns The escaped HTML string. */ export declare function EscapeHTML(text: string): string; /** * The format a piece of text appears to be authored in, as classified by * {@link detectRichTextFormat}. */ export type RichTextFormat = 'markdown' | 'html' | 'plain'; /** Default number of leading characters {@link detectRichTextFormat} inspects. */ export declare const DEFAULT_RICH_TEXT_SCAN_LENGTH = 500; /** * Lightweight, dependency-free detection of the likely format of a string — Markdown, HTML, * or plain text. Useful for deciding how to render free-text content (e.g. a long entity * field) without requiring callers to declare the format up front. * * The detection is intentionally **conservative**: it requires reasonably strong signals * before classifying content as Markdown or HTML, so ordinary prose (which may contain the * odd `<` or `*`) stays `'plain'`. Markdown is treated as the safe **superset** — content * showing Markdown signals is classified `'markdown'` even when it also contains inline HTML, * because Markdown renderers handle embedded HTML. * * Only the leading `maxScanLength` characters are inspected — format signals, when present, * appear early, so a small window keeps the regex work cheap on large values and slower * machines. If nothing matches within that window, the content is assumed `'plain'`. * * NOTE: this classifies; it does NOT sanitize. Anything rendered as HTML must still be passed * through an HTML sanitizer (e.g. Angular's `[innerHTML]` binding, which sanitizes in HTML * context) before being injected into the DOM. * * @param value - The text to classify (null/undefined/blank → `'plain'`). * @param maxScanLength - Leading characters to inspect. Defaults to {@link DEFAULT_RICH_TEXT_SCAN_LENGTH} (500). * @returns `'markdown'`, `'html'`, or `'plain'`. */ export declare function detectRichTextFormat(value: string | null | undefined, maxScanLength?: number): RichTextFormat; /** * Build an HTML-safe string with every case-insensitive occurrence of `query` inside * `text` wrapped in the supplied `` tag. Designed for search-result UIs whose * output is bound to Angular's `[innerHTML]` (or any equivalent that trusts raw HTML). * * SECURITY: The result IS raw HTML. Each text segment (before / match / after) is * HTML-escaped *individually* before concatenation. Callers must pass plain text, * not pre-escaped HTML — escaping the input up-front would corrupt entity codes * when the search term overlaps an entity (e.g. searching "amp" inside `&`) * and is the exact failure mode this helper is built to prevent. * * Behavior notes: * - Case-insensitive match; original casing of `text` is preserved in the output. * - All occurrences are highlighted (matches the behavior of a `/.../gi` regex). * - `query` is treated as a literal string — no regex semantics, so search terms * like `.` or `$10` work as users expect. * - Empty/falsy `query` returns `EscapeHTML(text)` so the result is always * `[innerHTML]`-safe. * * @param text - The plain text to search and render. * @param query - The substring to highlight (literal match, case-insensitive). * @param markClass - Optional CSS class to apply to the `` element. * @returns An HTML string safe for `[innerHTML]` binding. */ export declare function HighlightSearchMatches(text: string, query: string, markClass?: string): string; /** * Checks if two dates differ only by a timezone-like shift. * Returns true if the difference is EXACTLY a whole number of hours * (no variance in minutes/seconds/milliseconds) and within 23 hours. * This helps detect timezone interpretation issues with datetime/datetime2 fields * that don't store timezone information. * * @param date1 - The first date to compare * @param date2 - The second date to compare * @returns true if the dates differ only by a whole-hour timezone shift (1-23 hours) * * @example * // 6-hour timezone shift - returns true * IsOnlyTimezoneShift(new Date('2025-12-25T10:30:45.123Z'), new Date('2025-12-25T16:30:45.123Z')); * * @example * // Different by 1ms - returns false (real change) * IsOnlyTimezoneShift(new Date('2025-12-25T10:30:45.123Z'), new Date('2025-12-25T16:30:45.124Z')); */ export declare function IsOnlyTimezoneShift(date1: Date, date2: Date): boolean; /** * Epoch milliseconds for a value that may be a Date, an ISO/parseable string, a numeric * timestamp, or absent. Returns 0 for null/undefined/unparseable input so it is safe to use * directly in a sort comparator. * * Framework date fields such as `__mj_CreatedAt` are typed as `Date` but can hold a raw string * at runtime when rows arrive from a serialized source (cache payloads, wire JSON) rather than * through BaseEntity's coercing accessors. Optional chaining does not protect a `.getTime()` * call in that case — `"…"?.getTime` is `undefined`, and calling it throws. */ export declare function ToEpochMs(value: Date | string | number | null | undefined): number; //# sourceMappingURL=util.d.ts.map