maraj 2.8.4 → 2.9.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/dist/index.d.mts CHANGED
@@ -1,78 +1,18 @@
1
- /** Returns only the optional keys of an object. */
2
- type OptionalKeys<T> = {
3
- [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
4
- }[keyof T];
5
- /** Removes properties or indexes, order doesn't matter. */
6
- type Remove = <T extends Record<PropertyKey, any>>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
7
- /**
8
- * Removes properties or indexes, order doesn't matter.
9
- * @param value Object/array from where to remove keys/indexes shallowly.
10
- * @param keys Keys to remove.
11
- * @returns New object/array without the provided keys/indexes.
12
- */
13
- declare const remove: Remove;
14
-
15
- /** Index literal type to improve DX at managing updates. */
16
- declare const LITERAL_INDEX = "${number}";
17
- type LiteralIndex = typeof LITERAL_INDEX;
18
- type OptionValues = 'error' | 'skip' | 'add';
19
- type Options = {
20
- onNewProps?: OptionValues;
21
- onNewIndexes?: OptionValues;
22
- onPathsIntersectedByPrimitiveValues?: OptionValues;
23
- };
24
- type ImmutableUpdate = <TObject, TAllowedDotPathKeys extends DotPaths<TObject> = DotPaths<TObject>>(state: TObject, dotPathUpdateObject: UpdateObject<TObject, TAllowedDotPathKeys>, options?: Options) => TObject;
25
- /**
26
- * Creates a new object applying immutable updates using dot-path syntax.
27
- * Can add or skip new props or indexes depending on options.
28
- * TYPESCRIPT: Dot-Path Update Object type must STRICTLY match the type of state.
29
- * @param state Original State Object.
30
- * @param dotPathUpdateObject Dot Path Update Object.
31
- * @param options Options to change JS behaviour on non-existent fields.
32
- * @returns New Updated Object.
33
- */
34
- declare const update: ImmutableUpdate;
35
- type ExtendableImmutableUpdate = <TObject, TUpdateObject extends UpdateObject<TObject> = UpdateObject<TObject>>(state: TObject, dotPathUpdateObject: TUpdateObject) => ExtendedUpdate<TObject, TUpdateObject>;
36
- /**
37
- * Creates a new object applying immutable updates using dot-path syntax.
38
- * It will always add non-existent props or indexes if provided.
39
- * TYPESCRIPT: Dot-Path Update Object type extends from the type of state and you can add new non-existent properties.
40
- * @param state Original State Object.
41
- * @param dotPathUpdateObject Dot Path Update Object.
42
- * @returns New Updated Object.
43
- */
44
- declare const experimental_extendableUpdate: ExtendableImmutableUpdate;
45
-
46
1
  /**
47
2
  * --------------------------------------------
48
- * UTILITIES
49
- * --------------------------------------------
50
- */
51
- /** Primitives and browser native objects. */
52
- type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
53
- /** Array indexes type. */
54
- type ArrayIndexes = number | `${number}` | LiteralIndex;
55
- /** To check if a ReadonlyArray is a tuple or not. */
56
- type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
57
- /**
58
- * --------------------------------------------
59
- * DOT PATH IMPLEMENTATION
3
+ * DOT PATHS IMPLEMENTATION
60
4
  * --------------------------------------------
61
5
  */
62
6
  /** Dot-paths of an array. */
63
- type ArrayPaths<TInnerType, TAllowedTypes> = TInnerType extends TAllowedTypes ? TInnerType extends PrimitivesAndNativeObjects ? ArrayIndexes : ArrayIndexes | `${ArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}` : `${ArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}`;
7
+ type ArrayPaths<TInnerType, TAllowedTypes> = TInnerType extends TAllowedTypes ? TInnerType extends PrimitivesAndNativeObjects ? ExtendedArrayIndexes : ExtendedArrayIndexes | `${ExtendedArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}` : `${ExtendedArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}`;
64
8
  /** Dot-paths of an object. */
65
9
  type ObjectPaths<T, TAllowedTypes> = {
66
10
  [Key in keyof T & (string | number)]: T[Key] extends TAllowedTypes ? T[Key] extends PrimitivesAndNativeObjects ? `${Key}` : `${Key}` | `${Key}.${DotPathsImplementation<T[Key], TAllowedTypes>}` : `${Key}.${DotPathsImplementation<T[Key], TAllowedTypes>}`;
67
- }[keyof T & (string | number)] & unknown;
11
+ }[keyof T & (string | number)] & {};
68
12
  /** Dot-paths of a tuple. */
69
- type TuplePaths<T, TAllowedTypes> = ObjectPaths<Omit<T, keyof any[]>, TAllowedTypes> & unknown;
13
+ type TuplePaths<T, TAllowedTypes> = ObjectPaths<Omit<T, keyof any[]>, TAllowedTypes> & {};
70
14
  /** Dot-paths implementation */
71
- type DotPathsImplementation<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? TuplePaths<T, TAllowedTypes> : ArrayPaths<U, TAllowedTypes> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TAllowedTypes>;
72
- /** Extract Keys from any kind of type, including objects, arrays, tuples. */
73
- type KeyOf<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? U extends TAllowedTypes ? IsTuple<T> extends true ? keyof Omit<T, keyof any[]> : ArrayIndexes : never : T extends PrimitivesAndNativeObjects ? never : {
74
- [Key in keyof T]: T[Key] extends TAllowedTypes ? Key : never;
75
- }[keyof T];
15
+ type DotPathsImplementation<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? T extends Tuple ? TuplePaths<T, TAllowedTypes> : ArrayPaths<U, TAllowedTypes> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TAllowedTypes>;
76
16
  /** Literal union of all posible dot-paths which satisfy provided types as second argument (default: any). */
77
17
  type DotPaths<T, TAllowedTypes = any> = KeyOf<T, TAllowedTypes> | DotPathsImplementation<T, TAllowedTypes>;
78
18
  /**
@@ -97,7 +37,7 @@ type ReturnedValueInPath<TObject, TPath> = TPath extends '' ? TObject : TPath ex
97
37
  /** Value of a dot-path update object, can be the value or a function. */
98
38
  type UpdateValue<TObject, TPath> = ValueInPath<TObject, TPath> extends never ? never : ValueInPath<TObject, TPath> | ((fieldValue: ValueInPath<TObject, TPath>) => ValueInPath<TObject, TPath>);
99
39
  /** Dot-path update object, used to give updates to the updateImmutably function. */
100
- type UpdateObject<TObject, TPaths extends PropertyKey = DotPaths<TObject>> = {
40
+ type UpdateObject<TObject, TPaths extends DotPaths<TObject> = DotPaths<TObject>> = {
101
41
  [Path in TPaths]?: UpdateValue<TObject, Path>;
102
42
  };
103
43
  /**
@@ -141,6 +81,54 @@ type ExtractTypeFromDotPathUpdateObject<T extends Record<string, any>> = T exten
141
81
  /** New expanded value after aplying updates including new properties */
142
82
  type ExtendedUpdate<TObject, TDotPathUpdateObject extends Record<PropertyKey, any>> = TObject extends Array<infer U> ? ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject> extends Array<infer W> ? Array<U | W> : TObject & ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject> : TObject & ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject>;
143
83
 
84
+ /** Index literal type to improve DX at managing updates. */
85
+ declare const LITERAL_INDEX = "${number}";
86
+
87
+ /** Primitives and browser native objects. */
88
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
89
+ /** Tuple type, it has to have at least property "0" */
90
+ type Tuple = ReadonlyArray<any> & {
91
+ "0": any;
92
+ };
93
+ /** Array indexes type. */
94
+ type LiteralIndex = typeof LITERAL_INDEX;
95
+ type ExtendedArrayIndexes = number | `${number}` | LiteralIndex;
96
+ /** Object Literal */
97
+ type ObjectLiteral = {
98
+ [x: string]: any;
99
+ [x: number]: any;
100
+ [x: symbol]: any;
101
+ [Symbol.iterator]?: never;
102
+ [Symbol.toPrimitive]?: never;
103
+ [Symbol.hasInstance]?: never;
104
+ [Symbol.unscopables]?: never;
105
+ [Symbol.matchAll]?: never;
106
+ };
107
+ /** Strict key */
108
+ declare const strictSymbol: unique symbol;
109
+ type Strict<T> = T extends ObjectLiteral ? T & {
110
+ [strictSymbol]: DotPaths<T>;
111
+ } : T;
112
+ /** Smart KeyOf (doesnt include the "strict" key) */
113
+ type KeyOf<T, TAllowedValuesInKeys = any> = T extends ObjectLiteral ? T extends Strict<infer U> ? KeysOfObject<U, TAllowedValuesInKeys> : KeysOfObject<T, TAllowedValuesInKeys> : T extends Tuple ? KeysOfObject<Omit<T, keyof any[]>, TAllowedValuesInKeys> : T extends ReadonlyArray<infer U> ? U extends TAllowedValuesInKeys ? ExtendedArrayIndexes : never : never;
114
+ type KeysOfObject<T, TAllowedValuesInKeys> = {
115
+ [Key in keyof T]: T[Key] extends TAllowedValuesInKeys ? Key : never;
116
+ }[keyof T];
117
+
118
+ /** Returns only the optional keys of an object. */
119
+ type OptionalKeys<T> = {
120
+ [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
121
+ }[keyof T];
122
+ /** Removes properties or indexes, order doesn't matter. */
123
+ type Remove = <T extends ObjectLiteral | any[]>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
124
+ /**
125
+ * Removes properties or indexes, order doesn't matter.
126
+ * @param value Object/array from where to remove keys/indexes shallowly.
127
+ * @param keys Keys to remove.
128
+ * @returns New object/array without the provided keys/indexes.
129
+ */
130
+ declare const remove: Remove;
131
+
144
132
  type Select = {
145
133
  <T, TPath extends DotPaths<T>>(state: T, path: TPath): ReturnedValueInPath<T, TPath>;
146
134
  <T, TPath extends ''>(state: T, path: TPath): T;
@@ -171,28 +159,51 @@ type Set = <T>(newValue: T) => (v: unknown) => T;
171
159
  */
172
160
  declare const set: Set;
173
161
 
174
- type Iterator = typeof Symbol.iterator;
175
- type HasInstance = typeof Symbol.hasInstance;
176
- type ToPrimitive = typeof Symbol.toPrimitive;
177
- type Unscopables = typeof Symbol.unscopables;
178
- type MatchAll = typeof Symbol.matchAll;
179
- type NonObjectLiteralKeys = Unscopables | HasInstance | ToPrimitive | MatchAll | Iterator;
180
- type ObjectLiteral = Record<PropertyKey, any> & {
181
- [K in NonObjectLiteralKeys]?: never;
162
+ type OptionValues = 'error' | 'skip' | 'add';
163
+ type Options = {
164
+ onNewProps?: OptionValues;
165
+ onNewIndexes?: OptionValues;
166
+ onPathsIntersectedByPrimitiveValues?: OptionValues;
182
167
  };
168
+ type ImmutableUpdate = <TObject, TAllowedDotPathKeys extends DotPaths<TObject> = DotPaths<TObject>>(state: TObject, dotPathUpdateObject: UpdateObject<TObject, TAllowedDotPathKeys>, options?: Options) => TObject;
169
+ /**
170
+ * Creates a new object applying immutable updates using dot-path syntax.
171
+ * Can add or skip new props or indexes depending on options.
172
+ * TYPESCRIPT: Dot-Path Update Object type must STRICTLY match the type of state.
173
+ * @param state Original State Object.
174
+ * @param dotPathUpdateObject Dot Path Update Object.
175
+ * @param options Options to change JS behaviour on non-existent fields.
176
+ * @returns New Updated Object.
177
+ */
178
+ declare const update: ImmutableUpdate;
179
+ type ExtendableImmutableUpdate = <TObject, TUpdateObject extends UpdateObject<TObject> = UpdateObject<TObject>>(state: TObject, dotPathUpdateObject: TUpdateObject) => ExtendedUpdate<TObject, TUpdateObject>;
180
+ /**
181
+ * Creates a new object applying immutable updates using dot-path syntax.
182
+ * It will always add non-existent props or indexes if provided.
183
+ * TYPESCRIPT: Dot-Path Update Object type extends from the type of state and you can add new non-existent properties.
184
+ * @param state Original State Object.
185
+ * @param dotPathUpdateObject Dot Path Update Object.
186
+ * @returns New Updated Object.
187
+ */
188
+ declare const experimental_extendableUpdate: ExtendableImmutableUpdate;
189
+
190
+ type ForEachEntry = <T extends ObjectLiteral>(object: T, callbackfn: (key: keyof T, value: T[keyof T]) => void) => void;
191
+ declare const forEachEntry: ForEachEntry;
192
+
183
193
  /** Checks if any provided value is an object literal or not */
184
- declare const isObjectLiteral: (valueToTest: unknown) => valueToTest is ObjectLiteral;
194
+ type IsObjectLiteral = (valueToTest: unknown) => valueToTest is ObjectLiteral;
195
+ declare const isObjectLiteral: IsObjectLiteral;
185
196
 
186
- declare const parseStringIndex: (v: string) => number | null;
187
- declare const isStringIndex: (v: string) => v is `${number}`;
197
+ /** Adds strict property to an object literal */
198
+ type StrictFn = <T>(value: T) => Strict<T>;
199
+ declare const s: StrictFn;
200
+ /** Checks the strictness of a type passed to a function or callback without 3rd party implementation */
201
+ type EnsureStrictness = <T extends U, U>(v: T extends U ? DotPaths<T> extends DotPaths<U> ? T : Exclude<DotPaths<T>, DotPaths<U>> : never) => U;
202
+ declare const ensureStrictness: EnsureStrictness;
188
203
 
189
- type StrictCallbackError = "CALLBACK STRICTNESS RETURN ERROR: return the value using the first parameter";
190
- type StrictCallbackValue<T> = [StrictCallbackError, T];
191
- type StrictCallbackFunction<T> = (v: T) => StrictCallbackValue<T>;
192
- /** Apply strictness to a callback function */
193
- type StrictCallback<T extends (...args: any[]) => any> = (r: StrictCallbackFunction<ReturnType<T>>, ...args: Parameters<T>) => [StrictCallbackError, ReturnType<T>];
194
- type UnsealStrictCallback = <TCallback extends (r: StrictCallbackFunction<any>, ...args: any[]) => any>(callback: TCallback) => (...args: Parameters<TCallback> extends [infer _, ...infer RestParams] ? RestParams : never) => ReturnType<TCallback>['1'];
195
- /** Extract the callback from */
196
- declare const unsealStrictCallback: UnsealStrictCallback;
204
+ type ParseStringIndex = (stringKey: string) => number | null;
205
+ declare const parseStringIndex: ParseStringIndex;
206
+ type IsStringIndex = (stringKey: string) => stringKey is `${number}`;
207
+ declare const isStringIndex: IsStringIndex;
197
208
 
198
- export { type DotPaths, type KeyOf, type LiteralIndex, type ObjectLiteral, type ReturnedValueInPath, type StrictCallback, type UpdateObject, type UpdateValue, type ValueInPath, experimental_extendableUpdate, isObjectLiteral, isStringIndex, parseStringIndex, remove, select, set, splitPathAtLastKey, unsealStrictCallback, update };
209
+ export { type DotPaths, type ExtendedArrayIndexes, type KeyOf, type LiteralIndex, type ObjectLiteral, type PrimitivesAndNativeObjects, type ReturnedValueInPath, type Strict, type Tuple, type UpdateObject, type UpdateValue, type ValueInPath, ensureStrictness, experimental_extendableUpdate, forEachEntry, isObjectLiteral, isStringIndex, parseStringIndex, remove, s, select, set, splitPathAtLastKey, update };
package/dist/index.d.ts CHANGED
@@ -1,78 +1,18 @@
1
- /** Returns only the optional keys of an object. */
2
- type OptionalKeys<T> = {
3
- [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
4
- }[keyof T];
5
- /** Removes properties or indexes, order doesn't matter. */
6
- type Remove = <T extends Record<PropertyKey, any>>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
7
- /**
8
- * Removes properties or indexes, order doesn't matter.
9
- * @param value Object/array from where to remove keys/indexes shallowly.
10
- * @param keys Keys to remove.
11
- * @returns New object/array without the provided keys/indexes.
12
- */
13
- declare const remove: Remove;
14
-
15
- /** Index literal type to improve DX at managing updates. */
16
- declare const LITERAL_INDEX = "${number}";
17
- type LiteralIndex = typeof LITERAL_INDEX;
18
- type OptionValues = 'error' | 'skip' | 'add';
19
- type Options = {
20
- onNewProps?: OptionValues;
21
- onNewIndexes?: OptionValues;
22
- onPathsIntersectedByPrimitiveValues?: OptionValues;
23
- };
24
- type ImmutableUpdate = <TObject, TAllowedDotPathKeys extends DotPaths<TObject> = DotPaths<TObject>>(state: TObject, dotPathUpdateObject: UpdateObject<TObject, TAllowedDotPathKeys>, options?: Options) => TObject;
25
- /**
26
- * Creates a new object applying immutable updates using dot-path syntax.
27
- * Can add or skip new props or indexes depending on options.
28
- * TYPESCRIPT: Dot-Path Update Object type must STRICTLY match the type of state.
29
- * @param state Original State Object.
30
- * @param dotPathUpdateObject Dot Path Update Object.
31
- * @param options Options to change JS behaviour on non-existent fields.
32
- * @returns New Updated Object.
33
- */
34
- declare const update: ImmutableUpdate;
35
- type ExtendableImmutableUpdate = <TObject, TUpdateObject extends UpdateObject<TObject> = UpdateObject<TObject>>(state: TObject, dotPathUpdateObject: TUpdateObject) => ExtendedUpdate<TObject, TUpdateObject>;
36
- /**
37
- * Creates a new object applying immutable updates using dot-path syntax.
38
- * It will always add non-existent props or indexes if provided.
39
- * TYPESCRIPT: Dot-Path Update Object type extends from the type of state and you can add new non-existent properties.
40
- * @param state Original State Object.
41
- * @param dotPathUpdateObject Dot Path Update Object.
42
- * @returns New Updated Object.
43
- */
44
- declare const experimental_extendableUpdate: ExtendableImmutableUpdate;
45
-
46
1
  /**
47
2
  * --------------------------------------------
48
- * UTILITIES
49
- * --------------------------------------------
50
- */
51
- /** Primitives and browser native objects. */
52
- type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
53
- /** Array indexes type. */
54
- type ArrayIndexes = number | `${number}` | LiteralIndex;
55
- /** To check if a ReadonlyArray is a tuple or not. */
56
- type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
57
- /**
58
- * --------------------------------------------
59
- * DOT PATH IMPLEMENTATION
3
+ * DOT PATHS IMPLEMENTATION
60
4
  * --------------------------------------------
61
5
  */
62
6
  /** Dot-paths of an array. */
63
- type ArrayPaths<TInnerType, TAllowedTypes> = TInnerType extends TAllowedTypes ? TInnerType extends PrimitivesAndNativeObjects ? ArrayIndexes : ArrayIndexes | `${ArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}` : `${ArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}`;
7
+ type ArrayPaths<TInnerType, TAllowedTypes> = TInnerType extends TAllowedTypes ? TInnerType extends PrimitivesAndNativeObjects ? ExtendedArrayIndexes : ExtendedArrayIndexes | `${ExtendedArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}` : `${ExtendedArrayIndexes}.${DotPathsImplementation<TInnerType, TAllowedTypes>}`;
64
8
  /** Dot-paths of an object. */
65
9
  type ObjectPaths<T, TAllowedTypes> = {
66
10
  [Key in keyof T & (string | number)]: T[Key] extends TAllowedTypes ? T[Key] extends PrimitivesAndNativeObjects ? `${Key}` : `${Key}` | `${Key}.${DotPathsImplementation<T[Key], TAllowedTypes>}` : `${Key}.${DotPathsImplementation<T[Key], TAllowedTypes>}`;
67
- }[keyof T & (string | number)] & unknown;
11
+ }[keyof T & (string | number)] & {};
68
12
  /** Dot-paths of a tuple. */
69
- type TuplePaths<T, TAllowedTypes> = ObjectPaths<Omit<T, keyof any[]>, TAllowedTypes> & unknown;
13
+ type TuplePaths<T, TAllowedTypes> = ObjectPaths<Omit<T, keyof any[]>, TAllowedTypes> & {};
70
14
  /** Dot-paths implementation */
71
- type DotPathsImplementation<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? TuplePaths<T, TAllowedTypes> : ArrayPaths<U, TAllowedTypes> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TAllowedTypes>;
72
- /** Extract Keys from any kind of type, including objects, arrays, tuples. */
73
- type KeyOf<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? U extends TAllowedTypes ? IsTuple<T> extends true ? keyof Omit<T, keyof any[]> : ArrayIndexes : never : T extends PrimitivesAndNativeObjects ? never : {
74
- [Key in keyof T]: T[Key] extends TAllowedTypes ? Key : never;
75
- }[keyof T];
15
+ type DotPathsImplementation<T, TAllowedTypes = any> = T extends ReadonlyArray<infer U> ? T extends Tuple ? TuplePaths<T, TAllowedTypes> : ArrayPaths<U, TAllowedTypes> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TAllowedTypes>;
76
16
  /** Literal union of all posible dot-paths which satisfy provided types as second argument (default: any). */
77
17
  type DotPaths<T, TAllowedTypes = any> = KeyOf<T, TAllowedTypes> | DotPathsImplementation<T, TAllowedTypes>;
78
18
  /**
@@ -97,7 +37,7 @@ type ReturnedValueInPath<TObject, TPath> = TPath extends '' ? TObject : TPath ex
97
37
  /** Value of a dot-path update object, can be the value or a function. */
98
38
  type UpdateValue<TObject, TPath> = ValueInPath<TObject, TPath> extends never ? never : ValueInPath<TObject, TPath> | ((fieldValue: ValueInPath<TObject, TPath>) => ValueInPath<TObject, TPath>);
99
39
  /** Dot-path update object, used to give updates to the updateImmutably function. */
100
- type UpdateObject<TObject, TPaths extends PropertyKey = DotPaths<TObject>> = {
40
+ type UpdateObject<TObject, TPaths extends DotPaths<TObject> = DotPaths<TObject>> = {
101
41
  [Path in TPaths]?: UpdateValue<TObject, Path>;
102
42
  };
103
43
  /**
@@ -141,6 +81,54 @@ type ExtractTypeFromDotPathUpdateObject<T extends Record<string, any>> = T exten
141
81
  /** New expanded value after aplying updates including new properties */
142
82
  type ExtendedUpdate<TObject, TDotPathUpdateObject extends Record<PropertyKey, any>> = TObject extends Array<infer U> ? ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject> extends Array<infer W> ? Array<U | W> : TObject & ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject> : TObject & ExtractTypeFromDotPathUpdateObject<TDotPathUpdateObject>;
143
83
 
84
+ /** Index literal type to improve DX at managing updates. */
85
+ declare const LITERAL_INDEX = "${number}";
86
+
87
+ /** Primitives and browser native objects. */
88
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
89
+ /** Tuple type, it has to have at least property "0" */
90
+ type Tuple = ReadonlyArray<any> & {
91
+ "0": any;
92
+ };
93
+ /** Array indexes type. */
94
+ type LiteralIndex = typeof LITERAL_INDEX;
95
+ type ExtendedArrayIndexes = number | `${number}` | LiteralIndex;
96
+ /** Object Literal */
97
+ type ObjectLiteral = {
98
+ [x: string]: any;
99
+ [x: number]: any;
100
+ [x: symbol]: any;
101
+ [Symbol.iterator]?: never;
102
+ [Symbol.toPrimitive]?: never;
103
+ [Symbol.hasInstance]?: never;
104
+ [Symbol.unscopables]?: never;
105
+ [Symbol.matchAll]?: never;
106
+ };
107
+ /** Strict key */
108
+ declare const strictSymbol: unique symbol;
109
+ type Strict<T> = T extends ObjectLiteral ? T & {
110
+ [strictSymbol]: DotPaths<T>;
111
+ } : T;
112
+ /** Smart KeyOf (doesnt include the "strict" key) */
113
+ type KeyOf<T, TAllowedValuesInKeys = any> = T extends ObjectLiteral ? T extends Strict<infer U> ? KeysOfObject<U, TAllowedValuesInKeys> : KeysOfObject<T, TAllowedValuesInKeys> : T extends Tuple ? KeysOfObject<Omit<T, keyof any[]>, TAllowedValuesInKeys> : T extends ReadonlyArray<infer U> ? U extends TAllowedValuesInKeys ? ExtendedArrayIndexes : never : never;
114
+ type KeysOfObject<T, TAllowedValuesInKeys> = {
115
+ [Key in keyof T]: T[Key] extends TAllowedValuesInKeys ? Key : never;
116
+ }[keyof T];
117
+
118
+ /** Returns only the optional keys of an object. */
119
+ type OptionalKeys<T> = {
120
+ [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
121
+ }[keyof T];
122
+ /** Removes properties or indexes, order doesn't matter. */
123
+ type Remove = <T extends ObjectLiteral | any[]>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
124
+ /**
125
+ * Removes properties or indexes, order doesn't matter.
126
+ * @param value Object/array from where to remove keys/indexes shallowly.
127
+ * @param keys Keys to remove.
128
+ * @returns New object/array without the provided keys/indexes.
129
+ */
130
+ declare const remove: Remove;
131
+
144
132
  type Select = {
145
133
  <T, TPath extends DotPaths<T>>(state: T, path: TPath): ReturnedValueInPath<T, TPath>;
146
134
  <T, TPath extends ''>(state: T, path: TPath): T;
@@ -171,28 +159,51 @@ type Set = <T>(newValue: T) => (v: unknown) => T;
171
159
  */
172
160
  declare const set: Set;
173
161
 
174
- type Iterator = typeof Symbol.iterator;
175
- type HasInstance = typeof Symbol.hasInstance;
176
- type ToPrimitive = typeof Symbol.toPrimitive;
177
- type Unscopables = typeof Symbol.unscopables;
178
- type MatchAll = typeof Symbol.matchAll;
179
- type NonObjectLiteralKeys = Unscopables | HasInstance | ToPrimitive | MatchAll | Iterator;
180
- type ObjectLiteral = Record<PropertyKey, any> & {
181
- [K in NonObjectLiteralKeys]?: never;
162
+ type OptionValues = 'error' | 'skip' | 'add';
163
+ type Options = {
164
+ onNewProps?: OptionValues;
165
+ onNewIndexes?: OptionValues;
166
+ onPathsIntersectedByPrimitiveValues?: OptionValues;
182
167
  };
168
+ type ImmutableUpdate = <TObject, TAllowedDotPathKeys extends DotPaths<TObject> = DotPaths<TObject>>(state: TObject, dotPathUpdateObject: UpdateObject<TObject, TAllowedDotPathKeys>, options?: Options) => TObject;
169
+ /**
170
+ * Creates a new object applying immutable updates using dot-path syntax.
171
+ * Can add or skip new props or indexes depending on options.
172
+ * TYPESCRIPT: Dot-Path Update Object type must STRICTLY match the type of state.
173
+ * @param state Original State Object.
174
+ * @param dotPathUpdateObject Dot Path Update Object.
175
+ * @param options Options to change JS behaviour on non-existent fields.
176
+ * @returns New Updated Object.
177
+ */
178
+ declare const update: ImmutableUpdate;
179
+ type ExtendableImmutableUpdate = <TObject, TUpdateObject extends UpdateObject<TObject> = UpdateObject<TObject>>(state: TObject, dotPathUpdateObject: TUpdateObject) => ExtendedUpdate<TObject, TUpdateObject>;
180
+ /**
181
+ * Creates a new object applying immutable updates using dot-path syntax.
182
+ * It will always add non-existent props or indexes if provided.
183
+ * TYPESCRIPT: Dot-Path Update Object type extends from the type of state and you can add new non-existent properties.
184
+ * @param state Original State Object.
185
+ * @param dotPathUpdateObject Dot Path Update Object.
186
+ * @returns New Updated Object.
187
+ */
188
+ declare const experimental_extendableUpdate: ExtendableImmutableUpdate;
189
+
190
+ type ForEachEntry = <T extends ObjectLiteral>(object: T, callbackfn: (key: keyof T, value: T[keyof T]) => void) => void;
191
+ declare const forEachEntry: ForEachEntry;
192
+
183
193
  /** Checks if any provided value is an object literal or not */
184
- declare const isObjectLiteral: (valueToTest: unknown) => valueToTest is ObjectLiteral;
194
+ type IsObjectLiteral = (valueToTest: unknown) => valueToTest is ObjectLiteral;
195
+ declare const isObjectLiteral: IsObjectLiteral;
185
196
 
186
- declare const parseStringIndex: (v: string) => number | null;
187
- declare const isStringIndex: (v: string) => v is `${number}`;
197
+ /** Adds strict property to an object literal */
198
+ type StrictFn = <T>(value: T) => Strict<T>;
199
+ declare const s: StrictFn;
200
+ /** Checks the strictness of a type passed to a function or callback without 3rd party implementation */
201
+ type EnsureStrictness = <T extends U, U>(v: T extends U ? DotPaths<T> extends DotPaths<U> ? T : Exclude<DotPaths<T>, DotPaths<U>> : never) => U;
202
+ declare const ensureStrictness: EnsureStrictness;
188
203
 
189
- type StrictCallbackError = "CALLBACK STRICTNESS RETURN ERROR: return the value using the first parameter";
190
- type StrictCallbackValue<T> = [StrictCallbackError, T];
191
- type StrictCallbackFunction<T> = (v: T) => StrictCallbackValue<T>;
192
- /** Apply strictness to a callback function */
193
- type StrictCallback<T extends (...args: any[]) => any> = (r: StrictCallbackFunction<ReturnType<T>>, ...args: Parameters<T>) => [StrictCallbackError, ReturnType<T>];
194
- type UnsealStrictCallback = <TCallback extends (r: StrictCallbackFunction<any>, ...args: any[]) => any>(callback: TCallback) => (...args: Parameters<TCallback> extends [infer _, ...infer RestParams] ? RestParams : never) => ReturnType<TCallback>['1'];
195
- /** Extract the callback from */
196
- declare const unsealStrictCallback: UnsealStrictCallback;
204
+ type ParseStringIndex = (stringKey: string) => number | null;
205
+ declare const parseStringIndex: ParseStringIndex;
206
+ type IsStringIndex = (stringKey: string) => stringKey is `${number}`;
207
+ declare const isStringIndex: IsStringIndex;
197
208
 
198
- export { type DotPaths, type KeyOf, type LiteralIndex, type ObjectLiteral, type ReturnedValueInPath, type StrictCallback, type UpdateObject, type UpdateValue, type ValueInPath, experimental_extendableUpdate, isObjectLiteral, isStringIndex, parseStringIndex, remove, select, set, splitPathAtLastKey, unsealStrictCallback, update };
209
+ export { type DotPaths, type ExtendedArrayIndexes, type KeyOf, type LiteralIndex, type ObjectLiteral, type PrimitivesAndNativeObjects, type ReturnedValueInPath, type Strict, type Tuple, type UpdateObject, type UpdateValue, type ValueInPath, ensureStrictness, experimental_extendableUpdate, forEachEntry, isObjectLiteral, isStringIndex, parseStringIndex, remove, s, select, set, splitPathAtLastKey, update };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var D=(e,t)=>{for(var r in t)j(e,r,{get:t[r],enumerable:!0})},N=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of v(t))!V.call(e,n)&&n!==r&&j(e,n,{get:()=>t[n],enumerable:!(a=R(t,n))||a.enumerable});return e};var $=e=>N(j({},"__esModule",{value:!0}),e);var F={};D(F,{experimental_extendableUpdate:()=>k,isObjectLiteral:()=>p,isStringIndex:()=>y,parseStringIndex:()=>K,remove:()=>h,select:()=>P,set:()=>S,splitPathAtLastKey:()=>L,unsealStrictCallback:()=>A,update:()=>g});module.exports=$(F);var p=e=>!!e&&Object.getPrototypeOf(e)===Object.prototype,B=Symbol();var M={[B]:[""]};var h=(e,t)=>{if(!Array.isArray(e)&&!p(e))throw'Wrong type provided in "remove" function';let r=Array.isArray(t)?t:[t];if(Array.isArray(e)){let n=Symbol(),i=[...e];return r.forEach(o=>{i[o]=n}),i.filter(o=>o!==n)}let a={...e};return r.forEach(n=>delete a[n]),a};var P=(e,t)=>{if(typeof t!="string")throw new Error("path is not a string");if(!t)return e;let r=t.split("."),a=e;for(;r.length;){let n=r.join(".");if(a?.hasOwnProperty(n))return a[n];if(!a?.hasOwnProperty(r[0]))return;a=a[r[0]],r.shift()}return a};var L=e=>{if(typeof e!="string")throw new Error(`Wrong dotPath type: ${e}`);let t=e.lastIndexOf(".")+1,r=t?e.slice(0,t-1):"",a=e.slice(t);return[r,a]};var S=e=>()=>e;var K=e=>{let t=parseInt(e);return t.toString()===e?t:null},y=e=>parseInt(e).toString()===e;var w=e=>JSON.stringify(e),x=e=>Array.isArray(e),E=(e,t,r={})=>{if(!p(e)&&!x(e))throw new Error(`"${w(e)}" is not an literalObject/array`);if(!p(t))throw new Error('wrong "updateObject" type provided');let a=Array.isArray(e)?[...e]:{...e},n={};for(let[i,f]of Object.entries(t)){if(i==="")continue;let o=i.split("."),d=n,l=a;for(;o.length>1;){let m=o.join(".");if(Object.hasOwn(l,m)){o=[m];break}let s=o[0],u=l[s],T=p(u),O=x(u);if(!T&&!O&&!(u===void 0)){if(r.onPathsIntersectedByPrimitiveValues==="error")throw new Error(`Property "${s}" in "${i}" is a primitive`);if(r.onPathsIntersectedByPrimitiveValues==="skip")continue}if(!d[s]){if(!T&&!O){let U=x(l)&&y(s),C=y(o[1]),I=U?r.onNewIndexes:r.onNewProps;if(I==="error")throw new Error(`${s} doesn't exist in "${i}"`);if(I==="skip")continue;l[s]=C?[]:{}}else l[s]=O?[...u]:{...u};d[s]={}}l=l[s],d=d[s],o.shift()}let c=o[0],b=l;if(!Object.hasOwn(b,c)){let s=x(b)&&y(c)?r.onNewIndexes:r.onNewProps;if(s==="error")throw new Error(`Property/Index "${c}" doesnt exist in the path "${i}". Its value is: "${w(b)}"`);if(s==="skip")continue}b[c]=typeof f=="function"?f(b[c]):f,delete d[c]}return a},g=(e,t,r)=>E(e,t,r),k=(e,t)=>E(e,t);var A=e=>(...t)=>e(r=>r,...t);0&&(module.exports={experimental_extendableUpdate,isObjectLiteral,isStringIndex,parseStringIndex,remove,select,set,splitPathAtLastKey,unsealStrictCallback,update});
1
+ "use strict";var m=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var N=(e,t)=>{for(var r in t)m(e,r,{get:t[r],enumerable:!0})},F=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of R(t))!C.call(e,s)&&s!==r&&m(e,s,{get:()=>t[s],enumerable:!(n=$(t,s))||n.enumerable});return e};var B=e=>F(m({},"__esModule",{value:!0}),e);var q={};N(q,{ensureStrictness:()=>D,experimental_extendableUpdate:()=>U,forEachEntry:()=>A,isObjectLiteral:()=>l,isStringIndex:()=>y,parseStringIndex:()=>g,remove:()=>I,s:()=>v,select:()=>L,set:()=>E,splitPathAtLastKey:()=>P,update:()=>S});module.exports=B(q);var l=e=>!!e&&Object.getPrototypeOf(e)===Object.prototype,W=Symbol();var _={[W]:[""]};var I=(e,t)=>{if(!Array.isArray(e)&&!l(e))throw'Wrong type provided in "remove" function';let r=Array.isArray(t)?t:[t];if(Array.isArray(e)){let s=Symbol(),o=[...e];return r.forEach(i=>{o[i]=s}),o.filter(i=>i!==s)}let n={...e};return r.forEach(s=>delete n[s]),n};var L=(e,t)=>{if(typeof t!="string")throw new Error("path is not a string");if(!t)return e;let r=t.split("."),n=e;for(;r.length;){let s=r[0],o=r.join(".");if(Object.hasOwn(n,o))return n[o];if(!Object.hasOwn(n,s))return;n=n[s],r.shift()}return n};var P=e=>{if(typeof e!="string")throw new Error(`Wrong dotPath type: ${e}`);let t=e.lastIndexOf(".")+1,r=t?e.slice(0,t-1):"",n=e.slice(t);return[r,n]};var E=e=>()=>e;var g=e=>{let t=parseInt(e);return t.toString()===e?t:null},y=e=>parseInt(e).toString()===e;var w=e=>JSON.stringify(e),f=e=>Array.isArray(e),K=(e,t,r={})=>{if(!l(e)&&!f(e))throw new Error(`"${w(e)}" is not an literalObject/array`);if(!l(t))throw new Error('wrong "updateObject" type provided');let n=Array.isArray(e)?[...e]:{...e},s={};for(let[o,x]of Object.entries(t)){if(o==="")continue;let i=o.split("."),d=s,p=n;for(;i.length>1;){let O=i.join(".");if(Object.hasOwn(p,O)){i=[O];break}let a=i[0],b=p[a],T=l(b),j=f(b);if(!T&&!j&&!(b===void 0)){if(r.onPathsIntersectedByPrimitiveValues==="error")throw new Error(`Property "${a}" in "${o}" is a primitive`);if(r.onPathsIntersectedByPrimitiveValues==="skip")continue}if(!d[a]){if(!T&&!j){let k=f(p)&&y(a),V=y(i[1]),h=k?r.onNewIndexes:r.onNewProps;if(h==="error")throw new Error(`${a} doesn't exist in "${o}"`);if(h==="skip")continue;p[a]=V?[]:{}}else p[a]=j?[...b]:{...b};d[a]={}}p=p[a],d=d[a],i.shift()}let c=i[0],u=p;if(!Object.hasOwn(u,c)){let a=f(u)&&y(c)?r.onNewIndexes:r.onNewProps;if(a==="error")throw new Error(`Property/Index "${c}" doesnt exist in the path "${o}". Its value is: "${w(u)}"`);if(a==="skip")continue}u[c]=typeof x=="function"?x(u[c]):x,delete d[c]}return n},S=(e,t,r)=>K(e,t,r),U=(e,t)=>K(e,t);var A=(e,t)=>Object.keys(e).forEach(r=>t(r,e[r]));var v=e=>e,D=e=>e;0&&(module.exports={ensureStrictness,experimental_extendableUpdate,forEachEntry,isObjectLiteral,isStringIndex,parseStringIndex,remove,s,select,set,splitPathAtLastKey,update});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var p=e=>!!e&&Object.getPrototypeOf(e)===Object.prototype,S=Symbol();var v={[S]:[""]};var K=(e,t)=>{if(!Array.isArray(e)&&!p(e))throw'Wrong type provided in "remove" function';let r=Array.isArray(t)?t:[t];if(Array.isArray(e)){let o=Symbol(),i=[...e];return r.forEach(s=>{i[s]=o}),i.filter(s=>s!==o)}let a={...e};return r.forEach(o=>delete a[o]),a};var w=(e,t)=>{if(typeof t!="string")throw new Error("path is not a string");if(!t)return e;let r=t.split("."),a=e;for(;r.length;){let o=r.join(".");if(a?.hasOwnProperty(o))return a[o];if(!a?.hasOwnProperty(r[0]))return;a=a[r[0]],r.shift()}return a};var E=e=>{if(typeof e!="string")throw new Error(`Wrong dotPath type: ${e}`);let t=e.lastIndexOf(".")+1,r=t?e.slice(0,t-1):"",a=e.slice(t);return[r,a]};var g=e=>()=>e;var k=e=>{let t=parseInt(e);return t.toString()===e?t:null},u=e=>parseInt(e).toString()===e;var I=e=>JSON.stringify(e),x=e=>Array.isArray(e),h=(e,t,r={})=>{if(!p(e)&&!x(e))throw new Error(`"${I(e)}" is not an literalObject/array`);if(!p(t))throw new Error('wrong "updateObject" type provided');let a=Array.isArray(e)?[...e]:{...e},o={};for(let[i,f]of Object.entries(t)){if(i==="")continue;let s=i.split("."),y=o,l=a;for(;s.length>1;){let m=s.join(".");if(Object.hasOwn(l,m)){s=[m];break}let n=s[0],b=l[n],j=p(b),O=x(b);if(!j&&!O&&!(b===void 0)){if(r.onPathsIntersectedByPrimitiveValues==="error")throw new Error(`Property "${n}" in "${i}" is a primitive`);if(r.onPathsIntersectedByPrimitiveValues==="skip")continue}if(!y[n]){if(!j&&!O){let P=x(l)&&u(n),L=u(s[1]),T=P?r.onNewIndexes:r.onNewProps;if(T==="error")throw new Error(`${n} doesn't exist in "${i}"`);if(T==="skip")continue;l[n]=L?[]:{}}else l[n]=O?[...b]:{...b};y[n]={}}l=l[n],y=y[n],s.shift()}let c=s[0],d=l;if(!Object.hasOwn(d,c)){let n=x(d)&&u(c)?r.onNewIndexes:r.onNewProps;if(n==="error")throw new Error(`Property/Index "${c}" doesnt exist in the path "${i}". Its value is: "${I(d)}"`);if(n==="skip")continue}d[c]=typeof f=="function"?f(d[c]):f,delete y[c]}return a},A=(e,t,r)=>h(e,t,r),U=(e,t)=>h(e,t);var C=e=>(...t)=>e(r=>r,...t);export{U as experimental_extendableUpdate,p as isObjectLiteral,u as isStringIndex,k as parseStringIndex,K as remove,w as select,g as set,E as splitPathAtLastKey,C as unsealStrictCallback,A as update};
1
+ var l=e=>!!e&&Object.getPrototypeOf(e)===Object.prototype,E=Symbol();var R={[E]:[""]};var g=(e,t)=>{if(!Array.isArray(e)&&!l(e))throw'Wrong type provided in "remove" function';let r=Array.isArray(t)?t:[t];if(Array.isArray(e)){let i=Symbol(),a=[...e];return r.forEach(o=>{a[o]=i}),a.filter(o=>o!==i)}let n={...e};return r.forEach(i=>delete n[i]),n};var w=(e,t)=>{if(typeof t!="string")throw new Error("path is not a string");if(!t)return e;let r=t.split("."),n=e;for(;r.length;){let i=r[0],a=r.join(".");if(Object.hasOwn(n,a))return n[a];if(!Object.hasOwn(n,i))return;n=n[i],r.shift()}return n};var K=e=>{if(typeof e!="string")throw new Error(`Wrong dotPath type: ${e}`);let t=e.lastIndexOf(".")+1,r=t?e.slice(0,t-1):"",n=e.slice(t);return[r,n]};var S=e=>()=>e;var U=e=>{let t=parseInt(e);return t.toString()===e?t:null},b=e=>parseInt(e).toString()===e;var h=e=>JSON.stringify(e),f=e=>Array.isArray(e),I=(e,t,r={})=>{if(!l(e)&&!f(e))throw new Error(`"${h(e)}" is not an literalObject/array`);if(!l(t))throw new Error('wrong "updateObject" type provided');let n=Array.isArray(e)?[...e]:{...e},i={};for(let[a,x]of Object.entries(t)){if(a==="")continue;let o=a.split("."),y=i,p=n;for(;o.length>1;){let O=o.join(".");if(Object.hasOwn(p,O)){o=[O];break}let s=o[0],u=p[s],m=l(u),j=f(u);if(!m&&!j&&!(u===void 0)){if(r.onPathsIntersectedByPrimitiveValues==="error")throw new Error(`Property "${s}" in "${a}" is a primitive`);if(r.onPathsIntersectedByPrimitiveValues==="skip")continue}if(!y[s]){if(!m&&!j){let L=f(p)&&b(s),P=b(o[1]),T=L?r.onNewIndexes:r.onNewProps;if(T==="error")throw new Error(`${s} doesn't exist in "${a}"`);if(T==="skip")continue;p[s]=P?[]:{}}else p[s]=j?[...u]:{...u};y[s]={}}p=p[s],y=y[s],o.shift()}let c=o[0],d=p;if(!Object.hasOwn(d,c)){let s=f(d)&&b(c)?r.onNewIndexes:r.onNewProps;if(s==="error")throw new Error(`Property/Index "${c}" doesnt exist in the path "${a}". Its value is: "${h(d)}"`);if(s==="skip")continue}d[c]=typeof x=="function"?x(d[c]):x,delete y[c]}return n},A=(e,t,r)=>I(e,t,r),v=(e,t)=>I(e,t);var D=(e,t)=>Object.keys(e).forEach(r=>t(r,e[r]));var k=e=>e,V=e=>e;export{V as ensureStrictness,v as experimental_extendableUpdate,D as forEachEntry,l as isObjectLiteral,b as isStringIndex,U as parseStringIndex,g as remove,k as s,w as select,S as set,K as splitPathAtLastKey,A as update};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maraj",
3
- "version": "2.8.4",
3
+ "version": "2.9.0",
4
4
  "description": "A lightweight 600 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
5
  "keywords": [
6
6
  "shallow",