@rimbu/deep 0.14.5 → 1.0.0-alpha.1

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.
Files changed (86) hide show
  1. package/{src/deep.ts → dist/bun/deep.mts} +7 -7
  2. package/{src/index.ts → dist/bun/index.mts} +5 -5
  3. package/dist/bun/internal.mts +8 -0
  4. package/{src/match.ts → dist/bun/match.mts} +6 -6
  5. package/{src/patch.ts → dist/bun/patch.mts} +9 -4
  6. package/{src/path.ts → dist/bun/path.mts} +2 -2
  7. package/{src/selector.ts → dist/bun/selector.mts} +1 -1
  8. package/dist/cjs/deep.js +590 -0
  9. package/dist/cjs/index.js +663 -0
  10. package/dist/cjs/internal.js +583 -0
  11. package/dist/cjs/match.js +376 -0
  12. package/dist/cjs/patch.js +105 -0
  13. package/dist/cjs/path.js +585 -0
  14. package/dist/cjs/protected.js +18 -0
  15. package/dist/cjs/selector.js +581 -0
  16. package/dist/cjs/tuple.js +73 -0
  17. package/dist/{module/deep.js → esm/deep.mjs} +6 -6
  18. package/dist/esm/deep.mjs.map +1 -0
  19. package/dist/{module/index.js → esm/index.mjs} +5 -5
  20. package/dist/esm/index.mjs.map +1 -0
  21. package/dist/esm/internal.mjs +5 -0
  22. package/dist/esm/internal.mjs.map +1 -0
  23. package/dist/{module/match.js → esm/match.mjs} +21 -21
  24. package/dist/esm/match.mjs.map +1 -0
  25. package/dist/{module/patch.js → esm/patch.mjs} +5 -5
  26. package/dist/esm/patch.mjs.map +1 -0
  27. package/dist/{module/path.js → esm/path.mjs} +2 -2
  28. package/dist/esm/path.mjs.map +1 -0
  29. package/dist/esm/protected.mjs +2 -0
  30. package/dist/esm/protected.mjs.map +1 -0
  31. package/dist/{module/selector.js → esm/selector.mjs} +2 -2
  32. package/dist/esm/selector.mjs.map +1 -0
  33. package/dist/{module/tuple.js → esm/tuple.mjs} +1 -1
  34. package/dist/esm/tuple.mjs.map +1 -0
  35. package/dist/types/{deep.d.ts → deep.d.mts} +6 -6
  36. package/dist/types/{index.d.ts → index.d.mts} +5 -5
  37. package/dist/types/internal.d.mts +7 -0
  38. package/dist/types/{match.d.ts → match.d.mts} +3 -3
  39. package/dist/types/{patch.d.ts → patch.d.mts} +3 -3
  40. package/dist/types/{path.d.ts → path.d.mts} +2 -2
  41. package/dist/types/{selector.d.ts → selector.d.mts} +1 -1
  42. package/package.json +29 -23
  43. package/src/deep.mts +364 -0
  44. package/src/index.mts +23 -0
  45. package/src/internal.mts +8 -0
  46. package/src/match.mts +700 -0
  47. package/src/patch.mts +262 -0
  48. package/src/path.mts +430 -0
  49. package/src/protected.mts +30 -0
  50. package/src/selector.mts +90 -0
  51. package/src/tuple.mts +197 -0
  52. package/dist/main/deep.js +0 -211
  53. package/dist/main/deep.js.map +0 -1
  54. package/dist/main/index.js +0 -19
  55. package/dist/main/index.js.map +0 -1
  56. package/dist/main/internal.js +0 -9
  57. package/dist/main/internal.js.map +0 -1
  58. package/dist/main/match.js +0 -284
  59. package/dist/main/match.js.map +0 -1
  60. package/dist/main/patch.js +0 -133
  61. package/dist/main/patch.js.map +0 -1
  62. package/dist/main/path.js +0 -126
  63. package/dist/main/path.js.map +0 -1
  64. package/dist/main/protected.js +0 -3
  65. package/dist/main/protected.js.map +0 -1
  66. package/dist/main/selector.js +0 -40
  67. package/dist/main/selector.js.map +0 -1
  68. package/dist/main/tuple.js +0 -164
  69. package/dist/main/tuple.js.map +0 -1
  70. package/dist/module/deep.js.map +0 -1
  71. package/dist/module/index.js.map +0 -1
  72. package/dist/module/internal.js +0 -4
  73. package/dist/module/internal.js.map +0 -1
  74. package/dist/module/match.js.map +0 -1
  75. package/dist/module/patch.js.map +0 -1
  76. package/dist/module/path.js.map +0 -1
  77. package/dist/module/protected.js +0 -2
  78. package/dist/module/protected.js.map +0 -1
  79. package/dist/module/selector.js.map +0 -1
  80. package/dist/module/tuple.js.map +0 -1
  81. package/dist/types/internal.d.ts +0 -7
  82. package/src/internal.ts +0 -8
  83. /package/{src/protected.ts → dist/bun/protected.mts} +0 -0
  84. /package/{src/tuple.ts → dist/bun/tuple.mts} +0 -0
  85. /package/dist/types/{protected.d.ts → protected.d.mts} +0 -0
  86. /package/dist/types/{tuple.d.ts → tuple.d.mts} +0 -0
package/src/patch.mts ADDED
@@ -0,0 +1,262 @@
1
+ import {
2
+ type IsAnyFunc,
3
+ type IsArray,
4
+ isPlainObj,
5
+ type IsPlainObj,
6
+ } from '@rimbu/base';
7
+
8
+ import type { Protected } from './internal.mjs';
9
+ import type { Tuple } from './tuple.mjs';
10
+
11
+ /**
12
+ * A type to determine the allowed input type for the `patch` function.
13
+ * @typeparam T - the input type to be patched
14
+ */
15
+ export type Patch<T, C = T> = Patch.Entry<T, C, T, T>;
16
+
17
+ export namespace Patch {
18
+ /**
19
+ * The entry type for a (nested) patch. Can be either a patch object or a function accepting the nested patch function and returning a patch object.
20
+ * @typeparam T - the input value type
21
+ * @typeparam C - a utility type
22
+ * @typeparam P - the parent type
23
+ * @typeparam R - the root object type
24
+ */
25
+ export type Entry<T, C, P, R> = IsAnyFunc<T> extends true
26
+ ? T
27
+ : IsPlainObj<T> extends true
28
+ ? Patch.WithResult<T, P, R, Patch.Obj<T, C, R>>
29
+ : Tuple.IsTuple<T> extends true
30
+ ? Patch.WithResult<T, P, R, T | Patch.Tup<T, C, R>>
31
+ : IsArray<T> extends true
32
+ ? Patch.WithResult<T, P, R, T>
33
+ : Patch.WithResult<T, P, R, T>;
34
+
35
+ /**
36
+ * Either result type S, or a patch function with the value type, the parent type, and the root type.
37
+ * @typeparam T - the value type
38
+ * @typeparam P - the parent type
39
+ * @typeparam R - the root type
40
+ * @typeparam S - the result type
41
+ */
42
+ export type WithResult<T, P, R, S> = S | Patch.Func<T, P, R, S>;
43
+
44
+ /**
45
+ * A function patch type that is a function taking the current value, the parent and root values,
46
+ * and returns a return value.
47
+ * @typeparam T - the value type
48
+ * @typeparam P - the parent type
49
+ * @typeparam R - the root type
50
+ * @typeparam S - the result type
51
+ */
52
+ export type Func<T, P, R, S> = (
53
+ current: Protected<T>,
54
+ parent: Protected<P>,
55
+ root: Protected<R>
56
+ ) => Protected<S>;
57
+
58
+ /**
59
+ * A type defining the allowed patch values for tuples.
60
+ * @typeparam T - the input tuple type
61
+ * @typeparam C - a utility type
62
+ * @typeparam R - the root type
63
+ */
64
+ export type Tup<T, C, R> = {
65
+ [K in Tuple.KeysOf<T>]?: Patch.Entry<T[K & keyof T], C[K & keyof C], T, R>;
66
+ } & NotIterable;
67
+
68
+ /**
69
+ * Utility type to exclude Iterable types.
70
+ */
71
+ export type NotIterable = {
72
+ [Symbol.iterator]?: never;
73
+ };
74
+
75
+ /**
76
+ * A type defining the allowed patch values for objects.
77
+ * @typeparam T - the input value type
78
+ * @typeparam C - a utility type
79
+ * @typeparam R - the root object type
80
+ */
81
+ export type Obj<T, C, R> = T | Patch.ObjProps<T, C, R>[];
82
+
83
+ /**
84
+ * A type defining the allowed patch values for object properties.
85
+ * @typeparam T - the input value type
86
+ * @typeparam C - a utility type
87
+ * @typeparam R - the root object type
88
+ */
89
+ export type ObjProps<T, C, R> = {
90
+ [K in keyof C]?: K extends keyof T ? Patch.Entry<T[K], C[K], T, R> : never;
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Returns an immutably updated version of the given `value` where the given `patchItems` have been
96
+ * applied to the result.
97
+ * The Rimbu patch notation is as follows:
98
+ * - if the target is a simple value or array, the patch can be the same type or a function returning the same type
99
+ * - if the target is a tuple (array of fixed length), the patch be the same type or an object containing numeric keys with patches indicating the tuple index to patch
100
+ * - if the target is an object, the patch can be the same type, or an array containing partial keys with their patches for the object
101
+ * @typeparam T - the type of the value to patch
102
+ * @typeparam TE - a utility type
103
+ * @typeparam TT - a utility type
104
+ * @param value - the input value to patch
105
+ * @param patchItem - the `Patch` value to apply to the input value
106
+ * @example
107
+ * ```ts
108
+ * const input = { a: 1, b: { c: true, d: 'a' } }
109
+ * patch(input, [{ a: 2 }]) // => { a: 2, b: { c: true, d: 'a' } }
110
+ * patch(input, [{ b: [{ c: (v) => !v }] }] )
111
+ * // => { a: 1, b: { c: false, d: 'a' } }
112
+ * patch(input: [{ a: (v) => v + 1, b: [{ d: 'q' }] }] )
113
+ * // => { a: 2, b: { c: true, d: 'q' } }
114
+ * ```
115
+ */
116
+ export function patch<T, TE extends T = T, TT = T>(
117
+ value: T,
118
+ patchItem: Patch<TE, T & TT>
119
+ ): T {
120
+ return patchEntry(value, value, value, patchItem as Patch<T>);
121
+ }
122
+
123
+ function patchEntry<T, C, P, R>(
124
+ value: T,
125
+ parent: P,
126
+ root: R,
127
+ patchItem: Patch.Entry<T, C, P, R>
128
+ ): T {
129
+ if (Object.is(value, patchItem)) {
130
+ // patching a value with itself never changes the value
131
+ return value;
132
+ }
133
+
134
+ if (typeof value === 'function') {
135
+ // function input, directly return patch
136
+ return patchItem as T;
137
+ }
138
+
139
+ if (typeof patchItem === 'function') {
140
+ // function patch always needs to be resolved first
141
+ const item = patchItem(value, parent, root);
142
+
143
+ return patchEntry(value, parent, root, item);
144
+ }
145
+
146
+ if (isPlainObj(value)) {
147
+ // value is plain object
148
+ return patchPlainObj(value, root, patchItem as any);
149
+ }
150
+
151
+ if (Array.isArray(value)) {
152
+ // value is tuple or array
153
+ return patchArr(value, root, patchItem as any);
154
+ }
155
+
156
+ // value is primitive type or complex object
157
+
158
+ return patchItem as T;
159
+ }
160
+
161
+ function patchPlainObj<T, C, R>(
162
+ value: T,
163
+ root: R,
164
+ patchItem: T | Patch.Obj<T, C, R>
165
+ ): T {
166
+ if (!Array.isArray(patchItem)) {
167
+ // the patch is a complete replacement of the current value
168
+
169
+ return patchItem as T;
170
+ }
171
+
172
+ // patch is an array of partial updates
173
+
174
+ // copy the input value
175
+ const result = { ...value };
176
+
177
+ let anyChange = false;
178
+
179
+ // loop over patches in array
180
+ for (const entry of patchItem) {
181
+ // update root if needed
182
+ const currentRoot = (value as any) === root ? { ...result } : root;
183
+
184
+ // keep current updated result as parent
185
+ const parent = { ...result };
186
+
187
+ // loop over all the patch keys
188
+ for (const key in entry as T) {
189
+ // patch the value at the given key with the patch at that key
190
+ const currentValue = result[key];
191
+ const newValue = patchEntry(
192
+ currentValue,
193
+ parent,
194
+ currentRoot,
195
+ (entry as any)[key]
196
+ );
197
+
198
+ if (!Object.is(currentValue, newValue)) {
199
+ // if value changed, set it in result and mark change
200
+ anyChange = true;
201
+ result[key] = newValue;
202
+ }
203
+ }
204
+ }
205
+
206
+ if (anyChange) {
207
+ // something changed, return new value
208
+ return result;
209
+ }
210
+
211
+ // nothing changed, return old value
212
+ return value;
213
+ }
214
+
215
+ function patchArr<T extends any[], C, R>(
216
+ value: T,
217
+ root: R,
218
+ patchItem: T | Patch.Tup<T, C, R>
219
+ ): T {
220
+ if (Array.isArray(patchItem)) {
221
+ // value is a normal array
222
+ // patch is a complete replacement of current array
223
+
224
+ return patchItem;
225
+ }
226
+
227
+ // value is a tuple
228
+ // patch is an object containing numeric keys with function values
229
+ // that update the tuple at the given indices
230
+
231
+ // copy the tuple
232
+ const result = [...value] as T;
233
+ let anyChange = false;
234
+
235
+ // loop over all index keys in object
236
+ for (const index in patchItem) {
237
+ const numIndex = index as any as number;
238
+
239
+ // patch the tuple at the given index
240
+ const currentValue = result[numIndex];
241
+ const newValue = patchEntry(
242
+ currentValue,
243
+ value,
244
+ root,
245
+ (patchItem as any)[index]
246
+ );
247
+
248
+ if (!Object.is(newValue, currentValue)) {
249
+ // if value changed, set it in result and mark change
250
+ anyChange = true;
251
+ result[numIndex] = newValue;
252
+ }
253
+ }
254
+
255
+ if (anyChange) {
256
+ // something changed, return new value
257
+ return result;
258
+ }
259
+
260
+ // nothing changed, return old value
261
+ return value;
262
+ }
package/src/path.mts ADDED
@@ -0,0 +1,430 @@
1
+ import type { IsAnyFunc, IsArray, IsPlainObj } from '@rimbu/base';
2
+ import { Deep, type Patch } from './internal.mjs';
3
+ import type { Tuple } from './tuple.mjs';
4
+
5
+ export namespace Path {
6
+ /**
7
+ * A string representing a path into an (nested) object of type T.
8
+ * @typeparam T - the object type to select in
9
+ * @example
10
+ * ```ts
11
+ * const p: Path.Get<{ a: { b: { c : 5 } } }> = 'a.b'
12
+ * ```
13
+ */
14
+ export type Get<T> = Path.Internal.Generic<T, false, false, true>;
15
+
16
+ /**
17
+ * A string representing a path into an (nested) object of type T.
18
+ * @typeparam T - the object type to select in
19
+ * @example
20
+ * ```ts
21
+ * const p: Path.Set<{ a: { b: { c : 5 } } }> = 'a.b'
22
+ * ```
23
+ */
24
+ export type Set<T> = Path.Internal.Generic<T, true, false, true>;
25
+
26
+ export namespace Internal {
27
+ /**
28
+ * Determines the allowed paths into a value of type `T`.
29
+ * @typeparam T - the source type
30
+ * @typeparam Write - if true the path should be writable (no optional chaining)
31
+ * @typeparam Maybe - if true the value at the current path is optional
32
+ * @typeparam First - if true this is the root call
33
+ * @note type is mapped as template literal to prevent non-string types to leak through
34
+ */
35
+ export type Generic<
36
+ T,
37
+ Write extends boolean,
38
+ Maybe extends boolean,
39
+ First extends boolean = false
40
+ > = `${IsAnyFunc<T> extends true
41
+ ? // functions can not be further decomposed
42
+ ''
43
+ : // empty string is always an option
44
+ '' | Path.Internal.NonEmpty<T, Write, Maybe, First>}`;
45
+
46
+ /**
47
+ * Determines the allowed non-empty paths into a value of type `T`.
48
+ * @typeparam T - the source type
49
+ * @typeparam Write - if true the path should be writable (no optional chaining)
50
+ * @typeparam Maybe - if true the value at the current path is optional
51
+ * @typeparam First - if true this is the root call
52
+ */
53
+ export type NonEmpty<
54
+ T,
55
+ Write extends boolean,
56
+ Maybe extends boolean,
57
+ First extends boolean
58
+ > = Path.Internal.IsOptional<T> extends true
59
+ ? // the value T may be null or undefined, check whether further chaining is allowed
60
+ Write extends false
61
+ ? // path is not used to write to, so optional chaining is allowed
62
+ Path.Internal.Generic<Exclude<T, undefined | null>, Write, true>
63
+ : // path can be written to, no optional chaining allowed
64
+ never
65
+ : // determine separator, and continue with non-optional value
66
+ `${Path.Internal.Separator<
67
+ First,
68
+ Maybe,
69
+ IsArray<T>
70
+ >}${Path.Internal.NonOptional<T, Write, Maybe>}`;
71
+
72
+ /**
73
+ * Determines the allowed paths into a non-optional value of type `T`.
74
+ * @typeparam T - the source type
75
+ * @typeparam Write - if true the path should be writable (no optional chaining)
76
+ * @typeparam Maybe - if true the value at the current path is optional
77
+ * @typeparam First - if true this is the root call
78
+ */
79
+ export type NonOptional<
80
+ T,
81
+ Write extends boolean,
82
+ Maybe extends boolean
83
+ > = Tuple.IsTuple<T> extends true
84
+ ? // determine allowed paths for tuple
85
+ Path.Internal.Tup<T, Write, Maybe>
86
+ : T extends readonly any[]
87
+ ? // determine allowed paths for array
88
+ Write extends false
89
+ ? // path is not writable so arrays are allowed
90
+ Path.Internal.Arr<T>
91
+ : // path is writable, no arrays allowed
92
+ never
93
+ : IsPlainObj<T> extends true
94
+ ? // determine allowed paths for object
95
+ Path.Internal.Obj<T, Write, Maybe>
96
+ : // no match
97
+ never;
98
+
99
+ /**
100
+ * Determines the allowed paths for a tuple. Since tuples have fixed types, they do not
101
+ * need to be optional, in contrast to arrays.
102
+ * @typeparam T - the input tuple type
103
+ * @typeparam Write - if true the path should be writable (no optional chaining)
104
+ * @typeparam Maybe - if true the value at the current path is optional
105
+ */
106
+ export type Tup<T, Write extends boolean, Maybe extends boolean> = {
107
+ [K in Tuple.KeysOf<T>]: `[${K}]${Path.Internal.Generic<
108
+ T[K],
109
+ Write,
110
+ Maybe
111
+ >}`;
112
+ }[Tuple.KeysOf<T>];
113
+
114
+ /**
115
+ * Determines the allowed paths for an array.
116
+ * @typeparam T - the input array type
117
+ */
118
+ export type Arr<T extends readonly any[]> =
119
+ // first `[index]` and then the rest of the path, which cannot be Write (since optional) and must be Maybe
120
+ `[${number}]${Path.Internal.Generic<T[number], false, true>}`;
121
+
122
+ /**
123
+ * Determines the allowed paths for an object.
124
+ * @typeparam T - the input object type
125
+ * @typeparam Write - if true the path should be writable (no optional chaining)
126
+ * @typeparam Maybe - if true the value at the current path is optional
127
+ */
128
+ export type Obj<T, Write extends boolean, Maybe extends boolean> = {
129
+ [K in keyof T]: `${K & string}${Path.Internal.Generic<
130
+ T[K],
131
+ Write,
132
+ // If writable (not optional), Maybe is false. If value is optional, Maybe is true. Otherwise, forward current Maybe.
133
+ Write extends true ? false : Path.Internal.IsOptional<T[K], true, Maybe>
134
+ >}`;
135
+ }[keyof T];
136
+
137
+ /**
138
+ * Determines the allowed path part seperator based on the input types.
139
+ * @typeparam First - if true, this is the first call
140
+ * @typeparam Maybe - if true, the value is optional
141
+ * @typeparam IsArray - if true, the value is an array
142
+ */
143
+ export type Separator<
144
+ First extends boolean,
145
+ Maybe extends boolean,
146
+ IsArray extends boolean
147
+ > = Maybe extends true
148
+ ? First extends true
149
+ ? // first optional value cannot have separator
150
+ never
151
+ : // non-first optional value must have separator
152
+ '?.'
153
+ : First extends true
154
+ ? // first non-optional value has empty separator
155
+ ''
156
+ : IsArray extends true
157
+ ? // array selectors do not have separator
158
+ ''
159
+ : // normal separator
160
+ '.';
161
+
162
+ /**
163
+ * Determines whether the given type `T` is optional, that is, whether it can be null or undefined.
164
+ * @typeparam T - the input type
165
+ * @typeparam True - the value to return if `T` is optional
166
+ * @typeparam False - the value to return if `T` is mandatory
167
+ */
168
+ export type IsOptional<T, True = true, False = false> = undefined extends T
169
+ ? // is optional
170
+ True
171
+ : null extends T
172
+ ? // is optional
173
+ True
174
+ : // not optional
175
+ False;
176
+
177
+ /**
178
+ * Returns type `T` if `Maybe` is false, `T | undefined` otherwise.
179
+ * @typeparam T - the input type
180
+ * @typeparam Maybe - if true, the return type value should be optional
181
+ */
182
+ export type MaybeValue<T, Maybe extends boolean> = Maybe extends true
183
+ ? T | undefined
184
+ : T;
185
+
186
+ /**
187
+ * Utility type to only add non-empty string types to a string array.
188
+ * @typeparma A - the input string array
189
+ * @typeparam T - the string value to optionally add
190
+ */
191
+ export type AppendIfNotEmpty<
192
+ A extends string[],
193
+ T extends string
194
+ > = T extends ''
195
+ ? // empty string, do not add
196
+ A
197
+ : // non-empty string, add to array
198
+ [...A, T];
199
+ }
200
+
201
+ /**
202
+ * The result type when selecting from object type T a path with type P.
203
+ * @typeparam T - the object type to select in
204
+ * @typeparam P - a Path in object type T
205
+ * @example
206
+ * ```ts
207
+ * let r!: Path.Result<{ a: { b: { c: number } } }, 'a.b'>;
208
+ * // => type of r: { c: number }
209
+ * ```
210
+ */
211
+ export type Result<T, P extends string> = Path.Result.For<
212
+ T,
213
+ Path.Result.Tokenize<P>,
214
+ false
215
+ >;
216
+
217
+ export namespace Result {
218
+ /**
219
+ * Determines the result type for an array of tokens representing subpaths in type `T`.
220
+ * @typeparam T - the current source type
221
+ * @typeparam Tokens - an array of elements indicating a path into the source type
222
+ * @typeparam Maybe - if true indicates that the path may be undefined
223
+ */
224
+ export type For<
225
+ T,
226
+ Tokens,
227
+ Maybe extends boolean = Path.Internal.IsOptional<T>
228
+ > = Tokens extends []
229
+ ? // no more token
230
+ Path.Internal.MaybeValue<T, Maybe>
231
+ : Path.Internal.IsOptional<T> extends true
232
+ ? // T can be null or undefined, so continue with Maybe set to true
233
+ Path.Result.For<Exclude<T, undefined | null>, Tokens, Maybe>
234
+ : Tokens extends ['?.', infer Key, ...infer Rest]
235
+ ? // optional chaining, process first part and set Maybe to true
236
+ Path.Result.For<Path.Result.Part<T, Key, Maybe>, Rest, true>
237
+ : Tokens extends ['.', infer Key, ...infer Rest]
238
+ ? // normal chaining, process first part and continue
239
+ Path.Result.For<Path.Result.Part<T, Key, false>, Rest, Maybe>
240
+ : Tokens extends [infer Key, ...infer Rest]
241
+ ? // process first part, and continue
242
+ Path.Result.For<Path.Result.Part<T, Key, false>, Rest, Maybe>
243
+ : never;
244
+
245
+ /**
246
+ * Determines the result of getting the property/index `K` from type `T`, taking into
247
+ * account that the value may be optional.
248
+ * @typeparam T - the current source type
249
+ * @typeparam K - the key to get from the source type
250
+ * @typeparam Maybe - if true indicates that the path may be undefined
251
+ */
252
+ export type Part<T, K, Maybe extends boolean> = IsArray<T> extends true
253
+ ? // for arrays, Maybe needs to be set to true to force optional chaining
254
+ // for tuples, Maybe should be false
255
+ Path.Internal.MaybeValue<
256
+ T[K & keyof T],
257
+ Tuple.IsTuple<T> extends true ? Maybe : true
258
+ >
259
+ : // Return the type at the given key, and take `Maybe` into account
260
+ Path.Internal.MaybeValue<T[K & keyof T], Maybe>;
261
+
262
+ /**
263
+ * Converts a path string into separate tokens in a string array.
264
+ * @typeparam P - the literal string path type
265
+ * @typeparam Token - the token currently being produced
266
+ * @typeparam Res - the resulting literal string token array
267
+ */
268
+ export type Tokenize<
269
+ P extends string,
270
+ Token extends string = '',
271
+ Res extends string[] = []
272
+ > = P extends ''
273
+ ? // no more input to process, return result
274
+ Path.Internal.AppendIfNotEmpty<Res, Token>
275
+ : P extends `[${infer Index}]${infer Rest}`
276
+ ? // input is an array selector, append index to tokens. Continue with new token
277
+ Tokenize<
278
+ Rest,
279
+ '',
280
+ [...Path.Internal.AppendIfNotEmpty<Res, Token>, Index]
281
+ >
282
+ : P extends `?.${infer Rest}`
283
+ ? // optional chaining, append to tokens. Continue with new token
284
+ Tokenize<
285
+ Rest,
286
+ '',
287
+ [...Path.Internal.AppendIfNotEmpty<Res, Token>, '?.']
288
+ >
289
+ : P extends `.${infer Rest}`
290
+ ? // normal chaining, append to tokens. Continue with new token
291
+ Tokenize<Rest, '', [...Path.Internal.AppendIfNotEmpty<Res, Token>, '.']>
292
+ : P extends `${infer First}${infer Rest}`
293
+ ? // process next character
294
+ Tokenize<Rest, `${Token}${First}`, Res>
295
+ : never;
296
+ }
297
+
298
+ /**
299
+ * Regular expression used to split a path string into tokens.
300
+ */
301
+ export const stringSplitRegex = /\?\.|\.|\[|\]/g;
302
+
303
+ /**
304
+ * The allowed values of a split path.
305
+ */
306
+ export type StringSplit = (string | number | undefined)[];
307
+
308
+ /**
309
+ * Return the given `path` string split into an array of subpaths.
310
+ * @param path - the input string path
311
+ */
312
+ export function stringSplit(path: string): Path.StringSplit {
313
+ return path.split(Path.stringSplitRegex);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Returns the value resulting from selecting the given `path` in the given `source` object.
319
+ * It supports optional chaining for nullable values or values that may be undefined, and also
320
+ * for accessing objects inside an array.
321
+ * There is currently no support for forcing non-null (the `!` operator).
322
+ * @typeparam T - the object type to select in
323
+ * @typeparam P - a Path in object type T
324
+ * @param source - the object to select in
325
+ * @param path - the path into the object
326
+ * @example
327
+ * ```ts
328
+ * const value = { a: { b: { c: [{ d: 5 }, { d: 6 }] } } }
329
+ * Deep.getAt(value, 'a.b');
330
+ * // => { c: 5 }
331
+ * Deep.getAt(value, 'a.b.c');
332
+ * // => [{ d: 5 }, { d: 5 }]
333
+ * Deep.getAt(value, 'a.b.c[1]');
334
+ * // => { d: 6 }
335
+ * Deep.getAt(value, 'a.b.c[1]?.d');
336
+ * // => 6
337
+ * ```
338
+ */
339
+ export function getAt<T, P extends Path.Get<T>>(
340
+ source: T,
341
+ path: P
342
+ ): Path.Result<T, P> {
343
+ if (path === '') {
344
+ // empty path always directly returns source value
345
+ return source as any;
346
+ }
347
+
348
+ const items = Path.stringSplit(path);
349
+
350
+ // start with `source` as result value
351
+ let result = source as any;
352
+
353
+ for (const item of items) {
354
+ if (undefined === item || item === '' || item === '[') {
355
+ // ignore irrelevant items
356
+ continue;
357
+ }
358
+
359
+ if (undefined === result || null === result) {
360
+ // optional chaining assumed and no value available, skip rest of path and return undefined
361
+ return undefined as any;
362
+ }
363
+
364
+ // set current result to subpath value
365
+ result = result[item];
366
+ }
367
+
368
+ return result;
369
+ }
370
+
371
+ /**
372
+ * Patches the value at the given path in the source to the given value.
373
+ * Because the path to update must exist in the `source` object, optional
374
+ * chaining and array indexing is not allowed.
375
+ * @param source - the object to update
376
+ * @param path - the path in the object to update
377
+ * @param patchItem - the patch for the value at the given path
378
+ * @example
379
+ * ```ts
380
+ * const value = { a: { b: { c: 5 } } };
381
+ * Deep.patchAt(value, 'a.b.c', v => v + 5);
382
+ * // => { a: { b: { c: 6 } } }
383
+ * ```
384
+ */
385
+ export function patchAt<T, P extends Path.Set<T>, C = Path.Result<T, P>>(
386
+ source: T,
387
+ path: P,
388
+ patchItem: Patch<Path.Result<T, P>, Path.Result<T, P> & C>
389
+ ): T {
390
+ if (path === '') {
391
+ return Deep.patch(source, patchItem as any);
392
+ }
393
+
394
+ const items = Path.stringSplit(path);
395
+
396
+ // creates a patch object based on the current path
397
+ function createPatchPart(index: number, target: any): any {
398
+ if (index === items.length) {
399
+ // processed all items, return the input `patchItem`
400
+ return patchItem;
401
+ }
402
+
403
+ const item = items[index];
404
+
405
+ if (undefined === item || item === '') {
406
+ // empty items can be ignored
407
+ return createPatchPart(index + 1, target);
408
+ }
409
+
410
+ if (item === '[') {
411
+ // next item is array index, set arrayMode to true
412
+ return createPatchPart(index + 1, target);
413
+ }
414
+
415
+ // create object with subPart as property key, and the restuls of processing next parts as value
416
+ const result = {
417
+ [item]: createPatchPart(index + 1, target[item]),
418
+ };
419
+
420
+ if (Array.isArray(target)) {
421
+ // target in source object is array/tuple, so the patch should be object
422
+ return result;
423
+ }
424
+
425
+ // target in source is not an array, so it patch should be an array
426
+ return [result];
427
+ }
428
+
429
+ return Deep.patch(source, createPatchPart(0, source));
430
+ }