@leanmcp/utils 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +262 -0
- package/dist/index.d.mts +79 -0
- package/dist/index.d.ts +79 -0
- package/dist/index.js +229 -0
- package/dist/index.mjs +191 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 LeanMCP Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# @leanmcp/utils
|
|
2
|
+
|
|
3
|
+
Utility functions and helpers for LeanMCP SDK.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔄 **Retry logic** - Exponential backoff for resilient operations
|
|
8
|
+
- 📊 **Response formatting** - Format data as JSON, Markdown, HTML, or tables
|
|
9
|
+
- 🔀 **Object utilities** - Deep merge, validation, and manipulation
|
|
10
|
+
- ⏱️ **Async helpers** - Sleep, timeout, and promise utilities
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @leanmcp/utils
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## API Reference
|
|
19
|
+
|
|
20
|
+
### Response Formatting
|
|
21
|
+
|
|
22
|
+
#### formatResponse(data, format)
|
|
23
|
+
|
|
24
|
+
Format data based on specified format type.
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { formatResponse } from "@leanmcp/utils";
|
|
28
|
+
|
|
29
|
+
// JSON formatting
|
|
30
|
+
const json = formatResponse({ hello: "world" }, "json");
|
|
31
|
+
// Output: '{\n "hello": "world"\n}'
|
|
32
|
+
|
|
33
|
+
// Markdown formatting
|
|
34
|
+
const md = formatResponse({ hello: "world" }, "markdown");
|
|
35
|
+
// Output: '```json\n{\n "hello": "world"\n}\n```'
|
|
36
|
+
|
|
37
|
+
// HTML formatting
|
|
38
|
+
const html = formatResponse({ hello: "world" }, "html");
|
|
39
|
+
// Output: '<pre>{\n "hello": "world"\n}</pre>'
|
|
40
|
+
|
|
41
|
+
// Table formatting (for arrays)
|
|
42
|
+
const table = formatResponse([
|
|
43
|
+
{ name: "Alice", age: 30 },
|
|
44
|
+
{ name: "Bob", age: 25 }
|
|
45
|
+
], "table");
|
|
46
|
+
// Output: Markdown table format
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Supported formats:**
|
|
50
|
+
- `json` - Pretty-printed JSON
|
|
51
|
+
- `markdown` - JSON wrapped in markdown code block
|
|
52
|
+
- `html` - JSON wrapped in HTML pre tag
|
|
53
|
+
- `table` - Markdown table (for arrays of objects)
|
|
54
|
+
- Default - String conversion
|
|
55
|
+
|
|
56
|
+
#### formatAsTable(data)
|
|
57
|
+
|
|
58
|
+
Format array of objects as a Markdown table.
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
import { formatAsTable } from "@leanmcp/utils";
|
|
62
|
+
|
|
63
|
+
const data = [
|
|
64
|
+
{ name: "Alice", age: 30, city: "NYC" },
|
|
65
|
+
{ name: "Bob", age: 25, city: "LA" }
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
const table = formatAsTable(data);
|
|
69
|
+
console.log(table);
|
|
70
|
+
// | name | age | city |
|
|
71
|
+
// | --- | --- | --- |
|
|
72
|
+
// | Alice | 30 | NYC |
|
|
73
|
+
// | Bob | 25 | LA |
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Object Utilities
|
|
77
|
+
|
|
78
|
+
#### deepMerge(target, ...sources)
|
|
79
|
+
|
|
80
|
+
Deep merge multiple objects.
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import { deepMerge } from "@leanmcp/utils";
|
|
84
|
+
|
|
85
|
+
const target = { a: 1, b: { c: 2 } };
|
|
86
|
+
const source1 = { b: { d: 3 } };
|
|
87
|
+
const source2 = { e: 4 };
|
|
88
|
+
|
|
89
|
+
const result = deepMerge(target, source1, source2);
|
|
90
|
+
// { a: 1, b: { c: 2, d: 3 }, e: 4 }
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### isObject(item)
|
|
94
|
+
|
|
95
|
+
Check if value is a plain object.
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { isObject } from "@leanmcp/utils";
|
|
99
|
+
|
|
100
|
+
isObject({}); // true
|
|
101
|
+
isObject([]); // false
|
|
102
|
+
isObject(null); // false
|
|
103
|
+
isObject("string"); // false
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Async Utilities
|
|
107
|
+
|
|
108
|
+
#### retry(fn, options)
|
|
109
|
+
|
|
110
|
+
Retry a function with exponential backoff.
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
import { retry } from "@leanmcp/utils";
|
|
114
|
+
|
|
115
|
+
// Retry API call up to 3 times
|
|
116
|
+
const result = await retry(
|
|
117
|
+
async () => {
|
|
118
|
+
const response = await fetch('https://api.example.com/data');
|
|
119
|
+
if (!response.ok) throw new Error('API error');
|
|
120
|
+
return response.json();
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
maxRetries: 3, // Maximum number of retries
|
|
124
|
+
delayMs: 1000, // Initial delay in milliseconds
|
|
125
|
+
backoff: 2 // Backoff multiplier (2^n)
|
|
126
|
+
}
|
|
127
|
+
);
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Retry logic:**
|
|
131
|
+
- Attempt 1: Immediate
|
|
132
|
+
- Attempt 2: Wait 1000ms
|
|
133
|
+
- Attempt 3: Wait 2000ms
|
|
134
|
+
- Attempt 4: Wait 4000ms
|
|
135
|
+
|
|
136
|
+
#### sleep(ms)
|
|
137
|
+
|
|
138
|
+
Async sleep function.
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
import { sleep } from "@leanmcp/utils";
|
|
142
|
+
|
|
143
|
+
await sleep(1000); // Wait 1 second
|
|
144
|
+
console.log("1 second later");
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
#### timeout(promise, ms)
|
|
148
|
+
|
|
149
|
+
Add timeout to a promise.
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
import { timeout } from "@leanmcp/utils";
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
const result = await timeout(
|
|
156
|
+
fetch('https://slow-api.example.com'),
|
|
157
|
+
5000 // 5 second timeout
|
|
158
|
+
);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
console.log('Request timed out');
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Usage Examples
|
|
165
|
+
|
|
166
|
+
### Formatting API Responses
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
import { formatResponse } from "@leanmcp/utils";
|
|
170
|
+
|
|
171
|
+
class DataService {
|
|
172
|
+
@Tool({ description: 'Get user data' })
|
|
173
|
+
async getUsers() {
|
|
174
|
+
const users = await fetchUsers();
|
|
175
|
+
|
|
176
|
+
// Return as formatted table
|
|
177
|
+
return {
|
|
178
|
+
content: [{
|
|
179
|
+
type: "text",
|
|
180
|
+
text: formatResponse(users, "table")
|
|
181
|
+
}]
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Resilient API Calls
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
import { retry } from "@leanmcp/utils";
|
|
191
|
+
|
|
192
|
+
class ExternalService {
|
|
193
|
+
@Tool({ description: 'Fetch external data' })
|
|
194
|
+
async fetchData(input: { url: string }) {
|
|
195
|
+
// Automatically retry failed requests
|
|
196
|
+
const data = await retry(
|
|
197
|
+
() => fetch(input.url).then(r => r.json()),
|
|
198
|
+
{ maxRetries: 3, delayMs: 1000 }
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
return { data };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### Deep Configuration Merging
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
import { deepMerge } from "@leanmcp/utils";
|
|
210
|
+
|
|
211
|
+
const defaultConfig = {
|
|
212
|
+
server: { port: 3000, host: 'localhost' },
|
|
213
|
+
logging: { level: 'info' }
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const userConfig = {
|
|
217
|
+
server: { port: 4000 },
|
|
218
|
+
features: { auth: true }
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const config = deepMerge(defaultConfig, userConfig);
|
|
222
|
+
// {
|
|
223
|
+
// server: { port: 4000, host: 'localhost' },
|
|
224
|
+
// logging: { level: 'info' },
|
|
225
|
+
// features: { auth: true }
|
|
226
|
+
// }
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## Type Definitions
|
|
230
|
+
|
|
231
|
+
All functions are fully typed with TypeScript:
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
export function formatResponse(data: any, format: string): string;
|
|
235
|
+
export function formatAsTable(data: any[]): string;
|
|
236
|
+
export function deepMerge<T extends Record<string, any>>(target: T, ...sources: Partial<T>[]): T;
|
|
237
|
+
export function isObject(item: any): boolean;
|
|
238
|
+
export function retry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
239
|
+
export function sleep(ms: number): Promise<void>;
|
|
240
|
+
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
|
|
241
|
+
|
|
242
|
+
interface RetryOptions {
|
|
243
|
+
maxRetries?: number;
|
|
244
|
+
delayMs?: number;
|
|
245
|
+
backoff?: number;
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## License
|
|
250
|
+
|
|
251
|
+
MIT
|
|
252
|
+
|
|
253
|
+
## Related Packages
|
|
254
|
+
|
|
255
|
+
- [@leanmcp/core](../core) - Core MCP server functionality
|
|
256
|
+
- [@leanmcp/auth](../auth) - Authentication decorators
|
|
257
|
+
- [@leanmcp/cli](../cli) - CLI tool for creating new projects
|
|
258
|
+
|
|
259
|
+
## Links
|
|
260
|
+
|
|
261
|
+
- [GitHub Repository](https://github.com/LeanMCP/leanmcp-sdk)
|
|
262
|
+
- [Documentation](https://github.com/LeanMCP/leanmcp-sdk#readme)
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @leanmcp/utils - Utility Functions
|
|
3
|
+
*
|
|
4
|
+
* This module provides helper utilities and shared functions across the LeanMCP SDK.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Validate JSON against a schema (basic implementation)
|
|
8
|
+
* For advanced validation, use ajv or similar libraries in your project
|
|
9
|
+
*/
|
|
10
|
+
declare function validateSchema(data: any, schema: any): {
|
|
11
|
+
valid: boolean;
|
|
12
|
+
errors?: any[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Format response based on render type
|
|
16
|
+
*/
|
|
17
|
+
declare function formatResponse(data: any, format: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Format data as a markdown table
|
|
20
|
+
*/
|
|
21
|
+
declare function formatAsTable(data: any[]): string;
|
|
22
|
+
/**
|
|
23
|
+
* Deep merge objects
|
|
24
|
+
*/
|
|
25
|
+
declare function deepMerge<T extends Record<string, any>>(target: T, ...sources: Partial<T>[]): T;
|
|
26
|
+
/**
|
|
27
|
+
* Check if value is a plain object
|
|
28
|
+
*/
|
|
29
|
+
declare function isObject(item: any): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Retry a function with exponential backoff
|
|
32
|
+
*/
|
|
33
|
+
declare function retry<T>(fn: () => Promise<T>, options?: {
|
|
34
|
+
maxRetries?: number;
|
|
35
|
+
delayMs?: number;
|
|
36
|
+
backoff?: number;
|
|
37
|
+
}): Promise<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Sleep for a given duration
|
|
40
|
+
*/
|
|
41
|
+
declare function sleep(ms: number): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Create a debounced function
|
|
44
|
+
*/
|
|
45
|
+
declare function debounce<T extends (...args: any[]) => any>(func: T, waitMs: number): (...args: Parameters<T>) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Create a throttled function
|
|
48
|
+
*/
|
|
49
|
+
declare function throttle<T extends (...args: any[]) => any>(func: T, limitMs: number): (...args: Parameters<T>) => void;
|
|
50
|
+
/**
|
|
51
|
+
* Parse environment variables with type coercion
|
|
52
|
+
*/
|
|
53
|
+
declare function parseEnv(value: string | undefined, defaultValue: any, type?: 'string' | 'number' | 'boolean'): any;
|
|
54
|
+
/**
|
|
55
|
+
* Generate a unique ID
|
|
56
|
+
*/
|
|
57
|
+
declare function generateId(prefix?: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Truncate string to max length
|
|
60
|
+
*/
|
|
61
|
+
declare function truncate(str: string, maxLength: number, suffix?: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* Add timeout to a promise
|
|
64
|
+
*/
|
|
65
|
+
declare function timeout<T>(promise: Promise<T>, ms: number, errorMessage?: string): Promise<T>;
|
|
66
|
+
/**
|
|
67
|
+
* Convert camelCase to kebab-case
|
|
68
|
+
*/
|
|
69
|
+
declare function camelToKebab(str: string): string;
|
|
70
|
+
/**
|
|
71
|
+
* Convert kebab-case to camelCase
|
|
72
|
+
*/
|
|
73
|
+
declare function kebabToCamel(str: string): string;
|
|
74
|
+
/**
|
|
75
|
+
* Capitalize first letter
|
|
76
|
+
*/
|
|
77
|
+
declare function capitalize(str: string): string;
|
|
78
|
+
|
|
79
|
+
export { camelToKebab, capitalize, debounce, deepMerge, formatAsTable, formatResponse, generateId, isObject, kebabToCamel, parseEnv, retry, sleep, throttle, timeout, truncate, validateSchema };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @leanmcp/utils - Utility Functions
|
|
3
|
+
*
|
|
4
|
+
* This module provides helper utilities and shared functions across the LeanMCP SDK.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Validate JSON against a schema (basic implementation)
|
|
8
|
+
* For advanced validation, use ajv or similar libraries in your project
|
|
9
|
+
*/
|
|
10
|
+
declare function validateSchema(data: any, schema: any): {
|
|
11
|
+
valid: boolean;
|
|
12
|
+
errors?: any[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Format response based on render type
|
|
16
|
+
*/
|
|
17
|
+
declare function formatResponse(data: any, format: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Format data as a markdown table
|
|
20
|
+
*/
|
|
21
|
+
declare function formatAsTable(data: any[]): string;
|
|
22
|
+
/**
|
|
23
|
+
* Deep merge objects
|
|
24
|
+
*/
|
|
25
|
+
declare function deepMerge<T extends Record<string, any>>(target: T, ...sources: Partial<T>[]): T;
|
|
26
|
+
/**
|
|
27
|
+
* Check if value is a plain object
|
|
28
|
+
*/
|
|
29
|
+
declare function isObject(item: any): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Retry a function with exponential backoff
|
|
32
|
+
*/
|
|
33
|
+
declare function retry<T>(fn: () => Promise<T>, options?: {
|
|
34
|
+
maxRetries?: number;
|
|
35
|
+
delayMs?: number;
|
|
36
|
+
backoff?: number;
|
|
37
|
+
}): Promise<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Sleep for a given duration
|
|
40
|
+
*/
|
|
41
|
+
declare function sleep(ms: number): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Create a debounced function
|
|
44
|
+
*/
|
|
45
|
+
declare function debounce<T extends (...args: any[]) => any>(func: T, waitMs: number): (...args: Parameters<T>) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Create a throttled function
|
|
48
|
+
*/
|
|
49
|
+
declare function throttle<T extends (...args: any[]) => any>(func: T, limitMs: number): (...args: Parameters<T>) => void;
|
|
50
|
+
/**
|
|
51
|
+
* Parse environment variables with type coercion
|
|
52
|
+
*/
|
|
53
|
+
declare function parseEnv(value: string | undefined, defaultValue: any, type?: 'string' | 'number' | 'boolean'): any;
|
|
54
|
+
/**
|
|
55
|
+
* Generate a unique ID
|
|
56
|
+
*/
|
|
57
|
+
declare function generateId(prefix?: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Truncate string to max length
|
|
60
|
+
*/
|
|
61
|
+
declare function truncate(str: string, maxLength: number, suffix?: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* Add timeout to a promise
|
|
64
|
+
*/
|
|
65
|
+
declare function timeout<T>(promise: Promise<T>, ms: number, errorMessage?: string): Promise<T>;
|
|
66
|
+
/**
|
|
67
|
+
* Convert camelCase to kebab-case
|
|
68
|
+
*/
|
|
69
|
+
declare function camelToKebab(str: string): string;
|
|
70
|
+
/**
|
|
71
|
+
* Convert kebab-case to camelCase
|
|
72
|
+
*/
|
|
73
|
+
declare function kebabToCamel(str: string): string;
|
|
74
|
+
/**
|
|
75
|
+
* Capitalize first letter
|
|
76
|
+
*/
|
|
77
|
+
declare function capitalize(str: string): string;
|
|
78
|
+
|
|
79
|
+
export { camelToKebab, capitalize, debounce, deepMerge, formatAsTable, formatResponse, generateId, isObject, kebabToCamel, parseEnv, retry, sleep, throttle, timeout, truncate, validateSchema };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
camelToKebab: () => camelToKebab,
|
|
25
|
+
capitalize: () => capitalize,
|
|
26
|
+
debounce: () => debounce,
|
|
27
|
+
deepMerge: () => deepMerge,
|
|
28
|
+
formatAsTable: () => formatAsTable,
|
|
29
|
+
formatResponse: () => formatResponse,
|
|
30
|
+
generateId: () => generateId,
|
|
31
|
+
isObject: () => isObject,
|
|
32
|
+
kebabToCamel: () => kebabToCamel,
|
|
33
|
+
parseEnv: () => parseEnv,
|
|
34
|
+
retry: () => retry,
|
|
35
|
+
sleep: () => sleep,
|
|
36
|
+
throttle: () => throttle,
|
|
37
|
+
timeout: () => timeout,
|
|
38
|
+
truncate: () => truncate,
|
|
39
|
+
validateSchema: () => validateSchema
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(index_exports);
|
|
42
|
+
function validateSchema(data, schema) {
|
|
43
|
+
const errors = [];
|
|
44
|
+
if (!schema || typeof schema !== "object") {
|
|
45
|
+
return {
|
|
46
|
+
valid: true
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (schema.type) {
|
|
50
|
+
const actualType = Array.isArray(data) ? "array" : typeof data;
|
|
51
|
+
if (actualType !== schema.type && !(schema.type === "integer" && typeof data === "number")) {
|
|
52
|
+
errors.push({
|
|
53
|
+
message: `Expected type ${schema.type}, got ${actualType}`
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (schema.required && Array.isArray(schema.required) && typeof data === "object") {
|
|
58
|
+
for (const prop of schema.required) {
|
|
59
|
+
if (!(prop in data)) {
|
|
60
|
+
errors.push({
|
|
61
|
+
message: `Missing required property: ${prop}`
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
valid: errors.length === 0,
|
|
68
|
+
errors: errors.length > 0 ? errors : void 0
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
__name(validateSchema, "validateSchema");
|
|
72
|
+
function formatResponse(data, format) {
|
|
73
|
+
switch (format) {
|
|
74
|
+
case "json":
|
|
75
|
+
return JSON.stringify(data, null, 2);
|
|
76
|
+
case "markdown":
|
|
77
|
+
return typeof data === "string" ? data : `\`\`\`json
|
|
78
|
+
${JSON.stringify(data, null, 2)}
|
|
79
|
+
\`\`\``;
|
|
80
|
+
case "html":
|
|
81
|
+
return typeof data === "string" ? data : `<pre>${JSON.stringify(data, null, 2)}</pre>`;
|
|
82
|
+
case "table":
|
|
83
|
+
return formatAsTable(data);
|
|
84
|
+
default:
|
|
85
|
+
return String(data);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
__name(formatResponse, "formatResponse");
|
|
89
|
+
function formatAsTable(data) {
|
|
90
|
+
if (!Array.isArray(data) || data.length === 0) {
|
|
91
|
+
return String(data);
|
|
92
|
+
}
|
|
93
|
+
const keys = Object.keys(data[0]);
|
|
94
|
+
const header = `| ${keys.join(" | ")} |`;
|
|
95
|
+
const separator = `| ${keys.map(() => "---").join(" | ")} |`;
|
|
96
|
+
const rows = data.map((row) => `| ${keys.map((key) => row[key]).join(" | ")} |`);
|
|
97
|
+
return [
|
|
98
|
+
header,
|
|
99
|
+
separator,
|
|
100
|
+
...rows
|
|
101
|
+
].join("\n");
|
|
102
|
+
}
|
|
103
|
+
__name(formatAsTable, "formatAsTable");
|
|
104
|
+
function deepMerge(target, ...sources) {
|
|
105
|
+
if (!sources.length) return target;
|
|
106
|
+
const source = sources.shift();
|
|
107
|
+
if (isObject(target) && isObject(source)) {
|
|
108
|
+
for (const key in source) {
|
|
109
|
+
if (isObject(source[key])) {
|
|
110
|
+
if (!target[key]) Object.assign(target, {
|
|
111
|
+
[key]: {}
|
|
112
|
+
});
|
|
113
|
+
deepMerge(target[key], source[key]);
|
|
114
|
+
} else {
|
|
115
|
+
Object.assign(target, {
|
|
116
|
+
[key]: source[key]
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return deepMerge(target, ...sources);
|
|
122
|
+
}
|
|
123
|
+
__name(deepMerge, "deepMerge");
|
|
124
|
+
function isObject(item) {
|
|
125
|
+
return item && typeof item === "object" && !Array.isArray(item);
|
|
126
|
+
}
|
|
127
|
+
__name(isObject, "isObject");
|
|
128
|
+
async function retry(fn, options = {}) {
|
|
129
|
+
const { maxRetries = 3, delayMs = 1e3, backoff = 2 } = options;
|
|
130
|
+
let lastError;
|
|
131
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
132
|
+
try {
|
|
133
|
+
return await fn();
|
|
134
|
+
} catch (error) {
|
|
135
|
+
lastError = error;
|
|
136
|
+
if (i < maxRetries - 1) {
|
|
137
|
+
await sleep(delayMs * Math.pow(backoff, i));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
throw lastError;
|
|
142
|
+
}
|
|
143
|
+
__name(retry, "retry");
|
|
144
|
+
function sleep(ms) {
|
|
145
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
146
|
+
}
|
|
147
|
+
__name(sleep, "sleep");
|
|
148
|
+
function debounce(func, waitMs) {
|
|
149
|
+
let timeout2 = null;
|
|
150
|
+
return function(...args) {
|
|
151
|
+
if (timeout2) clearTimeout(timeout2);
|
|
152
|
+
timeout2 = setTimeout(() => func.apply(this, args), waitMs);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
__name(debounce, "debounce");
|
|
156
|
+
function throttle(func, limitMs) {
|
|
157
|
+
let inThrottle = false;
|
|
158
|
+
return function(...args) {
|
|
159
|
+
if (!inThrottle) {
|
|
160
|
+
func.apply(this, args);
|
|
161
|
+
inThrottle = true;
|
|
162
|
+
setTimeout(() => inThrottle = false, limitMs);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
__name(throttle, "throttle");
|
|
167
|
+
function parseEnv(value, defaultValue, type = "string") {
|
|
168
|
+
if (value === void 0) return defaultValue;
|
|
169
|
+
switch (type) {
|
|
170
|
+
case "number":
|
|
171
|
+
const num = Number(value);
|
|
172
|
+
return isNaN(num) ? defaultValue : num;
|
|
173
|
+
case "boolean":
|
|
174
|
+
return value.toLowerCase() === "true";
|
|
175
|
+
case "string":
|
|
176
|
+
default:
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
__name(parseEnv, "parseEnv");
|
|
181
|
+
function generateId(prefix = "") {
|
|
182
|
+
const timestamp = Date.now().toString(36);
|
|
183
|
+
const random = Math.random().toString(36).substring(2, 9);
|
|
184
|
+
return prefix ? `${prefix}-${timestamp}-${random}` : `${timestamp}-${random}`;
|
|
185
|
+
}
|
|
186
|
+
__name(generateId, "generateId");
|
|
187
|
+
function truncate(str, maxLength, suffix = "...") {
|
|
188
|
+
if (str.length <= maxLength) return str;
|
|
189
|
+
return str.substring(0, maxLength - suffix.length) + suffix;
|
|
190
|
+
}
|
|
191
|
+
__name(truncate, "truncate");
|
|
192
|
+
function timeout(promise, ms, errorMessage = "Operation timed out") {
|
|
193
|
+
return Promise.race([
|
|
194
|
+
promise,
|
|
195
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(errorMessage)), ms))
|
|
196
|
+
]);
|
|
197
|
+
}
|
|
198
|
+
__name(timeout, "timeout");
|
|
199
|
+
function camelToKebab(str) {
|
|
200
|
+
return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
201
|
+
}
|
|
202
|
+
__name(camelToKebab, "camelToKebab");
|
|
203
|
+
function kebabToCamel(str) {
|
|
204
|
+
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
205
|
+
}
|
|
206
|
+
__name(kebabToCamel, "kebabToCamel");
|
|
207
|
+
function capitalize(str) {
|
|
208
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
209
|
+
}
|
|
210
|
+
__name(capitalize, "capitalize");
|
|
211
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
212
|
+
0 && (module.exports = {
|
|
213
|
+
camelToKebab,
|
|
214
|
+
capitalize,
|
|
215
|
+
debounce,
|
|
216
|
+
deepMerge,
|
|
217
|
+
formatAsTable,
|
|
218
|
+
formatResponse,
|
|
219
|
+
generateId,
|
|
220
|
+
isObject,
|
|
221
|
+
kebabToCamel,
|
|
222
|
+
parseEnv,
|
|
223
|
+
retry,
|
|
224
|
+
sleep,
|
|
225
|
+
throttle,
|
|
226
|
+
timeout,
|
|
227
|
+
truncate,
|
|
228
|
+
validateSchema
|
|
229
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// src/index.ts
|
|
5
|
+
function validateSchema(data, schema) {
|
|
6
|
+
const errors = [];
|
|
7
|
+
if (!schema || typeof schema !== "object") {
|
|
8
|
+
return {
|
|
9
|
+
valid: true
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
if (schema.type) {
|
|
13
|
+
const actualType = Array.isArray(data) ? "array" : typeof data;
|
|
14
|
+
if (actualType !== schema.type && !(schema.type === "integer" && typeof data === "number")) {
|
|
15
|
+
errors.push({
|
|
16
|
+
message: `Expected type ${schema.type}, got ${actualType}`
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (schema.required && Array.isArray(schema.required) && typeof data === "object") {
|
|
21
|
+
for (const prop of schema.required) {
|
|
22
|
+
if (!(prop in data)) {
|
|
23
|
+
errors.push({
|
|
24
|
+
message: `Missing required property: ${prop}`
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
valid: errors.length === 0,
|
|
31
|
+
errors: errors.length > 0 ? errors : void 0
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
__name(validateSchema, "validateSchema");
|
|
35
|
+
function formatResponse(data, format) {
|
|
36
|
+
switch (format) {
|
|
37
|
+
case "json":
|
|
38
|
+
return JSON.stringify(data, null, 2);
|
|
39
|
+
case "markdown":
|
|
40
|
+
return typeof data === "string" ? data : `\`\`\`json
|
|
41
|
+
${JSON.stringify(data, null, 2)}
|
|
42
|
+
\`\`\``;
|
|
43
|
+
case "html":
|
|
44
|
+
return typeof data === "string" ? data : `<pre>${JSON.stringify(data, null, 2)}</pre>`;
|
|
45
|
+
case "table":
|
|
46
|
+
return formatAsTable(data);
|
|
47
|
+
default:
|
|
48
|
+
return String(data);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
__name(formatResponse, "formatResponse");
|
|
52
|
+
function formatAsTable(data) {
|
|
53
|
+
if (!Array.isArray(data) || data.length === 0) {
|
|
54
|
+
return String(data);
|
|
55
|
+
}
|
|
56
|
+
const keys = Object.keys(data[0]);
|
|
57
|
+
const header = `| ${keys.join(" | ")} |`;
|
|
58
|
+
const separator = `| ${keys.map(() => "---").join(" | ")} |`;
|
|
59
|
+
const rows = data.map((row) => `| ${keys.map((key) => row[key]).join(" | ")} |`);
|
|
60
|
+
return [
|
|
61
|
+
header,
|
|
62
|
+
separator,
|
|
63
|
+
...rows
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
66
|
+
__name(formatAsTable, "formatAsTable");
|
|
67
|
+
function deepMerge(target, ...sources) {
|
|
68
|
+
if (!sources.length) return target;
|
|
69
|
+
const source = sources.shift();
|
|
70
|
+
if (isObject(target) && isObject(source)) {
|
|
71
|
+
for (const key in source) {
|
|
72
|
+
if (isObject(source[key])) {
|
|
73
|
+
if (!target[key]) Object.assign(target, {
|
|
74
|
+
[key]: {}
|
|
75
|
+
});
|
|
76
|
+
deepMerge(target[key], source[key]);
|
|
77
|
+
} else {
|
|
78
|
+
Object.assign(target, {
|
|
79
|
+
[key]: source[key]
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return deepMerge(target, ...sources);
|
|
85
|
+
}
|
|
86
|
+
__name(deepMerge, "deepMerge");
|
|
87
|
+
function isObject(item) {
|
|
88
|
+
return item && typeof item === "object" && !Array.isArray(item);
|
|
89
|
+
}
|
|
90
|
+
__name(isObject, "isObject");
|
|
91
|
+
async function retry(fn, options = {}) {
|
|
92
|
+
const { maxRetries = 3, delayMs = 1e3, backoff = 2 } = options;
|
|
93
|
+
let lastError;
|
|
94
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
95
|
+
try {
|
|
96
|
+
return await fn();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
lastError = error;
|
|
99
|
+
if (i < maxRetries - 1) {
|
|
100
|
+
await sleep(delayMs * Math.pow(backoff, i));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
throw lastError;
|
|
105
|
+
}
|
|
106
|
+
__name(retry, "retry");
|
|
107
|
+
function sleep(ms) {
|
|
108
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
109
|
+
}
|
|
110
|
+
__name(sleep, "sleep");
|
|
111
|
+
function debounce(func, waitMs) {
|
|
112
|
+
let timeout2 = null;
|
|
113
|
+
return function(...args) {
|
|
114
|
+
if (timeout2) clearTimeout(timeout2);
|
|
115
|
+
timeout2 = setTimeout(() => func.apply(this, args), waitMs);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
__name(debounce, "debounce");
|
|
119
|
+
function throttle(func, limitMs) {
|
|
120
|
+
let inThrottle = false;
|
|
121
|
+
return function(...args) {
|
|
122
|
+
if (!inThrottle) {
|
|
123
|
+
func.apply(this, args);
|
|
124
|
+
inThrottle = true;
|
|
125
|
+
setTimeout(() => inThrottle = false, limitMs);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
__name(throttle, "throttle");
|
|
130
|
+
function parseEnv(value, defaultValue, type = "string") {
|
|
131
|
+
if (value === void 0) return defaultValue;
|
|
132
|
+
switch (type) {
|
|
133
|
+
case "number":
|
|
134
|
+
const num = Number(value);
|
|
135
|
+
return isNaN(num) ? defaultValue : num;
|
|
136
|
+
case "boolean":
|
|
137
|
+
return value.toLowerCase() === "true";
|
|
138
|
+
case "string":
|
|
139
|
+
default:
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
__name(parseEnv, "parseEnv");
|
|
144
|
+
function generateId(prefix = "") {
|
|
145
|
+
const timestamp = Date.now().toString(36);
|
|
146
|
+
const random = Math.random().toString(36).substring(2, 9);
|
|
147
|
+
return prefix ? `${prefix}-${timestamp}-${random}` : `${timestamp}-${random}`;
|
|
148
|
+
}
|
|
149
|
+
__name(generateId, "generateId");
|
|
150
|
+
function truncate(str, maxLength, suffix = "...") {
|
|
151
|
+
if (str.length <= maxLength) return str;
|
|
152
|
+
return str.substring(0, maxLength - suffix.length) + suffix;
|
|
153
|
+
}
|
|
154
|
+
__name(truncate, "truncate");
|
|
155
|
+
function timeout(promise, ms, errorMessage = "Operation timed out") {
|
|
156
|
+
return Promise.race([
|
|
157
|
+
promise,
|
|
158
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(errorMessage)), ms))
|
|
159
|
+
]);
|
|
160
|
+
}
|
|
161
|
+
__name(timeout, "timeout");
|
|
162
|
+
function camelToKebab(str) {
|
|
163
|
+
return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
164
|
+
}
|
|
165
|
+
__name(camelToKebab, "camelToKebab");
|
|
166
|
+
function kebabToCamel(str) {
|
|
167
|
+
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
168
|
+
}
|
|
169
|
+
__name(kebabToCamel, "kebabToCamel");
|
|
170
|
+
function capitalize(str) {
|
|
171
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
172
|
+
}
|
|
173
|
+
__name(capitalize, "capitalize");
|
|
174
|
+
export {
|
|
175
|
+
camelToKebab,
|
|
176
|
+
capitalize,
|
|
177
|
+
debounce,
|
|
178
|
+
deepMerge,
|
|
179
|
+
formatAsTable,
|
|
180
|
+
formatResponse,
|
|
181
|
+
generateId,
|
|
182
|
+
isObject,
|
|
183
|
+
kebabToCamel,
|
|
184
|
+
parseEnv,
|
|
185
|
+
retry,
|
|
186
|
+
sleep,
|
|
187
|
+
throttle,
|
|
188
|
+
timeout,
|
|
189
|
+
truncate,
|
|
190
|
+
validateSchema
|
|
191
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@leanmcp/utils",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Helper utilities and decorators shared across modules",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"require": "./dist/index.js",
|
|
12
|
+
"import": "./dist/index.mjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsup src/index.ts --format esm,cjs --dts",
|
|
22
|
+
"dev": "tsup src/index.ts --format esm,cjs --dts --watch",
|
|
23
|
+
"test": "jest --passWithNoTests",
|
|
24
|
+
"test:watch": "jest --watch"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@leanmcp/core": "^0.1.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^20.0.0"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/LeanMCP/leanmcp-sdk.git",
|
|
35
|
+
"directory": "packages/utils"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/LeanMCP/leanmcp-sdk#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/LeanMCP/leanmcp-sdk/issues"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"mcp",
|
|
43
|
+
"model-context-protocol",
|
|
44
|
+
"typescript",
|
|
45
|
+
"utilities",
|
|
46
|
+
"helpers",
|
|
47
|
+
"validation"
|
|
48
|
+
],
|
|
49
|
+
"author": "LeanMCP <admin@leanmcp.com>",
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
}
|
|
54
|
+
}
|