|
1
|
const UNSAFE_PATH_KEYS = new Set(["__proto__", "constructor", "prototype"]) |
|
2
|
|
|
3
|
/** |
|
4
|
* Convert a collection of dot string into a nested object |
|
5
|
* @example |
|
6
|
* input: [ |
|
7
|
* order, |
|
8
|
* order.items, |
|
9
|
* order.swaps, |
|
10
|
* order.swaps.additional_items, |
|
11
|
* order.discounts, |
|
12
|
* order.discounts.rule, |
|
13
|
* order.claims, |
|
14
|
* order.claims.additional_items, |
|
15
|
* additional_items, |
|
16
|
* additional_items.variant, |
|
17
|
* return_order, |
|
18
|
* return_order.items, |
|
19
|
* return_order.shipping_method, |
|
20
|
* return_order.shipping_method.tax_lines |
|
21
|
* ] |
|
22
|
* output: { |
|
23
|
* "order": { |
|
24
|
* "items": true, |
|
25
|
* "swaps": { |
|
26
|
* "additional_items": true |
|
27
|
* }, |
|
28
|
* "discounts": { |
|
29
|
* "rule": true |
|
30
|
* }, |
|
31
|
* "claims": { |
|
32
|
* "additional_items": true |
|
33
|
* } |
|
34
|
* }, |
|
35
|
* "additional_items": { |
|
36
|
* "variant": true |
|
37
|
* }, |
|
38
|
* "return_order": { |
|
39
|
* "items": true, |
|
40
|
* "shipping_method": { |
|
41
|
* "tax_lines": true |
|
42
|
* } |
|
43
|
* } |
|
44
|
* } |
|
45
|
* @param collection |
|
46
|
*/ |
|
47
|
export function objectFromStringPath( |
|
48
|
collection: string[] |
|
49
|
): Record<string, any> { |
|
50
|
collection = collection.sort() |
|
51
|
const output: Record<string, any> = {} |
|
52
|
|
|
53
|
for (const relation of collection) { |
|
54
|
if (!relation) { |
|
55
|
continue |
|
56
|
} |
|
57
|
|
|
58
|
const nestedRelations = relation.split(".") |
|
59
|
|
|
60
|
// Guard against prototype pollution through unsafe path segments |
|
61
|
if (nestedRelations.some((segment) => UNSAFE_PATH_KEYS.has(segment))) { |
|
62
|
continue |
|
63
|
} |
|
64
|
|
|
65
|
if (nestedRelations.length > 1) { |
|
66
|
let parent = output |
|
67
|
|
|
68
|
while (nestedRelations.length > 1) { |
|
69
|
const nestedRelation = nestedRelations.shift() as string |
|
70
|
parent = parent[nestedRelation] = |
|
71
|
parent[nestedRelation] !== true && |
|
72
|
typeof parent[nestedRelation] === "object" |
|
73
|
? parent[nestedRelation] |
|
74
|
: {} |
|
75
|
} |
|
76
|
|
|
77
|
parent[nestedRelations[0]] = true |
|
78
|
|
|
79
|
continue |
|
80
|
} |
|
81
|
|
|
82
|
output[relation] = output[relation] ?? true |
|
83
|
} |
|
84
|
|
|
85
|
return output |
|
86
|
} |