@oxog/utils 1.0.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/CHANGELOG.md +44 -0
- package/LICENSE +21 -0
- package/README.md +297 -0
- package/dist/index.cjs +645 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +780 -0
- package/dist/index.d.ts +780 -0
- package/dist/index.js +611 -0
- package/dist/index.js.map +1 -0
- package/dist/plugins/async.cjs +188 -0
- package/dist/plugins/async.cjs.map +1 -0
- package/dist/plugins/async.d.cts +169 -0
- package/dist/plugins/async.d.ts +169 -0
- package/dist/plugins/async.js +182 -0
- package/dist/plugins/async.js.map +1 -0
- package/dist/plugins/deep.cjs +157 -0
- package/dist/plugins/deep.cjs.map +1 -0
- package/dist/plugins/deep.d.cts +157 -0
- package/dist/plugins/deep.d.ts +157 -0
- package/dist/plugins/deep.js +152 -0
- package/dist/plugins/deep.js.map +1 -0
- package/dist/plugins/guard.cjs +47 -0
- package/dist/plugins/guard.cjs.map +1 -0
- package/dist/plugins/guard.d.cts +213 -0
- package/dist/plugins/guard.d.ts +213 -0
- package/dist/plugins/guard.js +38 -0
- package/dist/plugins/guard.js.map +1 -0
- package/dist/plugins/transform.cjs +49 -0
- package/dist/plugins/transform.cjs.map +1 -0
- package/dist/plugins/transform.d.cts +231 -0
- package/dist/plugins/transform.d.ts +231 -0
- package/dist/plugins/transform.js +42 -0
- package/dist/plugins/transform.js.map +1 -0
- package/dist/types-XmRC5wYO.d.cts +97 -0
- package/dist/types-XmRC5wYO.d.ts +97 -0
- package/package.json +115 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { D as DebounceOptions, R as RetryOptions } from '../types-XmRC5wYO.js';
|
|
2
|
+
|
|
3
|
+
interface DebouncedFunction<T extends (...args: any[]) => any> {
|
|
4
|
+
(...args: Parameters<T>): ReturnType<T>;
|
|
5
|
+
cancel: () => void;
|
|
6
|
+
flush: () => ReturnType<T>;
|
|
7
|
+
pending: () => boolean;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Debounce function execution.
|
|
11
|
+
*
|
|
12
|
+
* Delays function execution until after `wait` milliseconds have elapsed
|
|
13
|
+
* since the last time the debounced function was invoked.
|
|
14
|
+
*
|
|
15
|
+
* @param fn - Function to debounce
|
|
16
|
+
* @param wait - Wait time in milliseconds
|
|
17
|
+
* @param options - Debounce options
|
|
18
|
+
* @returns Debounced function with control methods
|
|
19
|
+
*
|
|
20
|
+
* @example Basic usage
|
|
21
|
+
* ```typescript
|
|
22
|
+
* const debouncedSave = debounce(save, 300);
|
|
23
|
+
* debouncedSave(data);
|
|
24
|
+
* // save() will be called 300ms after last call
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @example With control methods
|
|
28
|
+
* ```typescript
|
|
29
|
+
* const debouncedSave = debounce(save, 300);
|
|
30
|
+
* debouncedSave(data);
|
|
31
|
+
* debouncedSave.cancel(); // Cancel pending execution
|
|
32
|
+
* debouncedSave.flush(); // Execute immediately
|
|
33
|
+
* debouncedSave.pending(); // Check if pending
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @example Leading edge
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const debounced = debounce(fn, 300, { leading: true });
|
|
39
|
+
* debounced(); // Executes immediately on first call
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number, options?: DebounceOptions): DebouncedFunction<T>;
|
|
43
|
+
/**
|
|
44
|
+
* Throttle function execution.
|
|
45
|
+
*
|
|
46
|
+
* Ensures function is called at most once every `wait` milliseconds.
|
|
47
|
+
*
|
|
48
|
+
* @param fn - Function to throttle
|
|
49
|
+
* @param wait - Wait time in milliseconds
|
|
50
|
+
* @param options - Throttle options
|
|
51
|
+
* @returns Throttled function with control methods
|
|
52
|
+
*
|
|
53
|
+
* @example Basic usage
|
|
54
|
+
* ```typescript
|
|
55
|
+
* const throttledScroll = throttle(onScroll, 100);
|
|
56
|
+
* window.addEventListener('scroll', throttledScroll);
|
|
57
|
+
* // onScroll will be called at most once every 100ms
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @example With control methods
|
|
61
|
+
* ```typescript
|
|
62
|
+
* const throttled = throttle(fn, 100);
|
|
63
|
+
* throttled.cancel(); // Cancel pending execution
|
|
64
|
+
* throttled.pending(); // Check if pending
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
interface ThrottledFunction<T extends (...args: any[]) => any> {
|
|
68
|
+
(...args: Parameters<T>): ReturnType<T>;
|
|
69
|
+
cancel: () => void;
|
|
70
|
+
pending: () => boolean;
|
|
71
|
+
}
|
|
72
|
+
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, options?: {
|
|
73
|
+
leading?: boolean;
|
|
74
|
+
trailing?: boolean;
|
|
75
|
+
}): ThrottledFunction<T>;
|
|
76
|
+
/**
|
|
77
|
+
* Sleep for specified milliseconds.
|
|
78
|
+
*
|
|
79
|
+
* Returns a promise that resolves after the specified delay.
|
|
80
|
+
*
|
|
81
|
+
* @param ms - Milliseconds to sleep
|
|
82
|
+
* @returns Promise that resolves after delay
|
|
83
|
+
*
|
|
84
|
+
* @example Basic usage
|
|
85
|
+
* ```typescript
|
|
86
|
+
* await sleep(1000); // Wait 1 second
|
|
87
|
+
* console.log('Done!');
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @example In async function
|
|
91
|
+
* ```typescript
|
|
92
|
+
* async function process() {
|
|
93
|
+
* console.log('Start');
|
|
94
|
+
* await sleep(1000);
|
|
95
|
+
* console.log('After 1 second');
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
declare function sleep(ms: number): Promise<void>;
|
|
100
|
+
/**
|
|
101
|
+
* Retry a function with exponential backoff.
|
|
102
|
+
*
|
|
103
|
+
* Retries the function until it succeeds or max attempts are reached.
|
|
104
|
+
*
|
|
105
|
+
* @param options - Retry options
|
|
106
|
+
* @returns Promise with function result
|
|
107
|
+
*
|
|
108
|
+
* @example Basic usage
|
|
109
|
+
* ```typescript
|
|
110
|
+
* const result = await retry({
|
|
111
|
+
* fn: async () => fetchData(),
|
|
112
|
+
* attempts: 3,
|
|
113
|
+
* delay: 1000,
|
|
114
|
+
* backoff: 'exponential'
|
|
115
|
+
* });
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* @example With retry condition
|
|
119
|
+
* ```typescript
|
|
120
|
+
* const result = await retry({
|
|
121
|
+
* fn: async () => fetchData(),
|
|
122
|
+
* attempts: 5,
|
|
123
|
+
* retryIf: (error) => error.code === 'ECONNRESET'
|
|
124
|
+
* });
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* @example Linear backoff
|
|
128
|
+
* ```typescript
|
|
129
|
+
* const result = await retry({
|
|
130
|
+
* fn: async () => fetchData(),
|
|
131
|
+
* attempts: 3,
|
|
132
|
+
* delay: 1000,
|
|
133
|
+
* backoff: 'linear'
|
|
134
|
+
* });
|
|
135
|
+
* // Waits 1000ms, 2000ms, 3000ms between retries
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
declare function retry<T>(options: RetryOptions<T>): Promise<T>;
|
|
139
|
+
/**
|
|
140
|
+
* Add timeout to a promise.
|
|
141
|
+
*
|
|
142
|
+
* Rejects with TimeoutError if promise doesn't resolve within specified time.
|
|
143
|
+
*
|
|
144
|
+
* @param promise - Promise to add timeout to
|
|
145
|
+
* @param ms - Timeout in milliseconds
|
|
146
|
+
* @returns Promise with timeout
|
|
147
|
+
*
|
|
148
|
+
* @example Basic usage
|
|
149
|
+
* ```typescript
|
|
150
|
+
* const data = await timeout(fetch('/api'), 5000);
|
|
151
|
+
* // Throws TimeoutError if takes > 5 seconds
|
|
152
|
+
* ```
|
|
153
|
+
*
|
|
154
|
+
* @example With error handling
|
|
155
|
+
* ```typescript
|
|
156
|
+
* try {
|
|
157
|
+
* const data = await timeout(fetch('/api'), 5000);
|
|
158
|
+
* } catch (error) {
|
|
159
|
+
* if (error instanceof TimeoutError) {
|
|
160
|
+
* console.error('Request timed out');
|
|
161
|
+
* } else {
|
|
162
|
+
* console.error('Request failed:', error);
|
|
163
|
+
* }
|
|
164
|
+
* }
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
declare function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
|
|
168
|
+
|
|
169
|
+
export { debounce, retry, sleep, throttle, timeout };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var UtilsError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(message, code) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "UtilsError";
|
|
7
|
+
this.code = code;
|
|
8
|
+
Error.captureStackTrace(this, this.constructor);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
var TimeoutError = class extends UtilsError {
|
|
12
|
+
constructor(ms) {
|
|
13
|
+
super(`Operation timed out after ${ms}ms`, "TIMEOUT");
|
|
14
|
+
this.name = "TimeoutError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var MaxRetriesExceededError = class extends UtilsError {
|
|
18
|
+
constructor(attempts) {
|
|
19
|
+
super(`Maximum retry attempts (${attempts}) exceeded`, "MAX_RETRIES_EXCEEDED");
|
|
20
|
+
this.name = "MaxRetriesExceededError";
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// src/plugins/optional/async.ts
|
|
25
|
+
function debounce(fn, wait, options = {}) {
|
|
26
|
+
let timeoutId;
|
|
27
|
+
let lastArgs;
|
|
28
|
+
let lastThis;
|
|
29
|
+
let result;
|
|
30
|
+
const { leading = false, trailing = true } = options;
|
|
31
|
+
const invoke = () => {
|
|
32
|
+
if (lastArgs) {
|
|
33
|
+
result = fn.apply(lastThis, lastArgs);
|
|
34
|
+
lastArgs = void 0;
|
|
35
|
+
lastThis = void 0;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const debounced = function(...args) {
|
|
39
|
+
lastArgs = args;
|
|
40
|
+
lastThis = this;
|
|
41
|
+
const shouldCallLeading = leading && !timeoutId;
|
|
42
|
+
if (timeoutId) {
|
|
43
|
+
clearTimeout(timeoutId);
|
|
44
|
+
}
|
|
45
|
+
if (shouldCallLeading) {
|
|
46
|
+
invoke();
|
|
47
|
+
}
|
|
48
|
+
timeoutId = setTimeout(() => {
|
|
49
|
+
if (trailing && !shouldCallLeading) {
|
|
50
|
+
invoke();
|
|
51
|
+
}
|
|
52
|
+
timeoutId = void 0;
|
|
53
|
+
}, wait);
|
|
54
|
+
};
|
|
55
|
+
debounced.cancel = () => {
|
|
56
|
+
clearTimeout(timeoutId);
|
|
57
|
+
timeoutId = void 0;
|
|
58
|
+
lastArgs = void 0;
|
|
59
|
+
lastThis = void 0;
|
|
60
|
+
};
|
|
61
|
+
debounced.flush = () => {
|
|
62
|
+
if (timeoutId) {
|
|
63
|
+
clearTimeout(timeoutId);
|
|
64
|
+
invoke();
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
};
|
|
68
|
+
debounced.pending = () => {
|
|
69
|
+
return timeoutId !== void 0;
|
|
70
|
+
};
|
|
71
|
+
return debounced;
|
|
72
|
+
}
|
|
73
|
+
function throttle(fn, wait, options = {}) {
|
|
74
|
+
const { leading = true, trailing = true } = options;
|
|
75
|
+
let lastCallTime = Date.now();
|
|
76
|
+
let timeoutId;
|
|
77
|
+
let lastArgs;
|
|
78
|
+
let lastThis;
|
|
79
|
+
let firstCall = true;
|
|
80
|
+
const throttled = function(...args) {
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
const remaining = wait - (now - lastCallTime);
|
|
83
|
+
lastArgs = args;
|
|
84
|
+
lastThis = this;
|
|
85
|
+
if (firstCall) {
|
|
86
|
+
firstCall = false;
|
|
87
|
+
if (leading) {
|
|
88
|
+
lastCallTime = now;
|
|
89
|
+
fn.apply(this, args);
|
|
90
|
+
lastArgs = void 0;
|
|
91
|
+
lastThis = void 0;
|
|
92
|
+
} else if (trailing) {
|
|
93
|
+
timeoutId = setTimeout(() => {
|
|
94
|
+
lastCallTime = Date.now();
|
|
95
|
+
if (lastArgs) {
|
|
96
|
+
fn.apply(lastThis, lastArgs);
|
|
97
|
+
lastArgs = void 0;
|
|
98
|
+
lastThis = void 0;
|
|
99
|
+
}
|
|
100
|
+
timeoutId = void 0;
|
|
101
|
+
}, wait);
|
|
102
|
+
}
|
|
103
|
+
} else if (remaining <= 0 || remaining > wait) {
|
|
104
|
+
if (timeoutId) {
|
|
105
|
+
clearTimeout(timeoutId);
|
|
106
|
+
timeoutId = void 0;
|
|
107
|
+
}
|
|
108
|
+
lastCallTime = now;
|
|
109
|
+
fn.apply(this, args);
|
|
110
|
+
lastArgs = void 0;
|
|
111
|
+
lastThis = void 0;
|
|
112
|
+
} else if (!timeoutId && trailing) {
|
|
113
|
+
timeoutId = setTimeout(() => {
|
|
114
|
+
lastCallTime = Date.now();
|
|
115
|
+
if (lastArgs) {
|
|
116
|
+
fn.apply(lastThis, lastArgs);
|
|
117
|
+
lastArgs = void 0;
|
|
118
|
+
lastThis = void 0;
|
|
119
|
+
}
|
|
120
|
+
timeoutId = void 0;
|
|
121
|
+
}, remaining);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
throttled.cancel = () => {
|
|
125
|
+
clearTimeout(timeoutId);
|
|
126
|
+
timeoutId = void 0;
|
|
127
|
+
lastArgs = void 0;
|
|
128
|
+
lastThis = void 0;
|
|
129
|
+
};
|
|
130
|
+
throttled.pending = () => {
|
|
131
|
+
return timeoutId !== void 0;
|
|
132
|
+
};
|
|
133
|
+
return throttled;
|
|
134
|
+
}
|
|
135
|
+
function sleep(ms) {
|
|
136
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
137
|
+
}
|
|
138
|
+
async function retry(options) {
|
|
139
|
+
const { fn, attempts = 3, delay = 1e3, backoff = "exponential", retryIf } = options;
|
|
140
|
+
let lastError;
|
|
141
|
+
for (let i = 0; i < attempts; i++) {
|
|
142
|
+
try {
|
|
143
|
+
return await fn();
|
|
144
|
+
} catch (error) {
|
|
145
|
+
lastError = error;
|
|
146
|
+
if (retryIf && !retryIf(lastError)) {
|
|
147
|
+
throw lastError;
|
|
148
|
+
}
|
|
149
|
+
if (i < attempts - 1) {
|
|
150
|
+
let waitTime = delay;
|
|
151
|
+
if (backoff === "exponential") {
|
|
152
|
+
waitTime = delay * Math.pow(2, i);
|
|
153
|
+
} else if (backoff === "linear") {
|
|
154
|
+
waitTime = delay * (i + 1);
|
|
155
|
+
}
|
|
156
|
+
await sleep(waitTime);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
throw new MaxRetriesExceededError(attempts);
|
|
161
|
+
}
|
|
162
|
+
function timeout(promise, ms) {
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
const timer = setTimeout(() => {
|
|
165
|
+
reject(new TimeoutError(ms));
|
|
166
|
+
}, ms);
|
|
167
|
+
promise.then(
|
|
168
|
+
(value) => {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
resolve(value);
|
|
171
|
+
},
|
|
172
|
+
(error) => {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
reject(error);
|
|
175
|
+
}
|
|
176
|
+
);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export { debounce, retry, sleep, throttle, timeout };
|
|
181
|
+
//# sourceMappingURL=async.js.map
|
|
182
|
+
//# sourceMappingURL=async.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/plugins/optional/async.ts"],"names":[],"mappings":";AAGO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,IAAA;AAAA,EAEA,WAAA,CAAY,SAAiB,IAAA,EAAc;AACzC,IAAA,KAAA,CAAM,OAAO,CAA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Ae;AAC7B,UAAA,QAAA,GAAW,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAA;AAAA,QAClC,CAAA,MAAA,IAAW,YAAY,QAAA,EAAU;AAC/B,UAAA,QAAA,GAAW,SAAS,CAAA,GAAI,CAAA,CAAA;AAAA,QAC1B;AAEA,QAAA,MAAM,MAAM,QAAQ,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,EAAA,MAAM,IAAI,wBAAwB,QAAQ,CAAA;AAC5C;AA8BO,SAAS,OAAA,CAAW,SAAqB,EAAA,EAAwB;AACtE,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,CAAO,IAAI,YAAA,CAAa,EAAE,CAAC,CAAA;AAAA,IAC7B,GAAG,EAAE,CAAA;AAEL,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,MACf,CAAA;AAAA,MACA,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,MAAA,CAAO,KAAK,CAAA;AAAA,MACd;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH","file":"async.js","sourcesContent":["/**\n * Base error class for all @oxog/utils errors.\n */\nexport class UtilsError extends Error {\n code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = 'UtilsError';\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Error thrown when an invalid path is provided to get/set/has functions.\n */\nexport class InvalidPathError extends UtilsError {\n constructor(path: string) {\n super(`Invalid path: ${path}`, 'INVALID_PATH');\n this.name = 'InvalidPathError';\n }\n}\n\n/**\n * Error thrown when a circular reference is detected during deep operations.\n */\nexport class CircularReferenceError extends UtilsError {\n constructor() {\n super('Circular reference detected', 'CIRCULAR_REF');\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Error thrown when an operation times out.\n */\nexport class TimeoutError extends UtilsError {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`, 'TIMEOUT');\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Error thrown when a plugin is already registered.\n */\nexport class PluginAlreadyRegisteredError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" already registered`, 'PLUGIN_ALREADY_REGISTERED');\n this.name = 'PluginAlreadyRegisteredError';\n }\n}\n\n/**\n * Error thrown when a requested plugin is not found.\n */\nexport class PluginNotFoundError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" not found`, 'PLUGIN_NOT_FOUND');\n this.name = 'PluginNotFoundError';\n }\n}\n\n/**\n * Error thrown when a plugin dependency is missing.\n */\nexport class PluginDependencyMissingError extends UtilsError {\n constructor(plugin: string, dependency: string) {\n super(`Plugin \"${plugin}\" requires \"${dependency}\" to be registered first`, 'PLUGIN_DEPENDENCY_MISSING');\n this.name = 'PluginDependencyMissingError';\n }\n}\n\n/**\n * Error thrown when retry attempts are exhausted.\n */\nexport class MaxRetriesExceededError extends UtilsError {\n constructor(attempts: number) {\n super(`Maximum retry attempts (${attempts}) exceeded`, 'MAX_RETRIES_EXCEEDED');\n this.name = 'MaxRetriesExceededError';\n }\n}\n","import { DebounceOptions, RetryOptions } from '../../types.js';\nimport { TimeoutError, MaxRetriesExceededError } from '../../errors.js';\n\ninterface DebouncedFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n flush: () => ReturnType<T>;\n pending: () => boolean;\n}\n\n/**\n * Debounce function execution.\n *\n * Delays function execution until after `wait` milliseconds have elapsed\n * since the last time the debounced function was invoked.\n *\n * @param fn - Function to debounce\n * @param wait - Wait time in milliseconds\n * @param options - Debounce options\n * @returns Debounced function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * // save() will be called 300ms after last call\n * ```\n *\n * @example With control methods\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * debouncedSave.cancel(); // Cancel pending execution\n * debouncedSave.flush(); // Execute immediately\n * debouncedSave.pending(); // Check if pending\n * ```\n *\n * @example Leading edge\n * ```typescript\n * const debounced = debounce(fn, 300, { leading: true });\n * debounced(); // Executes immediately on first call\n * ```\n */\nexport function debounce<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: DebounceOptions = {}\n): DebouncedFunction<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let result: ReturnType<T>;\n\n const { leading = false, trailing = true } = options;\n\n const invoke = () => {\n if (lastArgs) {\n result = fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const debounced = function (this: any, ...args: Parameters<T>) {\n lastArgs = args;\n lastThis = this;\n\n const shouldCallLeading = leading && !timeoutId;\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (shouldCallLeading) {\n invoke();\n }\n\n timeoutId = setTimeout(() => {\n if (trailing && !shouldCallLeading) {\n invoke();\n }\n timeoutId = undefined;\n }, wait);\n } as DebouncedFunction<T>;\n\n debounced.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n debounced.flush = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n invoke();\n }\n return result;\n };\n\n debounced.pending = () => {\n return timeoutId !== undefined;\n };\n\n return debounced;\n}\n\n/**\n * Throttle function execution.\n *\n * Ensures function is called at most once every `wait` milliseconds.\n *\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const throttledScroll = throttle(onScroll, 100);\n * window.addEventListener('scroll', throttledScroll);\n * // onScroll will be called at most once every 100ms\n * ```\n *\n * @example With control methods\n * ```typescript\n * const throttled = throttle(fn, 100);\n * throttled.cancel(); // Cancel pending execution\n * throttled.pending(); // Check if pending\n * ```\n */\ninterface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n pending: () => boolean;\n}\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: { leading?: boolean; trailing?: boolean } = {}\n): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let lastCallTime = Date.now(); // Initialize to current time\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let firstCall = true;\n\n const throttled = function (this: any, ...args: Parameters<T>) {\n const now = Date.now();\n const remaining = wait - (now - lastCallTime);\n\n lastArgs = args;\n lastThis = this;\n\n if (firstCall) {\n firstCall = false;\n if (leading) {\n // Execute immediately on first call\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (trailing) {\n // Schedule trailing call\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, wait);\n }\n } else if (remaining <= 0 || remaining > wait) {\n // Leading edge after throttle period - execute immediately\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (!timeoutId && trailing) {\n // Trailing edge - schedule execution\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, remaining);\n }\n } as ThrottledFunction<T>;\n\n throttled.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n throttled.pending = () => {\n return timeoutId !== undefined;\n };\n\n return throttled;\n}\n\n/**\n * Sleep for specified milliseconds.\n *\n * Returns a promise that resolves after the specified delay.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after delay\n *\n * @example Basic usage\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * console.log('Done!');\n * ```\n *\n * @example In async function\n * ```typescript\n * async function process() {\n * console.log('Start');\n * await sleep(1000);\n * console.log('After 1 second');\n * }\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * Retries the function until it succeeds or max attempts are reached.\n *\n * @param options - Retry options\n * @returns Promise with function result\n *\n * @example Basic usage\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'exponential'\n * });\n * ```\n *\n * @example With retry condition\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 5,\n * retryIf: (error) => error.code === 'ECONNRESET'\n * });\n * ```\n *\n * @example Linear backoff\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'linear'\n * });\n * // Waits 1000ms, 2000ms, 3000ms between retries\n * ```\n */\nexport async function retry<T>(options: RetryOptions<T>): Promise<T> {\n const { fn, attempts = 3, delay = 1000, backoff = 'exponential', retryIf } = options;\n\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n if (retryIf && !retryIf(lastError)) {\n throw lastError;\n }\n\n if (i < attempts - 1) {\n let waitTime = delay;\n\n if (backoff === 'exponential') {\n waitTime = delay * Math.pow(2, i);\n } else if (backoff === 'linear') {\n waitTime = delay * (i + 1);\n }\n\n await sleep(waitTime);\n }\n }\n }\n\n throw new MaxRetriesExceededError(attempts);\n}\n\n/**\n * Add timeout to a promise.\n *\n * Rejects with TimeoutError if promise doesn't resolve within specified time.\n *\n * @param promise - Promise to add timeout to\n * @param ms - Timeout in milliseconds\n * @returns Promise with timeout\n *\n * @example Basic usage\n * ```typescript\n * const data = await timeout(fetch('/api'), 5000);\n * // Throws TimeoutError if takes > 5 seconds\n * ```\n *\n * @example With error handling\n * ```typescript\n * try {\n * const data = await timeout(fetch('/api'), 5000);\n * } catch (error) {\n * if (error instanceof TimeoutError) {\n * console.error('Request timed out');\n * } else {\n * console.error('Request failed:', error);\n * }\n * }\n * ```\n */\nexport function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new TimeoutError(ms));\n }, ms);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n}\n"]}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/plugins/optional/deep.ts
|
|
4
|
+
function cloneDeep(obj, seen = /* @__PURE__ */ new WeakMap()) {
|
|
5
|
+
if (obj === null || typeof obj !== "object") {
|
|
6
|
+
return obj;
|
|
7
|
+
}
|
|
8
|
+
if (seen.has(obj)) {
|
|
9
|
+
return seen.get(obj);
|
|
10
|
+
}
|
|
11
|
+
if (obj instanceof Date) {
|
|
12
|
+
const clone2 = new Date(obj.getTime());
|
|
13
|
+
seen.set(obj, clone2);
|
|
14
|
+
return clone2;
|
|
15
|
+
}
|
|
16
|
+
if (obj instanceof RegExp) {
|
|
17
|
+
const clone2 = new RegExp(obj.source, obj.flags);
|
|
18
|
+
seen.set(obj, clone2);
|
|
19
|
+
return clone2;
|
|
20
|
+
}
|
|
21
|
+
if (obj instanceof Map) {
|
|
22
|
+
const clone2 = /* @__PURE__ */ new Map();
|
|
23
|
+
seen.set(obj, clone2);
|
|
24
|
+
for (const [key, value] of obj) {
|
|
25
|
+
clone2.set(cloneDeep(key, seen), cloneDeep(value, seen));
|
|
26
|
+
}
|
|
27
|
+
return clone2;
|
|
28
|
+
}
|
|
29
|
+
if (obj instanceof Set) {
|
|
30
|
+
const clone2 = /* @__PURE__ */ new Set();
|
|
31
|
+
seen.set(obj, clone2);
|
|
32
|
+
for (const value of obj) {
|
|
33
|
+
clone2.add(cloneDeep(value, seen));
|
|
34
|
+
}
|
|
35
|
+
return clone2;
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(obj)) {
|
|
38
|
+
const clone2 = [];
|
|
39
|
+
seen.set(obj, clone2);
|
|
40
|
+
for (let i = 0; i < obj.length; i++) {
|
|
41
|
+
clone2[i] = cloneDeep(obj[i], seen);
|
|
42
|
+
}
|
|
43
|
+
return clone2;
|
|
44
|
+
}
|
|
45
|
+
const clone = {};
|
|
46
|
+
seen.set(obj, clone);
|
|
47
|
+
for (const key in obj) {
|
|
48
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
49
|
+
clone[key] = cloneDeep(obj[key], seen);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return clone;
|
|
53
|
+
}
|
|
54
|
+
function mergeDeep(target, ...sources) {
|
|
55
|
+
const DANGEROUS_KEYS = ["__proto__", "constructor", "prototype"];
|
|
56
|
+
const result = cloneDeep(target);
|
|
57
|
+
for (const source of sources) {
|
|
58
|
+
if (!source || typeof source !== "object") continue;
|
|
59
|
+
for (const key of Object.keys(source)) {
|
|
60
|
+
if (DANGEROUS_KEYS.includes(key)) continue;
|
|
61
|
+
const sourceValue = source[key];
|
|
62
|
+
const targetValue = result[key];
|
|
63
|
+
if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
|
|
64
|
+
result[key] = mergeDeep(targetValue, sourceValue);
|
|
65
|
+
} else {
|
|
66
|
+
result[key] = cloneDeep(sourceValue);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
function isEqual(a, b) {
|
|
73
|
+
if (a === b) return true;
|
|
74
|
+
if (Number.isNaN(a) && Number.isNaN(b)) return true;
|
|
75
|
+
if (a == null || b == null) return false;
|
|
76
|
+
if (typeof a !== typeof b) return false;
|
|
77
|
+
if (typeof a !== "object") return false;
|
|
78
|
+
if (a instanceof Date && b instanceof Date) {
|
|
79
|
+
return a.getTime() === b.getTime();
|
|
80
|
+
}
|
|
81
|
+
if (a instanceof RegExp && b instanceof RegExp) {
|
|
82
|
+
return a.source === b.source && a.flags === b.flags;
|
|
83
|
+
}
|
|
84
|
+
if (a instanceof Map && b instanceof Map) {
|
|
85
|
+
if (a.size !== b.size) return false;
|
|
86
|
+
for (const [key, value] of a) {
|
|
87
|
+
if (!b.has(key) || !isEqual(value, b.get(key))) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
if (a instanceof Set && b instanceof Set) {
|
|
94
|
+
if (a.size !== b.size) return false;
|
|
95
|
+
for (const value of a) {
|
|
96
|
+
if (!b.has(value)) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
103
|
+
if (a.length !== b.length) return false;
|
|
104
|
+
return a.every((item, index) => isEqual(item, b[index]));
|
|
105
|
+
}
|
|
106
|
+
if (typeof a === "object" && typeof b === "object") {
|
|
107
|
+
const keysA = Object.keys(a);
|
|
108
|
+
const keysB = Object.keys(b);
|
|
109
|
+
if (keysA.length !== keysB.length) return false;
|
|
110
|
+
for (const key of keysA) {
|
|
111
|
+
if (!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key])) {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
function diff(a, b) {
|
|
120
|
+
const result = {
|
|
121
|
+
changed: {},
|
|
122
|
+
added: {},
|
|
123
|
+
removed: {}
|
|
124
|
+
};
|
|
125
|
+
const keysA = Object.keys(a);
|
|
126
|
+
const keysB = Object.keys(b);
|
|
127
|
+
const allKeys = Array.from(/* @__PURE__ */ new Set([...keysA, ...keysB]));
|
|
128
|
+
for (const key of allKeys) {
|
|
129
|
+
const valueA = a[key];
|
|
130
|
+
const valueB = b[key];
|
|
131
|
+
const hasA = Object.prototype.hasOwnProperty.call(a, key);
|
|
132
|
+
const hasB = Object.prototype.hasOwnProperty.call(b, key);
|
|
133
|
+
if (!hasA && hasB) {
|
|
134
|
+
result.added[key] = valueB;
|
|
135
|
+
} else if (hasA && !hasB) {
|
|
136
|
+
result.removed[key] = valueA;
|
|
137
|
+
} else if (!isEqual(valueA, valueB)) {
|
|
138
|
+
if (typeof valueA === "object" && valueA !== null && typeof valueB === "object" && valueB !== null) {
|
|
139
|
+
const nestedDiff = diff(valueA, valueB);
|
|
140
|
+
const nestedChanged = nestedDiff.changed || {};
|
|
141
|
+
if (Object.keys(nestedChanged).length > 0) {
|
|
142
|
+
result.changed[key] = nestedChanged;
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
result.changed[key] = { from: valueA, to: valueB };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
exports.cloneDeep = cloneDeep;
|
|
153
|
+
exports.diff = diff;
|
|
154
|
+
exports.isEqual = isEqual;
|
|
155
|
+
exports.mergeDeep = mergeDeep;
|
|
156
|
+
//# sourceMappingURL=deep.cjs.map
|
|
157
|
+
//# sourceMappingURL=deep.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/optional/deep.ts"],"names":["clone"],"mappings":";;;AAyCO,SAAS,SAAA,CAAa,GAAA,EAAQ,I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AU,cAAA,CAAe,IAAA,CAAK,GAAG,GAAG,CAAA;AAExD,IAAA,IAAI,CAAC,QAAQ,IAAA,EAAM;AACjB,MAAC,MAAA,CAAO,KAAA,CAAc,GAAG,CAAA,GAAI,MAAA;AAAA,IAC/B,CAAA,MAAA,IAAW,IAAA,IAAQ,CAAC,IAAA,EAAM;AACxB,MAAC,MAAA,CAAO,OAAA,CAAgB,GAAG,CAAA,GAAI,MAAA;AAAA,IACjC,CAAA,MAAA,IAAW,CAAC,OAAA,CAAQ,MAAA,EAAQ,MAAM,CAAA,EAAG;AACnC,MAAA,IACE,OAAO,WAAW,QAAA,IAClB,MAAA,KAAW,QACX,OAAO,MAAA,KAAW,QAAA,IAClB,MAAA,KAAW,IAAA,EACX;AACA,QAAA,MAAM,UAAA,GAAa,IAAA,CAAK,MAAA,EAAkB,MAAgB,CAAA;AAE1D,QAAA,MAAM,aAAA,GAAgB,UAAA,CAAW,OAAA,IAAW,EAAC;AAC7C,QAAA,IAAI,MAAA,CAAO,IAAA,CAAK,aAAa,CAAA,CAAE,SAAS,CAAA,EAAG;AACzC,UAAC,MAAA,CAAO,OAAA,CAAgB,GAAG,CAAA,GAAI,aAAA;AAAA,QACjC;AAAA,MACF,CAAA,MAAO;AACL,QAAC,MAAA,CAAO,QAAgB,GAAG,CAAA,GAAI,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAI,MAAA,EAAO;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT","file":"deep.cjs","sourcesContent":["import { DiffResult } from '../../types.js';\n\n/**\n * Deep clone an object with circular reference support.\n *\n * Creates a deep copy of an object, handling circular references,\n * Date, RegExp, Map, Set, and other special types.\n *\n * @param obj - Object to clone\n * @returns Deep cloned object\n *\n * @example Basic usage\n * ```typescript\n * const obj = { a: 1, b: { c: 2 } };\n * const clone = cloneDeep(obj);\n * console.log(clone === obj); // false (different references)\n * console.log(clone.b === obj.b); // false (deep clone)\n * ```\n *\n * @example Circular reference handling\n * ```typescript\n * const obj = { a: 1 };\n * obj.self = obj; // circular!\n * const clone = cloneDeep(obj); // Works! No infinite loop\n * ```\n *\n * @example Special types\n * ```typescript\n * const obj = {\n * date: new Date(),\n * regex: /test/g,\n * map: new Map([['key', 'value']]),\n * set: new Set([1, 2, 3])\n * };\n * const clone = cloneDeep(obj);\n * console.log(clone.date instanceof Date); // true\n * console.log(clone.regex instanceof RegExp); // true\n * console.log(clone.map instanceof Map); // true\n * console.log(clone.set instanceof Set); // true\n * ```\n */\nexport function cloneDeep<T>(obj: T, seen = new WeakMap<object, any>()): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (seen.has(obj)) {\n return seen.get(obj);\n }\n\n if (obj instanceof Date) {\n const clone = new Date(obj.getTime());\n seen.set(obj, clone);\n return clone as T;\n }\n\n if (obj instanceof RegExp) {\n const clone = new RegExp(obj.source, obj.flags);\n seen.set(obj, clone);\n return clone as T;\n }\n\n if (obj instanceof Map) {\n const clone = new Map();\n seen.set(obj, clone);\n for (const [key, value] of obj) {\n clone.set(cloneDeep(key, seen), cloneDeep(value, seen));\n }\n return clone as T;\n }\n\n if (obj instanceof Set) {\n const clone = new Set();\n seen.set(obj, clone);\n for (const value of obj) {\n clone.add(cloneDeep(value, seen));\n }\n return clone as T;\n }\n\n if (Array.isArray(obj)) {\n const clone = [] as any;\n seen.set(obj, clone);\n for (let i = 0; i < obj.length; i++) {\n clone[i] = cloneDeep(obj[i], seen);\n }\n return clone;\n }\n\n const clone = {} as any;\n seen.set(obj, clone);\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = cloneDeep(obj[key], seen);\n }\n }\n\n return clone;\n}\n\n/**\n * Deep merge objects with prototype pollution protection.\n *\n * Recursively merges sources into target, creating new objects for nested structures.\n * Prototype pollution protection: filters out __proto__, constructor, prototype.\n *\n * @param target - Target object\n * @param sources - Source objects to merge\n * @returns Deep merged object\n *\n * @example Basic usage\n * ```typescript\n * const target = { a: { b: 1, c: 1 } };\n * const source = { a: { b: 2, d: 2 }, e: 3 };\n * mergeDeep(target, source);\n * // { a: { b: 2, c: 1, d: 2 }, e: 3 }\n * ```\n *\n * @example Prototype pollution protection\n * ```typescript\n * mergeDeep({}, { a: { __proto__: { evil: true } } }); // { a: {} }\n * mergeDeep({}, { __proto__: { evil: true } }); // {}\n * ```\n *\n * @example Multiple sources\n * ```typescript\n * mergeDeep(\n * { a: { b: 1 } },\n * { a: { c: 2 } },\n * { a: { d: 3 } }\n * );\n * // { a: { b: 1, c: 2, d: 3 } }\n * ```\n */\nexport function mergeDeep<T extends object>(target: T, ...sources: Partial<T>[]): T {\n const DANGEROUS_KEYS = ['__proto__', 'constructor', 'prototype'];\n\n const result = cloneDeep(target);\n\n for (const source of sources) {\n if (!source || typeof source !== 'object') continue;\n\n for (const key of Object.keys(source)) {\n if (DANGEROUS_KEYS.includes(key)) continue;\n\n const sourceValue = (source as any)[key];\n const targetValue = (result as any)[key];\n\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n (result as any)[key] = mergeDeep(targetValue, sourceValue);\n } else {\n (result as any)[key] = cloneDeep(sourceValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Deep equality comparison.\n *\n * Recursively compares two values for deep equality.\n * Handles objects, arrays, Date, RegExp, Map, Set, and primitives.\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns True if values are deeply equal\n *\n * @example Primitives\n * ```typescript\n * isEqual(1, 1); // true\n * isEqual('hello', 'hello'); // true\n * isEqual(true, true); // true\n * isEqual(1, '1'); // false\n * ```\n *\n * @example Arrays\n * ```typescript\n * isEqual([1, 2, 3], [1, 2, 3]); // true\n * isEqual([1, 2, 3], [1, 2, 4]); // false\n * isEqual([1, [2, 3]], [1, [2, 3]]); // true\n * ```\n *\n * @example Objects\n * ```typescript\n * isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true\n * isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true (order doesn't matter)\n * isEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false\n * isEqual({ a: { b: 1 } }, { a: { b: 1 } }); // true\n * ```\n *\n * @example Special types\n * ```typescript\n * isEqual(new Date('2024-01-01'), new Date('2024-01-01')); // true\n * isEqual(/test/g, /test/g); // true\n * isEqual(new Set([1, 2]), new Set([1, 2])); // true\n * isEqual(new Map([['a', 1]]), new Map([['a', 1]])); // true\n * ```\n *\n * @example NaN handling\n * ```typescript\n * isEqual(NaN, NaN); // true\n * ```\n */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n\n // Handle NaN: NaN !== NaN, but we want them to be equal\n if (Number.isNaN(a) && Number.isNaN(b)) return true;\n\n if (a == null || b == null) return false;\n\n if (typeof a !== typeof b) return false;\n\n if (typeof a !== 'object') return false;\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.source === b.source && a.flags === b.flags;\n }\n\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (const [key, value] of a) {\n if (!b.has(key) || !isEqual(value, b.get(key))) {\n return false;\n }\n }\n return true;\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) {\n return false;\n }\n }\n return true;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => isEqual(item, b[index]));\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n const keysA = Object.keys(a as object);\n const keysB = Object.keys(b as object);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !isEqual((a as any)[key], (b as any)[key])\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Get differences between two objects.\n *\n * Compares two objects and returns a summary of changes.\n *\n * @param a - First object\n * @param b - Second object\n * @returns Diff result with changed, added, and removed properties\n *\n * @example Basic usage\n * ```typescript\n * diff({ a: 1, b: 2 }, { a: 1, b: 3, c: 4 });\n * // { changed: { b: { from: 2, to: 3 } }, added: { c: 4 }, removed: {} }\n * ```\n *\n * @example Complex object\n * ```typescript\n * diff(\n * { user: { name: 'Alice', age: 30 } },\n * { user: { name: 'Alice', age: 31 }, role: 'admin' }\n * );\n * // { changed: { user: { age: { from: 30, to: 31 } } }, added: { role: 'admin' }, removed: {} }\n * ```\n *\n * @example Removed properties\n * ```typescript\n * diff({ a: 1, b: 2, c: 3 }, { a: 1 });\n * // { changed: {}, added: {}, removed: { b: 2, c: 3 } }\n * ```\n */\nexport function diff<T extends object>(a: T, b: Partial<T>): DiffResult {\n const result: DiffResult = {\n changed: {},\n added: {},\n removed: {}\n };\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n const allKeys = Array.from(new Set([...keysA, ...keysB]));\n\n for (const key of allKeys) {\n const valueA = a[key as keyof T];\n const valueB = b[key as keyof T];\n\n const hasA = Object.prototype.hasOwnProperty.call(a, key);\n const hasB = Object.prototype.hasOwnProperty.call(b, key);\n\n if (!hasA && hasB) {\n (result.added as any)[key] = valueB;\n } else if (hasA && !hasB) {\n (result.removed as any)[key] = valueA;\n } else if (!isEqual(valueA, valueB)) {\n if (\n typeof valueA === 'object' &&\n valueA !== null &&\n typeof valueB === 'object' &&\n valueB !== null\n ) {\n const nestedDiff = diff(valueA as object, valueB as object);\n // For nested diffs, only include 'changed' property (not added/removed)\n const nestedChanged = nestedDiff.changed || {};\n if (Object.keys(nestedChanged).length > 0) {\n (result.changed as any)[key] = nestedChanged;\n }\n } else {\n (result.changed as any)[key] = { from: valueA, to: valueB };\n }\n }\n }\n\n return result;\n}\n"]}
|