> Part of the walkerOS documentation. Project overview and full index: <https://www.walkeros.io/llms.txt>

# Core utilities

Core utilities are a collection of platform-agnostic functions that can be used across all walkerOS environments. They provide standardized building blocks for data manipulation, validation, mapping, and more.

## Installation[​](#installation "Direct link to Installation")

Import the core utilities directly from the `@walkeros/core` package:

```typescript
import { assign, anonymizeIP, getMappingValue } from '@walkeros/core';
```

## Data manipulation[​](#data-manipulation "Direct link to Data manipulation")

### assign[​](#assign "Direct link to assign")

`assign<T, U>(target: T, source: U, options?): T & U` merges two objects with advanced merging capabilities. It has special behavior for arrays: when merging, it concatenates arrays from both objects, removing duplicates.

```typescript
interface AssignOptions {
merge?: boolean; // Merge array properties (default: true)
shallow?: boolean; // Create shallow copy (default: true)
extend?: boolean; // Extend with new properties (default: true)
}

const obj1 = { a: 1, b: [1, 2] };
const obj2 = { b: [2, 3], c: 3 };

assign(obj1, obj2); // Returns { a: 1, b: [1, 2, 3], c: 3 }
assign(obj1, obj2, { merge: false }); // Returns { a: 1, b: [2, 3], c: 3 }
```

### Path operations[​](#path-operations "Direct link to Path operations")

#### getByPath[​](#getbypath "Direct link to getByPath")

`getByPath(object: unknown, path: string, defaultValue?: unknown): unknown` accesses nested properties using dot notation. Supports wildcard `*` for array iteration.

```javascript
getByPath({ data: { id: 'wow' } }, 'data.id'); // Returns "wow"
getByPath({ nested: [1, 2, { id: 'cool' }] }, 'nested.*.id'); // Returns ['', '', 'cool']
getByPath({ arr: ['foo', 'bar'] }, 'arr.1'); // Returns "bar"
```

#### setByPath[​](#setbypath "Direct link to setByPath")

`setByPath(object: WalkerOS.Event, path: string, value: unknown): WalkerOS.Event` sets nested values using dot notation, returning a new object with the updated value.

```javascript
const updatedEvent = setByPath(event, 'data.id', 'new-value');
// Returns a new event with data.id set to 'new-value'
```

### clone[​](#clone "Direct link to clone")

`clone<T>(original: T): T` creates a deep copy of objects/arrays with circular reference handling.

```javascript
const original = { foo: true, arr: ['a', 'b'] };
const cloned = clone(original);
original.foo = false; // cloned.foo remains true
```

### castValue[​](#castvalue "Direct link to castValue")

`castValue(value: unknown): WalkerOS.PropertyType` converts string values to appropriate types (number, boolean).

```javascript
castValue('123'); // Returns 123 (number)
castValue('true'); // Returns true (boolean)
castValue('hello'); // Returns 'hello' (unchanged)
```

## Privacy and security[​](#privacy-and-security "Direct link to Privacy and security")

### anonymizeIP[​](#anonymizeip "Direct link to anonymizeIP")

`anonymizeIP(ip: string): string` anonymizes IPv4 addresses by setting the last octet to zero.

```javascript
anonymizeIP('192.168.1.100'); // Returns '192.168.1.0'
```

### Hashing[​](#hashing "Direct link to Hashing")

`getId(length?: number, charset?: string): string` generates random identifier strings. Defaults to a 6-character alphanumeric id; pass `charset` to restrict the allowed characters.

```javascript
getId(); // Returns random 6-char string like 'a1b2c3'
getId(10); // Returns 10-character alphanumeric string
getId(5, 'abcdefghijklmnopqrstuvwxyz'); // Lowercase letters only
```

## Event processing[​](#event-processing "Direct link to Event processing")

### getMappingValue[​](#getmappingvalue "Direct link to getMappingValue")

`getMappingValue(event: WalkerOS.Event, mapping: Mapping.Data, context: Mapping.ValueContext): Promise<WalkerOS.Property | undefined>` extracts values from events using

[mapping configurations](/preview/pr-749/docs/mapping.md). The context requires the running `collector`: inside a step, take it from the step's context; elsewhere, use the one `startFlow` returns.

```typescript
import { startFlow } from '@walkeros/collector';
import { getMappingValue } from '@walkeros/core';

const { collector } = await startFlow();
const event = {
  name: 'order complete',
  data: { id: '0rd3r1d' },
  nested: [
    { entity: 'product', data: { id: 'ers', name: 'Everyday Ruck Snack' } },
    { entity: 'gift', data: { name: 'Surprise' } },
  ],
};

// Simple path mapping
await getMappingValue(event, 'data.id', { collector }); // '0rd3r1d'

// Complex mapping with conditions and loops
const mapping = {
  map: {
    orderId: 'data.id',
    products: {
      loop: [
        'nested',
        {
          condition: (entity) => entity.entity === 'product',
          map: { id: 'data.id', name: 'data.name' },
        },
      ],
    },
  },
};
await getMappingValue(event, mapping, { collector });
// { orderId: '0rd3r1d', products: [{ id: 'ers', name: 'Everyday Ruck Snack' }] }
```

### getMappingEvent[​](#getmappingevent "Direct link to getMappingEvent")

`getMappingEvent(event: WalkerOS.PartialEvent, mapping?: Mapping.Rules): Promise<Mapping.Result>` finds the appropriate mapping rule for an event.

## Marketing and analytics[​](#marketing-and-analytics "Direct link to Marketing and analytics")

### getMarketingParameters[​](#getmarketingparameters "Direct link to getMarketingParameters")

`getMarketingParameters(url: URL, custom?: MarketingParameters): WalkerOS.Properties` extracts UTM and click ID parameters from URLs.

```javascript
getMarketingParameters(
new URL('https://example.com/?utm_source=docs&gclid=123'),
);
// Returns { source: "docs", gclid: "123", clickId: "gclid" }

// With custom parameters
getMarketingParameters(url, { utm_custom: 'custom', partner: 'partnerId' });
```

## Type validation[​](#type-validation "Direct link to Type validation")

### Type checkers[​](#type-checkers "Direct link to Type checkers")

A comprehensive set of type checking functions:

* `isString(value)`, `isNumber(value)`, `isBoolean(value)`
* `isArray(value)`, `isObject(value)`, `isFunction(value)`
* `isDefined(value)`, `isSameType(a, b)`
* `isPropertyType(value)` - Checks if value is valid walkerOS property

### Property utilities[​](#property-utilities "Direct link to Property utilities")

* `castToProperty(value)` - Casts to valid property type
* `filterValues(object)` - Filters object to valid properties only
* `isPropertyType(value)` - Type guard for property validation

## Request handling[​](#request-handling "Direct link to Request handling")

### requestToData[​](#requesttodata "Direct link to requestToData")

`requestToData(parameter: unknown): WalkerOS.AnyObject | undefined` converts query strings to JavaScript objects with type casting.

```javascript
requestToData('a=1&b=true&c=hello&arr[0]=x&arr[1]=y');
// Returns { a: 1, b: true, c: 'hello', arr: ['x', 'y'] }
```

### requestToParameter[​](#requesttoparameter "Direct link to requestToParameter")

`requestToParameter(data: WalkerOS.AnyObject): string` converts objects to URL-encoded query strings.

```javascript
requestToParameter({ a: 1, b: true, arr: ['x', 'y'] });
// Returns 'a=1&b=true&arr[0]=x&arr[1]=y'
```

## User agent parsing[​](#user-agent-parsing "Direct link to User agent parsing")

### parseUserAgent[​](#parseuseragent "Direct link to parseUserAgent")

`parseUserAgent(userAgent?: string): WalkerOS.User` extracts browser, OS, and device information.

```javascript
parseUserAgent(navigator.userAgent);
// Returns { browser: 'Chrome', browserVersion: '91.0', os: 'Windows', ... }
```

Individual functions are also available:

* `getBrowser(userAgent)` - Returns browser name
* `getBrowserVersion(userAgent)` - Returns browser version
* `getOS(userAgent)` - Returns operating system
* `getOSVersion(userAgent)` - Returns OS version
* `getDeviceType(userAgent)` - Returns 'Desktop', 'Tablet', or 'Mobile'

## Error handling[​](#error-handling "Direct link to Error handling")

### tryCatch[​](#trycatch "Direct link to tryCatch")

`tryCatch(tryFn: Function, catchFn?: Function, finallyFn?: Function)` wraps functions with error handling.

```javascript
const safeParse = tryCatch(JSON.parse, () => ({}));
safeParse('{"valid": "json"}'); // Parses successfully
safeParse('invalid'); // Returns {} instead of throwing
```

### tryCatchAsync[​](#trycatchasync "Direct link to tryCatchAsync")

`tryCatchAsync(tryFn: Function, catchFn?: Function, finallyFn?: Function)` for async operations.

```javascript
const safeAsyncCall = tryCatchAsync(
() => fetchUserData(),
(error) => ({ error: 'Failed to load user' }),
);
```

## Performance optimization[​](#performance-optimization "Direct link to Performance optimization")

### debounce[​](#debounce "Direct link to debounce")

`debounce(fn: Function, wait?: number)` delays function execution until after the wait time.

```javascript
const debouncedSearch = debounce(searchFunction, 300);
// Only executes after 300ms of inactivity
```

### throttle[​](#throttle "Direct link to throttle")

`throttle(fn: Function, wait?: number)` limits function execution frequency.

```javascript
const throttledScroll = throttle(scrollHandler, 100);
// Executes at most every 100ms
```

## Tag Mode loader[​](#tag-mode-loader "Direct link to Tag Mode loader")

### moin[​](#moin "Direct link to moin")

`moin()` lets the walkerOS app open [Tag Mode](/preview/pr-749/docs/getting-started/quickstart/walkerjs.md#tag-mode) on your page, in the one browser tab the app opened for it. There is nothing to configure. walker.js and the web bundles the CLI builds call it first in their entry, so call it yourself only when you start a flow from your own browser code:

```typescript
import { moin } from '@walkeros/core';

moin(); // once, early, before startFlow
```

It does nothing unless the page was opened with `elbMoin` in its address. On such a page it waits for the walkerOS app tab to answer and only then loads the Tag Mode script from `https://cdn.walkeros.io`; without that answer nothing loads. Without `https://cdn.walkeros.io` in your Content Security Policy's `script-src`, nothing loads either, unless the policy uses `'strict-dynamic'`, which trusts scripts added by a script that carries your nonce.

`moin(target?: MoinTarget)` takes no argument in normal use: the default, `MOIN_PRODUCTION`, trusts the walkerOS app at `https://app.walkeros.io`. `MOIN_PARAM` is the address parameter, `'elbMoin'`.

## Utilities[​](#utilities "Direct link to Utilities")

### trim[​](#trim "Direct link to trim")

`trim(str: string): string` removes whitespace from string ends.

### throwError[​](#throwerror "Direct link to throwError")

`throwError(message: string)` throws descriptive errors.

### onLog[​](#onlog "Direct link to onLog")

`onLog(message: unknown, verbose?: boolean)` provides consistent logging.

```javascript
onLog('Debug info', true); // Logs message
onLog('Silent message'); // No output
```

For platform-specific utilities, see:

* [Web Core](/preview/pr-749/docs/core/web.md) - Browser-specific functions
* [Server Core](/preview/pr-749/docs/core/server.md) - Node.js server functions
