-
-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (401 loc) · 11.9 KB
/
index.js
File metadata and controls
498 lines (401 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
const isObject = value => {
const type = typeof value;
return value !== null && (type === 'object' || type === 'function');
};
// Optimized empty check without creating an array.
const isEmptyObject = value => {
if (!isObject(value)) {
return false;
}
for (const key in value) {
if (Object.hasOwn(value, key)) {
return false;
}
}
return true;
};
const disallowedKeys = new Set([
'__proto__',
'prototype',
'constructor',
]);
// Maximum allowed array index to prevent DoS via memory exhaustion.
const MAX_ARRAY_INDEX = 1_000_000;
// Optimized digit check without Set overhead.
const isDigit = character => character >= '0' && character <= '9';
// Check if a segment should be coerced to a number.
function shouldCoerceToNumber(segment) {
// Only coerce valid non-negative integers without leading zeros.
if (segment === '0') {
return true;
}
if (/^[1-9]\d*$/.test(segment)) {
const parsedNumber = Number.parseInt(segment, 10);
// Check within safe integer range and under MAX_ARRAY_INDEX to prevent DoS.
return parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX;
}
return false;
}
// Helper to process a path segment (eliminates duplication).
function processSegment(segment, parts) {
if (disallowedKeys.has(segment)) {
return false; // Signal to return empty array.
}
if (segment && shouldCoerceToNumber(segment)) {
parts.push(Number.parseInt(segment, 10));
} else {
parts.push(segment);
}
return true;
}
export function parsePath(path) { // eslint-disable-line complexity
if (typeof path !== 'string') {
throw new TypeError(`Expected a string, got ${typeof path}`);
}
const parts = [];
let currentSegment = '';
let currentPart = 'start';
let isEscaping = false;
let position = 0;
for (const character of path) {
position++;
// Handle escaping.
if (isEscaping) {
currentSegment += character;
isEscaping = false;
continue;
}
// Handle escape character.
if (character === '\\') {
if (currentPart === 'index') {
throw new Error(`Invalid character '${character}' in an index at position ${position}`);
}
if (currentPart === 'indexEnd') {
throw new Error(`Invalid character '${character}' after an index at position ${position}`);
}
isEscaping = true;
currentPart = currentPart === 'start' ? 'property' : currentPart;
continue;
}
switch (character) {
case '.': {
if (currentPart === 'index') {
throw new Error(`Invalid character '${character}' in an index at position ${position}`);
}
if (currentPart === 'indexEnd') {
currentPart = 'property';
break;
}
if (!processSegment(currentSegment, parts)) {
return [];
}
currentSegment = '';
currentPart = 'property';
break;
}
case '[': {
if (currentPart === 'index') {
throw new Error(`Invalid character '${character}' in an index at position ${position}`);
}
if (currentPart === 'indexEnd') {
currentPart = 'index';
break;
}
if (currentPart === 'property' || currentPart === 'start') {
// Only push if we have content OR if we're in 'property' mode (not 'start')
if ((currentSegment || currentPart === 'property') && !processSegment(currentSegment, parts)) {
return [];
}
currentSegment = '';
}
currentPart = 'index';
break;
}
case ']': {
if (currentPart === 'index') {
if (currentSegment === '') {
// Empty brackets - backtrack and treat as literal
const lastSegment = parts.pop() || '';
currentSegment = lastSegment + '[]';
currentPart = 'property';
} else {
// Index must be digits only (enforced by default case)
const parsedNumber = Number.parseInt(currentSegment, 10);
const isValidInteger = !Number.isNaN(parsedNumber)
&& Number.isFinite(parsedNumber)
&& parsedNumber >= 0
&& parsedNumber <= Number.MAX_SAFE_INTEGER
&& parsedNumber <= MAX_ARRAY_INDEX
&& currentSegment === String(parsedNumber);
if (isValidInteger) {
parts.push(parsedNumber);
} else {
// Keep as string if not a valid integer representation or exceeds MAX_ARRAY_INDEX
parts.push(currentSegment);
}
currentSegment = '';
currentPart = 'indexEnd';
}
break;
}
if (currentPart === 'indexEnd') {
throw new Error(`Invalid character '${character}' after an index at position ${position}`);
}
// In property context, treat ] as literal character
currentSegment += character;
break;
}
default: {
if (currentPart === 'index' && !isDigit(character)) {
throw new Error(`Invalid character '${character}' in an index at position ${position}`);
}
if (currentPart === 'indexEnd') {
throw new Error(`Invalid character '${character}' after an index at position ${position}`);
}
if (currentPart === 'start') {
currentPart = 'property';
}
currentSegment += character;
}
}
}
// Handle unfinished escaping (trailing backslash)
if (isEscaping) {
currentSegment += '\\';
}
// Handle end of path
switch (currentPart) {
case 'property': {
if (!processSegment(currentSegment, parts)) {
return [];
}
break;
}
case 'index': {
throw new Error('Index was not closed');
}
case 'start': {
parts.push('');
break;
}
// No default
}
return parts;
}
function normalizePath(path) {
if (typeof path === 'string') {
return parsePath(path);
}
if (Array.isArray(path)) {
const normalized = [];
for (const [index, segment] of path.entries()) {
// Type validation.
if (typeof segment !== 'string' && typeof segment !== 'number') {
throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`);
}
// Validate numbers are finite (reject NaN, Infinity, -Infinity).
if (typeof segment === 'number' && !Number.isFinite(segment)) {
throw new TypeError(`Path segment at index ${index} must be a finite number, got ${segment}`);
}
// Check for disallowed keys.
if (disallowedKeys.has(segment)) {
return [];
}
// Normalize numeric strings to numbers for simplicity.
// This treats ['items', '0'] the same as ['items', 0].
if (typeof segment === 'string' && shouldCoerceToNumber(segment)) {
normalized.push(Number.parseInt(segment, 10));
} else {
normalized.push(segment);
}
}
return normalized;
}
return [];
}
export function getProperty(object, path, value) {
if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) {
return value === undefined ? object : value;
}
const pathArray = normalizePath(path);
if (pathArray.length === 0) {
return value;
}
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
object = object[key];
if (object === undefined || object === null) {
// Return default value if we hit undefined/null before the end of the path.
// This ensures get({foo: null}, 'foo.bar') returns the default value, not null.
if (index !== pathArray.length - 1) {
return value;
}
break;
}
}
return object === undefined ? value : object;
}
export function setProperty(object, path, value) {
if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) {
return object;
}
const root = object;
const pathArray = normalizePath(path);
if (pathArray.length === 0) {
return object;
}
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
if (index === pathArray.length - 1) {
object[key] = value;
} else if (!isObject(object[key])) {
const nextKey = pathArray[index + 1];
// Create arrays for numeric indices, objects for string keys
const shouldCreateArray = typeof nextKey === 'number';
object[key] = shouldCreateArray ? [] : {};
}
object = object[key];
}
return root;
}
export function deleteProperty(object, path) {
if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) {
return false;
}
const pathArray = normalizePath(path);
if (pathArray.length === 0) {
return false;
}
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
if (index === pathArray.length - 1) {
const existed = Object.hasOwn(object, key);
if (!existed) {
return false;
}
delete object[key];
return true;
}
object = object[key];
if (!isObject(object)) {
return false;
}
}
}
export function hasProperty(object, path) {
if (!isObject(object) || (typeof path !== 'string' && !Array.isArray(path))) {
return false;
}
const pathArray = normalizePath(path);
if (pathArray.length === 0) {
return false;
}
for (const key of pathArray) {
if (!isObject(object) || !(key in object)) {
return false;
}
object = object[key];
}
return true;
}
export function escapePath(path) {
if (typeof path !== 'string') {
throw new TypeError(`Expected a string, got ${typeof path}`);
}
// Escape special characters in one pass
return path.replaceAll(/[\\.[]/g, String.raw`\$&`);
}
function normalizeEntries(value) {
const entries = Object.entries(value);
if (Array.isArray(value)) {
return entries.map(([key, entryValue]) => {
// Use shouldCoerceToNumber for consistency with parsePath
const normalizedKey = shouldCoerceToNumber(key)
? Number.parseInt(key, 10)
: key;
return [normalizedKey, entryValue];
});
}
return entries;
}
export function stringifyPath(pathSegments, options = {}) {
if (!Array.isArray(pathSegments)) {
throw new TypeError(`Expected an array, got ${typeof pathSegments}`);
}
const {preferDotForIndices = false} = options;
const parts = [];
for (const [index, segment] of pathSegments.entries()) {
// Validate segment types at runtime
if (typeof segment !== 'string' && typeof segment !== 'number') {
throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`);
}
if (typeof segment === 'number') {
// Handle numeric indices
if (!Number.isInteger(segment) || segment < 0) {
// Non-integer or negative numbers are treated as string keys
const escaped = escapePath(String(segment));
parts.push(index === 0 ? escaped : `.${escaped}`);
} else if (preferDotForIndices && index > 0) {
parts.push(`.${segment}`);
} else {
parts.push(`[${segment}]`);
}
} else if (typeof segment === 'string') {
if (segment === '') {
// Empty string handling
if (index === 0) {
// Start with empty string, no prefix needed
} else {
parts.push('.');
}
} else if (shouldCoerceToNumber(segment)) {
// Numeric strings are normalized to numbers
const numericValue = Number.parseInt(segment, 10);
if (preferDotForIndices && index > 0) {
parts.push(`.${numericValue}`);
} else {
parts.push(`[${numericValue}]`);
}
} else {
// Regular strings use dot notation
const escaped = escapePath(segment);
parts.push(index === 0 ? escaped : `.${escaped}`);
}
}
}
return parts.join('');
}
function * deepKeysIterator(object, currentPath = [], ancestors = new Set()) {
if (!isObject(object) || isEmptyObject(object)) {
if (currentPath.length > 0) {
yield stringifyPath(currentPath);
}
return;
}
// Check if this object is already in the current path (circular reference)
if (ancestors.has(object)) {
return;
}
// Add to ancestors, recurse, then remove (backtrack)
ancestors.add(object);
// Reuse currentPath array by push/pop instead of creating new arrays
for (const [key, value] of normalizeEntries(object)) {
currentPath.push(key);
yield * deepKeysIterator(value, currentPath, ancestors);
currentPath.pop();
}
ancestors.delete(object);
}
export function deepKeys(object) {
return [...deepKeysIterator(object)];
}
export function unflatten(object) {
const result = {};
if (!isObject(object)) {
return result;
}
for (const [path, value] of Object.entries(object)) {
setProperty(result, path, value);
}
return result;
}