npm.io
1.5.1 • Published 6 months ago

nx-helpers

Licence
ISC
Version
1.5.1
Deps
6
Size
126 kB
Vulns
1
Weekly
0

nx-helpers

A collection of high-performance utility functions for deep-merging and object manipulation, specifically designed for Nx Intelligence projects.

Installation

npm install nx-helpers

Features

mergeNoRedundancy<T>(base: T, override: Partial<T>): T

Deep-merges a base object with an override object with the following rules:

  • Plain Objects: Merged recursively.
  • Arrays: Merged as a UNION (deduplicated) using deep equality comparison.
  • Primitives/Other: The override value always wins.
Example
import { mergeNoRedundancy } from 'nx-helpers';

const base = {
  id: 1,
  tags: ["typescript", "nx"],
  metadata: {
    version: "1.0.0",
    active: true
  }
};

const override = {
  tags: ["nx", "ai"],
  metadata: {
    active: false
  }
};

const result = mergeNoRedundancy(base, override);

console.log(result);
/*
{
  id: 1,
  tags: ["typescript", "nx", "ai"],
  metadata: {
    version: "1.0.0",
    active: false
  }
}
*/
loadJson<T>(filePath: string): T

Loads and parses a JSON file synchronously. Supports both relative and absolute paths.

Example
import { loadJson } from 'nx-helpers';

const config = loadJson('./config.json');
console.log(config.name);
mergeMultiple<T>(...objects: Partial<T>[]): T

Merges multiple objects sequentially. Later objects have higher priority.

const result = mergeMultiple(obj1, obj2, obj3);
mergeWithRoles(items: MergableItem[]): any

Wraps values in objects keyed by their camelCased role and merges them. Useful for combining different data sources into a single structured object.

const items = [
  { role: 'user info', value: { name: 'John' } },
  { role: 'tags', value: ['a', 'b'] }
];
const result = mergeWithRoles(items);
// { userInfo: { name: 'John' }, tags: ['a', 'b'] }
anyToMarkdownString(input: unknown, opts?: AnyToMarkdownOptions): string

The primary high-level helper for converting any value into a clean Markdown string. It handles strings, primitives, objects, and arrays with built-in error handling and fallback mechanisms.

  • Strings: Returned as-is.
  • Primitives: Converted to strings.
  • Objects/Arrays: Converted via json2mdWithTables.
  • Fallback: If conversion fails, it defaults to a prettified JSON.stringify.
import { anyToMarkdownString } from 'nx-helpers';

const data = {
  title: "Project Alpha",
  metadata: { version: 1, tags: ["ai", "nx"] }
};

console.log(anyToMarkdownString(data, { level: 1 }));
/*
# Title
Project Alpha

# Metadata
## Version
1

## Tags
ai, nx
*/
json2mdWithTables(json: any, level?: number): string

Recursive JSON-to-Markdown converter that:

  • Title Cases all keys and headings.
  • Converts Arrays of Objects into clean Markdown tables.
  • Converts Arrays of Primitives into bulleted lists.
  • Maintains Hierarchy by automatically incrementing heading levels (H1, H2, etc.).
json2table(rows: any[], columns?: string[]): string

Converts an array of objects to a Markdown table, with headers automatically transformed to Title Case. It uses json-to-markdown-table if available, with a robust fallback.

String Helpers

toCamelCase(input: string): string

Converts strings to camelCase format. Handles spaces, dashes, and underscores.

toCamelCase("hello-world"); // "helloWorld"
toCamelCase("User Name");   // "userName"
fromCamelToTitle(camelCase: string): string

Converts camelCase strings to readable Title Case.

fromCamelToTitle("helloWorld"); // "Hello World"
toTitleCase(input: string): string

Converts any string (kebab-case, snake_case, camelCase) to Title Case.

toTitleCase("hello-world"); // "Hello World"
toTitleCase("user_profile"); // "User Profile"

Advanced String Matching (matcher.tunable.ts)

The package includes a powerful, tunable fuzzy string matcher designed for mapping ambiguous input (like LLM outputs or human typing) to strict schema keys.

Core Functions
  • scoreStrings(a, b, cfg): Computes a similarity score (0..1) using a weighted blend of metrics (Jaro-Winkler, Dice, Levenshtein, Jaccard Tokens, Fast-Fuzzy).
  • bestMatchOneToMany(term, candidates, cfg, kind): Finds the single best match above a threshold.
  • bestMatchManyToMany(listA, listB, cfg, options): Performs optimal unique assignment between two sets of strings.
Tunable Configuration

You can customize the matcher behavior via the MatcherConfig:

const cfg = defaultMatcherConfig();
cfg.weights.jaroWinkler = 0.4; // give more weight to Jaro-Winkler
cfg.thresholds.titleToKey = 0.65; // tighten the requirement for matching
Calibration

Once you have ground-truth examples, you can auto-tune the weights:

const examples = [
  { a: "Max Tokens", b: "maxTokens", label: 1, kind: "titleToKey" },
  { a: "Temp", b: "maxTokens", label: 0, kind: "titleToKey" },
];
const { bestConfig } = calibrateMatcher(examples, defaultConfig);
// Use bestConfig for your production matching
Alias Auto-Learning

Propose new aliases by mining successful historical mappings:

const mappings = [ { from: "ipaddr", to: "ip" }, { from: "IP Address", to: "ip" } ];
const { proposedAliases } = learnAliasesFromMappings(mappings, cfg);
// proposedAliases = { ip: ["ipaddr", "ip address"] }

JSON Transformation & Schema Validation (transformers.ts)

The JSONTransformer uses the tunable matcher to "fix" messy/ambiguous JSON data to match a target schema.

Schema Definitions
import { string, number, boolean, array, object } from 'nx-helpers';

const schema = object({
  fullName: string,
  profile: object({
    age: number,
    tags: array(string)
  })
});
Capabilities
  • Fuzzy Key Matching: Maps Name -> fullName, Tags -> tags.
  • Type Casting: Converts "30" to 30, "true" to true, "a,b,c" to ["a","b","c"].
  • Structural Cleanup:
    • Wraps single values in arrays: "ai" -> ["ai"].
    • Converts strings to objects: "msg" -> { message: "msg" } (if schema has 1 property).
    • Recover nested keys from root: { age: 30 } -> { profile: { age: 30 } }.
const transformer = new JSONTransformer(schema);
const { status, result } = transformer.transform({
  "Name": "Alice",
  "age": "25",
  "tags": "dev,ts"
});

// result = { fullName: "Alice", profile: { age: 25, tags: ["dev", "ts"] } }
// status = "fixed"

Running Examples

You can see all these features in action by running the included examples via tsx:

npx tsx src/verify.ts

Development & Verification

To verify the library logic and run transformation examples:

npx tsx src/verify.ts

License

ISC

Keywords