or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array.mdcrypto.mddate.mdfs.mdfunction.mdindex.mdjson.mdnumber.mdobject.mdoptimize.mdstring.mdtimeout.mdweb.md

index.mddocs/

0

# Utility

1

2

Utility is a comprehensive TypeScript/JavaScript library providing 50+ utility functions for common programming tasks. It offers zero-dependency, high-performance solutions for cryptographic operations, date formatting, string processing, number validation, JSON handling, and more, designed for server-side Node.js applications.

3

4

## Package Information

5

6

- **Package Name**: utility

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install utility`

10

11

## Core Imports

12

13

```typescript

14

import { md5, sha256, YYYYMMDD, randomString } from "utility";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { md5, sha256, YYYYMMDD, randomString } = require("utility");

21

```

22

23

Namespace import:

24

25

```typescript

26

import * as utils from "utility";

27

```

28

29

## Basic Usage

30

31

```typescript

32

import { md5, sha256, logDate, randomString, base64encode } from "utility";

33

34

// Cryptographic operations

35

const hash = md5("hello world");

36

const secureHash = sha256("sensitive data", "base64");

37

38

// Date formatting

39

const timestamp = logDate(); // "2025-09-06 12:05:30.123"

40

const dateOnly = YYYYMMDD(); // "2025-09-06"

41

42

// String utilities

43

const randomId = randomString(16); // Generate 16-char random string

44

const encoded = base64encode("data to encode");

45

46

// Number operations

47

import { toSafeNumber, random } from "utility";

48

const safeNum = toSafeNumber("12345678901234567890");

49

const randomNum = random(10, 100);

50

```

51

52

## Architecture

53

54

The utility package is organized into focused modules, each providing related functionality:

55

56

- **Cryptographic Functions**: Hash functions (MD5, SHA1, SHA256, SHA512), HMAC, Base64 encoding/decoding

57

- **Date Operations**: Multiple formatting options, timezone handling, timestamp conversion, caching for performance

58

- **String Processing**: Random generation, splitting, HTTP header validation, character replacement

59

- **Number Utilities**: Safe integer operations, random number generation, precision handling

60

- **Object Operations**: High-performance assignment, property enumeration, clean object creation

61

- **JSON Handling**: Safe parsing, file I/O operations with proper error handling

62

- **Optimization Utilities**: Try-catch wrappers, safe property access, performance optimizations

63

- **Timeout Management**: Promise timeout handling with custom error types

64

- **Web Utilities**: HTML escaping, URI encoding/decoding with error safety

65

- **File System**: Async file existence checking

66

- **Function Utilities**: Parameter introspection, no-op functions

67

68

## Capabilities

69

70

### Cryptographic Operations

71

72

Core cryptographic functionality including multiple hash algorithms, HMAC generation, and Base64 encoding/decoding with support for URL-safe variants.

73

74

```typescript { .api }

75

function hash(method: string, s: HashInput, format?: BinaryToTextEncoding): string;

76

function md5(s: HashInput, format?: BinaryToTextEncoding): string;

77

function sha256(s: HashInput, format?: BinaryToTextEncoding): string;

78

function hmac(algorithm: string, key: string, data: string | Buffer, encoding?: BinaryToTextEncoding): string;

79

function base64encode(s: string | Buffer, urlSafe?: boolean): string;

80

function base64decode(encodeStr: string, urlSafe?: boolean, encoding?: BufferEncoding | 'buffer'): string | Buffer;

81

82

type HashInput = string | Buffer | ArrayBuffer | DataView | object;

83

```

84

85

[Cryptographic Operations](./crypto.md)

86

87

### Date Formatting and Processing

88

89

Comprehensive date formatting utilities with multiple output formats, timezone support, caching for performance, and timestamp conversion operations.

90

91

```typescript { .api }

92

function logDate(d?: Date | string | null, msSep?: string): string;

93

function YYYYMMDD(d?: Date | string, sep?: string): string;

94

function YYYYMMDDHHmmss(d?: Date | string | number, options?: YYYYMMDDHHmmssOptions): string;

95

function accessLogDate(d?: Date): string;

96

function timestamp(t?: number | string): number | Date;

97

function getDateFromMilliseconds(milliseconds: number, format?: DateFormat): string;

98

99

interface YYYYMMDDHHmmssOptions {

100

dateSep?: string;

101

timeSep?: string;

102

}

103

104

enum DateFormat {

105

DateTimeWithTimeZone = 'DateTimeWithTimeZone',

106

DateTimeWithMilliSeconds = 'DateTimeWithMilliSeconds',

107

DateTimeWithSeconds = 'DateTimeWithSeconds',

108

UnixTimestamp = 'UnixTimestamp',

109

}

110

```

111

112

[Date Formatting](./date.md)

113

114

### String Processing

115

116

String manipulation utilities including random generation, splitting with trimming, HTTP header validation, and character replacement operations.

117

118

```typescript { .api }

119

function randomString(length?: number, charSet?: string): string;

120

function split(str?: string, sep?: string): string[];

121

function replace(str: string, substr: string | RegExp, newSubstr: string | StringReplacer): string;

122

function replaceInvalidHttpHeaderChar(val: string, replacement?: string | Replacement): {val: string, invalid: boolean};

123

function includesInvalidHttpHeaderChar(val: string): boolean;

124

125

type StringReplacer = (substring: string, ...args: any[]) => string;

126

type Replacement = (char: string) => string;

127

```

128

129

[String Processing](./string.md)

130

131

### Number Operations

132

133

Safe number operations with precision handling, random number generation, and validation for JavaScript's safe integer limits.

134

135

```typescript { .api }

136

function toSafeNumber(s: string | number): number | string;

137

function isSafeNumberString(s: string): boolean;

138

function random(lower?: number, upper?: number): number;

139

140

const MAX_SAFE_INTEGER: number;

141

const MIN_SAFE_INTEGER: number;

142

const MAX_SAFE_INTEGER_STR: string;

143

```

144

145

[Number Operations](./number.md)

146

147

### Object Utilities

148

149

High-performance object operations including assignment, property enumeration, ownership checking, and clean object creation.

150

151

```typescript { .api }

152

function assign(target: any, objects: any | any[]): any;

153

function has(obj: object, prop: string): boolean;

154

function getOwnEnumerables(obj: any, ignoreNull?: boolean): Array<string>;

155

function map(obj?: any): Record<string, any>;

156

```

157

158

[Object Utilities](./object.md)

159

160

### JSON Operations

161

162

Safe JSON parsing and file I/O operations with proper error handling, directory creation, and configurable formatting options.

163

164

```typescript { .api }

165

function strictJSONParse<T extends object = object>(content: string): T;

166

function readJSONSync<T = any>(filepath: string): T;

167

function writeJSONSync(filepath: string, content: string | object, options?: JSONStringifyOptions): void;

168

function readJSON<T = any>(filepath: string): Promise<T>;

169

function writeJSON(filepath: string, content: string | object, options?: JSONStringifyOptions): Promise<void>;

170

171

interface JSONStringifyOptions {

172

space?: number | string;

173

replacer?: (this: any, key: string, value: any) => any;

174

}

175

```

176

177

[JSON Operations](./json.md)

178

179

### Optimization Utilities

180

181

Performance optimization utilities including try-catch wrappers, safe property access, and efficient argument handling.

182

183

```typescript { .api }

184

function tryCatch<T = any>(fn: () => T): {error: Error | undefined, value: T | undefined};

185

function dig(obj?: any, ...keys: string[]): any;

186

function argumentsToArray(args: any[]): any[];

187

188

const UNSTABLE_METHOD: {

189

try: typeof tryCatch;

190

};

191

```

192

193

[Optimization Utilities](./optimize.md)

194

195

### Timeout Management

196

197

Promise timeout handling with custom error types and wrapper functions for time-limited operations.

198

199

```typescript { .api }

200

class TimeoutError extends Error {

201

timeout: number;

202

constructor(timeout: number);

203

}

204

205

function promiseTimeout<T>(promiseArg: Promise<T>, timeout: number): Promise<T>;

206

function runWithTimeout<T>(scope: () => Promise<T>, timeout: number): Promise<T>;

207

```

208

209

[Timeout Management](./timeout.md)

210

211

### Web Utilities

212

213

Web-related utilities for HTML escaping/unescaping and safe URI component encoding/decoding with error handling.

214

215

```typescript { .api }

216

function escape(html: string): string;

217

function unescape(html: string, type?: string): string;

218

function encodeURIComponent(text: string): string;

219

function decodeURIComponent(encodeText: string): string;

220

```

221

222

[Web Utilities](./web.md)

223

224

### Array Operations

225

226

Array manipulation utilities for random slicing and efficient element removal operations.

227

228

```typescript { .api }

229

function randomSlice<T = any>(arr: T[], num?: number): T[];

230

function spliceOne<T = any>(arr: T[], index: number): T[];

231

```

232

233

[Array Operations](./array.md)

234

235

### File System Operations

236

237

Asynchronous file system utilities for checking file existence with proper error handling.

238

239

```typescript { .api }

240

function exists(file: string): Promise<Stats | false>;

241

```

242

243

[File System Operations](./fs.md)

244

245

### Function Utilities

246

247

Function introspection and utility operations including parameter name extraction and no-op functions.

248

249

```typescript { .api }

250

function noop(..._args: any[]): any;

251

function getParamNames(func: (...args: any[]) => any, cache?: boolean): string[];

252

```

253

254

[Function Utilities](./function.md)