Skip to content

Commit 138d41d

Browse files
committed
fix(protect): preserve root array index paths in toJsonPath
- Handle $[0] paths without inserting erroneous dot ($[0] not $.[0]) - Update module documentation to reflect array index support - Add tests for root array index preservation
1 parent d84f482 commit 138d41d

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

packages/protect/__tests__/jsonb-helpers.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ describe('toJsonPath', () => {
5454
expect(toJsonPath('[0].name')).toBe('$[0].name')
5555
})
5656

57+
it('preserves already-prefixed root array index', () => {
58+
expect(toJsonPath('$[0]')).toBe('$[0]')
59+
})
60+
61+
it('preserves already-prefixed root array index with property', () => {
62+
expect(toJsonPath('$[0].name')).toBe('$[0].name')
63+
})
64+
5765
it('handles large array index', () => {
5866
expect(toJsonPath('items[999].value')).toBe('$.items[999].value')
5967
})

packages/protect/src/helpers/jsonb.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
/**
22
* JSONB path utilities for converting between path formats.
33
*
4-
* These utilities support simple dot-notation paths only.
5-
* Path segments are not validated - callers are responsible for ensuring
6-
* segments contain valid property names (no brackets, quotes, or special chars).
4+
* These utilities support dot-notation and basic JSONPath-style array indices (e.g., "[0]").
5+
* Only limited validation is performed (forbidden prototype keys); callers should still
6+
* ensure segments are valid property names.
77
*/
88

99
/**
@@ -17,6 +17,7 @@
1717
*/
1818
export function toJsonPath(path: string): string {
1919
if (!path || path === '$') return '$'
20+
if (path.startsWith('$[')) return path
2021
if (path.startsWith('$.')) return path
2122
if (path.startsWith('$')) return `$.${path.slice(1)}`
2223
if (path.startsWith('.')) return `$${path}`

0 commit comments

Comments
 (0)